holosphere 2.0.0-alpha11 → 2.0.0-alpha13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{2019-D2OG2idw.js → 2019-CLMqIAfQ.js} +1722 -1668
- package/dist/{2019-D2OG2idw.js.map → 2019-CLMqIAfQ.js.map} +1 -1
- package/dist/2019-Cp3uYhyY.cjs +8 -0
- package/dist/{2019-EION3wKo.cjs.map → 2019-Cp3uYhyY.cjs.map} +1 -1
- package/dist/browser-D6cNVl0v.cjs +2 -0
- package/dist/{browser-Cq59Ij19.cjs.map → browser-D6cNVl0v.cjs.map} +1 -1
- package/dist/{browser-BSniCNqO.js → browser-nUQt1cnB.js} +2 -2
- package/dist/{browser-BSniCNqO.js.map → browser-nUQt1cnB.js.map} +1 -1
- package/dist/cjs/holosphere.cjs +1 -1
- package/dist/esm/holosphere.js +67 -50
- package/dist/{index-D-jZhliX.js → index-BN_uoxQK.js} +20324 -735
- package/dist/index-BN_uoxQK.js.map +1 -0
- package/dist/{index-Bl6rM1NW.js → index-CoAjtqsD.js} +2 -2
- package/dist/{index-Bl6rM1NW.js.map → index-CoAjtqsD.js.map} +1 -1
- package/dist/{index-Bwg3OzRM.cjs → index-Cp3tI53z.cjs} +3 -3
- package/dist/{index-Bwg3OzRM.cjs.map → index-Cp3tI53z.cjs.map} +1 -1
- package/dist/index-DJjGSwXG.cjs +13 -0
- package/dist/index-DJjGSwXG.cjs.map +1 -0
- package/dist/index-V8EHMYEY.cjs +29 -0
- package/dist/index-V8EHMYEY.cjs.map +1 -0
- package/dist/index-Z5TstN1e.js +11663 -0
- package/dist/index-Z5TstN1e.js.map +1 -0
- package/dist/indexeddb-storage-CZK5A7XH.cjs +2 -0
- package/dist/indexeddb-storage-CZK5A7XH.cjs.map +1 -0
- package/dist/{indexeddb-storage-5eiUNsHC.js → indexeddb-storage-bpA01pAU.js} +39 -2
- package/dist/indexeddb-storage-bpA01pAU.js.map +1 -0
- package/dist/{memory-storage-DMt36uZO.cjs → memory-storage-B1k8Jszd.cjs} +2 -2
- package/dist/{memory-storage-DMt36uZO.cjs.map → memory-storage-B1k8Jszd.cjs.map} +1 -1
- package/dist/{memory-storage-CI-gfmuG.js → memory-storage-BqhmytP_.js} +2 -2
- package/dist/{memory-storage-CI-gfmuG.js.map → memory-storage-BqhmytP_.js.map} +1 -1
- package/docs/FEDERATION.md +474 -0
- package/package.json +3 -1
- package/src/crypto/nostr-utils.js +7 -0
- package/src/crypto/secp256k1.js +104 -38
- package/src/federation/capabilities.js +162 -0
- package/src/federation/card-storage.js +376 -0
- package/src/federation/handshake.js +561 -9
- package/src/federation/hologram.js +194 -57
- package/src/federation/holon-registry.js +187 -0
- package/src/federation/index.js +68 -0
- package/src/federation/registry.js +164 -6
- package/src/federation/request-card.js +373 -0
- package/src/hierarchical/upcast.js +19 -3
- package/src/index.js +209 -75
- package/src/lib/federation-methods.js +527 -5
- package/src/storage/indexeddb-storage.js +41 -0
- package/src/storage/nostr-async.js +14 -5
- package/src/storage/nostr-client.js +471 -155
- package/src/storage/nostr-wrapper.js +6 -3
- package/dist/2019-EION3wKo.cjs +0 -8
- package/dist/_commonjsHelpers-C37NGDzP.cjs +0 -2
- package/dist/_commonjsHelpers-C37NGDzP.cjs.map +0 -1
- package/dist/_commonjsHelpers-CUmg6egw.js +0 -7
- package/dist/_commonjsHelpers-CUmg6egw.js.map +0 -1
- package/dist/browser-Cq59Ij19.cjs +0 -2
- package/dist/index-D-jZhliX.js.map +0 -1
- package/dist/index-Dc6Z8Aob.cjs +0 -18
- package/dist/index-Dc6Z8Aob.cjs.map +0 -1
- package/dist/indexeddb-storage-5eiUNsHC.js.map +0 -1
- package/dist/indexeddb-storage-FNFUVvTJ.cjs +0 -2
- package/dist/indexeddb-storage-FNFUVvTJ.cjs.map +0 -1
- package/dist/secp256k1-CEwJNcfV.js +0 -1890
- package/dist/secp256k1-CEwJNcfV.js.map +0 -1
- package/dist/secp256k1-CiEONUnj.cjs +0 -12
- package/dist/secp256k1-CiEONUnj.cjs.map +0 -1
package/dist/index-Dc6Z8Aob.cjs
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
"use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;const e=require("nostr-tools"),t=require("h3-js"),n=require("ajv");function s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const r=s(t);class a{constructor(e,t={}){this.storage=e,this.queuePrefix="_outbox/",this.maxRetries=t.maxRetries||5,this.baseDelay=t.baseDelay||1e3,this.maxDelay=t.maxDelay||6e4,this.failedTTL=t.failedTTL||864e5}async enqueue(e,t){const n={id:e.id,event:e,relays:t,status:"pending",retries:0,createdAt:Date.now(),nextRetryAt:Date.now(),failedRelays:[]},s=`${this.queuePrefix}${e.id}`;return await this.storage.put(s,n),n}async markSent(e,t){const n=`${this.queuePrefix}${e}`,s=await this.storage.get(n);s&&(t.length>0?await this.storage.delete(n):await this._scheduleRetry(n,s))}async _scheduleRetry(e,t){if(t.retries++,t.retries>=this.maxRetries)t.status="failed",t.failedAt=Date.now();else{t.status="pending";const e=Math.min(this.baseDelay*Math.pow(2,t.retries)+1e3*Math.random(),this.maxDelay);t.nextRetryAt=Date.now()+e}await this.storage.put(e,t)}async getPendingEvents(){const e=await this.storage.getAll(this.queuePrefix),t=Date.now();return e.filter(e=>e&&"pending"===e.status&&e.nextRetryAt<=t).sort((e,t)=>e.createdAt-t.createdAt)}async getFailedEvents(){return(await this.storage.getAll(this.queuePrefix)).filter(e=>e&&"failed"===e.status)}async getStats(){const e=await this.storage.getAll(this.queuePrefix),t={total:e.length,pending:0,failed:0,oldestPending:null,oldestFailed:null};for(const n of e)n&&("pending"===n.status?(t.pending++,(!t.oldestPending||n.createdAt<t.oldestPending)&&(t.oldestPending=n.createdAt)):"failed"===n.status&&(t.failed++,(!t.oldestFailed||n.failedAt<t.oldestFailed)&&(t.oldestFailed=n.failedAt)));return t}async purgeOldFailed(e=this.failedTTL){const t=await this.storage.getAll(this.queuePrefix),n=Date.now();let s=0;for(const r of t)r&&"failed"===r.status&&n-r.failedAt>e&&(await this.storage.delete(`${this.queuePrefix}${r.id}`),s++);return s}async clear(){const e=await this.storage.getAll(this.queuePrefix);let t=0;for(const n of e)n&&n.id&&(await this.storage.delete(`${this.queuePrefix}${n.id}`),t++);return t}async retryFailed(e){const t=`${this.queuePrefix}${e}`,n=await this.storage.get(t);return n&&"failed"===n.status?(n.status="pending",n.retries=0,n.nextRetryAt=Date.now(),delete n.failedAt,await this.storage.put(t,n),n):null}}class i{constructor(e,t={}){this.client=e,this.interval=t.interval||1e4,this.running=!1,this.timer=null,this._processing=!1,t.autoStart&&this.start()}start(){this.running||(this.running=!0,this._scheduleNextRun())}stop(){this.running=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}isRunning(){return this.running}async syncNow(){return this._processOutbox()}_scheduleNextRun(){this.running&&(this.timer=setTimeout(()=>{this._runLoop()},this.interval))}async _runLoop(){if(this.running){try{await this._processOutbox()}catch(e){console.warn("[sync] Outbox processing failed:",e.message)}this._scheduleNextRun()}}async _processOutbox(){if(this._processing)return{skipped:!0,reason:"already processing"};this._processing=!0;const e={processed:0,succeeded:0,failed:0,purged:0};try{if(!this.client.outboxQueue)return{...e,skipped:!0,reason:"no outbox queue"};const n=await this.client.outboxQueue.getPendingEvents();e.processed=n.length;for(const s of n)try{(await this.client._attemptDelivery(s.event,s.relays)).successful.length>0?e.succeeded++:e.failed++}catch(t){console.warn(`[sync] Retry failed for ${s.id}:`,t.message),e.failed++}e.purged=await this.client.outboxQueue.purgeOldFailed()}finally{this._processing=!1}return e}async getStats(){const e={running:this.running,interval:this.interval,queue:null};return this.client.outboxQueue&&(e.queue=await this.client.outboxQueue.getStats()),e}}let o=null,f=new Set;const c=new Map,l=new Map,u=new Map,d=3e4,p=new Map,h=new Map;class y{constructor(e=500){this.maxSize=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}set(e,t){for(this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t);this.cache.size>this.maxSize;){const e=this.cache.keys().next().value;this.cache.delete(e)}}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}keys(){return this.cache.keys()}values(){return this.cache.values()}entries(){return this.cache.entries()}forEach(e){this.cache.forEach(e)}}let m=null;class g{constructor(t={}){if(t.relays&&!Array.isArray(t.relays))throw new Error("Relays must be an array");this.relays=t.relays||[],this.privateKey=t.privateKey||this._generatePrivateKey(),this.publicKey=e.getPublicKey(this.privateKey),this.config=t,this._subscriptions=new Map,this._eventCache=new y(t.cacheSize||500),this._cacheIndex=new Map,this.persistentStorage=null,this._persistQueue=new Map,this._persistTimer=null,this._persistBatchMs=t.persistBatchMs||100,this._initReady=this._initialize()}async _initialize(){await(void 0!==globalThis.WebSocket?Promise.resolve():(m||(m=(async()=>{try{const{default:e}=await import("ws");globalThis.WebSocket=e}catch(e){}})()),m)),this.relays.length>0?(this.pool=function(t={}){return o||(o=new e.SimplePool({enableReconnect:!1!==t.enableReconnect,enablePing:!1!==t.enablePing})),o}(this.config),this.relays.forEach(e=>f.add(e))):this.pool={publish:(e,t)=>[Promise.resolve()],querySync:(e,t,n)=>Promise.resolve([]),subscribeMany:(e,t,n)=>({close:()=>{}}),close:e=>{}},await this._initPersistentStorage(),this.relays.length>0&&this._initLongLivedSubscription()}_initLongLivedSubscription(){const e=this.publicKey;if(h.has(e))return;const t={subscription:null,initialized:!1,initPromise:null,initResolve:null};t.initPromise=new Promise(e=>{t.initResolve=e}),h.set(e,t);const n={kinds:[3e4],authors:[this.publicKey]},s=this.pool.subscribeMany(this.relays,[n],{onevent:e=>{e.pubkey===this.publicKey&&this._cacheEvent(e)},oneose:()=>{t.initialized||(t.initialized=!0,t.initResolve())}});t.subscription=s,setTimeout(()=>{t.initialized||(t.initialized=!0,t.initResolve())},5e3)}async _waitForSubscriptionInit(){const e=h.get(this.publicKey);e&&e.initPromise&&await e.initPromise}async _initPersistentStorage(){if(!1!==this.config.persistence&&(this.config.radisk||this.config.appName))try{const e=this.config.appName||"holosphere_default";this.persistentStorage=await async function(e){const t="undefined"!=typeof window&&void 0!==window.indexedDB;if("undefined"!=typeof process&&process.versions,t){const{IndexedDBStorage:t}=await Promise.resolve().then(()=>require("./indexeddb-storage-FNFUVvTJ.cjs")),n=new t;return await n.init(e),n}{const{MemoryStorage:t}=await Promise.resolve().then(()=>require("./memory-storage-DMt36uZO.cjs")),n=new t;return await n.init(e),n}}(e,{dataDir:this.config.dataDir}),await this._loadFromPersistentStorage(),this.outboxQueue=new a(this.persistentStorage,{maxRetries:this.config.maxRetries||5,baseDelay:this.config.retryBaseDelay||1e3,maxDelay:this.config.retryMaxDelay||6e4,failedTTL:this.config.failedTTL||864e5}),!1!==this.config.backgroundSync&&(this.syncService=new i(this,{interval:this.config.syncInterval||1e4,autoStart:!0}))}catch(e){console.warn("Failed to initialize persistent storage:",e)}}async _loadFromPersistentStorage(){if(this.persistentStorage)try{const e=await this.persistentStorage.getAll("");for(const t of e)t&&t.id&&!t.status&&this._cacheEventSync(t)}catch(e){console.warn("Failed to load from persistent storage:",e)}}async persistentGet(e){if(await this._initReady,!this.persistentStorage)return null;try{return await this.persistentStorage.get(e)||null}catch(t){return console.warn("[nostr] Persistent storage read failed:",t),null}}getCachedByPath(e,t=3e4){const n=`d:${t}:${e}`,s=this._eventCache.get(n);return s&&s.events&&s.events[0]?s.events[0]:null}async persistentGetAll(e){if(await this._initReady,!this.persistentStorage)return[];try{return(await this.persistentStorage.getAll(e)).filter(e=>e&&e.id&&!e.status)}catch(t){return console.warn("[nostr] Persistent storage read failed:",t),[]}}_generatePrivateKey(){const e=new Uint8Array(32);if("undefined"!=typeof window&&window.crypto)window.crypto.getRandomValues(e);else try{const t=globalThis.crypto||global.crypto;if(t&&t.getRandomValues)t.getRandomValues(e);else for(let n=0;n<32;n++)e[n]=Math.floor(256*Math.random())}catch(t){for(let n=0;n<32;n++)e[n]=Math.floor(256*Math.random())}return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}async publish(e,t={}){await this._initReady;const n=t.waitForRelays||!1;if(e.kind>=3e4&&e.kind<4e4&&!1!==t.debounce&&!n){const n=e.tags?.find(e=>"d"===e[0]);if(n&&n[1])return this._debouncedPublish(e,n[1],t)}return this._doPublish(e,t)}_debouncedPublish(t,n,s){return new Promise((r,a)=>{const i=p.get(n);i&&(clearTimeout(i.timer),i.resolve({event:null,results:[],debounced:!0,supersededBy:t}));const o=setTimeout(async()=>{p.delete(n);try{const e=await this._doPublish(t,s);r(e)}catch(e){a(e)}},500);p.set(n,{event:t,timer:o,resolve:r,reject:a});const f=e.finalizeEvent(t,this.privateKey);this._cacheEvent(f)})}async _doPublish(t,n={}){const s=n.waitForRelays||!1,r=t.id&&t.sig?t:e.finalizeEvent(t,this.privateKey);if(await this._cacheEvent(r),this.outboxQueue&&await this.outboxQueue.enqueue(r,this.relays),s){return{event:r,results:(await this._attemptDelivery(r,this.relays)).results,queued:!!this.outboxQueue}}return this._attemptDelivery(r,this.relays).catch(()=>{}),{event:r,results:[],queued:!!this.outboxQueue}}async _attemptDelivery(e,t){const n=await Promise.allSettled(this.pool.publish(t,e)),s=[],r=[],a=[];if(n.forEach((e,n)=>{a.push({relay:t[n],status:e.status,value:e.value,reason:e.reason}),"fulfilled"===e.status?s.push(t[n]):r.push(t[n])}),this.outboxQueue&&await this.outboxQueue.markSent(e.id,s),r.length>0&&0===s.length){const t=n.filter(e=>"rejected"===e.status).map(e=>e.reason?.message||e.reason||"unknown").join(", ");t.includes("timed out")||console.warn(`[nostr] All relays failed for ${e.id.slice(0,8)}: ${t}`)}return{successful:s,failed:r,results:a}}async query(e,t={}){await this._initReady;const n=void 0!==t.timeout?t.timeout:3e4,s=!1!==t.localFirst,r=!0===t.forceRelay;if(0===this.relays.length){return this._getMatchingCachedEvents(e)}const a=h.get(this.publicKey),i=e.authors&&1===e.authors.length&&e.authors[0]===this.publicKey;if(!r&&i&&a&&a.initialized){return this._getMatchingCachedEvents(e)}if(i&&a&&!a.initialized&&(await Promise.race([a.initPromise,new Promise(e=>setTimeout(e,Math.min(n,5e3)))]),a.initialized)){return this._getMatchingCachedEvents(e)}if(e["#d"]&&1===e["#d"].length&&e.kinds&&1===e.kinds.length){const t=`d:${e.kinds[0]}:${e["#d"][0]}`,n=this._eventCache.get(t);if(n&&Date.now()-n.timestamp<5e3)return n.events}const o=JSON.stringify(e),f=this._eventCache.get(o);return f&&Date.now()-f.timestamp<5e3?f.events:s&&f?(this._refreshCacheInBackground(e,o,n),f.events):this._queryRelaysAndCache(e,o,n)}async _queryRelaysAndCache(e,t,n){const s=c.get(t);if(s&&Date.now()-s.timestamp<5e3)return s.promise;const r=(async()=>{try{let s=await this.pool.querySync(this.relays,e,{timeout:n});return e.authors&&e.authors.length>0&&(s=s.filter(t=>e.authors.includes(t.pubkey))),this._eventCache.set(t,{events:s,timestamp:Date.now()}),this._indexCacheEntry(t,e),s}finally{c.delete(t)}})();return c.set(t,{promise:r,timestamp:Date.now()}),r}_limitCacheSize(){}_indexCacheEntry(e,t){if(t.kinds)for(const n of t.kinds)this._cacheIndex.has(n)||this._cacheIndex.set(n,new Set),this._cacheIndex.get(n).add(e)}_unindexCacheEntry(e){if(e.startsWith("{"))try{const t=JSON.parse(e);if(t.kinds)for(const n of t.kinds){const t=this._cacheIndex.get(n);t&&(t.delete(e),0===t.size&&this._cacheIndex.delete(n))}}catch{}}_refreshCacheInBackground(e,t,n){this._queryRelaysAndCache(e,t,n).catch(e=>{console.debug("[nostr] Background cache refresh failed:",e.message)})}refreshPathInBackground(e,t=3e4,n={}){this._doBackgroundPathRefresh(e,t,n).catch(e=>{console.debug("[nostr] Background path refresh failed:",e.message)})}async _doBackgroundPathRefresh(e,t,n){if(0===this.relays.length)return;const s=u.get(e);if(s&&Date.now()-s<d)return;if(u.set(e,Date.now()),u.size>1e3){const e=Date.now()-d;for(const[t,n]of u)n<e&&u.delete(t)}const r={kinds:[t],authors:n.authors||[this.publicKey],"#d":[e],limit:1},a=JSON.stringify(r),i=n.timeout||3e4,o=(await this._queryRelaysAndCache(r,a,i)).filter(e=>(n.authors||[this.publicKey]).includes(e.pubkey));o.length>0&&await this._cacheEvent(o[0])}refreshPrefixInBackground(e,t=3e4,n={}){this._doBackgroundPrefixRefresh(e,t,n).catch(e=>{console.debug("[nostr] Background prefix refresh failed:",e.message)})}async _doBackgroundPrefixRefresh(e,t,n){if(0===this.relays.length)return;const s=`prefix:${e}`,r=u.get(s);if(r&&Date.now()-r<d)return;u.set(s,Date.now());const a={kinds:[t],authors:n.authors||[this.publicKey],limit:n.limit||1e3},i=JSON.stringify(a),o=n.timeout||3e4;let f=await this._queryRelaysAndCache(a,i,o);f=f.filter(e=>(n.authors||[this.publicKey]).includes(e.pubkey)),f=f.filter(t=>{const n=t.tags.find(e=>"d"===e[0]);return n&&n[1]&&n[1].startsWith(e)});for(const c of f)await this._cacheEvent(c)}async queryHybrid(e,t={}){await this._initReady;const n=void 0!==t.timeout?t.timeout:3e4,s=this._getMatchingCachedEvents(e);if(0===this.relays.length)return s;let r=[];try{r=await this.pool.querySync(this.relays,e,{timeout:n}),e.authors&&e.authors.length>0&&(r=r.filter(t=>e.authors.includes(t.pubkey)))}catch(f){console.warn("Relay query failed, using local cache only:",f.message)}const a=new Map;for(const c of s){const e=this._getEventKey(c);a.set(e,c)}for(const c of r){const e=this._getEventKey(c),t=a.get(e);c.kind>=3e4&&c.kind<4e4&&t?c.created_at>=t.created_at&&a.set(e,c):a.set(e,c)}const i=Array.from(a.values()),o=JSON.stringify(e);return this._eventCache.set(o,{events:i,timestamp:Date.now()}),i}_getEventKey(e){if(e.kind>=3e4&&e.kind<4e4){const t=e.tags.find(e=>"d"===e[0]);if(t&&t[1])return`${e.kind}:${t[1]}`}return e.id}async subscribe(e,t,n={}){await this._initReady;const s=`sub-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,r=JSON.stringify(e);if(0===this.relays.length){const r=this._getMatchingCachedEvents(e),a={filter:e,onEvent:t,active:!0};return this._subscriptions.set(s,a),setTimeout(()=>{a.active&&(r.forEach(e=>t(e)),n.onEOSE&&n.onEOSE())},10),{id:s,unsubscribe:()=>{a.active=!1,this._subscriptions.delete(s),a.onEvent=()=>{}}}}const a=l.get(r);if(a)return a.callbacks.add(t),a.refCount++,{id:s,unsubscribe:()=>{a.callbacks.delete(t),a.refCount--,0===a.refCount&&(a.subscription&&a.subscription.close&&a.subscription.close(),l.delete(r)),this._subscriptions.delete(s)}};const i=new Set([t]),o={callbacks:i,refCount:1,subscription:null};l.set(r,o);const f=this.pool.subscribeMany(this.relays,[e],{onevent:t=>{if(e.authors&&e.authors.length>0&&!e.authors.includes(t.pubkey))return;this._cacheEvent(t);const n=l.get(r);if(n)for(const e of n.callbacks)try{e(t)}catch(s){console.warn("[nostr] Subscription callback error:",s.message)}},oneose:()=>{n.onEOSE&&n.onEOSE()}});return o.subscription=f,this._subscriptions.set(s,f),{id:s,unsubscribe:()=>{i.delete(t),o.refCount--,0===o.refCount&&(f.close&&f.close(),l.delete(r)),this._subscriptions.delete(s)}}}_cacheEventSync(e){const t=e.id;if(this._eventCache.set(t,{events:[e],timestamp:Date.now()}),e.kind>=3e4&&e.kind<4e4){const t=e.tags.find(e=>"d"===e[0]);if(t&&t[1]){const n=`d:${e.kind}:${t[1]}`,s=this._eventCache.get(n);(!s||!s.events[0]||e.created_at>s.events[0].created_at||e.created_at===s.events[0].created_at&&e.id!==s.events[0].id)&&(this._eventCache.set(n,{events:[e],timestamp:Date.now()}),s&&s.events[0]&&this._eventCache.delete(s.events[0].id),this._invalidateQueryCachesForEvent(e))}}}_invalidateQueryCachesForEvent(e){const t=this._cacheIndex.get(e.kind);if(!t||0===t.size)return;const n=[];for(const s of t){if(this._eventCache.get(s))try{const t=JSON.parse(s);this._eventMatchesFilter(e,t)&&n.push(s)}catch{t.delete(s)}else t.delete(s)}for(const s of n)this._eventCache.delete(s),this._unindexCacheEntry(s)}async _cacheEvent(e){if(this._cacheEventSync(e),this.persistentStorage){let t=e.id;if(e.kind>=3e4&&e.kind<4e4){const n=e.tags.find(e=>"d"===e[0]);n&&n[1]&&(t=n[1])}this._persistQueue.set(t,e),this._persistTimer||(this._persistTimer=setTimeout(()=>this._flushPersistQueue(),this._persistBatchMs))}if(0===this.relays.length)for(const t of this._subscriptions.values())t.active&&this._eventMatchesFilter(e,t.filter)&&setTimeout(()=>{t.active&&t.onEvent(e)},10)}async _flushPersistQueue(){if(this._persistTimer=null,!this.persistentStorage||0===this._persistQueue.size)return;const e=Array.from(this._persistQueue.entries());this._persistQueue.clear();const t=e.map(async([e,t])=>{try{await this.persistentStorage.put(e,t)}catch(n){console.warn(`Failed to persist event ${e}:`,n.message)}});await Promise.all(t)}_getMatchingCachedEvents(e){const t=[],n=new Map;for(const s of this._eventCache.values())for(const r of s.events||[])if(this._eventMatchesFilter(r,e)){if(r.kind>=3e4&&r.kind<4e4){const e=r.tags.find(e=>"d"===e[0]);if(e&&e[1]){const s=`${r.kind}:${e[1]}`,a=n.get(s);if(!a||r.created_at>a.created_at||r.created_at===a.created_at&&JSON.parse(r.content)?._deleted&&!JSON.parse(a.content)?._deleted){if(a){const e=t.indexOf(a);e>-1&&t.splice(e,1)}n.set(s,r),t.push(r)}continue}}t.push(r)}return t}_eventMatchesFilter(e,t){if(t.kinds&&!t.kinds.includes(e.kind))return!1;if(t.ids&&!t.ids.includes(e.id))return!1;if(t.authors&&!t.authors.includes(e.pubkey))return!1;if(t["#d"]){const n=e.tags.find(e=>"d"===e[0]);if(!n||!t["#d"].includes(n[1]))return!1}return!(t.since&&e.created_at<t.since)&&!(t.until&&e.created_at>t.until)}async getEvent(e){const t=await this.query({ids:[e]});return t.length>0?t[0]:null}clearCache(e=null){if(e)for(const t of this._eventCache.keys())t.includes(e)&&this._eventCache.delete(t);else this._eventCache.clear()}async close(e={}){!1!==e.flush&&this._persistTimer&&(clearTimeout(this._persistTimer),await this._flushPersistQueue()),this.syncService&&this.syncService.stop();const t=h.get(this.publicKey);t&&t.subscription&&(t.subscription.close&&t.subscription.close(),h.delete(this.publicKey));for(const n of this._subscriptions.values())n.close?n.close():void 0!==n.active&&(n.active=!1);this._subscriptions.clear(),this.pool.close(this.relays),this._eventCache.clear(),this._cacheIndex.clear()}getRelayStatus(){return this.relays.map(e=>({url:e,connected:!0}))}}const b={nostr:"./backends/nostr-backend.js",gundb:"./backends/gundb-backend.js",activitypub:"./backends/activitypub-backend.js"},w=new Map;class v{static getAvailableBackends(){return Object.keys(b)}static isAvailable(e){return e in b}static async loadBackend(e){if(w.has(e))return w.get(e);const t=b[e];if(!t)throw new Error(`Unknown backend type: '${e}'. Available backends: ${Object.keys(b).join(", ")}`);try{const s=await import(t),r=s.default||s[`${n=e,n.charAt(0).toUpperCase()+n.slice(1)}Backend`];if(!r)throw new Error(`Backend module '${e}' does not export a valid backend class`);return w.set(e,r),r}catch(s){if("ERR_MODULE_NOT_FOUND"===s.code)throw new Error(`Backend '${e}' requires additional dependencies. Please install them: ${function(e){return{nostr:"npm install nostr-tools",gundb:"npm install gun",activitypub:"npm install express"}[e]||"Check the documentation for required dependencies"}(e)}`);throw s}var n}static async create(e,t){const n=new(await this.loadBackend(e))(t);return await n.init(),n}static register(e,t){"string"==typeof t?b[e]=t:(w.set(e,t),b[e]=null)}}function _(e,t=1e3){return new Promise((n,s)=>{let r=!1;const a=setTimeout(()=>{r||(r=!0,n(null))},t);e.once(e=>{r||(r=!0,clearTimeout(a),n(e||null))})})}function T(e,t,n=1e3){return new Promise((s,r)=>{let a=!1;const i=setTimeout(()=>{a||(a=!0,s({ok:!0,timeout:!0}))},n);e.put(t,e=>{a||(a=!0,clearTimeout(i),e.err?r(new Error(e.err)):s(e))})})}async function x(e,t=5e3){return new Promise(n=>{const s={};let r=!1,a=0,i=0;e.once(t=>{if(r)return;if(!t)return r=!0,void n({});const o=Object.keys(t).filter(e=>"_"!==e);if(0===o.length)return r=!0,void n({});for(const e of o){const n=t[e];n&&("object"==typeof n&&n["#"]||(s[e]=n))}a=o.length,e.map().once((e,t)=>{r||!e||t.startsWith("_")||(s[t]=e,i++,r||a>0&&i>=a&&(r=!0,n(s)))})}),setTimeout(()=>{r||(r=!0,n(s))},t)})}function A(e,t,n,s=null){const r=k(t),a=k(n);if(s){return`${e}/${r}/${a}/${k(s)}`}return`${e}/${r}/${a}`}function S(e,t,n=null){const s=k(t);if(n){return`${e}/${s}/${k(n)}`}return`${e}/${s}`}function k(e){return encodeURIComponent(e).replace(/%2F/g,"/")}function E(e,t){const n=t.split("/").filter(e=>e.length>0);let s=e;for(const r of n)s=s.get(r);return s}function N(e){return JSON.stringify(e)}function I(e){if(!e)return null;try{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}if(e._json&&"string"==typeof e._json)try{return JSON.parse(e._json)}catch(t){return console.warn("Failed to parse _json field:",t),null}if(e._&&e._["#"])return e;if(e._&&e._[">"]){const n=Object.entries(e).find(([e,t])=>"_"!==e&&"string"==typeof t);if(n)try{return JSON.parse(n[1])}catch(t){return n[1]}}if("object"==typeof e&&null!==e){const t={...e};return delete t._,0===Object.keys(t).length?null:t}return e}catch(n){return console.warn("Error deserializing Gun data:",n),e}}async function C(e,t,n){try{const s=N(n),r=t.split("/").filter(e=>e.length>0);console.log("[gun-wrapper] write:",{path:t,parts:r,dataId:n?.id});const a=E(e,t);console.log("[gun-wrapper] write ref soul:",a?._.get);const i=await T(a,s,5e3);return console.log("[gun-wrapper] write ack:",{ok:i.ok,timeout:i.timeout}),i.timeout&&console.warn("[gun-wrapper] write timed out (data may not be persisted):",t),console.log("[gun-wrapper] write complete:",t),{ok:!0,timeout:i.timeout||!1}}catch(s){throw console.error("[gun-wrapper] write error:",s),s}}async function O(e,t){const n=t.split("/").filter(e=>e.length>0);console.log("[gun-wrapper] read:",{path:t,parts:n});const s=E(e,t);console.log("[gun-wrapper] read ref soul:",s?._.get);const r=await _(s,2e3);if(console.log("[gun-wrapper] read rawData:",r?"string"==typeof r?r.substring(0,100):"object":"null"),!r)return null;const a=I(r);return!a||a._deleted?null:a}async function R(e,t,n=5e3){const s=t.split("/").filter(e=>e.length>0);return console.log("[gun-wrapper] readAll:",{path:t,parts:s}),new Promise(s=>{const r=new Map;let a=!1,i=0,o=0;const f=E(e,t);console.log("[gun-wrapper] readAll ref soul:",f?._.get);const c=e=>I(e);f.once(e=>{if(a)return;if(console.log("[gun-wrapper] readAll parentData:",e),console.log("[gun-wrapper] readAll parentData keys:",e?Object.keys(e).filter(e=>"_"!==e):"null"),console.log("[gun-wrapper] readAll parentData type:",typeof e),!e)return a=!0,console.log("[gun-wrapper] readAll: no parent data, returning empty"),void s([]);const t=Object.keys(e).filter(e=>"_"!==e);if(console.log("[gun-wrapper] readAll keys:",t),0===t.length)return a=!0,console.log("[gun-wrapper] readAll: no keys, returning empty"),void s([]);for(const n of t){const t=e[n];if(!t)continue;if("object"==typeof t&&t["#"])continue;const s=c(t);s&&s.id&&!s._deleted&&r.set(s.id,s)}if(i=t.length,0===i)return a=!0,void s(Array.from(r.values()));f.map().once((e,t)=>{if(a||!e||"_"===t)return;const n=c(e);n&&n.id&&!n._deleted&&(r.has(n.id)||r.set(n.id,n)),o++,a||i>0&&o>=i&&(a=!0,console.log("[gun-wrapper] readAll resolved with",r.size,"items"),s(Array.from(r.values())))})}),setTimeout(()=>{a||(a=!0,s(Array.from(r.values())))},n)})}async function $(e,t,n){const s=await _(E(e,t));if(!s)return!1;const r=I(s);if(!r||!r.id||r._deleted)return!1;const a={...r,...n};try{const n=N(a);return await T(E(e,t),n,2e3),await new Promise(e=>setTimeout(e,200)),!0}catch(i){throw i}}async function P(e,t){try{const n=await _(E(e,t));if(!n)return!0;const s=I(n),r={id:s?.id,_deleted:!0,_deletedAt:Date.now()};return await T(E(e,t),N(r),2e3),await new Promise(e=>setTimeout(e,200)),!0}catch(n){throw n}}async function M(e,t){const n=await R(e,t);let s=0;for(const r of n)if(r&&r.id){const n=`${t}/${r.id}`;await P(e,n),s++}return{success:!0,count:s}}function D(e,t,n,s={}){const r=t.split("/");if(void 0!==s.prefix?s.prefix:r.length<=3){const s=E(e,t);return s.map().on((e,t)=>{if(e&&!t.startsWith("_")){const s=I(e);s&&!s._deleted&&n(s,t)}}),{unsubscribe:()=>{try{s.off()}catch(e){}}}}{const s=E(e,t).on((e,t)=>{if(e){const s=I(e);s&&!s._deleted&&n(s,t)}});return{unsubscribe:()=>{try{s.off()}catch(e){}}}}}async function F(e,t,n,s){if(!s||!s.id)throw new Error("writeGlobal: data must have an id field");return C(e,S(t,n,s.id),s)}async function H(e,t,n,s){return O(e,S(t,n,s))}async function B(e,t,n,s=2e3){return R(e,S(t,n))}async function j(e,t,n,s){return P(e,S(t,n,s))}async function U(e,t,n){return M(e,S(t,n))}function L(e){return I(e)}const q=Object.freeze(Object.defineProperty({__proto__:null,buildGlobalPath:S,buildPath:A,deleteAll:M,deleteAllGlobal:U,deleteData:P,deleteGlobal:j,parse:L,read:O,readAll:R,readAllGlobal:B,readGlobal:H,serialize:function(e){return N(e)},subscribe:D,update:$,write:C,writeGlobal:F},Symbol.toStringTag,{value:"Module"}));async function J(e,t){if(!t)throw new Error("getFederation: Missing space ID");return e.readGlobal("federation",t)}async function G(e,t,n){const s=`${t}_${n}_fedmsgs`;return e.readGlobal("federation_messages",s)}class z{constructor(e){if(new.target===z)throw new Error("StorageBackend is abstract and cannot be instantiated directly");this.config=e,this.publicKey=null}async init(){throw new Error("init() must be implemented by subclass")}buildPath(e,t,n,s=null){throw new Error("buildPath() must be implemented by subclass")}async write(e,t,n={}){throw new Error("write() must be implemented by subclass")}async read(e,t={}){throw new Error("read() must be implemented by subclass")}async readAll(e,t={}){throw new Error("readAll() must be implemented by subclass")}async update(e,t){throw new Error("update() must be implemented by subclass")}async delete(e){throw new Error("delete() must be implemented by subclass")}async deleteAll(e){throw new Error("deleteAll() must be implemented by subclass")}async subscribe(e,t,n={}){throw new Error("subscribe() must be implemented by subclass")}async exportData(e=""){throw new Error("exportData() must be implemented by subclass")}async importData(e,t={}){throw new Error("importData() must be implemented by subclass")}close(){throw new Error("close() must be implemented by subclass")}getStatus(){throw new Error("getStatus() must be implemented by subclass")}}class W{constructor(e){this.appname=e}createReference(e,t,n){if(!n||!n.id)throw new Error("createReference: data must have an id field");return{id:n.id,soul:`${this.appname}/${e}/${t}/${n.id}`}}isReference(e){return!!e&&(!!(e.soul&&e.id&&Object.keys(e).filter(e=>!e.startsWith("_")).length<=2)||(!(!e._federation||!e._federation.isReference)||!(!e._||!e._["#"])))}parseSoulPath(e){if(!e||"string"!=typeof e)return null;const t=e.split("/");return t.length<4?null:{appname:t[0],holon:t[1],lens:t[2],key:t.slice(3).join("/")}}async resolveReference(e,t,n={}){const{followReferences:s=!0}=n;if(!t)return null;let r=null,a=null;if(t.soul)r=t.soul;else if(t._federation&&t._federation.isReference){const e=t._federation;e.origin&&e.lens&&t.id&&(r=`${this.appname}/${e.origin}/${e.lens}/${t.id}`,a=e)}else t._&&t._["#"]&&(r=t._["#"]);if(!r)return null;const i=this.parseSoulPath(r);if(!i)return null;try{const t=`${i.appname}/${i.holon}/${i.lens}/${i.key}`,n=await O(e,t);if(!n)return null;if(s&&this.isReference(n)){const t=await this.resolveReference(e,n,{followReferences:!0});if(t)return{...t,_federation:{resolved:!0,soul:r,origin:i.holon,lens:i.lens,timestamp:Date.now()}}}return{...n,_federation:{resolved:!0,soul:r,origin:a?.origin||i.holon,lens:a?.lens||i.lens,timestamp:Date.now()}}}catch(o){return console.warn("Error resolving reference:",o),null}}getSoul(e,t,n){return`${this.appname}/${e}/${t}/${n}`}}class K{constructor(e,t){this.gun=e,this.appname=t,this.user=null,this.authenticated=!1,this.currentHolonId=null}userName(e){return`${this.appname}:${e}`}async authenticate(e,t){if(!e||!t)throw new Error("authenticate: holonId and password are required");const n=this.userName(e);return this.user=this.gun.user(),new Promise((s,r)=>{this.user.auth(n,t,t=>{t.err?(this.authenticated=!1,this.currentHolonId=null,r(new Error(t.err))):(this.authenticated=!0,this.currentHolonId=e,s(this.user))})})}async createUser(e,t){if(!e||!t)throw new Error("createUser: holonId and password are required");const n=this.userName(e);return this.user=this.gun.user(),new Promise((s,r)=>{this.user.create(n,t,a=>{a.err?r(new Error(a.err)):this.user.auth(n,t,t=>{t.err?r(new Error(t.err)):(this.authenticated=!0,this.currentHolonId=e,s(this.user))})})})}logout(){this.user&&this.user.leave(),this.authenticated=!1,this.currentHolonId=null,this.user=null}isAuthenticated(){return this.authenticated&&null!==this.user}getPrivatePath(e,t=null){if(!this.isAuthenticated())throw new Error("Not authenticated");const n=this.user.get("private").get(e);return t?n.get(t):n}async writePrivate(e,t,n){if(!this.isAuthenticated())throw new Error("Not authenticated");if(!n||!t)throw new Error("writePrivate: key and data are required");try{const s=JSON.stringify(n);return await T(this.getPrivatePath(e,t),s,2e3),!0}catch(s){throw s}}async readPrivate(e,t){if(!this.isAuthenticated())throw new Error("Not authenticated");try{const s=await _(this.getPrivatePath(e,t),2e3);if(!s)return null;if("string"==typeof s)try{return JSON.parse(s)}catch(n){return s}if(s._json&&"string"==typeof s._json)try{return JSON.parse(s._json)}catch(n){return null}if("object"==typeof s){const e={...s};return delete e._,e}return null}catch(s){throw s}}async readAllPrivate(e,t=5e3){if(!this.isAuthenticated())throw new Error("Not authenticated");return new Promise(n=>{const s=[],r=new Set,a=this.getPrivatePath(e);let i=!1,o=0,f=0;const c=e=>{if(!e)return null;let t=null;if("string"==typeof e)try{t=JSON.parse(e)}catch(n){t=e}else if(e._json&&"string"==typeof e._json)try{t=JSON.parse(e._json)}catch(n){}else"object"==typeof e&&(t={...e},delete t._);return t};a.once(e=>{if(i)return;if(!e)return i=!0,void n([]);const t=Object.keys(e).filter(e=>"_"!==e);if(0===t.length)return i=!0,void n([]);for(const n of t){const t=e[n];if(!t)continue;if("object"==typeof t&&t["#"])continue;const a=c(t);!a||a._deleted||r.has(n)||(r.add(n),s.push(a))}o=t.length,a.map().once((e,t)=>{if(!i&&e&&!t.startsWith("_")){if(!r.has(t)){r.add(t);const n=c(e);n&&!n._deleted&&s.push(n)}f++,i||o>0&&f>=o&&(i=!0,n(s))}})}),setTimeout(()=>{i||(i=!0,n(s))},t)})}async deletePrivate(e,t){if(!this.isAuthenticated())throw new Error("Not authenticated");try{const n=await this.readPrivate(e,t),s={id:n?.id||t,_deleted:!0,_deletedAt:Date.now()};return await T(this.getPrivatePath(e,t),JSON.stringify(s)),!0}catch(n){throw n}}}const V={type:"object",required:["type"],properties:{$schema:{type:"string"},$id:{type:"string"},type:{type:"string"},properties:{type:"object"},required:{type:"array",items:{type:"string"}},additionalProperties:{type:"boolean"}}};class Z{constructor(e={}){this.strict=e.strict||!1,this.cacheMaxAge=e.cacheMaxAge||36e5,this.schemaCache=new Map,this.validator=null,this.Ajv=null}async init(){if(this.validator)return!0;try{const e=await Promise.resolve().then(()=>require("./2019-EION3wKo.cjs")).then(e=>e._2019);return this.Ajv=e.default||e,this.validator=new this.Ajv({allErrors:!0,strict:!1,validateSchema:!0}),!0}catch(e){return console.warn("AJV not available, schema validation disabled:",e.message),!1}}async setSchema(e,t,n,s){if(!s||"object"!=typeof s)throw new Error("setSchema: schema must be an object");if(this.strict&&this.validator){if(!this.validateSchema(V,s))throw new Error("setSchema: Invalid schema definition")}const r={id:n,lens:n,schema:s,timestamp:Date.now()};return await F(e,t,"schemas",r),this.schemaCache.set(n,{schema:s,timestamp:Date.now()}),!0}async getSchema(e,t,n,s={}){const{useCache:r=!0}=s;if(r){const e=this.schemaCache.get(n);if(e&&Date.now()-e.timestamp<this.cacheMaxAge)return e.schema}const a=await H(e,t,"schemas",n);return a&&a.schema?(this.schemaCache.set(n,{schema:a.schema,timestamp:Date.now()}),a.schema):null}async getAllSchemas(e,t){return B(e,t,"schemas")}async deleteSchema(e,t,n){return this.schemaCache.delete(n),j(e,t,"schemas",n)}validate(e,t){if(!this.validator)return{valid:!0,errors:[]};try{const n=this.validator.compile(e),s=n(t);return{valid:s,errors:s?[]:this.formatErrors(n.errors)}}catch(n){return{valid:!1,errors:[{message:n.message,path:""}]}}}async validateData(e,t,n,s){const r=await this.getSchema(e,t,n);return r?this.validate(r,s):{valid:!0,errors:[]}}validateSchema(e,t){if(!this.validator)return!0;try{return this.validator.compile(e)(t)}catch(n){return!1}}formatErrors(e){return e?e.map(e=>({message:e.message||"Validation error",path:e.instancePath||e.dataPath||"",keyword:e.keyword,params:e.params})):[]}clearCache(e=null){e?this.schemaCache.delete(e):this.schemaCache.clear()}isStrict(){return this.strict}setStrict(e){this.strict=e}}class Y extends z{constructor(e){super(e),this.gun=null,this.keyPair=null,this.appName=e.appName||"holosphere",this.references=null,this.auth=null,this.schemaValidator=null,this.subscriptions=new Map,this.subscriptionCounter=0,this.writeCache=new Map,this.writeCacheTTL=3e5,this.pendingWrites=new Map,this.maxWriteRetries=5,this.writeRetryInterval=1e4}async init(){let e;try{console.log("[gundb-backend] Importing Gun...");const t=await Promise.resolve().then(()=>require("./browser-Cq59Ij19.cjs")).then(e=>e.browser);e=t.default||t,console.log("[gundb-backend] Gun imported:",typeof e)}catch(s){throw new Error('GunDB backend requires the "gun" package. Install it with: npm install gun')}const t=this.config.dataDir||"radata",n={peers:this.config.peers||[],radisk:!1!==this.config.radisk,localStorage:!1!==this.config.localStorage,file:t};console.log("[gundb-backend] Gun config:",JSON.stringify(n)),this.gun=e(n),console.log("[gundb-backend] Gun instance created:",!!this.gun);try{const e=`_test_${Date.now()}`;this.gun.get(e).put({test:!0},e=>{console.log("[gundb-backend] Gun test write ack:",e)}),console.log("[gundb-backend] Gun test write initiated")}catch(r){console.error("[gundb-backend] Gun test write failed:",r.message)}await new Promise(e=>setTimeout(e,500));try{const t=e.SEA;t?this.config.privateKey?(this.keyPair={priv:this.config.privateKey,pub:this.config.publicKey},this.publicKey=this.config.publicKey||this.config.privateKey.substring(0,32)):(this.keyPair=await t.pair(),this.publicKey=this.keyPair.pub):this.publicKey=this.appName}catch(s){this.publicKey=this.appName}this.references=new W(this.appName),this.auth=new K(this.gun,this.appName),this.schemaValidator=new Z({strict:this.config.strict||!1,cacheMaxAge:this.config.schemaCacheMaxAge||36e5}),await this.schemaValidator.init()}_addToWriteCache(e,t){if(!t||!t.id)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;this.writeCache.has(n)||this.writeCache.set(n,new Map);this.writeCache.get(n).set(t.id.toString(),{data:t,timestamp:Date.now()})}_removeFromWriteCache(e,t){const n=e.substring(0,e.lastIndexOf("/")),s=this.writeCache.get(n);s&&s.delete(t.toString())}_getWriteCacheEntries(e){const t=this.writeCache.get(e);if(!t)return[];const n=Date.now(),s=[];for(const[r,a]of t)n-a.timestamp<this.writeCacheTTL?s.push(a.data):t.delete(r);return s}_mergeWithWriteCache(e,t){const n=this._getWriteCacheEntries(e);if(0===n.length)return t;const s=new Map;for(const r of t)r&&r.id&&s.set(r.id.toString(),r);for(const r of n)r&&r.id&&!r._deleted?s.set(r.id.toString(),r):r&&r.id&&r._deleted&&s.delete(r.id.toString());return Array.from(s.values())}clearWriteCache(e=null){e?this.writeCache.delete(e):this.writeCache.clear()}buildPath(e,t,n,s=null){return A(e,t,n,s)}buildGlobalPath(e,t=null){return S(this.appName,e,t)}async write(e,t,n={}){if(this.schemaValidator&&this.schemaValidator.isStrict()){const n=e.split("/");if(n.length>=3){const e=n[2];if(!this.isReference(t)){const n=await this.schemaValidator.validateData(this.gun,this.appName,e,t);if(!n.valid)throw new Error(`Schema validation failed: ${JSON.stringify(n.errors)}`)}}}this._addToWriteCache(e,t);return await this._writeWithRetry(e,t)}async _writeWithRetry(e,t,n=0){const s=await C(this.gun,e,t);return s.timeout&&n<this.maxWriteRetries?(this.pendingWrites.set(e,{data:t,retries:n+1,lastAttempt:Date.now()}),this._scheduleRetry(e)):s.timeout||this.pendingWrites.delete(e),s}_scheduleRetry(e){setTimeout(async()=>{const t=this.pendingWrites.get(e);if(t){if(t.retries>=this.maxWriteRetries)return console.warn(`[gundb-backend] Max retries reached for: ${e}`),void this.pendingWrites.delete(e);console.log(`[gundb-backend] Retrying write (attempt ${t.retries+1}): ${e}`),await this._writeWithRetry(e,t.data,t.retries)}},this.writeRetryInterval)}async read(e,t={}){const n=await O(this.gun,e);return n&&t.resolveReferences&&this.isReference(n)?this.resolveReference(n):n}async readAll(e,t={}){const n=await R(this.gun,e),s=this._mergeWithWriteCache(e,n);if(t.resolveReferences){const e=[];for(const t of s)if(this.isReference(t)){const n=await this.resolveReference(t);n&&e.push(n)}else e.push(t);return e}return s}async update(e,t){return $(this.gun,e,t)}async delete(e){const t=await P(this.gun,e),n=e.split("/"),s=n[n.length-1];if(s){const t=e.substring(0,e.lastIndexOf("/"));this.writeCache.has(t)||this.writeCache.set(t,new Map),this.writeCache.get(t).set(s.toString(),{data:{id:s,_deleted:!0},timestamp:Date.now()})}return t}async deleteAll(e){const t=await this.readAll(e);let n=0;for(const s of t)if(s&&s.id){const t=`${e}/${s.id}`;await P(this.gun,t),n++}return{success:!0,count:n}}async writeGlobal(e,t){const n=this.buildGlobalPath(e,t.id);this._addToWriteCache(n,t);return await this._writeGlobalWithRetry(e,t)}async _writeGlobalWithRetry(e,t,n=0){const s=this.buildGlobalPath(e,t.id),r=await F(this.gun,this.appName,e,t);return r.timeout&&n<this.maxWriteRetries?(this.pendingWrites.set(s,{data:{tableName:e,data:t},isGlobal:!0,retries:n+1,lastAttempt:Date.now()}),this._scheduleGlobalRetry(s,e)):r.timeout||this.pendingWrites.delete(s),r}_scheduleGlobalRetry(e,t){setTimeout(async()=>{const n=this.pendingWrites.get(e);if(n&&n.isGlobal){if(n.retries>=this.maxWriteRetries)return console.warn(`[gundb-backend] Max retries reached for global: ${e}`),void this.pendingWrites.delete(e);console.log(`[gundb-backend] Retrying global write (attempt ${n.retries+1}): ${e}`),await this._writeGlobalWithRetry(t,n.data.data,n.retries)}},this.writeRetryInterval)}async readGlobal(e,t){return H(this.gun,this.appName,e,t)}async readAllGlobal(e,t=5e3){const n=await B(this.gun,this.appName,e,t),s=this.buildGlobalPath(e);return this._mergeWithWriteCache(s,n)}async deleteGlobal(e,t){const n=await j(this.gun,this.appName,e,t),s=this.buildGlobalPath(e);return this.writeCache.has(s)||this.writeCache.set(s,new Map),this.writeCache.get(s).set(t.toString(),{data:{id:t,_deleted:!0},timestamp:Date.now()}),n}async deleteAllGlobal(e){return U(this.gun,this.appName,e)}createReference(e,t,n){return this.references.createReference(e,t,n)}isReference(e){return this.references.isReference(e)}async resolveReference(e,t={}){return this.references.resolveReference(this.gun,e,t)}parseSoulPath(e){return this.references.parseSoulPath(e)}getSoul(e,t,n){return this.references.getSoul(e,t,n)}async authenticate(e,t){return this.auth.authenticate(e,t)}async createUser(e,t){return this.auth.createUser(e,t)}logout(){this.auth.logout()}isAuthenticated(){return this.auth.isAuthenticated()}async writePrivate(e,t,n){return this.auth.writePrivate(e,t,n)}async readPrivate(e,t){return this.auth.readPrivate(e,t)}async readAllPrivate(e,t=2e3){return this.auth.readAllPrivate(e,t)}async deletePrivate(e,t){return this.auth.deletePrivate(e,t)}async setSchema(e,t){return this.schemaValidator.setSchema(this.gun,this.appName,e,t)}async getSchema(e,t={}){return this.schemaValidator.getSchema(this.gun,this.appName,e,t)}async getAllSchemas(){return this.schemaValidator.getAllSchemas(this.gun,this.appName)}async deleteSchema(e){return this.schemaValidator.deleteSchema(this.gun,this.appName,e)}validate(e,t){return this.schemaValidator.validate(e,t)}async validateData(e,t){return this.schemaValidator.validateData(this.gun,this.appName,e,t)}clearSchemaCache(e=null){this.schemaValidator.clearCache(e)}async subscribe(e,t,n={}){const s=++this.subscriptionCounter,r=e.split("/").length<=3,a={id:s,path:e,active:!0,gunRef:null};if(r){const r=this.gun.get(e);a.gunRef=r,r.map().on(async(e,r)=>{if(!this.subscriptions.get(s)?.active)return;if(!e||r.startsWith("_")||e._deleted)return;let a=L(e);a&&(n.resolveReferences&&this.isReference(a)&&(a=await this.resolveReference(a)),a&&t(a,r))})}else{const r=this.gun.get(e);a.gunRef=r,r.on(async(e,r)=>{if(!this.subscriptions.get(s)?.active)return;if(!e)return;let a=L(e);a&&!a._deleted&&(n.resolveReferences&&this.isReference(a)&&(a=await this.resolveReference(a)),a&&t(a,r))})}return this.subscriptions.set(s,a),{id:s,unsubscribe:()=>{const e=this.subscriptions.get(s);if(e){if(e.active=!1,e.gunRef)try{e.gunRef.off()}catch(t){}this.subscriptions.delete(s)}}}}async exportData(e=""){const t=[],n=e||this.appName;try{const e=await x(this.gun.get(n),2e3);for(const[s,r]of Object.entries(e))s.startsWith("_")||!r||"object"!=typeof r||r._deleted||await this._collectRecords(n,s,r,t)}catch(s){console.warn("Export data error:",s)}return t}async _collectRecords(e,t,n,s){const r=`${e}/${t}`;if(n.id)s.push({path:r,data:this._cleanGunData(n),timestamp:n._meta?.timestamp||Date.now()});else try{const e=await x(this.gun.get(r),500);for(const[t,n]of Object.entries(e))!t.startsWith("_")&&n&&await this._collectRecords(r,t,n,s)}catch(a){}}_cleanGunData(e){const t={...e};return delete t._,t}async importData(e,t={}){const n={success:0,failed:0,errors:[]};for(const r of e)try{await C(this.gun,r.path,r.data),n.success++}catch(s){n.failed++,n.errors.push({path:r.path,error:s.message})}return n}close(){for(const[n,s]of this.subscriptions)if(s.active&&(s.active=!1,s.gunRef))try{s.gunRef.off()}catch(e){}if(this.subscriptions.clear(),this.schemaValidator&&this.schemaValidator.clearCache(),this.writeCache.clear(),this.auth&&this.auth.logout(),this.gun)try{const e=this.gun.back("opt.mesh");e&&(e.way&&Object.values(e.way).forEach(e=>{e?.wire?.close&&e.wire.close()}),e.opt?.peers&&(e.opt.peers={}));const t=this.gun.back("opt.web");t?.close&&t.close(),this.gun.off()}catch(t){console.warn("Error during Gun cleanup:",t)}}getStatus(){return{type:"gundb",publicKey:this.publicKey,peers:this.config.peers||[],connected:!!this.gun,authenticated:this.isAuthenticated(),subscriptionCount:this.subscriptions.size,schemaValidationEnabled:this.schemaValidator?.isStrict()||!1}}}const X="2.0.0-alpha11";function Q(e){if("undefined"!=typeof process&&process.env)return process.env[e]}function ee(){const e=Q("HOLOSPHERE_RELAYS");return e?e.split(",").map(e=>e.trim()).filter(e=>e):["wss://relay.holons.io"]}let te=class{constructor(e={}){if("string"==typeof e&&(e={appName:e}),e&&"object"!=typeof e)throw new TypeError("Config must be an object");if(void 0!==e.appName&&"string"!=typeof e.appName)throw new TypeError("config.appName must be a string");if(void 0!==e.relays&&!Array.isArray(e.relays))throw new TypeError("config.relays must be an array");if(void 0!==e.logLevel&&!["ERROR","WARN","INFO","DEBUG"].includes(e.logLevel))throw new TypeError("config.logLevel must be one of: ERROR, WARN, INFO, DEBUG");if(void 0!==e.backend&&!v.isAvailable(e.backend))throw new TypeError(`config.backend must be one of: ${v.getAvailableBackends().join(", ")}`);this.config={appName:e.appName||Q("HOLOSPHERE_APP_NAME")||"holosphere",backend:e.backend||"nostr",relays:e.relays||ee(),privateKey:e.privateKey||Q("HOLOSPHERE_PRIVATE_KEY"),logLevel:e.logLevel||Q("HOLOSPHERE_LOG_LEVEL")||"INFO",hybridMode:!1!==e.hybridMode},this._rawConfig=e,this.logLevels={ERROR:0,WARN:1,INFO:2,DEBUG:3},this.currentLogLevel=this.logLevels[this.config.logLevel]||1,this._backend=null,"nostr"===this.config.backend?this._initNostrSync(e):"gundb"===this.config.backend?this._backendReady=this._initGunDBAsync(e):this._backendReady=this._initBackendAsync(e),this._metrics={writes:0,reads:0,subscriptions:0}}_initNostrSync(e){try{this.client=function(e){return new g(e)}({relays:this.config.relays,privateKey:this.config.privateKey,enableReconnect:!1!==e.enableReconnect,enablePing:!1!==e.enablePing,appName:this.config.appName,radisk:!1!==e.radisk,persistence:!1!==e.persistence,dataDir:e.dataDir}),this._logStartup({version:X,appName:this.config.appName,backend:"nostr",relays:this.config.relays,publicKey:this.client.publicKey,logLevel:this.config.logLevel,persistence:!1!==e.persistence,reconnect:!1!==e.enableReconnect,dataDir:e.dataDir}),this._backendReady=Promise.resolve()}catch(t){throw this._log("ERROR","Nostr client initialization failed",{error:t.message}),new Error(`Nostr client initialization failed: ${t.message}`)}}async _initGunDBAsync(e){try{const t=e.gundb||{};this._backend=new Y({appName:this.config.appName,peers:t.peers||[],radisk:!1!==t.radisk,localStorage:!1!==t.localStorage,dataDir:e.dataDir,privateKey:this.config.privateKey,strict:t.strict||!1,schemaCacheMaxAge:t.schemaCacheMaxAge||36e5}),await this._backend.init(),this.publicKey=this._backend.publicKey,this._gun=this._backend.gun,this.client={publicKey:this.publicKey,gun:this._gun,write:(e,t)=>this._backend.write(e,t),read:(e,t)=>this._backend.read(e,t),readAll:(e,t)=>this._backend.readAll(e,t),update:(e,t)=>this._backend.update(e,t),delete:e=>this._backend.delete(e),subscribe:(e,t,n)=>this._backend.subscribe(e,t,n),buildPath:A},this._gunWrapper=q,this._logStartup({version:X,appName:this.config.appName,backend:"gundb",peers:t.peers||[],publicKey:this.publicKey,logLevel:this.config.logLevel,persistence:!1!==t.radisk,dataDir:e.dataDir})}catch(t){throw this._log("ERROR","GunDB client initialization failed",{error:t.message}),new Error(`GunDB client initialization failed: ${t.message}`)}}async _initBackendAsync(e){const t=this.config.backend,n=e[t]||{};try{const s={appName:this.config.appName,privateKey:this.config.privateKey,persistence:!1!==e.persistence,dataDir:e.dataDir,...n};this._backend=await v.create(t,s),this.client=this._backend.client||this._backend,this._logStartup({version:X,appName:this.config.appName,backend:t,publicKey:this._backend.publicKey,logLevel:this.config.logLevel,persistence:!1!==e.persistence,...this._backend.getStatus()})}catch(s){throw this._log("ERROR",`${t} backend initialization failed`,{error:s.message}),new Error(`${t} backend initialization failed: ${s.message}`)}}async ready(){this._backendReady&&await this._backendReady}get backend(){return this._backend}_log(e,t,n={}){if(this.logLevels[e]<=this.currentLogLevel){const s={timestamp:Date.now(),level:e,message:t,app:this.config.appName,...n};console.log(JSON.stringify(s))}}_logStartup(e){this.currentLogLevel>=this.logLevels.INFO&&(console.log("\n"+"=".repeat(60)),console.log(" HoloSphere - Holonic Geospatial Infrastructure"),console.log("=".repeat(60)),console.log(` Version: ${e.version}`),console.log(` App Name: ${e.appName}`),console.log(` Backend: ${e.backend||"nostr"}`),console.log(" Public Key: "+(e.publicKey?e.publicKey.substring(0,16)+"...":"N/A")),console.log(` Log Level: ${e.logLevel}`),console.log(` Persistence: ${e.persistence?"Enabled":"Disabled"}${e.dataDir?` (${e.dataDir})`:""}`),"nostr"!==e.backend&&e.backend?"gundb"===e.backend?(console.log("\n Gun Peers:"),e.peers&&0!==e.peers.length?e.peers.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}):console.log(" (none - running in local mode)")):"activitypub"===e.backend&&(console.log(` Server URL: ${e.serverUrl||"N/A"}`),console.log(` Actor ID: ${e.actorId||"N/A"}`)):(console.log(" Auto-reconnect: "+(e.reconnect?"Enabled":"Disabled")),console.log("\n Connected Relays:"),e.relays&&0!==e.relays.length?e.relays.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}):console.log(" (none - running in local mode)")),console.log("=".repeat(60)+"\n"))}metrics(){return{...this._metrics}}_requireGunDB(){if("gundb"!==this.config.backend)throw new Error("This method requires the GunDB backend");if(!this._backend)throw new Error("Backend not initialized. Call ready() first.")}async putGlobal(e,t){return await this.ready(),this._requireGunDB(),this._backend.writeGlobal(e,t)}async getGlobal(e,t){return await this.ready(),this._requireGunDB(),this._backend.readGlobal(e,t)}async getAllGlobal(e){return await this.ready(),this._requireGunDB(),this._backend.readAllGlobal(e)}async deleteGlobal(e,t){return await this.ready(),this._requireGunDB(),this._backend.deleteGlobal(e,t)}createReference(e,t,n){return this._requireGunDB(),this._backend.createReference(e,t,n)}isReference(e){return this._requireGunDB(),this._backend.isReference(e)}async resolveReference(e,t={}){return await this.ready(),this._requireGunDB(),this._backend.resolveReference(e,t)}async authenticate(e,t){return await this.ready(),this._requireGunDB(),this._backend.authenticate(e,t)}async createUser(e,t){return await this.ready(),this._requireGunDB(),this._backend.createUser(e,t)}logout(){this._requireGunDB(),this._backend.logout()}isAuthenticated(){return this._requireGunDB(),this._backend.isAuthenticated()}async writePrivate(e,t,n){return await this.ready(),this._requireGunDB(),this._backend.writePrivate(e,t,n)}async readPrivate(e,t){return await this.ready(),this._requireGunDB(),this._backend.readPrivate(e,t)}async setSchema(e,t){return await this.ready(),this._requireGunDB(),this._backend.setSchema(e,t)}async getSchema(e){return await this.ready(),this._requireGunDB(),this._backend.getSchema(e)}async validateData(e,t){return await this.ready(),this._requireGunDB(),this._backend.validateData(e,t)}async federate(e,t,n=!0){return await this.ready(),this._requireGunDB(),async function(e,t,n,s=!0){if(!t||!n)throw new Error("federate: Missing required space IDs");if(t===n)throw new Error("Cannot federate a space with itself");try{let r=await e.readGlobal("federation",t);r||(r={id:t,name:t,federation:[],notify:[],timestamp:Date.now()}),r.federation||(r.federation=[]),r.notify||(r.notify=[]),r.federation.includes(n)||r.federation.push(n),r.timestamp=Date.now(),await e.writeGlobal("federation",r);let a=await e.readGlobal("federation",n);a||(a={id:n,name:n,federation:[],notify:[],timestamp:Date.now()}),a.notify||(a.notify=[]),a.notify.includes(t)||a.notify.push(t),a.timestamp=Date.now(),await e.writeGlobal("federation",a);const i={id:`${t}_${n}`,space1:t,space2:n,created:Date.now(),status:"active",bidirectional:s};return await e.writeGlobal("federationMeta",i),!0}catch(r){throw console.error(`Federation creation failed: ${r.message}`),r}}(this._backend,e,t,n)}async unfederate(e,t){return await this.ready(),this._requireGunDB(),async function(e,t,n){if(!t||!n)throw new Error("unfederate: Missing required space IDs");try{let s=await e.readGlobal("federation",t);s&&s.federation&&(s.federation=s.federation.filter(e=>e!==n),s.timestamp=Date.now(),await e.writeGlobal("federation",s));let r=await e.readGlobal("federation",n);r&&r.notify&&(r.notify=r.notify.filter(e=>e!==t),r.timestamp=Date.now(),await e.writeGlobal("federation",r));const a=`${t}_${n}`,i=`${n}_${t}`;let o=await e.readGlobal("federationMeta",a);return o||(o=await e.readGlobal("federationMeta",i)),o&&(o.status="inactive",o.endedAt=Date.now(),await e.writeGlobal("federationMeta",o)),!0}catch(s){throw console.error(`Federation removal failed: ${s.message}`),s}}(this._backend,e,t)}async getFederation(e){return await this.ready(),this._requireGunDB(),J(this._backend,e)}async resetFederation(e,t={}){return await this.ready(),this._requireGunDB(),async function(e,t,n={}){if(!t)throw new Error("resetFederation: Missing required space ID");const{notifyPartners:s=!0,spaceName:r=null}=n,a={success:!1,federatedCount:0,notifyCount:0,partnersNotified:0,errors:[]};try{const n=await J(e,t);if(!n)return{...a,success:!0,message:"No federation configuration found for this space"};a.federatedCount=n.federation?.length||0,a.notifyCount=n.notify?.length||0;const o={id:t,name:r||t,federation:[],notify:[],timestamp:Date.now()};if(await e.writeGlobal("federation",o),s&&n.federation&&n.federation.length>0)for(const s of n.federation)try{const n=await J(e,s);n&&(n.federation&&(n.federation=n.federation.filter(e=>e!==t.toString())),n.notify&&(n.notify=n.notify.filter(e=>e!==t.toString())),n.timestamp=Date.now(),await e.writeGlobal("federation",n),a.partnersNotified++)}catch(i){a.errors.push({partner:s,error:i.message})}if(n.federation&&n.federation.length>0)for(const s of n.federation)try{const n=`${t}_${s}`,r=`${s}_${t}`;let a=await e.readGlobal("federationMeta",n);a||(a=await e.readGlobal("federationMeta",r)),a&&(a.status="inactive",a.endedAt=Date.now(),await e.writeGlobal("federationMeta",a))}catch(i){}return a.success=!0,a}catch(i){return console.error(`Federation reset failed: ${i.message}`),{...a,success:!1,error:i.message}}}(this._backend,e,t)}async propagate(e,t,n,s={}){return await this.ready(),this._requireGunDB(),async function(e,t,n,s,r={}){if(!(e&&t&&n&&s))throw new Error("propagate: Missing required parameters");const{useReferences:a=!0,targetSpaces:i=null}=r,o={success:0,errors:0,errorDetails:[],propagated:!1,referencesUsed:a};try{const r=await J(e,t);if(!r||!r.federation||0===r.federation.length)return{...o,message:`No federation found for ${t}`};if(!r.notify||0===r.notify.length)return{...o,message:`No notification targets found for ${t}`};let c=r.notify;if(i&&Array.isArray(i)&&i.length>0&&(c=c.filter(e=>i.includes(e))),0===c.length)return{...o,message:"No valid target spaces found after filtering"};const l=e.isReference(s);for(const i of c)try{if(a&&!l){const r=e.createReference(t,n,s);r._federation={origin:t,lens:n,timestamp:Date.now()};const a=e.buildPath(e.appName,i,n,r.id);await e.write(a,r),o.success++}else if(l){const r={...s,_federation:s._federation||{origin:t,lens:n,timestamp:Date.now()}},a=e.buildPath(e.appName,i,n,s.id);await e.write(a,r),o.success++}else{const r={...s,_federation:{origin:t,lens:n,timestamp:Date.now()}},a=e.buildPath(e.appName,i,n,s.id);await e.write(a,r),o.success++}}catch(f){o.errors++,o.errorDetails.push({space:i,error:f.message})}return o.propagated=o.success>0,o}catch(f){return console.error("Error in propagate:",f),{...o,error:f.message}}}(this._backend,e,t,n,s)}async getFederated(e,t,n={}){return await this.ready(),this._requireGunDB(),async function(e,t,n,s={}){const{aggregate:r=!1,idField:a="id",sumFields:i=[],concatArrays:o=[],removeDuplicates:f=!0,mergeStrategy:c=null,includeLocal:l=!0,includeFederated:u=!0,resolveReferences:d=!0,maxFederatedSpaces:p=-1,timeout:h=1e4}=s;if(!e||!t||!n)throw new Error("Missing required parameters: backend, holon, and lens are required");const y=await J(e,t),m=[],g=new Set;if(u&&y&&y.federation&&y.federation.length>0){const t=-1===p?y.federation:y.federation.slice(0,p);for(const s of t)try{const t=e.buildPath(e.appName,s,n),r=await e.readAll(t);for(const e of r)e&&e[a]&&(m.push(e),g.add(e[a]))}catch(b){console.warn(`Error processing federated space ${s}: ${b.message}`)}}if(l){const s=e.buildPath(e.appName,t,n),r=await e.readAll(s);for(const e of r)e&&e[a]&&!g.has(e[a])&&(m.push(e),g.add(e[a]))}if(d)for(let w=0;w<m.length;w++){const t=m[w];if(t.soul&&t.id)try{const n=await e.resolveReference(t);n&&(m[w]=n)}catch(b){m[w]={id:t.id,_federation:{isReference:!0,resolved:!1,soul:t.soul,error:b.message,timestamp:Date.now()}}}else if(t._federation&&t._federation.isReference)try{const n=await e.resolveReference(t);n&&(m[w]=n)}catch(b){console.warn(`Error resolving legacy reference: ${b.message}`)}}if(r&&m.length>0){const e=m.reduce((e,t)=>{const n=t[a];return e[n]||(e[n]=[]),e[n].push(t),e},{});return Object.values(e).map(e=>{if(1===e.length)return e[0];if(c&&"function"==typeof c)return c(e);const t={...e[0]};for(const n of i)"number"==typeof t[n]&&(t[n]=e.reduce((e,t)=>e+(Number(t[n])||0),0));for(const n of o)if(Array.isArray(t[n])){const s=e.reduce((e,t)=>Array.isArray(t[n])?[...e,...t[n]]:e,[]);t[n]=f?Array.from(new Set(s)):s}return t._aggregated={count:e.length,timestamp:Date.now()},t})}return m}(this._backend,e,t,n)}async subscribeFederation(e,t,n={}){return await this.ready(),this._requireGunDB(),async function(e,t,n,s={}){if(!t||!n)throw new Error("subscribeFederation: Missing required parameters");const{lenses:r=["*"],throttle:a=0,resolveReferences:i=!0}=s,o=await J(e,t);if(!o)throw new Error("No federation info found for space");const f=[];let c={};if(o.federation&&o.federation.length>0)for(const u of o.federation)for(const t of r)try{const s=e.buildPath(e.appName,u,t),r=await e.subscribe(s,async(s,r)=>{try{if(!s||!s.id)return;const r=Date.now(),o=`${u}_${t}_${s.id}`;if(a>0){if(c[o]&&r-c[o]<a)return;c[o]=r}let f=s;i&&e.isReference(s)&&(f=await e.resolveReference(s)),f._federation||(f._federation={origin:u,timestamp:r}),await n(f,u,t)}catch(o){console.warn("Federation notification error:",o)}},{resolveReferences:!1});r&&"function"==typeof r.unsubscribe&&f.push(r)}catch(l){console.warn(`Error creating subscription for ${u}/${t}:`,l)}return{unsubscribe:()=>{f.forEach(e=>{try{e&&"function"==typeof e.unsubscribe&&e.unsubscribe()}catch(l){console.warn("Error unsubscribing:",l)}}),f.length=0,c={}},getSubscriptionCount:()=>f.length}}(this._backend,e,t,n)}async federateMessage(e,t,n,s,r="generic"){return await this.ready(),this._requireGunDB(),async function(e,t,n,s,r,a="generic"){const i=`${t}_${n}_fedmsgs`;let o=await e.readGlobal("federation_messages",i);o||(o={id:i,originalChatId:t,originalMessageId:n,type:a,messages:[]});const f=o.messages.find(e=>e.chatId===s);f?(f.messageId=r,f.timestamp=Date.now()):o.messages.push({chatId:s,messageId:r,timestamp:Date.now()}),await e.writeGlobal("federation_messages",o)}(this._backend,e,t,n,s,r)}async getFederatedMessages(e,t){return await this.ready(),this._requireGunDB(),G(this._backend,e,t)}async updateFederatedMessages(e,t,n){return await this.ready(),this._requireGunDB(),async function(e,t,n,s){const r=await G(e,t,n);if(r?.messages)for(const i of r.messages)try{await s(i.chatId,i.messageId)}catch(a){console.warn(`Failed to update federated message in chat ${i.chatId}:`,a)}}(this._backend,e,t,n)}close(){this._backend&&this._backend.close(),this.client&&"function"==typeof this.client.close&&this.client.close()}};function ne(e,n,s){if("number"!=typeof e||e<-90||e>90)throw new RangeError(`Invalid latitude: ${e}. Must be between -90 and 90.`);if("number"!=typeof n||n<-180||n>180)throw new RangeError(`Invalid longitude: ${n}. Must be between -180 and 180.`);if(!Number.isInteger(s)||s<0||s>15)throw new RangeError(`Invalid resolution: ${s}. Must be integer between 0 and 15.`);try{return t.latLngToCell(e,n,s)}catch(r){throw new Error(`H3 conversion failed: ${r.message}`)}}function se(e,n=0){if(!ae(e))throw new Error(`Invalid H3 holon ID: ${e}`);const s=[];let r=e;for(let i=t.getResolution(e)-1;i>=n;i--)try{r=t.cellToParent(r,i),s.push(r)}catch(a){break}return s}function re(e){if(!ae(e))throw new Error(`Invalid H3 holon ID: ${e}`);try{const n=t.getResolution(e);if(n>=15)throw new Error("Cannot get children of resolution 15 cell (maximum resolution)");return t.cellToChildren(e,n+1)}catch(n){throw new Error(`Failed to get children: ${n.message}`)}}function ae(e){return"string"==typeof e&&t.isValidCell(e)}const ie=Object.freeze(Object.defineProperty({__proto__:null,getChildren:re,getH3Resolution:function(e){if(!ae(e))throw new Error(`Invalid H3 holon ID: ${e}`);return t.getResolution(e)},getParents:se,isValidH3:ae,toHolon:ne},Symbol.toStringTag,{value:"Module"})),oe=new Map,fe=new Map,ce=new Map,le=2e3;async function ue(e,t,n,s=3e4){const r={kind:s,created_at:Math.floor(Date.now()/1e3),tags:[["d",t]],content:JSON.stringify(n)};return await e.publish(r)}async function de(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,a=s.authors||[e.publicKey];if(!s.skipCache&&e.getCachedByPath){const r=e.getCachedByPath(t,n);if(r&&r.content&&a.includes(r.pubkey))try{const e=JSON.parse(r.content);return!e||e._deleted?null:(s.includeAuthor&&(e._author=r.pubkey),e)}catch(c){}}if(!s.skipPersistent&&e.persistentGet){const i=await e.persistentGet(t);if(i&&i.content)if(a.includes(i.pubkey))try{const o=JSON.parse(i.content);return!o||o._deleted?null:(s.includeAuthor&&(o._author=i.pubkey),e.refreshPathInBackground&&e.refreshPathInBackground(t,n,{authors:a,timeout:r}),o)}catch(c){console.warn("[nostrGet] Failed to parse persisted event:",c)}else;}const i=`get:${e.publicKey}:${n}:${t}:${a.join(",")}`,o=ce.get(i);if(o&&Date.now()-o.timestamp<le)return o.promise;const f=async function(e,t,n,s,r,a){const i={kinds:[n],authors:s,"#d":[t],limit:s.length},o=await e.query(i,{timeout:r}),f=o.filter(e=>s.includes(e.pubkey));if(0===f.length)return null;const l=f.sort((e,t)=>t.created_at-e.created_at)[0];try{const e=JSON.parse(l.content);return!e||e._deleted?null:(a.includeAuthor&&(e._author=l.pubkey),e)}catch(c){return null}}(e,t,n,a,r,s);return ce.set(i,{promise:f,timestamp:Date.now()}),f.finally(()=>{setTimeout(()=>{const e=ce.get(i);e&&e.promise===f&&ce.delete(i)},le)}),f}async function pe(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,a=s.limit||1e3,i=s.authors||[e.publicKey];if(!s.skipPersistent&&e.persistentGetAll){const o=await e.persistentGetAll(t);if(o.length>0){const f=new Map;for(const e of o){if(!e||!e.tags)continue;if(!i.includes(e.pubkey))continue;const n=e.tags.find(e=>"d"===e[0]);if(!n||!n[1]||!n[1].startsWith(t))continue;const r=n[1],a=f.get(r);if(!a||e.created_at>a.created_at)try{const t=JSON.parse(e.content);if(!t||t._deleted){f.delete(r);continue}s.includeAuthor&&(t._author=e.pubkey),f.set(r,{data:t,created_at:e.created_at})}catch(l){}}return e.refreshPrefixInBackground&&e.refreshPrefixInBackground(t,n,{authors:i,timeout:r,limit:a}),Array.from(f.values()).map(e=>e.data)}}const o=`getAll:${e.publicKey}:${n}:${t}:${i.join(",")}`,f=ce.get(o);if(f&&Date.now()-f.timestamp<le)return f.promise;const c=async function(e,t,n,s,r,a,i){const o={kinds:[n],authors:s,limit:a},f=await e.query(o,{timeout:r}),c=f.filter(e=>{const n=e.tags.find(e=>"d"===e[0]),r=n&&n[1]&&n[1].startsWith(t),a=s.includes(e.pubkey);return r&&a}),u=new Map;for(const d of c){const e=d.tags.find(e=>"d"===e[0])[1],t=u.get(e);if(!t||d.created_at>t.created_at)try{const t=JSON.parse(d.content);if(!t||t._deleted){u.delete(e);continue}i.includeAuthor&&(t._author=d.pubkey),u.set(e,{data:t,created_at:d.created_at})}catch(l){}}return Array.from(u.values()).map(e=>e.data)}(e,t,n,i,r,a,s);return ce.set(o,{promise:c,timestamp:Date.now()}),c.finally(()=>{setTimeout(()=>{const e=ce.get(o);e&&e.promise===c&&ce.delete(o)},le)}),c}async function he(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,a=s.limit||1e3,i=s.authors||[e.publicKey],o=e.queryHybrid||e.query,f={kinds:[n],authors:i,limit:a},c=(await o.call(e,f,{timeout:r})).filter(e=>{const n=e.tags.find(e=>"d"===e[0]),s=n&&n[1]&&n[1].startsWith(t),r=i.includes(e.pubkey);return s&&r}),l=new Map;for(const d of c){const e=d.tags.find(e=>"d"===e[0])[1],t=l.get(e);if(!t||d.created_at>t.created_at)try{const t=JSON.parse(d.content);if(null===t||"object"!=typeof t)continue;if(t._deleted){l.delete(e);continue}s.includeAuthor&&(t._author=d.pubkey),l.set(e,{data:t,created_at:d.created_at})}catch(u){}}return Array.from(l.values()).map(e=>e.data)}function ye(e){return encodeURIComponent(e).replace(/%2F/g,"/")}async function me(e,t){try{const n=await async function(e,t,n=3e4){if(!(await de(e,t,n)))return{reason:"not_found",results:[]};const s={_deleted:!0,_deletedAt:Date.now()},r=await ue(e,t,s,n);if(e.persistentStorage)try{await e.persistentStorage.delete(t)}catch(o){}const a=`${n}:${e.publicKey}:${t}`,i={kind:5,created_at:Math.floor(Date.now()/1e3),tags:[["a",a]],content:""};try{await e.publish(i)}catch(f){}return r}(e,t);if("not_found"===n.reason)return!1;return 0===n.results.length||n.results.some(e=>"fulfilled"===e.status)}catch(n){throw console.error("Nostr delete error:",n),n}}async function ge(e,t){try{const n=await async function(e,t,n=3e4){const s={kinds:[n],authors:[e.publicKey],limit:1e3},r=await e.query(s,{timeout:3e4});let a=[];if(e.persistentStorage)try{a=await e.persistentStorage.getAll(t)}catch(l){}const i=new Map;for(const d of r){const e=d.tags?.find(e=>"d"===e[0]);e&&e[1]&&e[1].startsWith(t)&&i.set(e[1],d)}for(const d of a){const e=d.tags?.find(e=>"d"===e[0]);if(e&&e[1]&&e[1].startsWith(t)){const t=i.get(e[1]);(!t||d.created_at>t.created_at)&&i.set(e[1],d)}}const o=Array.from(i.values());if(0===o.length)return{success:!0,count:0,results:[]};const f=[];for(let d=0;d<o.length;d++){const t=o[d].tags.find(e=>"d"===e[0])[1];try{const s={_deleted:!0,_deletedAt:Date.now()},r=await ue(e,t,s,n);if(f.push(r),e.persistentStorage)try{await e.persistentStorage.delete(t)}catch(l){}d<o.length-1&&await new Promise(e=>setTimeout(e,100))}catch(u){console.error(`Failed to delete item ${t}:`,u)}}const c=o.map(t=>{const s=t.tags.find(e=>"d"===e[0])[1];return`${n}:${e.publicKey}:${s}`});try{const t={kind:5,created_at:Math.floor(Date.now()/1e3),tags:c.map(e=>["a",e]),content:""};await e.publish(t)}catch(u){}return{success:!0,count:o.length,results:f}}(e,t);return n}catch(n){throw console.error("Nostr deleteAll error:",n),n}}async function be(e,t,n,s={}){return t.split("/").length<=3?await async function(e,t,n,s={}){const r=s.kind||3e4,a=`${e.publicKey}:${r}:${t}`,i=oe.get(a);if(i)return i.callbacks.push(n),{unsubscribe:()=>{const e=i.callbacks.indexOf(n);e>-1&&i.callbacks.splice(e,1),0===i.callbacks.length&&(i.actualSubscription.unsubscribe(),oe.delete(a))}};const o=new Set,f=[n];let c=0,l=0,u=Date.now();const d=n=>{if(o.has(n.id))return;if(o.add(n.id),n.pubkey!==e.publicKey){c++;const t=Date.now();return void(t-u>1e4&&(console.warn("[nostrSubscribeMany] ⚠️ Relay not respecting authors filter!",{rejectedCount:c,acceptedCount:l,expected:e.publicKey,message:"Consider using a different relay or implementing private relay"}),u=t))}const s=n.tags.find(e=>"d"===e[0]),r=s?.[1];if(r&&r.startsWith(t))try{const e=JSON.parse(n.content);if(!e||e._deleted)return;l++;for(const t of f)t(e,r,n)}catch(a){console.error("[nostrSubscribeMany] Failed to parse event:",a)}},p=Math.floor(Date.now()/1e3),h={kinds:[r],authors:[e.publicKey],since:p},y=await e.subscribe(h,d);let m="undefined"!=typeof document&&document.hidden,g=p;const b=async()=>{if("undefined"==typeof document)return;const t=m;if(m=document.hidden,t&&!m){const t=Math.floor(Date.now()/1e3);try{const n={...h,since:g,until:t},s=await e.query(n,{timeout:3e4});for(const e of s)d(e);g=t}catch(n){}}};"undefined"!=typeof document&&document.addEventListener("visibilitychange",b);const w={unsubscribe:()=>{y&&y.unsubscribe&&y.unsubscribe(),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",b),oe.delete(a)}},v={callbacks:f,actualSubscription:w};return oe.set(a,v),w}(e,t+"/",(e,t)=>{const s=t.split("/").pop();n(e,s)},s):function(e,t,n,s={}){const r=s.kind||3e4,a=`single:${e.publicKey}:${r}:${t}`,i=fe.get(a);if(i)return i.callbacks.push(n),{unsubscribe:()=>{const e=i.callbacks.indexOf(n);e>-1&&i.callbacks.splice(e,1),0===i.callbacks.length&&(i.subscription.unsubscribe(),fe.delete(a))}};const o=[n],f={callbacks:o,subscription:null};fe.set(a,f);const c={kinds:[r],authors:[e.publicKey],"#d":[t],limit:10},l=e.subscribe(c,t=>{if(t.pubkey===e.publicKey)try{const e=JSON.parse(t.content);if(!e||e._deleted)return;for(const s of o)try{s(e,t)}catch(n){console.error("Subscription callback error:",n)}}catch(s){console.error("Failed to parse event in subscription:",s)}},{onEOSE:()=>{}});return f.subscription=l,{unsubscribe:()=>{const e=o.indexOf(n);e>-1&&o.splice(e,1),0===o.length&&(l.unsubscribe(),fe.delete(a))}}}(e,t,e=>{n(e,t.split("/").pop())},s)}function we(e,t,n,s=null){return function(e,t,n,s=null){const r=ye(t),a=ye(n);if(s)return`${e}/${r}/${a}/${ye(s)}`;return`${e}/${r}/${a}`}(e,t,n,s)}async function ve(e,t,n){return e.write&&e.gun?e.write(t,n):e.gun?C(e.gun,t,n):async function(e,t,n){try{const s=await ue(e,t,n);return 0===s.results.length||s.results.some(e=>"fulfilled"===e.status)}catch(s){throw console.error("Nostr write error:",s),s}}(e,t,n)}async function _e(e,t,n={}){return e.read&&e.gun?e.read(t,n):e.gun?O(e.gun,t):async function(e,t,n={}){const s=await de(e,t,3e4,n);return!s||s._deleted?null:s}(e,t,n)}async function Te(e,t,n={}){return e.readAll&&e.gun?e.readAll(t,n):e.gun?R(e.gun,t):async function(e,t,n={}){const s=n.hybrid&&"function"==typeof e.queryHybrid?he:pe;return(await s(e,t,3e4,n)).filter(e=>!(!e||"object"!=typeof e||e._deleted))}(e,t,n)}async function xe(e,t,n){return e.update&&e.gun?e.update(t,n):e.gun?$(e.gun,t,n):async function(e,t,n){try{const s=await de(e,t);if(!s||!s.id||s._deleted)return!1;const r={...s,...n};r._meta||(r._meta={}),r._meta.timestamp=Date.now();const a=await ue(e,t,r);return 0===a.results.length||a.results.some(e=>"fulfilled"===e.status)}catch(s){throw console.error("Nostr update error:",s),s}}(e,t,n)}async function Ae(e,t){return e.delete&&e.gun?e.delete(t):e.gun?P(e.gun,t):me(e,t)}async function Se(e,t){return e.gun?M(e.gun,t):ge(e,t)}function ke(e,t,n,s={}){return e.subscribe&&e.gun?e.subscribe(t,n,s):e.gun?D(e.gun,t,n,s):be(e,t,n,s)}const Ee=Object.freeze(Object.defineProperty({__proto__:null,buildPath:we,deleteAll:Se,deleteData:Ae,read:_e,readAll:Te,subscribe:ke,update:xe,write:ve},Symbol.toStringTag,{value:"Module"}));async function Ne(e,t,n,s){s.id||(s.id=`${Date.now()}-${Math.random().toString(36).substr(2,9)}`);return ve(e,`${t}/${n}/${s.id}`,s)}async function Ie(e,t,n,s=null){if(s){return _e(e,`${t}/${n}/${s}`)}return Te(e,`${t}/${n}`)}const Ce=new n({allErrors:!0,strict:!1}),Oe=new Map;let Re=class extends Error{constructor(e,t=[]){super(e),this.name="ValidationError",this.errors=t}};function $e(e,t){const n=t,s=Oe.get(n);if(s&&Date.now()-s.timestamp<36e5)return s.validator;try{const t=Ce.compile(e);return Oe.set(n,{validator:t,timestamp:Date.now()}),t}catch(r){throw new Error(`Schema compilation failed: ${r.message}`)}}function Pe(e,t,n,s=!1){const r=$e(t,n);if(!r(e)){const e=r.errors||[],t=e.map(e=>`${e.instancePath} ${e.message}`).join("; ");if(s)throw new Re(`ValidationError: Validation failed: ${t}`,e);return console.warn(`[Schema Validation Warning] ${n}: ${t}`),!1}return!0}const Me=Object.freeze(Object.defineProperty({__proto__:null,ValidationError:Re,clearAllCaches:function(){Oe.clear()},clearSchemaCache:function(e){Oe.delete(e)},compileSchema:$e,validate:Pe},Symbol.toStringTag,{value:"Module"})),De="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;
|
|
2
|
-
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
|
-
function Fe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function He(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Be(e,...t){if(!Fe(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function je(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ue(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Le(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function qe(e,t){return e<<32-t|e>>>t}const Je=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Ge=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ze(e){if(Be(e),Je)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ge[e[n]];return t}const We=48,Ke=57,Ve=65,Ze=70,Ye=97,Xe=102;function Qe(e){return e>=We&&e<=Ke?e-We:e>=Ve&&e<=Ze?e-(Ve-10):e>=Ye&&e<=Xe?e-(Ye-10):void 0}function et(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),Be(e),e}let tt=class{};function nt(e){const t=t=>e().update(et(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function st(e,t,n){return e&t^~e&n}function rt(e,t,n){return e&t^e&n^t&n}class at extends tt{constructor(e,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Le(this.buffer)}update(e){je(this),Be(e=et(e));const{view:t,buffer:n,blockLen:s}=this,r=e.length;for(let a=0;a<r;){const i=Math.min(s-this.pos,r-a);if(i===s){const t=Le(e);for(;s<=r-a;a+=s)this.process(t,a);continue}n.set(e.subarray(a,a+i),this.pos),this.pos+=i,a+=i,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){je(this),function(e,t){Be(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:r}=this;let{pos:a}=this;t[a++]=128,Ue(this.buffer.subarray(a)),this.padOffset>s-a&&(this.process(n,0),a=0);for(let l=a;l<s;l++)t[l]=0;!function(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const r=BigInt(32),a=BigInt(4294967295),i=Number(n>>r&a),o=Number(n&a),f=s?4:0,c=s?0:4;e.setUint32(t+f,i,s),e.setUint32(t+c,o,s)}(n,s-8,BigInt(8*this.length),r),this.process(n,0);const i=Le(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=o/4,c=this.get();if(f>c.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)i.setUint32(4*l,c[l],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:r,destroyed:a,pos:i}=this;return e.destroyed=a,e.finished=r,e.length=s,e.pos=i,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const it=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ot=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ft=new Uint32Array(64);class ct extends at{constructor(e=32){super(64,e,8,!1),this.A=0|it[0],this.B=0|it[1],this.C=0|it[2],this.D=0|it[3],this.E=0|it[4],this.F=0|it[5],this.G=0|it[6],this.H=0|it[7]}get(){const{A:e,B:t,C:n,D:s,E:r,F:a,G:i,H:o}=this;return[e,t,n,s,r,a,i,o]}set(e,t,n,s,r,a,i,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|s,this.E=0|r,this.F=0|a,this.G=0|i,this.H=0|o}process(e,t){for(let l=0;l<16;l++,t+=4)ft[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){const e=ft[l-15],t=ft[l-2],n=qe(e,7)^qe(e,18)^e>>>3,s=qe(t,17)^qe(t,19)^t>>>10;ft[l]=s+ft[l-7]+n+ft[l-16]|0}let{A:n,B:s,C:r,D:a,E:i,F:o,G:f,H:c}=this;for(let l=0;l<64;l++){const e=c+(qe(i,6)^qe(i,11)^qe(i,25))+st(i,o,f)+ot[l]+ft[l]|0,t=(qe(n,2)^qe(n,13)^qe(n,22))+rt(n,s,r)|0;c=f,f=o,o=i,i=a+e|0,a=r,r=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,a=a+this.D|0,i=i+this.E|0,o=o+this.F|0,f=f+this.G|0,c=c+this.H|0,this.set(n,s,r,a,i,o,f,c)}roundClean(){Ue(ft)}destroy(){this.set(0,0,0,0,0,0,0,0),Ue(this.buffer)}}const lt=nt(()=>new ct),ut=lt;let dt=null;async function pt(){if(!dt){const e=await Promise.resolve().then(()=>require("./secp256k1-CiEONUnj.cjs"));dt=e.secp256k1}return dt}async function ht(e){return ze((await pt()).getPublicKey(e))}async function yt(e,t){try{const n=await pt(),s=vt(e);return n.sign(s,t).toCompactHex()}catch(n){throw new Error(`Signature generation failed: ${n.message}`)}}async function mt(e,t,n){try{if(!n||"string"!=typeof n||n.length<64)throw new Error("Invalid public key format");const s=await pt(),r=vt(e);return s.verify(t,r,n)}catch(s){if("Invalid public key format"===s.message)throw s;return!1}}function gt(e,t){if("string"==typeof e||"string"==typeof t){return("string"==typeof e?e:JSON.stringify(e))===("string"==typeof t?t:JSON.stringify(t))}return("*"===e.holonId||e.holonId===t.holonId)&&(("*"===e.lensName||e.lensName===t.lensName)&&(!e.dataId||"*"===e.dataId||!t.dataId||e.dataId===t.dataId))}async function bt(e,t,n,s={}){const{expiresIn:r=36e5,issuer:a="holosphere",issuerKey:i}=s;if(!Array.isArray(e)||0===e.length)throw new Error("Permissions array cannot be empty");if("object"==typeof t){if(void 0===t.holonId||""===t.holonId)throw new Error('Invalid scope: holonId is required (use "*" for wildcard)');if(void 0===t.lensName||""===t.lensName)throw new Error('Invalid scope: lensName is required (use "*" for wildcard)')}else if("string"==typeof t&&""===t)throw new Error("Invalid scope: cannot be empty string");if(i&&("string"!=typeof i||i.length<32))throw new Error("Invalid issuer key");const o={type:"capability",permissions:e,scope:t,recipient:n,issuer:a,nonce:Date.now().toString(36)+Math.random().toString(36).substring(2,15),issued:Date.now(),expires:Date.now()+r},f=JSON.stringify(o),c=Buffer.from?Buffer.from(f).toString("base64"):btoa(f);if(i){return`${c}.${await yt(f,i)}`}return c}async function wt(e,t,n){try{let s;if("string"==typeof e){const t=e.split(".")[0],n=Buffer.from?Buffer.from(t,"base64").toString("utf8"):atob(t);s=JSON.parse(n)}else s=e;return!(!s||"capability"!==s.type)&&(!(Date.now()>s.expires)&&(!!gt(s.scope,n)&&!!s.permissions.includes(t)))}catch(s){return!1}}function vt(e){const t="string"==typeof e?e:JSON.stringify(e),n=(new TextEncoder).encode(t);return ze(ut(n))}const _t=Object.freeze(Object.defineProperty({__proto__:null,getPublicKey:ht,issueCapability:bt,matchScope:gt,sign:yt,verify:mt,verifyCapability:wt},Symbol.toStringTag,{value:"Module"})),Tt="federations";async function xt(e,t){return await Ie(e,t,Tt,e.publicKey)||{id:e.publicKey,federatedWith:[],discoveryEnabled:!1,autoAccept:!1,defaultScope:{holonId:"*",lensName:"*"},defaultPermissions:["read"]}}async function At(e,t,n){return Ne(e,t,Tt,n)}async function St(e,t,n,s={}){const r=await xt(e,t),a=r.federatedWith.findIndex(e=>e.pubKey===n);if(a>=0){const e=r.federatedWith[a];s.alias&&(e.alias=s.alias),s.inboundCapabilities&&(e.inboundCapabilities=[...e.inboundCapabilities||[],...s.inboundCapabilities]),e.updatedAt=Date.now(),r.federatedWith[a]=e}else r.federatedWith.push({pubKey:n,alias:s.alias||null,addedAt:Date.now(),addedVia:s.addedVia||"manual",inboundCapabilities:s.inboundCapabilities||[],outboundCapabilities:[]});return At(e,t,r)}async function kt(e,t,n,s){const r=(await xt(e,t)).federatedWith.find(e=>e.pubKey===n);return r&&r.inboundCapabilities&&r.inboundCapabilities.find(e=>!(e.expires&&e.expires<Date.now())&>(e.scope,s))||null}async function Et(e,t,n,s){const r=await xt(e,t),a=r.federatedWith.find(e=>e.pubKey===n);if(!a)return St(e,t,n,{addedVia:"capability_received",inboundCapabilities:[s]});a.inboundCapabilities||(a.inboundCapabilities=[]);const i=a.inboundCapabilities.findIndex(e=>JSON.stringify(e.scope)===JSON.stringify(s.scope));return i>=0?a.inboundCapabilities[i]={...s,updatedAt:Date.now()}:a.inboundCapabilities.push({...s,receivedAt:Date.now()}),At(e,t,r)}async function Nt(e,t,n,s,r,a){const i=new Set,o=[];let f=n,c=r,l=a,u=t;for(;i.size<10;){const t=`${u}:${f}:${c}:${l}`;if(i.has(t))return{isCircular:!0,chain:o,reason:"existing_cycle"};if(i.add(t),o.push({holon:f,lens:c,dataId:l}),f===s)return{isCircular:!0,chain:o,reason:"would_create_cycle"};const n=we(u,f,c,l),r=await _e(e,n);if(!r)return{isCircular:!1,chain:o};if(!r.hologram||!r.target)return{isCircular:!1,chain:o};u=r.target.appname||u,f=r.target.holonId,c=r.target.lensName||c,l=r.target.dataId||l}return{isCircular:!0,chain:o,reason:"max_depth_exceeded"}}function It(e,t,n,s,r,a={}){const{authorPubKey:i=null,capability:o=null}=a,f={id:s,hologram:!0,soul:we(r,e,n,s),target:{appname:r,holonId:e,lensName:n,dataId:s},_meta:{created:Date.now(),sourceHolon:e,source:e}};return i&&(f.crossHolosphere=!0,f.target.authorPubKey=i,f._meta.sourcePubKey=i),o&&(f.capability=o,f._meta.grantedAt=Date.now()),f}async function Ct(e,t,n=new Set,s=[],r={}){const{deleteCircular:a=!0,hologramPath:i=null}=r;if(!t||!t.hologram)return t;const{soul:o}=t,f=t.target||{};if(n.has(o)){const r=[...s,o].join(" → ");return console.warn("🔄 Circular reference detected - removing hologram"),console.warn(` Soul: ${o}`),console.warn(` Chain: ${r}`),console.warn(` Source holon: ${f.holonId||"unknown"}`),console.warn(` Lens: ${f.lensName||"unknown"}`),console.warn(` Data ID: ${f.dataId||t.id||"unknown"}`),console.warn(` Resolution depth: ${n.size}`),a&&i&&(console.info(` 🗑️ Deleting circular hologram at: ${i}`),await ve(e,i,null)),null}if(n.size>=10){const t=[...s,o].join(" → ");return console.warn("⚠️ Max resolution depth (10) exceeded - removing hologram"),console.warn(` Current soul: ${o}`),console.warn(` Chain: ${t}`),console.warn(` Source holon: ${f.holonId||"unknown"}`),console.warn(` Lens: ${f.lensName||"unknown"}`),a&&i&&(console.info(` 🗑️ Deleting deep chain hologram at: ${i}`),await ve(e,i,null)),null}let c;if(n.add(o),s.push(o),t.crossHolosphere&&f.authorPubKey){let n=t.capability;if(!n&&r.appname){const t=await kt(e,r.appname,f.authorPubKey,{holonId:f.holonId,lensName:f.lensName,dataId:f.dataId});t&&(n=t.token)}if(!n)return console.warn(`❌ Cross-holosphere hologram missing capability: ${o}`),null;if(!(await wt(n,"read",{holonId:f.holonId,lensName:f.lensName,dataId:f.dataId})))return console.warn(`❌ Capability verification failed for cross-holosphere hologram: ${o}`),null;c=await _e(e,o,{authors:[f.authorPubKey]})}else c=await _e(e,o);return c?c.hologram?Ct(e,c,n,s,{...r,hologramPath:o}):function(e,t){const n=["hologram","soul","target","_meta","id","capability","crossHolosphere"],s={},r=[];for(const o of Object.keys(e))n.includes(o)||(s[o]=e[o],r.push(o));const a=e._meta?.sourceHolon||e._meta?.source||e.target?.holonId,i={...t,...s,_hologram:{isHologram:!0,soul:e.soul,sourceHolon:a,localOverrides:r,crossHolosphere:e.crossHolosphere||!1,sourcePubKey:e._meta?.sourcePubKey||null}};t._meta?i._meta={...t._meta,source:a}:i._meta={source:a};return i}(t,c):null}async function Ot(e,t,n,s,r,a={}){const{direction:i="outbound",mode:o="reference"}=a,f={sourceHolon:n,targetHolon:s,lensName:r,direction:i,mode:o,created:Date.now()};return ve(e,we(t,n,r,"_federation"),f)}async function Rt(e,t,n,s,r,a,i="reference"){const o=n.id;if(s===r)return console.info(`⏭️ Skipping propagation - source and target are the same holon: ${s}`),!0;if(!0===n.hologram){if(n.target&&n.target.holonId===r)return console.info("🔄 Skipping propagation - would create circular reference:"),console.info(` Data ID: ${o}`),console.info(` Source holon: ${s}`),console.info(` Target holon: ${r}`),console.info(` Hologram points to: ${n.target.holonId}`),console.info(` Lens: ${a}`),console.info(` Original soul: ${n.soul||"unknown"}`),!0;if(n.target){const s=we(n.target.appname||t,n.target.holonId,n.target.lensName||a,n.target.dataId||o),i=await _e(e,s);if(i?._meta?.activeHolograms){if(i._meta.activeHolograms.some(e=>e.targetHolon===r))return console.info("⏭️ Skipping propagation - target already in activeHolograms:"),console.info(` Data ID: ${o}`),console.info(` Original source: ${n.target.holonId}`),console.info(` Target holon: ${r}`),!0}}const i=n.target.holonId,f=n.target.dataId||o,c=n.target.lensName||a,l=n.target.appname||t,u=await Nt(e,l,i,r,c,f);if(u.isCircular){const e=u.chain.map(e=>e.holon).join(" → ");return console.warn("🔄 Preventing circular hologram copy:"),console.warn(` Data ID: ${o}`),console.warn(` Original source: ${i}`),console.warn(` Would copy to: ${r}`),console.warn(` Existing chain: ${e}`),console.warn(` Reason: ${u.reason}`),!1}const d=we(t,r,a,o),p={...n,_meta:{...n._meta,copiedFrom:s,copiedAt:Date.now()}},h=await ve(e,d,p);return h&&n.target&&(await Ft(e,n.target.appname||t,n.target.holonId,n.target.lensName||a,n.target.dataId||o,r),console.info(`📋 Copied hologram to ${r}:`),console.info(` Data ID: ${o}`),console.info(` Original source: ${n.target.holonId}`),console.info(` Copied from: ${s}`)),h}if("reference"===i&&n._meta?.activeHolograms){if(n._meta.activeHolograms.some(e=>e.targetHolon===r))return console.info("⏭️ Skipping propagation - target already in activeHolograms:"),console.info(` Data ID: ${o}`),console.info(` Source holon: ${s}`),console.info(` Target holon: ${r}`),!0}if("reference"===i){const n=await Nt(e,t,s,r,a,o);if(n.isCircular){const e=n.chain.map(e=>e.holon).join(" → ");return console.warn("🔄 Preventing circular hologram creation:"),console.warn(` Data ID: ${o}`),console.warn(` Would create: ${s} → ${r}`),console.warn(` Existing chain: ${e}`),console.warn(` Reason: ${n.reason}`),!1}const i=It(s,0,a,o,t),f=we(t,r,a,o),c=await ve(e,f,i);return c&&await Ft(e,t,s,a,o,r),c}return ve(e,we(t,r,a,o),{...n,_meta:{...n._meta,source:s}})}async function $t(e,t,n,s,r,a){const i=we(t,n,s,r),o=await _e(e,i);if(!o)return console.warn(`Hologram not found at ${i}`),!1;if(!o.hologram)return console.warn(`Data at ${i} is not a hologram, cannot update overrides`),!1;const f=["hologram","soul","target","_meta","id"],c={};for(const[l,u]of Object.entries(a))f.includes(l)||(c[l]=u);return ve(e,i,{...o,...c})}function Pt(e){return e&&!0===e.hologram}function Mt(e){return e&&e._hologram&&!0===e._hologram.isHologram}function Dt(e){return Mt(e)?{soul:e._hologram.soul,sourceHolon:e._hologram.sourceHolon,localOverrides:e._hologram.localOverrides||[]}:null}async function Ft(e,t,n,s,r,a){let i=t,o=n,f=s,c=r,l=we(i,o,f,c),u=await _e(e,l);if(!u)return console.warn(`Source data not found at ${l}`),!1;let d=0;for(;!0===u.hologram&&u.target&&d<10;)if(d++,i=u.target.appname||i,o=u.target.holonId,f=u.target.lensName||f,c=u.target.dataId||c,l=we(i,o,f,c),u=await _e(e,l),!u)return console.warn(`Real source data not found at ${l}`),!1;d>0&&console.info(`📍 Followed hologram chain (depth: ${d}) to real source: ${o}/${f}/${c}`),u._meta||(u._meta={}),Array.isArray(u._meta.activeHolograms)||(u._meta.activeHolograms=[]);const p=Date.now(),h=u._meta.activeHolograms.findIndex(e=>e.targetHolon===a);return h>=0?u._meta.activeHolograms[h].lastUpdated=p:u._meta.activeHolograms.push({targetHolon:a,created:p,lastUpdated:p,platforms:{}}),ve(e,l,u)}async function Ht(e,t,n,s,r,a){let i=t,o=n,f=s,c=r,l=we(i,o,f,c),u=await _e(e,l);if(!u)return!1;let d=0;for(;!0===u.hologram&&u.target&&d<10;)if(d++,i=u.target.appname||i,o=u.target.holonId,f=u.target.lensName||f,c=u.target.dataId||c,l=we(i,o,f,c),u=await _e(e,l),!u)return!1;if(!u._meta||!Array.isArray(u._meta.activeHolograms))return!1;const p=u._meta.activeHolograms.length;return u._meta.activeHolograms=u._meta.activeHolograms.filter(e=>e.targetHolon!==a),u._meta.activeHolograms.length<p&&ve(e,l,u)}async function Bt(e,t,n,s,r,a,i,o){let f=t,c=n,l=s,u=r,d=we(f,c,l,u),p=await _e(e,d);if(!p)return console.warn(`Source data not found at ${d}`),!1;let h=0;for(;!0===p.hologram&&p.target&&h<10;)if(h++,f=p.target.appname||f,c=p.target.holonId,l=p.target.lensName||l,u=p.target.dataId||u,d=we(f,c,l,u),p=await _e(e,d),!p)return console.warn(`Real source data not found at ${d}`),!1;if(!p._meta||!Array.isArray(p._meta.activeHolograms))return console.warn(`No activeHolograms found for ${d}`),!1;const y=p._meta.activeHolograms.find(e=>e.targetHolon===a);return y?(y.platforms||(y.platforms={}),y.platforms[i]={...y.platforms[i],...o,lastUpdated:Date.now()},y.lastUpdated=Date.now(),ve(e,d,p)):(console.warn(`No hologram entry found for target ${a}`),!1)}async function jt(e,t,n,s,r,a=null){const i=we(t,n,s,r),o=await _e(e,i);if(!o?._meta?.activeHolograms)return[];let f=o._meta.activeHolograms;return a&&(f=f.filter(e=>e.platforms?.[a])),f}async function Ut(e,t,n,s,r,a=null){if(!a){const i=we(t,n,s,r);a=await _e(e,i)}if(!a||!a._meta||!Array.isArray(a._meta.activeHolograms))return{refreshed:0,holograms:[]};const i=Date.now(),o=[];for(const f of a._meta.activeHolograms){f.lastUpdated=i;const n=we(t,f.targetHolon,s,r),a=await _e(e,n);a&&!0===a.hologram&&(a._meta||(a._meta={}),a._meta.lastUpdated=i,await ve(e,n,a),o.push({targetHolon:f.targetHolon,dataId:r,timestamp:i}))}return{refreshed:o.length,holograms:o,sourceData:a}}async function Lt(e,t,n,s,r,a={}){const{deleteData:i=!0}=a,o=we(t,n,s,r),f={success:!1,wasHologram:!1,sourceHolon:null,activeHologramsUpdated:!1,error:null};try{const a=await _e(e,o);if(!a)return console.warn(`🗑️ Hologram not found at ${o}`),f.error="Hologram not found",f;if(!0===a.hologram&&a.target){f.wasHologram=!0,f.sourceHolon=a.target.holonId,console.info("🗑️ Deleting hologram:"),console.info(` Path: ${o}`),console.info(` Data ID: ${r}`),console.info(` From holon: ${n}`),console.info(` Source holon: ${a.target.holonId}`),console.info(` Lens: ${s}`);const i=await Ht(e,a.target.appname||t,a.target.holonId,a.target.lensName||s,a.target.dataId||r,n);f.activeHologramsUpdated=i,i?console.info(" ✓ Removed from activeHolograms on source"):console.warn(" ⚠️ Could not update activeHolograms on source (may already be removed)")}else console.info(`🗑️ Deleting non-hologram data at ${o}`);if(i){const t=await ve(e,o,null);f.success=t,t?console.info(" ✓ Hologram deleted successfully"):(console.warn(" ⚠️ Failed to delete hologram data"),f.error="Failed to delete hologram data")}else f.success=!0;return f}catch(c){return console.error(`❌ Error deleting hologram at ${o}:`,c),f.error=c.message||"Unknown error",f}}async function qt(e,t,n,s,r={}){const{dryRun:a=!1}=r,i={scanned:0,circularFound:0,deleted:0,errors:[],details:[]};console.info(`🧹 ${a?"[DRY RUN] ":""}Cleaning up circular holograms in ${n}/${s}...`);try{we(t,n,s);const r=we(t,n,s,"_index"),o=await _e(e,r);if(!o||!Array.isArray(o.items))return console.warn(` No index found for ${n}/${s}, cannot scan for circular references`),console.info(" Tip: Provide specific IDs to check using cleanupCircularHologramsByIds()"),i;for(const f of o.items){i.scanned++;const r=we(t,n,s,f),o=await _e(e,r);if(!o||!0!==o.hologram||!o.target)continue;const c=o.target.holonId,l=o.target.dataId||f,u=o.target.lensName||s,d=we(o.target.appname||t,c,u,l),p=await _e(e,d);if(p&&!0===p.hologram&&p.target&&p.target.holonId===n){i.circularFound++;const o={itemId:f,path:r,pointsTo:`${c}/${u}/${l}`,circularWith:`${p.target.holonId}/${p.target.lensName}/${p.target.dataId}`};if(i.details.push(o),console.warn(" 🔄 Found circular hologram:"),console.warn(` ${n}/${s}/${f} → ${c}/${u}/${l} → ${n}`),!a){const r=await Lt(e,t,n,s,f);r.success?(i.deleted++,console.info(" ✓ Deleted circular hologram")):(i.errors.push({itemId:f,error:r.error}),console.error(` ❌ Failed to delete: ${r.error}`))}}}return console.info(`🧹 Cleanup complete for ${n}/${s}:`),console.info(` Scanned: ${i.scanned}`),console.info(` Circular found: ${i.circularFound}`),console.info(` Deleted: ${i.deleted}`),i.errors.length>0&&console.warn(` Errors: ${i.errors.length}`),i}catch(o){return console.error("❌ Error during cleanup:",o),i.errors.push({error:o.message}),i}}async function Jt(e,t,n,s,r,a={}){const{dryRun:i=!1}=a,o={scanned:0,circularFound:0,deleted:0,errors:[],details:[]};console.info(`🧹 ${i?"[DRY RUN] ":""}Cleaning up circular holograms for ${r.length} IDs in ${n}/${s}...`);for(const f of r){o.scanned++;const r=we(t,n,s,f),a=await _e(e,r);if(!a||!0!==a.hologram||!a.target)continue;const c=a.target.holonId,l=a.target.dataId||f,u=a.target.lensName||s,d=we(a.target.appname||t,c,u,l),p=await _e(e,d);if(p&&!0===p.hologram&&p.target&&p.target.holonId===n){o.circularFound++;const a={itemId:f,path:r,pointsTo:`${c}/${u}/${l}`,circularWith:`${p.target.holonId}/${p.target.lensName}/${p.target.dataId}`};if(o.details.push(a),console.warn(` 🔄 Found circular hologram: ${f}`),console.warn(` Chain: ${n} → ${c} → ${n}`),!i){const r=await Lt(e,t,n,s,f);r.success?(o.deleted++,console.info(" ✓ Deleted")):(o.errors.push({itemId:f,error:r.error}),console.error(` ❌ Failed: ${r.error}`))}}}return console.info(`🧹 Cleanup complete: scanned=${o.scanned}, circular=${o.circularFound}, deleted=${o.deleted}`),o}const Gt=Object.freeze(Object.defineProperty({__proto__:null,addActiveHologram:Ft,cleanupCircularHolograms:qt,cleanupCircularHologramsByIds:Jt,createHologram:It,deleteHologram:Lt,getActiveHolograms:jt,getHologramSource:Dt,isHologram:Pt,isResolvedHologram:Mt,propagateData:Rt,refreshActiveHolograms:Ut,removeActiveHologram:Ht,resolveHologram:Ct,setupFederation:Ot,updateActiveHologramPlatform:Bt,updateHologramOverrides:$t,wouldCreateCircularHologram:Nt},Symbol.toStringTag,{value:"Module"}));function zt(e){const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t}function Wt(t){try{return e.nip19.npubEncode(t)}catch(n){return console.error("Failed to encode hex to npub:",n),t}}async function Kt(t,n,s){return await e.nip04.decrypt(t,n,s)}function Vt(t,n,s){const r=zt(t),a=e.nip44.v2.utils.getConversationKey(r,n);return e.nip44.v2.encrypt(s,a)}function Zt(t,n,s){const r=zt(t),a=e.nip44.v2.utils.getConversationKey(r,n);return e.nip44.v2.decrypt(s,a)}function Yt(t,n,s,r){const a={kind:t,content:n,tags:s,created_at:Math.floor(Date.now()/1e3)};return e.finalizeEvent(a,zt(r))}function Xt(e,t,n){return Yt(4,t,[["p",e]],n)}function Qt(){return Date.now().toString(36)+Math.random().toString(36).substring(2,15)}function en(t,n){const s={kind:t.kind,content:t.content,tags:t.tags||[],created_at:t.created_at||Math.floor(Date.now()/1e3)};return e.finalizeEvent(s,zt(n))}function tn(t){return e.verifyEvent(t)}const nn=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex:function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},createDMEvent:Xt,createSignedEvent:Yt,decryptNIP04:Kt,decryptNIP44:Zt,encryptNIP04:async function(t,n,s){return await e.nip04.encrypt(t,n,s)},encryptNIP44:Vt,generateNonce:Qt,getPublicKey:function(t){return e.getPublicKey(zt(t))},hexToBytes:zt,hexToNpub:Wt,isValidHexPubKey:function(e){return"string"==typeof e&&/^[0-9a-fA-F]{64}$/.test(e)},isValidNpub:function(t){if("string"!=typeof t||!t.startsWith("npub1"))return!1;try{return"npub"===e.nip19.decode(t).type}catch{return!1}},npubToHex:function(t){try{const n=e.nip19.decode(t);return"npub"===n.type?n.data:null}catch(n){return null}},parseNpubOrHex:function(t){const n=t?.trim();if(!n)return{valid:!1,error:"Public key is required"};if(/^[0-9a-fA-F]{64}$/.test(n))return{valid:!0,hexPubKey:n.toLowerCase()};let s=n;if(s.startsWith("nostr:")&&(s=s.slice(6)),s.startsWith("npub1"))try{const t=e.nip19.decode(s);return"npub"===t.type?{valid:!0,hexPubKey:t.data}:{valid:!1,error:"Invalid npub format"}}catch(r){return{valid:!1,error:"Invalid npub: unable to decode"}}return{valid:!1,error:"Enter a valid npub (npub1...) or 64-character hex public key"}},shortenNpub:function(e){return!e||e.length<=20?e||"":`${e.slice(0,12)}...${e.slice(-8)}`},shortenPubKey:function(e){return!e||e.length<=20?e||"":`${e.slice(0,8)}...${e.slice(-8)}`},signEvent:en,verifyEvent:tn},Symbol.toStringTag,{value:"Module"}));function sn({senderHolonId:e,senderHolonName:t,senderPubKey:n,lensConfig:s={inbound:[],outbound:[]},capabilities:r=[],message:a}){return{type:"federation_request",version:"1.0",requestId:Qt(),timestamp:Date.now(),senderHolonId:e,senderHolonName:t,senderNpub:Wt(n),lensConfig:s,capabilities:r,message:a}}function rn({requestId:e,status:t,responderHolonId:n,responderHolonName:s,responderPubKey:r,lensConfig:a,capabilities:i,message:o}){return{type:"federation_response",version:"1.0",requestId:e,timestamp:Date.now(),status:t,responderHolonId:n,responderHolonName:s,responderNpub:r?Wt(r):void 0,lensConfig:a,capabilities:i,message:o}}async function an(e,t,n,s){try{const r=JSON.stringify(s),a=Xt(n,Vt(t,n,r),t);return e?.publish?(await e.publish(a),console.log("[Handshake] Federation request sent to:",n.substring(0,8)+"..."),!0):(console.error("[Handshake] No publish method on client"),!1)}catch(r){return console.error("[Handshake] Failed to send federation request:",r),!1}}async function on(e,t,n,s){try{const r=JSON.stringify(s),a=Xt(n,Vt(t,n,r),t);return e?.publish?(await e.publish(a),console.log("[Handshake] Federation response sent to:",n.substring(0,8)+"..."),!0):(console.error("[Handshake] No publish method on client"),!1)}catch(r){return console.error("[Handshake] Failed to send federation response:",r),!1}}const fn=Object.freeze(Object.defineProperty({__proto__:null,acceptFederationRequest:async function(e,t,n){const{request:s,senderPubKey:r,holonId:a,holonName:i,lensConfig:o={inbound:[],outbound:[]},message:f}=n;try{const{getPublicKey:n}=await Promise.resolve().then(()=>nn),c=n(t);if(e.client&&(await St(e.client,e.config.appName,r,{alias:s.senderHolonName,addedVia:"handshake_accepted"}),s.capabilities&&s.capabilities.length>0))for(const t of s.capabilities)await Et(e.client,e.config.appName,r,t);await e.federateHolon(a,r,{lensConfig:o,partnerName:s.senderHolonName});const l=rn({requestId:s.requestId,status:"accepted",responderHolonId:a,responderHolonName:i,responderPubKey:c,lensConfig:o,capabilities:[],message:f});return await on(e.client,t,r,l)?{success:!0}:{success:!1,error:"Failed to send response DM"}}catch(c){return{success:!1,error:c.message}}},createFederationRequest:sn,createFederationResponse:rn,initiateFederationHandshake:async function(e,t,n){const{partnerPubKey:s,holonId:r,holonName:a,lensConfig:i={inbound:[],outbound:[]},message:o}=n;try{const{getPublicKey:n}=await Promise.resolve().then(()=>nn),f=sn({senderHolonId:r,senderHolonName:a,senderPubKey:n(t),lensConfig:i,capabilities:[],message:o});e.client&&await St(e.client,e.config.appName,s,{alias:null,addedVia:"handshake_initiated"});return await an(e.client,t,s,f)?{success:!0,requestId:f.requestId}:{success:!1,error:"Failed to send DM"}}catch(f){return{success:!1,error:f.message}}},isFederationRequest:function(e){return"federation_request"===e?.type&&"1.0"===e?.version},isFederationResponse:function(e){return"federation_response"===e?.type&&"1.0"===e?.version},rejectFederationRequest:async function(e,t,n){const{requestId:s,senderPubKey:r,message:a}=n;try{const n=rn({requestId:s,status:"rejected",message:a}),i=await on(e.client,t,r,n);return{success:i,error:i?void 0:"Failed to send response DM"}}catch(i){return{success:!1,error:i.message}}},sendFederationRequest:an,sendFederationResponse:on,subscribeToFederationDMs:function(e,t,n,s){const{onRequest:r,onResponse:a}=s;let i=!0;const o=new Set,f=async e=>{if(!i)return;if(o.has(e.id))return;if(o.add(e.id),4!==e.kind)return;const s=e.tags?.find(e=>"p"===e[0]);if(s&&s[1]===n)try{let n;try{n=Zt(t,e.pubkey,e.content)}catch(f){n=await Kt(t,e.pubkey,e.content)}const s=JSON.parse(n);"federation_request"===s.type&&"1.0"===s.version?(console.log("[Handshake] Received federation request from:",e.pubkey.substring(0,8)+"..."),r?.(s,e.pubkey)):"federation_response"===s.type&&"1.0"===s.version&&(console.log("[Handshake] Received federation response from:",e.pubkey.substring(0,8)+"..."),a?.(s,e.pubkey))}catch(c){}};let c=null;return(async()=>{const t=e?.client;if(!t?.subscribe)return void console.warn("[Handshake] No NostrClient subscribe method available");const s={kinds:[4],"#p":[n],since:Math.floor(Date.now()/1e3)-86400};try{c=await t.subscribe(s,f,{}),console.log("[Handshake] Federation DM subscription started")}catch(r){console.error("[Handshake] Failed to subscribe:",r)}})(),()=>{i=!1,c?.unsubscribe?c.unsubscribe():c?.close&&c.close()}}},Symbol.toStringTag,{value:"Module"}));function cn(e,t=!0,n=!1){if(!e||"object"!=typeof e){if(n)throw new Re("ValidationError: Invalid Nostr event format");return!1}if("number"!=typeof e.kind){if(n)throw new Re("ValidationError: Invalid Nostr event format - kind must be a number");return!1}if(!Array.isArray(e.tags)){if(n)throw new Re("ValidationError: Invalid Nostr event format - tags must be an array");return!1}if("string"!=typeof e.content){if(n)throw new Re("ValidationError: Invalid Nostr event format - content must be a string");return!1}if("number"!=typeof e.created_at){if(n)throw new Re("ValidationError: Invalid Nostr event format - created_at must be a number");return!1}if(!t){if("string"!=typeof e.id){if(n)throw new Re("ValidationError: Invalid Nostr event format - id must be a string");return!1}if("string"!=typeof e.pubkey){if(n)throw new Re("ValidationError: Invalid Nostr event format - pubkey must be a string");return!1}if("string"!=typeof e.sig){if(n)throw new Re("ValidationError: Invalid Nostr event format - sig must be a string");return!1}}return!0}function ln(e,t=!1,n=!1){if(!e||"object"!=typeof e){if(t)throw new Re("ValidationError: Invalid ActivityPub object format");return!1}if(!e["@context"]){if(t)throw new Re("ValidationError: Invalid ActivityPub object format - @context is required");return!1}if("string"!=typeof e.type){if(t)throw new Re("ValidationError: Invalid ActivityPub object format - type must be a string");return!1}if(n&&"string"!=typeof e.id){if(t)throw new Re("ValidationError: Invalid ActivityPub object format - id must be a string");return!1}return!0}function un(e){const t=e.id||`ap-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return{id:t,protocol:"activitypub",type:e.type,actor:e.actor,published:e.published,content:e.content||e.name,originalObject:{...e,id:t},_meta:{timestamp:e.published?new Date(e.published).getTime():Date.now(),protocol:"activitypub"}}}const dn=Object.freeze(Object.defineProperty({__proto__:null,filterByAccessLevel:function(e,t){return t?e.filter(e=>!e.accessLevel||e.accessLevel===t):e},filterByProtocol:function(e,t){return t&&"all"!==t?Array.isArray(e)?e.filter(e=>e.protocol===t):[]:e},transformActivityPubObject:un,transformNostrEvent:function(e){const t=e.id||`nostr-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n=e.pubkey||"anonymous",s=e.sig||"";return{id:t,protocol:"nostr",originalFormat:"nip-01",pubkey:n,sig:s,created_at:e.created_at,kind:e.kind,tags:JSON.stringify(e.tags),content:e.content,signature:s,_meta:{timestamp:1e3*e.created_at,protocol:"nostr"}}},validateActivityPubObject:ln,validateNostrEvent:cn},Symbol.toStringTag,{value:"Module"}));async function pn(e,t,n,s={}){const{throttle:r=0,filter:a=null,includeFederated:i=!1,triggerInitial:o=!1,realtimeOnly:f=!0,resolveHolograms:c=!0}=s;let l=0,u=null;const d=new Set;let p=!0;const h=await ke(e,t,async(t,s)=>{if(!p)return;const i=`${s}-${t?.id||""}-${t?._meta?.timestamp||Date.now()}`;if(d.has(i))return;d.add(i);let o=t;if(c&&t&&!0===t.hologram)try{if(o=await Ct(e,t),!o)return}catch(h){return void console.warn("Failed to resolve hologram in subscription:",h)}if(a&&!a(o,s))return;const f=Date.now();if(r>0&&f-l<r)return u&&clearTimeout(u),void(u=setTimeout(()=>{l=Date.now(),n(o,s)},r-(f-l)));l=f,n(o,s)},{realtimeOnly:f});return{path:t,unsubscribe:()=>{p=!1,u&&clearTimeout(u),h&&h.unsubscribe&&h.unsubscribe(),d.clear()}}}class hn{constructor(){this.subscriptions=new Map}register(e,t){this.subscriptions.set(e,t)}unregister(e){const t=this.subscriptions.get(e);t&&(t.unsubscribe(),this.subscriptions.delete(e))}unsubscribeAll(){for(const[e,t]of this.subscriptions)t.unsubscribe();this.subscriptions.clear()}count(){return this.subscriptions.size}}const yn=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionRegistry:hn,createSubscription:pn},Symbol.toStringTag,{value:"Module"}));async function mn(e,t,n,s,r={}){const{maxLevel:a=3,operation:i="concatenate"}=r,o=e.client,f=e.config.appName;if(!ae(t))throw new Error("Upcast only supported for geographic (H3) holons, not noospheric holons");const c=se(t).slice(0,a);if(0===c.length)return!0;const l=c.map(async e=>async function(e,t,n,s,r,a,i){const o=It(n,0,r,a,t);o._meta.operation=i,o._meta.upcast=!0;const f=`${t}/${s}/${r}/${a}`;return ve(e,f,o)}(o,f,t,e,n,s,i));return await Promise.all(l),!0}const gn=Object.freeze(Object.defineProperty({__proto__:null,aggregate:function(e){const t={operation:"aggregate"};for(const n of e)Object.assign(t,n);return t},concatenate:function(e){return{operation:"concatenate",items:e.flat()}},summarize:function(e){return{operation:"summarize",count:e.length,summary:!0}},upcast:mn},Symbol.toStringTag,{value:"Module"})),bn="RFC3986",wn={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},vn=Array.isArray,_n=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Tn=1024;function xn(e,t){if(vn(e)){const n=[];for(let s=0;s<e.length;s+=1)n.push(t(e[s]));return n}return t(e)}const An=Object.prototype.hasOwnProperty,Sn={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},kn=Array.isArray,En=Array.prototype.push,Nn=function(e,t){En.apply(e,kn(t)?t:[t])},In=Date.prototype.toISOString,Cn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,n,s,r)=>{if(0===e.length)return e;let a=e;if("symbol"==typeof e?a=Symbol.prototype.toString.call(e):"string"!=typeof e&&(a=String(e)),"iso-8859-1"===n)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=Tn){const e=a.length>=Tn?a.slice(o,o+Tn):a,t=[];for(let n=0;n<e.length;++n){let s=e.charCodeAt(n);45===s||46===s||95===s||126===s||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||"RFC1738"===r&&(40===s||41===s)?t[t.length]=e.charAt(n):s<128?t[t.length]=_n[s]:s<2048?t[t.length]=_n[192|s>>6]+_n[128|63&s]:s<55296||s>=57344?t[t.length]=_n[224|s>>12]+_n[128|s>>6&63]+_n[128|63&s]:(n+=1,s=65536+((1023&s)<<10|1023&e.charCodeAt(n)),t[t.length]=_n[240|s>>18]+_n[128|s>>12&63]+_n[128|s>>6&63]+_n[128|63&s])}i+=t.join("")}return i},encodeValuesOnly:!1,format:bn,formatter:wn[bn],indices:!1,serializeDate:e=>In.call(e),skipNulls:!1,strictNullHandling:!1};const On={};function Rn(e,t,n,s,r,a,i,o,f,c,l,u,d,p,h,y,m,g){let b=e,w=g,v=0,_=!1;for(;void 0!==(w=w.get(On))&&!_;){const t=w.get(e);if(v+=1,void 0!==t){if(t===v)throw new RangeError("Cyclic object value");_=!0}void 0===w.get(On)&&(v=0)}if("function"==typeof c?b=c(t,b):b instanceof Date?b=d?.(b):"comma"===n&&kn(b)&&(b=xn(b,function(e){return e instanceof Date?d?.(e):e})),null===b){if(a)return f&&!y?f(t,Cn.encoder,m,"key",p):t;b=""}if("string"==typeof(T=b)||"number"==typeof T||"boolean"==typeof T||"symbol"==typeof T||"bigint"==typeof T||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(b)){if(f){const e=y?t:f(t,Cn.encoder,m,"key",p);return[h?.(e)+"="+h?.(f(b,Cn.encoder,m,"value",p))]}return[h?.(t)+"="+h?.(String(b))]}var T;const x=[];if(void 0===b)return x;let A;if("comma"===n&&kn(b))y&&f&&(b=xn(b,f)),A=[{value:b.length>0?b.join(",")||null:void 0}];else if(kn(c))A=c;else{const e=Object.keys(b);A=l?e.sort(l):e}const S=o?String(t).replace(/\./g,"%2E"):String(t),k=s&&kn(b)&&1===b.length?S+"[]":S;if(r&&kn(b)&&0===b.length)return k+"[]";for(let E=0;E<A.length;++E){const t=A[E],w="object"==typeof t&&void 0!==t.value?t.value:b[t];if(i&&null===w)continue;const _=u&&o?t.replace(/\./g,"%2E"):t,T=kn(b)?"function"==typeof n?n(k,_):k:k+(u?"."+_:"["+_+"]");g.set(e,v);const S=new WeakMap;S.set(On,g),Nn(x,Rn(w,T,n,s,r,a,i,o,"comma"===n&&y&&kn(b)?null:f,c,l,u,d,p,h,y,m,S))}return x}function $n(e,t={}){let n=e;const s=function(e=Cn){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||Cn.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=bn;if(void 0!==e.format){if(!An.call(wn,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const s=wn[n];let r,a=Cn.filter;if(("function"==typeof e.filter||kn(e.filter))&&(a=e.filter),r=e.arrayFormat&&e.arrayFormat in Sn?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":Cn.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=void 0===e.allowDots?1==!!e.encodeDotInKeys||Cn.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Cn.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:Cn.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Cn.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?Cn.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Cn.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:Cn.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:Cn.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Cn.encodeValuesOnly,filter:a,format:n,formatter:s,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Cn.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Cn.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Cn.strictNullHandling}}(t);let r,a;"function"==typeof s.filter?(a=s.filter,n=a("",n)):kn(s.filter)&&(a=s.filter,r=a);const i=[];if("object"!=typeof n||null===n)return"";const o=Sn[s.arrayFormat],f="comma"===o&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const c=new WeakMap;for(let d=0;d<r.length;++d){const e=r[d];s.skipNulls&&null===n[e]||Nn(i,Rn(n[e],e,o,f,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,c))}const l=i.join(s.delimiter);let u=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),l.length>0?u+l:""}const Pn="4.104.0";let Mn,Dn,Fn,Hn,Bn,jn,Un,Ln,qn,Jn=!1;class Gn{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}const zn=()=>{Mn||function(e,t={auto:!1}){if(Jn)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(Mn)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${Mn}'\``);Jn=t.auto,Mn=e.kind,Dn=e.fetch,Fn=e.FormData,Hn=e.File,Bn=e.ReadableStream,jn=e.getMultipartRequestOptions,Un=e.getDefaultAgent,Ln=e.fileFromPath,qn=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let n,s,r,a;try{n=fetch,s=Request,r=Response,a=Headers}catch(i){throw new Error(`this environment is missing the following Web Fetch API type: ${i.message}. ${t}`)}return{kind:"web",fetch:n,Request:s,Response:r,Headers:a,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new Gn(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0})};zn();class Wn extends Error{}class Kn extends Wn{constructor(e,t,n,s){super(`${Kn.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["x-request-id"],this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,n){const s=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new Zn({message:n,cause:Ws(t)});const r=t?.error;return 400===e?new Xn(e,r,n,s):401===e?new Qn(e,r,n,s):403===e?new es(e,r,n,s):404===e?new ts(e,r,n,s):409===e?new ns(e,r,n,s):422===e?new ss(e,r,n,s):429===e?new rs(e,r,n,s):e>=500?new as(e,r,n,s):new Kn(e,r,n,s)}}class Vn extends Kn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Zn extends Kn{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Yn extends Zn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Xn extends Kn{}class Qn extends Kn{}class es extends Kn{}class ts extends Kn{}class ns extends Kn{}class ss extends Kn{}class rs extends Kn{}class as extends Kn{}class is extends Wn{constructor(){super("Could not parse response content as the length limit was reached")}}class os extends Wn{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var fs,cs=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},ls=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class us{constructor(){fs.set(this,void 0),this.buffer=new Uint8Array,cs(this,fs,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const s=[];let r;for(;null!=(r=ds(this.buffer,ls(this,fs,"f")));){if(r.carriage&&null==ls(this,fs,"f")){cs(this,fs,r.index,"f");continue}if(null!=ls(this,fs,"f")&&(r.index!==ls(this,fs,"f")+1||r.carriage)){s.push(this.decodeText(this.buffer.slice(0,ls(this,fs,"f")-1))),this.buffer=this.buffer.slice(ls(this,fs,"f")),cs(this,fs,null,"f");continue}const e=null!==ls(this,fs,"f")?r.preceding-1:r.preceding,t=this.decodeText(this.buffer.slice(0,e));s.push(t),this.buffer=this.buffer.slice(r.index),cs(this,fs,null,"f")}return s}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new Wn(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new Wn(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Wn("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function ds(e,t){for(let n=t??0;n<e.length;n++){if(10===e[n])return{preceding:n,index:n+1,carriage:!1};if(13===e[n])return{preceding:n,index:n+1,carriage:!0}}return null}function ps(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}function hs(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}fs=new WeakMap,us.NEWLINE_CHARS=new Set(["\n","\r"]),us.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class ys{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;return new ys(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of async function*(e,t){if(!e.body)throw t.abort(),new Wn("Attempted to iterate over a response with no body");const n=new ms,s=new us,r=hs(e.body);for await(const a of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?(new TextEncoder).encode(n):n;let s,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(s=ps(t));)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}(r))for(const e of s.decode(a)){const t=n.decode(e);t&&(yield t)}for(const a of s.flush()){const e=n.decode(a);e&&(yield e)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null===n.event||n.event.startsWith("response.")||n.event.startsWith("transcript.")){let t;try{t=JSON.parse(n.data)}catch(r){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),r}if(t&&t.error)throw new Kn(void 0,t.error,void 0,Ps(e.headers));yield t}else{let e;try{e=JSON.parse(n.data)}catch(r){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),r}if("error"==n.event)throw new Kn(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}s=!0}catch(r){if(r instanceof Error&&"AbortError"===r.name)return;throw r}finally{s||t.abort()}},t)}static fromReadableStream(e,t){let n=!1;return new ys(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new us,n=hs(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(r){if(r instanceof Error&&"AbortError"===r.name)return;throw r}finally{s||t.abort()}},t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=s=>({next:()=>{if(0===s.length){const s=n.next();e.push(s),t.push(s)}return s.shift()}});return[new ys(()=>s(e),this.controller),new ys(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new Bn({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:r}=await t.next();if(r)return e.close();const a=n.encode(JSON.stringify(s)+"\n");e.enqueue(a)}catch(s){e.error(s)}},async cancel(){await(t.return?.())}})}}class ms{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=function(e,t){const n=e.indexOf(t);if(-1!==n)return[e.substring(0,n),t,e.substring(n+t.length)];return[e,"",""]}(e,":");return s.startsWith(" ")&&(s=s.substring(1)),"event"===t?this.event=s:"data"===t&&this.data.push(s),null}}const gs=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,bs=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&ws(e),ws=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function vs(e,t,n){if(e=await e,bs(e))return e;if(gs(e)){const s=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=ws(s)?[await s.arrayBuffer()]:[s];return new Hn(r,t,n)}const s=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(ws(e))t.push(await e.arrayBuffer());else{if(!Ts(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`);for await(const n of e)t.push(n)}return t}(e);if(t||(t=function(e){return _s(e.name)||_s(e.filename)||_s(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!n?.type){const e=s[0]?.type;"string"==typeof e&&(n={...n,type:e})}return new Hn(s,t,n)}const _s=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,Ts=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],xs=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],As=async e=>{const t=await Ss(e.body);return jn(t,e)},Ss=async e=>{const t=new Fn;return await Promise.all(Object.entries(e||{}).map(([e,n])=>ks(t,e,n))),t},ks=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if((e=>bs(e)||gs(e)||qn(e))(n)){const s=await vs(n);e.append(t,s)}else if(Array.isArray(n))await Promise.all(n.map(n=>ks(e,t+"[]",n)));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map(([n,s])=>ks(e,`${t}[${n}]`,s)))}}};var Es;async function Ns(e){const{response:t}=e;if(e.options.stream)return Qs("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):ys.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const n=t.headers.get("content-type"),s=n?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){const e=await t.json();return Qs("response",t.status,t.url,t.headers,e),Is(e,t)}const r=await t.text();return Qs("response",t.status,t.url,t.headers,r),r}function Is(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}zn();class Cs extends Promise{constructor(e,t=Ns){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new Cs(this.responsePromise,async t=>Is(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class Os{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:r}){this.baseURL=e,this.maxRetries=zs("maxRetries",t),this.timeout=zs("timeout",n),this.httpAgent=s,this.fetch=r??Dn}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Us(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${er()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async n=>{const s=n&&ws(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:s}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:s,path:r,query:a,headers:i={}}=n,o=ArrayBuffer.isView(n.body)||n.__binaryRequest&&"string"==typeof n.body?n.body:xs(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,f=this.calculateContentLength(o),c=this.buildURL(r,a);"timeout"in n&&zs("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const l=n.httpAgent??this.httpAgent??Un(c),u=n.timeout+1e3;"number"==typeof l?.options?.timeout&&u>(l.options.timeout??0)&&(l.options.timeout=u),this.idempotencyHeader&&"get"!==s&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:s,...o&&{body:o},headers:this.buildHeaders({options:n,headers:i,contentLength:f,retryCount:t}),...l&&{agent:l},signal:n.signal??null},url:c,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const r={};n&&(r["content-length"]=n);const a=this.defaultHeaders(e);return Ys(r,a),Ys(r,t),xs(e.body)&&"node"!==Mn&&delete r["content-type"],void 0===tr(a,"x-stainless-retry-count")&&void 0===tr(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(s)),void 0===tr(a,"x-stainless-timeout")&&void 0===tr(t,"x-stainless-timeout")&&e.timeout&&(r["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(e=>[...e])):{...e}:{}}makeStatusError(e,t,n,s){return Kn.generate(e,t,n,s)}request(e,t=null){return new Cs(this.makeRequest(e,t))}async makeRequest(e,t){const n=await e,s=n.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(n);const{req:r,url:a,timeout:i}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(r,{url:a,options:n}),Qs("request",a,n,r.headers),n.signal?.aborted)throw new Vn;const o=new AbortController,f=await this.fetchWithTimeout(a,r,i,o).catch(Ws);if(f instanceof Error){if(n.signal?.aborted)throw new Vn;if(t)return this.retryRequest(n,t);if("AbortError"===f.name)throw new Yn;throw new Zn({cause:f})}const c=Ps(f.headers);if(!f.ok){if(t&&this.shouldRetry(f)){return Qs(`response (error; ${`retrying, ${t} attempts remaining`})`,f.status,a,c),this.retryRequest(n,t,c)}const e=await f.text().catch(e=>Ws(e).message),s=Ls(e),r=s?void 0:e;Qs(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,f.status,a,c,r);throw this.makeStatusError(f.status,s,r,c)}return{response:f,options:n,controller:o}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new $s(this,n,e)}buildURL(e,t){const n=Js(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Vs(s)||(t={...s,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new Wn(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:r,...a}=t||{};r&&r.addEventListener("abort",()=>s.abort());const i=setTimeout(()=>s.abort(),n),o={signal:s.signal,...a};return o.method&&(o.method=o.method.toUpperCase()),this.fetch.call(void 0,e,o).finally(()=>{clearTimeout(i)})}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,n){let s;const r=n?.["retry-after-ms"];if(r){const e=parseFloat(r);Number.isNaN(e)||(s=e)}const a=n?.["retry-after"];if(a&&!s){const e=parseFloat(a);s=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const n=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Gs(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Pn}`}}class Rs{constructor(e,t,n,s){Es.set(this,void 0),function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===s?r.call(e,n):r?r.value=n:t.set(e,n)}(this,Es,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new Wn("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,s]of n)e.url.searchParams.set(t,s);t.query=void 0,t.path=e.url.toString()}return await function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)}(this,Es,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Es=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class $s extends Cs{constructor(e,t,n){super(t,async t=>new n(e,t.response,await Ns(t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Ps=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),Ms={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},Ds=e=>"object"==typeof e&&null!==e&&!Vs(e)&&Object.keys(e).every(e=>Zs(Ms,e)),Fs=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pn,"X-Stainless-OS":Bs(Deno.build.os),"X-Stainless-Arch":Hs(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pn,"X-Stainless-OS":Bs(process.platform),"X-Stainless-Arch":Hs(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const e=n.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Hs=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Bs=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let js;const Us=()=>js??(js=Fs()),Ls=e=>{try{return JSON.parse(e)}catch(t){return}},qs=/^[a-z][a-z0-9+.-]*:/i,Js=e=>qs.test(e),Gs=e=>new Promise(t=>setTimeout(t,e)),zs=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Wn(`${e} must be an integer`);if(t<0)throw new Wn(`${e} must be a positive integer`);return t},Ws=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},Ks=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Vs(e){if(!e)return!0;for(const t in e)return!1;return!0}function Zs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ys(e,t){for(const n in t){if(!Zs(t,n))continue;const s=n.toLowerCase();if(!s)continue;const r=t[n];null===r?delete e[s]:void 0!==r&&(e[s]=r)}}const Xs=new Set(["authorization","api-key"]);function Qs(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const n=t.map(e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const n in e.headers)Xs.has(n.toLowerCase())&&(t.headers[n]="REDACTED");return t}let t=null;for(const n in e)Xs.has(n.toLowerCase())&&(t??(t={...e}),t[n]="REDACTED");return t??e});console.log(`OpenAI:DEBUG:${e}`,...n)}}const er=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),tr=(e,t)=>{const n=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const s=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,(e,t,n)=>t+n.toUpperCase());for(const r of[t,n,t.toUpperCase(),s]){const t=e.get(r);if(t)return t}}for(const[s,r]of Object.entries(e))if(s.toLowerCase()===n)return Array.isArray(r)?(r.length<=1||console.warn(`Received ${r.length} entries for the ${t} header, using the first entry.`),r[0]):r};function nr(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class sr extends Rs{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class rr extends Rs{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class ar{constructor(e){this._client=e}}let ir=class extends ar{list(e,t={},n){return Ds(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,cr,{query:t,...n})}},or=class extends ar{constructor(){super(...arguments),this.messages=new ir(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return Ds(e)?this.list({},e):this._client.getAPIList("/chat/completions",fr,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class fr extends rr{}class cr extends rr{}or.ChatCompletionsPage=fr,or.Messages=ir;let lr=class extends ar{constructor(){super(...arguments),this.completions=new or(this._client)}};lr.Completions=or,lr.ChatCompletionsPage=fr;class ur extends ar{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class dr extends ar{create(e,t){return this._client.post("/audio/transcriptions",As({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class pr extends ar{create(e,t){return this._client.post("/audio/translations",As({body:e,...t,__metadata:{model:e.model}}))}}class hr extends ar{constructor(){super(...arguments),this.transcriptions=new dr(this._client),this.translations=new pr(this._client),this.speech=new ur(this._client)}}hr.Transcriptions=dr,hr.Translations=pr,hr.Speech=ur;class yr extends ar{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return Ds(e)?this.list({},e):this._client.getAPIList("/batches",mr,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class mr extends rr{}yr.BatchesPage=mr;var gr,br,wr,vr,_r,Tr,xr,Ar,Sr,kr,Er,Nr,Ir,Cr=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},Or=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class Rr{constructor(){gr.add(this),this.controller=new AbortController,br.set(this,void 0),wr.set(this,()=>{}),vr.set(this,()=>{}),_r.set(this,void 0),Tr.set(this,()=>{}),xr.set(this,()=>{}),Ar.set(this,{}),Sr.set(this,!1),kr.set(this,!1),Er.set(this,!1),Nr.set(this,!1),Cr(this,br,new Promise((e,t)=>{Cr(this,wr,e,"f"),Cr(this,vr,t,"f")}),"f"),Cr(this,_r,new Promise((e,t)=>{Cr(this,Tr,e,"f"),Cr(this,xr,t,"f")}),"f"),Or(this,br,"f").catch(()=>{}),Or(this,_r,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Or(this,gr,"m",Ir).bind(this))},0)}_connected(){this.ended||(Or(this,wr,"f").call(this),this._emit("connect"))}get ended(){return Or(this,Sr,"f")}get errored(){return Or(this,kr,"f")}get aborted(){return Or(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(Or(this,Ar,"f")[e]||(Or(this,Ar,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=Or(this,Ar,"f")[e];if(!n)return this;const s=n.findIndex(e=>e.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(Or(this,Ar,"f")[e]||(Or(this,Ar,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Cr(this,Nr,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)})}async done(){Cr(this,Nr,!0,"f"),await Or(this,_r,"f")}_emit(e,...t){if(Or(this,Sr,"f"))return;"end"===e&&(Cr(this,Sr,!0,"f"),Or(this,Tr,"f").call(this));const n=Or(this,Ar,"f")[e];if(n&&(Or(this,Ar,"f")[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return Or(this,Nr,"f")||n?.length||Promise.reject(e),Or(this,vr,"f").call(this,e),Or(this,xr,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Or(this,Nr,"f")||n?.length||Promise.reject(e),Or(this,vr,"f").call(this,e),Or(this,xr,"f").call(this,e),this._emit("end")}}_emitFinal(){}}br=new WeakMap,wr=new WeakMap,vr=new WeakMap,_r=new WeakMap,Tr=new WeakMap,xr=new WeakMap,Ar=new WeakMap,Sr=new WeakMap,kr=new WeakMap,Er=new WeakMap,Nr=new WeakMap,gr=new WeakSet,Ir=function(e){if(Cr(this,kr,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new Vn),e instanceof Vn)return Cr(this,Er,!0,"f"),this._emit("abort",e);if(e instanceof Wn)return this._emit("error",e);if(e instanceof Error){const t=new Wn(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Wn(String(e)))};var $r,Pr,Mr,Dr,Fr,Hr,Br,jr,Ur,Lr,qr,Jr,Gr,zr,Wr,Kr,Vr,Zr,Yr,Xr,Qr,ea,ta=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},na=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n};class sa extends Rr{constructor(){super(...arguments),$r.add(this),Pr.set(this,[]),Mr.set(this,{}),Dr.set(this,{}),Fr.set(this,void 0),Hr.set(this,void 0),Br.set(this,void 0),jr.set(this,void 0),Ur.set(this,void 0),Lr.set(this,void 0),qr.set(this,void 0),Jr.set(this,void 0),Gr.set(this,void 0)}[(Pr=new WeakMap,Mr=new WeakMap,Dr=new WeakMap,Fr=new WeakMap,Hr=new WeakMap,Br=new WeakMap,jr=new WeakMap,Ur=new WeakMap,Lr=new WeakMap,qr=new WeakMap,Jr=new WeakMap,Gr=new WeakMap,$r=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new sa;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=ys.fromReadableStream(e,this.controller);for await(const r of s)ta(this,$r,"m",zr).call(this,r);if(s.controller.signal?.aborted)throw new Vn;return this._addRun(ta(this,$r,"m",Wr).call(this))}toReadableStream(){return new ys(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,r){const a=new sa;return a._run(()=>a._runToolAssistantStream(e,t,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,s,r){const a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},o=await e.submitToolOutputs(t,n,i,{...r,signal:this.controller.signal});this._connected();for await(const f of o)ta(this,$r,"m",zr).call(this,f);if(o.controller.signal?.aborted)throw new Vn;return this._addRun(ta(this,$r,"m",Wr).call(this))}static createThreadAssistantStream(e,t,n){const s=new sa;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const r=new sa;return r._run(()=>r._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}currentEvent(){return ta(this,qr,"f")}currentRun(){return ta(this,Jr,"f")}currentMessageSnapshot(){return ta(this,Fr,"f")}currentRunStepSnapshot(){return ta(this,Gr,"f")}async finalRunSteps(){return await this.done(),Object.values(ta(this,Mr,"f"))}async finalMessages(){return await this.done(),Object.values(ta(this,Dr,"f"))}async finalRun(){if(await this.done(),!ta(this,Hr,"f"))throw Error("Final run was not received.");return ta(this,Hr,"f")}async _createThreadAssistantStream(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const r={...t,stream:!0},a=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(const i of a)ta(this,$r,"m",zr).call(this,i);if(a.controller.signal?.aborted)throw new Vn;return this._addRun(ta(this,$r,"m",Wr).call(this))}async _createAssistantStream(e,t,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.create(t,a,{...s,signal:this.controller.signal});this._connected();for await(const o of i)ta(this,$r,"m",zr).call(this,o);if(i.controller.signal?.aborted)throw new Vn;return this._addRun(ta(this,$r,"m",Wr).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof s)t+=s;else if("number"==typeof t&&"number"==typeof s)t+=s;else{if(!nr(t)||!nr(s)){if(Array.isArray(t)&&Array.isArray(s)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...s);continue}for(const e of s){if(!nr(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const n=e.index;if(null==n)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof n)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);const s=t[n];null==s?t.push(e):t[n]=this.accumulateDelta(s,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${t}`)}t=this.accumulateDelta(t,s)}e[n]=t}else e[n]=s;else e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,r){return await this._createToolAssistantStream(n,e,t,s,r)}}zr=function(e){if(!this.ended)switch(na(this,qr,e,"f"),ta(this,$r,"m",Zr).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":ta(this,$r,"m",ea).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":ta(this,$r,"m",Vr).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":ta(this,$r,"m",Kr).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Wr=function(){if(this.ended)throw new Wn("stream has ended, this shouldn't happen");if(!ta(this,Hr,"f"))throw Error("Final run has not been received");return ta(this,Hr,"f")},Kr=function(e){const[t,n]=ta(this,$r,"m",Xr).call(this,e,ta(this,Fr,"f"));na(this,Fr,t,"f"),ta(this,Dr,"f")[t.id]=t;for(const s of n){const e=t.content[s.index];"text"==e?.type&&this._emit("textCreated",e.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const n of e.data.delta.content){if("text"==n.type&&n.text){let e=n.text,s=t.content[n.index];if(!s||"text"!=s.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,s.text)}if(n.index!=ta(this,Br,"f")){if(ta(this,jr,"f"))switch(ta(this,jr,"f").type){case"text":this._emit("textDone",ta(this,jr,"f").text,ta(this,Fr,"f"));break;case"image_file":this._emit("imageFileDone",ta(this,jr,"f").image_file,ta(this,Fr,"f"))}na(this,Br,n.index,"f")}na(this,jr,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==ta(this,Br,"f")){const t=e.data.content[ta(this,Br,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,ta(this,Fr,"f"));break;case"text":this._emit("textDone",t.text,ta(this,Fr,"f"))}}ta(this,Fr,"f")&&this._emit("messageDone",e.data),na(this,Fr,void 0,"f")}},Vr=function(e){const t=ta(this,$r,"m",Yr).call(this,e);switch(na(this,Gr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of n.step_details.tool_calls)e.index==ta(this,Ur,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(ta(this,Lr,"f")&&this._emit("toolCallDone",ta(this,Lr,"f")),na(this,Ur,e.index,"f"),na(this,Lr,t.step_details.tool_calls[e.index],"f"),ta(this,Lr,"f")&&this._emit("toolCallCreated",ta(this,Lr,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":na(this,Gr,void 0,"f");"tool_calls"==e.data.step_details.type&&ta(this,Lr,"f")&&(this._emit("toolCallDone",ta(this,Lr,"f")),na(this,Lr,void 0,"f")),this._emit("runStepDone",e.data,t)}},Zr=function(e){ta(this,Pr,"f").push(e),this._emit("event",e)},Yr=function(e){switch(e.event){case"thread.run.step.created":return ta(this,Mr,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=ta(this,Mr,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=sa.accumulateDelta(t,n.delta);ta(this,Mr,"f")[e.data.id]=s}return ta(this,Mr,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":ta(this,Mr,"f")[e.data.id]=e.data}if(ta(this,Mr,"f")[e.data.id])return ta(this,Mr,"f")[e.data.id];throw new Error("No snapshot available")},Xr=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const e of s.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=ta(this,$r,"m",Qr).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Qr=function(e,t){return sa.accumulateDelta(t,e)},ea=function(e){switch(na(this,Jr,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":na(this,Hr,e.data,"f"),ta(this,Lr,"f")&&(this._emit("toolCallDone",ta(this,Lr,"f")),na(this,Lr,void 0,"f"))}};class ra extends ar{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return Ds(e)?this.list({},e):this._client.getAPIList("/assistants",aa,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class aa extends rr{}function ia(e){return"function"==typeof e.parse}ra.AssistantsPage=aa;const oa=e=>"assistant"===e?.role,fa=e=>"function"===e?.role,ca=e=>"tool"===e?.role;function la(e){return"auto-parseable-response-format"===e?.$brand}function ua(e){return"auto-parseable-tool"===e?.$brand}function da(e,t){const n=e.choices.map(e=>{if("length"===e.finish_reason)throw new is;if("content_filter"===e.finish_reason)throw new os;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>function(e,t){const n=e.tools?.find(e=>e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:ua(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?pa(t,e.message.content):null}}});return{...e,choices:n}}function pa(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function ha(e,t){if(!e)return!1;const n=e.tools?.find(e=>e.function?.name===t.function.name);return ua(n)||n?.function.strict||!1}function ya(e){return!!la(e.response_format)||(e.tools?.some(e=>ua(e)||"function"===e.type&&!0===e.function.strict)??!1)}var ma,ga,ba,wa,va,_a,Ta,xa,Aa=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};const Sa=10;class ka extends Rr{constructor(){super(...arguments),ma.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(fa(e)||ca(e))&&e.content)this._emit("functionCallResult",e.content);else if(oa(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(oa(e)&&e.tool_calls)for(const n of e.tool_calls)"function"===n.type&&this._emit("functionCall",n.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Wn("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Aa(this,ma,"m",ga).call(this)}async finalMessage(){return await this.done(),Aa(this,ma,"m",ba).call(this)}async finalFunctionCall(){return await this.done(),Aa(this,ma,"m",wa).call(this)}async finalFunctionCallResult(){return await this.done(),Aa(this,ma,"m",va).call(this)}async totalUsage(){return await this.done(),Aa(this,ma,"m",_a).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Aa(this,ma,"m",ba).call(this);t&&this._emit("finalMessage",t);const n=Aa(this,ma,"m",ga).call(this);n&&this._emit("finalContent",n);const s=Aa(this,ma,"m",wa).call(this);s&&this._emit("finalFunctionCall",s);const r=Aa(this,ma,"m",va).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",Aa(this,ma,"m",_a).call(this))}async _createChatCompletion(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Aa(this,ma,"m",Ta).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(da(r,t))}async _runChatCompletion(e,t,n){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){const s="function",{function_call:r="auto",stream:a,...i}=t,o="string"!=typeof r&&r?.name,{maxChatCompletions:f=Sa}=n||{},c={};for(const d of t.functions)c[d.name||d.function.name]=d;const l=t.functions.map(e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description}));for(const d of t.messages)this._addMessage(d,!1);for(let d=0;d<f;++d){const t=await this._createChatCompletion(e,{...i,function_call:r,functions:l,messages:[...this.messages]},n),a=t.choices[0]?.message;if(!a)throw new Wn("missing message in ChatCompletion response");if(!a.function_call)return;const{name:f,arguments:d}=a.function_call,p=c[f];if(!p){const e=`Invalid function_call: ${JSON.stringify(f)}. Available options are: ${l.map(e=>JSON.stringify(e.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:f,content:e});continue}if(o&&o!==f){const e=`Invalid function_call: ${JSON.stringify(f)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:s,name:f,content:e});continue}let h;try{h=ia(p)?await p.parse(d):d}catch(u){this._addMessage({role:s,name:f,content:u instanceof Error?u.message:String(u)});continue}const y=await p.function(h,this),m=Aa(this,ma,"m",xa).call(this,y);if(this._addMessage({role:s,name:f,content:m}),o)return}}async _runTools(e,t,n){const s="tool",{tool_choice:r="auto",stream:a,...i}=t,o="string"!=typeof r&&r?.function?.name,{maxChatCompletions:f=Sa}=n||{},c=t.tools.map(e=>{if(ua(e)){if(!e.$callback)throw new Wn("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),l={};for(const p of c)"function"===p.type&&(l[p.function.name||p.function.function.name]=p.function);const u="tools"in t?c.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const p of t.messages)this._addMessage(p,!1);for(let p=0;p<f;++p){const t=await this._createChatCompletion(e,{...i,tool_choice:r,tools:u,messages:[...this.messages]},n),a=t.choices[0]?.message;if(!a)throw new Wn("missing message in ChatCompletion response");if(!a.tool_calls?.length)return;for(const e of a.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:n,arguments:r}=e.function,a=l[n];if(!a){const e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(l).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}if(o&&o!==n){const e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}let i;try{i=ia(a)?await a.parse(r):r}catch(d){const e=d instanceof Error?d.message:String(d);this._addMessage({role:s,tool_call_id:t,content:e});continue}const f=await a.function(i,this),c=Aa(this,ma,"m",xa).call(this,f);if(this._addMessage({role:s,tool_call_id:t,content:c}),o)return}}}}ma=new WeakSet,ga=function(){return Aa(this,ma,"m",ba).call(this).content??null},ba=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(oa(t)){const{function_call:e,...n}=t,s={...n,content:t.content??null,refusal:t.refusal??null};return e&&(s.function_call=e),s}}throw new Wn("stream ended without producing a ChatCompletionMessage with role=assistant")},wa=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(oa(t)&&t?.function_call)return t.function_call;if(oa(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},va=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(fa(t)&&null!=t.content)return t.content;if(ca(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},_a=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ta=function(e){if(null!=e.n&&e.n>1)throw new Wn("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},xa=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Ea extends ka{static runFunctions(e,t,n){const s=new Ea,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,r)),s}static runTools(e,t,n){const s=new Ea,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,r)),s}_addMessage(e,t=!0){super._addMessage(e,t),oa(e)&&e.content&&this._emit("content",e.content)}}const Na=1,Ia=2,Ca=4,Oa=8,Ra=16,$a=32,Pa=64,Ma=128,Da=256,Fa=511;class Ha extends Error{}class Ba extends Error{}const ja=(e,t)=>{const n=e.length;let s=0;const r=e=>{throw new Ha(`${e} at position ${s}`)},a=e=>{throw new Ba(`${e} at position ${s}`)},i=()=>(u(),s>=n&&r("Unexpected end of input"),'"'===e[s]?o():"{"===e[s]?f():"["===e[s]?c():"null"===e.substring(s,s+4)||Ra&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||$a&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||$a&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||Ma&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||Da&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||Pa&t&&n-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):l()),o=()=>{const i=s;let o=!1;for(s++;s<n&&('"'!==e[s]||o&&"\\"===e[s-1]);)o="\\"===e[s]&&!o,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(i,++s-Number(o)))}catch(f){a(String(f))}else if(Na&t)try{return JSON.parse(e.substring(i,s-Number(o))+'"')}catch(f){return JSON.parse(e.substring(i,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},f=()=>{s++,u();const a={};try{for(;"}"!==e[s];){if(u(),s>=n&&Oa&t)return a;const r=o();u(),s++;try{const e=i();Object.defineProperty(a,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(f){if(Oa&t)return a;throw f}u(),","===e[s]&&s++}}catch(f){if(Oa&t)return a;r("Expected '}' at end of object")}return s++,a},c=()=>{s++;const n=[];try{for(;"]"!==e[s];)n.push(i()),u(),","===e[s]&&s++}catch(a){if(Ca&t)return n;r("Expected ']' at end of array")}return s++,n},l=()=>{if(0===s){"-"===e&&Ia&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(o){if(Ia&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(f){}a(String(o))}}const i=s;for("-"===e[s]&&s++;e[s]&&!",]}".includes(e[s]);)s++;s!=n||Ia&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,s))}catch(o){"-"===e.substring(i,s)&&Ia&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(f){a(String(f))}}},u=()=>{for(;s<n&&" \n\r\t".includes(e[s]);)s++};return i()},Ua=e=>function(e,t=Fa){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return ja(e.trim(),t)}(e,Fa^Ia);var La,qa,Ja,Ga,za,Wa,Ka,Va,Za,Ya,Xa,Qa,ei=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},ti=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class ni extends ka{constructor(e){super(),La.add(this),qa.set(this,void 0),Ja.set(this,void 0),Ga.set(this,void 0),ei(this,qa,e,"f"),ei(this,Ja,[],"f")}get currentChatCompletionSnapshot(){return ti(this,Ga,"f")}static fromReadableStream(e){const t=new ni(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new ni(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){super._createChatCompletion;const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),ti(this,La,"m",za).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const a of r)ti(this,La,"m",Ka).call(this,a);if(r.controller.signal?.aborted)throw new Vn;return this._addChatCompletion(ti(this,La,"m",Ya).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),ti(this,La,"m",za).call(this),this._connected();const s=ys.fromReadableStream(e,this.controller);let r;for await(const a of s)r&&r!==a.id&&this._addChatCompletion(ti(this,La,"m",Ya).call(this)),ti(this,La,"m",Ka).call(this,a),r=a.id;if(s.controller.signal?.aborted)throw new Vn;return this._addChatCompletion(ti(this,La,"m",Ya).call(this))}[(qa=new WeakMap,Ja=new WeakMap,Ga=new WeakMap,La=new WeakSet,za=function(){this.ended||ei(this,Ga,void 0,"f")},Wa=function(e){let t=ti(this,Ja,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},ti(this,Ja,"f")[e.index]=t,t)},Ka=function(e){if(this.ended)return;const t=ti(this,La,"m",Qa).call(this,e);this._emit("chunk",e,t);for(const n of e.choices){const e=t.choices[n.index];null!=n.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",n.delta.content,e.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=n.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:e.message.refusal}),null!=n.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=n.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const s=ti(this,La,"m",Wa).call(this,e);e.finish_reason&&(ti(this,La,"m",Za).call(this,e),null!=s.current_tool_call_index&&ti(this,La,"m",Va).call(this,e,s.current_tool_call_index));for(const t of n.delta.tool_calls??[])s.current_tool_call_index!==t.index&&(ti(this,La,"m",Za).call(this,e),null!=s.current_tool_call_index&&ti(this,La,"m",Va).call(this,e,s.current_tool_call_index)),s.current_tool_call_index=t.index;for(const t of n.delta.tool_calls??[]){const n=e.message.tool_calls?.[t.index];n?.type&&("function"===n?.type?this._emit("tool_calls.function.arguments.delta",{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):ri(n?.type))}}},Va=function(e,t){if(ti(this,La,"m",Wa).call(this,e).done_tool_calls.has(t))return;const n=e.message.tool_calls?.[t];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if("function"===n.type){const e=ti(this,qa,"f")?.tools?.find(e=>"function"===e.type&&e.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:ua(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},Za=function(e){const t=ti(this,La,"m",Wa).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=ti(this,La,"m",Xa).call(this);this._emit("content.done",{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},Ya=function(){if(this.ended)throw new Wn("stream has ended, this shouldn't happen");const e=ti(this,Ga,"f");if(!e)throw new Wn("request ended without sending any chunks");return ei(this,Ga,void 0,"f"),ei(this,Ja,[],"f"),function(e,t){const{id:n,choices:s,created:r,model:a,system_fingerprint:i,...o}=e,f={...o,id:n,choices:s.map(({message:t,finish_reason:n,index:s,logprobs:r,...a})=>{if(!n)throw new Wn(`missing finish_reason for choice ${s}`);const{content:i=null,function_call:o,tool_calls:f,...c}=t,l=t.role;if(!l)throw new Wn(`missing role for choice ${s}`);if(o){const{arguments:e,name:f}=o;if(null==e)throw new Wn(`missing function_call.arguments for choice ${s}`);if(!f)throw new Wn(`missing function_call.name for choice ${s}`);return{...a,message:{content:i,function_call:{arguments:e,name:f},role:l,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}return f?{...a,index:s,finish_reason:n,logprobs:r,message:{...c,role:l,content:i,refusal:t.refusal??null,tool_calls:f.map((t,n)=>{const{function:r,type:a,id:i,...o}=t,{arguments:f,name:c,...l}=r||{};if(null==i)throw new Wn(`missing choices[${s}].tool_calls[${n}].id\n${si(e)}`);if(null==a)throw new Wn(`missing choices[${s}].tool_calls[${n}].type\n${si(e)}`);if(null==c)throw new Wn(`missing choices[${s}].tool_calls[${n}].function.name\n${si(e)}`);if(null==f)throw new Wn(`missing choices[${s}].tool_calls[${n}].function.arguments\n${si(e)}`);return{...o,id:i,type:a,function:{...l,name:c,arguments:f}}})}}:{...a,message:{...c,content:i,role:l,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&ya(t)?da(e,t):{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(f,t)}(e,ti(this,qa,"f"))},Xa=function(){const e=ti(this,qa,"f")?.response_format;return la(e)?e:null},Qa=function(e){var t,n,s,r;let a=ti(this,Ga,"f");const{choices:i,...o}=e;a?Object.assign(a,o):a=ei(this,Ga,{...o,choices:[]},"f");for(const{delta:f,finish_reason:c,index:l,logprobs:u=null,...d}of e.choices){let e=a.choices[l];if(e||(e=a.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d}),u)if(e.logprobs){const{content:s,refusal:r,...a}=u;Object.assign(e.logprobs,a),s&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...s)),r&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},u);if(c&&(e.finish_reason=c,ti(this,qa,"f")&&ya(ti(this,qa,"f")))){if("length"===c)throw new is;if("content_filter"===c)throw new os}if(Object.assign(e,d),!f)continue;const{content:i,refusal:o,function_call:p,role:h,tool_calls:y,...m}=f;if(Object.assign(e.message,m),o&&(e.message.refusal=(e.message.refusal||"")+o),h&&(e.message.role=h),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((s=e.message.function_call).arguments??(s.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),i&&(e.message.content=(e.message.content||"")+i,!e.message.refusal&&ti(this,La,"m",Xa).call(this)&&(e.message.parsed=Ua(e.message.content))),y){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:s,function:a,...i}of y){const o=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(o,i),n&&(o.id=n),s&&(o.type=s),a&&(o.function??(o.function={name:a.name??"",arguments:""})),a?.name&&(o.function.name=a.name),a?.arguments&&(o.function.arguments+=a.arguments,ha(ti(this,qa,"f"),o)&&(o.function.parsed_arguments=Ua(o.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ys(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function si(e){return JSON.stringify(e)}function ri(e){}class ai extends ni{static fromReadableStream(e){const t=new ai(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new ai(null),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,r)),s}static runTools(e,t,n){const s=new ai(t),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,r)),s}}let ii=class extends ar{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new Wn(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new Wn(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(t=>da(t,e))}runFunctions(e,t){return e.stream?ai.runFunctions(this._client,e,t):Ea.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?ai.runTools(this._client,e,t):Ea.runTools(this._client,e,t)}stream(e,t){return ni.createChatCompletion(this._client,e,t)}};class oi extends ar{constructor(){super(...arguments),this.completions=new ii(this._client)}}(oi||(oi={})).Completions=ii;class fi extends ar{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class ci extends ar{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class li extends ar{constructor(){super(...arguments),this.sessions=new fi(this._client),this.transcriptionSessions=new ci(this._client)}}li.Sessions=fi,li.TranscriptionSessions=ci;class ui extends ar{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Ds(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,di,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class di extends rr{}ui.MessagesPage=di;class pi extends ar{retrieve(e,t,n,s={},r){return Ds(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t,n={},s){return Ds(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,hi,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class hi extends rr{}pi.RunStepsPage=hi;let yi=class extends ar{constructor(){super(...arguments),this.steps=new pi(this._client)}create(e,t,n){const{include:s,...r}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Ds(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,mi,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return sa.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Gs(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,n){return sa.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const r=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,r.id,s)}submitToolOutputsStream(e,t,n,s){return sa.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class mi extends rr{}yi.RunsPage=mi,yi.Steps=pi,yi.RunStepsPage=hi;class gi extends ar{constructor(){super(...arguments),this.runs=new yi(this._client),this.messages=new ui(this._client)}create(e={},t){return Ds(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return sa.createThreadAssistantStream(e,this._client.beta.threads,t)}}gi.Runs=yi,gi.RunsPage=mi,gi.Messages=ui,gi.MessagesPage=di;class bi extends ar{constructor(){super(...arguments),this.realtime=new li(this._client),this.chat=new oi(this._client),this.assistants=new ra(this._client),this.threads=new gi(this._client)}}bi.Realtime=li,bi.Assistants=ra,bi.AssistantsPage=aa,bi.Threads=gi;class wi extends ar{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class vi extends ar{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n?.headers},__binaryResponse:!0})}}let _i=class extends ar{constructor(){super(...arguments),this.content=new vi(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,As({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return Ds(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Ti,{query:t,...n})}del(e,t,n){return this._client.delete(`/containers/${e}/files/${t}`,{...n,headers:{Accept:"*/*",...n?.headers}})}};class Ti extends rr{}_i.FileListResponsesPage=Ti,_i.Content=vi;class xi extends ar{constructor(){super(...arguments),this.files=new _i(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return Ds(e)?this.list({},e):this._client.getAPIList("/containers",Ai,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class Ai extends rr{}xi.ContainerListResponsesPage=Ai,xi.Files=_i,xi.FileListResponsesPage=Ti;let Si=class extends ar{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Qs("Request","User defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?r:(Qs("response","Decoding base64 embeddings to float32 array"),r._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),n=t.length,s=new Uint8Array(n);for(let e=0;e<n;e++)s[e]=t.charCodeAt(e);return Array.from(new Float32Array(s.buffer))}})(t)}),e)))}};class ki extends ar{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return Ds(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Ei,{query:n,...s})}}class Ei extends rr{}ki.OutputItemListResponsesPage=Ei;class Ni extends ar{constructor(){super(...arguments),this.outputItems=new ki(this._client)}create(e,t,n){return this._client.post(`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){return this._client.get(`/evals/${e}/runs/${t}`,n)}list(e,t={},n){return Ds(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Ii,{query:t,...n})}del(e,t,n){return this._client.delete(`/evals/${e}/runs/${t}`,n)}cancel(e,t,n){return this._client.post(`/evals/${e}/runs/${t}`,n)}}class Ii extends rr{}Ni.RunListResponsesPage=Ii,Ni.OutputItems=ki,Ni.OutputItemListResponsesPage=Ei;class Ci extends ar{constructor(){super(...arguments),this.runs=new Ni(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,n){return this._client.post(`/evals/${e}`,{body:t,...n})}list(e={},t){return Ds(e)?this.list({},e):this._client.getAPIList("/evals",Oi,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class Oi extends rr{}Ci.EvalListResponsesPage=Oi,Ci.Runs=Ni,Ci.RunListResponsesPage=Ii;let Ri=class extends ar{create(e,t){return this._client.post("/files",As({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return Ds(e)?this.list({},e):this._client.getAPIList("/files",$i,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){const s=new Set(["processed","error","deleted"]),r=Date.now();let a=await this.retrieve(e);for(;!a.status||!s.has(a.status);)if(await Gs(t),a=await this.retrieve(e),Date.now()-r>n)throw new Yn({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};class $i extends rr{}Ri.FileObjectsPage=$i;class Pi extends ar{}let Mi=class extends ar{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Di extends ar{constructor(){super(...arguments),this.graders=new Mi(this._client)}}Di.Graders=Mi;class Fi extends ar{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Hi,{body:t,method:"post",...n})}retrieve(e,t={},n){return Ds(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}del(e,t,n){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,n)}}class Hi extends sr{}Fi.PermissionCreateResponsesPage=Hi;let Bi=class extends ar{constructor(){super(...arguments),this.permissions=new Fi(this._client)}};Bi.Permissions=Fi,Bi.PermissionCreateResponsesPage=Hi;class ji extends ar{list(e,t={},n){return Ds(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Ui,{query:t,...n})}}class Ui extends rr{}ji.FineTuningJobCheckpointsPage=Ui;class Li extends ar{constructor(){super(...arguments),this.checkpoints=new ji(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return Ds(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",qi,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return Ds(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Ji,{query:t,...n})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}}class qi extends rr{}class Ji extends rr{}Li.FineTuningJobsPage=qi,Li.FineTuningJobEventsPage=Ji,Li.Checkpoints=ji,Li.FineTuningJobCheckpointsPage=Ui;class Gi extends ar{constructor(){super(...arguments),this.methods=new Pi(this._client),this.jobs=new Li(this._client),this.checkpoints=new Bi(this._client),this.alpha=new Di(this._client)}}Gi.Methods=Pi,Gi.Jobs=Li,Gi.FineTuningJobsPage=qi,Gi.FineTuningJobEventsPage=Ji,Gi.Checkpoints=Bi,Gi.Alpha=Di;class zi extends ar{}class Wi extends ar{constructor(){super(...arguments),this.graderModels=new zi(this._client)}}Wi.GraderModels=zi;class Ki extends ar{createVariation(e,t){return this._client.post("/images/variations",As({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",As({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Vi extends ar{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Zi,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Zi extends sr{}Vi.ModelsPage=Zi;class Yi extends ar{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Xi(e,t){return t&&function(e){if(la(e.text?.format))return!0;return!1}(t)?Qi(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}function Qi(e,t){const n=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:to(t,e)};if("message"===e.type){const n=e.content.map(e=>"output_text"===e.type?{...e,parsed:eo(t,e.text)}:e);return{...e,content:n}}return e}),s=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||no(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const e of s.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),s}function eo(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const n=e.text?.format;return n.$parseRaw(t)}return JSON.parse(t)}function to(e,t){const n=(s=e.tools??[],r=t.name,s.find(e=>"function"===e.type&&e.name===r));var s,r,a;return{...t,...t,parsed_arguments:(a=n,"auto-parseable-tool"===a?.$brand?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null)}}function no(e){const t=[];for(const n of e.output)if("message"===n.type)for(const e of n.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}class so extends ar{list(e,t={},n){return Ds(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,go,{query:t,...n})}}var ro,ao,io,oo,fo,co,lo,uo,po=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},ho=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class yo extends Rr{constructor(e){super(),ro.add(this),ao.set(this,void 0),io.set(this,void 0),oo.set(this,void 0),po(this,ao,e,"f")}static createResponse(e,t,n){const s=new yo(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){const s=n?.signal;let r;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),ho(this,ro,"m",fo).call(this);let a=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const i of r)ho(this,ro,"m",co).call(this,i,a);if(r.controller.signal?.aborted)throw new Vn;return ho(this,ro,"m",lo).call(this)}[(ao=new WeakMap,io=new WeakMap,oo=new WeakMap,ro=new WeakSet,fo=function(){this.ended||po(this,io,void 0,"f")},co=function(e,t){if(this.ended)return;const n=(e,n)=>{(null==t||n.sequence_number>t)&&this._emit(e,n)},s=ho(this,ro,"m",uo).call(this,e);switch(n("event",e),e.type){case"response.output_text.delta":{const t=s.output[e.output_index];if(!t)throw new Wn(`missing output at index ${e.output_index}`);if("message"===t.type){const s=t.content[e.content_index];if(!s)throw new Wn(`missing content at index ${e.content_index}`);if("output_text"!==s.type)throw new Wn(`expected content to be 'output_text', got ${s.type}`);n("response.output_text.delta",{...e,snapshot:s.text})}break}case"response.function_call_arguments.delta":{const t=s.output[e.output_index];if(!t)throw new Wn(`missing output at index ${e.output_index}`);"function_call"===t.type&&n("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:n(e.type,e)}},lo=function(){if(this.ended)throw new Wn("stream has ended, this shouldn't happen");const e=ho(this,io,"f");if(!e)throw new Wn("request ended without sending any events");po(this,io,void 0,"f");const t=function(e,t){return Xi(e,t)}(e,ho(this,ao,"f"));return po(this,oo,t,"f"),t},uo=function(e){let t=ho(this,io,"f");if(!t){if("response.created"!==e.type)throw new Wn(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=po(this,io,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const n=t.output[e.output_index];if(!n)throw new Wn(`missing output at index ${e.output_index}`);"message"===n.type&&n.content.push(e.part);break}case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new Wn(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new Wn(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Wn(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new Wn(`missing output at index ${e.output_index}`);"function_call"===n.type&&(n.arguments+=e.delta);break}case"response.completed":po(this,io,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=ho(this,oo,"f");if(!e)throw new Wn("stream ended without producing a ChatCompletion");return e}}class mo extends ar{constructor(){super(...arguments),this.inputItems=new so(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&no(e),e))}retrieve(e,t={},n){return this._client.get(`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>Qi(t,e))}stream(e,t){return yo.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class go extends rr{}mo.InputItems=so;class bo extends ar{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,As({body:t,...n}))}}class wo extends ar{constructor(){super(...arguments),this.parts=new bo(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}wo.Parts=bo;class vo extends ar{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Ds(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,_o,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const r=await this.retrieve(e,t,{...n,headers:s}).withResponse(),a=r.data;switch(a.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Gs(e);break;case"failed":case"completed":return a}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,To,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class _o extends rr{}class To extends sr{}vo.VectorStoreFilesPage=_o,vo.FileContentResponsesPage=To;class xo extends ar{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return Ds(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,_o,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:a}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Gs(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=s?.maxConcurrency??5,a=Math.min(r,t.length),i=this._client,o=t.values(),f=[...n];const c=Array(a).fill(o).map(async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},s);f.push(e.id)}});return await(async e=>{const t=await Promise.allSettled(e),n=t.filter(e=>"rejected"===e.status);if(n.length){for(const e of n)console.error(e.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const r of t)"fulfilled"===r.status&&s.push(r.value);return s})(c),await this.createAndPoll(e,{file_ids:f})}}class Ao extends ar{constructor(){super(...arguments),this.files=new vo(this._client),this.fileBatches=new xo(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return Ds(e)?this.list({},e):this._client.getAPIList("/vector_stores",So,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,ko,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class So extends rr{}class ko extends sr{}var Eo;Ao.VectorStoresPage=So,Ao.VectorStoreSearchResponsesPage=ko,Ao.Files=vo,Ao.VectorStoreFilesPage=_o,Ao.FileContentResponsesPage=To,Ao.FileBatches=xo;class No extends Os{constructor({baseURL:e=Ks("OPENAI_BASE_URL"),apiKey:t=Ks("OPENAI_API_KEY"),organization:n=Ks("OPENAI_ORG_ID")??null,project:s=Ks("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new Wn("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const a={apiKey:t,organization:n,project:s,...r,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Wn("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new wi(this),this.chat=new lr(this),this.embeddings=new Si(this),this.files=new Ri(this),this.images=new Ki(this),this.audio=new hr(this),this.moderations=new Yi(this),this.models=new Vi(this),this.fineTuning=new Gi(this),this.graders=new Wi(this),this.vectorStores=new Ao(this),this.beta=new bi(this),this.batches=new yr(this),this.uploads=new wo(this),this.responses=new mo(this),this.evals=new Ci(this),this.containers=new xi(this),this._options=a,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return $n(e,{arrayFormat:"brackets"})}}Eo=No,No.OpenAI=Eo,No.DEFAULT_TIMEOUT=6e5,No.OpenAIError=Wn,No.APIError=Kn,No.APIConnectionError=Zn,No.APIConnectionTimeoutError=Yn,No.APIUserAbortError=Vn,No.NotFoundError=ts,No.ConflictError=ns,No.RateLimitError=rs,No.BadRequestError=Xn,No.AuthenticationError=Qn,No.InternalServerError=as,No.PermissionDeniedError=es,No.UnprocessableEntityError=ss,No.toFile=vs,No.fileFromPath=Ln,No.Completions=wi,No.Chat=lr,No.ChatCompletionsPage=fr,No.Embeddings=Si,No.Files=Ri,No.FileObjectsPage=$i,No.Images=Ki,No.Audio=hr,No.Moderations=Yi,No.Models=Vi,No.ModelsPage=Zi,No.FineTuning=Gi,No.Graders=Wi,No.VectorStores=Ao,No.VectorStoresPage=So,No.VectorStoreSearchResponsesPage=ko,No.Beta=bi,No.Batches=yr,No.BatchesPage=mr,No.Uploads=wo,No.Responses=mo,No.Evals=Ci,No.EvalListResponsesPage=Oi,No.Containers=xi,No.ContainerListResponsesPage=Ai;class Io{constructor(e,t={}){if(!e)throw new Error("OpenAI API key is required");this.openai=new No({apiKey:e}),this.model=t.model||"gpt-4o-mini",this.maxTokens=t.maxTokens||2e3,this.temperature=t.temperature||.7}async sendMessage(e,t,n={}){try{const s=await this.openai.chat.completions.create({model:n.model||this.model,messages:[{role:"system",content:e},{role:"user",content:t}],max_tokens:n.maxTokens||this.maxTokens,temperature:n.temperature??this.temperature});return s.choices[0]?.message?.content?.trim()||""}catch(s){throw new Error(`LLM request failed: ${s.message}`)}}async chat(e,t={}){try{const n=await this.openai.chat.completions.create({model:t.model||this.model,messages:e,max_tokens:t.maxTokens||this.maxTokens,temperature:t.temperature??this.temperature});return n.choices[0]?.message?.content?.trim()||""}catch(n){throw new Error(`LLM chat failed: ${n.message}`)}}async summarize(e,t={}){const n=`You are a helpful assistant that summarizes text concisely while preserving key information. Keep summaries clear and focused.${t.maxLength?` Keep the summary under ${t.maxLength} words.`:""}${t.style?` Style: ${t.style}.`:""}`;return this.sendMessage(n,e,{temperature:.5})}async analyze(e,t){const n=`You are an expert analyst. Analyze the following text from the perspective of "${t}". Provide a clear, structured analysis.`;return this.sendMessage(n,e,{temperature:.3})}async extractKeywords(e,t=10){const n=`Extract the ${t} most important keywords or key phrases from the text. Return ONLY a JSON array of strings, nothing else. Example: ["keyword1", "keyword2"]`,s=await this.sendMessage(n,e,{temperature:.2});try{return JSON.parse(s)}catch{const e=s.match(/\[[\s\S]*\]/);return e?JSON.parse(e[0]):s.split(",").map(e=>e.trim().replace(/["\[\]]/g,""))}}async categorize(e,t){const n=`Categorize the following text into one of these categories: ${t.join(", ")}.\nReturn ONLY a JSON object with: {"category": "chosen_category", "confidence": 0.0-1.0, "reasoning": "brief explanation"}`,s=await this.sendMessage(n,e,{temperature:.2});try{return JSON.parse(s)}catch{const e=s.match(/\{[\s\S]*\}/);return e?JSON.parse(e[0]):{category:t[0],confidence:.5,reasoning:s}}}async translate(e,t){const n=`Translate the following text to ${t}. Return ONLY the translation, nothing else.`;return this.sendMessage(n,e,{temperature:.3})}async generateQuestions(e,t=5){const n=`Generate ${t} insightful questions about the following text. Return ONLY a JSON array of question strings, nothing else. Example: ["Question 1?", "Question 2?"]`,s=await this.sendMessage(n,e,{temperature:.7});try{return JSON.parse(s)}catch{const e=s.match(/\[[\s\S]*\]/);return e?JSON.parse(e[0]):s.split("\n").filter(e=>e.trim().endsWith("?"))}}async getJSON(e,t,n={}){const s=await this.sendMessage(e+"\n\nReturn ONLY valid JSON, no additional text.",t,{...n,temperature:n.temperature??.2});try{return JSON.parse(s)}catch{const e=s.match(/[\[{][\s\S]*[\]}]/);if(e)return JSON.parse(e[0]);throw new Error(`Failed to parse JSON response: ${s.substring(0,100)}`)}}}class Co{constructor(e){this.llm=e}async extractToSchema(e,t,n={}){const s=this._describeSchema(t),r=`You are a data extraction expert. Extract structured information from the provided text according to this JSON schema:\n\n${JSON.stringify(t,null,2)}\n\nSchema field descriptions:\n${s}\n\nRules:\n1. Extract ONLY information present in the text\n2. Use null for fields where information is not available\n3. Follow the exact schema structure and field types\n4. For arrays, include all relevant items found\n5. Return ONLY valid JSON matching the schema`;return await this.llm.getJSON(r,e,{temperature:.2,maxTokens:n.maxTokens||2e3})}_describeSchema(e,t=""){const n=[];if(e.description&&n.push(`${t||"root"}: ${e.description}`),e.properties)for(const[s,r]of Object.entries(e.properties)){const a=t?`${t}.${s}`:s,i=r.type||"any",o=e.required?.includes(s)?" (required)":"",f=r.description||"";n.push(`- ${a} [${i}]${o}: ${f}`),"object"===r.type&&r.properties&&n.push(this._describeSchema(r,a)),"array"===r.type&&r.items&&r.items.properties&&n.push(this._describeSchema(r.items,`${a}[]`))}return n.join("\n")}async extractMultiple(e,t,n={}){const s=`You are a data extraction expert. Extract ALL items matching this schema from the text:\n\n${JSON.stringify(t,null,2)}\n\nReturn a JSON array of all items found. If no items found, return [].\nReturn ONLY valid JSON array.`,r=await this.llm.getJSON(s,e,{temperature:.2,maxTokens:n.maxTokens||3e3});return Array.isArray(r)?r:[r]}async fillMissing(e,t,n){const s=this._findMissingFields(e,n);if(0===s.length)return e;const r=`You have existing data:\n${JSON.stringify(e,null,2)}\n\nExtract ONLY the following missing fields from the text:\n${s.join(", ")}\n\nBased on this schema:\n${JSON.stringify(n,null,2)}\n\nReturn JSON with ONLY the missing fields that you can extract. Do not modify existing fields.`,a=await this.llm.getJSON(r,t,{temperature:.2});return{...e,...a}}_findMissingFields(e,t,n=""){const s=[];if(t.properties)for(const[r,a]of Object.entries(t.properties)){const t=n?`${n}.${r}`:r,i=e[r];null==i?s.push(t):"object"===a.type&&a.properties&&s.push(...this._findMissingFields(i,a,t))}return s}validateExtraction(e,t){const n=[];if(t.required)for(const s of t.required)void 0!==e[s]&&null!==e[s]||n.push(`Missing required field: ${s}`);if(t.properties)for(const[s,r]of Object.entries(t.properties)){const t=e[s];if(null!=t){this._validateType(t,r.type)||n.push(`Invalid type for ${s}: expected ${r.type}, got ${typeof t}`)}}return{valid:0===n.length,errors:n}}_validateType(e,t){switch(t){case"string":return"string"==typeof e;case"number":case"integer":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"array":return Array.isArray(e);case"object":return"object"==typeof e&&!Array.isArray(e);default:return!0}}}class Oo{constructor(e){this.llm=e}async add(e,t,n={}){const s=`You are a JSON merge expert. Semantically merge these two JSON objects.\n\nRules:\n1. Combine information from both objects intelligently\n2. For conflicting values, prefer the more complete/detailed one${n.preferSecond?", or prefer the second object":""}\n3. Merge arrays by combining items, removing duplicates by semantic similarity\n4. Preserve all unique information from both objects\n5. Return ONLY valid JSON`,r=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON(s,r,{temperature:.2})}async subtract(e,t){const n=`Base object (to modify):\n${JSON.stringify(e,null,2)}\n\nConcepts to remove:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON manipulation expert. Remove concepts from the first object that are semantically present in the second object.\n\nRules:\n1. Remove fields from obj1 that have semantic equivalents in obj2\n2. For arrays, remove items that are semantically similar to items in obj2\n3. Preserve fields/items in obj1 that have no semantic match in obj2\n4. Remove nested content that matches semantically\n5. Return ONLY valid JSON",n,{temperature:.2})}async union(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON merge expert. Create a semantic union of these two JSON objects.\n\nRules:\n1. Include all unique information from both objects\n2. For duplicate concepts, keep only one (the more complete version)\n3. Deduplicate array items by semantic similarity, not just exact match\n4. Merge nested objects recursively with the same rules\n5. Return ONLY valid JSON",n,{temperature:.2})}async difference(e,t){const n=`Object 1 (original):\n${JSON.stringify(e,null,2)}\n\nObject 2 (new):\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON('You are a JSON comparison expert. Find the semantic differences between these two JSON objects.\n\nReturn a JSON object with:\n- "added": fields/values present in obj2 but not in obj1\n- "removed": fields/values present in obj1 but not in obj2\n- "changed": fields where the value changed (show both old and new)\n\nConsider semantic similarity - fields with different names but same meaning should be considered the same.\nReturn ONLY valid JSON with the structure: {"added": {}, "removed": {}, "changed": {}}',n,{temperature:.2})}async concatenate(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON concatenation expert. Concatenate these two JSON objects.\n\nRules:\n1. For string fields: append obj2 values to obj1 values with appropriate separators\n2. For array fields: append obj2 arrays to obj1 arrays\n3. For number fields: sum the values\n4. For object fields: recursively concatenate\n5. For boolean fields: use logical OR\n6. Preserve the structure of obj1\n7. Return ONLY valid JSON",n,{temperature:.2})}async intersection(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON comparison expert. Find the semantic intersection of these two JSON objects.\n\nRules:\n1. Return only fields/values that are semantically present in BOTH objects\n2. For arrays, return only items that have semantic matches in both\n3. Consider semantic similarity, not just exact matches\n4. Return ONLY valid JSON",n,{temperature:.2})}async transform(e,t){const n=`You are a JSON transformation expert. Transform this JSON object according to the target structure description.\n\nTarget structure: ${t}\n\nRules:\n1. Map existing fields to the new structure\n2. Preserve all information, reorganizing as needed\n3. Use appropriate type conversions\n4. Return ONLY valid JSON`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}async simplify(e,t={}){const n=`You are a JSON simplification expert. Simplify this nested JSON object.\n\nRules:\n1. Flatten deeply nested structures where appropriate\n2. Combine redundant fields\n3. Remove null/empty values${t.keepEmpty?" (unless specified to keep)":""}\n4. Use clear, concise field names\n5. Return ONLY valid JSON`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}async apply(e,t){const n=`You are a JSON manipulation expert. Apply the following operation to the JSON object:\n\nOperation: ${t}\n\nReturn ONLY valid JSON with the operation applied.`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}}class Ro{constructor(e,t=null){this.openai=e,this.holosphere=t,this.model="text-embedding-3-small",this.dimensions=1536}setHoloSphere(e){this.holosphere=e}async embed(e){try{return(await this.openai.embeddings.create({model:this.model,input:e})).data[0].embedding}catch(t){throw new Error(`Embedding generation failed: ${t.message}`)}}async embedBatch(e){try{return(await this.openai.embeddings.create({model:this.model,input:e})).data.map(e=>e.embedding)}catch(t){throw new Error(`Batch embedding failed: ${t.message}`)}}cosineSimilarity(e,t){if(e.length!==t.length)throw new Error("Vectors must have same length");let n=0,s=0,r=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],s+=e[a]*e[a],r+=t[a]*t[a];return n/(Math.sqrt(s)*Math.sqrt(r))}async storeWithEmbedding(e,t,n,s=null){if(!this.holosphere)throw new Error("HoloSphere instance required for storage");const r=s?n[s]:n.content||n.text||n.description||JSON.stringify(n);if(!r)throw new Error("No text found to embed");const a=await this.embed(r),i={...n,_embedding:a,_embeddedField:s||"auto",_embeddedAt:Date.now()};return await this.holosphere.put(e,t,i),i}async semanticSearch(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required for search");const{limit:r=10,threshold:a=.5}=s,i=await this.embed(e),o=await this.holosphere.getAll(t,n),f=[];for(const c of o)if(c._embedding){const e=this.cosineSimilarity(i,c._embedding);e>=a&&f.push({item:{...c,_embedding:void 0},similarity:e})}return f.sort((e,t)=>t.similarity-e.similarity),f.slice(0,r)}async findSimilar(e,t,n,s={}){const r=e.content||e.text||e.description||JSON.stringify(e);return this.semanticSearch(r,t,n,s)}async cluster(e,t=5){const n=await Promise.all(e.map(async e=>{if(e._embedding)return e;const t=e.content||e.text||e.description||JSON.stringify(e),n=await this.embed(t);return{...e,_embedding:n}}));return this._kMeans(n,t).map(e=>e.map(e=>({...e,_embedding:void 0})))}_kMeans(e,t,n=100){if(e.length<=t)return e.map(e=>[e]);let s=[...e].sort(()=>Math.random()-.5).slice(0,t).map(e=>[...e._embedding]),r=new Array(e.length);for(let i=0;i<n;i++){const n=e.map(e=>{let t=1/0,n=0;for(let r=0;r<s.length;r++){const a=1-this.cosineSimilarity(e._embedding,s[r]);a<t&&(t=a,n=r)}return n});if(JSON.stringify(n)===JSON.stringify(r))break;r=n;for(let a=0;a<t;a++){const t=e.filter((e,t)=>r[t]===a);if(t.length>0){s[a]=new Array(this.dimensions).fill(0);for(const e of t)for(let t=0;t<this.dimensions;t++)s[a][t]+=e._embedding[t];for(let e=0;e<this.dimensions;e++)s[a][e]/=t.length}}}const a=Array.from({length:t},()=>[]);return e.forEach((e,t)=>{a[r[t]].push(e)}),a.filter(e=>e.length>0)}}const $o=[{name:"Values & Worldview",prompt:"Answer from the embodied perspective of Values and Worldview - considering ethics, beliefs, culture, and meaning."},{name:"Health & Wellbeing",prompt:"Answer from the embodied perspective of Health & Wellbeing - considering physical, mental, and social health."},{name:"Food & Agriculture",prompt:"Answer from the embodied perspective of Food & Agriculture - considering food systems, nutrition, and farming."},{name:"Business & Trade",prompt:"Answer from the embodied perspective of Business & Trade - considering commerce, markets, and economic exchange."},{name:"Energy & Resources",prompt:"Answer from the embodied perspective of Energy & Resources - considering power, materials, and sustainability."},{name:"Climate & Environment",prompt:"Answer from the embodied perspective of Climate Change - considering environmental impact and adaptation."},{name:"Ecosystems & Biosphere",prompt:"Answer from the embodied perspective of Ecosystems & Biosphere - considering biodiversity and natural systems."},{name:"Water Availability",prompt:"Answer from the embodied perspective of Water Availability - considering water access, quality, and management."},{name:"Habitat & Infrastructure",prompt:"Answer from the embodied perspective of Habitat & Infrastructure - considering built environment and housing."},{name:"Economy & Wealth",prompt:"Answer from the embodied perspective of Economy & Wealth - considering prosperity, inequality, and resources."},{name:"Governance & Institutions",prompt:"Answer from the embodied perspective of Governance & Institutions - considering power, policy, and organization."},{name:"Community & Resilience",prompt:"Answer from the embodied perspective of Community & Resilience - considering social bonds and adaptability."}];class Po{constructor(e,t=null){this.llm=e,this.perspectives=t||$o}setPerspectives(e){this.perspectives=e}static getDefaultPerspectives(){return $o}async ask(e,t={}){const{parallel:n=!0,includeSummary:s=!0}=t,r=t.perspectives||this.perspectives;let a;if(n)a=await Promise.all(r.map(async t=>{const n=await this._askPerspective(e,t);return{perspective:t.name,answer:n}}));else{a=[];for(const t of r){const n=await this._askPerspective(e,t);a.push({perspective:t.name,answer:n})}}let i=null;return s&&(i=await this._summarize(e,a)),{question:e,perspectives:a,summary:i,timestamp:Date.now()}}async _askPerspective(e,t){const n=`You are a wise council member representing a specific perspective.\n\n${t.prompt}\n\nProvide thoughtful, nuanced answers that honor your unique perspective while being constructive and helpful. Be concise but insightful.`;return this.llm.sendMessage(n,e,{temperature:.7})}async _summarize(e,t){const n=`Question: ${e}\n\nPerspectives:\n${t.map(e=>`**${e.perspective}**: ${e.answer}`).join("\n\n")}`;return this.llm.sendMessage("You are a wise facilitator. Synthesize the following perspectives into a balanced summary that:\n1. Identifies common themes and agreements\n2. Notes important tensions or tradeoffs\n3. Provides actionable wisdom\n4. Remains neutral and balanced\n\nBe concise but comprehensive.",n,{temperature:.5})}static createPerspectives(e){return e.map(e=>({name:e,prompt:`Answer from the embodied perspective of ${e} - considering all aspects related to ${e.toLowerCase()}.`}))}async askCustom(e,t,n={}){const s=Po.createPerspectives(t);return this.ask(e,{...n,perspectives:s})}async askSingle(e,t){const n=this.perspectives.find(e=>e.name===t)||{name:t,prompt:`Answer from the perspective of ${t}.`};return this._askPerspective(e,n)}async debate(e,t,n=3){if(2!==t.length)throw new Error("Debate requires exactly 2 perspectives");const s=t.map(e=>this.perspectives.find(t=>t.name===e)||{name:e,prompt:`Argue from the perspective of ${e}.`}),r=[];let a=`Topic: ${e}`;for(let i=0;i<n;i++)for(const e of s){const t=`You are debating from the perspective of ${e.name}.\n${e.prompt}\nRespond to the previous arguments constructively, acknowledging good points but advocating for your perspective.`,n=await this.llm.sendMessage(t,a,{temperature:.7});r.push({perspective:e.name,round:i+1,response:n}),a+=`\n\n${e.name}: ${n}`}return{topic:e,perspectives:t,exchanges:r,conclusion:await this.llm.sendMessage("As a neutral moderator, summarize the key insights from this debate and identify areas of agreement and disagreement.",a,{temperature:.5})}}}const Mo={ALLOY:"alloy",ECHO:"echo",FABLE:"fable",ONYX:"onyx",NOVA:"nova",SHIMMER:"shimmer"},Do={TTS_1:"tts-1",TTS_1_HD:"tts-1-hd"};class Fo{constructor(e){this.openai=e,this.defaultVoice=Mo.ECHO,this.defaultModel=Do.TTS_1}async speak(e,t={}){const{voice:n=this.defaultVoice,model:s=this.defaultModel,speed:r=1,responseFormat:a="mp3"}=t;try{const t=await this.openai.audio.speech.create({model:s,voice:n,input:e,speed:r,response_format:a}),i=await t.arrayBuffer();return Buffer.from(i)}catch(i){throw new Error(`TTS failed: ${i.message}`)}}async speakBase64(e,t={}){return(await this.speak(e,t)).toString("base64")}async speakDataUrl(e,t={}){const n=t.responseFormat||"mp3";return`data:${"mp3"===n?"audio/mpeg":`audio/${n}`};base64,${await this.speakBase64(e,t)}`}setDefaultVoice(e){if(!Object.values(Mo).includes(e))throw new Error(`Invalid voice: ${e}. Use one of: ${Object.values(Mo).join(", ")}`);this.defaultVoice=e}setDefaultModel(e){if(!Object.values(Do).includes(e))throw new Error(`Invalid model: ${e}. Use one of: ${Object.values(Do).join(", ")}`);this.defaultModel=e}static getVoices(){return Object.values(Mo)}static getModels(){return Object.values(Do)}static estimateDuration(e,t=1){return 60*(e.split(/\s+/).length/150)/t}static splitText(e,t=4e3){if(e.length<=t)return[e];const n=[],s=e.split(/(?<=[.!?])\s+/);let r="";for(const a of s)(r+a).length>t?(r&&n.push(r.trim()),r=a):r+=(r?" ":"")+a;return r&&n.push(r.trim()),n}async speakLong(e,t={}){const n=Fo.splitText(e,t.maxChars||4e3);return await Promise.all(n.map(e=>this.speak(e,t)))}}class Ho{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async parse(e,t={}){const n=`You are a query parser. Convert natural language queries into structured JSON filters for a geospatial database.\n\nAvailable holons: ${t.holons?.join(", ")||"any"}\nAvailable lenses: ${t.lenses?.join(", ")||"any"}\n\nReturn a JSON object with:\n{\n "holon": "holon_id or null",\n "lens": "lens_name or null",\n "filters": {\n "field_name": { "op": "eq|ne|gt|gte|lt|lte|contains|in", "value": value }\n },\n "sort": { "field": "field_name", "order": "asc|desc" } or null,\n "limit": number or null,\n "spatial": { "near": "location_name", "radius": "distance" } or null,\n "temporal": { "after": "date", "before": "date" } or null\n}\n\nExamples:\n- "show projects near Rome" -> { "lens": "projects", "spatial": { "near": "Rome" } }\n- "find quests with more than 10 participants" -> { "lens": "quests", "filters": { "participants": { "op": "gt", "value": 10 } } }`;return await this.llm.getJSON(n,e,{temperature:.2})}async execute(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required for query execution");const n=await this.parse(e,t.context);let s=[];if(n.holon&&n.lens)s=await this.holosphere.getAll(n.holon,n.lens);else if(n.lens&&t.holons)for(const r of t.holons){const e=await this.holosphere.getAll(r,n.lens);s.push(...e.map(e=>({...e,_holon:r})))}return n.filters&&(s=this._applyFilters(s,n.filters)),n.sort&&(s=this._applySort(s,n.sort)),n.limit&&(s=s.slice(0,n.limit)),{query:e,parsed:n,results:s,count:s.length}}_applyFilters(e,t){return e.filter(e=>{for(const[n,s]of Object.entries(t)){const t=this._getNestedValue(e,n);if(!this._matchCondition(t,s))return!1}return!0})}_getNestedValue(e,t){return t.split(".").reduce((e,t)=>e?.[t],e)}_matchCondition(e,t){const{op:n,value:s}=t;switch(n){case"eq":return e===s;case"ne":return e!==s;case"gt":return e>s;case"gte":return e>=s;case"lt":return e<s;case"lte":return e<=s;case"contains":return String(e).toLowerCase().includes(String(s).toLowerCase());case"in":return Array.isArray(s)&&s.includes(e);default:return!0}}_applySort(e,t){const{field:n,order:s}=t,r="desc"===s?-1:1;return[...e].sort((e,t)=>{const s=this._getNestedValue(e,n),a=this._getNestedValue(t,n);return s<a?-1*r:s>a?1*r:0})}async suggest(e={}){const t=`Suggest 5 useful natural language queries for exploring geospatial data.\n\nAvailable holons: ${e.holons?.join(", ")||"geographic areas"}\nAvailable lenses: ${e.lenses?.join(", ")||"projects, quests, events, resources"}\n\nReturn ONLY a JSON array of query strings.`;return this.llm.getJSON(t,"Generate query suggestions",{temperature:.7})}async explain(e,t){const n=`You are a helpful data analyst. Explain the results of a query in natural language.\n\nOriginal query: ${e}\nNumber of results: ${t.length}\n\nProvide a brief, helpful summary of what was found.`,s=t.slice(0,5);return this.llm.sendMessage(n,`Results sample: ${JSON.stringify(s,null,2)}`,{temperature:.5})}}class Bo{constructor(e,t=null){this.llm=e,this.holosphere=t,this.lensDescriptions=new Map}setHoloSphere(e){this.holosphere=e}registerLens(e,t,n=null){this.lensDescriptions.set(e,{description:t,schema:n})}registerLenses(e){for(const[t,n]of Object.entries(e))this.registerLens(t,n.description,n.schema)}async classifyToLens(e){const t=Array.from(this.lensDescriptions.entries());if(0===t.length)throw new Error("No lenses registered. Use registerLens() first.");const n=t.map(([e,t])=>`- ${e}: ${t.description}`).join("\n"),s="string"==typeof e?e:JSON.stringify(e,null,2),r=`You are a content classifier. Classify the following content into the most appropriate lens.\n\nAvailable lenses:\n${n}\n\nReturn JSON: {"lens": "lens_name", "confidence": 0.0-1.0, "reasoning": "brief explanation"}`;return this.llm.getJSON(r,s,{temperature:.2})}async classifyMultiple(e,t=3){const n=Array.from(this.lensDescriptions.entries());if(0===n.length)throw new Error("No lenses registered");const s=n.map(([e,t])=>`- ${e}: ${t.description}`).join("\n"),r="string"==typeof e?e:JSON.stringify(e,null,2),a=`You are a content classifier. Classify the content into up to ${t} appropriate lenses, ranked by fit.\n\nAvailable lenses:\n${s}\n\nReturn JSON array: [{"lens": "name", "confidence": 0.0-1.0}, ...]\nOrder by confidence descending.`;return this.llm.getJSON(a,r,{temperature:.2})}async autoStore(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required for storage");const n=await this.classifyToLens(t),s=await this.holosphere.put(e,n.lens,t);return{lens:n.lens,confidence:n.confidence,reasoning:n.reasoning,stored:!0,result:s}}async suggestNewLens(e){const t=`You are helping design a data organization system. Suggest a new lens (category) for this type of content.\n\nExisting lenses: ${Array.from(this.lensDescriptions.keys()).join(", ")}\n\nReturn JSON: {"name": "lens_name", "description": "what this lens contains"}\nUse lowercase_snake_case for names.`;return this.llm.getJSON(t,e,{temperature:.5})}async suggestSchema(e){const t=JSON.stringify(e,null,2);return this.llm.getJSON("You are a data modeling expert. Analyze this content and suggest a JSON schema for validating similar content.\n\nReturn a valid JSON schema with:\n- Type definitions\n- Required fields\n- Field descriptions\n- Reasonable constraints",t,{temperature:.3})}async validateForLens(e,t){const n=this.lensDescriptions.get(t);if(!n)throw new Error(`Lens not found: ${t}`);if(!n.schema){const s=`Validate if this content is appropriate for the "${t}" lens.\nLens description: ${n.description}\n\nReturn JSON: {"valid": true/false, "issues": ["issue1", "issue2"] or []}`;return this.llm.getJSON(s,JSON.stringify(e,null,2),{temperature:.2})}return{valid:!0,issues:[]}}async analyzeCollection(e){const t=await Promise.all(e.map(e=>this.classifyToLens(e))),n={};for(const s of t)n[s.lens]=(n[s.lens]||0)+1;return{total:e.length,byLens:n,classifications:t}}}class jo{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async analyzeRegion(e,t=null,n="general"){if(!this.holosphere)throw new Error("HoloSphere instance required");let s=[];s=t?await this.holosphere.getAll(e,t):await this.holosphere.getAll(e,"default");const r=JSON.stringify(s.slice(0,50),null,2),a=`You are a geospatial data analyst. Analyze the following data from a geographic region.\n\nRegion (holon): ${e}\nLens: ${t||"all"}\nAnalysis aspect: ${n}\nTotal items: ${s.length}\n\nProvide insights about:\n1. Key patterns and trends\n2. Notable clusters or concentrations\n3. Anomalies or outliers\n4. Recommendations for the region\n\nReturn JSON:\n{\n "summary": "brief overview",\n "patterns": ["pattern1", "pattern2"],\n "insights": ["insight1", "insight2"],\n "metrics": {"metric1": value},\n "recommendations": ["rec1", "rec2"],\n "confidence": 0.0-1.0\n}`,i=await this.llm.getJSON(a,r,{temperature:.3});return{holon:e,lens:t,aspect:n,dataCount:s.length,analysis:i,timestamp:Date.now()}}async compareRegions(e,t,n){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,n),r=await this.holosphere.getAll(t,n),a=`You are a comparative analyst. Compare data between two geographic regions.\n\nRegion 1 (${e}): ${s.length} items\nRegion 2 (${t}): ${r.length} items\nLens: ${n}\n\nAnalyze and compare:\n1. Similarities between regions\n2. Key differences\n3. Relative strengths of each region\n4. Opportunities for collaboration\n\nReturn JSON:\n{\n "summary": "brief comparison",\n "similarities": ["sim1", "sim2"],\n "differences": ["diff1", "diff2"],\n "region1_strengths": ["strength1"],\n "region2_strengths": ["strength1"],\n "collaboration_opportunities": ["opp1"],\n "metrics_comparison": {"metric": {"region1": val, "region2": val}}\n}`,i=`Region 1 data sample:\n${JSON.stringify(s.slice(0,25),null,2)}\n\nRegion 2 data sample:\n${JSON.stringify(r.slice(0,25),null,2)}`,o=await this.llm.getJSON(a,i,{temperature:.3});return{regions:[e,t],lens:n,dataCounts:{[e]:s.length,[t]:r.length},comparison:o,timestamp:Date.now()}}async spatialTrends(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t);let r=s;(n.start||n.end)&&(r=s.filter(e=>{const t=e.timestamp||e.created_at||e.date;if(!t)return!0;const s=new Date(t).getTime();return!(n.start&&s<new Date(n.start).getTime())&&!(n.end&&s>new Date(n.end).getTime())}));const a=`You are a trend analyst. Analyze temporal patterns in geographic data.\n\nRegion: ${e}\nLens: ${t}\nTime range: ${JSON.stringify(n)}\nItems analyzed: ${r.length}\n\nIdentify:\n1. Growth/decline trends\n2. Seasonal patterns\n3. Emerging themes\n4. Predictions\n\nReturn JSON:\n{\n "trends": [{"trend": "description", "direction": "up|down|stable", "strength": 0.0-1.0}],\n "patterns": ["pattern1"],\n "emerging_themes": ["theme1"],\n "predictions": ["pred1"],\n "summary": "overview"\n}`,i=await this.llm.getJSON(a,JSON.stringify(r.slice(0,50),null,2),{temperature:.3});return{holon:e,lens:t,timeRange:n,dataCount:r.length,trends:i,timestamp:Date.now()}}async findHotspots(e,t,n="count"){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t),r=`You are a spatial analyst. Identify hotspots (areas of high concentration/activity) in geographic data.\n\nRegion: ${e}\nLens: ${t}\nMetric: ${n}\nData points: ${s.length}\n\nIdentify:\n1. High-activity areas\n2. Emerging areas\n3. Underserved areas\n4. Recommended focus areas\n\nReturn JSON:\n{\n "hotspots": [{"location": "desc", "intensity": 0.0-1.0, "type": "high_activity|emerging|underserved"}],\n "concentration_patterns": ["pattern1"],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`;return this.llm.getJSON(r,JSON.stringify(s.slice(0,50),null,2),{temperature:.3})}async generateReport(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const n=t.lenses||["default"],s={};for(const i of n)s[i]=await this.holosphere.getAll(e,i);const r=`You are a regional analyst. Generate a comprehensive report for this geographic region.\n\nRegion: ${e}\nData by lens: ${Object.entries(s).map(([e,t])=>`${e}: ${t.length} items`).join(", ")}\n\nGenerate a professional report including:\n1. Executive Summary\n2. Key Statistics\n3. Notable Patterns\n4. Opportunities\n5. Recommendations\n\nFormat as markdown.`,a={};for(const[i,o]of Object.entries(s))a[i]=o.slice(0,20);return this.llm.sendMessage(r,JSON.stringify(a,null,2),{temperature:.5,maxTokens:2e3})}}class Uo{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async smartUpcast(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{maxLevels:s=5,storeResults:a=!0}=n,i=await this.holosphere.getAll(e,t),o=await this._generateSummary(i,e,t),f=r.getResolution(e);if(f<=0||s<=0)return{holon:e,lens:t,summary:o,level:f};const c=r.cellToParent(e,f-1);a&&await this.holosphere.put(c,`${t}_summaries`,{id:e,childHolon:e,summary:o,dataCount:i.length,timestamp:Date.now()});const l=await this.smartUpcast(c,t,{...n,maxLevels:s-1});return{holon:e,lens:t,summary:o,dataCount:i.length,parent:l}}async _generateSummary(e,t,n){if(0===e.length)return{text:"No data in this region",stats:{count:0}};const s=`You are a data summarization expert. Create a concise summary of this geographic data.\n\nRegion: ${t}\nCategory: ${n}\nItems: ${e.length}\n\nGenerate:\n1. A brief text summary (2-3 sentences)\n2. Key statistics\n3. Notable items\n4. Themes/patterns\n\nReturn JSON:\n{\n "text": "summary text",\n "stats": {"count": n, "key_metric": value},\n "notable": ["item1", "item2"],\n "themes": ["theme1", "theme2"]\n}`;return this.llm.getJSON(s,JSON.stringify(e.slice(0,30),null,2),{temperature:.3})}async generateHolonSummary(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=["projects","quests","events","resources","default"],n={};for(const a of t)try{const t=await this.holosphere.getAll(e,a);t.length>0&&(n[a]=t)}catch{}const s=`You are a regional analyst. Generate a comprehensive summary of this geographic area.\n\nRegion: ${e}\nData available: ${Object.entries(n).map(([e,t])=>`${e}: ${t.length}`).join(", ")}\n\nGenerate a complete overview including:\n1. Executive summary\n2. Key activities and projects\n3. Community engagement\n4. Resources and assets\n5. Challenges and opportunities\n6. Overall health assessment\n\nReturn JSON:\n{\n "title": "Region Title",\n "executive_summary": "brief overview",\n "highlights": ["highlight1", "highlight2"],\n "activities": {"count": n, "summary": "text"},\n "community": {"engagement_level": "high|medium|low", "notes": "text"},\n "resources": ["resource1"],\n "challenges": ["challenge1"],\n "opportunities": ["opp1"],\n "health_score": 0.0-1.0,\n "recommendations": ["rec1"]\n}`,r={};for(const[a,i]of Object.entries(n))r[a]=i.slice(0,15);return{holon:e,summary:await this.llm.getJSON(s,JSON.stringify(r,null,2),{temperature:.4,maxTokens:2e3}),lensesAnalyzed:Object.keys(n),totalItems:Object.values(n).reduce((e,t)=>e+t.length,0),timestamp:Date.now()}}async aggregateChildren(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required");const n=r.getResolution(e),s=r.cellToChildren(e,n+1),a=[];for(const r of s.slice(0,7))try{const e=await this.holosphere.getAll(r,t);if(e.length>0){const n=await this._generateSummary(e,r,t);a.push({holon:r,summary:n})}}catch{}if(0===a.length)return{holon:e,summary:null,message:"No child data found"};const i=`You are aggregating summaries from child regions into a parent region summary.\n\nParent region: ${e}\nChild summaries: ${a.length}\n\nCreate an aggregated summary that:\n1. Synthesizes common themes\n2. Highlights regional diversity\n3. Identifies cross-cutting patterns\n4. Notes outliers\n\nReturn JSON:\n{\n "aggregated_summary": "text",\n "common_themes": ["theme1"],\n "regional_diversity": ["diff1"],\n "patterns": ["pattern1"],\n "total_activity": {"count": n, "trend": "growing|stable|declining"}\n}`,o=await this.llm.getJSON(i,JSON.stringify(a,null,2),{temperature:.3});return{holon:e,lens:t,childCount:a.length,summary:o,timestamp:Date.now()}}async comparePeriods(e,t,n,s){if(!this.holosphere)throw new Error("HoloSphere instance required");const r=await this.holosphere.getAll(e,t),a=(e,t)=>e.filter(e=>{const n=e.timestamp||e.created_at;if(!n)return!1;const s=new Date(n).getTime();return s>=new Date(t.start).getTime()&&s<=new Date(t.end).getTime()}),i=a(r,n),o=a(r,s),f=`Compare data between two time periods for a geographic region.\n\nRegion: ${e}\nPeriod 1: ${JSON.stringify(n)} - ${i.length} items\nPeriod 2: ${JSON.stringify(s)} - ${o.length} items\n\nAnalyze:\n1. Growth/decline\n2. New themes in period 2\n3. Themes that disappeared\n4. Key changes\n\nReturn JSON:\n{\n "growth_rate": percentage,\n "direction": "growth|decline|stable",\n "new_themes": ["theme1"],\n "disappeared": ["theme1"],\n "key_changes": ["change1"],\n "summary": "text"\n}`,c=`Period 1 data:\n${JSON.stringify(i.slice(0,20),null,2)}\n\nPeriod 2 data:\n${JSON.stringify(o.slice(0,20),null,2)}`;return this.llm.getJSON(f,c,{temperature:.3})}}class Lo{constructor(e,t=null,n=null){this.llm=e,this.holosphere=t,this.embeddings=n}setHoloSphere(e){this.holosphere=e}setEmbeddings(e){this.embeddings=e}async suggestFederations(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{candidateHolons:n=[],lens:s="default",maxSuggestions:r=5}=t,a=await this.holosphere.getAll(e,s);if(0===a.length)return{holon:e,suggestions:[],message:"No data in source holon"};const i=[];for(const c of n.slice(0,10))if(c!==e)try{const e=await this.holosphere.getAll(c,s);e.length>0&&i.push({holon:c,dataCount:e.length,dataSample:e.slice(0,10)})}catch{}if(0===i.length)return{holon:e,suggestions:[],message:"No candidate holons with data"};const o=`You are a federation advisor. Analyze which regions would benefit from federating (sharing data) with the source region.\n\nSource region: ${e}\nSource data count: ${a.length}\n\nConsider:\n1. Content similarity - similar topics benefit from shared visibility\n2. Complementary content - different but related content enables collaboration\n3. Geographic proximity relevance\n4. Potential for knowledge sharing\n\nReturn JSON array:\n[\n {\n "holon": "id",\n "score": 0.0-1.0,\n "reasoning": "why federate",\n "benefits": ["benefit1"],\n "type": "similarity|complementary|geographic"\n }\n]\n\nOrder by score descending, max ${r} suggestions.`,f=`Source data sample:\n${JSON.stringify(a.slice(0,15),null,2)}\n\nCandidate regions:\n${JSON.stringify(i,null,2)}`;return{holon:e,lens:s,suggestions:(await this.llm.getJSON(o,f,{temperature:.3})).slice(0,r),timestamp:Date.now()}}async analyzeFederationHealth(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=await this.holosphere.getFederation(e);if(!t||!t.federation||0===t.federation.length)return{holon:e,health:"none",message:"No federations configured",score:0};const n=[];for(const a of t.federation.slice(0,5))try{const e=await this.holosphere.getAll(a,"default");n.push({holon:a,active:e.length>0,dataCount:e.length})}catch{n.push({holon:a,active:!1,error:!0})}const s=`You are a federation health analyst. Assess the health of this holon's federation relationships.\n\nSource holon: ${e}\nFederation partners: ${t.federation.length}\nActive federations: ${n.filter(e=>e.active).length}\n\nFederation details:\n${JSON.stringify(n,null,2)}\n\nAnalyze:\n1. Overall federation health\n2. Active vs inactive relationships\n3. Balance of the federation network\n4. Recommendations\n\nReturn JSON:\n{\n "health_score": 0.0-1.0,\n "status": "healthy|degraded|unhealthy",\n "active_count": n,\n "inactive_count": n,\n "issues": ["issue1"],\n "recommendations": ["rec1"],\n "summary": "text"\n}`,r=await this.llm.getJSON(s,"",{temperature:.3});return{holon:e,federation:t.federation,analysis:r,timestamp:Date.now()}}async optimizeFederation(e){const t=await this.analyzeFederationHealth(e);if("none"===t.health)return{holon:e,suggestions:["Consider establishing initial federations"]};const n=`Based on federation health analysis, suggest optimizations.\n\nHealth analysis:\n${JSON.stringify(t.analysis,null,2)}\n\nSuggest:\n1. Federations to strengthen\n2. Federations to reconsider\n3. New potential federations\n4. Data flow improvements\n\nReturn JSON:\n{\n "strengthen": ["holon_id"],\n "reconsider": ["holon_id"],\n "new_potential": ["description"],\n "improvements": ["improvement1"],\n "priority": "high|medium|low"\n}`;return this.llm.getJSON(n,"",{temperature:.4})}async analyzeDataFlow(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=await this.holosphere.getFederation(e);if(!t)return{holon:e,message:"No federation configured"};const n=`Analyze the data flow patterns in a federation network.\n\nSource holon: ${e}\nFederated with: ${t.federation?.join(", ")||"none"}\nNotifies: ${t.notify?.join(", ")||"none"}\n\nConsider:\n1. Bidirectional vs unidirectional relationships\n2. Hub patterns (many connections)\n3. Data propagation paths\n4. Potential bottlenecks\n\nReturn JSON:\n{\n "flow_type": "bidirectional|unidirectional|mixed",\n "topology": "hub|mesh|chain|star",\n "propagation_depth": n,\n "bottlenecks": ["desc"],\n "recommendations": ["rec1"]\n}`;return this.llm.getJSON(n,JSON.stringify(t,null,2),{temperature:.3})}async findBridges(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=[];for(const s of e.slice(0,20))try{const e=await this.holosphere.getFederation(s);e&&t.push({holon:s,federations:e.federation||[],notifies:e.notify||[]})}catch{}const n=`Analyze a federation network to identify bridge holons (connectors between clusters).\n\nNetwork:\n${JSON.stringify(t,null,2)}\n\nIdentify:\n1. Bridge holons that connect clusters\n2. Isolated holons\n3. Central hubs\n4. Network clusters\n\nReturn JSON:\n{\n "bridges": [{"holon": "id", "connects": ["cluster1", "cluster2"]}],\n "isolated": ["holon_id"],\n "hubs": [{"holon": "id", "connections": n}],\n "clusters": [["holon1", "holon2"]],\n "network_health": 0.0-1.0\n}`;return this.llm.getJSON(n,"",{temperature:.3})}}class qo{constructor(e,t=null,n=null){this.llm=e,this.holosphere=t,this.embeddings=n}setHoloSphere(e){this.holosphere=e}setEmbeddings(e){this.embeddings=e}async discoverRelationships(e,t=null){if(!this.holosphere)throw new Error("HoloSphere instance required");let n=[];const s=t?[t]:["projects","quests","events","resources","default"];for(const i of s)try{const t=await this.holosphere.getAll(e,i);n.push(...t.map(e=>({...e,_lens:i})))}catch{}if(n.length<2)return{holon:e,relationships:[],message:"Not enough data for relationship discovery"};const r=`You are a relationship discovery expert. Find hidden connections between items in this dataset.\n\nRegion: ${e}\nItems: ${n.length}\n\nLook for:\n1. Thematic connections (shared topics, goals)\n2. Entity connections (shared people, organizations)\n3. Temporal connections (same timeframes)\n4. Causal connections (one enables/requires another)\n5. Geographic connections (same sub-regions)\n\nReturn JSON:\n{\n "relationships": [\n {\n "item1": {"id": "id1", "title": "title"},\n "item2": {"id": "id2", "title": "title"},\n "type": "thematic|entity|temporal|causal|geographic",\n "strength": 0.0-1.0,\n "description": "relationship description"\n }\n ],\n "clusters": [\n {\n "theme": "cluster theme",\n "items": ["id1", "id2"]\n }\n ],\n "key_entities": ["entity1", "entity2"],\n "summary": "overview of relationship network"\n}`,a=await this.llm.getJSON(r,JSON.stringify(n.slice(0,40),null,2),{temperature:.3});return{holon:e,lens:t,itemCount:n.length,relationships:a,timestamp:Date.now()}}async findSimilar(e,t=null,n=null,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{limit:r=10,threshold:a=.5,useEmbeddings:i=!0}=s;if(i&&this.embeddings&&t&&n)return this.embeddings.findSimilar(e,t,n,{limit:r,threshold:a});if(!t)throw new Error("Holon required for LLM-based similarity");const o=n?[n]:["projects","quests","events","resources","default"];let f=[];for(const l of o)try{const e=await this.holosphere.getAll(t,l);f.push(...e.map(e=>({...e,_lens:l})))}catch{}if(0===f.length)return[];const c=`Find items most similar to the reference item.\n\nReference item:\n${JSON.stringify(e,null,2)}\n\nConsider:\n1. Topic/theme similarity\n2. Goal alignment\n3. Participant overlap\n4. Resource requirements\n5. Timeline compatibility\n\nReturn JSON array of similar items with similarity scores:\n[\n {\n "item": {item object},\n "similarity": 0.0-1.0,\n "reasons": ["reason1"]\n }\n]\n\nOrder by similarity descending. Max ${r} items with similarity >= ${a}.`;return(await this.llm.getJSON(c,JSON.stringify(f.slice(0,50),null,2),{temperature:.2})).slice(0,r).filter(e=>e.similarity>=a)}async buildGraph(e,t){const n=await this.discoverRelationships(e,t),s=new Map,r=[];for(const a of n.relationships?.relationships||[])s.has(a.item1.id)||s.set(a.item1.id,{id:a.item1.id,label:a.item1.title}),s.has(a.item2.id)||s.set(a.item2.id,{id:a.item2.id,label:a.item2.title}),r.push({source:a.item1.id,target:a.item2.id,type:a.type,weight:a.strength});return{nodes:Array.from(s.values()),edges:r,clusters:n.relationships?.clusters||[]}}async findCrossHolonRelationships(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required");const n={};for(const r of e.slice(0,5))try{const e=await this.holosphere.getAll(r,t);e.length>0&&(n[r]=e.slice(0,15))}catch{}if(Object.keys(n).length<2)return{message:"Need at least 2 holons with data"};const s=`Find relationships between items across different geographic regions.\n\nRegions and their data:\n${JSON.stringify(n,null,2)}\n\nIdentify:\n1. Cross-region collaborations\n2. Shared themes across regions\n3. Potential synergies\n4. Knowledge transfer opportunities\n\nReturn JSON:\n{\n "cross_relationships": [\n {\n "holon1": "id",\n "item1": "item_id",\n "holon2": "id",\n "item2": "item_id",\n "type": "type",\n "potential": "collaboration|knowledge_share|synergy"\n }\n ],\n "shared_themes": [{"theme": "theme", "holons": ["id1", "id2"]}],\n "opportunities": ["opp1"]\n}`;return this.llm.getJSON(s,"",{temperature:.4})}async suggestConnections(e,t,n){const s=await this.findSimilar(e,t,n,{limit:10}),r=`Based on similar items found, suggest specific actions to create connections.\n\nReference item:\n${JSON.stringify(e,null,2)}\n\nSimilar items found:\n${JSON.stringify(s,null,2)}\n\nSuggest:\n1. Collaboration opportunities\n2. Resource sharing possibilities\n3. Joint initiatives\n4. Knowledge exchange\n\nReturn JSON:\n{\n "collaborations": [{"with": "item_id", "action": "suggested action"}],\n "resource_sharing": [{"items": ["id1", "id2"], "resource": "what to share"}],\n "initiatives": [{"description": "joint initiative", "participants": ["id1"]}],\n "knowledge_exchange": [{"from": "id", "to": "id", "topic": "topic"}]\n}`;return this.llm.getJSON(r,"",{temperature:.5})}async detectPatterns(e,t){const n=await this.discoverRelationships(e,t),s=`Analyze relationships and detect higher-level patterns.\n\nRelationships:\n${JSON.stringify(n.relationships,null,2)}\n\nDetect:\n1. Hub-spoke patterns (central connectors)\n2. Cluster patterns (tight groups)\n3. Bridge patterns (connecting different groups)\n4. Chain patterns (sequential relationships)\n5. Cyclical patterns (mutual dependencies)\n\nReturn JSON:\n{\n "patterns": [\n {\n "type": "hub|cluster|bridge|chain|cycle",\n "description": "pattern description",\n "items": ["id1", "id2"],\n "significance": "why this matters"\n }\n ],\n "network_structure": "description of overall structure",\n "recommendations": ["rec1"]\n}`;return this.llm.getJSON(s,"",{temperature:.3})}}class Jo{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async breakdown(e,t,n,s={}){if(!e||!e.id)throw new Error("Item must have an id property");const{depth:r=2,stepsPerLevel:a={min:3,max:5},useContext:i=!0,storeResults:o=!0,dependencyField:f="dependencies",parentField:c="parent"}=s,l="number"==typeof a?{min:a,max:a}:a;let u=[];if(i&&this.holosphere)try{u=(await this.holosphere.getAll(t,n)).filter(t=>t.id!==e.id).slice(0,10)}catch{}let d=null;if(this.holosphere)try{d=await this.holosphere.getSchema(n)}catch{}const p=await this._breakdownRecursive(e,t,n,r,l,u,d,f,c,o,0);return{original:e,holonId:t,lensName:n,breakdown:p,totalSubtasks:this._countSubtasks(p),maxDepth:r,timestamp:Date.now()}}async _breakdownRecursive(e,t,n,s,r,a,i,o,f,c,l){if(l>=s)return{item:e,children:[],depth:l};const u=await this._generateSubtasks(e,a,i,r,o,f);if(c&&this.holosphere&&u.length>0){for(const e of u)try{await this.holosphere.write(t,n,e)}catch(p){console.warn(`Failed to store subtask ${e.id}:`,p.message)}if(e._meta?.childTasks!==u.map(e=>e.id))try{await this.holosphere.update(t,n,e.id,{_meta:{...e._meta,childTasks:u.map(e=>e.id),breakdownTimestamp:Date.now()}})}catch{}}const d=[];for(const h of u){const e=await this._breakdownRecursive(h,t,n,s,r,a,i,o,f,c,l+1);d.push(e)}return{item:e,children:d,depth:l}}async _generateSubtasks(e,t,n,s,r,a){const{min:i,max:o}=s,f=`You are a task decomposition expert. Break down the given task/quest into ${i}-${o} concrete, actionable subtasks.\n\nEach subtask should:\n1. Be a clear, specific action\n2. Be smaller and more manageable than the parent\n3. Together with siblings, fully accomplish the parent task\n4. Have a unique ID (format: parentId-1, parentId-2, etc.)\n5. Reference the parent task in the "${a}" field\n6. List any dependencies on sibling tasks in "${r}" array\n\n${n?`Follow this schema structure:\n${JSON.stringify(n,null,2)}`:""}\n\n${t.length>0?`Consider these existing items for context and avoid duplication:\n${JSON.stringify(t.slice(0,5),null,2)}`:""}\n\nReturn a JSON array of subtasks. Each subtask must have:\n- id: unique identifier (parentId-1, parentId-2, etc.)\n- title/name: clear action title\n- description: what needs to be done\n- ${a}: reference to parent id\n- ${r}: array of sibling task ids this depends on (empty if first task)\n- status: "pending"\n- Any other relevant fields from the parent schema\n\nExample output format:\n[\n {\n "id": "parent-1",\n "title": "First subtask",\n "description": "Details...",\n "${a}": "parentId",\n "${r}": [],\n "status": "pending"\n },\n {\n "id": "parent-2",\n "title": "Second subtask (depends on first)",\n "description": "Details...",\n "${a}": "parentId",\n "${r}": ["parent-1"],\n "status": "pending"\n }\n]`,c=`Break down this task into ${i}-${o} subtasks:\n\n${JSON.stringify(e,null,2)}`;try{return(await this.llm.getJSON(f,c,{temperature:.4,maxTokens:2e3})).map((t,n)=>({...t,id:t.id||`${e.id}-${n+1}`,[a]:e.id,[r]:t[r]||[],status:t.status||"pending",_meta:{...t._meta,generatedFrom:e.id,generatedAt:Date.now(),depth:(e._meta?.depth||0)+1}}))}catch(l){return console.error("Failed to generate subtasks:",l),[]}}_countSubtasks(e){return e.children&&0!==e.children.length?e.children.length+e.children.reduce((e,t)=>e+this._countSubtasks(t),0):0}flatten(e){const t=[],n=e=>{if(e.item&&t.push(e.item),e.children)for(const t of e.children)n(t)};return e.breakdown&&n(e.breakdown),t}getDependencyOrder(e){return this.flatten(e).sort((e,t)=>{const n=e._meta?.depth||0,s=t._meta?.depth||0;if(n!==s)return n-s;if((t.dependencies||[]).includes(e.id))return-1;return(e.dependencies||[]).includes(t.id)?1:0})}async suggestStrategy(e){return this.llm.getJSON('You are a task decomposition expert. Analyze this task and suggest the best breakdown strategy.\n\nConsider:\n1. Task complexity\n2. Recommended depth (1-4 levels)\n3. Recommended subtasks per level (2-7)\n4. Key areas to focus on\n5. Potential dependencies between subtasks\n\nReturn JSON:\n{\n "complexity": "simple|moderate|complex|very_complex",\n "recommendedDepth": n,\n "recommendedStepsPerLevel": {"min": n, "max": n},\n "focusAreas": ["area1", "area2"],\n "potentialChallenges": ["challenge1"],\n "estimatedTotalSubtasks": n,\n "reasoning": "explanation"\n}',JSON.stringify(e,null,2),{temperature:.3})}async rebalance(e,t={}){const{targetStepsPerLevel:n={min:3,max:5}}=t,s=this.flatten(e),r=`You are a task organization expert. Rebalance these tasks to have ${n.min}-${n.max} items per level.\n\nCurrent tasks:\n${JSON.stringify(s,null,2)}\n\nReorganize by:\n1. Merging tasks that are too granular\n2. Splitting tasks that are too large\n3. Maintaining proper dependency chains\n4. Keeping the same overall scope\n\nReturn JSON with the rebalanced structure:\n{\n "tasks": [...],\n "changes": [{"type": "merge|split|move", "description": "..."}],\n "summary": "what changed"\n}`;return this.llm.getJSON(r,"",{temperature:.3})}async getProgress(e,t,n){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t),r=s.find(e=>e.id===n);if(!r)throw new Error(`Item ${n} not found`);const a=this._findDescendants(n,s),i=a.length,o=a.filter(e=>"completed"===e.status||"done"===e.status).length,f=a.filter(e=>"in_progress"===e.status||"active"===e.status).length,c=i-o-f;return{itemId:n,title:r.title||r.name,total:i,completed:o,inProgress:f,pending:c,percentComplete:i>0?Math.round(o/i*100):0,blockers:this._findBlockers(a),nextUp:this._findNextTasks(a)}}_findDescendants(e,t,n="parent"){const s=[],r=t.filter(t=>t[n]===e);for(const a of r)s.push(a),s.push(...this._findDescendants(a.id,t,n));return s}_findBlockers(e,t="dependencies"){return e.filter(n=>{const s=n[t]||[];return 0!==s.length&&s.some(t=>{const n=e.find(e=>e.id===t);return n&&"completed"!==n.status&&"done"!==n.status})}).map(e=>({id:e.id,title:e.title||e.name,blockedBy:e[t]}))}_findNextTasks(e,t="dependencies"){return e.filter(n=>{if("completed"===n.status||"done"===n.status)return!1;if("in_progress"===n.status||"active"===n.status)return!1;const s=n[t]||[];return 0===s.length||s.every(t=>{const n=e.find(e=>e.id===t);return!n||"completed"===n.status||"done"===n.status})}).slice(0,5).map(e=>({id:e.id,title:e.title||e.name,description:e.description}))}}class Go{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async suggestResolution(e,t={}){const{currentResolution:n=null,context:s=null}=t,r=`You are a geospatial planning expert. Analyze this item and suggest the optimal H3 hexagonal resolution (0-15) for organizing it.\n\nH3 Resolution Guide:\n- Resolution 0-2: Continental/country scale (thousands of km)\n- Resolution 3-4: Regional/state scale (hundreds of km)\n- Resolution 5-6: Metropolitan/city scale (tens of km)\n- Resolution 7-8: District/neighborhood scale (km)\n- Resolution 9-10: Block/street scale (hundreds of meters)\n- Resolution 11-12: Building/lot scale (tens of meters)\n- Resolution 13-15: Room/precise scale (meters)\n\nConsider:\n1. Geographic scope mentioned in the item\n2. Number of potential participants/stakeholders\n3. Type of activity (local vs regional)\n4. Resource requirements and logistics\n5. Similar projects' typical scale\n\n${null!==n?`Current resolution: ${n}`:""}\n${s?`Context:\n${JSON.stringify(s,null,2)}`:""}\n\nReturn JSON:\n{\n "recommendedResolution": n,\n "reasoning": "why this resolution",\n "alternativeResolutions": [{"resolution": n, "useCase": "when to use"}],\n "geographicScope": "description of area covered",\n "scaleSuggestions": {\n "expansion": {"resolution": n, "reason": "when to expand"},\n "contraction": {"resolution": n, "reason": "when to focus"}\n }\n}`;return this.llm.getJSON(r,JSON.stringify(e,null,2),{temperature:.3})}async analyzeDistribution(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{includeChildren:s=!0,maxChildren:a=20}=n,i=await this.holosphere.getAll(e,t),o={};if(s&&r.isValidCell(e)){const n=r.getResolution(e);if(n<15){const s=r.cellToChildren(e,n+1);for(const e of s.slice(0,a))try{const n=await this.holosphere.getAll(e,t);n.length>0&&(o[e]={count:n.length,sample:n.slice(0,3)})}catch{}}}const f=`You are a geospatial analyst. Analyze the distribution of data across this H3 hexagonal region.\n\nParent holon: ${e}\nResolution: ${r.isValidCell(e)?r.getResolution(e):"N/A"}\nParent data count: ${i.length}\nChildren with data: ${Object.keys(o).length}\n\nAnalyze:\n1. Data density and distribution patterns\n2. Geographic hotspots and cold spots\n3. Coverage gaps\n4. Clustering patterns\n5. Recommendations for better coverage\n\nReturn JSON:\n{\n "distribution": {\n "pattern": "clustered|uniform|sparse|concentrated",\n "density": "high|medium|low",\n "coverage": 0.0-1.0\n },\n "hotspots": [{"holonId": "id", "reason": "why"}],\n "gaps": [{"description": "gap description", "suggestedAction": "what to do"}],\n "clusters": [{"theme": "cluster theme", "holons": ["id1"]}],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`,c=`Parent data sample:\n${JSON.stringify(i.slice(0,10),null,2)}\n\nChildren distribution:\n${JSON.stringify(o,null,2)}`,l=await this.llm.getJSON(f,c,{temperature:.3});return{holonId:e,lensName:t,resolution:r.isValidCell(e)?r.getResolution(e):null,parentDataCount:i.length,childrenAnalyzed:Object.keys(o).length,analysis:l,timestamp:Date.now()}}async findNeighborRelevance(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(e))throw new Error("Invalid H3 cell");const{ringSize:s=1,relevanceThreshold:a=.5}=n,i=await this.holosphere.getAll(e,t),o=r.gridDisk(e,s).filter(t=>t!==e),f={};for(const r of o)try{const e=await this.holosphere.getAll(r,t);e.length>0&&(f[r]=e.slice(0,5))}catch{}if(0===Object.keys(f).length)return{holonId:e,neighbors:[],message:"No data found in neighboring cells"};const c=`You are a geospatial relevance analyst. Find items in neighboring H3 cells that are relevant to the center cell's data.\n\nCenter cell: ${e}\nRing size: ${s} (immediate neighbors)\n\nConsider:\n1. Thematic overlap\n2. Potential collaborations\n3. Shared resources\n4. Cross-boundary projects\n5. Geographic continuity of activities\n\nReturn JSON:\n{\n "relevantNeighbors": [\n {\n "holonId": "neighbor_id",\n "relevanceScore": 0.0-1.0,\n "relevantItems": [{"id": "item_id", "reason": "why relevant"}],\n "collaborationPotential": "description"\n }\n ],\n "crossBoundaryOpportunities": [\n {\n "description": "opportunity",\n "involvedHolons": ["id1", "id2"],\n "suggestedAction": "what to do"\n }\n ],\n "geographicPatterns": ["pattern1"],\n "summary": "overview"\n}`,l=`Center cell data:\n${JSON.stringify(i.slice(0,10),null,2)}\n\nNeighbor data:\n${JSON.stringify(f,null,2)}`,u=await this.llm.getJSON(c,l,{temperature:.4});return u.relevantNeighbors&&(u.relevantNeighbors=u.relevantNeighbors.filter(e=>e.relevanceScore>=a)),{holonId:e,lensName:t,ringSize:s,neighborsAnalyzed:Object.keys(f).length,analysis:u,timestamp:Date.now()}}async suggestGeographicScope(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(t))throw new Error("Invalid H3 cell");const a=r.getResolution(t);let i=[];if(a>0){const e=r.cellToParent(t,a-1);try{i=await this.holosphere.getAll(e,n)}catch{}}let o=[];if(a<15){const e=r.cellToChildren(t,a+1);for(const t of e.slice(0,7))try{const e=await this.holosphere.getAll(t,n);o.push(...e.slice(0,2))}catch{}}const f=`You are a geographic scope advisor. Analyze whether this item should expand to a larger region (parent holon) or focus on smaller sub-regions (children holons).\n\nCurrent holon: ${t}\nCurrent resolution: ${a}\n\nFactors to consider:\n1. Item's stated scope and goals\n2. Current participation/activity level\n3. Resource requirements\n4. Similar activities in parent/children\n5. Natural geographic boundaries\n\nReturn JSON:\n{\n "currentScopeAssessment": {\n "appropriate": true/false,\n "reasoning": "why"\n },\n "expansionRecommendation": {\n "recommended": true/false,\n "targetResolution": n,\n "reasoning": "why expand",\n "benefits": ["benefit1"],\n "risks": ["risk1"]\n },\n "contractionRecommendation": {\n "recommended": true/false,\n "targetResolution": n,\n "reasoning": "why contract",\n "suggestedFocusAreas": ["description"],\n "benefits": ["benefit1"],\n "risks": ["risk1"]\n },\n "optimalAction": "expand|contract|maintain",\n "summary": "recommendation summary"\n}`,c=`Item to analyze:\n${JSON.stringify(e,null,2)}\n\nParent region data (${i.length} items):\n${JSON.stringify(i.slice(0,5),null,2)}\n\nChildren regions data (${o.length} items):\n${JSON.stringify(o.slice(0,5),null,2)}`;return this.llm.getJSON(f,c,{temperature:.3})}async analyzeCoverage(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(e))throw new Error("Invalid H3 cell");const{targetResolution:s=null}=n,a=r.getResolution(e),i=s||Math.min(a+1,15),o=r.cellToChildren(e,i),f={total:o.length,withData:0,withoutData:0,dataDistribution:{}},c=[],l=[];for(const r of o)try{const e=await this.holosphere.getAll(r,t);e.length>0?(f.withData++,f.dataDistribution[r]=e.length,c.push({holon:r,count:e.length})):(f.withoutData++,l.push(r))}catch{f.withoutData++,l.push(r)}const u=`You are a geographic coverage analyst. Analyze the data coverage in this H3 region.\n\nRegion: ${e}\nResolution: ${a}\nChild resolution analyzed: ${i}\nTotal children: ${f.total}\nChildren with data: ${f.withData}\nChildren without data: ${f.withoutData}\nCoverage ratio: ${(f.withData/f.total*100).toFixed(1)}%\n\nAnalyze:\n1. Coverage patterns\n2. Potential reasons for gaps\n3. Priority areas for expansion\n4. Whether gaps are concerning or expected\n\nReturn JSON:\n{\n "coverageScore": 0.0-1.0,\n "coverageQuality": "excellent|good|moderate|poor|minimal",\n "patterns": {\n "type": "clustered|scattered|peripheral|central|uniform",\n "description": "pattern description"\n },\n "gaps": {\n "count": n,\n "significance": "high|medium|low",\n "likelyReasons": ["reason1"],\n "priorityAreas": ["description of areas to focus"]\n },\n "recommendations": [\n {\n "action": "what to do",\n "priority": "high|medium|low",\n "targetArea": "description"\n }\n ],\n "summary": "overview"\n}`,d=await this.llm.getJSON(u,"",{temperature:.3});return{holonId:e,lensName:t,resolution:a,childResolution:i,coverage:{...f,ratio:f.withData/f.total},childrenWithData:c.slice(0,10),gapCount:l.length,analysis:d,timestamp:Date.now()}}async crossResolutionInsights(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(e))throw new Error("Invalid H3 cell");const{levels:s=3}=n,a=r.getResolution(e),i={},o=await this.holosphere.getAll(e,t);i[a]={holon:e,count:o.length,sample:o.slice(0,5)};let f=e;for(let l=0;l<s&&r.getResolution(f)>0;l++){const e=r.getResolution(f)-1;f=r.cellToParent(f,e);try{const n=await this.holosphere.getAll(f,t);i[e]={holon:f,count:n.length,sample:n.slice(0,5)}}catch{}}if(a<15){const n=a+1,s=r.cellToChildren(e,n);let o=0;const f=[];for(const e of s.slice(0,7))try{const n=await this.holosphere.getAll(e,t);o+=n.length,n.length>0&&f.push(...n.slice(0,2))}catch{}i[n]={holon:`${s.length} children`,count:o,sample:f.slice(0,5)}}const c=`You are a multi-scale geographic analyst. Find patterns that emerge across different H3 resolutions.\n\nStarting holon: ${e}\nResolutions analyzed: ${Object.keys(i).sort().join(", ")}\n\nData at each resolution:\n${JSON.stringify(i,null,2)}\n\nAnalyze:\n1. How themes evolve across scales\n2. What appears only at certain resolutions\n3. Aggregation patterns (local vs regional)\n4. Scale-dependent opportunities\n5. Optimal resolution for different activities\n\nReturn JSON:\n{\n "scalePatterns": [\n {\n "pattern": "description",\n "visibleAt": [resolution_numbers],\n "significance": "why this matters"\n }\n ],\n "themeEvolution": {\n "localThemes": ["themes at fine resolution"],\n "regionalThemes": ["themes at coarse resolution"],\n "consistentThemes": ["themes across all scales"]\n },\n "optimalResolutions": {\n "forCollaboration": n,\n "forResources": n,\n "forCommunity": n,\n "reasoning": "why"\n },\n "insights": ["insight1"],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`;return this.llm.getJSON(c,"",{temperature:.4})}async suggestMigration(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(t))throw new Error("Invalid H3 cell");const{searchRadius:a=2}=s,i=r.gridDisk(t,a),o={};for(const r of i)if(r!==t)try{const e=await this.holosphere.getAll(r,n);e.length>0&&(o[r]={count:e.length,sample:e.slice(0,3)})}catch{}const f=r.getResolution(t);let c=null;if(f>0){const e=r.cellToParent(t,f-1);try{const t=await this.holosphere.getAll(e,n);c={holon:e,count:t.length,sample:t.slice(0,3)}}catch{}}const l=`You are a geographic placement advisor. Determine if this item would be better suited in a different H3 cell.\n\nCurrent location: ${t}\nCurrent resolution: ${f}\n\nConsider:\n1. Thematic fit with existing data in each cell\n2. Geographic scope of the item\n3. Collaboration opportunities\n4. Resource proximity\n5. Community alignment\n\nReturn JSON:\n{\n "currentFit": {\n "score": 0.0-1.0,\n "reasoning": "why current location is/isn't appropriate"\n },\n "migrationRecommended": true/false,\n "suggestedDestinations": [\n {\n "holonId": "cell_id",\n "fitScore": 0.0-1.0,\n "reasoning": "why this location",\n "benefits": ["benefit1"],\n "drawbacks": ["drawback1"]\n }\n ],\n "stayReasons": ["reason to stay if applicable"],\n "moveReasons": ["reason to move if applicable"],\n "recommendation": "stay|move|duplicate",\n "summary": "final recommendation"\n}`,u=`Item to place:\n${JSON.stringify(e,null,2)}\n\nNearby cells with data:\n${JSON.stringify(o,null,2)}\n\n${c?`Parent cell data:\n${JSON.stringify(c,null,2)}`:""}`;return this.llm.getJSON(l,u,{temperature:.3})}async generateGeographicReport(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{lenses:n=["projects","quests","events","resources","default"]}=t,s={};for(const r of n)try{const t=await this.holosphere.getAll(e,r);t.length>0&&(s[r]={count:t.length,sample:t.slice(0,5)})}catch{}let a={};if(r.isValidCell(e)){const t=r.getResolution(e),[n,s]=r.cellToLatLng(e),i=r.cellToBoundary(e);a={resolution:t,center:{lat:n,lng:s},areaKm2:r.cellArea(e,"km2"),vertexCount:i.length}}const i=`You are a regional activity reporter. Generate a comprehensive report on geographic activity in this H3 region.\n\nRegion: ${e}\nGeographic context: ${JSON.stringify(a,null,2)}\nData available in ${Object.keys(s).length} categories\n\nGenerate a report covering:\n1. Executive summary\n2. Activity overview by category\n3. Key highlights and achievements\n4. Geographic patterns\n5. Opportunities and challenges\n6. Recommendations\n\nReturn JSON:\n{\n "title": "Region Report Title",\n "executiveSummary": "2-3 sentence overview",\n "activityOverview": {\n "totalItems": n,\n "categorySummaries": {"lens": "summary"}\n },\n "highlights": [\n {"title": "highlight", "description": "details", "category": "lens"}\n ],\n "geographicPatterns": ["pattern1"],\n "strengths": ["strength1"],\n "challenges": ["challenge1"],\n "opportunities": ["opportunity1"],\n "recommendations": [\n {"priority": "high|medium|low", "action": "what to do", "rationale": "why"}\n ],\n "metrics": {\n "activityLevel": "high|medium|low",\n "diversity": "high|medium|low",\n "growth": "growing|stable|declining"\n }\n}`,o=await this.llm.getJSON(i,JSON.stringify(s,null,2),{temperature:.4,maxTokens:2e3});return{holonId:e,geoContext:a,lensesAnalyzed:Object.keys(s),totalItems:Object.values(s).reduce((e,t)=>e+t.count,0),report:o,timestamp:Date.now()}}async findGeographicClusters(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!r.isValidCell(e))throw new Error("Invalid H3 cell");const{clusterResolution:s=null}=n,a=r.getResolution(e),i=s||Math.min(a+1,15),o=r.cellToChildren(e,i),f={};for(const r of o)try{const e=await this.holosphere.getAll(r,t);e.length>0&&(f[r]=e)}catch{}if(Object.keys(f).length<2)return{holonId:e,clusters:[],message:"Not enough data for clustering"};const c=`You are a geographic clustering expert. Find thematic clusters in this spatial data.\n\nRegion: ${e}\nResolution analyzed: ${i}\nCells with data: ${Object.keys(f).length}\n\nIdentify:\n1. Thematic clusters (cells with similar content)\n2. Activity clusters (cells with related activities)\n3. Isolated cells (unique content)\n4. Potential connections between clusters\n\nReturn JSON:\n{\n "clusters": [\n {\n "name": "cluster name",\n "theme": "what unifies this cluster",\n "cells": ["cell_id1", "cell_id2"],\n "strength": 0.0-1.0,\n "characteristics": ["char1"]\n }\n ],\n "isolatedCells": [\n {"cellId": "id", "uniqueAspect": "what makes it unique"}\n ],\n "interClusterConnections": [\n {"cluster1": "name", "cluster2": "name", "connection": "how related"}\n ],\n "spatialPatterns": ["pattern1"],\n "recommendations": ["rec1"]\n}`,l=await this.llm.getJSON(c,JSON.stringify(f,null,2),{temperature:.4});return{holonId:e,lensName:t,clusterResolution:i,cellsAnalyzed:Object.keys(f).length,analysis:l,timestamp:Date.now()}}async analyzeGeographicImpact(e,t,n,s={}){if(!r.isValidCell(t))throw new Error("Invalid H3 cell");const a=r.getResolution(t),[i,o]=r.cellToLatLng(t),f=r.cellArea(t,"km2");let c=null;if(a>0){const e=r.cellToParent(t,Math.max(0,a-2));c={holon:e,resolution:a-2,areaKm2:r.cellArea(e,"km2")}}const l=`You are a geographic impact analyst. Analyze the geographic reach and impact of this item.\n\nItem location: ${t}\nResolution: ${a}\nCenter: ${i.toFixed(4)}, ${o.toFixed(4)}\nArea: ${f.toFixed(2)} km²\n\n${c?`Broader region: ${c.areaKm2.toFixed(2)} km²`:""}\n\nAnalyze:\n1. Direct impact area (immediate cell)\n2. Indirect impact area (spillover effects)\n3. Potential reach (if expanded)\n4. Geographic barriers/enablers\n5. Network effects\n\nReturn JSON:\n{\n "directImpact": {\n "areaKm2": n,\n "description": "direct impact area",\n "affectedPopulation": "estimate or N/A"\n },\n "indirectImpact": {\n "estimatedReach": n,\n "mechanisms": ["how impact spreads"],\n "neighboringAreas": ["affected areas"]\n },\n "potentialReach": {\n "ifExpanded": {\n "maxAreaKm2": n,\n "optimalResolution": n,\n "limitingFactors": ["factor1"]\n }\n },\n "geographicFactors": {\n "enablers": ["what helps geographic spread"],\n "barriers": ["what limits spread"]\n },\n "impactScore": {\n "local": 0.0-1.0,\n "regional": 0.0-1.0,\n "network": 0.0-1.0\n },\n "recommendations": ["how to increase impact"],\n "summary": "impact overview"\n}`;return this.llm.getJSON(l,JSON.stringify(e,null,2),{temperature:.3})}}const zo={ethereum:{name:"Ethereum Mainnet",chainId:1,rpc:"https://eth.llamarpc.com",explorer:"https://etherscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"mainnet"},polygon:{name:"Polygon Mainnet",chainId:137,rpc:"https://polygon-rpc.com",explorer:"https://polygonscan.com",currency:{name:"MATIC",symbol:"MATIC",decimals:18},type:"mainnet"},arbitrum:{name:"Arbitrum One",chainId:42161,rpc:"https://arb1.arbitrum.io/rpc",explorer:"https://arbiscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"mainnet"},base:{name:"Base",chainId:8453,rpc:"https://mainnet.base.org",explorer:"https://basescan.org",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"mainnet"},optimism:{name:"Optimism",chainId:10,rpc:"https://mainnet.optimism.io",explorer:"https://optimistic.etherscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"mainnet"},avalanche:{name:"Avalanche C-Chain",chainId:43114,rpc:"https://api.avax.network/ext/bc/C/rpc",explorer:"https://snowtrace.io",currency:{name:"AVAX",symbol:"AVAX",decimals:18},type:"mainnet"},bsc:{name:"BNB Smart Chain",chainId:56,rpc:"https://bsc-dataseed.binance.org",explorer:"https://bscscan.com",currency:{name:"BNB",symbol:"BNB",decimals:18},type:"mainnet"},sepolia:{name:"Sepolia",chainId:11155111,rpc:"https://rpc.sepolia.org",explorer:"https://sepolia.etherscan.io",currency:{name:"Sepolia ETH",symbol:"ETH",decimals:18},type:"testnet",faucet:"https://sepoliafaucet.com"},goerli:{name:"Goerli",chainId:5,rpc:"https://rpc.goerli.eth.gateway.fm",explorer:"https://goerli.etherscan.io",currency:{name:"Goerli ETH",symbol:"ETH",decimals:18},type:"testnet",faucet:"https://goerlifaucet.com"},mumbai:{name:"Polygon Mumbai",chainId:80001,rpc:"https://rpc-mumbai.maticvigil.com",explorer:"https://mumbai.polygonscan.com",currency:{name:"MATIC",symbol:"MATIC",decimals:18},type:"testnet",faucet:"https://faucet.polygon.technology"},amoy:{name:"Polygon Amoy",chainId:80002,rpc:"https://rpc-amoy.polygon.technology",explorer:"https://amoy.polygonscan.com",currency:{name:"MATIC",symbol:"MATIC",decimals:18},type:"testnet",faucet:"https://faucet.polygon.technology"},arbitrumSepolia:{name:"Arbitrum Sepolia",chainId:421614,rpc:"https://sepolia-rollup.arbitrum.io/rpc",explorer:"https://sepolia.arbiscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"testnet"},baseSepolia:{name:"Base Sepolia",chainId:84532,rpc:"https://sepolia.base.org",explorer:"https://sepolia.basescan.org",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"testnet"},optimismSepolia:{name:"Optimism Sepolia",chainId:11155420,rpc:"https://sepolia.optimism.io",explorer:"https://sepolia-optimism.etherscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"testnet"},hardhat:{name:"Hardhat Local",chainId:31337,rpc:"http://127.0.0.1:8545",explorer:null,currency:{name:"Ether",symbol:"ETH",decimals:18},type:"local"},anvil:{name:"Anvil Local",chainId:31337,rpc:"http://127.0.0.1:8545",explorer:null,currency:{name:"Ether",symbol:"ETH",decimals:18},type:"local"},ganache:{name:"Ganache Local",chainId:1337,rpc:"http://127.0.0.1:7545",explorer:null,currency:{name:"Ether",symbol:"ETH",decimals:18},type:"local"}};function Wo(e){if("string"==typeof e)return zo[e]||null;for(const[t,n]of Object.entries(zo))if(n.chainId===e)return{...n,key:t};return null}function Ko(e){return Object.fromEntries(Object.entries(zo).filter(([t,n])=>n.type===e))}function Vo(){return Object.keys(zo)}function Zo(e){return e in zo}function Yo(e,t){const n=zo[e];return n?.explorer?`${n.explorer}/tx/${t}`:null}function Xo(e,t){const n=zo[e];return n?.explorer?`${n.explorer}/address/${t}`:null}const Qo=Object.freeze(Object.defineProperty({__proto__:null,NETWORKS:zo,default:zo,getAddressUrl:Xo,getNetwork:Wo,getNetworksByType:Ko,getTxUrl:Yo,isNetworkSupported:Zo,listNetworks:Vo},Symbol.toStringTag,{value:"Module"}));class ef{constructor(e={}){this.config=e,this.provider=null,this.signer=null,this.network=null,this.networkName=null,this.ethers=null,this._initialized=!1}async _loadEthers(){if(!this.ethers){const e=await Promise.resolve().then(()=>require("./index-Bwg3OzRM.cjs"));this.ethers=e}return this.ethers}async connect(e,t,n){const s=await this._loadEthers();if(!Zo(e)&&!n)throw new Error(`Unsupported network: ${e}. Use a custom rpcUrl or choose from: ${Object.keys(zo).join(", ")}`);const r=Wo(e)||{chainId:0,name:e},a=n||r.rpc;if(this.provider=new s.JsonRpcProvider(a,{chainId:r.chainId,name:r.name}),await this.provider.ready,this.network=await this.provider.getNetwork(),this.networkName=e,t){const e=t.startsWith("0x")?t:`0x${t}`;this.signer=new s.Wallet(e,this.provider)}return this._initialized=!0,{provider:this.provider,signer:this.signer,network:this.network,networkName:this.networkName,config:r}}async connectBrowser(e){const t=await this._loadEthers();if("undefined"==typeof window||!window.ethereum)throw new Error("No browser wallet detected. Please install MetaMask or another Web3 wallet.");if(await window.ethereum.request({method:"eth_requestAccounts"}),this.provider=new t.BrowserProvider(window.ethereum),this.signer=await this.provider.getSigner(),this.network=await this.provider.getNetwork(),e&&Zo(e)){const t=Wo(e);this.network.chainId!==BigInt(t.chainId)&&await this.switchNetwork(e)}const n=await this.signer.getAddress();return this._initialized=!0,{provider:this.provider,signer:this.signer,network:this.network,address:n}}async switchNetwork(e){if("undefined"==typeof window||!window.ethereum)throw new Error("Network switching requires a browser wallet");const t=Wo(e);if(!t)throw new Error(`Unknown network: ${e}`);const n="0x"+t.chainId.toString(16);try{await window.ethereum.request({method:"wallet_switchEthereumChain",params:[{chainId:n}]})}catch(r){if(4902!==r.code)throw r;await window.ethereum.request({method:"wallet_addEthereumChain",params:[{chainId:n,chainName:t.name,nativeCurrency:t.currency,rpcUrls:[t.rpc],blockExplorerUrls:t.explorer?[t.explorer]:[]}]})}const s=await this._loadEthers();this.provider=new s.BrowserProvider(window.ethereum),this.signer=await this.provider.getSigner(),this.network=await this.provider.getNetwork(),this.networkName=e}getProvider(){return this._requireInitialized(),this.provider}getSigner(){if(this._requireInitialized(),!this.signer)throw new Error("No signer available. Connect with a private key or use connectBrowser().");return this.signer}async getAddress(){return this.getSigner().getAddress()}async getBalance(e){this._requireInitialized();const t=await this._loadEthers(),n=e||(this.signer?await this.signer.getAddress():null);if(!n)throw new Error("No address provided and no signer available");const s=await this.provider.getBalance(n);return t.formatEther(s)}getNetworkConfig(){return this._requireInitialized(),Wo(this.networkName)}getChainId(){return this._requireInitialized(),Number(this.network.chainId)}isOnNetwork(e){if(!this._initialized)return!1;const t=Wo(e);return!!t&&this.getChainId()===t.chainId}async getContract(e,t,n=!0){this._requireInitialized();const s=await this._loadEthers(),r=n&&this.signer?this.signer:this.provider;return new s.Contract(e,t,r)}async deployContract(e,t,n=[]){if(this._requireInitialized(),!this.signer)throw new Error("Signer required for contract deployment");const s=new((await this._loadEthers()).ContractFactory)(e,t,this.signer),r=await s.deploy(...n);await r.waitForDeployment();const a=await r.getAddress(),i=r.deploymentTransaction();return{contract:r,address:a,deployTx:i,txHash:i?.hash}}async waitForTransaction(e,t=1){return this._requireInitialized(),this.provider.waitForTransaction(e,t)}async estimateGas(e){return this._requireInitialized(),this.provider.estimateGas(e)}async getGasPrice(){this._requireInitialized();const e=await this._loadEthers(),t=await this.provider.getFeeData();return{gasPrice:t.gasPrice?e.formatUnits(t.gasPrice,"gwei"):null,maxFeePerGas:t.maxFeePerGas?e.formatUnits(t.maxFeePerGas,"gwei"):null,maxPriorityFeePerGas:t.maxPriorityFeePerGas?e.formatUnits(t.maxPriorityFeePerGas,"gwei"):null}}async parseUnits(e,t="ether"){return(await this._loadEthers()).parseUnits(e.toString(),t)}async formatUnits(e,t="ether"){return(await this._loadEthers()).formatUnits(e,t)}_requireInitialized(){if(!this._initialized)throw new Error("ChainManager not initialized. Call connect() or connectBrowser() first.")}isConnected(){return this._initialized&&null!==this.provider}disconnect(){this.provider=null,this.signer=null,this.network=null,this.networkName=null,this._initialized=!1}}const tf=[{type:"constructor",inputs:[{name:"_owner",type:"address",internalType:"address"},{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"},{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"addMember",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"},{name:"_membername",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addParent",inputs:[{name:"_parentaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"changeName",inputs:[{name:"_address",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeOwner",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"contractsByType",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"createManagedContract",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"createZonedContract",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"creatorUserId",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"debugGetContractAddress",inputs:[{name:"contractKey",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"depositEtherForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"depositTokenForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_tokenAddress",type:"address",internalType:"address"},{name:"_amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"externalContractSplitPercentage",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getContractAddresses",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"},{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"getContractInfo",inputs:[{name:"key",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getContractKeys",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"internalContractSplitPercentage",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"isMember",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isSplitterMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"listMembers",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address payable[]"}],stateMutability:"view"},{type:"function",name:"listParents",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"managedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"manifest",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"percentages",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"removeMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"routeCommand",inputs:[{name:"contractName",type:"string",internalType:"string"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[{name:"",type:"bool",internalType:"bool"},{name:"",type:"bytes",internalType:"bytes"}],stateMutability:"nonpayable"},{type:"function",name:"setContractSplit",inputs:[{name:"_internalPercentage",type:"uint256",internalType:"uint256"},{name:"_externalPercentage",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setFactories",inputs:[{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManifest",inputs:[{name:"_IPFSHash",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setSplit",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"},{name:"percentage",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"toName",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"zonedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"AddedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"AppreciationGiven",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"fromUserId",type:"string",indexed:!1,internalType:"string"},{name:"toUserId",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ChangedName",inputs:[{name:"namefrom",type:"string",indexed:!1,internalType:"string"},{name:"nameto",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"ChildContractCreated",inputs:[{name:"parentContract",type:"address",indexed:!0,internalType:"address"},{name:"childContract",type:"address",indexed:!0,internalType:"address"},{name:"parentHolonId",type:"string",indexed:!1,internalType:"string"},{name:"childHolonId",type:"string",indexed:!1,internalType:"string"},{name:"childType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"ChildRewardTriggered",inputs:[{name:"",type:"address",indexed:!1,internalType:"address"},{name:"",type:"address",indexed:!1,internalType:"address"},{name:"",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ContractSplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"internalPercentage",type:"uint256",indexed:!1,internalType:"uint256"},{name:"externalPercentage",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsCascaded",inputs:[{name:"fromContract",type:"address",indexed:!0,internalType:"address"},{name:"toContract",type:"address",indexed:!0,internalType:"address"},{name:"fromHolonId",type:"string",indexed:!1,internalType:"string"},{name:"toHolonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"splitType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsForwarded",inputs:[{name:"",type:"address",indexed:!1,internalType:"address"},{name:"",type:"address",indexed:!1,internalType:"address"},{name:"",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberRemoved",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RemovedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"splitType",type:"string",indexed:!1,internalType:"string"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"WeightChanged",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldWeight",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newWeight",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}],nf=[{type:"constructor",inputs:[{name:"_creator",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"},{name:"_botAddress",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"addMember",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"},{name:"_membername",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addParent",inputs:[{name:"_parentaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"appreciation",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"changeName",inputs:[{name:"_address",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeOwner",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"depositEtherForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"depositTokenForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_tokenAddress",type:"address",internalType:"address"},{name:"_amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getTokensOf",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isManagedMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isMember",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"listMembers",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address payable[]"}],stateMutability:"view"},{type:"function",name:"listParents",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"manifest",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"maxAppreciation",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"removeMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"setAppreciation",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"},{name:"_appreciationAmounts",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManifest",inputs:[{name:"_IPFSHash",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setUserAppreciation",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_appreciationAmount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"toName",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"totalappreciation",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"AddedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"AppreciationGiven",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"fromUserId",type:"string",indexed:!1,internalType:"string"},{name:"toUserId",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ChangedName",inputs:[{name:"namefrom",type:"string",indexed:!1,internalType:"string"},{name:"nameto",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsCascaded",inputs:[{name:"fromContract",type:"address",indexed:!0,internalType:"address"},{name:"toContract",type:"address",indexed:!0,internalType:"address"},{name:"fromHolonId",type:"string",indexed:!1,internalType:"string"},{name:"toHolonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"splitType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberRemoved",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RemovedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"splitType",type:"string",indexed:!1,internalType:"string"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"WeightChanged",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldWeight",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newWeight",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1}],sf=[{type:"constructor",inputs:[{name:"creatorUserId",type:"string",internalType:"string"},{name:"_creator",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"},{name:"_nzones",type:"uint256",internalType:"uint256"},{name:"_botAddress",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"a",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"addFederationMember",inputs:[{name:"federationId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"},{name:"_membername",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addParent",inputs:[{name:"_parentaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addToZone",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userId",type:"string",internalType:"string"},{name:"_zone",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addressToUserId",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"b",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"c",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"calculateRewards",inputs:[],outputs:[{name:"",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"changeName",inputs:[{name:"_address",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeOwner",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"depositEtherForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"depositTokenForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_tokenAddress",type:"address",internalType:"address"},{name:"_amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"factory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getZoneMembers",inputs:[{name:"_zone",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isMember",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isZonedMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"listMembers",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address payable[]"}],stateMutability:"view"},{type:"function",name:"listParents",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"manifest",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"nzones",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"percentages",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"removeFromZone",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"removeMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"rewards",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"setManifest",inputs:[{name:"_IPFSHash",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setRewardFunction",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_a",type:"uint256",internalType:"uint256"},{name:"_b",type:"uint256",internalType:"uint256"},{name:"_c",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"toName",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"zone",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"zonemembers",inputs:[{name:"",type:"uint256",internalType:"uint256"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"AddedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"AppreciationGiven",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"fromUserId",type:"string",indexed:!1,internalType:"string"},{name:"toUserId",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ChangedName",inputs:[{name:"namefrom",type:"string",indexed:!1,internalType:"string"},{name:"nameto",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsCascaded",inputs:[{name:"fromContract",type:"address",indexed:!0,internalType:"address"},{name:"toContract",type:"address",indexed:!0,internalType:"address"},{name:"fromHolonId",type:"string",indexed:!1,internalType:"string"},{name:"toHolonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"splitType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberRemoved",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RemovedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"splitType",type:"string",indexed:!1,internalType:"string"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"WeightChanged",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldWeight",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newWeight",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1}],rf=[{type:"constructor",inputs:[{name:"_name",type:"string",internalType:"string"},{name:"creatorUserId",type:"string",internalType:"string"},{name:"_creator",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"addMember",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"},{name:"_membername",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addParent",inputs:[{name:"_parentaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addressToUserId",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"appreciate",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userId",type:"string",internalType:"string"},{name:"_percentage",type:"uint8",internalType:"uint8"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"appreciation",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"changeName",inputs:[{name:"_address",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeOwner",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"depositEtherForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"depositTokenForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_tokenAddress",type:"address",internalType:"address"},{name:"_amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isAppreciativeMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isMember",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"listMembers",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address payable[]"}],stateMutability:"view"},{type:"function",name:"listParents",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"manifest",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"remainingappreciation",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"removeMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"resetAppreciation",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"setAppreciation",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"},{name:"_percentages",type:"uint8[]",internalType:"uint8[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManifest",inputs:[{name:"_IPFSHash",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"toName",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"totalappreciation",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"AddedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"AppreciationGiven",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"fromUserId",type:"string",indexed:!1,internalType:"string"},{name:"toUserId",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ChangedName",inputs:[{name:"namefrom",type:"string",indexed:!1,internalType:"string"},{name:"nameto",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsCascaded",inputs:[{name:"fromContract",type:"address",indexed:!0,internalType:"address"},{name:"toContract",type:"address",indexed:!0,internalType:"address"},{name:"fromHolonId",type:"string",indexed:!1,internalType:"string"},{name:"toHolonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"splitType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberRemoved",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RemovedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"splitType",type:"string",indexed:!1,internalType:"string"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"WeightChanged",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldWeight",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newWeight",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1}],af={abi:[{type:"constructor",inputs:[{name:"_owner",type:"address",internalType:"address"},{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_steepness",type:"uint256",internalType:"uint256"},{name:"_nzones",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"BASIS_POINTS",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"WAD",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"addMember",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"assignToZone",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_zone",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"cancelElection",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"candidates",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"electionActive",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"exteriorPercentage",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"factory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"finalizeElection",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getCandidates",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"getInteriorMembers",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getTokensOf",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"getZoneMembers",inputs:[{name:"_zone",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"getZoneWeights",inputs:[],outputs:[{name:"",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"hasVoted",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"interiorMembers",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"interiorPercentage",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"interiorShare",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"isBundleMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isCandidate",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isExteriorMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isInteriorMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"nominateSelf",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"nzones",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"removeFromExterior",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"setContractSplit",inputs:[{name:"_interior",type:"uint256",internalType:"uint256"},{name:"_exterior",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setInteriorSplit",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"},{name:"_percentages",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setNzones",inputs:[{name:"_nzones",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setSteepness",inputs:[{name:"_steepness",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"startElection",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"steepness",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"totalWeightedMembers",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"vote",inputs:[{name:"_voterId",type:"string",internalType:"string"},{name:"_candidateId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"votedFor",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"votes",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"zone",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"zoneWeights",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"zonemembers",inputs:[{name:"",type:"uint256",internalType:"uint256"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"CandidateNominated",inputs:[{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"ContractSplitSet",inputs:[{name:"interior",type:"uint256",indexed:!1,internalType:"uint256"},{name:"exterior",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ElectionCancelled",inputs:[],anonymous:!1},{type:"event",name:"ElectionFinalized",inputs:[{name:"winner",type:"string",indexed:!1,internalType:"string"},{name:"voteCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ElectionStarted",inputs:[],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"InteriorSplitSet",inputs:[{name:"userIds",type:"string[]",indexed:!1,internalType:"string[]"},{name:"percentages",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberAddedStd",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberAssignedToZone",inputs:[{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"zoneNumber",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberRemovedFromZone",inputs:[{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SteepnessSet",inputs:[{name:"steepness",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"VoteCast",inputs:[{name:"voter",type:"string",indexed:!1,internalType:"string"},{name:"candidate",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}],bytecode:"0x60806040526040518060400160405280600681526020017f42756e646c650000000000000000000000000000000000000000000000000000815250600290816200004a9190620006da565b5034801562000057575f80fd5b5060405162007e0338038062007e0383398181016040528101906200007d9190620009a6565b60015f819055505f821180156200009b5750670de0b6b3a764000082105b620000dd576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401620000d49062000ac6565b60405180910390fd5b8460035f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508460045f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055503360055f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508260019081620001ae9190620006da565b5081601381905550806014819055506001600985604051620001d1919062000b26565b90815260200160405180910390205f6101000a81548160ff021916908315150217905550600684908060018154018082558091505060019003905f5260205f20015f909190919091509081620002289190620006da565b50620002396200024460201b60201c565b505050505062000d3a565b60185f620002539190620003e9565b600160145462000264919062000b6b565b67ffffffffffffffff81111562000280576200027f62000480565b5b604051908082528060200260200182016040528015620002af5781602001602082028036833780820191505090505b5060189080519060200190620002c792919062000409565b505f6019819055505f670de0b6b3a764000090505f5b60145481116200037b578160188281548110620002ff57620002fe62000ba5565b5b905f5260205f2001819055508160155f8381526020019081526020015f20805490506200032d919062000bd2565b60195f8282546200033f919062000b6b565b925050819055506200036382601354670de0b6b3a76400006200037f60201b60201c565b91508080620003729062000c1c565b915050620002dd565b5050565b5f808211620003c5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401620003bc9062000cb6565b60405180910390fd5b818385620003d4919062000bd2565b620003e0919062000d03565b90509392505050565b5080545f8255905f5260205f209081019062000406919062000459565b50565b828054828255905f5260205f2090810192821562000446579160200282015b828111156200044557825182559160200191906001019062000428565b5b50905062000455919062000459565b5090565b5b8082111562000472575f815f9055506001016200045a565b5090565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f6002820490506001821680620004f257607f821691505b602082108103620005085762000507620004ad565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026200056c7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff826200052f565b6200057886836200052f565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f620005c2620005bc620005b68462000590565b62000599565b62000590565b9050919050565b5f819050919050565b620005dd83620005a2565b620005f5620005ec82620005c9565b8484546200053b565b825550505050565b5f90565b6200060b620005fd565b62000618818484620005d2565b505050565b5b818110156200063f57620006335f8262000601565b6001810190506200061e565b5050565b601f8211156200068e5762000658816200050e565b620006638462000520565b8101602085101562000673578190505b6200068b620006828562000520565b8301826200061d565b50505b505050565b5f82821c905092915050565b5f620006b05f198460080262000693565b1980831691505092915050565b5f620006ca83836200069f565b9150826002028217905092915050565b620006e58262000476565b67ffffffffffffffff81111562000701576200070062000480565b5b6200070d8254620004da565b6200071a82828562000643565b5f60209050601f83116001811462000750575f84156200073b578287015190505b620007478582620006bd565b865550620007b6565b601f19841662000760866200050e565b5f5b82811015620007895784890151825560018201915060208501945060208101905062000762565b86831015620007a95784890151620007a5601f8916826200069f565b8355505b6001600288020188555050505b505050505050565b5f604051905090565b5f80fd5b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f620007fa82620007cf565b9050919050565b6200080c81620007ee565b811462000817575f80fd5b50565b5f815190506200082a8162000801565b92915050565b5f80fd5b5f80fd5b5f601f19601f8301169050919050565b620008538262000838565b810181811067ffffffffffffffff8211171562000875576200087462000480565b5b80604052505050565b5f62000889620007be565b905062000897828262000848565b919050565b5f67ffffffffffffffff821115620008b957620008b862000480565b5b620008c48262000838565b9050602081019050919050565b5f5b83811015620008f0578082015181840152602081019050620008d3565b5f8484015250505050565b5f620009116200090b846200089c565b6200087e565b90508281526020810184848401111562000930576200092f62000834565b5b6200093d848285620008d1565b509392505050565b5f82601f8301126200095c576200095b62000830565b5b81516200096e848260208601620008fb565b91505092915050565b620009828162000590565b81146200098d575f80fd5b50565b5f81519050620009a08162000977565b92915050565b5f805f805f60a08688031215620009c257620009c1620007c7565b5b5f620009d1888289016200081a565b955050602086015167ffffffffffffffff811115620009f557620009f4620007cb565b5b62000a038882890162000945565b945050604086015167ffffffffffffffff81111562000a275762000a26620007cb565b5b62000a358882890162000945565b935050606062000a488882890162000990565b925050608062000a5b8882890162000990565b9150509295509295909350565b5f82825260208201905092915050565b7f53746565706e657373206d7573742062652030203c2073203c203165313800005f82015250565b5f62000aae601e8362000a68565b915062000abb8262000a78565b602082019050919050565b5f6020820190508181035f83015262000adf8162000aa0565b9050919050565b5f81905092915050565b5f62000afc8262000476565b62000b08818562000ae6565b935062000b1a818560208601620008d1565b80840191505092915050565b5f62000b33828462000af0565b915081905092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f62000b778262000590565b915062000b848362000590565b925082820190508082111562000b9f5762000b9e62000b3e565b5b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f62000bde8262000590565b915062000beb8362000590565b925082820262000bfb8162000590565b9150828204841483151762000c155762000c1462000b3e565b5b5092915050565b5f62000c288262000590565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820362000c5d5762000c5c62000b3e565b5b600182019050919050565b7f4469766973696f6e206279207a65726f000000000000000000000000000000005f82015250565b5f62000c9e60108362000a68565b915062000cab8262000c68565b602082019050919050565b5f6020820190508181035f83015262000ccf8162000c90565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f62000d0f8262000590565b915062000d1c8362000590565b92508262000d2f5762000d2e62000cd6565b5b828204905092915050565b6170bb8062000d485f395ff3fe608060405260043610610338575f3560e01c806377e7fca2116101aa578063c21be6ae116100f6578063dad4ae3711610094578063e1f1c4a71161006e578063e1f1c4a714610ca5578063e8d5940d14610ccf578063ead6252014610cf7578063f59e4f6514610d3357610349565b8063dad4ae3714610c03578063de8fa43114610c3f578063e15b3f5f14610c6957610349565b8063cafa4ffa116100d0578063cafa4ffa14610b4b578063cc18494814610b75578063d118a53f14610bb1578063d7841a1c14610bdb57610349565b8063c21be6ae14610aa9578063c45a015514610ae5578063ca22431314610b0f57610349565b8063873010d911610163578063918f96871161013d578063918f9687146109e1578063981a63dc14610a09578063b801603514610a45578063b99ef1fa14610a6d57610349565b8063873010d91461095157806387563ec11461098d5780638da5cb5b146109b757610349565b806377e7fca2146108355780637a3c22eb1461085f5780637b0a7e33146108875780637c59dd5f146108c35780637ed628bb146108ff578063804d74701461092957610349565b806339bfeae31161028457806357a32534116102225780636a146024116101fc5780636a1460241461078f5780636bd39c52146107b95780636cc6837e146107e35780636d2687c0146107f957610349565b806357a325341461071557806360a1da831461075157806362d73eb81461077957610349565b80634635fd681161025e5780634635fd681461064b57806351599b151461068757806353055481146106c35780635744426e146106ff57610349565b806339bfeae3146105ab578063404880d9146105e7578063441179e51461062357610349565b806321670f22116102f15780633477ee2e116102cb5780633477ee2e146104e3578063363454ee1461051f578063372c3e7c1461055b57806338eccabd1461058357610349565b806321670f221461046157806328c317d71461047d57806333d6e65f146104b957610349565b806302d05d3f1461035557806306a49fce1461037f57806306fdde03146103a957806312feb905146103d35780631821fcab146103fd5780631a2f4ee51461043957610349565b36610349576103475f34610d5d565b005b6103535f34610d5d565b005b348015610360575f80fd5b50610369611149565b604051610376919061509c565b60405180910390f35b34801561038a575f80fd5b5061039361116e565b6040516103a091906151fa565b60405180910390f35b3480156103b4575f80fd5b506103bd611242565b6040516103ca9190615262565b60405180910390f35b3480156103de575f80fd5b506103e76112ce565b6040516103f491906151fa565b60405180910390f35b348015610408575f80fd5b50610423600480360381019061041e91906153bf565b6113a2565b604051610430919061541e565b60405180910390f35b348015610444575f80fd5b5061045f600480360381019061045a9190615461565b6113cf565b005b61047b600480360381019061047691906154c9565b610d5d565b005b348015610488575f80fd5b506104a3600480360381019061049e91906153bf565b6114f8565b6040516104b091906155be565b60405180910390f35b3480156104c4575f80fd5b506104cd6115a1565b6040516104da919061541e565b60405180910390f35b3480156104ee575f80fd5b50610509600480360381019061050491906155de565b6115a7565b6040516105169190615262565b60405180910390f35b34801561052a575f80fd5b50610545600480360381019061054091906153bf565b61164d565b6040516105529190615623565b60405180910390f35b348015610566575f80fd5b50610581600480360381019061057c91906155de565b611682565b005b34801561058e575f80fd5b506105a960048036038101906105a491906153bf565b611723565b005b3480156105b6575f80fd5b506105d160048036038101906105cc91906153bf565b61189c565b6040516105de9190615623565b60405180910390f35b3480156105f2575f80fd5b5061060d600480360381019061060891906153bf565b6118d1565b60405161061a9190615623565b60405180910390f35b34801561062e575f80fd5b506106496004803603810190610644919061563c565b611906565b005b348015610656575f80fd5b50610671600480360381019061066c91906155de565b611c2b565b60405161067e9190615262565b60405180910390f35b348015610692575f80fd5b506106ad60048036038101906106a891906153bf565b611cd1565b6040516106ba9190615623565b60405180910390f35b3480156106ce575f80fd5b506106e960048036038101906106e49190615696565b611d06565b6040516106f6919061541e565b60405180910390f35b34801561070a575f80fd5b50610713611d1b565b005b348015610720575f80fd5b5061073b600480360381019061073691906153bf565b611e3f565b604051610748919061541e565b60405180910390f35b34801561075c575f80fd5b50610777600480360381019061077291906156c1565b611e6c565b005b348015610784575f80fd5b5061078d612201565b005b34801561079a575f80fd5b506107a361245e565b6040516107b0919061541e565b60405180910390f35b3480156107c4575f80fd5b506107cd61246a565b6040516107da919061541e565b60405180910390f35b3480156107ee575f80fd5b506107f7612470565b005b348015610804575f80fd5b5061081f600480360381019061081a91906155de565b612987565b60405161082c9190615262565b60405180910390f35b348015610840575f80fd5b50610849612a2d565b604051610856919061541e565b60405180910390f35b34801561086a575f80fd5b50610885600480360381019061088091906153bf565b612a33565b005b348015610892575f80fd5b506108ad60048036038101906108a891906155de565b612c87565b6040516108ba91906151fa565b60405180910390f35b3480156108ce575f80fd5b506108e960048036038101906108e491906153bf565b612d6c565b6040516108f69190615623565b60405180910390f35b34801561090a575f80fd5b50610913612da1565b6040516109209190615623565b60405180910390f35b348015610934575f80fd5b5061094f600480360381019061094a91906157fd565b612db3565b005b34801561095c575f80fd5b50610977600480360381019061097291906155de565b612fac565b604051610984919061541e565b60405180910390f35b348015610998575f80fd5b506109a1612fcc565b6040516109ae919061541e565b60405180910390f35b3480156109c2575f80fd5b506109cb612fd2565b6040516109d8919061509c565b60405180910390f35b3480156109ec575f80fd5b50610a076004803603810190610a0291906153bf565b612ff7565b005b348015610a14575f80fd5b50610a2f6004803603810190610a2a91906153bf565b6131ab565b604051610a3c9190615262565b60405180910390f35b348015610a50575f80fd5b50610a6b6004803603810190610a669190615904565b61325e565b005b348015610a78575f80fd5b50610a936004803603810190610a8e91906153bf565b61368c565b604051610aa0919061541e565b60405180910390f35b348015610ab4575f80fd5b50610acf6004803603810190610aca91906153bf565b6136b9565b604051610adc919061509c565b60405180910390f35b348015610af0575f80fd5b50610af9613701565b604051610b06919061509c565b60405180910390f35b348015610b1a575f80fd5b50610b356004803603810190610b3091906156c1565b613726565b604051610b42919061541e565b60405180910390f35b348015610b56575f80fd5b50610b5f61375e565b604051610b6c919061541e565b60405180910390f35b348015610b80575f80fd5b50610b9b6004803603810190610b96919061563c565b613764565b604051610ba8919061509c565b60405180910390f35b348015610bbc575f80fd5b50610bc56137c4565b604051610bd29190615a31565b60405180910390f35b348015610be6575f80fd5b50610c016004803603810190610bfc91906155de565b61381a565b005b348015610c0e575f80fd5b50610c296004803603810190610c2491906153bf565b613947565b604051610c369190615623565b60405180910390f35b348015610c4a575f80fd5b50610c5361397c565b604051610c60919061541e565b60405180910390f35b348015610c74575f80fd5b50610c8f6004803603810190610c8a91906153bf565b613988565b604051610c9c919061541e565b60405180910390f35b348015610cb0575f80fd5b50610cb96139b5565b604051610cc6919061541e565b60405180910390f35b348015610cda575f80fd5b50610cf56004803603810190610cf09190615a51565b6139bb565b005b348015610d02575f80fd5b50610d1d6004803603810190610d189190615461565b613ca9565b604051610d2a9190615262565b60405180910390f35b348015610d3e575f80fd5b50610d47613d5a565b604051610d549190615262565b60405180910390f35b610d65613de6565b5f8034118015610da057505f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b90505f8115610e18573492503373ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f37de26b9f29dba736fb8291dad9ace7d2f6dc76e3e5faaeca097145b5298f94b5f86604051610e0b929190615ac7565b60405180910390a3610f8a565b8390505f600d5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20548273ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401610e93919061509c565b602060405180830381865afa158015610eae573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ed29190615b02565b610edc9190615b5a565b905083811015610f21576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610f1890615bd7565b60405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f37de26b9f29dba736fb8291dad9ace7d2f6dc76e3e5faaeca097145b5298f94b8787604051610f80929190615ac7565b60405180910390a3505b5f610f9a84600e54612710613e2a565b90505f8185610fa99190615b5a565b90505f8083118015610fbf57505f601080549050115b15610fde57610fd087848787613e8d565b81610fdb9190615bf5565b90505b5f82118015610fee57505f601954115b1561100d57610fff87838787613fb6565b8161100a9190615bf5565b90505b3073ffffffffffffffffffffffffffffffffffffffff167fd83308e9158842b2115ec5e6f6395db42fff24e4b5506ef42fe33854fafad655878388611087576040518060400160405280600581526020017f45524332300000000000000000000000000000000000000000000000000000008152506110be565b6040518060400160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152505b6040516110cd93929190615c28565b60405180910390a23073ffffffffffffffffffffffffffffffffffffffff167fc2d2b959adca67349f750fed9ef9eaefbec59f24fa563c7fa410157130395c4060018761111a578961111c565b5f5b89855f604051611130959493929190615d96565b60405180910390a25050505050611145614184565b5050565b60045f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6060601b805480602002602001604051908101604052809291908181526020015f905b82821015611239578382905f5260205f200180546111ae90615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546111da90615c91565b80156112255780601f106111fc57610100808354040283529160200191611225565b820191905f5260205f20905b81548152906001019060200180831161120857829003601f168201915b505050505081526020019060010190611191565b50505050905090565b6001805461124f90615c91565b80601f016020809104026020016040519081016040528092919081815260200182805461127b90615c91565b80156112c65780601f1061129d576101008083540402835291602001916112c6565b820191905f5260205f20905b8154815290600101906020018083116112a957829003601f168201915b505050505081565b60606010805480602002602001604051908101604052809291908181526020015f905b82821015611399578382905f5260205f2001805461130e90615c91565b80601f016020809104026020016040519081016040528092919081815260200182805461133a90615c91565b80156113855780601f1061135c57610100808354040283529160200191611385565b820191905f5260205f20905b81548152906001019060200180831161136857829003601f168201915b5050505050815260200190600101906112f1565b50505050905090565b6016818051602081018201805184825260208301602085012081835280955050505050505f915090505481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461145e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161145590615e38565b60405180910390fd5b612710818361146d9190615bf5565b146114ad576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016114a490615ea0565b60405180910390fd5b81600e8190555080600f819055507f29dd4a83e71eab2a472a8bb7a7bb9467395098acb48b07c8d9ea7294de0ba0ae82826040516114ec929190615ebe565b60405180910390a15050565b6060600c8260405161150a9190615f1f565b908152602001604051809103902080548060200260200160405190810160405280929190818152602001828054801561159557602002820191905f5260205f20905b815f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001906001019080831161154c575b50505050509050919050565b60145481565b601b81815481106115b6575f80fd5b905f5260205f20015f9150905080546115ce90615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546115fa90615c91565b80156116455780601f1061161c57610100808354040283529160200191611645565b820191905f5260205f20905b81548152906001019060200180831161162857829003601f168201915b505050505081565b6008818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611711576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161170890615e38565b60405180910390fd5b8060148190555061172061418d565b50565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146117b2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016117a990615e38565b60405180910390fd5b6017816040516117c29190615f1f565b90815260200160405180910390205f9054906101000a900460ff1661181c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161181390615f7f565b60405180910390fd5b611825816142ab565b5f6017826040516118369190615f1f565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555061186261418d565b7fe6db474363a3116f4cf525fc0d78d9dd53e214383db31efef8368f08c4bf7991816040516118919190615262565b60405180910390a150565b601e818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b6009818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611995576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161198c90615e38565b60405180910390fd5b6009826040516119a59190615f1f565b90815260200160405180910390205f9054906101000a900460ff166119ff576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016119f690615fe7565b60405180910390fd5b601454811115611a44576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611a3b9061604f565b60405180910390fd5b5f601783604051611a559190615f1f565b90815260200160405180910390205f9054906101000a900460ff16611a9a577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff611aba565b601683604051611aaa9190615f1f565b9081526020016040518091039020545b9050601783604051611acc9190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615611af657611af5836142ab565b5b81601684604051611b079190615f1f565b90815260200160405180910390208190555060155f8381526020019081526020015f2083908060018154018082558091505060019003905f5260205f20015f909190919091509081611b5991906161ef565b506001601784604051611b6c9190615f1f565b90815260200160405180910390205f6101000a81548160ff021916908315150217905550611b9861418d565b7f9bca84993827a6bd2bc824f45db9e0ae931cf1f7b1706b7c735ba0102300b4ca8383604051611bc99291906162be565b60405180910390a13073ffffffffffffffffffffffffffffffffffffffff167f7d482c93a88a92e4d27ba697265785162f607bc0ac6c55b868232b3ba3fbb63d6001858486604051611c1e94939291906162ec565b60405180910390a2505050565b60068181548110611c3a575f80fd5b905f5260205f20015f915090508054611c5290615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054611c7e90615c91565b8015611cc95780601f10611ca057610100808354040283529160200191611cc9565b820191905f5260205f20905b815481529060010190602001808311611cac57829003601f168201915b505050505081565b601c818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b600d602052805f5260405f205f915090505481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611daa576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611da190615e38565b60405180910390fd5b601a5f9054906101000a900460ff16611df8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611def90616387565b60405180910390fd5b5f601a5f6101000a81548160ff0219169083151502179055507f990bb31515adefe5ecd88a4dca3e9772b32d484c81e22cae38d5482e0d9f35e460405160405180910390a1565b600a818051602081018201805184825260208301602085012081835280955050505050505f915090505481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611efb576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611ef290615e38565b60405180910390fd5b611f03613de6565b600882604051611f139190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615611f6e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f65906163ef565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1603611fdc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611fd390616457565b60405180910390fd5b600982604051611fec9190615f1f565b90815260200160405180910390205f9054906101000a900460ff16612046576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161203d906164bf565b60405180910390fd5b5f600a836040516120579190615f1f565b9081526020016040518091039020549050600160088460405161207a9190615f1f565b90815260200160405180910390205f6101000a81548160ff0219169083151502179055505f73ffffffffffffffffffffffffffffffffffffffff166007846040516120c59190615f1f565b90815260200160405180910390205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff160361216b578160078460405161211f9190615f1f565b90815260200160405180910390205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b61217583836143c9565b61217f83836144c5565b5f8111156121f4578173ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f605614956ef211f270ab0b08a13dd69698dc38d70e20899e1051ae2e1ae6cd5b6001865f866040516121eb94939291906164dd565b60405180910390a35b506121fd614184565b5050565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614612290576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161228790615e38565b60405180910390fd5b5f5b601b80549050811015612340575f601d601b83815481106122b6576122b561652e565b5b905f5260205f20016040516122cb91906165db565b9081526020016040518091039020819055505f601c601b83815481106122f4576122f361652e565b5b905f5260205f200160405161230991906165db565b90815260200160405180910390205f6101000a81548160ff0219169083151502179055508080612338906165f1565b915050612292565b50601b5f61234e9190614f5b565b5f5b600680549050811015612415575f601e600683815481106123745761237361652e565b5b905f5260205f200160405161238991906165db565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555060405180602001604052805f815250601f600683815481106123d2576123d161652e565b5b905f5260205f20016040516123e791906165db565b9081526020016040518091039020908161240191906161ef565b50808061240d906165f1565b915050612350565b506001601a5f6101000a81548160ff0219169083151502179055507fc475c26aa25ed8e85a7faa790e5f63b5d7ee1025f12821f4c9bfddd36ab4d11260405160405180910390a1565b670de0b6b3a764000081565b600e5481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146124ff576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016124f690615e38565b60405180910390fd5b601a5f9054906101000a900460ff1661254d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161254490616387565b60405180910390fd5b5f601b8054905011612594576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161258b90616682565b60405180910390fd5b5f601b5f815481106125a9576125a861652e565b5b905f5260205f200180546125bc90615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546125e890615c91565b80156126335780601f1061260a57610100808354040283529160200191612633565b820191905f5260205f20905b81548152906001019060200180831161261657829003601f168201915b505050505090505f601d601b5f815481106126515761265061652e565b5b905f5260205f200160405161266691906165db565b90815260200160405180910390205490505f600190505b601b805490508110156127c05781601d601b83815481106126a1576126a061652e565b5b905f5260205f20016040516126b691906165db565b90815260200160405180910390205411156127ad57601d601b82815481106126e1576126e061652e565b5b905f5260205f20016040516126f691906165db565b9081526020016040518091039020549150601b818154811061271b5761271a61652e565b5b905f5260205f2001805461272e90615c91565b80601f016020809104026020016040519081016040528092919081815260200182805461275a90615c91565b80156127a55780601f1061277c576101008083540402835291602001916127a5565b820191905f5260205f20905b81548152906001019060200180831161278857829003601f168201915b505050505092505b80806127b8906165f1565b91505061267d565b505f6007836040516127d29190615f1f565b90815260200160405180910390205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690505f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1603612870576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161286790616710565b60405180910390fd5b5f60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508160035f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505f601a5f6101000a81548160ff0219169083151502179055507f5e99cd5235d5c8c4f0f8dc2626c83130cf843047e4ecbe4c111076e2b31a0d52848460405161291f9291906162be565b60405180910390a18173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a350505050565b60108181548110612996575f80fd5b905f5260205f20015f9150905080546129ae90615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546129da90615c91565b8015612a255780601f106129fc57610100808354040283529160200191612a25565b820191905f5260205f20905b815481529060010190602001808311612a0857829003601f168201915b505050505081565b600f5481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614612ac2576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612ab990615e38565b60405180910390fd5b601a5f9054906101000a900460ff16612b10576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612b0790616387565b60405180910390fd5b600981604051612b209190615f1f565b90815260200160405180910390205f9054906101000a900460ff16612b7a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612b7190616778565b60405180910390fd5b601c81604051612b8a9190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615612be5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612bdc906167e0565b60405180910390fd5b601b81908060018154018082558091505060019003905f5260205f20015f909190919091509081612c1691906161ef565b506001601c82604051612c299190615f1f565b90815260200160405180910390205f6101000a81548160ff0219169083151502179055507f134c877b5bd4770ffc56867fc5d2c549dd813a5db276d378f8d855a04fc7aa1d81604051612c7c9190615262565b60405180910390a150565b606060155f8381526020019081526020015f20805480602002602001604051908101604052809291908181526020015f905b82821015612d61578382905f5260205f20018054612cd690615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054612d0290615c91565b8015612d4d5780601f10612d2457610100808354040283529160200191612d4d565b820191905f5260205f20905b815481529060010190602001808311612d3057829003601f168201915b505050505081526020019060010190612cb9565b505050509050919050565b6011818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b601a5f9054906101000a900460ff1681565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614612e42576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612e3990615e38565b60405180910390fd5b5f5b8151811015612fa8575f828281518110612e6157612e6061652e565b5b60200260200101519050600981604051612e7b9190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615612ea15750612f95565b6001600982604051612eb39190615f1f565b90815260200160405180910390205f6101000a81548160ff021916908315150217905550600681908060018154018082558091505060019003905f5260205f20015f909190919091509081612f0891906161ef565b507fdfaa3c24567cbffbf024ddfd8dfca7a224b307e94b0df5437facad0f2fea2f9b81604051612f389190615262565b60405180910390a13073ffffffffffffffffffffffffffffffffffffffff167f954917c11fc57299ff064c483b4113756221231fcea3a1a3aa54ebd605a9c1e860018333604051612f8b939291906167fe565b60405180910390a2505b8080612fa0906165f1565b915050612e44565b5050565b60188181548110612fbb575f80fd5b905f5260205f20015f915090505481565b60135481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614613086576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161307d90615e38565b60405180910390fd5b6009816040516130969190615f1f565b90815260200160405180910390205f9054906101000a900460ff166131a85760016009826040516130c79190615f1f565b90815260200160405180910390205f6101000a81548160ff021916908315150217905550600681908060018154018082558091505060019003905f5260205f20015f90919091909150908161311c91906161ef565b507fdfaa3c24567cbffbf024ddfd8dfca7a224b307e94b0df5437facad0f2fea2f9b8160405161314c9190615262565b60405180910390a13073ffffffffffffffffffffffffffffffffffffffff167f954917c11fc57299ff064c483b4113756221231fcea3a1a3aa54ebd605a9c1e86001833360405161319f939291906167fe565b60405180910390a25b50565b601f818051602081018201805184825260208301602085012081835280955050505050505f9150905080546131df90615c91565b80601f016020809104026020016040519081016040528092919081815260200182805461320b90615c91565b80156132565780601f1061322d57610100808354040283529160200191613256565b820191905f5260205f20905b81548152906001019060200180831161323957829003601f168201915b505050505081565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146132ed576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016132e490615e38565b60405180910390fd5b8051825114613331576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016133289061688b565b60405180910390fd5b5f5b6010805490508110156133e1575f6012601083815481106133575761335661652e565b5b905f5260205f200160405161336c91906165db565b9081526020016040518091039020819055505f6011601083815481106133955761339461652e565b5b905f5260205f20016040516133aa91906165db565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555080806133d9906165f1565b915050613333565b5060105f6133ef9190614f5b565b5f805b83518110156136095760098482815181106134105761340f61652e565b5b60200260200101516040516134259190615f1f565b90815260200160405180910390205f9054906101000a900460ff1661347f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613476906168f3565b60405180910390fd5b5f8382815181106134935761349261652e565b5b6020026020010151116134db576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016134d29061695b565b60405180910390fd5b60108482815181106134f0576134ef61652e565b5b6020026020010151908060018154018082558091505060019003905f5260205f20015f90919091909150908161352691906161ef565b506001601185838151811061353e5761353d61652e565b5b60200260200101516040516135539190615f1f565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555082818151811061358a5761358961652e565b5b602002602001015160128583815181106135a7576135a661652e565b5b60200260200101516040516135bc9190615f1f565b9081526020016040518091039020819055508281815181106135e1576135e061652e565b5b6020026020010151826135f49190615bf5565b91508080613601906165f1565b9150506133f2565b50612710811461364e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613645906169c3565b60405180910390fd5b7f7749ddba77d660c1351ff548a0bf5b09743d6ad44914e3cb9a29a1f805fb09fe838360405161367f9291906169e1565b60405180910390a1505050565b601d818051602081018201805184825260208301602085012081835280955050505050505f915090505481565b6007818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600b82805160208101820180518482526020830160208501208183528095505050505050602052805f5260405f205f91509150505481565b60195481565b600c828051602081018201805184825260208301602085012081835280955050505050508181548110613795575f80fd5b905f5260205f20015f915091509054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6060601880548060200260200160405190810160405280929190818152602001828054801561381057602002820191905f5260205f20905b8154815260200190600101908083116137fc575b5050505050905090565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146138a9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016138a090615e38565b60405180910390fd5b5f811180156138bf5750670de0b6b3a764000081105b6138fe576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016138f590616a60565b60405180910390fd5b8060138190555061390d61418d565b7f5fad7fda6b8fb652ca59780d340772fed3852ba698b3a4cd40ebc117b8ec57508160405161393c919061541e565b60405180910390a150565b6017818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b5f600680549050905090565b6012818051602081018201805184825260208301602085012081835280955050505050505f915090505481565b61271081565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614613a4a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613a4190615e38565b60405180910390fd5b601a5f9054906101000a900460ff16613a98576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613a8f90616387565b60405180910390fd5b600982604051613aa89190615f1f565b90815260200160405180910390205f9054906101000a900460ff16613b02576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613af990616ac8565b60405180910390fd5b601c81604051613b129190615f1f565b90815260200160405180910390205f9054906101000a900460ff16613b6c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613b6390616b30565b60405180910390fd5b601e82604051613b7c9190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615613bd7576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613bce90616b98565b60405180910390fd5b6001601e83604051613be99190615f1f565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555080601f83604051613c1e9190615f1f565b90815260200160405180910390209081613c3891906161ef565b50601d81604051613c499190615f1f565b90815260200160405180910390205f815480929190613c67906165f1565b91905055507f137ad23732468494166ec34d1367743690ffa17f6ceac8429cba8fc35d088b6e8282604051613c9d929190616bb6565b60405180910390a15050565b6015602052815f5260405f208181548110613cc2575f80fd5b905f5260205f20015f91509150508054613cdb90615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054613d0790615c91565b8015613d525780601f10613d2957610100808354040283529160200191613d52565b820191905f5260205f20905b815481529060010190602001808311613d3557829003601f168201915b505050505081565b60028054613d6790615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054613d9390615c91565b8015613dde5780601f10613db557610100808354040283529160200191613dde565b820191905f5260205f20905b815481529060010190602001808311613dc157829003601f168201915b505050505081565b60025f5403613e21576040517f3ee5aeb500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60025f81905550565b5f808211613e6d576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613e6490616c35565b60405180910390fd5b818385613e7a9190616c53565b613e849190616cc1565b90509392505050565b5f805f90505b601080549050811015613fad575f60108281548110613eb557613eb461652e565b5b905f5260205f20018054613ec890615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054613ef490615c91565b8015613f3f5780601f10613f1657610100808354040283529160200191613f3f565b820191905f5260205f20905b815481529060010190602001808311613f2257829003601f168201915b505050505090505f613f7287601284604051613f5b9190615f1f565b908152602001604051809103902054612710613e2a565b90505f811115613f9857613f898289838989614737565b8380613f94906165f1565b9450505b50508080613fa5906165f1565b915050613e93565b50949350505050565b5f805f90505b601454811161417b575f60155f8381526020019081526020015f208054905090505f8103613fea5750614168565b5f60188381548110613fff57613ffe61652e565b5b905f5260205f200154826140139190616c53565b90505f6140238883601954613e2a565b90505f83826140329190616cc1565b90505f805b85811015614161575f60018761404d9190615b5a565b820361406657828561405f9190615b5a565b9050614078565b83905083836140759190615bf5565b92505b5f81111561414d5761413e60155f8a81526020019081526020015f2083815481106140a6576140a561652e565b5b905f5260205f200180546140b990615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546140e590615c91565b80156141305780601f1061410757610100808354040283529160200191614130565b820191905f5260205f20905b81548152906001019060200180831161411357829003601f168201915b50505050508e838e8e614737565b8880614149906165f1565b9950505b508080614159906165f1565b915050614037565b5050505050505b8080614173906165f1565b915050613fbc565b50949350505050565b60015f81905550565b60185f61419a9190614f79565b60016014546141a99190615bf5565b67ffffffffffffffff8111156141c2576141c161529b565b5b6040519080825280602002602001820160405280156141f05781602001602082028036833780820191505090505b5060189080519060200190614206929190614f97565b505f6019819055505f670de0b6b3a764000090505f5b60145481116142a757816018828154811061423a5761423961652e565b5b905f5260205f2001819055508160155f8381526020019081526020015f20805490506142669190616c53565b60195f8282546142769190615bf5565b9250508190555061429282601354670de0b6b3a7640000613e2a565b9150808061429f906165f1565b91505061421c565b5050565b5f6016826040516142bc9190615f1f565b90815260200160405180910390205490505f60155f8381526020019081526020015f2090505f5b81805490508110156143c357838051906020012082828154811061430a5761430961652e565b5b905f5260205f200160405161431f9190616d8d565b6040518091039020036143b057816001838054905061433e9190615b5a565b8154811061434f5761434e61652e565b5b905f5260205f200182828154811061436a5761436961652e565b5b905f5260205f2001908161437e9190616dca565b50818054806143905761438f616eaf565b5b600190038181905f5260205f20015f6143a99190614fe2565b90556143c3565b80806143bb906165f1565b9150506142e3565b50505050565b5f600a836040516143da9190615f1f565b90815260200160405180910390205490505f8111156144c0575f600a846040516144049190615f1f565b9081526020016040518091039020819055505f8273ffffffffffffffffffffffffffffffffffffffff168260405161443b90616eff565b5f6040518083038185875af1925050503d805f8114614475576040519150601f19603f3d011682016040523d82523d5f602084013e61447a565b606091505b50509050806144be576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016144b590616f5d565b60405180910390fd5b505b505050565b5f600c836040516144d69190615f1f565b908152602001604051809103902080548060200260200160405190810160405280929190818152602001828054801561456157602002820191905f5260205f20905b815f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019060010190808311614518575b505050505090505f5b8151811015614731575f600b856040516145849190615f1f565b90815260200160405180910390205f8484815181106145a6576145a561652e565b5b602002602001015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205490505f81111561471d575f600b866040516146039190615f1f565b90815260200160405180910390205f8585815181106146255761462461652e565b5b602002602001015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208190555080600d5f8585815181106146815761468061652e565b5b602002602001015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8282546146d09190615b5a565b9250508190555061471c84828585815181106146ef576146ee61652e565b5b602002602001015173ffffffffffffffffffffffffffffffffffffffff16614e419092919063ffffffff16565b5b508080614729906165f1565b91505061456a565b50505050565b5f6007866040516147489190615f1f565b90815260200160405180910390205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690505f8073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141580156147cb57505f8273ffffffffffffffffffffffffffffffffffffffff163b115b90506008876040516147dd9190615f1f565b90815260200160405180910390205f9054906101000a900460ff16801561483057505f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614155b15614a715783156148e9575f8273ffffffffffffffffffffffffffffffffffffffff168660405161486090616eff565b5f6040518083038185875af1925050503d805f811461489a576040519150601f19603f3d011682016040523d82523d5f602084013e61489f565b606091505b50509050806148e3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016148da90616fc5565b60405180910390fd5b50614915565b61491482868573ffffffffffffffffffffffffffffffffffffffff16614e419092919063ffffffff16565b5b8173ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f7d6a6b7452c2fec7981096e354fb3311f3f3b800ff27def1017b22cbff2751908784886149a6576040518060400160405280600581526020017f45524332300000000000000000000000000000000000000000000000000000008152506149dd565b6040518060400160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152505b6040516149ec93929190616fe3565b60405180910390a38173ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f71e611184866cc19c5f49af6c856ce9bde5a13bcd197c7499b61ab410ac9439960018a88614a51578a614a53565b5f5b8a604051614a6494939291906164dd565b60405180910390a3614e38565b8315614ab05784600a88604051614a889190615f1f565b90815260200160405180910390205f828254614aa49190615bf5565b92505081905550614c50565b5f600b88604051614ac19190615f1f565b90815260200160405180910390205f8873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205403614b8d57600c87604051614b209190615f1f565b908152602001604051809103902086908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b84600b88604051614b9e9190615f1f565b90815260200160405180910390205f8873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f828254614bf59190615bf5565b9250508190555084600d5f8873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f828254614c489190615bf5565b925050819055505b5f73ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f7d6a6b7452c2fec7981096e354fb3311f3f3b800ff27def1017b22cbff275190875f88614ce1576040518060400160405280600c81526020017f53544f5245445f45524332300000000000000000000000000000000000000000815250614d18565b6040518060400160405280600a81526020017f53544f5245445f455448000000000000000000000000000000000000000000008152505b604051614d2793929190616fe3565b60405180910390a35f601188604051614d409190615f1f565b90815260200160405180910390205f9054906101000a900460ff16614d9a576040518060400160405280600481526020017f7a6f6e6500000000000000000000000000000000000000000000000000000000815250614dd1565b6040518060400160405280600a81526020017f70657263656e74616765000000000000000000000000000000000000000000008152505b90503073ffffffffffffffffffffffffffffffffffffffff167ff9700e8ac41cc506d3f79229bad9981619140b63838136cdb10ac6ba5f6976ab60018a88614e19578a614e1b565b5f5b8a86604051614e2e95949392919061701f565b60405180910390a2505b50505050505050565b614ebb838473ffffffffffffffffffffffffffffffffffffffff1663a9059cbb8585604051602401614e74929190615ac7565b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050614ec0565b505050565b5f8060205f8451602086015f885af180614edf576040513d5f823e3d81fd5b3d92505f519150505f8214614ef8576001811415614f13565b5f8473ffffffffffffffffffffffffffffffffffffffff163b145b15614f5557836040517f5274afe7000000000000000000000000000000000000000000000000000000008152600401614f4c919061509c565b60405180910390fd5b50505050565b5080545f8255905f5260205f2090810190614f76919061501f565b50565b5080545f8255905f5260205f2090810190614f949190615042565b50565b828054828255905f5260205f20908101928215614fd1579160200282015b82811115614fd0578251825591602001919060010190614fb5565b5b509050614fde9190615042565b5090565b508054614fee90615c91565b5f825580601f10614fff575061501c565b601f0160209004905f5260205f209081019061501b9190615042565b5b50565b5b8082111561503e575f81816150359190614fe2565b50600101615020565b5090565b5b80821115615059575f815f905550600101615043565b5090565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6150868261505d565b9050919050565b6150968161507c565b82525050565b5f6020820190506150af5f83018461508d565b92915050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b5f81519050919050565b5f82825260208201905092915050565b5f5b838110156151155780820151818401526020810190506150fa565b5f8484015250505050565b5f601f19601f8301169050919050565b5f61513a826150de565b61514481856150e8565b93506151548185602086016150f8565b61515d81615120565b840191505092915050565b5f6151738383615130565b905092915050565b5f602082019050919050565b5f615191826150b5565b61519b81856150bf565b9350836020820285016151ad856150cf565b805f5b858110156151e857848403895281516151c98582615168565b94506151d48361517b565b925060208a019950506001810190506151b0565b50829750879550505050505092915050565b5f6020820190508181035f8301526152128184615187565b905092915050565b5f82825260208201905092915050565b5f615234826150de565b61523e818561521a565b935061524e8185602086016150f8565b61525781615120565b840191505092915050565b5f6020820190508181035f83015261527a818461522a565b905092915050565b5f604051905090565b5f80fd5b5f80fd5b5f80fd5b5f80fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b6152d182615120565b810181811067ffffffffffffffff821117156152f0576152ef61529b565b5b80604052505050565b5f615302615282565b905061530e82826152c8565b919050565b5f67ffffffffffffffff82111561532d5761532c61529b565b5b61533682615120565b9050602081019050919050565b828183375f83830152505050565b5f61536361535e84615313565b6152f9565b90508281526020810184848401111561537f5761537e615297565b5b61538a848285615343565b509392505050565b5f82601f8301126153a6576153a5615293565b5b81356153b6848260208601615351565b91505092915050565b5f602082840312156153d4576153d361528b565b5b5f82013567ffffffffffffffff8111156153f1576153f061528f565b5b6153fd84828501615392565b91505092915050565b5f819050919050565b61541881615406565b82525050565b5f6020820190506154315f83018461540f565b92915050565b61544081615406565b811461544a575f80fd5b50565b5f8135905061545b81615437565b92915050565b5f80604083850312156154775761547661528b565b5b5f6154848582860161544d565b92505060206154958582860161544d565b9150509250929050565b6154a88161507c565b81146154b2575f80fd5b50565b5f813590506154c38161549f565b92915050565b5f80604083850312156154df576154de61528b565b5b5f6154ec858286016154b5565b92505060206154fd8582860161544d565b9150509250929050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b6155398161507c565b82525050565b5f61554a8383615530565b60208301905092915050565b5f602082019050919050565b5f61556c82615507565b6155768185615511565b935061558183615521565b805f5b838110156155b1578151615598888261553f565b97506155a383615556565b925050600181019050615584565b5085935050505092915050565b5f6020820190508181035f8301526155d68184615562565b905092915050565b5f602082840312156155f3576155f261528b565b5b5f6156008482850161544d565b91505092915050565b5f8115159050919050565b61561d81615609565b82525050565b5f6020820190506156365f830184615614565b92915050565b5f80604083850312156156525761565161528b565b5b5f83013567ffffffffffffffff81111561566f5761566e61528f565b5b61567b85828601615392565b925050602061568c8582860161544d565b9150509250929050565b5f602082840312156156ab576156aa61528b565b5b5f6156b8848285016154b5565b91505092915050565b5f80604083850312156156d7576156d661528b565b5b5f83013567ffffffffffffffff8111156156f4576156f361528f565b5b61570085828601615392565b9250506020615711858286016154b5565b9150509250929050565b5f67ffffffffffffffff8211156157355761573461529b565b5b602082029050602081019050919050565b5f80fd5b5f61575c6157578461571b565b6152f9565b9050808382526020820190506020840283018581111561577f5761577e615746565b5b835b818110156157c657803567ffffffffffffffff8111156157a4576157a3615293565b5b8086016157b18982615392565b85526020850194505050602081019050615781565b5050509392505050565b5f82601f8301126157e4576157e3615293565b5b81356157f484826020860161574a565b91505092915050565b5f602082840312156158125761581161528b565b5b5f82013567ffffffffffffffff81111561582f5761582e61528f565b5b61583b848285016157d0565b91505092915050565b5f67ffffffffffffffff82111561585e5761585d61529b565b5b602082029050602081019050919050565b5f61588161587c84615844565b6152f9565b905080838252602082019050602084028301858111156158a4576158a3615746565b5b835b818110156158cd57806158b9888261544d565b8452602084019350506020810190506158a6565b5050509392505050565b5f82601f8301126158eb576158ea615293565b5b81356158fb84826020860161586f565b91505092915050565b5f806040838503121561591a5761591961528b565b5b5f83013567ffffffffffffffff8111156159375761593661528f565b5b615943858286016157d0565b925050602083013567ffffffffffffffff8111156159645761596361528f565b5b615970858286016158d7565b9150509250929050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b6159ac81615406565b82525050565b5f6159bd83836159a3565b60208301905092915050565b5f602082019050919050565b5f6159df8261597a565b6159e98185615984565b93506159f483615994565b805f5b83811015615a24578151615a0b88826159b2565b9750615a16836159c9565b9250506001810190506159f7565b5085935050505092915050565b5f6020820190508181035f830152615a4981846159d5565b905092915050565b5f8060408385031215615a6757615a6661528b565b5b5f83013567ffffffffffffffff811115615a8457615a8361528f565b5b615a9085828601615392565b925050602083013567ffffffffffffffff811115615ab157615ab061528f565b5b615abd85828601615392565b9150509250929050565b5f604082019050615ada5f83018561508d565b615ae7602083018461540f565b9392505050565b5f81519050615afc81615437565b92915050565b5f60208284031215615b1757615b1661528b565b5b5f615b2484828501615aee565b91505092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f615b6482615406565b9150615b6f83615406565b9250828203905081811115615b8757615b86615b2d565b5b92915050565b7f496e73756666696369656e7420746f6b656e2062616c616e63650000000000005f82015250565b5f615bc1601a8361521a565b9150615bcc82615b8d565b602082019050919050565b5f6020820190508181035f830152615bee81615bb5565b9050919050565b5f615bff82615406565b9150615c0a83615406565b9250828201905080821115615c2257615c21615b2d565b5b92915050565b5f606082019050615c3b5f83018661540f565b615c48602083018561540f565b8181036040830152615c5a818461522a565b9050949350505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f6002820490506001821680615ca857607f821691505b602082108103615cbb57615cba615c64565b5b50919050565b5f819050815f5260205f209050919050565b5f8154615cdf81615c91565b615ce9818661521a565b9450600182165f8114615d035760018114615d1957615d4b565b60ff198316865281151560200286019350615d4b565b615d2285615cc1565b5f5b83811015615d4357815481890152600182019150602081019050615d24565b808801955050505b50505092915050565b5f819050919050565b5f819050919050565b5f615d80615d7b615d7684615d54565b615d5d565b615406565b9050919050565b615d9081615d66565b82525050565b5f60a0820190508181035f830152615dae8188615cd3565b9050615dbd602083018761508d565b615dca604083018661540f565b615dd7606083018561540f565b615de46080830184615d87565b9695505050505050565b7f4f6e6c79206f776e6572000000000000000000000000000000000000000000005f82015250565b5f615e22600a8361521a565b9150615e2d82615dee565b602082019050919050565b5f6020820190508181035f830152615e4f81615e16565b9050919050565b7f4d7573742073756d20746f2031303030300000000000000000000000000000005f82015250565b5f615e8a60118361521a565b9150615e9582615e56565b602082019050919050565b5f6020820190508181035f830152615eb781615e7e565b9050919050565b5f604082019050615ed15f83018561540f565b615ede602083018461540f565b9392505050565b5f81905092915050565b5f615ef9826150de565b615f038185615ee5565b9350615f138185602086016150f8565b80840191505092915050565b5f615f2a8284615eef565b915081905092915050565b7f4e6f7420616e206578746572696f72206d656d626572000000000000000000005f82015250565b5f615f6960168361521a565b9150615f7482615f35565b602082019050919050565b5f6020820190508181035f830152615f9681615f5d565b9050919050565b7f4d75737420626520612062756e646c65206d656d6265720000000000000000005f82015250565b5f615fd160178361521a565b9150615fdc82615f9d565b602082019050919050565b5f6020820190508181035f830152615ffe81615fc5565b9050919050565b7f5a6f6e65206f7574206f662072616e67650000000000000000000000000000005f82015250565b5f61603960118361521a565b915061604482616005565b602082019050919050565b5f6020820190508181035f8301526160668161602d565b9050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026160b77fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8261607c565b6160c1868361607c565b95508019841693508086168417925050509392505050565b5f6160f36160ee6160e984615406565b615d5d565b615406565b9050919050565b5f819050919050565b61610c836160d9565b616120616118826160fa565b848454616088565b825550505050565b5f90565b616134616128565b61613f818484616103565b505050565b5b81811015616162576161575f8261612c565b600181019050616145565b5050565b601f8211156161a75761617881615cc1565b6161818461606d565b81016020851015616190578190505b6161a461619c8561606d565b830182616144565b50505b505050565b5f82821c905092915050565b5f6161c75f19846008026161ac565b1980831691505092915050565b5f6161df83836161b8565b9150826002028217905092915050565b6161f8826150de565b67ffffffffffffffff8111156162115761621061529b565b5b61621b8254615c91565b616226828285616166565b5f60209050601f831160018114616257575f8415616245578287015190505b61624f85826161d4565b8655506162b6565b601f19841661626586615cc1565b5f5b8281101561628c57848901518255600182019150602085019450602081019050616267565b868310156162a957848901516162a5601f8916826161b8565b8355505b6001600288020188555050505b505050505050565b5f6040820190508181035f8301526162d6818561522a565b90506162e5602083018461540f565b9392505050565b5f6080820190508181035f8301526163048187615cd3565b90508181036020830152616318818661522a565b9050616327604083018561540f565b616334606083018461540f565b95945050505050565b7f4e6f2061637469766520656c656374696f6e00000000000000000000000000005f82015250565b5f61637160128361521a565b915061637c8261633d565b602082019050919050565b5f6020820190508181035f83015261639e81616365565b9050919050565b7f416c726561647920636c61696d656400000000000000000000000000000000005f82015250565b5f6163d9600f8361521a565b91506163e4826163a5565b602082019050919050565b5f6020820190508181035f830152616406816163cd565b9050919050565b7f496e76616c69642062656e6566696369617279000000000000000000000000005f82015250565b5f61644160138361521a565b915061644c8261640d565b602082019050919050565b5f6020820190508181035f83015261646e81616435565b9050919050565b7f4e6f742061206d656d62657200000000000000000000000000000000000000005f82015250565b5f6164a9600c8361521a565b91506164b482616475565b602082019050919050565b5f6020820190508181035f8301526164d68161649d565b9050919050565b5f6080820190508181035f8301526164f58187615cd3565b90508181036020830152616509818661522a565b9050616518604083018561508d565b616525606083018461540f565b95945050505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f815461656781615c91565b6165718186615ee5565b9450600182165f811461658b57600181146165a0576165d2565b60ff19831686528115158202860193506165d2565b6165a985615cc1565b5f5b838110156165ca578154818901526001820191506020810190506165ab565b838801955050505b50505092915050565b5f6165e6828461655b565b915081905092915050565b5f6165fb82615406565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361662d5761662c615b2d565b5b600182019050919050565b7f4e6f2063616e64696461746573000000000000000000000000000000000000005f82015250565b5f61666c600d8361521a565b915061667782616638565b602082019050919050565b5f6020820190508181035f83015261669981616660565b9050919050565b7f57696e6e6572206d757374206861766520636c61696d656420746f20726563655f8201527f697665206f776e65727368697000000000000000000000000000000000000000602082015250565b5f6166fa602d8361521a565b9150616705826166a0565b604082019050919050565b5f6020820190508181035f830152616727816166ee565b9050919050565b7f4d7573742062652061206d656d626572000000000000000000000000000000005f82015250565b5f61676260108361521a565b915061676d8261672e565b602082019050919050565b5f6020820190508181035f83015261678f81616756565b9050919050565b7f416c726561647920612063616e646964617465000000000000000000000000005f82015250565b5f6167ca60138361521a565b91506167d582616796565b602082019050919050565b5f6020820190508181035f8301526167f7816167be565b9050919050565b5f6060820190508181035f8301526168168186615cd3565b9050818103602083015261682a818561522a565b9050616839604083018461508d565b949350505050565b7f4172726179206c656e677468206d69736d6174636800000000000000000000005f82015250565b5f61687560158361521a565b915061688082616841565b602082019050919050565b5f6020820190508181035f8301526168a281616869565b9050919050565b7f55736572206d75737420626520612062756e646c65206d656d626572000000005f82015250565b5f6168dd601c8361521a565b91506168e8826168a9565b602082019050919050565b5f6020820190508181035f83015261690a816168d1565b9050919050565b7f50657263656e74616765206d75737420626520706f73697469766500000000005f82015250565b5f616945601b8361521a565b915061695082616911565b602082019050919050565b5f6020820190508181035f83015261697281616939565b9050919050565b7f50657263656e7461676573206d7573742073756d20746f2031303030300000005f82015250565b5f6169ad601d8361521a565b91506169b882616979565b602082019050919050565b5f6020820190508181035f8301526169da816169a1565b9050919050565b5f6040820190508181035f8301526169f98185615187565b90508181036020830152616a0d81846159d5565b90509392505050565b7f53746565706e657373206d7573742062652030203c2073203c203165313800005f82015250565b5f616a4a601e8361521a565b9150616a5582616a16565b602082019050919050565b5f6020820190508181035f830152616a7781616a3e565b9050919050565b7f566f746572206d7573742062652061206d656d626572000000000000000000005f82015250565b5f616ab260168361521a565b9150616abd82616a7e565b602082019050919050565b5f6020820190508181035f830152616adf81616aa6565b9050919050565b7f4e6f7420612076616c69642063616e64696461746500000000000000000000005f82015250565b5f616b1a60158361521a565b9150616b2582616ae6565b602082019050919050565b5f6020820190508181035f830152616b4781616b0e565b9050919050565b7f416c726561647920766f746564000000000000000000000000000000000000005f82015250565b5f616b82600d8361521a565b9150616b8d82616b4e565b602082019050919050565b5f6020820190508181035f830152616baf81616b76565b9050919050565b5f6040820190508181035f830152616bce818561522a565b90508181036020830152616be2818461522a565b90509392505050565b7f4469766973696f6e206279207a65726f000000000000000000000000000000005f82015250565b5f616c1f60108361521a565b9150616c2a82616beb565b602082019050919050565b5f6020820190508181035f830152616c4c81616c13565b9050919050565b5f616c5d82615406565b9150616c6883615406565b9250828202616c7681615406565b91508282048414831517616c8d57616c8c615b2d565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f616ccb82615406565b9150616cd683615406565b925082616ce657616ce5616c94565b5b828204905092915050565b5f81905092915050565b5f819050815f5260205f209050919050565b5f8154616d1981615c91565b616d238186616cf1565b9450600182165f8114616d3d5760018114616d5257616d84565b60ff1983168652811515820286019350616d84565b616d5b85616cfb565b5f5b83811015616d7c57815481890152600182019150602081019050616d5d565b838801955050505b50505092915050565b5f616d988284616d0d565b915081905092915050565b5f81549050616db181615c91565b9050919050565b5f819050815f5260205f209050919050565b818103616dd8575050616ead565b616de182616da3565b67ffffffffffffffff811115616dfa57616df961529b565b5b616e048254615c91565b616e0f828285616166565b5f601f831160018114616e3c575f8415616e2a578287015490505b616e3485826161d4565b865550616ea6565b601f198416616e4a87616db8565b9650616e5586615cc1565b5f5b82811015616e7c57848901548255600182019150600185019450602081019050616e57565b86831015616e995784890154616e95601f8916826161b8565b8355505b6001600288020188555050505b5050505050505b565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603160045260245ffd5b50565b5f616eea5f83616cf1565b9150616ef582616edc565b5f82019050919050565b5f616f0982616edf565b9150819050919050565b7f45544820636c61696d206661696c6564000000000000000000000000000000005f82015250565b5f616f4760108361521a565b9150616f5282616f13565b602082019050919050565b5f6020820190508181035f830152616f7481616f3b565b9050919050565b7f455448207472616e73666572206661696c6564000000000000000000000000005f82015250565b5f616faf60138361521a565b9150616fba82616f7b565b602082019050919050565b5f6020820190508181035f830152616fdc81616fa3565b9050919050565b5f606082019050616ff65f83018661540f565b6170036020830185615614565b8181036040830152617015818461522a565b9050949350505050565b5f60a0820190508181035f8301526170378188615cd3565b9050818103602083015261704b818761522a565b905061705a604083018661508d565b617067606083018561540f565b8181036080830152617079818461522a565b9050969550505050505056fea2646970667358221220e61ca743da8bf74312a4d4f6b348b3282428098da8234b281a8987056df9bb6364736f6c63430008140033"},of=[{type:"function",name:"getFlavorAddress",inputs:[{name:"_name",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"knownflavors",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"listFlavors",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"managedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"newFlavor",inputs:[{name:"_flavorname",type:"string",internalType:"string"},{name:"_flavoraddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"newHolonBundle",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"setFactories",inputs:[{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManagedFactory",inputs:[{name:"_managedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setZonedFactory",inputs:[{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"zonedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"HolonCreated",inputs:[{name:"holonAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonName",type:"string",indexed:!1,internalType:"string"},{name:"flavor",type:"string",indexed:!1,internalType:"string"},{name:"creator",type:"address",indexed:!0,internalType:"address"},{name:"timestamp",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"NewFlavor",inputs:[{name:"flavor",type:"address",indexed:!0,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],ff=[{type:"function",name:"createSplitter",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"},{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"managedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"},{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"setFactories",inputs:[{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManagedFactory",inputs:[{name:"_managedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setZonedFactory",inputs:[{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"zonedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],cf=[{type:"constructor",inputs:[{name:"_botAddress",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"createManaged",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],lf=[{type:"constructor",inputs:[{name:"_botAddress",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"createZoned",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],uf=[{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],df=[{type:"function",name:"createBundle",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_steepness",type:"uint256",internalType:"uint256"},{name:"_nzones",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],pf=[{type:"constructor",inputs:[{name:"initialSupply",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"allowance",inputs:[{name:"owner",type:"address",internalType:"address"},{name:"spender",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"approve",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"function",name:"balanceOf",inputs:[{name:"account",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"decimals",inputs:[],outputs:[{name:"",type:"uint8",internalType:"uint8"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"symbol",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"totalSupply",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"transfer",inputs:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"function",name:"transferFrom",inputs:[{name:"from",type:"address",internalType:"address"},{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"event",name:"Approval",inputs:[{name:"owner",type:"address",indexed:!0,internalType:"address"},{name:"spender",type:"address",indexed:!0,internalType:"address"},{name:"value",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Transfer",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"value",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"error",name:"ERC20InsufficientAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"allowance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ERC20InsufficientBalance",inputs:[{name:"sender",type:"address",internalType:"address"},{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ERC20InvalidApprover",inputs:[{name:"approver",type:"address",internalType:"address"}]},{type:"error",name:"ERC20InvalidReceiver",inputs:[{name:"receiver",type:"address",internalType:"address"}]},{type:"error",name:"ERC20InvalidSender",inputs:[{name:"sender",type:"address",internalType:"address"}]},{type:"error",name:"ERC20InvalidSpender",inputs:[{name:"spender",type:"address",internalType:"address"}]}],hf={Splitter:tf,Managed:nf,Zoned:sf,Appreciative:rf,Bundle:af,Holons:of,SplitterFactory:ff,ManagedFactory:cf,ZonedFactory:lf,AppreciativeFactory:uf,BundleFactory:df,TestToken:pf};class yf{constructor(e){this.chainManager=e,this.deployedContracts={},this.ethers=null}async _loadEthers(){return this.ethers||(this.ethers=await Promise.resolve().then(()=>require("./index-Bwg3OzRM.cjs"))),this.ethers}async deployAll(e={}){const t=await this._loadEthers(),n=this.chainManager.getSigner(),s=await n.getAddress(),r=e.botAddress||s,a=e.testTokenSupply||"1000000",i=!1!==e.deployTestToken,o=e.onProgress||(()=>{}),f={network:this.chainManager.networkName,chainId:this.chainManager.getChainId(),deployer:s,botAddress:r,timestamp:(new Date).toISOString(),contracts:{}};try{o({step:1,total:i?8:7,message:"Deploying ManagedFactory..."});const e=await this._deployContract(cf.abi,cf.bytecode,[r]);f.contracts.managedFactory=e.address,o({step:1,done:!0,address:e.address}),o({step:2,total:i?8:7,message:"Deploying ZonedFactory..."});const n=await this._deployContract(lf.abi,lf.bytecode,[r]);f.contracts.zonedFactory=n.address,o({step:2,done:!0,address:n.address}),o({step:3,total:i?8:7,message:"Deploying SplitterFactory..."});const s=await this._deployContract(ff.abi,ff.bytecode,[]);f.contracts.splitterFactory=s.address,o({step:3,done:!0,address:s.address}),o({step:4,total:i?8:7,message:"Deploying AppreciativeFactory..."});const c=await this._deployContract(uf.abi,uf.bytecode,[]);f.contracts.appreciativeFactory=c.address,o({step:4,done:!0,address:c.address}),o({step:5,total:i?8:7,message:"Deploying BundleFactory..."});const l=await this._deployContract(df.abi,df.bytecode,[]);f.contracts.bundleFactory=l.address,o({step:5,done:!0,address:l.address}),o({step:6,total:i?8:7,message:"Deploying Holons Registry..."});const u=await this._deployContract(of.abi,of.bytecode,[]);if(f.contracts.holons=u.address,o({step:6,done:!0,address:u.address}),o({step:7,total:i?8:7,message:"Configuring Holons Registry..."}),await u.contract.setFactories(e.address,n.address),await u.contract.newFlavor("Splitter",s.address),await u.contract.newFlavor("Managed",e.address),await u.contract.newFlavor("Zoned",n.address),await u.contract.newFlavor("Appreciative",c.address),await u.contract.newFlavor("Bundle",l.address),o({step:7,done:!0,message:"Registry configured"}),i){o({step:8,total:8,message:"Deploying TestToken..."});const e=t.parseEther(a),n=await this._deployContract(pf.abi,pf.bytecode,[e]);f.contracts.testToken=n.address,o({step:8,done:!0,address:n.address})}this.deployedContracts=f.contracts,f.explorerUrls={};for(const[t,r]of Object.entries(f.contracts)){const e=Xo(f.network,r);e&&(f.explorerUrls[t]=e)}return f}catch(c){throw new Error(`Deployment failed: ${c.message}`)}}async deploySplitter(e,t,n=70,s={}){const r=this.chainManager.getSigner(),a=await r.getAddress(),i=s.creatorUserId||e,o=s.managedFactory||this.deployedContracts.managedFactory,f=s.zonedFactory||this.deployedContracts.zonedFactory;if(!o||!f)throw new Error("Factories not deployed. Run deployAll() first or provide factory addresses.");const c=await this._deployContract(tf.abi,tf.bytecode,[a,i,t,n,o,f]);return await c.contract.setContractSplit(n,100-n),await c.contract.createManagedContract(i,t,0),await c.contract.createZonedContract(i,t,6),{...c,holonId:e,type:"Splitter",splitPercentage:n}}async deployManaged(e,t={}){const n=this.chainManager.getSigner(),s=await n.getAddress(),r=t.botAddress||s;return{...await this._deployContract(nf.abi,nf.bytecode,[s,e,r]),type:"Managed"}}async deployZoned(e,t=6,n={}){const s=this.chainManager.getSigner(),r=await s.getAddress(),a=n.botAddress||r,i=n.creatorUserId||"creator";return{...await this._deployContract(sf.abi,sf.bytecode,[i,r,e,t,a]),type:"Zoned",nZones:t}}async deployAppreciative(e,t,n={}){const s=this.chainManager.getSigner(),r=await s.getAddress();return{...await this._deployContract(rf.abi,rf.bytecode,[e,t,r]),type:"Appreciative"}}async deployBundle(e,t,n=6,s={}){const r=await this._loadEthers(),a=this.chainManager.getSigner(),i=await a.getAddress(),o=s.creatorUserId||"creator",f=t||r.parseEther("0.5"),c=af.abi||af,l=af.bytecode;if(!l)throw new Error("Bundle bytecode not available. Please rebuild contracts.");return{...await this._deployContract(c,l,[i,o,e,f,n]),type:"Bundle",steepness:f,nZones:n,creatorUserId:o,name:e}}async deployBundleDirect(e,t,n={}){const s=n.steepness,r=n.nZones||6;return this.deployBundle(t,s,r,{creatorUserId:e,...n})}async deployTestToken(e="1000000"){const t=(await this._loadEthers()).parseEther(e);return{...await this._deployContract(pf.abi,pf.bytecode,[t]),type:"TestToken",initialSupply:e}}async createHolonBundle(e,t,n=70){if(!this.deployedContracts.holons)throw new Error("Holons registry not deployed. Run deployAll() first.");const s=await this.chainManager.getContract(this.deployedContracts.holons,of.abi),r=await s.newHolonBundle(e,t,n),a=await r.wait(),i=a.logs.find(e=>{try{const t=s.interface.parseLog(e);return"NewHolon"===t?.name}catch{return!1}});return{address:i?s.interface.parseLog(i).args.addr:await s.toAddress(t),txHash:a.hash,name:t,creatorUserId:e}}async getContract(e,t){const n=hf[t];if(!n)throw new Error(`Unknown contract type: ${t}`);return this.chainManager.getContract(e,n.abi)}getDeployedAddresses(){return{...this.deployedContracts}}loadDeployedAddresses(e){this.deployedContracts={...e}}async _deployContract(e,t,n){const s=await this.chainManager.deployContract(e,t,n);return{contract:s.contract,address:s.address,txHash:s.txHash,explorerUrl:Xo(this.chainManager.networkName,s.address)}}}class mf{constructor(e,t,n){this.contract=e,this.type=t,this.chainManager=n,this.ethers=null}async _loadEthers(){return this.ethers||(this.ethers=await Promise.resolve().then(()=>require("./index-Bwg3OzRM.cjs"))),this.ethers}async addMember(e){const t=await this.contract.addMember(e),n=await t.wait();return{txHash:n.hash,receipt:n}}async addMembers(e){const t=await this.contract.addMembers(e),n=await t.wait();return{txHash:n.hash,receipt:n}}async getMembers(){await this.contract.userIds();try{const e=[];let t=0;for(;;)try{const n=await this.contract.userIds(t);e.push(n),t++}catch{break}return e}catch{return[]}}async isMember(e){try{return"Splitter"===this.type?await this.contract.isSplitterMember(e):await this.contract.isMember(e)}catch{return!1}}async getUserAddress(e){return this.contract.userIdToAddress(e)}async reward(e,t){const n=await this._loadEthers(),s="string"==typeof t?n.parseUnits(t,18):t,r=await this.contract.reward(e,s),a=await r.wait();return{txHash:a.hash,receipt:a}}async rewardEth(e){const t=(await this._loadEthers()).parseEther(e),n=await this.contract.reward("0x0000000000000000000000000000000000000000",t,{value:t}),s=await n.wait();return{txHash:s.hash,receipt:s}}async sendEth(e){const t=await this._loadEthers(),n=this.chainManager.getSigner(),s=t.parseEther(e),r=await n.sendTransaction({to:await this.contract.getAddress(),value:s}),a=await r.wait();return{txHash:a.hash,receipt:a}}async claim(e,t){const n=await this.contract.claim(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async getEthBalance(e){const t=await this._loadEthers(),n=await this.contract.etherBalance(e);return t.formatEther(n)}async getTokenBalance(e,t){const n=await this._loadEthers(),s=await this.contract.tokenBalance(e,t);return n.formatUnits(s,18)}async hasClaimed(e){return this.contract.hasClaimed(e)}async getTotalDeposited(e){const t=await this._loadEthers(),n=await this.contract.totalDeposited(e);return t.formatUnits(n,18)}async setContractSplit(e,t){if(this._requireType(["Splitter"]),e+t!==100)throw new Error("Percentages must sum to 100");const n=await this.contract.setContractSplit(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async getContractSplit(){this._requireType(["Splitter"]);const e=await this.contract.internalContractSplitPercentage(),t=await this.contract.externalContractSplitPercentage();return{internal:Number(e),external:Number(t)}}async createManagedContract(e,t,n=0){this._requireType(["Splitter"]);const s=await this.contract.createManagedContract(e,t,n),r=await s.wait();return{address:await this.contract.contractsByType(`${t}_managed`),txHash:r.hash,receipt:r}}async createZonedContract(e,t,n=6){this._requireType(["Splitter"]);const s=await this.contract.createZonedContract(e,t,n),r=await s.wait();return{address:await this.contract.contractsByType(`${t}_zoned`),txHash:r.hash,receipt:r}}async getChildContractKeys(){return this._requireType(["Splitter"]),this.contract.getContractKeys()}async getChildContracts(){this._requireType(["Splitter"]);const[e,t]=await this.contract.getContractAddresses();return{keys:e,addresses:t}}async getChildContract(e){return this._requireType(["Splitter"]),this.contract.contractsByType(e)}async setAppreciation(e,t){if(this._requireType(["Managed"]),e.length!==t.length)throw new Error("userIds and amounts arrays must have same length");const n=await this.contract.setAppreciation(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async getAppreciation(e){this._requireType(["Managed"]);const t=await this.contract.appreciation(e);return Number(t)}async getTotalAppreciation(){this._requireType(["Managed"]);const e=await this.contract.totalappreciation();return Number(e)}async addToZone(e,t,n){this._requireType(["Zoned"]);const s=await this.contract.addToZone(e,t,n),r=await s.wait();return{txHash:r.hash,receipt:r}}async removeFromZone(e,t){this._requireType(["Zoned"]);const n=await this.contract.removeFromZone(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async getZone(e){this._requireType(["Zoned"]);const t=await this.contract.zones(e);return Number(t)}async getNumZones(){this._requireType(["Zoned"]);const e=await this.contract.nzones();return Number(e)}async setZoneParameters(e,t,n,s){this._requireType(["Zoned"]);const r=await this.contract.setRewardFunction(e,t,n,s),a=await r.wait();return{txHash:a.hash,receipt:a}}async appreciate(e,t,n){this._requireType(["Appreciative"]);const s=await this.contract.appreciate(e,t,n),r=await s.wait();return{txHash:r.hash,receipt:r}}async getAppreciationGiven(e){this._requireType(["Appreciative"]);const t=await this.contract.appreciationGiven(e);return Number(t)}async getAppreciationReceived(e){this._requireType(["Appreciative"]);const t=await this.contract.appreciationReceived(e);return Number(t)}async getAppreciationRemaining(e){this._requireType(["Appreciative"]);const t=await this.contract.appreciationRemaining(e);return Number(t)}async setSteepness(e){this._requireType(["Bundle"]);const t=await this._loadEthers(),n="string"==typeof e?t.parseEther(e):e,s=await this.contract.setSteepness(n),r=await s.wait();return{txHash:r.hash,receipt:r}}async getSteepness(){this._requireType(["Bundle"]);const e=await this._loadEthers(),t=await this.contract.steepness();return e.formatEther(t)}async setInteriorSplit(e,t){this._requireType(["Bundle"]);if(100!==t.reduce((e,t)=>e+t,0))throw new Error("Percentages must sum to 100");const n=await this.contract.setInteriorSplit(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async startElection(){this._requireType(["Bundle"]);const e=await this.contract.startElection(),t=await e.wait();return{txHash:t.hash,receipt:t}}async nominateSelf(){this._requireType(["Bundle"]);const e=await this.contract.nominateSelf(),t=await e.wait();return{txHash:t.hash,receipt:t}}async vote(e){this._requireType(["Bundle"]);const t=await this.contract.vote(e),n=await t.wait();return{txHash:n.hash,receipt:n}}async finalizeElection(){this._requireType(["Bundle"]);const e=await this.contract.finalizeElection(),t=await e.wait();return{txHash:t.hash,receipt:t}}async getName(){return this.contract.name()}async getOwner(){return this.contract.owner()}async getBotAddress(){try{return await this.contract.botAddress()}catch{return null}}async getCreatorUserId(){try{return await this.contract.creatorUserId()}catch{return null}}async getAddress(){return this.contract.getAddress()}getType(){return this.type}_requireType(e){if(!e.includes(this.type))throw new Error(`Operation only available for ${e.join("/")} contracts. This is a ${this.type} contract.`)}getRawContract(){return this.contract}async call(e,...t){return this.contract[e](...t)}async send(e,...t){const n=await this.contract[e](...t),s=await n.wait();return{txHash:s.hash,receipt:s}}}class gf{constructor(e,t){this.chainManager=e,this.deployer=t||new yf(e),this.holonContracts=new Map,this.storage=null}setStorage(e){this.storage=e}async deploy(e,t="Splitter",n={}){if(this.holonContracts.has(e))throw new Error(`Holon ${e} already has a contract. Use unlink() first to remove it.`);const s=n.name||e,r=n.creatorUserId||e;let a;switch(t){case"Splitter":a=await this.deployer.deploySplitter(e,s,n.splitPercentage||70,{creatorUserId:r,...n});break;case"Managed":a=await this.deployer.deployManaged(s,n);break;case"Zoned":a=await this.deployer.deployZoned(s,n.nZones||6,n);break;case"Appreciative":a=await this.deployer.deployAppreciative(s,r,n);break;case"Bundle":a=await this.deployer.deployBundle(s,n.steepness,n.nZones||6,{creatorUserId:r,...n});break;default:throw new Error(`Unknown contract type: ${t}`)}const i=new mf(a.contract,t,this.chainManager),o={holonId:e,address:a.address,type:t,contract:a.contract,operations:i,deployedAt:(new Date).toISOString(),txHash:a.txHash};return this.holonContracts.set(e,o),await this._saveMapping(e,o),{contract:a.contract,address:a.address,operations:i,txHash:a.txHash,type:t}}async link(e,t,n="Splitter"){if(this.holonContracts.has(e))throw new Error(`Holon ${e} already has a contract. Use unlink() first.`);const s=hf[n];if(!s)throw new Error(`Unknown contract type: ${n}`);const r=await this.chainManager.getContract(t,s.abi);try{await r.name()}catch(o){throw new Error(`Invalid contract at ${t}: ${o.message}`)}const a=new mf(r,n,this.chainManager),i={holonId:e,address:t,type:n,contract:r,operations:a,linkedAt:(new Date).toISOString()};return this.holonContracts.set(e,i),await this._saveMapping(e,i),{contract:r,address:t,operations:a,type:n}}async unlink(e){return!!this.holonContracts.has(e)&&(this.holonContracts.delete(e),this.storage&&await(this.storage.delete?.(`holon_contract:${e}`)),!0)}getContract(e){const t=this.holonContracts.get(e);return t?.contract||null}getAddress(e){const t=this.holonContracts.get(e);return t?.address||null}getOperations(e){const t=this.holonContracts.get(e);return t?.operations||null}getType(e){const t=this.holonContracts.get(e);return t?.type||null}hasContract(e){return this.holonContracts.has(e)}listAll(){const e=[];for(const[t,n]of this.holonContracts)e.push({holonId:t,address:n.address,type:n.type,deployedAt:n.deployedAt,linkedAt:n.linkedAt});return e}getByType(e){const t=[];for(const[n,s]of this.holonContracts)s.type===e&&t.push({holonId:n,address:s.address});return t}async loadFromStorage(){if(!this.storage)return 0;const e=await(this.storage.get?.("holon_contracts_index"))||[];let t=0;for(const s of e)try{const e=await(this.storage.get?.(`holon_contract:${s}`));if(e&&e.address&&e.type){const n=hf[e.type];if(n){const r=await this.chainManager.getContract(e.address,n.abi),a=new mf(r,e.type,this.chainManager);this.holonContracts.set(s,{...e,contract:r,operations:a}),t++}}}catch(n){console.warn(`Failed to load contract for holon ${s}: ${n.message}`)}return t}async _saveMapping(e,t){if(!this.storage)return;await(this.storage.set?.(`holon_contract:${e}`,{holonId:t.holonId,address:t.address,type:t.type,deployedAt:t.deployedAt,linkedAt:t.linkedAt,txHash:t.txHash}));const n=await(this.storage.get?.("holon_contracts_index"))||[];n.includes(e)||(n.push(e),await(this.storage.set?.("holon_contracts_index",n)))}requireOperations(e){const t=this.getOperations(e);if(!t)throw new Error(`Holon ${e} has no linked contract. Deploy or link one first.`);return t}}const bf="6.16.0";function wf(e,t,n){const s=t.split("|").map(e=>e.trim());for(let a=0;a<s.length;a++)switch(t){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof e===t)return}const r=new Error(`invalid value for type ${t}`);throw r.code="INVALID_ARGUMENT",r.argument=`value.${n}`,r.value=e,r}async function vf(e){const t=Object.keys(e);return(await Promise.all(t.map(t=>Promise.resolve(e[t])))).reduce((e,n,s)=>(e[t[s]]=n,e),{})}function _f(e,t,n){for(let s in t){let r=t[s];const a=n?n[s]:null;a&&wf(r,a,s),Object.defineProperty(e,s,{enumerable:!0,value:r,writable:!1})}}function Tf(e,t){if(null==e)return"null";if(null==t&&(t=new Set),"object"==typeof e){if(t.has(e))return"[Circular]";t.add(e)}if(Array.isArray(e))return"[ "+e.map(e=>Tf(e,t)).join(", ")+" ]";if(e instanceof Uint8Array){const t="0123456789abcdef";let n="0x";for(let s=0;s<e.length;s++)n+=t[e[s]>>4],n+=t[15&e[s]];return n}if("object"==typeof e&&"function"==typeof e.toJSON)return Tf(e.toJSON(),t);switch(typeof e){case"boolean":case"number":case"symbol":return e.toString();case"bigint":return BigInt(e).toString();case"string":return JSON.stringify(e);case"object":{const n=Object.keys(e);return n.sort(),"{ "+n.map(n=>`${Tf(n,t)}: ${Tf(e[n],t)}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function xf(e,t){return e&&e.code===t}function Af(e){return xf(e,"CALL_EXCEPTION")}function Sf(e,t,n){let s,r=e;{const s=[];if(n){if("message"in n||"code"in n||"name"in n)throw new Error(`value will overwrite populated values: ${Tf(n)}`);for(const e in n){if("shortMessage"===e)continue;const t=n[e];s.push(e+"="+Tf(t))}}s.push(`code=${t}`),s.push(`version=${bf}`),s.length&&(e+=" ("+s.join(", ")+")")}switch(t){case"INVALID_ARGUMENT":s=new TypeError(e);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":s=new RangeError(e);break;default:s=new Error(e)}return _f(s,{code:t}),n&&Object.assign(s,n),null==s.shortMessage&&_f(s,{shortMessage:r}),s}function kf(e,t,n,s){if(!e)throw Sf(t,n,s)}function Ef(e,t,n,s){kf(e,t,"INVALID_ARGUMENT",{argument:n,value:s})}function Nf(e,t,n){null==n&&(n=""),n&&(n=": "+n),kf(e>=t,"missing argument"+n,"MISSING_ARGUMENT",{count:e,expectedCount:t}),kf(e<=t,"too many arguments"+n,"UNEXPECTED_ARGUMENT",{count:e,expectedCount:t})}const If=["NFD","NFC","NFKD","NFKC"].reduce((e,t)=>{try{if("test"!=="test".normalize(t))throw new Error("bad");if("NFD"===t){const e=String.fromCharCode(233).normalize("NFD");if(e!==String.fromCharCode(101,769))throw new Error("broken")}e.push(t)}catch(n){}return e},[]);function Cf(e){kf(If.indexOf(e)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:e}})}function Of(e,t,n){if(null==n&&(n=""),e!==t){let e=n,t="new";n&&(e+=".",t+=" "+n),kf(!1,`private constructor; use ${e}from* methods`,"UNSUPPORTED_OPERATION",{operation:t})}}function Rf(e,t,n){if(e instanceof Uint8Array)return n?new Uint8Array(e):e;if("string"==typeof e&&e.length%2==0&&e.match(/^0x[0-9a-f]*$/i)){const t=new Uint8Array((e.length-2)/2);let n=2;for(let s=0;s<t.length;s++)t[s]=parseInt(e.substring(n,n+2),16),n+=2;return t}Ef(!1,"invalid BytesLike value",t||"value",e)}function $f(e,t){return Rf(e,t,!1)}function Pf(e,t){return Rf(e,t,!0)}function Mf(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))&&(("number"!=typeof t||e.length===2+2*t)&&(!0!==t||e.length%2==0))}function Df(e){return Mf(e,!0)||e instanceof Uint8Array}const Ff="0123456789abcdef";function Hf(e){const t=$f(e);let n="0x";for(let s=0;s<t.length;s++){const e=t[s];n+=Ff[(240&e)>>4]+Ff[15&e]}return n}function Bf(e){return"0x"+e.map(e=>Hf(e).substring(2)).join("")}function jf(e,t,n){const s=$f(e);return null!=n&&n>s.length&&kf(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:s,length:s.length,offset:n}),Hf(s.slice(null==t?0:t,null==n?s.length:n))}function Uf(e,t,n){const s=$f(e);kf(t>=s.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(s),length:t,offset:t+1});const r=new Uint8Array(t);return r.fill(0),n?r.set(s,t-s.length):r.set(s,0),Hf(r)}function Lf(e,t){return Uf(e,t,!0)}function qf(e,t){return Uf(e,t,!1)}const Jf=BigInt(0),Gf=BigInt(1),zf=9007199254740991;function Wf(e,t){const n=Yf(e,"value"),s=BigInt(ec(t,"width"));if(kf(n>>s===Jf,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:e}),n>>s-Gf){return-((~n&(Gf<<s)-Gf)+Gf)}return n}function Kf(e,t){let n=Zf(e,"value");const s=BigInt(ec(t,"width")),r=Gf<<s-Gf;if(n<Jf){n=-n,kf(n<=r,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e});return(~n&(Gf<<s)-Gf)+Gf}return kf(n<r,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e}),n}function Vf(e,t){const n=Yf(e,"value"),s=BigInt(ec(t,"bits"));return n&(Gf<<s)-Gf}function Zf(e,t){switch(typeof e){case"bigint":return e;case"number":return Ef(Number.isInteger(e),"underflow",t||"value",e),Ef(e>=-zf&&e<=zf,"overflow",t||"value",e),BigInt(e);case"string":try{if(""===e)throw new Error("empty string");return"-"===e[0]&&"-"!==e[1]?-BigInt(e.substring(1)):BigInt(e)}catch(n){Ef(!1,`invalid BigNumberish string: ${n.message}`,t||"value",e)}}Ef(!1,"invalid BigNumberish value",t||"value",e)}function Yf(e,t){const n=Zf(e,t);return kf(n>=Jf,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:e}),n}const Xf="0123456789abcdef";function Qf(e){if(e instanceof Uint8Array){let t="0x0";for(const n of e)t+=Xf[n>>4],t+=Xf[15&n];return BigInt(t)}return Zf(e)}function ec(e,t){switch(typeof e){case"bigint":return Ef(e>=-zf&&e<=zf,"overflow",t||"value",e),Number(e);case"number":return Ef(Number.isInteger(e),"underflow",t||"value",e),Ef(e>=-zf&&e<=zf,"overflow",t||"value",e),e;case"string":try{if(""===e)throw new Error("empty string");return ec(BigInt(e),t)}catch(n){Ef(!1,`invalid numeric string: ${n.message}`,t||"value",e)}}Ef(!1,"invalid numeric value",t||"value",e)}function tc(e){return ec(Qf(e))}function nc(e,t){const n=Yf(e,"value");let s=n.toString(16);if(null==t)s.length%2&&(s="0"+s);else{const r=ec(t,"width");if(0===r&&n===Jf)return"0x";for(kf(2*r>=s.length,`value exceeds width (${r} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:e});s.length<2*r;)s="0"+s}return"0x"+s}function sc(e,t){const n=Yf(e,"value");if(n===Jf){const e=null!=t?ec(t,"width"):0;return new Uint8Array(e)}let s=n.toString(16);if(s.length%2&&(s="0"+s),null!=t){const n=ec(t,"width");for(;s.length<2*n;)s="00"+s;kf(2*n===s.length,`value exceeds width (${n} bytes)`,"NUMERIC_FAULT",{operation:"toBeArray",fault:"overflow",value:e})}const r=new Uint8Array(s.length/2);for(let a=0;a<r.length;a++){const e=2*a;r[a]=parseInt(s.substring(e,e+2),16)}return r}class rc{filter;emitter;#e;constructor(e,t,n){this.#e=t,_f(this,{emitter:e,filter:n})}async removeListener(){null!=this.#e&&await this.emitter.off(this.filter,this.#e)}}function ac(e,t,n,s,r){if("BAD_PREFIX"===e||"UNEXPECTED_CONTINUE"===e){let e=0;for(let s=t+1;s<n.length&&n[s]>>6==2;s++)e++;return e}return"OVERRUN"===e?n.length-t-1:0}const ic=Object.freeze({error:function(e,t,n,s,r){Ef(!1,`invalid codepoint at offset ${t}; ${e}`,"bytes",n)},ignore:ac,replace:function(e,t,n,s,r){return"OVERLONG"===e?(Ef("number"==typeof r,"invalid bad code point for replacement","badCodepoint",r),s.push(r),0):(s.push(65533),ac(e,t,n))}});function oc(e,t){null==t&&(t=ic.error);const n=$f(e,"bytes"),s=[];let r=0;for(;r<n.length;){const e=n[r++];if(!(e>>7)){s.push(e);continue}let a=null,i=null;if(192==(224&e))a=1,i=127;else if(224==(240&e))a=2,i=2047;else{if(240!=(248&e)){r+=t(128==(192&e)?"UNEXPECTED_CONTINUE":"BAD_PREFIX",r-1,n,s);continue}a=3,i=65535}if(r-1+a>=n.length){r+=t("OVERRUN",r-1,n,s);continue}let o=e&(1<<8-a-1)-1;for(let f=0;f<a;f++){let e=n[r];if(128!=(192&e)){r+=t("MISSING_CONTINUE",r,n,s),o=null;break}o=o<<6|63&e,r++}null!==o&&(o>1114111?r+=t("OUT_OF_RANGE",r-1-a,n,s,o):o>=55296&&o<=57343?r+=t("UTF16_SURROGATE",r-1-a,n,s,o):o<=i?r+=t("OVERLONG",r-1-a,n,s,o):s.push(o))}return s}function fc(e,t){Ef("string"==typeof e,"invalid string value","str",e),null!=t&&(Cf(t),e=e.normalize(t));let n=[];for(let s=0;s<e.length;s++){const t=e.charCodeAt(s);if(t<128)n.push(t);else if(t<2048)n.push(t>>6|192),n.push(63&t|128);else if(55296==(64512&t)){s++;const r=e.charCodeAt(s);Ef(s<e.length&&56320==(64512&r),"invalid surrogate pair","str",e);const a=65536+((1023&t)<<10)+(1023&r);n.push(a>>18|240),n.push(a>>12&63|128),n.push(a>>6&63|128),n.push(63&a|128)}else n.push(t>>12|224),n.push(t>>6&63|128),n.push(63&t|128)}return new Uint8Array(n)}function cc(e,t){return oc(e,t).map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10&1023),56320+(1023&e)))).join("")}const lc=BigInt(-1),uc=BigInt(0),dc=BigInt(1),pc=BigInt(5),hc={};let yc="0000";for(;yc.length<80;)yc+=yc;function mc(e){let t=yc;for(;t.length<e;)t+=t;return BigInt("1"+t.substring(0,e))}function gc(e,t,n){const s=BigInt(t.width);if(t.signed){const t=dc<<s-dc;kf(null==n||e>=-t&&e<t,"overflow","NUMERIC_FAULT",{operation:n,fault:"overflow",value:e}),e=e>uc?Wf(Vf(e,s),s):-Wf(Vf(-e,s),s)}else{const t=dc<<s;kf(null==n||e>=0&&e<t,"overflow","NUMERIC_FAULT",{operation:n,fault:"overflow",value:e}),e=(e%t+t)%t&t-dc}return e}function bc(e){"number"==typeof e&&(e=`fixed128x${e}`);let t=!0,n=128,s=18;if("string"==typeof e)if("fixed"===e);else if("ufixed"===e)t=!1;else{const r=e.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);Ef(r,"invalid fixed format","format",e),t="u"!==r[1],n=parseInt(r[2]),s=parseInt(r[3])}else if(e){const r=e,a=(e,t,n)=>null==r[e]?n:(Ef(typeof r[e]===t,"invalid fixed format ("+e+" not "+t+")","format."+e,r[e]),r[e]);t=a("signed","boolean",t),n=a("width","number",n),s=a("decimals","number",s)}Ef(n%8==0,"invalid FixedNumber width (not byte aligned)","format.width",n),Ef(s<=80,"invalid FixedNumber decimals (too large)","format.decimals",s);return{signed:t,width:n,decimals:s,name:(t?"":"u")+"fixed"+String(n)+"x"+String(s)}}class wc{format;#t;#n;#s;_value;constructor(e,t,n){Of(e,hc,"FixedNumber"),this.#n=t,this.#t=n;const s=function(e,t){let n="";e<uc&&(n="-",e*=lc);let s=e.toString();if(0===t)return n+s;for(;s.length<=t;)s=yc+s;const r=s.length-t;for(s=s.substring(0,r)+"."+s.substring(r);"0"===s[0]&&"."!==s[1];)s=s.substring(1);for(;"0"===s[s.length-1]&&"."!==s[s.length-2];)s=s.substring(0,s.length-1);return n+s}(t,n.decimals);_f(this,{format:n.name,_value:s}),this.#s=mc(n.decimals)}get signed(){return this.#t.signed}get width(){return this.#t.width}get decimals(){return this.#t.decimals}get value(){return this.#n}#r(e){Ef(this.format===e.format,"incompatible format; use fixedNumber.toFormat","other",e)}#a(e,t){return e=gc(e,this.#t,t),new wc(hc,e,this.#t)}#i(e,t){return this.#r(e),this.#a(this.#n+e.#n,t)}addUnsafe(e){return this.#i(e)}add(e){return this.#i(e,"add")}#o(e,t){return this.#r(e),this.#a(this.#n-e.#n,t)}subUnsafe(e){return this.#o(e)}sub(e){return this.#o(e,"sub")}#f(e,t){return this.#r(e),this.#a(this.#n*e.#n/this.#s,t)}mulUnsafe(e){return this.#f(e)}mul(e){return this.#f(e,"mul")}mulSignal(e){this.#r(e);const t=this.#n*e.#n;return kf(t%this.#s===uc,"precision lost during signalling mul","NUMERIC_FAULT",{operation:"mulSignal",fault:"underflow",value:this}),this.#a(t/this.#s,"mulSignal")}#c(e,t){return kf(e.#n!==uc,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#r(e),this.#a(this.#n*this.#s/e.#n,t)}divUnsafe(e){return this.#c(e)}div(e){return this.#c(e,"div")}divSignal(e){kf(e.#n!==uc,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#r(e);const t=this.#n*this.#s;return kf(t%e.#n===uc,"precision lost during signalling div","NUMERIC_FAULT",{operation:"divSignal",fault:"underflow",value:this}),this.#a(t/e.#n,"divSignal")}cmp(e){let t=this.value,n=e.value;const s=this.decimals-e.decimals;return s>0?n*=mc(s):s<0&&(t*=mc(-s)),t<n?-1:t>n?1:0}eq(e){return 0===this.cmp(e)}lt(e){return this.cmp(e)<0}lte(e){return this.cmp(e)<=0}gt(e){return this.cmp(e)>0}gte(e){return this.cmp(e)>=0}floor(){let e=this.#n;return this.#n<uc&&(e-=this.#s-dc),e=this.#n/this.#s*this.#s,this.#a(e,"floor")}ceiling(){let e=this.#n;return this.#n>uc&&(e+=this.#s-dc),e=this.#n/this.#s*this.#s,this.#a(e,"ceiling")}round(e){if(null==e&&(e=0),e>=this.decimals)return this;const t=this.decimals-e,n=pc*mc(t-1);let s=this.value+n;const r=mc(t);return s=s/r*r,gc(s,this.#t,"round"),new wc(hc,s,this.#t)}isZero(){return this.#n===uc}isNegative(){return this.#n<uc}toString(){return this._value}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return wc.fromString(this.toString(),e)}static fromValue(e,t,n){const s=null==t?0:ec(t),r=bc(n);let a=Zf(e,"value");const i=s-r.decimals;if(i>0){const t=mc(i);kf(a%t===uc,"value loses precision for format","NUMERIC_FAULT",{operation:"fromValue",fault:"underflow",value:e}),a/=t}else i<0&&(a*=mc(-i));return gc(a,r,"fromValue"),new wc(hc,a,r)}static fromString(e,t){const n=e.match(/^(-?)([0-9]*)\.?([0-9]*)$/);Ef(n&&n[2].length+n[3].length>0,"invalid FixedNumber string value","value",e);const s=bc(t);let r=n[2]||"0",a=n[3]||"";for(;a.length<s.decimals;)a+=yc;kf(a.substring(s.decimals).match(/^0*$/),"too many decimals for format","NUMERIC_FAULT",{operation:"fromString",fault:"underflow",value:e}),a=a.substring(0,s.decimals);const i=BigInt(n[1]+r+a);return gc(i,s,"fromString"),new wc(hc,i,s)}static fromBytes(e,t){let n=Qf($f(e,"value"));const s=bc(t);return s.signed&&(n=Wf(n,s.width)),gc(n,s,"fromBytes"),new wc(hc,n,s)}}const vc=["wei","kwei","mwei","gwei","szabo","finney","ether"];function _c(e,t){let n=18;if("string"==typeof t){const e=vc.indexOf(t);Ef(e>=0,"invalid unit","unit",t),n=3*e}else null!=t&&(n=ec(t,"unit"));return wc.fromValue(e,n,{decimals:n,width:512}).toString()}function Tc(e,t){Ef("string"==typeof e,"value must be a string","value",e);let n=18;if("string"==typeof t){const e=vc.indexOf(t);Ef(e>=0,"invalid unit","unit",t),n=3*e}else null!=t&&(n=ec(t,"unit"));return wc.fromString(e,{decimals:n,width:512}).value}function xc(e){return _c(e,18)}const Ac=32,Sc=new Uint8Array(Ac),kc=["then"],Ec={},Nc=new WeakMap;function Ic(e){return Nc.get(e)}function Cc(e,t){Nc.set(e,t)}function Oc(e,t){const n=new Error(`deferred error during ABI decoding triggered accessing ${e}`);throw n.error=t,n}function Rc(e,t,n){return e.indexOf(null)>=0?t.map((e,t)=>e instanceof $c?Rc(Ic(e),e,n):e):e.reduce((e,s,r)=>{let a=t.getValue(s);return s in e||(n&&a instanceof $c&&(a=Rc(Ic(a),a,n)),e[s]=a),e},{})}class $c extends Array{#l;constructor(...e){const t=e[0];let n=e[1],s=(e[2]||[]).slice(),r=!0;t!==Ec&&(n=e,s=[],r=!1),super(n.length),n.forEach((e,t)=>{this[t]=e});const a=s.reduce((e,t)=>("string"==typeof t&&e.set(t,(e.get(t)||0)+1),e),new Map);if(Cc(this,Object.freeze(n.map((e,t)=>{const n=s[t];return null!=n&&1===a.get(n)?n:null}))),this.#l=[],null==this.#l&&this.#l,!r)return;Object.freeze(this);const i=new Proxy(this,{get:(e,t,n)=>{if("string"==typeof t){if(t.match(/^[0-9]+$/)){const n=ec(t,"%index");if(n<0||n>=this.length)throw new RangeError("out of result range");const s=e[n];return s instanceof Error&&Oc(`index ${n}`,s),s}if(kc.indexOf(t)>=0)return Reflect.get(e,t,n);const s=e[t];if(s instanceof Function)return function(...t){return s.apply(this===n?e:this,t)};if(!(t in e))return e.getValue.apply(this===n?e:this,[t])}return Reflect.get(e,t,n)}});return Cc(i,Ic(this)),i}toArray(e){const t=[];return this.forEach((n,s)=>{n instanceof Error&&Oc(`index ${s}`,n),e&&n instanceof $c&&(n=n.toArray(e)),t.push(n)}),t}toObject(e){const t=Ic(this);return t.reduce((n,s,r)=>(kf(null!=s,`value at index ${r} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),Rc(t,this,e)),{})}slice(e,t){null==e&&(e=0),e<0&&(e+=this.length)<0&&(e=0),null==t&&(t=this.length),t<0&&(t+=this.length)<0&&(t=0),t>this.length&&(t=this.length);const n=Ic(this),s=[],r=[];for(let a=e;a<t;a++)s.push(this[a]),r.push(n[a]);return new $c(Ec,s,r)}filter(e,t){const n=Ic(this),s=[],r=[];for(let a=0;a<this.length;a++){const i=this[a];i instanceof Error&&Oc(`index ${a}`,i),e.call(t,i,a,this)&&(s.push(i),r.push(n[a]))}return new $c(Ec,s,r)}map(e,t){const n=[];for(let s=0;s<this.length;s++){const r=this[s];r instanceof Error&&Oc(`index ${s}`,r),n.push(e.call(t,r,s,this))}return n}getValue(e){const t=Ic(this).indexOf(e);if(-1===t)return;const n=this[t];return n instanceof Error&&Oc(`property ${JSON.stringify(e)}`,n.error),n}static fromItems(e,t){return new $c(Ec,e,t)}}function Pc(e){let t=sc(e);return kf(t.length<=Ac,"value out-of-bounds","BUFFER_OVERRUN",{buffer:t,length:Ac,offset:t.length}),t.length!==Ac&&(t=Pf(Bf([Sc.slice(t.length%Ac),t]))),t}class Mc{name;type;localName;dynamic;constructor(e,t,n,s){_f(this,{name:e,type:t,localName:n,dynamic:s},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){Ef(!1,e,this.localName,t)}}class Dc{#u;#d;constructor(){this.#u=[],this.#d=0}get data(){return Bf(this.#u)}get length(){return this.#d}#p(e){return this.#u.push(e),this.#d+=e.length,e.length}appendWriter(e){return this.#p(Pf(e.data))}writeBytes(e){let t=Pf(e);const n=t.length%Ac;return n&&(t=Pf(Bf([t,Sc.slice(n)]))),this.#p(t)}writeValue(e){return this.#p(Pc(e))}writeUpdatableValue(){const e=this.#u.length;return this.#u.push(Sc),this.#d+=Ac,t=>{this.#u[e]=Pc(t)}}}class Fc{allowLoose;#u;#h;#y;#m;#g;constructor(e,t,n){_f(this,{allowLoose:!!t}),this.#u=Pf(e),this.#y=0,this.#m=null,this.#g=null!=n?n:1024,this.#h=0}get data(){return Hf(this.#u)}get dataLength(){return this.#u.length}get consumed(){return this.#h}get bytes(){return new Uint8Array(this.#u)}#b(e){if(this.#m)return this.#m.#b(e);this.#y+=e,kf(this.#g<1||this.#y<=this.#g*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#g} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:Pf(this.#u),offset:this.#h,length:e,info:{bytesRead:this.#y,dataLength:this.dataLength}})}#w(e,t,n){let s=Math.ceil(t/Ac)*Ac;return this.#h+s>this.#u.length&&(this.allowLoose&&n&&this.#h+t<=this.#u.length?s=t:kf(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:Pf(this.#u),length:this.#u.length,offset:this.#h+s})),this.#u.slice(this.#h,this.#h+s)}subReader(e){const t=new Fc(this.#u.slice(this.#h+e),this.allowLoose,this.#g);return t.#m=this,t}readBytes(e,t){let n=this.#w(0,e,!!t);return this.#b(e),this.#h+=n.length,n.slice(0,e)}readValue(){return Qf(this.readBytes(Ac))}readIndex(){return tc(this.readBytes(Ac))}}function Hc(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Bc(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function jc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Uc(e,t){Bc(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Lc="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,qc=e=>e instanceof Uint8Array,Jc=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));
|
|
4
|
-
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw new Error("Non little-endian hardware is not supported");const Gc=async()=>{};function zc(e){if("string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),!qc(e))throw new Error("expected Uint8Array, got "+typeof e);return e}class Wc{clone(){return this._cloneInto()}}const Kc={}.toString;function Vc(e){const t=t=>e().update(zc(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}const Zc=BigInt(2**32-1),Yc=BigInt(32);function Xc(e,t=!1){return t?{h:Number(e&Zc),l:Number(e>>Yc&Zc)}:{h:0|Number(e>>Yc&Zc),l:0|Number(e&Zc)}}function Qc(e,t=!1){let n=new Uint32Array(e.length),s=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:a,l:i}=Xc(e[r],t);[n[r],s[r]]=[a,i]}return[n,s]}const el=(e,t,n)=>e<<n|t>>>32-n,tl=(e,t,n)=>t<<n|e>>>32-n,nl=(e,t,n)=>t<<n-32|e>>>64-n,sl=(e,t,n)=>e<<n-32|t>>>64-n;const rl={fromBig:Xc,split:Qc,toBig:(e,t)=>BigInt(e>>>0)<<Yc|BigInt(t>>>0),shrSH:(e,t,n)=>e>>>n,shrSL:(e,t,n)=>e<<32-n|t>>>n,rotrSH:(e,t,n)=>e>>>n|t<<32-n,rotrSL:(e,t,n)=>e<<32-n|t>>>n,rotrBH:(e,t,n)=>e<<64-n|t>>>n-32,rotrBL:(e,t,n)=>e>>>n-32|t<<64-n,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:el,rotlSL:tl,rotlBH:nl,rotlBL:sl,add:function(e,t,n,s){const r=(t>>>0)+(s>>>0);return{h:e+n+(r/2**32|0)|0,l:0|r}},add3L:(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H:(e,t,n,s)=>t+n+s+(e/2**32|0)|0,add4L:(e,t,n,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),add4H:(e,t,n,s,r)=>t+n+s+r+(e/2**32|0)|0,add5H:(e,t,n,s,r,a)=>t+n+s+r+a+(e/2**32|0)|0,add5L:(e,t,n,s,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0)+(r>>>0)},[al,il,ol]=[[],[],[]],fl=BigInt(0),cl=BigInt(1),ll=BigInt(2),ul=BigInt(7),dl=BigInt(256),pl=BigInt(113);for(let rp=0,ap=cl,ip=1,op=0;rp<24;rp++){[ip,op]=[op,(2*ip+3*op)%5],al.push(2*(5*op+ip)),il.push((rp+1)*(rp+2)/2%64);let e=fl;for(let t=0;t<7;t++)ap=(ap<<cl^(ap>>ul)*pl)%dl,ap&ll&&(e^=cl<<(cl<<BigInt(t))-cl);ol.push(e)}const[hl,yl]=Qc(ol,!0),ml=(e,t,n)=>n>32?nl(e,t,n):el(e,t,n),gl=(e,t,n)=>n>32?sl(e,t,n):tl(e,t,n);class bl extends Wc{constructor(e,t,n,s=!1,r=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=r,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Hc(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Jc(this.state)}keccak(){!function(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let s=0;s<10;s++)n[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){const t=(s+8)%10,r=(s+2)%10,a=n[r],i=n[r+1],o=ml(a,i,1)^n[t],f=gl(a,i,1)^n[t+1];for(let n=0;n<50;n+=10)e[s+n]^=o,e[s+n+1]^=f}let t=e[2],r=e[3];for(let n=0;n<24;n++){const s=il[n],a=ml(t,r,s),i=gl(t,r,s),o=al[n];t=e[o],r=e[o+1],e[o]=a,e[o+1]=i}for(let s=0;s<50;s+=10){for(let t=0;t<10;t++)n[t]=e[s+t];for(let t=0;t<10;t++)e[s+t]^=~n[(t+2)%10]&n[(t+4)%10]}e[0]^=hl[s],e[1]^=yl[s]}n.fill(0)}(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){jc(this);const{blockLen:t,state:n}=this,s=(e=zc(e)).length;for(let r=0;r<s;){const a=Math.min(t-this.pos,s-r);for(let t=0;t<a;t++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,128&t&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){jc(this,!1),Bc(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,r=e.length;s<r;){this.posOut>=n&&this.keccak();const a=Math.min(n-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+a),s),this.posOut+=a,s+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Hc(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Uc(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:a}=this;return e||(e=new bl(t,n,s,a,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=s,e.enableXOF=a,e.destroyed=this.destroyed,e}}const wl=((e,t,n)=>Vc(()=>new bl(t,e,n)))(1,136,32);let vl=!1;const _l=function(e){return wl(e)};let Tl=_l;function xl(e){const t=$f(e,"data");return Hf(Tl(t))}xl._=_l,xl.lock=function(){vl=!0},xl.register=function(e){if(vl)throw new TypeError("keccak256 is locked");Tl=e},Object.freeze(xl);const Al="0x0000000000000000000000000000000000000000",Sl=BigInt(0),kl=BigInt(36);function El(e){const t=(e=e.toLowerCase()).substring(2).split(""),n=new Uint8Array(40);for(let r=0;r<40;r++)n[r]=t[r].charCodeAt(0);const s=$f(xl(n));for(let r=0;r<40;r+=2)s[r>>1]>>4>=8&&(t[r]=t[r].toUpperCase()),(15&s[r>>1])>=8&&(t[r+1]=t[r+1].toUpperCase());return"0x"+t.join("")}const Nl={};for(let rp=0;rp<10;rp++)Nl[String(rp)]=String(rp);for(let rp=0;rp<26;rp++)Nl[String.fromCharCode(65+rp)]=String(10+rp);function Il(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map(e=>Nl[e]).join("");for(;t.length>=15;){let e=t.substring(0,15);t=parseInt(e,10)%97+t.substring(e.length)}let n=String(98-parseInt(t,10)%97);for(;n.length<2;)n="0"+n;return n}const Cl=function(){const e={};for(let t=0;t<36;t++){e["0123456789abcdefghijklmnopqrstuvwxyz"[t]]=BigInt(t)}return e}();function Ol(e){if(Ef("string"==typeof e,"invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith("0x")||(e="0x"+e);const t=El(e);return Ef(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||t===e,"bad address checksum","address",e),t}if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){Ef(e.substring(2,4)===Il(e),"bad icap checksum","address",e);let t=function(e){e=e.toLowerCase();let t=Sl;for(let n=0;n<e.length;n++)t=t*kl+Cl[e[n]];return t}(e.substring(4)).toString(16);for(;t.length<40;)t="0"+t;return El("0x"+t)}Ef(!1,"invalid address","address",e)}function Rl(e){return e&&"function"==typeof e.getAddress}async function $l(e,t){const n=await t;return null!=n&&"0x0000000000000000000000000000000000000000"!==n||(kf("string"!=typeof e,"unconfigured name","UNCONFIGURED_NAME",{value:e}),Ef(!1,"invalid AddressLike value; did not resolve to a value address","target",e)),Ol(n)}function Pl(e,t){return"string"==typeof e?e.match(/^0x[0-9a-f]{40}$/i)?Ol(e):(kf(null!=t,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),$l(e,t.resolveName(e))):Rl(e)?$l(e,e.getAddress()):e&&"function"==typeof e.then?$l(e,e):void Ef(!1,"unsupported addressable value","target",e)}const Ml={};function Dl(e,t){let n=!1;return t<0&&(n=!0,t*=-1),new Bl(Ml,`${n?"":"u"}int${t}`,e,{signed:n,width:t})}function Fl(e,t){return new Bl(Ml,`bytes${t||""}`,e,{size:t})}const Hl=Symbol.for("_ethers_typed");class Bl{type;value;#v;_typedSymbol;constructor(e,t,n,s){null==s&&(s=null),Of(Ml,e,"Typed"),_f(this,{_typedSymbol:Hl,type:t,value:n}),this.#v=s,this.format()}format(){if("array"===this.type)throw new Error("");if("dynamicArray"===this.type)throw new Error("");return"tuple"===this.type?`tuple(${this.value.map(e=>e.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return"string"===this.type}get tupleName(){if("tuple"!==this.type)throw TypeError("not a tuple");return this.#v}get arrayLength(){if("array"!==this.type)throw TypeError("not an array");return!0===this.#v?-1:!1===this.#v?this.value.length:null}static from(e,t){return new Bl(Ml,e,t)}static uint8(e){return Dl(e,8)}static uint16(e){return Dl(e,16)}static uint24(e){return Dl(e,24)}static uint32(e){return Dl(e,32)}static uint40(e){return Dl(e,40)}static uint48(e){return Dl(e,48)}static uint56(e){return Dl(e,56)}static uint64(e){return Dl(e,64)}static uint72(e){return Dl(e,72)}static uint80(e){return Dl(e,80)}static uint88(e){return Dl(e,88)}static uint96(e){return Dl(e,96)}static uint104(e){return Dl(e,104)}static uint112(e){return Dl(e,112)}static uint120(e){return Dl(e,120)}static uint128(e){return Dl(e,128)}static uint136(e){return Dl(e,136)}static uint144(e){return Dl(e,144)}static uint152(e){return Dl(e,152)}static uint160(e){return Dl(e,160)}static uint168(e){return Dl(e,168)}static uint176(e){return Dl(e,176)}static uint184(e){return Dl(e,184)}static uint192(e){return Dl(e,192)}static uint200(e){return Dl(e,200)}static uint208(e){return Dl(e,208)}static uint216(e){return Dl(e,216)}static uint224(e){return Dl(e,224)}static uint232(e){return Dl(e,232)}static uint240(e){return Dl(e,240)}static uint248(e){return Dl(e,248)}static uint256(e){return Dl(e,256)}static uint(e){return Dl(e,256)}static int8(e){return Dl(e,-8)}static int16(e){return Dl(e,-16)}static int24(e){return Dl(e,-24)}static int32(e){return Dl(e,-32)}static int40(e){return Dl(e,-40)}static int48(e){return Dl(e,-48)}static int56(e){return Dl(e,-56)}static int64(e){return Dl(e,-64)}static int72(e){return Dl(e,-72)}static int80(e){return Dl(e,-80)}static int88(e){return Dl(e,-88)}static int96(e){return Dl(e,-96)}static int104(e){return Dl(e,-104)}static int112(e){return Dl(e,-112)}static int120(e){return Dl(e,-120)}static int128(e){return Dl(e,-128)}static int136(e){return Dl(e,-136)}static int144(e){return Dl(e,-144)}static int152(e){return Dl(e,-152)}static int160(e){return Dl(e,-160)}static int168(e){return Dl(e,-168)}static int176(e){return Dl(e,-176)}static int184(e){return Dl(e,-184)}static int192(e){return Dl(e,-192)}static int200(e){return Dl(e,-200)}static int208(e){return Dl(e,-208)}static int216(e){return Dl(e,-216)}static int224(e){return Dl(e,-224)}static int232(e){return Dl(e,-232)}static int240(e){return Dl(e,-240)}static int248(e){return Dl(e,-248)}static int256(e){return Dl(e,-256)}static int(e){return Dl(e,-256)}static bytes1(e){return Fl(e,1)}static bytes2(e){return Fl(e,2)}static bytes3(e){return Fl(e,3)}static bytes4(e){return Fl(e,4)}static bytes5(e){return Fl(e,5)}static bytes6(e){return Fl(e,6)}static bytes7(e){return Fl(e,7)}static bytes8(e){return Fl(e,8)}static bytes9(e){return Fl(e,9)}static bytes10(e){return Fl(e,10)}static bytes11(e){return Fl(e,11)}static bytes12(e){return Fl(e,12)}static bytes13(e){return Fl(e,13)}static bytes14(e){return Fl(e,14)}static bytes15(e){return Fl(e,15)}static bytes16(e){return Fl(e,16)}static bytes17(e){return Fl(e,17)}static bytes18(e){return Fl(e,18)}static bytes19(e){return Fl(e,19)}static bytes20(e){return Fl(e,20)}static bytes21(e){return Fl(e,21)}static bytes22(e){return Fl(e,22)}static bytes23(e){return Fl(e,23)}static bytes24(e){return Fl(e,24)}static bytes25(e){return Fl(e,25)}static bytes26(e){return Fl(e,26)}static bytes27(e){return Fl(e,27)}static bytes28(e){return Fl(e,28)}static bytes29(e){return Fl(e,29)}static bytes30(e){return Fl(e,30)}static bytes31(e){return Fl(e,31)}static bytes32(e){return Fl(e,32)}static address(e){return new Bl(Ml,"address",e)}static bool(e){return new Bl(Ml,"bool",!!e)}static bytes(e){return new Bl(Ml,"bytes",e)}static string(e){return new Bl(Ml,"string",e)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(e){return new Bl(Ml,"overrides",Object.assign({},e))}static isTyped(e){return e&&"object"==typeof e&&"_typedSymbol"in e&&e._typedSymbol===Hl}static dereference(e,t){if(Bl.isTyped(e)){if(e.type!==t)throw new Error(`invalid type: expecetd ${t}, got ${e.type}`);return e.value}return e}}class jl extends Mc{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let n=Bl.dereference(t,"string");try{n=Ol(n)}catch(s){return this._throwError(s.message,t)}return e.writeValue(n)}decode(e){return Ol(nc(e.readValue(),20))}}class Ul extends Mc{coder;constructor(e){super(e.name,e.type,"_",e.dynamic),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}}function Ll(e,t,n){let s=[];if(Array.isArray(n))s=n;else if(n&&"object"==typeof n){let e={};s=t.map(t=>{const s=t.localName;return kf(s,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),kf(!e[s],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),e[s]=!0,n[s]})}else Ef(!1,"invalid tuple value","tuple",n);Ef(t.length===s.length,"types/value length mismatch","tuple",n);let r=new Dc,a=new Dc,i=[];t.forEach((e,t)=>{let n=s[t];if(e.dynamic){let t=a.length;e.encode(a,n);let s=r.writeUpdatableValue();i.push(e=>{s(e+t)})}else e.encode(r,n)}),i.forEach(e=>{e(r.length)});let o=e.appendWriter(r);return o+=e.appendWriter(a),o}function ql(e,t){let n=[],s=[],r=e.subReader(0);return t.forEach(t=>{let a=null;if(t.dynamic){let n=e.readIndex(),s=r.subReader(n);try{a=t.decode(s)}catch(i){if(xf(i,"BUFFER_OVERRUN"))throw i;a=i,a.baseType=t.name,a.name=t.localName,a.type=t.type}}else try{a=t.decode(e)}catch(i){if(xf(i,"BUFFER_OVERRUN"))throw i;a=i,a.baseType=t.name,a.name=t.localName,a.type=t.type}if(null==a)throw new Error("investigate");n.push(a),s.push(t.localName||null)}),$c.fromItems(n,s)}class Jl extends Mc{coder;length;constructor(e,t,n){super("array",e.type+"["+(t>=0?t:"")+"]",n,-1===t||e.dynamic),_f(this,{coder:e,length:t})}defaultValue(){const e=this.coder.defaultValue(),t=[];for(let n=0;n<this.length;n++)t.push(e);return t}encode(e,t){const n=Bl.dereference(t,"array");Array.isArray(n)||this._throwError("expected array value",n);let s=this.length;-1===s&&(s=n.length,e.writeValue(n.length)),Nf(n.length,s,"coder array"+(this.localName?" "+this.localName:""));let r=[];for(let a=0;a<n.length;a++)r.push(this.coder);return Ll(e,r,n)}decode(e){let t=this.length;-1===t&&(t=e.readIndex(),kf(t*Ac<=e.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:e.bytes,offset:t*Ac,length:e.dataLength}));let n=[];for(let s=0;s<t;s++)n.push(new Ul(this.coder));return ql(e,n)}}class Gl extends Mc{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const n=Bl.dereference(t,"bool");return e.writeValue(n?1:0)}decode(e){return!!e.readValue()}}class zl extends Mc{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=Pf(t);let n=e.writeValue(t.length);return n+=e.writeBytes(t),n}decode(e){return e.readBytes(e.readIndex(),!0)}}class Wl extends zl{constructor(e){super("bytes",e)}decode(e){return Hf(super.decode(e))}}class Kl extends Mc{size;constructor(e,t){let n="bytes"+String(e);super(n,n,t,!1),_f(this,{size:e},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(e,t){let n=Pf(Bl.dereference(t,this.type));return n.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(n)}decode(e){return Hf(e.readBytes(this.size))}}const Vl=new Uint8Array([]);class Zl extends Mc{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return null!=t&&this._throwError("not null",t),e.writeBytes(Vl)}decode(e){return e.readBytes(0),null}}const Yl=BigInt(0),Xl=BigInt(1),Ql=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class eu extends Mc{size;signed;constructor(e,t,n){const s=(t?"int":"uint")+8*e;super(s,s,n,!1),_f(this,{size:e,signed:t},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(e,t){let n=Zf(Bl.dereference(t,this.type)),s=Vf(Ql,256);if(this.signed){let e=Vf(s,8*this.size-1);(n>e||n<-(e+Xl))&&this._throwError("value out-of-bounds",t),n=Kf(n,256)}else(n<Yl||n>Vf(s,8*this.size))&&this._throwError("value out-of-bounds",t);return e.writeValue(n)}decode(e){let t=Vf(e.readValue(),8*this.size);return this.signed&&(t=Wf(t,8*this.size)),t}}class tu extends zl{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,fc(Bl.dereference(t,"string")))}decode(e){return cc(super.decode(e))}}class nu extends Mc{coders;constructor(e,t){let n=!1;const s=[];e.forEach(e=>{e.dynamic&&(n=!0),s.push(e.type)});super("tuple","tuple("+s.join(",")+")",t,n),_f(this,{coders:Object.freeze(e.slice())})}defaultValue(){const e=[];this.coders.forEach(t=>{e.push(t.defaultValue())});const t=this.coders.reduce((e,t)=>{const n=t.localName;return n&&(e[n]||(e[n]=0),e[n]++),e},{});return this.coders.forEach((n,s)=>{let r=n.localName;r&&1===t[r]&&("length"===r&&(r="_length"),null==e[r]&&(e[r]=e[s]))}),Object.freeze(e)}encode(e,t){const n=Bl.dereference(t,"tuple");return Ll(e,this.coders,n)}decode(e){return ql(e,this.coders)}}function su(e,t){return{address:Ol(e),storageKeys:t.map((e,t)=>(Ef(Mf(e,32),"invalid slot",`storageKeys[${t}]`,e),e.toLowerCase()))}}function ru(e){if(Array.isArray(e))return e.map((t,n)=>Array.isArray(t)?(Ef(2===t.length,"invalid slot set",`value[${n}]`,t),su(t[0],t[1])):(Ef(null!=t&&"object"==typeof t,"invalid address-slot set","value",e),su(t.address,t.storageKeys)));Ef(null!=e&&"object"==typeof e,"invalid access list","value",e);const t=Object.keys(e).map(t=>{const n=e[t].reduce((e,t)=>(e[t]=!0,e),{});return su(t,Object.keys(n).sort())});return t.sort((e,t)=>e.address.localeCompare(t.address)),t}function au(e){return xl(fc(e))}function iu(e){const t=new Set;return e.forEach(e=>t.add(e)),Object.freeze(t)}const ou=iu("external public payable override".split(" ")),fu="constant external internal payable private public pure view override",cu=iu(fu.split(" ")),lu="constructor error event fallback function receive struct",uu=iu(lu.split(" ")),du="calldata memory storage payable indexed",pu=iu(du.split(" ")),hu=iu([lu,du,"tuple returns",fu].join(" ").split(" ")),yu={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},mu=new RegExp("^(\\s*)"),gu=new RegExp("^([0-9]+)"),bu=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),wu=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),vu=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class _u{#h;#_;get offset(){return this.#h}get length(){return this.#_.length-this.#h}constructor(e){this.#h=0,this.#_=e.slice()}clone(){return new _u(this.#_)}reset(){this.#h=0}#T(e=0,t=0){return new _u(this.#_.slice(e,t).map(t=>Object.freeze(Object.assign({},t,{match:t.match-e,linkBack:t.linkBack-e,linkNext:t.linkNext-e}))))}popKeyword(e){const t=this.peek();if("KEYWORD"!==t.type||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e){const t=this.peek();throw new Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`)}return this.pop().text}popParen(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=this.#T(this.#h+1,e.match+1);return this.#h=e.match+1,t}popParams(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=[];for(;this.#h<e.match-1;){const e=this.peek().linkNext;t.push(this.#T(this.#h+1,e)),this.#h=e}return this.#h=e.match+1,t}peek(){if(this.#h>=this.#_.length)throw new Error("out-of-bounds");return this.#_[this.#h]}peekKeyword(e){const t=this.peekType("KEYWORD");return null!=t&&e.has(t)?t:null}peekType(e){if(0===this.length)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return this.#h++,e}toString(){const e=[];for(let t=this.#h;t<this.#_.length;t++){const n=this.#_[t];e.push(`${n.type}:${n.text}`)}return`<TokenString ${e.join(" ")}>`}}function Tu(e){const t=[],n=t=>{const n=a<e.length?JSON.stringify(e[a]):"$EOI";throw new Error(`invalid token ${n} at ${a}: ${t}`)};let s=[],r=[],a=0;for(;a<e.length;){let i=e.substring(a),o=i.match(mu);o&&(a+=o[1].length,i=e.substring(a));const f={depth:s.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:a,value:-1};t.push(f);let c=yu[i[0]]||"";if(c){if(f.type=c,f.text=i[0],a++,"OPEN_PAREN"===c)s.push(t.length-1),r.push(t.length-1);else if("CLOSE_PAREN"==c)0===s.length&&n("no matching open bracket"),f.match=s.pop(),t[f.match].match=t.length-1,f.depth--,f.linkBack=r.pop(),t[f.linkBack].linkNext=t.length-1;else if("COMMA"===c)f.linkBack=r.pop(),t[f.linkBack].linkNext=t.length-1,r.push(t.length-1);else if("OPEN_BRACKET"===c)f.type="BRACKET";else if("CLOSE_BRACKET"===c){let e=t.pop().text;if(t.length>0&&"NUMBER"===t[t.length-1].type){const n=t.pop().text;e=n+e,t[t.length-1].value=ec(n)}if(0===t.length||"BRACKET"!==t[t.length-1].type)throw new Error("missing opening bracket");t[t.length-1].text+=e}}else if(o=i.match(bu),o){if(f.text=o[1],a+=f.text.length,hu.has(f.text)){f.type="KEYWORD";continue}if(f.text.match(vu)){f.type="TYPE";continue}f.type="ID"}else{if(o=i.match(gu),!o)throw new Error(`unexpected token ${JSON.stringify(i[0])} at position ${a}`);f.text=o[1],f.type="NUMBER",a+=f.text.length}}return new _u(t.map(e=>Object.freeze(e)))}function xu(e,t){let n=[];for(const s in t.keys())e.has(s)&&n.push(s);if(n.length>1)throw new Error(`conflicting types: ${n.join(", ")}`)}function Au(e,t){if(t.peekKeyword(uu)){const n=t.pop().text;if(n!==e)throw new Error(`expected ${e}, got ${n}`)}return t.popType("ID")}function Su(e,t){const n=new Set;for(;;){const s=e.peekType("KEYWORD");if(null==s||t&&!t.has(s))break;if(e.pop(),n.has(s))throw new Error(`duplicate keywords: ${JSON.stringify(s)}`);n.add(s)}return Object.freeze(n)}function ku(e){let t=Su(e,cu);return xu(t,iu("constant payable nonpayable".split(" "))),xu(t,iu("pure view payable nonpayable".split(" "))),t.has("view")?"view":t.has("pure")?"pure":t.has("payable")?"payable":t.has("nonpayable")?"nonpayable":t.has("constant")?"view":"nonpayable"}function Eu(e,t){return e.popParams().map(e=>Uu.from(e,t))}function Nu(e){if(e.peekType("AT")){if(e.pop(),e.peekType("NUMBER"))return Zf(e.pop().text);throw new Error("invalid gas")}return null}function Iu(e){if(e.length)throw new Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`)}const Cu=new RegExp(/^(.*)\[([0-9]*)\]$/);function Ou(e){const t=e.match(vu);if(Ef(t,"invalid type","type",e),"uint"===e)return"uint256";if("int"===e)return"int256";if(t[2]){const n=parseInt(t[2]);Ef(0!==n&&n<=32,"invalid bytes length","type",e)}else if(t[3]){const n=parseInt(t[3]);Ef(0!==n&&n<=256&&n%8==0,"invalid numeric width","type",e)}return e}const Ru={},$u=Symbol.for("_ethers_internal"),Pu="_ParamTypeInternal",Mu="_ErrorInternal",Du="_EventInternal",Fu="_ConstructorInternal",Hu="_FallbackInternal",Bu="_FunctionInternal",ju="_StructInternal";class Uu{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(e,t,n,s,r,a,i,o){if(Of(e,Ru,"ParamType"),Object.defineProperty(this,$u,{value:Pu}),a&&(a=Object.freeze(a.slice())),"array"===s){if(null==i||null==o)throw new Error("")}else if(null!=i||null!=o)throw new Error("");if("tuple"===s){if(null==a)throw new Error("")}else if(null!=a)throw new Error("");_f(this,{name:t,type:n,baseType:s,indexed:r,components:a,arrayLength:i,arrayChildren:o})}format(e){if(null==e&&(e="sighash"),"json"===e){const t=this.name||"";if(this.isArray()){const e=JSON.parse(this.arrayChildren.format("json"));return e.name=t,e.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(e)}const n={type:"tuple"===this.baseType?"tuple":this.type,name:t};return"boolean"==typeof this.indexed&&(n.indexed=this.indexed),this.isTuple()&&(n.components=this.components.map(t=>JSON.parse(t.format(e)))),JSON.stringify(n)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?t+="("+this.components.map(t=>t.format(e)).join("full"===e?", ":",")+")":t+=this.type,"sighash"!==e&&(!0===this.indexed&&(t+=" indexed"),"full"===e&&this.name&&(t+=" "+this.name)),t}isArray(){return"array"===this.baseType}isTuple(){return"tuple"===this.baseType}isIndexable(){return null!=this.indexed}walk(e,t){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(-1!==this.arrayLength&&e.length!==this.arrayLength)throw new Error("array is wrong length");const n=this;return e.map(e=>n.arrayChildren.walk(e,t))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const n=this;return e.map((e,s)=>n.components[s].walk(e,t))}return t(this.type,e)}#x(e,t,n,s){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(-1!==this.arrayLength&&t.length!==this.arrayLength)throw new Error("array is wrong length");const r=this.arrayChildren,a=t.slice();return a.forEach((t,s)=>{r.#x(e,t,n,e=>{a[s]=e})}),void s(a)}if(this.isTuple()){const r=this.components;let a;if(Array.isArray(t))a=t.slice();else{if(null==t||"object"!=typeof t)throw new Error("invalid tuple value");a=r.map(e=>{if(!e.name)throw new Error("cannot use object value with unnamed components");if(!(e.name in t))throw new Error(`missing value for component ${e.name}`);return t[e.name]})}if(a.length!==this.components.length)throw new Error("array is wrong length");return a.forEach((t,s)=>{r[s].#x(e,t,n,e=>{a[s]=e})}),void s(a)}const r=n(this.type,t);r.then?e.push(async function(){s(await r)}()):s(r)}async walkAsync(e,t){const n=[],s=[e];return this.#x(n,e,t,e=>{s[0]=e}),n.length&&await Promise.all(n),s[0]}static from(e,t){if(Uu.isParamType(e))return e;if("string"==typeof e)try{return Uu.from(Tu(e),t)}catch(i){Ef(!1,"invalid param type","obj",e)}else if(e instanceof _u){let n="",s="",r=null;Su(e,iu(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(s="tuple",r=e.popParams().map(e=>Uu.from(e)),n=`tuple(${r.map(e=>e.format()).join(",")})`):(n=Ou(e.popType("TYPE")),s=n);let a=null,i=null;for(;e.length&&e.peekType("BRACKET");){const t=e.pop();a=new Uu(Ru,"",n,s,null,r,i,a),i=t.value,n+=t.text,s="array",r=null}let o=null;if(Su(e,pu).has("indexed")){if(!t)throw new Error("");o=!0}const f=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new Uu(Ru,f,n,s,o,r,i,a)}const n=e.name;Ef(!n||"string"==typeof n&&n.match(wu),"invalid name","obj.name",n);let s=e.indexed;null!=s&&(Ef(t,"parameter cannot be indexed","obj.indexed",e.indexed),s=!!s);let r=e.type,a=r.match(Cu);if(a){const t=parseInt(a[2]||"-1"),i=Uu.from({type:a[1],components:e.components});return new Uu(Ru,n||"",r,"array",s,null,t,i)}if("tuple"===r||r.startsWith("tuple(")||r.startsWith("(")){const t=null!=e.components?e.components.map(e=>Uu.from(e)):null;return new Uu(Ru,n||"",r,"tuple",s,t,null,null)}return r=Ou(e.type),new Uu(Ru,n||"",r,r,s,null,null,null)}static isParamType(e){return e&&e[$u]===Pu}}class Lu{type;inputs;constructor(e,t,n){Of(e,Ru,"Fragment"),_f(this,{type:t,inputs:n=Object.freeze(n.slice())})}static from(e){if("string"==typeof e){try{Lu.from(JSON.parse(e))}catch(t){}return Lu.from(Tu(e))}if(e instanceof _u){switch(e.peekKeyword(uu)){case"constructor":return Wu.from(e);case"error":return Gu.from(e);case"event":return zu.from(e);case"fallback":case"receive":return Ku.from(e);case"function":return Vu.from(e);case"struct":return Zu.from(e)}}else if("object"==typeof e){switch(e.type){case"constructor":return Wu.from(e);case"error":return Gu.from(e);case"event":return zu.from(e);case"fallback":case"receive":return Ku.from(e);case"function":return Vu.from(e);case"struct":return Zu.from(e)}kf(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}Ef(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return Wu.isFragment(e)}static isError(e){return Gu.isFragment(e)}static isEvent(e){return zu.isFragment(e)}static isFunction(e){return Vu.isFragment(e)}static isStruct(e){return Zu.isFragment(e)}}class qu extends Lu{name;constructor(e,t,n,s){super(e,t,s),Ef("string"==typeof n&&n.match(wu),"invalid identifier","name",n),s=Object.freeze(s.slice()),_f(this,{name:n})}}function Ju(e,t){return"("+t.map(t=>t.format(e)).join("full"===e?", ":",")+")"}class Gu extends qu{constructor(e,t,n){super(e,"error",t,n),Object.defineProperty(this,$u,{value:Mu})}get selector(){return au(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});const t=[];return"sighash"!==e&&t.push("error"),t.push(this.name+Ju(e,this.inputs)),t.join(" ")}static from(e){if(Gu.isFragment(e))return e;if("string"==typeof e)return Gu.from(Tu(e));if(e instanceof _u){const t=Au("error",e),n=Eu(e);return Iu(e),new Gu(Ru,t,n)}return new Gu(Ru,e.name,e.inputs?e.inputs.map(Uu.from):[])}static isFragment(e){return e&&e[$u]===Mu}}class zu extends qu{anonymous;constructor(e,t,n,s){super(e,"event",t,n),Object.defineProperty(this,$u,{value:Du}),_f(this,{anonymous:s})}get topicHash(){return au(this.format("sighash"))}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});const t=[];return"sighash"!==e&&t.push("event"),t.push(this.name+Ju(e,this.inputs)),"sighash"!==e&&this.anonymous&&t.push("anonymous"),t.join(" ")}static getTopicHash(e,t){t=(t||[]).map(e=>Uu.from(e));return new zu(Ru,e,t,!1).topicHash}static from(e){if(zu.isFragment(e))return e;if("string"==typeof e)try{return zu.from(Tu(e))}catch(t){Ef(!1,"invalid event fragment","obj",e)}else if(e instanceof _u){const t=Au("event",e),n=Eu(e,!0),s=!!Su(e,iu(["anonymous"])).has("anonymous");return Iu(e),new zu(Ru,t,n,s)}return new zu(Ru,e.name,e.inputs?e.inputs.map(e=>Uu.from(e,!0)):[],!!e.anonymous)}static isFragment(e){return e&&e[$u]===Du}}class Wu extends Lu{payable;gas;constructor(e,t,n,s,r){super(e,t,n),Object.defineProperty(this,$u,{value:Fu}),_f(this,{payable:s,gas:r})}format(e){if(kf(null!=e&&"sighash"!==e,"cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),"json"===e)return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});const t=[`constructor${Ju(e,this.inputs)}`];return this.payable&&t.push("payable"),null!=this.gas&&t.push(`@${this.gas.toString()}`),t.join(" ")}static from(e){if(Wu.isFragment(e))return e;if("string"==typeof e)try{return Wu.from(Tu(e))}catch(t){Ef(!1,"invalid constuctor fragment","obj",e)}else if(e instanceof _u){Su(e,iu(["constructor"]));const t=Eu(e),n=!!Su(e,ou).has("payable"),s=Nu(e);return Iu(e),new Wu(Ru,"constructor",t,n,s)}return new Wu(Ru,"constructor",e.inputs?e.inputs.map(Uu.from):[],!!e.payable,null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[$u]===Fu}}class Ku extends Lu{payable;constructor(e,t,n){super(e,"fallback",t),Object.defineProperty(this,$u,{value:Hu}),_f(this,{payable:n})}format(e){const t=0===this.inputs.length?"receive":"fallback";if("json"===e){const e=this.payable?"payable":"nonpayable";return JSON.stringify({type:t,stateMutability:e})}return`${t}()${this.payable?" payable":""}`}static from(e){if(Ku.isFragment(e))return e;if("string"==typeof e)try{return Ku.from(Tu(e))}catch(t){Ef(!1,"invalid fallback fragment","obj",e)}else if(e instanceof _u){const t=e.toString();Ef(e.peekKeyword(iu(["fallback","receive"])),"type must be fallback or receive","obj",t);if("receive"===e.popKeyword(iu(["fallback","receive"]))){const t=Eu(e);return Ef(0===t.length,"receive cannot have arguments","obj.inputs",t),Su(e,iu(["payable"])),Iu(e),new Ku(Ru,[],!0)}let n=Eu(e);n.length?Ef(1===n.length&&"bytes"===n[0].type,"invalid fallback inputs","obj.inputs",n.map(e=>e.format("minimal")).join(", ")):n=[Uu.from("bytes")];const s=ku(e);if(Ef("nonpayable"===s||"payable"===s,"fallback cannot be constants","obj.stateMutability",s),Su(e,iu(["returns"])).has("returns")){const t=Eu(e);Ef(1===t.length&&"bytes"===t[0].type,"invalid fallback outputs","obj.outputs",t.map(e=>e.format("minimal")).join(", "))}return Iu(e),new Ku(Ru,n,"payable"===s)}if("receive"===e.type)return new Ku(Ru,[],!0);if("fallback"===e.type){const t=[Uu.from("bytes")],n="payable"===e.stateMutability;return new Ku(Ru,t,n)}Ef(!1,"invalid fallback description","obj",e)}static isFragment(e){return e&&e[$u]===Hu}}class Vu extends qu{constant;outputs;stateMutability;payable;gas;constructor(e,t,n,s,r,a){super(e,"function",t,s),Object.defineProperty(this,$u,{value:Bu});_f(this,{constant:"view"===n||"pure"===n,gas:a,outputs:r=Object.freeze(r.slice()),payable:"payable"===n,stateMutability:n})}get selector(){return au(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map(t=>JSON.parse(t.format(e))),outputs:this.outputs.map(t=>JSON.parse(t.format(e)))});const t=[];return"sighash"!==e&&t.push("function"),t.push(this.name+Ju(e,this.inputs)),"sighash"!==e&&("nonpayable"!==this.stateMutability&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push("returns"),t.push(Ju(e,this.outputs))),null!=this.gas&&t.push(`@${this.gas.toString()}`)),t.join(" ")}static getSelector(e,t){t=(t||[]).map(e=>Uu.from(e));return new Vu(Ru,e,"view",t,[],null).selector}static from(e){if(Vu.isFragment(e))return e;if("string"==typeof e)try{return Vu.from(Tu(e))}catch(n){Ef(!1,"invalid function fragment","obj",e)}else if(e instanceof _u){const t=Au("function",e),n=Eu(e),s=ku(e);let r=[];Su(e,iu(["returns"])).has("returns")&&(r=Eu(e));const a=Nu(e);return Iu(e),new Vu(Ru,t,s,n,r,a)}let t=e.stateMutability;return null==t&&(t="payable","boolean"==typeof e.constant?(t="view",e.constant||(t="payable","boolean"!=typeof e.payable||e.payable||(t="nonpayable"))):"boolean"!=typeof e.payable||e.payable||(t="nonpayable")),new Vu(Ru,e.name,t,e.inputs?e.inputs.map(Uu.from):[],e.outputs?e.outputs.map(Uu.from):[],null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[$u]===Bu}}class Zu extends qu{constructor(e,t,n){super(e,"struct",t,n),Object.defineProperty(this,$u,{value:ju})}format(){throw new Error("@TODO")}static from(e){if("string"==typeof e)try{return Zu.from(Tu(e))}catch(t){Ef(!1,"invalid struct fragment","obj",e)}else if(e instanceof _u){const t=Au("struct",e),n=Eu(e);return Iu(e),new Zu(Ru,t,n)}return new Zu(Ru,e.name,e.inputs?e.inputs.map(Uu.from):[])}static isFragment(e){return e&&e[$u]===ju}}const Yu=new Map;Yu.set(0,"GENERIC_PANIC"),Yu.set(1,"ASSERT_FALSE"),Yu.set(17,"OVERFLOW"),Yu.set(18,"DIVIDE_BY_ZERO"),Yu.set(33,"ENUM_RANGE_ERROR"),Yu.set(34,"BAD_STORAGE_DATA"),Yu.set(49,"STACK_UNDERFLOW"),Yu.set(50,"ARRAY_RANGE_ERROR"),Yu.set(65,"OUT_OF_MEMORY"),Yu.set(81,"UNINITIALIZED_FUNCTION_CALL");const Xu=new RegExp(/^bytes([0-9]*)$/),Qu=new RegExp(/^(u?int)([0-9]*)$/);let ed=null,td=1024;class nd{#A(e){if(e.isArray())return new Jl(this.#A(e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new nu(e.components.map(e=>this.#A(e)),e.name);switch(e.baseType){case"address":return new jl(e.name);case"bool":return new Gl(e.name);case"string":return new tu(e.name);case"bytes":return new Wl(e.name);case"":return new Zl(e.name)}let t=e.type.match(Qu);if(t){let n=parseInt(t[2]||"256");return Ef(0!==n&&n<=256&&n%8==0,"invalid "+t[1]+" bit length","param",e),new eu(n/8,"int"===t[1],e.name)}if(t=e.type.match(Xu),t){let n=parseInt(t[1]);return Ef(0!==n&&n<=32,"invalid bytes length","param",e),new Kl(n,e.name)}Ef(!1,"invalid type","type",e.type)}getDefaultValue(e){const t=e.map(e=>this.#A(Uu.from(e)));return new nu(t,"_").defaultValue()}encode(e,t){Nf(t.length,e.length,"types/values length mismatch");const n=e.map(e=>this.#A(Uu.from(e))),s=new nu(n,"_"),r=new Dc;return s.encode(r,t),r.data}decode(e,t,n){const s=e.map(e=>this.#A(Uu.from(e)));return new nu(s,"_").decode(new Fc(t,n,td))}static _setDefaultMaxInflation(e){Ef("number"==typeof e&&Number.isInteger(e),"invalid defaultMaxInflation factor","value",e),td=e}static defaultAbiCoder(){return null==ed&&(ed=new nd),ed}static getBuiltinCallException(e,t,n){return function(e,t,n,s){let r="missing revert data",a=null,i=null;if(n){r="execution reverted";const e=$f(n);if(n=Hf(n),0===e.length)r+=" (no data present; likely require(false) occurred",a="require(false)";else if(e.length%32!=4)r+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===Hf(e.slice(0,4)))try{a=s.decode(["string"],e.slice(4))[0],i={signature:"Error(string)",name:"Error",args:[a]},r+=`: ${JSON.stringify(a)}`}catch(f){r+=" (could not decode reason; invalid string data)"}else if("0x4e487b71"===Hf(e.slice(0,4)))try{const t=Number(s.decode(["uint256"],e.slice(4))[0]);i={signature:"Panic(uint256)",name:"Panic",args:[t]},a=`Panic due to ${Yu.get(t)||"UNKNOWN"}(${t})`,r+=`: ${a}`}catch(f){r+=" (could not decode panic code)"}else r+=" (unknown custom error)"}const o={to:t.to?Ol(t.to):null,data:t.data||"0x"};return t.from&&(o.from=Ol(t.from)),Sf(r,"CALL_EXCEPTION",{action:e,data:n,reason:a,transaction:o,invocation:null,revert:i})}(e,t,n,nd.defaultAbiCoder())}}class sd{fragment;name;signature;topic;args;constructor(e,t,n){const s=e.name,r=e.format();_f(this,{fragment:e,name:s,signature:r,topic:t,args:n})}}class rd{fragment;name;args;signature;selector;value;constructor(e,t,n,s){const r=e.name,a=e.format();_f(this,{fragment:e,name:r,args:n,signature:a,selector:t,value:s})}}class ad{fragment;name;args;signature;selector;constructor(e,t,n){const s=e.name,r=e.format();_f(this,{fragment:e,name:s,args:n,signature:r,selector:t})}}class id{hash;_isIndexed;static isIndexed(e){return!(!e||!e._isIndexed)}constructor(e){_f(this,{hash:e,_isIndexed:!0})}}const od={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},fd={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:e=>`reverted with reason string ${JSON.stringify(e)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:e=>{let t="unknown panic code";return e>=0&&e<=255&&od[e.toString()]&&(t=od[e.toString()]),`reverted with panic code 0x${e.toString(16)} (${t})`}}};class cd{fragments;deploy;fallback;receive;#S;#k;#E;#N;constructor(e){let t=[];t="string"==typeof e?JSON.parse(e):e,this.#E=new Map,this.#S=new Map,this.#k=new Map;const n=[];for(const i of t)try{n.push(Lu.from(i))}catch(a){console.log(`[Warning] Invalid Fragment ${JSON.stringify(i)}:`,a.message)}_f(this,{fragments:Object.freeze(n)});let s=null,r=!1;this.#N=this.getAbiCoder(),this.fragments.forEach((e,t)=>{let n;switch(e.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void _f(this,{deploy:e});case"fallback":return void(0===e.inputs.length?r=!0:(Ef(!s||e.payable!==s.payable,"conflicting fallback fragments",`fragments[${t}]`,e),s=e,r=s.payable));case"function":n=this.#E;break;case"event":n=this.#k;break;case"error":n=this.#S;break;default:return}const a=e.format();n.has(a)||n.set(a,e)}),this.deploy||_f(this,{deploy:Wu.from("constructor()")}),_f(this,{fallback:s,receive:r})}format(e){const t=e?"minimal":"full";return this.fragments.map(e=>e.format(t))}formatJson(){const e=this.fragments.map(e=>e.format("json"));return JSON.stringify(e.map(e=>JSON.parse(e)))}getAbiCoder(){return nd.defaultAbiCoder()}#I(e,t,n){if(Mf(e)){const t=e.toLowerCase();for(const e of this.#E.values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const s=[];for(const[t,n]of this.#E)t.split("(")[0]===e&&s.push(n);if(t){const e=t.length>0?t[t.length-1]:null;let n=t.length,r=!0;Bl.isTyped(e)&&"overrides"===e.type&&(r=!1,n--);for(let t=s.length-1;t>=0;t--){const e=s[t].inputs.length;e===n||r&&e===n-1||s.splice(t,1)}for(let a=s.length-1;a>=0;a--){const e=s[a].inputs;for(let n=0;n<t.length;n++)if(Bl.isTyped(t[n])){if(n>=e.length){if("overrides"===t[n].type)continue;s.splice(a,1);break}if(t[n].type!==e[n].baseType){s.splice(a,1);break}}}}if(1===s.length&&t&&t.length!==s[0].inputs.length){const e=t[t.length-1];(null==e||Array.isArray(e)||"object"!=typeof e)&&s.splice(0,1)}if(0===s.length)return null;if(s.length>1&&n){Ef(!1,`ambiguous function description (i.e. matches ${s.map(e=>JSON.stringify(e.format())).join(", ")})`,"key",e)}return s[0]}const s=this.#E.get(Vu.from(e).format());return s||null}getFunctionName(e){const t=this.#I(e,null,!1);return Ef(t,"no matching function","key",e),t.name}hasFunction(e){return!!this.#I(e,null,!1)}getFunction(e,t){return this.#I(e,t||null,!0)}forEachFunction(e){const t=Array.from(this.#E.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){const s=t[n];e(this.#E.get(s),n)}}#C(e,t,n){if(Mf(e)){const t=e.toLowerCase();for(const e of this.#k.values())if(t===e.topicHash)return e;return null}if(-1===e.indexOf("(")){const s=[];for(const[t,n]of this.#k)t.split("(")[0]===e&&s.push(n);if(t){for(let e=s.length-1;e>=0;e--)s[e].inputs.length<t.length&&s.splice(e,1);for(let e=s.length-1;e>=0;e--){const n=s[e].inputs;for(let r=0;r<t.length;r++)if(Bl.isTyped(t[r])&&t[r].type!==n[r].baseType){s.splice(e,1);break}}}if(0===s.length)return null;if(s.length>1&&n){Ef(!1,`ambiguous event description (i.e. matches ${s.map(e=>JSON.stringify(e.format())).join(", ")})`,"key",e)}return s[0]}const s=this.#k.get(zu.from(e).format());return s||null}getEventName(e){const t=this.#C(e,null,!1);return Ef(t,"no matching event","key",e),t.name}hasEvent(e){return!!this.#C(e,null,!1)}getEvent(e,t){return this.#C(e,t||null,!0)}forEachEvent(e){const t=Array.from(this.#k.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){const s=t[n];e(this.#k.get(s),n)}}getError(e,t){if(Mf(e)){const t=e.toLowerCase();if(fd[t])return Gu.from(fd[t].signature);for(const e of this.#S.values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const t=[];for(const[n,s]of this.#S)n.split("(")[0]===e&&t.push(s);if(0===t.length)return"Error"===e?Gu.from("error Error(string)"):"Panic"===e?Gu.from("error Panic(uint256)"):null;if(t.length>1){Ef(!1,`ambiguous error description (i.e. ${t.map(e=>JSON.stringify(e.format())).join(", ")})`,"name",e)}return t[0]}if("Error(string)"===(e=Gu.from(e).format()))return Gu.from("error Error(string)");if("Panic(uint256)"===e)return Gu.from("error Panic(uint256)");const n=this.#S.get(e);return n||null}forEachError(e){const t=Array.from(this.#S.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){const s=t[n];e(this.#S.get(s),n)}}_decodeParams(e,t){return this.#N.decode(e,t)}_encodeParams(e,t){return this.#N.encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);Ef(t,"unknown error","fragment",e),e=t}return Ef(jf(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,jf(t,4))}encodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);Ef(t,"unknown error","fragment",e),e=t}return Bf([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);Ef(t,"unknown function","fragment",e),e=t}return Ef(jf(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,jf(t,4))}encodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);Ef(t,"unknown function","fragment",e),e=t}return Bf([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);Ef(t,"unknown function","fragment",e),e=t}let n="invalid length for result data";const s=Pf(t);if(s.length%32==0)try{return this.#N.decode(e.outputs,s)}catch(r){n="could not decode result data"}kf(!1,n,"BAD_DATA",{value:Hf(s),info:{method:e.name,signature:e.format()}})}makeError(e,t){const n=$f(e,"data"),s=nd.getBuiltinCallException("call",t,n);if(s.message.startsWith("execution reverted (unknown custom error)")){const e=Hf(n.slice(0,4)),t=this.getError(e);if(t)try{const e=this.#N.decode(t.inputs,n.slice(4));s.revert={name:t.name,signature:t.format(),args:e},s.reason=s.revert.signature,s.message=`execution reverted: ${s.reason}`}catch(a){s.message="execution reverted (coult not decode custom error)"}}const r=this.parseTransaction(t);return r&&(s.invocation={method:r.name,signature:r.signature,args:r.args}),s}encodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);Ef(t,"unknown function","fragment",e),e=t}return Hf(this.#N.encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if("string"==typeof e){const t=this.getEvent(e);Ef(t,"unknown event","eventFragment",e),e=t}kf(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const n=[];e.anonymous||n.push(e.topicHash);const s=(e,t)=>"string"===e.type?au(t):"bytes"===e.type?xl(Hf(t)):("bool"===e.type&&"boolean"==typeof t?t=t?"0x01":"0x00":e.type.match(/^u?int/)?t=nc(t):e.type.match(/^bytes/)?t=qf(t,32):"address"===e.type&&this.#N.encode(["address"],[t]),Lf(Hf(t),32));for(t.forEach((t,r)=>{const a=e.inputs[r];a.indexed?null==t?n.push(null):"array"===a.baseType||"tuple"===a.baseType?Ef(!1,"filtering with tuples or arrays not supported","contract."+a.name,t):Array.isArray(t)?n.push(t.map(e=>s(a,e))):n.push(s(a,t)):Ef(null==t,"cannot filter non-indexed parameters; must be null","contract."+a.name,t)});n.length&&null===n[n.length-1];)n.pop();return n}encodeEventLog(e,t){if("string"==typeof e){const t=this.getEvent(e);Ef(t,"unknown event","eventFragment",e),e=t}const n=[],s=[],r=[];return e.anonymous||n.push(e.topicHash),Ef(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach((e,a)=>{const i=t[a];if(e.indexed)if("string"===e.type)n.push(au(i));else if("bytes"===e.type)n.push(xl(i));else{if("tuple"===e.baseType||"array"===e.baseType)throw new Error("not implemented");n.push(this.#N.encode([e.type],[i]))}else s.push(e),r.push(i)}),{data:this.#N.encode(s,r),topics:n}}decodeEventLog(e,t,n){if("string"==typeof e){const t=this.getEvent(e);Ef(t,"unknown event","eventFragment",e),e=t}if(null!=n&&!e.anonymous){const t=e.topicHash;Ef(Mf(n[0],32)&&n[0].toLowerCase()===t,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const s=[],r=[],a=[];e.inputs.forEach((e,t)=>{e.indexed?"string"===e.type||"bytes"===e.type||"tuple"===e.baseType||"array"===e.baseType?(s.push(Uu.from({type:"bytes32",name:e.name})),a.push(!0)):(s.push(e),a.push(!1)):(r.push(e),a.push(!1))});const i=null!=n?this.#N.decode(s,Bf(n)):null,o=this.#N.decode(r,t,!0),f=[],c=[];let l=0,u=0;return e.inputs.forEach((e,t)=>{let n=null;if(e.indexed)if(null==i)n=new id(null);else if(a[t])n=new id(i[u++]);else try{n=i[u++]}catch(s){n=s}else try{n=o[l++]}catch(s){n=s}f.push(n),c.push(e.name||null)}),$c.fromItems(f,c)}parseTransaction(e){const t=$f(e.data,"tx.data"),n=Zf(null!=e.value?e.value:0,"tx.value"),s=this.getFunction(Hf(t.slice(0,4)));if(!s)return null;const r=this.#N.decode(s.inputs,t.slice(4));return new rd(s,s.selector,r,n)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new sd(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=Hf(e),n=this.getError(jf(t,0,4));if(!n)return null;const s=this.#N.decode(n.inputs,jf(t,4));return new ad(n,n.selector,s)}static from(e){return e instanceof cd?e:"string"==typeof e?new cd(JSON.parse(e)):"function"==typeof e.formatJson?new cd(e.formatJson()):"function"==typeof e.format?new cd(e.format("json")):new cd(e)}}const ld=BigInt(0);function ud(e){return null==e?null:e}function dd(e){return null==e?null:e.toString()}function pd(e){const t={};e.to&&(t.to=e.to),e.from&&(t.from=e.from),e.data&&(t.data=Hf(e.data));const n="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const r of n)r in e&&null!=e[r]&&(t[r]=Zf(e[r],`request.${r}`));const s="type,nonce".split(/,/);for(const r of s)r in e&&null!=e[r]&&(t[r]=ec(e[r],`request.${r}`));return e.accessList&&(t.accessList=ru(e.accessList)),e.authorizationList&&(t.authorizationList=e.authorizationList.slice()),"blockTag"in e&&(t.blockTag=e.blockTag),"enableCcipRead"in e&&(t.enableCcipRead=!!e.enableCcipRead),"customData"in e&&(t.customData=e.customData),"blobVersionedHashes"in e&&e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.slice()),"kzg"in e&&(t.kzg=e.kzg),"blobWrapperVersion"in e&&(t.blobWrapperVersion=e.blobWrapperVersion),"blobs"in e&&e.blobs&&(t.blobs=e.blobs.map(e=>Df(e)?Hf(e):Object.assign({},e))),t}class hd{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#O;constructor(e,t){this.#O=e.transactions.map(e=>"string"!=typeof e?new gd(e,t):e),_f(this,{provider:t,hash:ud(e.hash),number:e.number,timestamp:e.timestamp,parentHash:e.parentHash,parentBeaconBlockRoot:e.parentBeaconBlockRoot,nonce:e.nonce,difficulty:e.difficulty,gasLimit:e.gasLimit,gasUsed:e.gasUsed,blobGasUsed:e.blobGasUsed,excessBlobGas:e.excessBlobGas,miner:e.miner,prevRandao:ud(e.prevRandao),extraData:e.extraData,baseFeePerGas:ud(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot})}get transactions(){return this.#O.map(e=>"string"==typeof e?e:e.hash)}get prefetchedTransactions(){const e=this.#O.slice();return 0===e.length?[]:(kf("object"==typeof e[0],"transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),e)}toJSON(){const{baseFeePerGas:e,difficulty:t,extraData:n,gasLimit:s,gasUsed:r,hash:a,miner:i,prevRandao:o,nonce:f,number:c,parentHash:l,parentBeaconBlockRoot:u,stateRoot:d,receiptsRoot:p,timestamp:h,transactions:y}=this;return{_type:"Block",baseFeePerGas:dd(e),difficulty:dd(t),extraData:n,gasLimit:dd(s),gasUsed:dd(r),blobGasUsed:dd(this.blobGasUsed),excessBlobGas:dd(this.excessBlobGas),hash:a,miner:i,prevRandao:o,nonce:f,number:c,parentHash:l,timestamp:h,parentBeaconBlockRoot:u,stateRoot:d,receiptsRoot:p,transactions:y}}[Symbol.iterator](){let e=0;const t=this.transactions;return{next:()=>e<this.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#O.length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(e){let t;if("number"==typeof e)t=this.#O[e];else{const n=e.toLowerCase();for(const e of this.#O){if("string"==typeof e){if(e!==n)continue;t=e;break}if(e.hash===n){t=e;break}}}if(null==t)throw new Error("no such tx");return"string"==typeof t?await this.provider.getTransaction(t):t}getPrefetchedTransaction(e){const t=this.prefetchedTransactions;if("number"==typeof e)return t[e];e=e.toLowerCase();for(const n of t)if(n.hash===e)return n;Ef(!1,"no matching transaction","indexOrHash",e)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return{orphan:"drop-block",hash:(e=this).hash,number:e.number};var e}}class yd{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(e,t){this.provider=t;const n=Object.freeze(e.topics.slice());_f(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:n,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:n,data:s,index:r,removed:a,topics:i,transactionHash:o,transactionIndex:f}=this;return{_type:"log",address:e,blockHash:t,blockNumber:n,data:s,index:r,removed:a,topics:i,transactionHash:o,transactionIndex:f}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return kf(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return kf(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return kf(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return{orphan:"drop-log",log:{transactionHash:(e=this).transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,address:e.address,data:e.data,topics:Object.freeze(e.topics.slice()),index:e.index}};var e}}class md{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#R;constructor(e,t){this.#R=Object.freeze(e.logs.map(e=>new yd(e,t)));let n=ld;null!=e.effectiveGasPrice?n=e.effectiveGasPrice:null!=e.gasPrice&&(n=e.gasPrice),_f(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,blobGasUsed:e.blobGasUsed,gasPrice:n,blobGasPrice:e.blobGasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return this.#R}toJSON(){const{to:e,from:t,contractAddress:n,hash:s,index:r,blockHash:a,blockNumber:i,logsBloom:o,logs:f,status:c,root:l}=this;return{_type:"TransactionReceipt",blockHash:a,blockNumber:i,contractAddress:n,cumulativeGasUsed:dd(this.cumulativeGasUsed),from:t,gasPrice:dd(this.gasPrice),blobGasUsed:dd(this.blobGasUsed),blobGasPrice:dd(this.blobGasPrice),gasUsed:dd(this.gasUsed),hash:s,index:r,logs:f,logsBloom:o,root:l,status:c,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(null==e)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(null==e)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return wd(this)}reorderedEvent(e){return kf(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),bd(this,e)}}class gd{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;authorizationList;#$;constructor(e,t){this.provider=t,this.blockNumber=null!=e.blockNumber?e.blockNumber:null,this.blockHash=null!=e.blockHash?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=null!=e.maxPriorityFeePerGas?e.maxPriorityFeePerGas:null,this.maxFeePerGas=null!=e.maxFeePerGas?e.maxFeePerGas:null,this.maxFeePerBlobGas=null!=e.maxFeePerBlobGas?e.maxFeePerBlobGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=null!=e.accessList?e.accessList:null,this.blobVersionedHashes=null!=e.blobVersionedHashes?e.blobVersionedHashes:null,this.authorizationList=null!=e.authorizationList?e.authorizationList:null,this.#$=-1}toJSON(){const{blockNumber:e,blockHash:t,index:n,hash:s,type:r,to:a,from:i,nonce:o,data:f,signature:c,accessList:l,blobVersionedHashes:u}=this;return{_type:"TransactionResponse",accessList:l,blockNumber:e,blockHash:t,blobVersionedHashes:u,chainId:dd(this.chainId),data:f,from:i,gasLimit:dd(this.gasLimit),gasPrice:dd(this.gasPrice),hash:s,maxFeePerGas:dd(this.maxFeePerGas),maxPriorityFeePerGas:dd(this.maxPriorityFeePerGas),maxFeePerBlobGas:dd(this.maxFeePerBlobGas),nonce:o,signature:c,to:a,index:n,type:r,value:dd(this.value)}}async getBlock(){let e=this.blockNumber;if(null==e){const t=await this.getTransaction();t&&(e=t.blockNumber)}if(null==e)return null;const t=this.provider.getBlock(e);if(null==t)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(null==this.blockNumber){const{tx:e,blockNumber:t}=await vf({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return null==e||null==e.blockNumber?0:t-e.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(e,t){const n=null==e?1:e,s=null==t?0:t;let r=this.#$,a=-1,i=-1===r;const o=async()=>{if(i)return null;const{blockNumber:e,nonce:t}=await vf({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(t<this.nonce)return void(r=e);if(i)return null;const s=await this.getTransaction();if(!s||null==s.blockNumber)for(-1===a&&(a=r-3,a<this.#$&&(a=this.#$));a<=e;){if(i)return null;const t=await this.provider.getBlock(a,!0);if(null==t)return;for(const e of t)if(e===this.hash)return;for(let s=0;s<t.length;s++){const a=await t.getTransaction(s);if(a.from===this.from&&a.nonce===this.nonce){if(i)return null;const t=await this.provider.getTransactionReceipt(a.hash);if(null==t)return;if(e-t.blockNumber+1<n)return;let s="replaced";a.data===this.data&&a.to===this.to&&a.value===this.value?s="repriced":"0x"===a.data&&a.from===a.to&&a.value===ld&&(s="cancelled"),kf(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===s||"cancelled"===s,reason:s,replacement:a.replaceableTransaction(r),hash:a.hash,receipt:t})}}a++}},f=e=>{if(null==e||0!==e.status)return e;kf(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:e.to,from:e.from,data:""},receipt:e})},c=await this.provider.getTransactionReceipt(this.hash);if(0===n)return f(c);if(c){if(1===n||await c.confirmations()>=n)return f(c)}else if(await o(),0===n)return null;const l=new Promise((e,t)=>{const a=[],c=()=>{a.forEach(e=>e())};if(a.push(()=>{i=!0}),s>0){const e=setTimeout(()=>{c(),t(Sf("wait for transaction timeout","TIMEOUT"))},s);a.push(()=>{clearTimeout(e)})}const l=async s=>{if(await s.confirmations()>=n){c();try{e(f(s))}catch(r){t(r)}}};if(a.push(()=>{this.provider.off(this.hash,l)}),this.provider.on(this.hash,l),r>=0){const e=async()=>{try{await o()}catch(n){if(xf(n,"TRANSACTION_REPLACED"))return c(),void t(n)}i||this.provider.once("block",e)};a.push(()=>{this.provider.off("block",e)}),this.provider.once("block",e)}});return await l}isMined(){return null!=this.blockHash}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}removedEvent(){return kf(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),wd(this)}reorderedEvent(e){return kf(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),kf(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),bd(this,e)}replaceableTransaction(e){Ef(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const t=new gd(this,this.provider);return t.#$=e,t}}function bd(e,t){return{orphan:"reorder-transaction",tx:e,other:t}}function wd(e){return{orphan:"drop-transaction",tx:e}}class vd extends yd{interface;fragment;args;constructor(e,t,n){super(e,e.provider);_f(this,{args:t.decodeEventLog(n,e.data,e.topics),fragment:n,interface:t})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class _d extends yd{error;constructor(e,t){super(e,e.provider),_f(this,{error:t})}}class Td extends md{#P;constructor(e,t,n){super(n,t),this.#P=e}get logs(){return super.logs.map(e=>{const t=e.topics.length?this.#P.getEvent(e.topics[0]):null;if(t)try{return new vd(e,this.#P,t)}catch(n){return new _d(e,n)}return e})}}class xd extends gd{#P;constructor(e,t,n){super(n,t),this.#P=e}async wait(e,t){const n=await super.wait(e,t);return null==n?null:new Td(this.#P,this.provider,n)}}class Ad extends rc{log;constructor(e,t,n,s){super(e,t,n),_f(this,{log:s})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class Sd extends Ad{constructor(e,t,n,s,r){super(e,t,n,new vd(r,e.interface,s));_f(this,{args:e.interface.decodeEventLog(s,this.log.data,this.log.topics),fragment:s})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const kd=BigInt(0);function Ed(e){return e&&"function"==typeof e.call}function Nd(e){return e&&"function"==typeof e.estimateGas}function Id(e){return e&&"function"==typeof e.resolveName}function Cd(e){return e&&"function"==typeof e.sendTransaction}function Od(e){if(null!=e){if(Id(e))return e;if(e.provider)return e.provider}}class Rd{#M;fragment;constructor(e,t,n){if(_f(this,{fragment:t}),t.inputs.length<n.length)throw new Error("too many arguments");const s=$d(e.runner,"resolveName"),r=Id(s)?s:null;this.#M=async function(){const s=await Promise.all(t.inputs.map((e,t)=>null==n[t]?null:e.walkAsync(n[t],(e,t)=>"address"===e?Array.isArray(t)?Promise.all(t.map(e=>Pl(e,r))):Pl(t,r):t)));return e.interface.encodeFilterTopics(t,s)}()}getTopicFilter(){return this.#M}}function $d(e,t){return null==e?null:"function"==typeof e[t]?e:e.provider&&"function"==typeof e.provider[t]?e.provider:null}function Pd(e){return null==e?null:e.provider||null}async function Md(e,t){const n=Bl.dereference(e,"overrides");Ef("object"==typeof n,"invalid overrides parameter","overrides",e);const s=pd(n);return Ef(null==s.to||(t||[]).indexOf("to")>=0,"cannot override to","overrides.to",s.to),Ef(null==s.data||(t||[]).indexOf("data")>=0,"cannot override data","overrides.data",s.data),s.from&&(s.from=s.from),s}async function Dd(e,t,n){const s=$d(e,"resolveName"),r=Id(s)?s:null;return await Promise.all(t.map((e,t)=>e.walkAsync(n[t],(e,t)=>(t=Bl.dereference(t,e),"address"===e?Pl(t,r):t))))}function Fd(e){const t=async function(t){const n=await Md(t,["data"]);n.to=await e.getAddress(),n.from&&(n.from=await Pl(n.from,Od(e.runner)));const s=e.interface,r=Zf(n.value||kd,"overrides.value")===kd,a="0x"===(n.data||"0x");!s.fallback||s.fallback.payable||!s.receive||a||r||Ef(!1,"cannot send data to receive or send value to non-payable fallback","overrides",t),Ef(s.fallback||a,"cannot send data to receive-only contract","overrides.data",n.data);return Ef(s.receive||s.fallback&&s.fallback.payable||r,"cannot send value to non-payable fallback","overrides.value",n.value),Ef(s.fallback||a,"cannot send data to receive-only contract","overrides.data",n.data),n},n=async function(n){const s=e.runner;kf(Cd(s),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const r=await s.sendTransaction(await t(n)),a=Pd(e.runner);return new xd(e.interface,a,r)},s=async e=>await n(e);return _f(s,{_contract:e,estimateGas:async function(n){const s=$d(e.runner,"estimateGas");return kf(Nd(s),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await s.estimateGas(await t(n))},populateTransaction:t,send:n,staticCall:async function(n){const s=$d(e.runner,"call");kf(Ed(s),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const r=await t(n);try{return await s.call(r)}catch(a){if(Af(a)&&a.data)throw e.interface.makeError(a.data,r);throw a}}}),s}const Hd=Symbol.for("_ethersInternal_contract"),Bd=new WeakMap;function jd(e){return Bd.get(e[Hd])}async function Ud(e,t){let n,s=null;if(Array.isArray(t)){const s=function(t){if(Mf(t,32))return t;const n=e.interface.getEvent(t);return Ef(n,"unknown fragment","name",t),n.topicHash};n=t.map(e=>null==e?null:Array.isArray(e)?e.map(s):s(e))}else"*"===t?n=[null]:"string"==typeof t?Mf(t,32)?n=[t]:(s=e.interface.getEvent(t),Ef(s,"unknown fragment","event",t),n=[s.topicHash]):(r=t)&&"object"==typeof r&&"getTopicFilter"in r&&"function"==typeof r.getTopicFilter&&r.fragment?n=await t.getTopicFilter():"fragment"in t?(s=t.fragment,n=[s.topicHash]):Ef(!1,"unknown event name","event",t);var r;n=n.map(e=>{if(null==e)return null;if(Array.isArray(e)){const t=Array.from(new Set(e.map(e=>e.toLowerCase())).values());return 1===t.length?t[0]:(t.sort(),t)}return e.toLowerCase()});return{fragment:s,tag:n.map(e=>null==e?"null":Array.isArray(e)?e.join("|"):e).join("&"),topics:n}}async function Ld(e,t){const{subs:n}=jd(e);return n.get((await Ud(e,t)).tag)||null}async function qd(e,t,n){const s=Pd(e.runner);kf(s,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:t});const{fragment:r,tag:a,topics:i}=await Ud(e,n),{addr:o,subs:f}=jd(e);let c=f.get(a);if(!c){const t={address:o||e,topics:i},l=t=>{let s=r;if(null==s)try{s=e.interface.getEvent(t.topics[0])}catch(a){}if(s){const a=s,i=r?e.interface.decodeEventLog(r,t.data,t.topics):[];Gd(e,n,i,s=>new Sd(e,s,n,a,t))}else Gd(e,n,[],s=>new Ad(e,s,n,t))};let u=[];c={tag:a,listeners:[],start:()=>{u.length||u.push(s.on(t,l))},stop:async()=>{if(0==u.length)return;let e=u;u=[],await Promise.all(e),s.off(t,l)}},f.set(a,c)}return c}let Jd=Promise.resolve();async function Gd(e,t,n,s){try{await Jd}catch(a){}const r=async function(e,t,n,s){await Jd;const r=await Ld(e,t);if(!r)return!1;const i=r.listeners.length;return r.listeners=r.listeners.filter(({listener:t,once:r})=>{const i=Array.from(n);s&&i.push(s(r?null:t));try{t.call(e,...i)}catch(a){}return!r}),0===r.listeners.length&&(r.stop(),jd(e).subs.delete(r.tag)),i>0}(e,t,n,s);return Jd=r,await r}const zd=["then"];class Wd{target;interface;runner;filters;[Hd];fallback;constructor(e,t,n,s){Ef("string"==typeof e||Rl(e),"invalid value for Contract target","target",e),null==n&&(n=null);const r=cd.from(t);let a;_f(this,{target:e,runner:n,interface:r}),Object.defineProperty(this,Hd,{value:{}});let i=null,o=null;if(s){const e=Pd(n);o=new xd(this.interface,e,s)}let f=new Map;if("string"==typeof e)if(Mf(e))i=e,a=Promise.resolve(e);else{const t=$d(n,"resolveName");if(!Id(t))throw Sf("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});a=t.resolveName(e).then(t=>{if(null==t)throw Sf("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:e});return jd(this).addr=t,t})}else a=e.getAddress().then(e=>{if(null==e)throw new Error("TODO");return jd(this).addr=e,e});var c,l;c=this,l={addrPromise:a,addr:i,deployTx:o,subs:f},Bd.set(c[Hd],l);return _f(this,{filters:new Proxy({},{get:(e,t,n)=>{if("symbol"==typeof t||zd.indexOf(t)>=0)return Reflect.get(e,t,n);try{return this.getEvent(t)}catch(s){if(!xf(s,"INVALID_ARGUMENT")||"key"!==s.argument)throw s}},has:(e,t)=>zd.indexOf(t)>=0?Reflect.has(e,t):Reflect.has(e,t)||this.interface.hasEvent(String(t))})}),_f(this,{fallback:r.receive||r.fallback?Fd(this):null}),new Proxy(this,{get:(e,t,n)=>{if("symbol"==typeof t||t in e||zd.indexOf(t)>=0)return Reflect.get(e,t,n);try{return e.getFunction(t)}catch(s){if(!xf(s,"INVALID_ARGUMENT")||"key"!==s.argument)throw s}},has:(e,t)=>"symbol"==typeof t||t in e||zd.indexOf(t)>=0?Reflect.has(e,t):e.interface.hasFunction(t)})}connect(e){return new Wd(this.target,this.interface,e)}attach(e){return new Wd(e,this.interface,this.runner)}async getAddress(){return await jd(this).addrPromise}async getDeployedCode(){const e=Pd(this.runner);kf(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return"0x"===t?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(null!=await this.getDeployedCode())return this;const t=Pd(this.runner);return kf(null!=t,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((e,n)=>{const s=async()=>{try{if(null!=await this.getDeployedCode())return e(this);t.once("block",s)}catch(r){n(r)}};s()})}deploymentTransaction(){return jd(this).deployTx}getFunction(e){"string"!=typeof e&&(e=e.format());const t=function(e,t){const n=function(...n){const s=e.interface.getFunction(t,n);return kf(s,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),s},s=async function(...t){const s=n(...t);let r={};if(s.inputs.length+1===t.length&&(r=await Md(t.pop()),r.from&&(r.from=await Pl(r.from,Od(e.runner)))),s.inputs.length!==t.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const a=await Dd(e.runner,s.inputs,t);return Object.assign({},r,await vf({to:e.getAddress(),data:e.interface.encodeFunctionData(s,a)}))},r=async function(...e){const t=await i(...e);return 1===t.length?t[0]:t},a=async function(...t){const n=e.runner;kf(Cd(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const r=await n.sendTransaction(await s(...t)),a=Pd(e.runner);return new xd(e.interface,a,r)},i=async function(...t){const r=$d(e.runner,"call");kf(Ed(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const a=await s(...t);let i="0x";try{i=await r.call(a)}catch(f){if(Af(f)&&f.data)throw e.interface.makeError(f.data,a);throw f}const o=n(...t);return e.interface.decodeFunctionResult(o,i)},o=async(...e)=>n(...e).constant?await r(...e):await a(...e);return _f(o,{name:e.interface.getFunctionName(t),_contract:e,_key:t,getFragment:n,estimateGas:async function(...t){const n=$d(e.runner,"estimateGas");return kf(Nd(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await s(...t))},populateTransaction:s,send:a,staticCall:r,staticCallResult:i}),Object.defineProperty(o,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getFunction(t);return kf(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),o}(this,e);return t}getEvent(e){return"string"!=typeof e&&(e=e.format()),function(e,t){const n=function(...n){const s=e.interface.getEvent(t,n);return kf(s,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),s},s=function(...t){return new Rd(e,n(...t),t)};return _f(s,{name:e.interface.getEventName(t),_contract:e,_key:t,getFragment:n}),Object.defineProperty(s,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getEvent(t);return kf(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),s}(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,n){null==t&&(t=0),null==n&&(n="latest");const{addr:s,addrPromise:r}=jd(this),a=s||await r,{fragment:i,topics:o}=await Ud(this,e),f={address:a,topics:o,fromBlock:t,toBlock:n},c=Pd(this.runner);return kf(c,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await c.getLogs(f)).map(e=>{let t=i;if(null==t)try{t=this.interface.getEvent(e.topics[0])}catch(n){}if(t)try{return new vd(e,this.interface,t)}catch(n){return new _d(e,n)}return new yd(e,c)})}async on(e,t){const n=await qd(this,"on",e);return n.listeners.push({listener:t,once:!1}),n.start(),this}async once(e,t){const n=await qd(this,"once",e);return n.listeners.push({listener:t,once:!0}),n.start(),this}async emit(e,...t){return await Gd(this,e,t,null)}async listenerCount(e){if(e){const t=await Ld(this,e);return t?t.listeners.length:0}const{subs:t}=jd(this);let n=0;for(const{listeners:s}of t.values())n+=s.length;return n}async listeners(e){if(e){const t=await Ld(this,e);return t?t.listeners.map(({listener:e})=>e):[]}const{subs:t}=jd(this);let n=[];for(const{listeners:s}of t.values())n=n.concat(s.map(({listener:e})=>e));return n}async off(e,t){const n=await Ld(this,e);if(!n)return this;if(t){const e=n.listeners.map(({listener:e})=>e).indexOf(t);e>=0&&n.listeners.splice(e,1)}return null!=t&&0!==n.listeners.length||(n.stop(),jd(this).subs.delete(n.tag)),this}async removeAllListeners(e){if(e){const t=await Ld(this,e);if(!t)return this;t.stop(),jd(this).subs.delete(t.tag)}else{const{subs:e}=jd(this);for(const{tag:t,stop:n}of e.values())n(),e.delete(t)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(e){return class extends Wd{constructor(t,n=null){super(t,e,n)}}}static from(e,t,n){null==n&&(n=null);return new this(e,t,n)}}class Kd extends(function(){return Wd}()){}const Vd={Splitter:tf,Managed:nf,Zoned:sf,Appreciative:rf,Bundle:af,Holons:of};function Zd(e){return Number(xc(e))}const Yd=30078,Xd=30079,Qd=30080;class ep extends Error{constructor(e,t=null){super(e),this.name="AuthorizationError",this.requiredPermission=t}}class tp extends Error{constructor(e){super(e),this.name="ValidationError"}}const np=function(e){return class extends e{hasContracts(){return null!==this._contracts}_requireContracts(){if(!this._contracts)throw new Error("Contracts not initialized. Call initContracts() first.");return this._contracts}async initContracts(e){const t=new ef(e),n=await t.connect(e.network,e.privateKey,e.rpcUrl),s=new yf(t),r=new gf(t,s);return this._contracts={chainManager:t,deployer:s,holonContracts:r,network:e.network},{...n,address:e.privateKey?await t.getAddress():null}}async initContractsBrowser(e){const t=new ef,n=await t.connectBrowser(e),s=new yf(t),r=new gf(t,s);return this._contracts={chainManager:t,deployer:s,holonContracts:r,network:t.networkName},n}async deployContracts(e={}){const{deployer:t}=this._requireContracts();return t.deployAll(e)}loadDeployedContracts(e){const{deployer:t}=this._requireContracts();t.loadDeployedAddresses(e)}getDeployedContracts(){const{deployer:e}=this._requireContracts();return e.getDeployedAddresses()}async deployHolonContract(e,t="Splitter",n={}){const{holonContracts:s}=this._requireContracts();return s.deploy(e,t,n)}async linkHolonContract(e,t,n="Splitter"){const{holonContracts:s}=this._requireContracts();return s.link(e,t,n)}async unlinkHolonContract(e){const{holonContracts:t}=this._requireContracts();return t.unlink(e)}getHolonContract(e){return this._contracts?this._contracts.holonContracts.getContract(e):null}getHolonContractAddress(e){return this._contracts?this._contracts.holonContracts.getAddress(e):null}hasHolonContract(e){return!!this._contracts&&this._contracts.holonContracts.hasContract(e)}listHolonContracts(){return this._contracts?this._contracts.holonContracts.listAll():[]}getHolonOperations(e){const{holonContracts:t}=this._requireContracts();return t.requireOperations(e)}async contractAddMember(e,t){return this.getHolonOperations(e).addMember(t)}async contractAddMembers(e,t){return this.getHolonOperations(e).addMembers(t)}async contractIsMember(e,t){return this.getHolonOperations(e).isMember(t)}async contractReward(e,t,n){return this.getHolonOperations(e).reward(t,n)}async contractRewardEth(e,t){return this.getHolonOperations(e).rewardEth(t)}async contractSendEth(e,t){return this.getHolonOperations(e).sendEth(t)}async contractClaim(e,t,n){return this.getHolonOperations(e).claim(t,n)}async contractGetEthBalance(e,t){return this.getHolonOperations(e).getEthBalance(t)}async contractGetTokenBalance(e,t,n){return this.getHolonOperations(e).getTokenBalance(t,n)}async contractSetSplit(e,t,n){return this.getHolonOperations(e).setContractSplit(t,n)}async contractGetSplit(e){return this.getHolonOperations(e).getContractSplit()}async contractCreateManaged(e,t,n){return this.getHolonOperations(e).createManagedContract(t,n)}async contractCreateZoned(e,t,n,s=6){return this.getHolonOperations(e).createZonedContract(t,n,s)}async contractGetChildContracts(e){return this.getHolonOperations(e).getChildContracts()}async contractSetAppreciation(e,t,n){return this.getHolonOperations(e).setAppreciation(t,n)}async contractGetAppreciation(e,t){return this.getHolonOperations(e).getAppreciation(t)}async contractGetTotalAppreciation(e){return this.getHolonOperations(e).getTotalAppreciation()}async contractAddToZone(e,t,n,s){return this.getHolonOperations(e).addToZone(t,n,s)}async contractRemoveFromZone(e,t,n){return this.getHolonOperations(e).removeFromZone(t,n)}async contractGetZone(e,t){return this.getHolonOperations(e).getZone(t)}async contractSetZoneParams(e,t,n,s,r){return this.getHolonOperations(e).setZoneParameters(t,n,s,r)}async contractAppreciate(e,t,n,s){return this.getHolonOperations(e).appreciate(t,n,s)}async contractGetAppreciationGiven(e,t){return this.getHolonOperations(e).getAppreciationGiven(t)}async contractGetAppreciationReceived(e,t){return this.getHolonOperations(e).getAppreciationReceived(t)}async contractSetSteepness(e,t){return this.getHolonOperations(e).setSteepness(t)}async contractGetSteepness(e){return this.getHolonOperations(e).getSteepness()}async contractSetInteriorSplit(e,t,n){return this.getHolonOperations(e).setInteriorSplit(t,n)}async contractStartElection(e){return this.getHolonOperations(e).startElection()}async contractNominate(e){return this.getHolonOperations(e).nominateSelf()}async contractVote(e,t){return this.getHolonOperations(e).vote(t)}async contractFinalizeElection(e){return this.getHolonOperations(e).finalizeElection()}async contractGetName(e){return this.getHolonOperations(e).getName()}async contractGetOwner(e){return this.getHolonOperations(e).getOwner()}async contractGetBotAddress(e){return this.getHolonOperations(e).getBotAddress()}async contractGetTotalDeposited(e,t){return this.getHolonOperations(e).getTotalDeposited(t)}getNetworkUtils(){return Qo}getChainManager(){return this._contracts?.chainManager||null}}}(function(e){return class extends e{async addFederatedHolosphere(e,t={}){if(!e||"string"!=typeof e)throw new tp("pubKey must be a valid public key string");return St(this.client,this.config.appName,e,t)}async removeFederatedHolosphere(e){return async function(e,t,n){const s=await xt(e,t),r=s.federatedWith.length;return s.federatedWith=s.federatedWith.filter(e=>e.pubKey!==n),s.federatedWith.length!==r&&At(e,t,s)}(this.client,this.config.appName,e)}async getFederatedHolospheres(){return async function(e,t){return(await xt(e,t)).federatedWith.map(e=>e.pubKey)}(this.client,this.config.appName)}async getFederationRegistry(){return xt(this.client,this.config.appName)}async storeInboundCapability(e,t){return Et(this.client,this.config.appName,e,t)}async readFromFederatedSource(e,t,n,s=null){const r=await kt(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:s});if(!r)throw new ep("No valid capability for federated source","read");if(!(await this.verifyCapability(r.token,"read",{holonId:t,lensName:n,dataId:s})))throw new ep("Capability verification failed","read");if(s){const r=we(this.config.appName,t,n,s);return de(this.client,r,3e4,{authors:[e],includeAuthor:!0})}{const s=we(this.config.appName,t,n);return pe(this.client,s,3e4,{authors:[e],includeAuthor:!0})}}async createCrossHolosphereHologram(e,t,n,s,r,a={}){const{embedCapability:i=!0}=a,o=await kt(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:s});if(!o)throw new ep("No valid capability for cross-holosphere hologram","read");const f=It(t,0,n,s,this.config.appName,{authorPubKey:e,capability:i?o.token:null}),c=we(this.config.appName,r,n,s);return await ve(this.client,c,f),f}async issueCapabilityForFederation(e,t,n,s={}){const{expiresIn:r=36e5,trackInRegistry:a=!0}=s,i=await bt(n,t,e,{expiresIn:r,issuerKey:this.client.privateKey});if(a){await async function(e,t,n){return(await xt(e,t)).federatedWith.find(e=>e.pubKey===n)||null}(this.client,this.config.appName,e)||await St(this.client,this.config.appName,e,{addedVia:"capability_issued"}),await async function(e,t,n,s){const r=await xt(e,t),a=r.federatedWith.find(e=>e.pubKey===n);if(!a)throw new Error(`Partner ${n} not found in federation registry`);return a.outboundCapabilities||(a.outboundCapabilities=[]),a.outboundCapabilities.push({tokenHash:s.tokenHash,scope:s.scope,permissions:s.permissions,issuedAt:Date.now(),expires:s.expires}),At(e,t,r)}(this.client,this.config.appName,e,{tokenHash:await this._hashToken(i),scope:t,permissions:n,expires:Date.now()+r})}return i}async _hashToken(e){const t=new TextEncoder;return ze(ut(t.encode(e)))}async sendFederationRequest(e,t={}){return async function(e,t,n,s={}){const{scope:r={holonId:"*",lensName:"*"},permissions:a=["read"],message:i="Federation request",expiresIn:o=2592e6}=s,f=await bt(a,r,n,{issuerKey:e.privateKey,expiresIn:o}),c={kind:Yd,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-request-${n.slice(0,16)}`],["p",n],["holosphere",t],["scope",JSON.stringify(r)],["permissions",a.join(",")]],content:JSON.stringify({message:i,offeredCapability:f,requestedScope:r,requestedPermissions:a})},l=await e.publish(c);return{eventId:l.id||null,targetPubKey:n,scope:r,permissions:a,offeredCapability:f,...l}}(this.client,this.config.appName,e,t)}async subscribeFederationRequests(e){return async function(e,t){const n={kinds:[Yd],"#p":[e.publicKey]};return e.subscribe(n,e=>{try{const n=JSON.parse(e.content),s=e.tags.find(e=>"scope"===e[0]),r=e.tags.find(e=>"permissions"===e[0]),a=e.tags.find(e=>"holosphere"===e[0]),i={eventId:e.id,requesterPubKey:e.pubkey,appname:a?.[1],scope:s?JSON.parse(s[1]):{holonId:"*",lensName:"*"},permissions:r?r[1].split(","):["read"],message:n.message,offeredCapability:n.offeredCapability,timestamp:e.created_at};t(i)}catch(n){console.error("Failed to parse federation request:",n)}})}(this.client,e)}async acceptFederationRequest(e,t={}){return async function(e,t,n,s={}){const{scope:r=n.scope,permissions:a=n.permissions,alias:i=null,expiresIn:o=2592e6}=s,f=await bt(a,r,n.requesterPubKey,{issuerKey:e.privateKey,expiresIn:o});await St(e,t,n.requesterPubKey,{alias:i,addedVia:"nostr_discovery",inboundCapabilities:[{token:n.offeredCapability,scope:n.scope,permissions:n.permissions,expires:Date.now()+o}]});const c={kind:Xd,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-accept-${n.requesterPubKey.slice(0,16)}`],["p",n.requesterPubKey],["e",n.eventId],["holosphere",t],["scope",JSON.stringify(r)],["permissions",a.join(",")]],content:JSON.stringify({acceptedScope:r,grantedCapability:f})},l=await e.publish(c);return{eventId:l.id||null,requesterPubKey:n.requesterPubKey,grantedCapability:f,acceptedScope:r,...l}}(this.client,this.config.appName,e,t)}async declineFederationRequest(e,t=""){return async function(e,t,n,s=""){const r={kind:Qd,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-decline-${n.requesterPubKey.slice(0,16)}`],["p",n.requesterPubKey],["e",n.eventId],["holosphere",t]],content:JSON.stringify({reason:s})},a=await e.publish(r);return{eventId:a.id||null,requesterPubKey:n.requesterPubKey,reason:s,...a}}(this.client,this.config.appName,e,t)}async subscribeFederationAcceptances(e){return async function(e,t,n){const s={kinds:[Xd],"#p":[e.publicKey]};return e.subscribe(s,async s=>{try{const r=JSON.parse(s.content),a=s.tags.find(e=>"scope"===e[0]),i=s.tags.find(e=>"permissions"===e[0]);await Et(e,t,s.pubkey,{token:r.grantedCapability,scope:a?JSON.parse(a[1]):r.acceptedScope,permissions:i?i[1].split(","):["read"],expires:Date.now()+2592e6}),n({accepterPubKey:s.pubkey,originalRequestId:s.tags.find(e=>"e"===e[0])?.[1],acceptedScope:r.acceptedScope,grantedCapability:r.grantedCapability,timestamp:s.created_at})}catch(r){console.error("Failed to parse federation acceptance:",r)}})}(this.client,this.config.appName,e)}async subscribeFederationDeclines(e){return async function(e,t){const n={kinds:[Qd],"#p":[e.publicKey]};return e.subscribe(n,e=>{try{const n=JSON.parse(e.content);t({declinerPubKey:e.pubkey,originalRequestId:e.tags.find(e=>"e"===e[0])?.[1],reason:n.reason||"",timestamp:e.created_at})}catch(n){console.error("Failed to parse federation decline:",n)}})}(this.client,e)}async getPendingFederationRequests(e={}){return async function(e,t={}){const n=t.since||Math.floor((Date.now()-2592e6)/1e3),s={kinds:[Yd],authors:[e.publicKey],since:n},r=await e.query(s),a={kinds:[Xd,Qd],"#p":[e.publicKey],since:n},i=await e.query(a),o=new Set;for(const l of i){const e=l.tags.find(e=>"e"===e[0]);e&&o.add(e[1])}const f=[];for(const l of r)if(!o.has(l.id))try{const e=JSON.parse(l.content),t=l.tags.find(e=>"p"===e[0]),n=l.tags.find(e=>"scope"===e[0]),s=l.tags.find(e=>"permissions"===e[0]);f.push({eventId:l.id,targetPubKey:t?.[1],scope:n?JSON.parse(n[1]):{holonId:"*",lensName:"*"},permissions:s?s[1].split(","):["read"],message:e.message,timestamp:l.created_at})}catch(c){console.error("Failed to parse pending request:",c)}return f}(this.client,e)}}}((sp=
|
|
5
|
-
/**
|
|
6
|
-
* @fileoverview HoloSphere - Holonic Geospatial Communication Infrastructure
|
|
7
|
-
*
|
|
8
|
-
* This is the main entry point for the HoloSphere library, providing a comprehensive
|
|
9
|
-
* distributed P2P geospatial communication system. It combines H3 hexagonal indexing
|
|
10
|
-
* for spatial organization, Nostr protocol for distributed storage, smart contracts
|
|
11
|
-
* for fund distribution, and AI services for intelligent data processing.
|
|
12
|
-
*
|
|
13
|
-
* @module holosphere
|
|
14
|
-
* @author HoloSphere Team
|
|
15
|
-
* @license MIT
|
|
16
|
-
*/
|
|
17
|
-
class extends te{constructor(e){super(e),this.schemas=new Map,this._cache=new Map,this.subscriptionRegistry=new hn,this._writeCache=new Map,this._pendingWrites=new Map,this._deleteCache=new Set,this._ai=null;const t=e.openaiKey||this._getEnv("OPENAI_API_KEY");if(t){const n={...e.aiOptions,model:e.aiOptions?.model||this._getEnv("HOLOSPHERE_AI_MODEL"),temperature:e.aiOptions?.temperature??this._parseFloat(this._getEnv("HOLOSPHERE_AI_TEMPERATURE"))};this._initializeAI(t,n)}this._contracts=null}_getEnv(e){if("undefined"!=typeof process&&process.env)return process.env[e]}_parseFloat(e){if(null==e)return;const t=parseFloat(e);return isNaN(t)?void 0:t}_initializeAI(e,t={}){const n={...t.llm,model:t.model||t.llm?.model,temperature:t.temperature??t.llm?.temperature};this._ai={llm:new Io(e,n)};const s=new(0,require("openai").default)({apiKey:e});this._ai.openai=s,this._ai.embeddings=new Ro(s,this),this._ai.schemaExtractor=new Co(this._ai.llm),this._ai.jsonOps=new Oo(this._ai.llm),this._ai.council=new Po(this._ai.llm),this._ai.tts=new Fo(s),this._ai.nlQuery=new Ho(this._ai.llm,this),this._ai.classifier=new Bo(this._ai.llm,this),this._ai.spatial=new jo(this._ai.llm,this),this._ai.aggregation=new Uo(this._ai.llm,this),this._ai.federationAdvisor=new Lo(this._ai.llm,this,this._ai.embeddings),this._ai.relationships=new qo(this._ai.llm,this,this._ai.embeddings),this._ai.taskBreakdown=new Jo(this._ai.llm,this),this._ai.h3ai=new Go(this._ai.llm,this)}hasAI(){return null!==this._ai}getAIServices(){return this._ai}async toHolon(e,t,n){return ne(e,t,n)}async getParents(e,t){return se(e,t)}async getChildren(e){return re(e)}isValidH3(e){return ae(e)}async write(e,t,n,s={}){if(null!=e&&(e=String(e)),null!=t&&(t=String(t)),!e)throw new Re("ValidationError: holonId must be a non-empty string");if(!t)throw new Re("ValidationError: lensName must be a non-empty string");if(!n||"object"!=typeof n)throw new Re("ValidationError: data must be an object");const r=s.capabilityToken||s.capability;if(r&&!(await this.verifyCapability(r,"write",{holonId:e,lensName:t})))throw new ep("AuthorizationError: Invalid capability token for write operation","write");n.id?n.id=String(n.id):n.id=`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n._meta||(n._meta={}),n._meta.createdAt=n._meta.createdAt||Date.now(),n._meta.updatedAt=Date.now();const a=we(this.config.appName,e,t,n.id);if(this._log("DEBUG","write",{holonId:e,lensName:t,dataId:n.id,path:a,blocking:!!s.blocking}),!1!==s.validate&&this.schemas.has(t)){const e=this.schemas.get(t),r=void 0!==s.strict?s.strict:e.strict;e.schema&&"object"==typeof e.schema&&!e.schema.$ref&&Pe(n,e.schema,t,r)}this._writeCache.set(a,{data:{...n},timestamp:Date.now()}),this._deleteCache.delete(a),this._log("DEBUG","📝 CACHE WRITE",{path:a,dataId:n.id,cacheSize:this._writeCache.size,mode:s.blocking?"blocking":"optimistic"});const i=this._syncWriteToRelay(e,t,n,a,s);return s.blocking?(this._log("DEBUG","⏳ BLOCKING: Waiting for relay confirmation",{path:a}),i):(this._log("DEBUG","⚡ OPTIMISTIC: Returning immediately, sync in background",{path:a}),!0)}async _syncWriteToRelay(e,t,n,s,r){const a=Date.now();this._log("DEBUG","🔄 RELAY SYNC START",{path:s,dataId:n.id,relays:this.client?.relays?.map(e=>e.url)||["local-only"]});try{const i=await _e(this.client,s);if(i&&!0===i.hologram&&i.target)return this._log("DEBUG","🔗 Syncing hologram write",{path:s,target:i.target}),this._syncHologramWrite(i,n,s,t,r);await ve(this.client,s,n);const o=Date.now()-a;this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=o,this._log("DEBUG","✅ RELAY SYNC SUCCESS",{path:s,dataId:n.id,duration:`${o}ms`,totalWrites:this._metrics.writes});const{autoPropagate:f=!0}=r;return f&&!n.hologram&&(this._log("DEBUG","📤 Starting propagation",{path:s}),this.propagate(e,t,n,r.propagationOptions||{}).catch(e=>this._log("WARN","⚠️ Propagation failed",{path:s,error:e.message}))),!0}catch(i){const e=Date.now()-a;return this._log("ERROR","❌ RELAY SYNC FAILED",{path:s,dataId:n.id,duration:`${e}ms`,error:i.message,stack:i.stack?.split("\n")[1]?.trim()}),this._log("WARN","💾 Data retained in write cache for retry",{path:s,cacheSize:this._writeCache.size}),!1}}async _syncHologramWrite(e,t,n,s,r){const a=["hologram","soul","target","id","_meta"],i=Object.keys(e).filter(e=>!a.includes(e)),o={...e},f={};for(const[u,d]of Object.entries(t))a.includes(u)||"_hologram"===u||(i.includes(u)?o[u]=d:f[u]=d);if(Object.keys(f).length>0&&!1!==r.validate&&this.schemas.has(s)){const t=we(e.target.appname||this.config.appName,e.target.holonId,e.target.lensName,e.target.dataId),n={...await _e(this.client,t),...f},a=this.schemas.get(s),i=void 0!==r.strict?r.strict:a.strict;a.schema&&"object"==typeof a.schema&&!a.schema.$ref&&Pe(n,a.schema,s,i)}const c=Date.now();if(await ve(this.client,n,o),Object.keys(f).length>0){const t=we(e.target.appname||this.config.appName,e.target.holonId,e.target.lensName,e.target.dataId);await xe(this.client,t,f),await Ut(this.client,e.target.appname||this.config.appName,e.target.holonId,e.target.lensName,e.target.dataId)}const l=Date.now();return this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=l-c,!0}async _resolveHolograms(e,t=new Set){if(!e)return e;if(Array.isArray(e)){const t=[];for(const n of e){const e=await this._resolveHolograms(n,new Set);null!==e&&t.push(e)}return t}if(e&&"object"==typeof e&&!0===e.hologram&&e.target){const n=we(e.target.appname||this.config.appName,e.target.holonId,e.target.lensName,e.target.dataId);if(this._log("DEBUG","resolving hologram",{hologramId:e.id,sourcePath:n,targetHolon:e.target.holonId,targetLens:e.target.lensName,targetDataId:e.target.dataId}),t.has(n))return this._log("WARN","Circular hologram reference detected",{sourcePath:n}),null;t.add(n);let s={};e.target.authorPubKey&&(s.authors=[e.target.authorPubKey],s.includeAuthor=!0);const r=await _e(this.client,n,s);if(this._log("DEBUG","hologram source fetched",{found:!!r,sourcePath:n}),r){let n=r;if(!0===r.hologram&&r.target&&(n=await this._resolveHolograms(r,t),null===n))return null;const s=["hologram","soul","target","_meta","id","capability","crossHolosphere"],a={};for(const[t,r]of Object.entries(e))s.includes(t)||(a[t]=r);const i={...n,...a,_hologram:{isHologram:!0,soul:e.soul,sourceHolon:e.target.holonId,source:e.target,localOverrides:Object.keys(a),crossHolosphere:e.crossHolosphere||!1}};return n._meta?i._meta={...n._meta,source:e.target.holonId}:i._meta={source:e.target.holonId},i}return null}return e}async read(e,t,n=null,s={}){if(null!=e&&(e=String(e)),null!=t&&(t=String(t)),null!=n&&(n=String(n)),!e)throw new Re("ValidationError: holonId must be a non-empty string");if(!t)throw new Re("ValidationError: lensName must be a non-empty string");const r=s.capabilityToken||s.capability;if(r&&!(await this.verifyCapability(r,"read",{holonId:e,lensName:t,dataId:n})))throw new ep("AuthorizationError: Invalid capability token for read operation","read");const a=Date.now();let i;if(n){const s=we(this.config.appName,e,t,n);if(this._deleteCache.has(s))this._log("DEBUG","🗑️ CACHE READ: Deleted item",{path:s,source:"delete-cache",deleteCacheSize:this._deleteCache.size}),i=null;else{const e=this._writeCache.get(s);if(e){const t=Date.now()-e.timestamp;this._log("DEBUG","⚡ CACHE HIT: Write cache",{path:s,source:"write-cache",cacheAge:`${t}ms`,writeCacheSize:this._writeCache.size}),i=e.data}else this._log("DEBUG","📖 CACHE MISS: Reading from storage",{path:s}),i=await _e(this.client,s),this._log("DEBUG","💾 STORAGE READ",{path:s,source:"storage",found:!!i,isHologram:!0===i?.hologram})}}else{const n=we(this.config.appName,e,t);this._log("DEBUG","readAll",{holonId:e,lensName:t,path:n});const s=await Te(this.client,n);i=this._mergeWithWriteCache(s,n),this._log("DEBUG","readAll result",{count:Array.isArray(i)?i.length:0})}const{resolveHolograms:o=!0}=s;o&&i&&(this._log("DEBUG","resolving holograms",{itemCount:Array.isArray(i)?i.length:1}),i=await this._resolveHolograms(i));const f=Date.now();return this._metrics.reads++,this._metrics.totalReadTime||(this._metrics.totalReadTime=0),this._metrics.totalReadTime+=f-a,i}_mergeWithWriteCache(e,t){const n=Array.isArray(e)?[...e]:[],s=new Map(n.map(e=>[e.id,e]));for(const[r,a]of this._writeCache.entries())if(r.startsWith(t+"/")){const e=a.data;e.id&&s.set(e.id,e)}for(const r of this._deleteCache)if(r.startsWith(t+"/")){const e=r.split("/").pop();s.delete(e)}return Array.from(s.values())}async update(e,t,n,s,r={}){if(!e||"string"!=typeof e)throw new Re("ValidationError: holonId must be a non-empty string");if(!t||"string"!=typeof t)throw new Re("ValidationError: lensName must be a non-empty string");if(!n||"string"!=typeof n)throw new Re("ValidationError: dataId must be a non-empty string");if(!s||"object"!=typeof s)throw new Re("ValidationError: updates must be an object");const a=r.capabilityToken||r.capability;if(a&&!(await this.verifyCapability(a,"write",{holonId:e,lensName:t,dataId:n})))throw new ep("AuthorizationError: Invalid capability token for update operation","write");const i=we(this.config.appName,e,t,n),o=this._writeCache.get(i),f=o?o.data:await _e(this.client,i),c=o?"write-cache":"storage";if(!f)return this._log("DEBUG","✏️ UPDATE: Data not found",{path:i,dataId:n}),!1;if(this._log("DEBUG","✏️ UPDATE: Found data",{path:i,dataId:n,source:c}),!0===f.hologram&&f.target)return this._log("DEBUG","🔗 Updating hologram",{path:i}),this.write(e,t,{...f,...s,id:n},r);const l={...f,...s};if(l._meta=l._meta||{},l._meta.updatedAt=Date.now(),!1!==r.validate&&this.schemas.has(t)){const e=this.schemas.get(t),n=void 0!==r.strict?r.strict:e.strict;e.schema&&"object"==typeof e.schema&&!e.schema.$ref&&Pe(l,e.schema,t,n)}this._writeCache.set(i,{data:{...l},timestamp:Date.now()}),this._deleteCache.delete(i),this._log("DEBUG","✏️ CACHE UPDATE",{path:i,dataId:n,updatedFields:Object.keys(s),cacheSize:this._writeCache.size,mode:r.blocking?"blocking":"optimistic"});const u=this._syncUpdateToRelay(e,t,n,l,f,i);return!r.blocking||(this._log("DEBUG","⏳ BLOCKING: Waiting for update confirmation",{path:i}),u)}async _syncUpdateToRelay(e,t,n,s,r,a){const i=Date.now();this._log("DEBUG","🔄 UPDATE SYNC START",{path:a,dataId:n,relays:this.client?.relays?.map(e=>e.url)||["local-only"]});try{await ve(this.client,a,s);const o=Date.now()-i;return this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=o,this._log("DEBUG","✅ UPDATE SYNC SUCCESS",{path:a,dataId:n,duration:`${o}ms`,totalWrites:this._metrics.writes}),r._meta&&r._meta.activeHolograms&&(this._log("DEBUG","🔗 Refreshing active holograms",{path:a}),Ut(this.client,this.config.appName,e,t,n).catch(e=>this._log("WARN","⚠️ Hologram refresh failed",{path:a,error:e.message}))),!0}catch(o){const e=Date.now()-i;return this._log("ERROR","❌ UPDATE SYNC FAILED",{path:a,dataId:n,duration:`${e}ms`,error:o.message,stack:o.stack?.split("\n")[1]?.trim()}),this._log("WARN","💾 Data retained in write cache for retry",{path:a,cacheSize:this._writeCache.size}),!1}}async delete(e,t,n,s={}){if(null!=e&&(e=String(e)),null!=t&&(t=String(t)),null!=n&&(n=String(n)),!e)throw new Re("ValidationError: holonId must be a non-empty string");if(!t)throw new Re("ValidationError: lensName must be a non-empty string");if(!n)throw new Re("ValidationError: dataId must be a non-empty string");const r=we(this.config.appName,e,t,n),a=this._writeCache.get(r);let i=a?a.data:null,o=a?"write-cache":null;if(i||(i=await _e(this.client,r),o=i?"storage":null),!i)return this._log("DEBUG","🗑️ DELETE: Data not found",{path:r}),!1;this._log("DEBUG","🗑️ DELETE: Found data",{path:r,source:o});const f=i.owner||i._creator,c=!f||f===this.client.publicKey,l=s.capabilityToken||s.capability;if(c){if(l&&!(await this.verifyCapability(l,"delete",{holonId:e,lensName:t,dataId:n})))throw new ep("AuthorizationError: Invalid capability token for delete operation","delete")}else{if(!l)throw new ep("AuthorizationError: Capability token required for delete operation","delete");if(!(await this.verifyCapability(l,"delete",{holonId:e,lensName:t,dataId:n})))throw new ep("AuthorizationError: Invalid capability token for delete operation","delete")}if(this._writeCache.delete(r),this._deleteCache.add(r),this._log("DEBUG","🗑️ CACHE DELETE",{path:r,dataId:n,deleteCacheSize:this._deleteCache.size,writeCacheSize:this._writeCache.size,mode:s.blocking?"blocking":"optimistic"}),!0===i.hologram)return this._log("DEBUG","🔗 Deleting hologram",{path:r}),this.deleteHologram(e,t,n,s);const u=Date.now();this._log("DEBUG","🔄 DELETE SYNC START",{path:r,dataId:n});const d=Ae(this.client,r).then(()=>{const e=Date.now()-u;return this._metrics.deletes++,this._deleteCache.delete(r),this._log("DEBUG","✅ DELETE SYNC SUCCESS",{path:r,dataId:n,duration:`${e}ms`,totalDeletes:this._metrics.deletes,deleteCacheSize:this._deleteCache.size}),!0}).catch(e=>{const t=Date.now()-u;return this._log("ERROR","❌ DELETE SYNC FAILED",{path:r,dataId:n,duration:`${t}ms`,error:e.message}),this._log("WARN","💾 Path retained in delete cache",{path:r,deleteCacheSize:this._deleteCache.size}),!1});return s.blocking?(this._log("DEBUG","⏳ BLOCKING: Waiting for delete confirmation",{path:r}),d):(this._log("DEBUG","⚡ OPTIMISTIC: Returning immediately, delete sync in background",{path:r}),!0)}async writeGlobal(e,t){return null!=e&&(e=String(e)),null!=t?.id&&(t.id=String(t.id)),Ne(this.client,this.config.appName,e,t)}async readGlobal(e,t=null){return null!=e&&(e=String(e)),null!=t&&(t=String(t)),Ie(this.client,this.config.appName,e,t)}async updateGlobal(e,t,n){return null!=e&&(e=String(e)),null!=t&&(t=String(t)),async function(e,t,n,s,r){return xe(e,`${t}/${n}/${s}`,r)}(this.client,this.config.appName,e,t,n)}async deleteGlobal(e,t){return null!=e&&(e=String(e)),null!=t&&(t=String(t)),async function(e,t,n,s){return Ae(e,`${t}/${n}/${s}`)}(this.client,this.config.appName,e,t)}async getAllGlobal(e){return null!=e&&(e=String(e)),async function(e,t,n){return Te(e,`${t}/${n}`)}(this.client,this.config.appName,e)}async deleteAllGlobal(e){return null!=e&&(e=String(e)),async function(e,t,n){return Se(e,`${t}/${n}`)}(this.client,this.config.appName,e)}async getAll(e,t){return this.read(e,t,null)}async deleteAll(e,t){null!=e&&(e=String(e)),null!=t&&(t=String(t));const n=we(this.config.appName,e,t);return Se(this.client,n)}async setSchema(e,t,n=!1){if(!e||"string"!=typeof e)throw new Re("ValidationError: lensName must be a non-empty string");if(null==t)throw new Re("ValidationError: schema cannot be null or undefined");let s;if("string"==typeof t)s={$ref:t};else{if("object"!=typeof t)throw new Re("ValidationError: schema must be an object or URI string");if(!(t.$ref||t.type||t.properties||t.items||t.allOf||t.anyOf||t.oneOf||t.$schema))throw new Re("ValidationError: Invalid JSON Schema format");s=t}this.schemas.set(e,{schema:s,strict:n,timestamp:Date.now()})}async getSchema(e){const t=this.schemas.get(e);return t?t.schema:null}async clearSchema(e){this.schemas.delete(e)}async federate(e,t,n,s={}){const{direction:r="outbound",mode:a="reference",filter:i=null}=s;if(e===t)throw new Error("Cannot federate a holon with itself");if(!["inbound","outbound","bidirectional"].includes(r))throw new Error(`Invalid direction: ${r}. Must be 'inbound', 'outbound', or 'bidirectional'`);return await Ot(this.client,this.config.appName,e,t,n,s),"outbound"!==r&&"bidirectional"!==r||await this._propagateExistingData(e,t,n,{mode:a,filter:i}),"inbound"!==r&&"bidirectional"!==r||await this._propagateExistingData(t,e,n,{mode:a,filter:i}),this._metrics.federations=(this._metrics.federations||0)+1,!0}async _propagateExistingData(e,t,n,s={}){const{mode:r="reference",filter:a=null}=s,i=await this.read(e,n,null,{resolveHolograms:!1});if(!i)return;const o=Array.isArray(i)?i:[i];for(const f of o)!0!==f.hologram&&(a&&!a(f)||await Rt(this.client,this.config.appName,f,e,t,n,r))}async getFederatedData(e,t,n={}){const{resolveHolograms:s=!0}=n,r=we(this.config.appName,e,t),a=await Te(this.client,r);return a&&s?this._resolveHolograms(a):a}async unfederate(e,t,n){const s=we(this.config.appName,e,n,"_federation");try{await Ae(this.client,s)}catch(r){}return!0}async updateHologramOverrides(e,t,n,s){return $t(this.client,this.config.appName,e,t,n,s)}createHologram(e,t,n,s=null){return It(e,0,t,n.id,this.config.appName)}async getActiveHolograms(e,t,n){const s=we(this.config.appName,e,t,n),r=await _e(this.client,s);return r&&r._meta&&r._meta.activeHolograms?r._meta.activeHolograms:[]}async removeActiveHologram(e,t,n,s){return Ht(this.client,this.config.appName,e,t,n,s)}async deleteHologram(e,t,n,s={}){return Lt(this.client,this.config.appName,e,t,n,s)}async propagateData(e,t,n,s,r={}){const a=r.mode||"reference";return Rt(this.client,this.config.appName,e,t,n,s,a)}async resolveHologram(e,t={}){return Ct(this.client,e,new Set,[],{...t,appname:this.config.appName})}isHologram(e){return Pt(e)}isResolvedHologram(e){return Mt(e)}getHologramSource(e){return Dt(e)}async updateHologramPlatform(e,t,n,s,r,a){return Bt(this.client,this.config.appName,e,t,n,s,r,a)}async getActiveHolograms(e,t,n,s=null){return jt(this.client,this.config.appName,e,t,n,s)}async cleanupCircularHolograms(e,t,n={}){return qt(this.client,this.config.appName,e,t,n)}async cleanupCircularHologramsByIds(e,t,n,s={}){return Jt(this.client,this.config.appName,e,t,n,s)}async propagate(e,t,n,s={}){const r=await this.getFederation(e),a=r?.federated||r?.outbound||[];if(!a||0===a.length)return;const{useHolograms:i=!0,resolveExisting:o=!0}=s,f=[];for(const c of a){const s=await this.propagateData(n,e,c,t,{useHolograms:i,resolveExisting:o});f.push({parent:c,...s})}return f}async getFederation(e){if(!e)throw new Error("getFederation: Missing holon ID");const t=await this.readGlobal("federation",e);if(!t)return null;if(Array.isArray(t.inbound)||(t.inbound=[]),Array.isArray(t.outbound)||(t.outbound=[]),t.lensConfig&&"object"==typeof t.lensConfig||(t.lensConfig={}),t.partnerNames&&"object"==typeof t.partnerNames||(t.partnerNames={}),!Array.isArray(t.federated)){const e=new Set([...t.inbound,...t.outbound]);t.federated=Array.from(e)}return t}async federateHolon(e,t,n={}){const{lensConfig:s={inbound:[],outbound:[]},partnerName:r=null,skipPropagation:a=!1}=n;if(e===t)throw new Error("Cannot federate a holon with itself");let i=await this.readGlobal("federation",e)||{id:e,name:e,federated:[],inbound:[],outbound:[],lensConfig:{},partnerNames:{},timestamp:Date.now()};Array.isArray(i.federated)||(i.federated=[]),Array.isArray(i.inbound)||(i.inbound=[]),Array.isArray(i.outbound)||(i.outbound=[]),i.lensConfig&&"object"==typeof i.lensConfig||(i.lensConfig={}),i.partnerNames&&"object"==typeof i.partnerNames||(i.partnerNames={}),i.federated.includes(t)||i.federated.push(t),r&&(i.partnerNames[t]=r),s.outbound&&s.outbound.length>0?i.outbound.includes(t)||i.outbound.push(t):i.outbound=i.outbound.filter(e=>e!==t),s.inbound&&s.inbound.length>0?i.inbound.includes(t)||i.inbound.push(t):i.inbound=i.inbound.filter(e=>e!==t),i.lensConfig[t]={inbound:s.inbound||[],outbound:s.outbound||[],timestamp:Date.now()};const o=await this.writeGlobal("federation",i);if(this.clearCache("federation"),o&&!a){for(const n of s.inbound||[])await this.federate(t,e,n,{direction:"outbound",mode:"reference"});for(const n of s.outbound||[])await this.federate(e,t,n,{direction:"outbound",mode:"reference"})}return o}async unfederateHolon(e,t){const n=await this.readGlobal("federation",e);if(!n)return!1;const s=n.lensConfig?.[t];n.federated=(n.federated||[]).filter(e=>e!==t),n.inbound=(n.inbound||[]).filter(e=>e!==t),n.outbound=(n.outbound||[]).filter(e=>e!==t),n.lensConfig&&delete n.lensConfig[t];const r=await this.writeGlobal("federation",n);if(this.clearCache("federation"),r&&s){for(const n of s.inbound||[])await this.unfederate(t,e,n);for(const n of s.outbound||[])await this.unfederate(e,t,n)}return r}async getFederatedConfig(e,t){const n=await this.readGlobal("federation",e);return n&&n.lensConfig&&n.lensConfig[t]||null}async upcast(e,t,n,s={}){return mn(this,e,t,n,s)}subscribe(e,t,n,s={}){if("function"!=typeof n)throw new TypeError("callback must be a function");const r=we(this.config.appName,e,t),a={realtimeOnly:!0,...s},i=`${e}-${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;let o=null,f=!1;return pn(this.client,r,n,a).then(e=>{o=e,f?e.unsubscribe():this.subscriptionRegistry.register(i,e)}).catch(e=>{this._log("ERROR","Subscription setup failed",{path:r,error:e.message})}),this._metrics.subscriptions=(this._metrics.subscriptions||0)+1,{unsubscribe:()=>{f=!0,o&&this.subscriptionRegistry.unregister(i)}}}async subscribeGlobal(e,t,n,s={}){return async function(e,t,n,s,r,a={}){return ke(e,s?`${t}/${n}/${s}`:`${t}/${n}`,r,a)}(this.client,this.config.appName,e,t,n,s)}async getPublicKey(e){return ht(e)}async sign(e,t){return yt(e,t)}async verify(e,t,n){return mt(e,t,n)}async issueCapability(e,t,n,s){return bt(e,t,n,s)}async verifyCapability(e,t,n){return wt(e,t,n)}async publishNostr(e,t,n="social"){cn(e,!0,!0);const s=en({...e,tags:[...e.tags||[],["h",t],["l",n]]},this.client.privateKey),r={...s,protocol:"nostr"},a=we(this.config.appName,t,n,s.id);return await ve(this.client,a,r),!0}async publishActivityPub(e,t,n="social"){ln(e,!0);const s=un({...e,actor:e.actor||this.client.publicKey});return this.write(t,n,s)}async querySocial(e,t={}){const n=t.lens||"social",s=await this.read(e,n);return s?(Array.isArray(s)?s:[s]).filter(e=>!(t.protocol&&"all"!==t.protocol&&e.protocol!==t.protocol||t.type&&e.type!==t.type||t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)):[]}async verifyNostrEvent(e){const{id:t,pubkey:n,created_at:s,kind:r,tags:a,content:i,sig:o}=e;return tn({id:t,pubkey:n,created_at:s,kind:r,tags:a,content:i,sig:o})}metrics(){const e=this._metrics.reads||0,t=this._metrics.writes||0,n=this._metrics.totalReadTime||0,s=this._metrics.totalWriteTime||0;return{reads:e,writes:t,deletes:this._metrics.deletes||0,federations:this._metrics.federations||0,subscriptions:this._metrics.subscriptions||0,avgReadTime:e>0?n/e:0,avgWriteTime:t>0?s/t:0}}getCacheStatus(){const e=Date.now(),t=[];for(const[n,s]of this._writeCache.entries())t.push({path:n,dataId:s.data?.id,age:e-s.timestamp+"ms",timestamp:new Date(s.timestamp).toISOString()});return{writeCacheSize:this._writeCache.size,deleteCacheSize:this._deleteCache.size,writeCacheEntries:t,deleteCachePaths:Array.from(this._deleteCache)}}clearCaches(){const e=this._writeCache.size,t=this._deleteCache.size;this._writeCache.clear(),this._deleteCache.clear(),this._log("WARN","🧹 CACHES CLEARED",{writeCacheCleared:e,deleteCacheCleared:t})}async put(e,t,n,s={}){return this.write(e,t,n,s)}async get(e,t,n=null,s={}){return this.read(e,t,n,s)}async remove(e,t,n,s={}){return this.delete(e,t,n,s)}async putGlobal(e,t){return this.writeGlobal(e,t)}async getGlobal(e,t=null){return this.readGlobal(e,t)}async removeGlobal(e,t){return this.deleteGlobal(e,t)}async defineSchema(e,t,n=!1){return this.setSchema(e,t,n)}async fetchSchema(e){return this.getSchema(e)}async removeSchema(e){return this.clearSchema(e)}async store(e,t,n,s={}){return this.write(e,t,n,s)}async fetch(e,t,n=null,s={}){return this.read(e,t,n,s)}async save(e,t,n,s={}){return this.write(e,t,n,s)}async load(e,t,n=null,s={}){return this.read(e,t,n,s)}clearCache(e=null){if(e)for(const t of this._cache.keys())t.includes(e)&&this._cache.delete(t);else this._cache.clear()}},class extends sp{_requireAI(){if(!this._ai)throw new Error("AI services not initialized. Provide openaiKey in config.")}async summarize(e,t={}){return this._requireAI(),this._ai.llm.summarize(e,t)}async analyze(e,t,n={}){return this._requireAI(),this._ai.llm.analyze(e,t,n)}async extractKeywords(e,t={}){return this._requireAI(),this._ai.llm.extractKeywords(e,t)}async categorize(e,t,n={}){return this._requireAI(),this._ai.llm.categorize(e,t,n)}async translate(e,t,n={}){return this._requireAI(),this._ai.llm.translate(e,t,n)}async generateQuestions(e,t={}){return this._requireAI(),this._ai.llm.generateQuestions(e,t)}async extractToSchema(e,t,n={}){this._requireAI();const s=await this.getSchema(t);if(!s)throw new Error(`No schema found for lens: ${t}`);return this._ai.schemaExtractor.extractToSchema(e,s,n)}async jsonAdd(e,t,n={}){return this._requireAI(),this._ai.jsonOps.add(e,t,n)}async jsonSubtract(e,t,n={}){return this._requireAI(),this._ai.jsonOps.subtract(e,t,n)}async jsonUnion(e,t,n={}){return this._requireAI(),this._ai.jsonOps.union(e,t,n)}async jsonDifference(e,t,n={}){return this._requireAI(),this._ai.jsonOps.difference(e,t,n)}async jsonConcatenate(e,t,n={}){return this._requireAI(),this._ai.jsonOps.concatenate(e,t,n)}async embed(e){return this._requireAI(),this._ai.embeddings.embed(e)}async semanticSearch(e,t,n,s={}){return this._requireAI(),this._ai.embeddings.semanticSearch(e,t,n,s)}async storeWithEmbedding(e,t,n,s="description"){return this._requireAI(),this._ai.embeddings.storeWithEmbedding(e,t,n,s)}async askCouncil(e,t={}){return this._requireAI(),this._ai.council.ask(e,t)}async askCouncilCustom(e,t,n={}){return this._requireAI(),this._ai.council.askCustom(e,t,n)}async textToSpeech(e,t="nova",n={}){return this._requireAI(),this._ai.tts.speak(e,t,n)}async textToSpeechBase64(e,t="nova",n={}){return this._requireAI(),this._ai.tts.speakBase64(e,t,n)}async nlQuery(e,t=null,n=null,s={}){return this._requireAI(),this._ai.nlQuery.execute(e,t,n,s)}async parseNLQuery(e){return this._requireAI(),this._ai.nlQuery.parse(e)}async classifyToLens(e,t={}){return this._requireAI(),this._ai.classifier.classifyToLens(e,t)}async autoStore(e,t,n={}){return this._requireAI(),this._ai.classifier.autoStore(e,t,n)}registerLensForClassification(e,t,n=[]){this._requireAI(),this._ai.classifier.registerLens(e,t,n)}async analyzeRegion(e,t=null,n=null,s={}){return this._requireAI(),this._ai.spatial.analyzeRegion(e,t,n,s)}async compareRegions(e,t,n=null){return this._requireAI(),this._ai.spatial.compareRegions(e,t,n)}async spatialTrends(e,t,n=null){return this._requireAI(),this._ai.spatial.spatialTrends(e,t,n)}async smartUpcast(e,t,n={}){return this._requireAI(),this._ai.aggregation.smartUpcast(e,t,n)}async generateHolonSummary(e){return this._requireAI(),this._ai.aggregation.generateHolonSummary(e)}async suggestFederations(e,t={}){return this._requireAI(),this._ai.federationAdvisor.suggestFederations(e,t)}async analyzeFederationHealth(e){return this._requireAI(),this._ai.federationAdvisor.analyzeFederationHealth(e)}async optimizeFederation(e){return this._requireAI(),this._ai.federationAdvisor.optimizeFederation(e)}async discoverRelationships(e,t=null){return this._requireAI(),this._ai.relationships.discoverRelationships(e,t)}async findSimilar(e,t,n=null,s={}){return this._requireAI(),this._ai.relationships.findSimilar(e,t,n,s)}async buildRelationshipGraph(e,t){return this._requireAI(),this._ai.relationships.buildGraph(e,t)}async suggestConnections(e,t,n){return this._requireAI(),this._ai.relationships.suggestConnections(e,t,n)}async breakdown(e,t,n,s={}){return this._requireAI(),this._ai.taskBreakdown.breakdown(e,t,n,s)}async suggestBreakdownStrategy(e){return this._requireAI(),this._ai.taskBreakdown.suggestStrategy(e)}flattenBreakdown(e){return this._requireAI(),this._ai.taskBreakdown.flatten(e)}getBreakdownDependencyOrder(e){return this._requireAI(),this._ai.taskBreakdown.getDependencyOrder(e)}async getBreakdownProgress(e,t,n){return this._requireAI(),this._ai.taskBreakdown.getProgress(e,t,n)}async suggestH3Resolution(e,t={}){return this._requireAI(),this._ai.h3ai.suggestResolution(e,t)}async analyzeH3Distribution(e,t,n={}){return this._requireAI(),this._ai.h3ai.analyzeDistribution(e,t,n)}async findH3NeighborRelevance(e,t,n={}){return this._requireAI(),this._ai.h3ai.findNeighborRelevance(e,t,n)}async suggestGeographicScope(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.suggestGeographicScope(e,t,n,s)}async analyzeH3Coverage(e,t,n={}){return this._requireAI(),this._ai.h3ai.analyzeCoverage(e,t,n)}async crossH3ResolutionInsights(e,t,n={}){return this._requireAI(),this._ai.h3ai.crossResolutionInsights(e,t,n)}async suggestH3Migration(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.suggestMigration(e,t,n,s)}async generateH3Report(e,t={}){return this._requireAI(),this._ai.h3ai.generateGeographicReport(e,t)}async findH3Clusters(e,t,n={}){return this._requireAI(),this._ai.h3ai.findGeographicClusters(e,t,n)}async analyzeH3Impact(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.analyzeGeographicImpact(e,t,n,s)}})));var sp;exports.ABIs=hf,exports.AbiCoder=nd,exports.AuthorizationError=ep,exports.BaseContract=Wd,exports.Block=hd,exports.ChainManager=ef,exports.Classifier=Bo,exports.ConstructorFragment=Wu,exports.Contract=Kd,exports.ContractDeployer=yf,exports.ContractEventPayload=Sd,exports.ContractOperations=mf,exports.ContractQueries=class{constructor(e){this.provider=e}getContract(e,t){const n=Vd[t];if(!n)throw new Error(`Unknown contract flavor: ${t}`);return new Kd(e,n,this.provider)}async detectFlavor(e){const t=new Kd(e,["function flavor() view returns (string)","function version() view returns (string)"],this.provider);try{return await t.flavor()}catch{return"Unknown"}}async getContractInfo(e,t){const n=this.getContract(e,t),[s,r,a,i,o]=await Promise.all([n.name().catch(()=>""),n.flavor().catch(()=>t),n.version().catch(()=>""),n.creator().catch(()=>Al),n.getSize().catch(()=>0n)]);return{address:e,name:s,flavor:r,version:a,creator:i,memberCount:Number(o)}}async getMembers(e,t){const n=this.getContract(e,t),s=await n.getSize(),r=[];for(let a=0;a<s;a++){const e=await n.userIds(a);r.push(e)}return r}async getUserEthBalance(e,t,n){const s=this.getContract(e,t),r=await s.etherBalance(n);return{wei:r.toString(),eth:Zd(r)}}async getUserTokenBalance(e,t,n,s){const r=this.getContract(e,t),a=await r.tokenBalance(n,s);return{wei:a.toString(),formatted:Zd(a)}}async getTotalDeposited(e,t,n){const s=this.getContract(e,t),r=n||Al,a=await s.totalDeposited(r);return{wei:a.toString(),formatted:Zd(a)}}async hasClaimed(e,t,n){return this.getContract(e,t).hasClaimed(n)}async getSplitterSplit(e){const t=this.getContract(e,"Splitter"),[n,s]=await Promise.all([t.internalContractSplitPercentage(),t.externalContractSplitPercentage()]);return{internalPercentage:Number(n),externalPercentage:Number(s),internalPercent:Number(n)/100,externalPercent:Number(s)/100}}async getSplitterChildren(e){const t=this.getContract(e,"Splitter"),[n,s]=await t.getContractAddresses(),r=[];for(let a=0;a<n.length;a++)r.push({key:n[a],address:s[a]});return r}async getSplitterUserPercentage(e,t){const n=this.getContract(e,"Splitter"),s=await n.percentages(t);return{basisPoints:Number(s),percent:Number(s)/100}}async getSplitterAllPercentages(e){const t=await this.getMembers(e,"Splitter"),n=this.getContract(e,"Splitter"),s=[];for(const r of t){const e=await n.percentages(r);s.push({userId:r,basisPoints:Number(e),percent:Number(e)/100})}return s}async getZonedConfig(e){const t=this.getContract(e,"Zoned"),[n,s,r,a]=await Promise.all([t.nzones(),t.a(),t.b(),t.c()]);return{numberOfZones:Number(n),rewardFunction:{a:Number(s),b:Number(r),c:Number(a)}}}async getUserZone(e,t){const n=this.getContract(e,"Zoned"),s=await n.zone(t);return Number(s)}async getZoneMembers(e,t){return this.getContract(e,"Zoned").getZoneMembers(t)}async getZonedBreakdown(e){const t=await this.getZonedConfig(e),n=this.getContract(e,"Zoned"),s=[];for(let r=1;r<=t.numberOfZones;r++){const e=await n.getZoneMembers(r);s.push({zone:r,members:e,memberCount:e.length})}return{config:t,zones:s,rewardWeights:(await n.calculateRewards()).map((e,t)=>({zone:t+1,weight:Number(e)}))}}async getManagedAppreciation(e,t){const n=this.getContract(e,"Managed"),s=await n.appreciation(t),r=await n.totalappreciation();return{userAppreciation:Number(s),totalAppreciation:Number(r),sharePercent:Number(r)>0?Number(s)/Number(r)*100:0}}async getManagedAllAppreciation(e){const t=await this.getMembers(e,"Managed"),n=this.getContract(e,"Managed"),s=await n.totalappreciation(),r=await n.maxAppreciation().catch(()=>0n),a=[];for(const i of t){const e=await n.appreciation(i);a.push({userId:i,appreciation:Number(e),sharePercent:Number(s)>0?Number(e)/Number(s)*100:0})}return{members:a,totalAppreciation:Number(s),maxAppreciation:Number(r)}}async getAppreciativePeer(e,t){const n=this.getContract(e,"Appreciative"),[s,r,a]=await Promise.all([n.appreciation(t),n.remainingappreciation(t),n.totalappreciation()]);return{received:Number(s),remainingToGive:Number(r),totalPool:Number(a),sharePercent:Number(a)>0?Number(s)/Number(a)*100:0}}async getAppreciativeAll(e){const t=await this.getMembers(e,"Appreciative"),n=this.getContract(e,"Appreciative"),s=await n.totalappreciation(),r=[];for(const a of t){const[e,t]=await Promise.all([n.appreciation(a),n.remainingappreciation(a)]);r.push({userId:a,received:Number(e),remainingToGive:Number(t),sharePercent:Number(s)>0?Number(e)/Number(s)*100:0})}return{members:r,totalAppreciation:Number(s)}}async getBundleConfig(e){const t=this.getContract(e,"Bundle"),[n,s,r,a,i]=await Promise.all([t.steepness(),t.nzones(),t.interiorPercentage(),t.exteriorPercentage(),t.electionActive()]);return{steepness:Number(n),numberOfZones:Number(s),interiorPercentage:Number(r)/100,exteriorPercentage:Number(a)/100,electionActive:i}}async getBundleSplit(e){const t=this.getContract(e,"Bundle"),[n,s]=await Promise.all([t.interiorPercentage(),t.exteriorPercentage()]);return{interiorBasisPoints:Number(n),exteriorBasisPoints:Number(s),interiorPercent:Number(n)/100,exteriorPercent:Number(s)/100}}async getBundleZoneWeights(e){const t=this.getContract(e,"Bundle");return(await t.getZoneWeights()).map((e,t)=>({zone:t+1,weight:Number(e)}))}async getBundleUserInfo(e,t){const n=this.getContract(e,"Bundle"),[s,r,a,i,o]=await Promise.all([n.zone(t),n.interiorShare(t),n.isInteriorMember(t),n.isExteriorMember(t),n.isBundleMember(t)]);return{zone:Number(s),interiorShareBasisPoints:Number(r),interiorSharePercent:Number(r)/100,isInteriorMember:a,isExteriorMember:i,isMember:o}}async getBundleInteriorMembers(e){return this.getContract(e,"Bundle").getInteriorMembers()}async getBundleZoneBreakdown(e){const t=await this.getBundleConfig(e),n=this.getContract(e,"Bundle"),s=[];for(let r=1;r<=t.numberOfZones;r++){const e=await n.getZoneMembers(r);s.push({zone:r,members:e,memberCount:e.length})}return{config:t,zones:s,zoneWeights:await this.getBundleZoneWeights(e)}}async getBundleElection(e){const t=this.getContract(e,"Bundle"),[n,s]=await Promise.all([t.electionActive(),t.getCandidates()]);if(!n)return{active:!1,candidates:[]};const r=[];for(const a of s){const e=await t.votes(a);r.push({userId:a,votes:Number(e)})}return{active:!0,candidates:r.sort((e,t)=>t.votes-e.votes)}}async getFullSnapshot(e){const t=await this.detectFlavor(e),n=await this.getContractInfo(e,t),s=await this.getMembers(e,t),r={...n,members:s,memberDetails:[]};for(const a of s){const n={userId:a,ethBalance:await this.getUserEthBalance(e,t,a),hasClaimed:await this.hasClaimed(e,t,a)};if("Splitter"===t){const t=await this.getSplitterUserPercentage(e,a);n.percentage=t}else"Zoned"===t?n.zone=await this.getUserZone(e,a):"Managed"===t?n.appreciation=await this.getManagedAppreciation(e,a):"Appreciative"===t?n.appreciation=await this.getAppreciativePeer(e,a):"Bundle"===t&&(n.bundleInfo=await this.getBundleUserInfo(e,a));r.memberDetails.push(n)}return"Splitter"===t?(r.split=await this.getSplitterSplit(e),r.children=await this.getSplitterChildren(e)):"Zoned"===t?r.zoneConfig=await this.getZonedBreakdown(e):"Managed"===t?r.appreciationSummary=await this.getManagedAllAppreciation(e):"Appreciative"===t?r.appreciationSummary=await this.getAppreciativeAll(e):"Bundle"===t&&(r.bundleConfig=await this.getBundleConfig(e),r.bundleSplit=await this.getBundleSplit(e),r.bundleZones=await this.getBundleZoneBreakdown(e),r.election=await this.getBundleElection(e)),r}},exports.ContractTransactionReceipt=Td,exports.ContractTransactionResponse=xd,exports.ContractUnknownEventPayload=Ad,exports.Council=Po,exports.Embeddings=Ro,exports.ErrorDescription=ad,exports.ErrorFragment=Gu,exports.EventFragment=zu,exports.EventListener=class{constructor(e){this.chainManager=e,this.listeners=new Map,this.eventHistory=[],this.sankeyNodes=new Map,this.sankeyLinks=[]}async listenToContract(e,t,n){const s=["FundsReceived","FundsCascaded","FundsAllocated","FundsClaimed","FundsTransferred","DistributionCompleted","MemberAdded","WeightChanged","ZoneAssigned","AppreciationGiven"];for(const a of s)try{const s=n.filters[a]?.();s&&n.on(a,(...n)=>{this._handleEvent(a,n,e,t)})}catch(r){}this.listeners.set(e,{contract:n,holonId:t})}stopListening(e){const t=this.listeners.get(e);t&&(t.contract.removeAllListeners(),this.listeners.delete(e))}stopAll(){for(const[e,t]of this.listeners)t.contract.removeAllListeners();this.listeners.clear()}_handleEvent(e,t,n,s){const r=t[t.length-1],a={type:e,contractAddress:n,holonId:s,timestamp:Date.now(),blockNumber:r?.blockNumber,transactionHash:r?.transactionHash,data:this._parseEventData(e,t)};this.eventHistory.push(a),this._updateSankeyData(a),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("sankey-event",{detail:a}))}_parseEventData(e,t){switch(e){case"FundsReceived":return{contractAddress:t[0],sender:t[1],tokenAddress:t[2],amount:t[3]?.toString()};case"FundsCascaded":return{fromContract:t[0],toContract:t[1],fromHolonId:t[2],toHolonId:t[3],tokenAddress:t[4],amount:t[5]?.toString(),splitType:t[6]};case"FundsAllocated":return{contractAddress:t[0],holonId:t[1],userId:t[2],tokenAddress:t[3],amount:t[4]?.toString(),distributionType:t[5]};case"FundsClaimed":return{contractAddress:t[0],holonId:t[1],userId:t[2],beneficiary:t[3],tokenAddress:t[4],amount:t[5]?.toString()};case"FundsTransferred":return{contractAddress:t[0],holonId:t[1],userId:t[2],recipient:t[3],tokenAddress:t[4],amount:t[5]?.toString()};case"DistributionCompleted":return{contractAddress:t[0],holonId:t[1],tokenAddress:t[2],totalAmount:t[3]?.toString(),recipientCount:Number(t[4]),cascadeCount:Number(t[5])};case"MemberAdded":return{contractAddress:t[0],holonId:t[1],userId:t[2],addedBy:t[3]};case"WeightChanged":return{contractAddress:t[0],holonId:t[1],userId:t[2],oldWeight:t[3]?.toString(),newWeight:t[4]?.toString()};case"ZoneAssigned":return{contractAddress:t[0],holonId:t[1],userId:t[2],oldZone:t[3]?.toString(),newZone:t[4]?.toString()};case"AppreciationGiven":return{contractAddress:t[0],holonId:t[1],fromUserId:t[2],toUserId:t[3],amount:t[4]?.toString()};default:return{raw:t.slice(0,-1)}}}_updateSankeyData(e){const{type:t,data:n}=e;switch(t){case"FundsReceived":this._ensureNode(n.sender,"external","External"),this._ensureNode(n.contractAddress,"contract",e.holonId),this.sankeyLinks.push({source:n.sender,target:n.contractAddress,value:BigInt(n.amount),token:n.tokenAddress,type:"external_inflow"});break;case"FundsCascaded":this._ensureNode(n.fromContract,"contract",n.fromHolonId),this._ensureNode(n.toContract,"contract",n.toHolonId),this.sankeyLinks.push({source:n.fromContract,target:n.toContract,value:BigInt(n.amount),token:n.tokenAddress,type:"cascade",splitType:n.splitType});break;case"FundsAllocated":this._ensureNode(n.contractAddress,"contract",n.holonId),this._ensureNode(n.userId,"user",n.userId),this.sankeyLinks.push({source:n.contractAddress,target:n.userId,value:BigInt(n.amount),token:n.tokenAddress,type:"allocation",distributionType:n.distributionType});break;case"FundsClaimed":case"FundsTransferred":this._ensureNode(n.userId,"user",n.userId),this._ensureNode(n.beneficiary||n.recipient,"wallet",(n.beneficiary||n.recipient).slice(0,8)+"..."),this.sankeyLinks.push({source:n.userId,target:n.beneficiary||n.recipient,value:BigInt(n.amount),token:n.tokenAddress,type:"FundsClaimed"===t?"claim":"transfer"});break;case"MemberAdded":this._ensureNode(n.userId,"user",n.userId)}}_ensureNode(e,t,n){this.sankeyNodes.has(e)||this.sankeyNodes.set(e,{id:e,type:t,label:n})}getSankeyData(e={}){const{tokenAddress:t,fromBlock:n,toBlock:s,minValue:r}=e;let a=[...this.sankeyLinks];if(t&&(a=a.filter(e=>e.token===t)),r){const e=BigInt(r);a=a.filter(t=>t.value>=e)}const i=new Set;a.forEach(e=>{i.add(e.source),i.add(e.target)});const o=[...i].map(e=>{const t=this.sankeyNodes.get(e)||{id:e,type:"unknown",label:e};return{id:t.id,name:t.label,type:t.type}}),f=new Map;o.forEach((e,t)=>f.set(e.id,t));return{nodes:o,links:a.map(e=>({source:f.get(e.source),target:f.get(e.target),value:Number(e.value)/1e18,type:e.type,splitType:e.splitType,distributionType:e.distributionType,token:e.token}))}}getFlowSummary(){const e={totalInflow:0n,totalOutflow:0n,byDistributionType:{appreciation:0n,equal:0n,zone:0n,percentage:0n,peer_appreciation:0n}};for(const t of this.sankeyLinks)"external_inflow"===t.type&&(e.totalInflow+=t.value),"claim"!==t.type&&"transfer"!==t.type||(e.totalOutflow+=t.value),t.distributionType&&void 0!==e.byDistributionType[t.distributionType]&&(e.byDistributionType[t.distributionType]+=t.value);return{totalInflow:e.totalInflow.toString(),totalOutflow:e.totalOutflow.toString(),totalInflowEth:Number(e.totalInflow)/1e18,totalOutflowEth:Number(e.totalOutflow)/1e18,byDistributionType:Object.fromEntries(Object.entries(e.byDistributionType).map(([e,t])=>[e,t.toString()]))}}async queryPastEvents(e,t,n={}){const{fromBlock:s=0,toBlock:r="latest"}=n;try{const n=e.filters[t]?.();if(!n)return[];return(await e.queryFilter(n,s,r)).map(e=>({type:t,contractAddress:e.address,blockNumber:e.blockNumber,transactionHash:e.transactionHash,data:this._parseEventData(t,e.args)}))}catch(a){return console.error(`Error querying ${t}:`,a),[]}}async buildFromHistory(e,t,n={}){const s=["FundsReceived","FundsCascaded","FundsAllocated","FundsClaimed","FundsTransferred","MemberAdded"];for(const r of s){const s=await this.queryPastEvents(e,r,n);for(const e of s)e.holonId=t,this.eventHistory.push(e),this._updateSankeyData(e)}return this.getSankeyData()}clear(){this.eventHistory=[],this.sankeyNodes.clear(),this.sankeyLinks=[]}export(){return{events:this.eventHistory,nodes:Object.fromEntries(this.sankeyNodes),links:this.sankeyLinks.map(e=>({...e,value:e.value.toString()}))}}import(e){this.eventHistory=e.events||[],this.sankeyNodes=new Map(Object.entries(e.nodes||{})),this.sankeyLinks=(e.links||[]).map(e=>({...e,value:BigInt(e.value)}))}},exports.EventLog=vd,exports.EventPayload=rc,exports.FallbackFragment=Ku,exports.FederationAdvisor=Lo,exports.FeeData=class{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(e,t,n){_f(this,{gasPrice:ud(e),maxFeePerGas:ud(t),maxPriorityFeePerGas:ud(n)})}toJSON(){const{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:dd(e),maxFeePerGas:dd(t),maxPriorityFeePerGas:dd(n)}}},exports.FixedNumber=wc,exports.Fragment=Lu,exports.FunctionFragment=Vu,exports.H3AI=Go,exports.Hash=tt,exports.Hash$1=Wc,exports.HoloSphere=np,exports.HolonContracts=gf,exports.Indexed=id,exports.Interface=cd,exports.JSONOps=Oo,exports.LLMService=Io,exports.Log=yd,exports.LogDescription=sd,exports.MODELS=Do,exports.NETWORKS=zo,exports.NLQuery=Ho,exports.NamedFragment=qu,exports.ParamType=Uu,exports.PersistentStorage=class{async init(e){throw new Error("init() must be implemented by subclass")}async put(e,t){throw new Error("put() must be implemented by subclass")}async get(e){throw new Error("get() must be implemented by subclass")}async getAll(e){throw new Error("getAll() must be implemented by subclass")}async delete(e){throw new Error("delete() must be implemented by subclass")}async clear(){throw new Error("clear() must be implemented by subclass")}async close(){throw new Error("close() must be implemented by subclass")}},exports.RelationshipDiscovery=qo,exports.Result=$c,exports.SANKEY_EVENTS={FundsReceived:"FundsReceived",FundsCascaded:"FundsCascaded",FundsAllocated:"FundsAllocated",FundsClaimed:"FundsClaimed",FundsTransferred:"FundsTransferred",DistributionCompleted:"DistributionCompleted",ChildContractCreated:"ChildContractCreated",HolonCreated:"HolonCreated",MemberAdded:"MemberAdded",MemberRemoved:"MemberRemoved",WeightChanged:"WeightChanged",ZoneAssigned:"ZoneAssigned",AppreciationGiven:"AppreciationGiven",SplitConfigured:"SplitConfigured",ContractSplitConfigured:"ContractSplitConfigured"},exports.SchemaExtractor=Co,exports.SmartAggregation=Uo,exports.SpatialAnalysis=jo,exports.StructFragment=Zu,exports.TTS=Fo,exports.TaskBreakdown=Jo,exports.TransactionDescription=rd,exports.TransactionReceipt=md,exports.TransactionResponse=gd,exports.Typed=Bl,exports.UndecodedEventLog=_d,exports.Utf8ErrorFuncs=ic,exports.VOICES=Mo,exports.ValidationError=Re,exports.ZeroAddress=Al,exports.abytes=Be,exports.accessListify=ru,exports.aexists=je,exports.ahash=function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");He(e.outputLen),He(e.blockLen)},exports.anumber=He,exports.assert=kf,exports.assertArgument=Ef,exports.assertArgumentCount=Nf,exports.assertNormalize=Cf,exports.assertPrivate=Of,exports.asyncLoop=async function(e,t,n){let s=Date.now();for(let r=0;r<e;r++){n(r);const e=Date.now()-s;e>=0&&e<t||(await Gc(),s+=e)}},exports.bytes=Bc,exports.bytesToHex=ze,exports.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==Kc.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)},exports.checkResultErrors=function(e){const t=[],n=function(e,s){if(Array.isArray(s))for(let a in s){const i=e.slice();i.push(a);try{n(i,s[a])}catch(r){t.push({path:i,error:r})}}};return n([],e),t},exports.clean=Ue,exports.concat=Bf,exports.concatBytes=function(...e){let t=0;for(let s=0;s<e.length;s++){const n=e[s];Be(n),t+=n.length}const n=new Uint8Array(t);for(let s=0,r=0;s<e.length;s++){const t=e[s];n.set(t,r),r+=t.length}return n},exports.concatBytes$1=function(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let n=0;return e.forEach(e=>{if(!qc(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length}),t},exports.copyOverrides=Md,exports.copyRequest=pd,exports.createAIServices=function(e,t=null,n={},s=null){const r=new Io(e,n.llm),a=s,i=new Ro(a,t);return{llm:r,openai:a,embeddings:i,schemaExtractor:new Co(r),jsonOps:new Oo(r),council:new Po(r),tts:new Fo(a),nlQuery:new Ho(r,t),classifier:new Bo(r,t),spatial:new jo(r,t),aggregation:new Uo(r,t),federationAdvisor:new Lo(r,t,i),relationships:new qo(r,t,i),taskBreakdown:new Jo(r,t),h3ai:new Go(r,t)}},exports.createHologram=It,exports.createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),exports.dataLength=function(e){return Mf(e,!0)?(e.length-2)/2:$f(e).length},exports.dataSlice=jf,exports.defineProperties=_f,exports.exists=jc,exports.formatEther=xc,exports.formatUnits=_c,exports.fromTwos=Wf,exports.getAddress=Ol,exports.getAddressUrl=Xo,exports.getBigInt=Zf,exports.getBytes=$f,exports.getBytesCopy=Pf,exports.getIcapAddress=function(e){let t=BigInt(Ol(e)).toString(36).toUpperCase();for(;t.length<30;)t="0"+t;return"XE"+Il("XE00"+t)+t},exports.getNetwork=Wo,exports.getNetworksByType=Ko,exports.getNumber=ec,exports.getTxUrl=Yo,exports.getUint=Yf,exports.h3Operations=ie,exports.handshake=fn,exports.hash=function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Hc(e.outputLen),Hc(e.blockLen)},exports.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Je)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(n);for(let r=0,a=0;r<n;r++,a+=2){const t=Qe(e.charCodeAt(a)),n=Qe(e.charCodeAt(a+1));if(void 0===t||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[r]=16*t+n}return s},exports.hexlify=Hf,exports.hologram=Gt,exports.id=au,exports.isAddress=function(e){try{return Ol(e),!0}catch(t){}return!1},exports.isAddressable=Rl,exports.isBytes=Fe,exports.isBytesLike=Df,exports.isCallException=Af,exports.isError=xf,exports.isHexString=Mf,exports.isNetworkSupported=Zo,exports.keccak256=xl,exports.listNetworks=Vo,exports.makeError=Sf,exports.manager=yn,exports.mask=Vf,exports.matchScope=gt,exports.networks=Qo,exports.nostrUtils=nn,exports.number=Hc,exports.output=Uc,exports.parseEther=function(e){return Tc(e,18)},exports.parseUnits=Tc,exports.randomBytes=function(e=32){if(De&&"function"==typeof De.getRandomValues)return De.getRandomValues(new Uint8Array(e));if(De&&"function"==typeof De.randomBytes)return Uint8Array.from(De.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")},exports.randomBytes$1=function(e=32){if(Lc&&"function"==typeof Lc.getRandomValues)return Lc.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")},exports.resolveAddress=Pl,exports.resolveArgs=Dd,exports.resolveProperties=vf,exports.rotr=(e,t)=>e<<32-t|e>>>t,exports.secp256k1=_t,exports.sha256=lt,exports.socialProtocols=dn,exports.stripZerosLeft=function(e){let t=Hf(e).substring(2);for(;t.startsWith("00");)t=t.substring(2);return"0x"+t},exports.toBeArray=sc,exports.toBeHex=nc,exports.toBigInt=Qf,exports.toBytes=et,exports.toBytes$1=zc,exports.toNumber=tc,exports.toQuantity=function(e){let t=Hf(Df(e)?e:sc(e)).substring(2);for(;t.startsWith("0");)t=t.substring(1);return""===t&&(t="0"),"0x"+t},exports.toTwos=Kf,exports.toUtf8Bytes=fc,exports.toUtf8CodePoints=function(e,t){return oc(fc(e,t))},exports.toUtf8String=cc,exports.u32=Jc,exports.u64=rl,exports.unifiedStorage=Ee,exports.upcast=gn,exports.validator=Me,exports.version=bf,exports.wrapConstructor=Vc,exports.zeroPadBytes=qf,exports.zeroPadValue=Lf;
|
|
18
|
-
//# sourceMappingURL=index-Dc6Z8Aob.cjs.map
|