holosphere 2.0.0-alpha2 → 2.0.0-alpha4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/2019-D2OG2idw.js +6680 -0
  2. package/dist/2019-D2OG2idw.js.map +1 -0
  3. package/dist/2019-EION3wKo.cjs +8 -0
  4. package/dist/2019-EION3wKo.cjs.map +1 -0
  5. package/dist/_commonjsHelpers-C37NGDzP.cjs +2 -0
  6. package/dist/_commonjsHelpers-C37NGDzP.cjs.map +1 -0
  7. package/dist/_commonjsHelpers-CUmg6egw.js +7 -0
  8. package/dist/_commonjsHelpers-CUmg6egw.js.map +1 -0
  9. package/dist/browser-BSniCNqO.js +3058 -0
  10. package/dist/browser-BSniCNqO.js.map +1 -0
  11. package/dist/browser-Cq59Ij19.cjs +2 -0
  12. package/dist/browser-Cq59Ij19.cjs.map +1 -0
  13. package/dist/cjs/holosphere.cjs +1 -1
  14. package/dist/esm/holosphere.js +50 -53
  15. package/dist/index-BB_vVJgv.cjs +5 -0
  16. package/dist/index-BB_vVJgv.cjs.map +1 -0
  17. package/dist/index-CBitK71M.cjs +12 -0
  18. package/dist/index-CBitK71M.cjs.map +1 -0
  19. package/dist/index-CV0eOogK.js +37423 -0
  20. package/dist/index-CV0eOogK.js.map +1 -0
  21. package/dist/index-Cz-PLCUR.js +15104 -0
  22. package/dist/index-Cz-PLCUR.js.map +1 -0
  23. package/dist/indexeddb-storage-CRsZyB2f.cjs +2 -0
  24. package/dist/indexeddb-storage-CRsZyB2f.cjs.map +1 -0
  25. package/dist/{indexeddb-storage-CMW4qRQS.js → indexeddb-storage-DZaGlY_a.js} +49 -13
  26. package/dist/indexeddb-storage-DZaGlY_a.js.map +1 -0
  27. package/dist/{memory-storage-DQzcAZlf.js → memory-storage-BkUi6sZG.js} +6 -2
  28. package/dist/memory-storage-BkUi6sZG.js.map +1 -0
  29. package/dist/{memory-storage-DmePEP2q.cjs → memory-storage-C0DuUsdY.cjs} +2 -2
  30. package/dist/memory-storage-C0DuUsdY.cjs.map +1 -0
  31. package/dist/secp256k1-0kPdAVkK.cjs +12 -0
  32. package/dist/secp256k1-0kPdAVkK.cjs.map +1 -0
  33. package/dist/{secp256k1-vOXp40Fx.js → secp256k1-DN4FVXcv.js} +2 -393
  34. package/dist/secp256k1-DN4FVXcv.js.map +1 -0
  35. package/docs/CONTRACTS.md +797 -0
  36. package/examples/demo.html +47 -0
  37. package/package.json +10 -5
  38. package/src/contracts/abis/Appreciative.json +1280 -0
  39. package/src/contracts/abis/AppreciativeFactory.json +101 -0
  40. package/src/contracts/abis/Bundle.json +1435 -0
  41. package/src/contracts/abis/BundleFactory.json +106 -0
  42. package/src/contracts/abis/Holon.json +881 -0
  43. package/src/contracts/abis/Holons.json +330 -0
  44. package/src/contracts/abis/Managed.json +1262 -0
  45. package/src/contracts/abis/ManagedFactory.json +149 -0
  46. package/src/contracts/abis/Membrane.json +261 -0
  47. package/src/contracts/abis/Splitter.json +1624 -0
  48. package/src/contracts/abis/SplitterFactory.json +220 -0
  49. package/src/contracts/abis/TestToken.json +321 -0
  50. package/src/contracts/abis/Zoned.json +1461 -0
  51. package/src/contracts/abis/ZonedFactory.json +154 -0
  52. package/src/contracts/chain-manager.js +375 -0
  53. package/src/contracts/deployer.js +443 -0
  54. package/src/contracts/event-listener.js +507 -0
  55. package/src/contracts/holon-contracts.js +344 -0
  56. package/src/contracts/index.js +83 -0
  57. package/src/contracts/networks.js +224 -0
  58. package/src/contracts/operations.js +670 -0
  59. package/src/contracts/queries.js +589 -0
  60. package/src/core/holosphere.js +453 -1
  61. package/src/crypto/nostr-utils.js +263 -0
  62. package/src/federation/handshake.js +455 -0
  63. package/src/federation/hologram.js +1 -1
  64. package/src/hierarchical/upcast.js +6 -5
  65. package/src/index.js +463 -1939
  66. package/src/lib/ai-methods.js +308 -0
  67. package/src/lib/contract-methods.js +293 -0
  68. package/src/lib/errors.js +23 -0
  69. package/src/lib/federation-methods.js +238 -0
  70. package/src/lib/index.js +26 -0
  71. package/src/spatial/h3-operations.js +2 -2
  72. package/src/storage/backends/gundb-backend.js +377 -46
  73. package/src/storage/global-tables.js +28 -1
  74. package/src/storage/gun-auth.js +303 -0
  75. package/src/storage/gun-federation.js +776 -0
  76. package/src/storage/gun-references.js +198 -0
  77. package/src/storage/gun-schema.js +291 -0
  78. package/src/storage/gun-wrapper.js +347 -31
  79. package/src/storage/indexeddb-storage.js +49 -11
  80. package/src/storage/memory-storage.js +5 -0
  81. package/src/storage/nostr-async.js +45 -23
  82. package/src/storage/nostr-client.js +11 -5
  83. package/src/storage/persistent-storage.js +6 -1
  84. package/src/storage/unified-storage.js +119 -0
  85. package/src/subscriptions/manager.js +1 -1
  86. package/types/index.d.ts +133 -0
  87. package/dist/index-CDfIuXew.js +0 -15974
  88. package/dist/index-CDfIuXew.js.map +0 -1
  89. package/dist/index-ifOgtDvd.cjs +0 -3
  90. package/dist/index-ifOgtDvd.cjs.map +0 -1
  91. package/dist/indexeddb-storage-CMW4qRQS.js.map +0 -1
  92. package/dist/indexeddb-storage-DLZOgetM.cjs +0 -2
  93. package/dist/indexeddb-storage-DLZOgetM.cjs.map +0 -1
  94. package/dist/memory-storage-DQzcAZlf.js.map +0 -1
  95. package/dist/memory-storage-DmePEP2q.cjs.map +0 -1
  96. package/dist/secp256k1-CP0ZkpAx.cjs +0 -13
  97. package/dist/secp256k1-CP0ZkpAx.cjs.map +0 -1
  98. package/dist/secp256k1-vOXp40Fx.js.map +0 -1
@@ -0,0 +1,5 @@
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 r(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const s=r(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:[]},r=`${this.queuePrefix}${e.id}`;return await this.storage.put(r,n),n}async markSent(e,t){const n=`${this.queuePrefix}${e}`,r=await this.storage.get(n);r&&(t.length>0?await this.storage.delete(n):await this._scheduleRetry(n,r))}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 r=0;for(const s of t)s&&"failed"===s.status&&n-s.failedAt>e&&(await this.storage.delete(`${this.queuePrefix}${s.id}`),r++);return r}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 r of n)try{(await this.client._attemptDelivery(r.event,r.relays)).successful.length>0?e.succeeded++:e.failed++}catch(t){console.warn(`[sync] Retry failed for ${r.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;class l{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 Map,this.persistentStorage=null,this._initReady=this._initialize()}async _initialize(){await(void 0!==globalThis.WebSocket?Promise.resolve():(o||(o=(async()=>{try{const{default:e}=await import("ws");globalThis.WebSocket=e}catch(e){}})()),o)),this.relays.length>0?this.pool=new e.SimplePool({enableReconnect:!1!==this.config.enableReconnect,enablePing:!1!==this.config.enablePing}):this.pool={publish:(e,t)=>[Promise.resolve()],querySync:(e,t,n)=>Promise.resolve([]),subscribeMany:(e,t,n)=>({close:()=>{}}),close:e=>{}},await this._initPersistentStorage()}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-CRsZyB2f.cjs")),n=new t;return await n.init(e),n}{const{MemoryStorage:t}=await Promise.resolve().then(()=>require("./memory-storage-C0DuUsdY.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}}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(t,n={}){await this._initReady;const r=n.waitForRelays||!1,s=e.finalizeEvent(t,this.privateKey);if(await this._cacheEvent(s),this.outboxQueue&&await this.outboxQueue.enqueue(s,this.relays),r){return{event:s,results:(await this._attemptDelivery(s,this.relays)).results,queued:!!this.outboxQueue}}return this._attemptDelivery(s,this.relays).catch(()=>{}),{event:s,results:[],queued:!!this.outboxQueue}}async _attemptDelivery(e,t){const n=await Promise.allSettled(this.pool.publish(t,e)),r=[],s=[],a=[];if(n.forEach((e,n)=>{a.push({relay:t[n],status:e.status,value:e.value,reason:e.reason}),"fulfilled"===e.status?r.push(t[n]):s.push(t[n])}),this.outboxQueue&&await this.outboxQueue.markSent(e.id,r),s.length>0&&0===r.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:r,failed:s,results:a}}async query(e,t={}){await this._initReady;const n=void 0!==t.timeout?t.timeout:3e4,r=!1!==t.localFirst;if(0===this.relays.length){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 s=JSON.stringify(e),a=this._eventCache.get(s);return a&&Date.now()-a.timestamp<5e3?a.events:r&&a?(this._refreshCacheInBackground(e,s,n),a.events):this._queryRelaysAndCache(e,s,n)}async _queryRelaysAndCache(e,t,n){let r=await this.pool.querySync(this.relays,e,{timeout:n});if(e.authors&&e.authors.length>0&&(r=r.filter(t=>e.authors.includes(t.pubkey))),this._eventCache.set(t,{events:r,timestamp:Date.now()}),this._eventCache.size>100){const e=this._eventCache.keys().next().value;this._eventCache.delete(e)}return r}_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 r={kinds:[t],authors:n.authors||[this.publicKey],"#d":[e],limit:1},s=n.timeout||3e4,a=(await this.pool.querySync(this.relays,r,{timeout:s})).filter(e=>(n.authors||[this.publicKey]).includes(e.pubkey));a.length>0&&await this._cacheEvent(a[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 r={kinds:[t],authors:n.authors||[this.publicKey],limit:n.limit||1e3},s=n.timeout||3e4;let a=await this.pool.querySync(this.relays,r,{timeout:s});a=a.filter(e=>(n.authors||[this.publicKey]).includes(e.pubkey)),a=a.filter(t=>{const n=t.tags.find(e=>"d"===e[0]);return n&&n[1]&&n[1].startsWith(e)});for(const i of a)await this._cacheEvent(i)}async queryHybrid(e,t={}){await this._initReady;const n=void 0!==t.timeout?t.timeout:3e4,r=this._getMatchingCachedEvents(e);if(0===this.relays.length)return r;let s=[];try{s=await this.pool.querySync(this.relays,e,{timeout:n}),e.authors&&e.authors.length>0&&(s=s.filter(t=>e.authors.includes(t.pubkey)))}catch(l){console.warn("Relay query failed, using local cache only:",l.message)}const a=new Map;for(const c of r){const e=this._getEventKey(c);a.set(e,c)}for(const c of s){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 r=`sub-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;if(0===this.relays.length){const s=this._getMatchingCachedEvents(e),a={filter:e,onEvent:t,active:!0};return this._subscriptions.set(r,a),setTimeout(()=>{a.active&&(s.forEach(e=>t(e)),n.onEOSE&&n.onEOSE())},10),{id:r,unsubscribe:()=>{a.active=!1,this._subscriptions.delete(r),a.onEvent=()=>{}}}}const s=this.pool.subscribeMany(this.relays,[e],{onevent:n=>{e.authors&&e.authors.length>0&&!e.authors.includes(n.pubkey)||(this._cacheEvent(n),t(n))},oneose:()=>{n.onEOSE&&n.onEOSE()}});return this._subscriptions.set(r,s),{id:r,unsubscribe:()=>{s.close&&s.close(),this._subscriptions.delete(r)}}}_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]}`,r=this._eventCache.get(n);(!r||!r.events[0]||e.created_at>r.events[0].created_at||e.created_at===r.events[0].created_at&&e.id!==r.events[0].id)&&(this._eventCache.set(n,{events:[e],timestamp:Date.now()}),r&&r.events[0]&&this._eventCache.delete(r.events[0].id),this._invalidateQueryCachesForEvent(e))}}}_invalidateQueryCachesForEvent(e){const t=[];for(const[n,r]of this._eventCache.entries())if(n.startsWith("{"))try{const r=JSON.parse(n);this._eventMatchesFilter(e,r)&&t.push(n)}catch{}for(const n of t)this._eventCache.delete(n)}async _cacheEvent(e){if(this._cacheEventSync(e),this.persistentStorage)try{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])}await this.persistentStorage.put(t,e)}catch(t){console.warn("Failed to persist event:",t)}if(0===this.relays.length)for(const n of this._subscriptions.values())n.active&&this._eventMatchesFilter(e,n.filter)&&setTimeout(()=>{n.active&&n.onEvent(e)},10)}_getMatchingCachedEvents(e){const t=[],n=new Map;for(const r of this._eventCache.values())for(const s of r.events||[])if(this._eventMatchesFilter(s,e)){if(s.kind>=3e4&&s.kind<4e4){const e=s.tags.find(e=>"d"===e[0]);if(e&&e[1]){const r=`${s.kind}:${e[1]}`,a=n.get(r);if(!a||s.created_at>a.created_at||s.created_at===a.created_at&&JSON.parse(s.content)?._deleted&&!JSON.parse(a.content)?._deleted){if(a){const e=t.indexOf(a);e>-1&&t.splice(e,1)}n.set(r,s),t.push(s)}continue}}t.push(s)}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()}close(){this.syncService&&this.syncService.stop();for(const e of this._subscriptions.values())e.close?e.close():void 0!==e.active&&(e.active=!1);this._subscriptions.clear(),this.pool.close(this.relays),this._eventCache.clear()}getRelayStatus(){return this.relays.map(e=>({url:e,connected:!0}))}}const c={nostr:"./backends/nostr-backend.js",gundb:"./backends/gundb-backend.js",activitypub:"./backends/activitypub-backend.js"},u=new Map;class d{static getAvailableBackends(){return Object.keys(c)}static isAvailable(e){return e in c}static async loadBackend(e){if(u.has(e))return u.get(e);const t=c[e];if(!t)throw new Error(`Unknown backend type: '${e}'. Available backends: ${Object.keys(c).join(", ")}`);try{const r=await import(t),s=r.default||r[`${n=e,n.charAt(0).toUpperCase()+n.slice(1)}Backend`];if(!s)throw new Error(`Backend module '${e}' does not export a valid backend class`);return u.set(e,s),s}catch(r){if("ERR_MODULE_NOT_FOUND"===r.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 r}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?c[e]=t:(u.set(e,t),c[e]=null)}}function p(e,t=1e3){return new Promise((n,r)=>{let s=!1;const a=setTimeout(()=>{s||(s=!0,n(null))},t);e.once(e=>{s||(s=!0,clearTimeout(a),n(e||null))})})}function h(e,t,n=1e3){return new Promise((r,s)=>{let a=!1;const i=setTimeout(()=>{a||(a=!0,r({ok:!0,timeout:!0}))},n);e.put(t,e=>{a||(a=!0,clearTimeout(i),e.err?s(new Error(e.err)):r(e))})})}async function y(e,t=300){return new Promise(n=>{const r={};e.map().once((e,t)=>{e&&!t.startsWith("_")&&(r[t]=e)}),setTimeout(()=>{n(r)},t)})}function m(e,t,n,r=null){const s=g(t),a=g(n);if(r){return`${e}/${s}/${a}/${g(r)}`}return`${e}/${s}/${a}`}function f(e,t,n=null){const r=g(t);if(n){return`${e}/${r}/${g(n)}`}return`${e}/${r}`}function g(e){return encodeURIComponent(e).replace(/%2F/g,"/")}function b(e){return{_json:JSON.stringify(e)}}function w(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 v(e,t,n){try{const r=b(n);return await h(e.get(t),r,2e3),await new Promise(e=>setTimeout(e,50)),!0}catch(r){throw r}}async function _(e,t){const n=await p(e.get(t),2e3);if(!n)return null;const r=w(n);return!r||r._deleted?null:r}async function T(e,t){return new Promise(n=>{const r=new Map;let s=!1;const a=e.get(t);a.once(e=>{if(s)return;if(!e)return s=!0,void n([]);const t=Object.keys(e).filter(e=>"_"!==e);if(0===t.length)return s=!0,void n([]);for(const n of t){const t=e[n];if(!t)continue;let s=null;if("object"!=typeof t||!t["#"]){if(t._json&&"string"==typeof t._json)try{s=JSON.parse(t._json)}catch(i){}else if("string"==typeof t)try{s=JSON.parse(t)}catch(i){}s&&s.id&&!s._deleted&&r.set(s.id,s)}}if(r.size>0)return s=!0,void n(Array.from(r.values()));a.map().once((e,t)=>{if(s||!e||"_"===t)return;let n=null;if(e._json&&"string"==typeof e._json)try{n=JSON.parse(e._json)}catch(i){}else if("string"==typeof e)try{n=JSON.parse(e)}catch(i){}n&&n.id&&!n._deleted&&r.set(n.id,n)}),setTimeout(()=>{s||(s=!0,n(Array.from(r.values())))},500)}),setTimeout(()=>{s||(s=!0,n(Array.from(r.values())))},2e3)})}async function x(e,t,n){const r=await p(e.get(t));if(!r)return!1;const s=w(r);if(!s||!s.id||s._deleted)return!1;const a={...s,...n};try{const n=b(a);return await h(e.get(t),n),!0}catch(i){throw i}}async function A(e,t){try{const n=await p(e.get(t));if(!n)return!0;const r=w(n),s={id:r?.id,_deleted:!0,_deletedAt:Date.now()};return await h(e.get(t),b(s)),!0}catch(n){throw n}}async function S(e,t){const n=await T(e,t);let r=0;for(const s of n)if(s&&s.id){const n=`${t}/${s.id}`;await A(e,n),r++}return{success:!0,count:r}}function k(e,t,n,r={}){const s=t.split("/");if(void 0!==r.prefix?r.prefix:s.length<=3){const r=e.get(t);return r.map().on((e,t)=>{if(e&&!t.startsWith("_")){const r=w(e);r&&!r._deleted&&n(r,t)}}),{unsubscribe:()=>{try{r.off()}catch(e){}}}}{const r=e.get(t).on((e,t)=>{if(e){const r=w(e);r&&!r._deleted&&n(r,t)}});return{unsubscribe:()=>{try{r.off()}catch(e){}}}}}async function N(e,t,n,r){if(!r||!r.id)throw new Error("writeGlobal: data must have an id field");return v(e,f(t,n,r.id),r)}async function E(e,t,n,r){return _(e,f(t,n,r))}async function I(e,t,n,r=2e3){return T(e,f(t,n))}async function O(e,t,n,r){return A(e,f(t,n,r))}async function C(e,t,n){return S(e,f(t,n))}function R(e){return w(e)}const $=Object.freeze(Object.defineProperty({__proto__:null,buildGlobalPath:f,buildPath:m,deleteAll:S,deleteAllGlobal:C,deleteData:A,deleteGlobal:O,parse:R,read:_,readAll:T,readAllGlobal:I,readGlobal:E,serialize:function(e){return b(e)},subscribe:k,update:x,write:v,writeGlobal:N},Symbol.toStringTag,{value:"Module"}));async function M(e,t){if(!t)throw new Error("getFederation: Missing space ID");return e.readGlobal("federation",t)}async function P(e,t,n){const r=`${t}_${n}_fedmsgs`;return e.readGlobal("federation_messages",r)}class F{constructor(e){if(new.target===F)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,r=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 D{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:r=!0}=n;if(!t)return null;let s=null,a=null;if(t.soul)s=t.soul;else if(t._federation&&t._federation.isReference){const e=t._federation;e.origin&&e.lens&&t.id&&(s=`${this.appname}/${e.origin}/${e.lens}/${t.id}`,a=e)}else t._&&t._["#"]&&(s=t._["#"]);if(!s)return null;const i=this.parseSoulPath(s);if(!i)return null;try{const t=`${i.appname}/${i.holon}/${i.lens}/${i.key}`,n=await _(e,t);if(!n)return null;if(r&&this.isReference(n)){const t=await this.resolveReference(e,n,{followReferences:!0});if(t)return{...t,_federation:{resolved:!0,soul:s,origin:i.holon,lens:i.lens,timestamp:Date.now()}}}return{...n,_federation:{resolved:!0,soul:s,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 H{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((r,s)=>{this.user.auth(n,t,t=>{t.err?(this.authenticated=!1,this.currentHolonId=null,s(new Error(t.err))):(this.authenticated=!0,this.currentHolonId=e,r(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((r,s)=>{this.user.create(n,t,a=>{a.err?s(new Error(a.err)):this.user.auth(n,t,t=>{t.err?s(new Error(t.err)):(this.authenticated=!0,this.currentHolonId=e,r(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 r=JSON.stringify(n);return await h(this.getPrivatePath(e,t),r,2e3),!0}catch(r){throw r}}async readPrivate(e,t){if(!this.isAuthenticated())throw new Error("Not authenticated");try{const r=await p(this.getPrivatePath(e,t),2e3);if(!r)return null;if("string"==typeof r)try{return JSON.parse(r)}catch(n){return r}if(r._json&&"string"==typeof r._json)try{return JSON.parse(r._json)}catch(n){return null}if("object"==typeof r){const e={...r};return delete e._,e}return null}catch(r){throw r}}async readAllPrivate(e,t=2e3){if(!this.isAuthenticated())throw new Error("Not authenticated");return new Promise(n=>{const r=[],s=new Set,a=this.getPrivatePath(e);setTimeout(()=>{try{a.off()}catch(e){}n(r)},t),a.map().once((e,t)=>{if(e&&!t.startsWith("_")&&!s.has(t)){s.add(t);let a=null;if("string"==typeof e)try{a=JSON.parse(e)}catch(n){a=e}else if(e._json&&"string"==typeof e._json)try{a=JSON.parse(e._json)}catch(n){}else"object"==typeof e&&(a={...e},delete a._);a&&!a._deleted&&r.push(a)}})})}async deletePrivate(e,t){if(!this.isAuthenticated())throw new Error("Not authenticated");try{const n=await this.readPrivate(e,t),r={id:n?.id||t,_deleted:!0,_deletedAt:Date.now()};return await h(this.getPrivatePath(e,t),JSON.stringify(r)),!0}catch(n){throw n}}}const B={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 j{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,r){if(!r||"object"!=typeof r)throw new Error("setSchema: schema must be an object");if(this.strict&&this.validator){if(!this.validateSchema(B,r))throw new Error("setSchema: Invalid schema definition")}const s={id:n,lens:n,schema:r,timestamp:Date.now()};return await N(e,t,"schemas",s),this.schemaCache.set(n,{schema:r,timestamp:Date.now()}),!0}async getSchema(e,t,n,r={}){const{useCache:s=!0}=r;if(s){const e=this.schemaCache.get(n);if(e&&Date.now()-e.timestamp<this.cacheMaxAge)return e.schema}const a=await E(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 I(e,t,"schemas")}async deleteSchema(e,t,n){return this.schemaCache.delete(n),O(e,t,"schemas",n)}validate(e,t){if(!this.validator)return{valid:!0,errors:[]};try{const n=this.validator.compile(e),r=n(t);return{valid:r,errors:r?[]:this.formatErrors(n.errors)}}catch(n){return{valid:!1,errors:[{message:n.message,path:""}]}}}async validateData(e,t,n,r){const s=await this.getSchema(e,t,n);return s?this.validate(s,r):{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 U extends F{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}async init(){let e;try{const t=await Promise.resolve().then(()=>require("./browser-Cq59Ij19.cjs")).then(e=>e.browser);e=t.default||t}catch(n){throw new Error('GunDB backend requires the "gun" package. Install it with: npm install gun')}const t={peers:this.config.peers||[],radisk:!1!==this.config.radisk,localStorage:!1!==this.config.localStorage,file:this.config.dataDir};this.gun=e(t);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(n){this.publicKey=this.appName}this.references=new D(this.appName),this.auth=new H(this.gun,this.appName),this.schemaValidator=new j({strict:this.config.strict||!1,cacheMaxAge:this.config.schemaCacheMaxAge||36e5}),await this.schemaValidator.init()}buildPath(e,t,n,r=null){return m(e,t,n,r)}buildGlobalPath(e,t=null){return f(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)}`)}}}return v(this.gun,e,t)}async read(e,t={}){const n=await _(this.gun,e);return n&&t.resolveReferences&&this.isReference(n)?this.resolveReference(n):n}async readAll(e,t={}){const n=await T(this.gun,e);if(t.resolveReferences){const e=[];for(const t of n)if(this.isReference(t)){const n=await this.resolveReference(t);n&&e.push(n)}else e.push(t);return e}return n}async update(e,t){return x(this.gun,e,t)}async delete(e){return A(this.gun,e)}async deleteAll(e){const t=await this.readAll(e);let n=0;for(const r of t)if(r&&r.id){const t=`${e}/${r.id}`;await A(this.gun,t),n++}return{success:!0,count:n}}async writeGlobal(e,t){return N(this.gun,this.appName,e,t)}async readGlobal(e,t){return E(this.gun,this.appName,e,t)}async readAllGlobal(e,t=5e3){return I(this.gun,this.appName,e,t)}async deleteGlobal(e,t){return O(this.gun,this.appName,e,t)}async deleteAllGlobal(e){return C(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 r=++this.subscriptionCounter,s=e.split("/").length<=3,a={id:r,path:e,active:!0,gunRef:null};if(s){const s=this.gun.get(e);a.gunRef=s,s.map().on(async(e,s)=>{if(!this.subscriptions.get(r)?.active)return;if(!e||s.startsWith("_")||e._deleted)return;let a=R(e);a&&(n.resolveReferences&&this.isReference(a)&&(a=await this.resolveReference(a)),a&&t(a,s))})}else{const s=this.gun.get(e);a.gunRef=s,s.on(async(e,s)=>{if(!this.subscriptions.get(r)?.active)return;if(!e)return;let a=R(e);a&&!a._deleted&&(n.resolveReferences&&this.isReference(a)&&(a=await this.resolveReference(a)),a&&t(a,s))})}return this.subscriptions.set(r,a),{id:r,unsubscribe:()=>{const e=this.subscriptions.get(r);if(e){if(e.active=!1,e.gunRef)try{e.gunRef.off()}catch(t){}this.subscriptions.delete(r)}}}}async exportData(e=""){const t=[],n=e||this.appName;try{const e=await y(this.gun.get(n),2e3);for(const[r,s]of Object.entries(e))r.startsWith("_")||!s||"object"!=typeof s||s._deleted||await this._collectRecords(n,r,s,t)}catch(r){console.warn("Export data error:",r)}return t}async _collectRecords(e,t,n,r){const s=`${e}/${t}`;if(n.id)r.push({path:s,data:this._cleanGunData(n),timestamp:n._meta?.timestamp||Date.now()});else try{const e=await y(this.gun.get(s),500);for(const[t,n]of Object.entries(e))!t.startsWith("_")&&n&&await this._collectRecords(s,t,n,r)}catch(a){}}_cleanGunData(e){const t={...e};return delete t._,t}async importData(e,t={}){const n={success:0,failed:0,errors:[]};for(const s of e)try{await v(this.gun,s.path,s.data),n.success++}catch(r){n.failed++,n.errors.push({path:s.path,error:r.message})}return n}close(){for(const[n,r]of this.subscriptions)if(r.active&&(r.active=!1,r.gunRef))try{r.gunRef.off()}catch(e){}if(this.subscriptions.clear(),this.schemaValidator&&this.schemaValidator.clearCache(),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 q="2.0.0-alpha4";function L(e){if("undefined"!=typeof process&&process.env)return process.env[e]}function J(){const e=L("HOLOSPHERE_RELAYS");return e?e.split(",").map(e=>e.trim()).filter(e=>e):["wss://relay.holons.io"]}let G=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&&!d.isAvailable(e.backend))throw new TypeError(`config.backend must be one of: ${d.getAvailableBackends().join(", ")}`);this.config={appName:e.appName||L("HOLOSPHERE_APP_NAME")||"holosphere",backend:e.backend||"nostr",relays:e.relays||J(),privateKey:e.privateKey||L("HOLOSPHERE_PRIVATE_KEY"),logLevel:e.logLevel||L("HOLOSPHERE_LOG_LEVEL")||"WARN",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 l(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:q,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 U({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:m},this._gunWrapper=$,this._logStartup({version:q,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 r={appName:this.config.appName,privateKey:this.config.privateKey,persistence:!1!==e.persistence,dataDir:e.dataDir,...n};this._backend=await d.create(t,r),this.client=this._backend.client||this._backend,this._logStartup({version:q,appName:this.config.appName,backend:t,publicKey:this._backend.publicKey,logLevel:this.config.logLevel,persistence:!1!==e.persistence,...this._backend.getStatus()})}catch(r){throw this._log("ERROR",`${t} backend initialization failed`,{error:r.message}),new Error(`${t} backend initialization failed: ${r.message}`)}}async ready(){this._backendReady&&await this._backendReady}get backend(){return this._backend}_log(e,t,n={}){if(this.logLevels[e]<=this.currentLogLevel){const r={timestamp:Date.now(),level:e,message:t,app:this.config.appName,...n};console.log(JSON.stringify(r))}}_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,r=!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 s=await e.readGlobal("federation",t);s||(s={id:t,name:t,federation:[],notify:[],timestamp:Date.now()}),s.federation||(s.federation=[]),s.notify||(s.notify=[]),s.federation.includes(n)||s.federation.push(n),s.timestamp=Date.now(),await e.writeGlobal("federation",s);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:r};return await e.writeGlobal("federationMeta",i),!0}catch(s){throw console.error(`Federation creation failed: ${s.message}`),s}}(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 r=await e.readGlobal("federation",t);r&&r.federation&&(r.federation=r.federation.filter(e=>e!==n),r.timestamp=Date.now(),await e.writeGlobal("federation",r));let s=await e.readGlobal("federation",n);s&&s.notify&&(s.notify=s.notify.filter(e=>e!==t),s.timestamp=Date.now(),await e.writeGlobal("federation",s));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(r){throw console.error(`Federation removal failed: ${r.message}`),r}}(this._backend,e,t)}async getFederation(e){return await this.ready(),this._requireGunDB(),M(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:r=!0,spaceName:s=null}=n,a={success:!1,federatedCount:0,notifyCount:0,partnersNotified:0,errors:[]};try{const n=await M(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:s||t,federation:[],notify:[],timestamp:Date.now()};if(await e.writeGlobal("federation",o),r&&n.federation&&n.federation.length>0)for(const r of n.federation)try{const n=await M(e,r);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:r,error:i.message})}if(n.federation&&n.federation.length>0)for(const r of n.federation)try{const n=`${t}_${r}`,s=`${r}_${t}`;let a=await e.readGlobal("federationMeta",n);a||(a=await e.readGlobal("federationMeta",s)),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,r={}){return await this.ready(),this._requireGunDB(),async function(e,t,n,r,s={}){if(!(e&&t&&n&&r))throw new Error("propagate: Missing required parameters");const{useReferences:a=!0,targetSpaces:i=null}=s,o={success:0,errors:0,errorDetails:[],propagated:!1,referencesUsed:a};try{const s=await M(e,t);if(!s||!s.federation||0===s.federation.length)return{...o,message:`No federation found for ${t}`};if(!s.notify||0===s.notify.length)return{...o,message:`No notification targets found for ${t}`};let c=s.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 u=e.isReference(r);for(const i of c)try{if(a&&!u){const s=e.createReference(t,n,r);s._federation={origin:t,lens:n,timestamp:Date.now()};const a=e.buildPath(e.appName,i,n,s.id);await e.write(a,s),o.success++}else if(u){const s={...r,_federation:r._federation||{origin:t,lens:n,timestamp:Date.now()}},a=e.buildPath(e.appName,i,n,r.id);await e.write(a,s),o.success++}else{const s={...r,_federation:{origin:t,lens:n,timestamp:Date.now()}},a=e.buildPath(e.appName,i,n,r.id);await e.write(a,s),o.success++}}catch(l){o.errors++,o.errorDetails.push({space:i,error:l.message})}return o.propagated=o.success>0,o}catch(l){return console.error("Error in propagate:",l),{...o,error:l.message}}}(this._backend,e,t,n,r)}async getFederated(e,t,n={}){return await this.ready(),this._requireGunDB(),async function(e,t,n,r={}){const{aggregate:s=!1,idField:a="id",sumFields:i=[],concatArrays:o=[],removeDuplicates:l=!0,mergeStrategy:c=null,includeLocal:u=!0,includeFederated:d=!0,resolveReferences:p=!0,maxFederatedSpaces:h=-1,timeout:y=1e4}=r;if(!e||!t||!n)throw new Error("Missing required parameters: backend, holon, and lens are required");const m=await M(e,t),f=[],g=new Set;if(d&&m&&m.federation&&m.federation.length>0){const t=-1===h?m.federation:m.federation.slice(0,h);for(const r of t)try{const t=e.buildPath(e.appName,r,n),s=await e.readAll(t);for(const e of s)e&&e[a]&&(f.push(e),g.add(e[a]))}catch(b){console.warn(`Error processing federated space ${r}: ${b.message}`)}}if(u){const r=e.buildPath(e.appName,t,n),s=await e.readAll(r);for(const e of s)e&&e[a]&&!g.has(e[a])&&(f.push(e),g.add(e[a]))}if(p)for(let w=0;w<f.length;w++){const t=f[w];if(t.soul&&t.id)try{const n=await e.resolveReference(t);n&&(f[w]=n)}catch(b){f[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&&(f[w]=n)}catch(b){console.warn(`Error resolving legacy reference: ${b.message}`)}}if(s&&f.length>0){const e=f.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 r=e.reduce((e,t)=>Array.isArray(t[n])?[...e,...t[n]]:e,[]);t[n]=l?Array.from(new Set(r)):r}return t._aggregated={count:e.length,timestamp:Date.now()},t})}return f}(this._backend,e,t,n)}async subscribeFederation(e,t,n={}){return await this.ready(),this._requireGunDB(),async function(e,t,n,r={}){if(!t||!n)throw new Error("subscribeFederation: Missing required parameters");const{lenses:s=["*"],throttle:a=0,resolveReferences:i=!0}=r,o=await M(e,t);if(!o)throw new Error("No federation info found for space");const l=[];let c={};if(o.federation&&o.federation.length>0)for(const d of o.federation)for(const t of s)try{const r=e.buildPath(e.appName,d,t),s=await e.subscribe(r,async(r,s)=>{try{if(!r||!r.id)return;const s=Date.now(),o=`${d}_${t}_${r.id}`;if(a>0){if(c[o]&&s-c[o]<a)return;c[o]=s}let l=r;i&&e.isReference(r)&&(l=await e.resolveReference(r)),l._federation||(l._federation={origin:d,timestamp:s}),await n(l,d,t)}catch(o){console.warn("Federation notification error:",o)}},{resolveReferences:!1});s&&"function"==typeof s.unsubscribe&&l.push(s)}catch(u){console.warn(`Error creating subscription for ${d}/${t}:`,u)}return{unsubscribe:()=>{l.forEach(e=>{try{e&&"function"==typeof e.unsubscribe&&e.unsubscribe()}catch(u){console.warn("Error unsubscribing:",u)}}),l.length=0,c={}},getSubscriptionCount:()=>l.length}}(this._backend,e,t,n)}async federateMessage(e,t,n,r,s="generic"){return await this.ready(),this._requireGunDB(),async function(e,t,n,r,s,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 l=o.messages.find(e=>e.chatId===r);l?(l.messageId=s,l.timestamp=Date.now()):o.messages.push({chatId:r,messageId:s,timestamp:Date.now()}),await e.writeGlobal("federation_messages",o)}(this._backend,e,t,n,r,s)}async getFederatedMessages(e,t){return await this.ready(),this._requireGunDB(),P(this._backend,e,t)}async updateFederatedMessages(e,t,n){return await this.ready(),this._requireGunDB(),async function(e,t,n,r){const s=await P(e,t,n);if(s?.messages)for(const i of s.messages)try{await r(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 z(e,n,r){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(r)||r<0||r>15)throw new RangeError(`Invalid resolution: ${r}. Must be integer between 0 and 15.`);try{return t.latLngToCell(e,n,r)}catch(s){throw new Error(`H3 conversion failed: ${s.message}`)}}function V(e,n=0){if(!W(e))throw new Error(`Invalid H3 holon ID: ${e}`);const r=[];let s=e;for(let i=t.getResolution(e)-1;i>=n;i--)try{s=t.cellToParent(s,i),r.push(s)}catch(a){break}return r}function K(e){if(!W(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 W(e){return"string"==typeof e&&t.isValidCell(e)}const Z=Object.freeze(Object.defineProperty({__proto__:null,getChildren:K,getH3Resolution:function(e){if(!W(e))throw new Error(`Invalid H3 holon ID: ${e}`);return t.getResolution(e)},getParents:V,isValidH3:W,toHolon:z},Symbol.toStringTag,{value:"Module"})),Y=new Map;async function X(e,t,n,r=3e4){const s={kind:r,created_at:Math.floor(Date.now()/1e3),tags:[["d",t]],content:JSON.stringify(n)};return await e.publish(s)}async function Q(e,t,n=3e4,r={}){const s=void 0!==r.timeout?r.timeout:3e4,a=r.authors||[e.publicKey];if(!r.skipPersistent&&e.persistentGet){const i=await e.persistentGet(t);if(i&&i.content)try{const o=JSON.parse(i.content);return o._deleted?null:(r.includeAuthor&&(o._author=i.pubkey),e.refreshPathInBackground&&e.refreshPathInBackground(t,n,{authors:a,timeout:s}),o)}catch(c){console.warn("[nostrGet] Failed to parse persisted event:",c)}}const i={kinds:[n],authors:a,"#d":[t],limit:a.length},o=await e.query(i,{timeout:s});if(0===o.length)return null;const l=o.sort((e,t)=>t.created_at-e.created_at)[0];try{const e=JSON.parse(l.content);return e._deleted?null:(r.includeAuthor&&(e._author=l.pubkey),e)}catch(c){return null}}async function ee(e,t,n=3e4,r={}){const s=void 0!==r.timeout?r.timeout:3e4,a=r.limit||1e3,i=r.authors||[e.publicKey];if(!r.skipPersistent&&e.persistentGetAll){const o=await e.persistentGetAll(t);if(o.length>0){const l=new Map;for(const e of o){if(!e||!e.tags)continue;const n=e.tags.find(e=>"d"===e[0]);if(!n||!n[1]||!n[1].startsWith(t))continue;const s=n[1],a=l.get(s);if(!a||e.created_at>a.created_at)try{const t=JSON.parse(e.content);if(t._deleted){l.delete(s);continue}r.includeAuthor&&(t._author=e.pubkey),l.set(s,{data:t,created_at:e.created_at})}catch(u){}}return e.refreshPrefixInBackground&&e.refreshPrefixInBackground(t,n,{authors:i,timeout:s,limit:a}),Array.from(l.values()).map(e=>e.data)}}const o={kinds:[n],authors:i,limit:a},l=(await e.query(o,{timeout:s})).filter(e=>{const n=e.tags.find(e=>"d"===e[0]);return n&&n[1]&&n[1].startsWith(t)}),c=new Map;for(const d of l){const e=d.tags.find(e=>"d"===e[0])[1],t=c.get(e);if(!t||d.created_at>t.created_at)try{const t=JSON.parse(d.content);if(t._deleted){c.delete(e);continue}r.includeAuthor&&(t._author=d.pubkey),c.set(e,{data:t,created_at:d.created_at})}catch(u){}}return Array.from(c.values()).map(e=>e.data)}async function te(e,t,n=3e4,r={}){const s=void 0!==r.timeout?r.timeout:3e4,a=r.limit||1e3,i=r.authors||[e.publicKey],o=e.queryHybrid||e.query,l={kinds:[n],authors:i,limit:a},c=(await o.call(e,l,{timeout:s})).filter(e=>{const n=e.tags.find(e=>"d"===e[0]);return n&&n[1]&&n[1].startsWith(t)}),u=new Map;for(const p of c){const e=p.tags.find(e=>"d"===e[0])[1],t=u.get(e);if(!t||p.created_at>t.created_at)try{const t=JSON.parse(p.content);if(null===t||"object"!=typeof t)continue;if(t._deleted){u.delete(e);continue}r.includeAuthor&&(t._author=p.pubkey),u.set(e,{data:t,created_at:p.created_at})}catch(d){}}return Array.from(u.values()).map(e=>e.data)}function ne(e){return encodeURIComponent(e).replace(/%2F/g,"/")}async function re(e,t){try{const n=await async function(e,t,n=3e4){if(!(await Q(e,t,n)))return{reason:"not_found",results:[]};const r={_deleted:!0,_deletedAt:Date.now()},s=await X(e,t,r,n);if(e.persistentStorage)try{await e.persistentStorage.delete(t)}catch(o){}e.clearCache&&e.clearCache(t);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(l){}return s}(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 se(e,t){try{const n=await async function(e,t,n=3e4){const r={kinds:[n],authors:[e.publicKey],limit:1e3},s=await e.query(r,{timeout:3e4});let a=[];if(e.persistentStorage)try{a=await e.persistentStorage.getAll(t)}catch(u){}const i=new Map;for(const p of s){const e=p.tags?.find(e=>"d"===e[0]);e&&e[1]&&e[1].startsWith(t)&&i.set(e[1],p)}for(const p of a){const e=p.tags?.find(e=>"d"===e[0]);if(e&&e[1]&&e[1].startsWith(t)){const t=i.get(e[1]);(!t||p.created_at>t.created_at)&&i.set(e[1],p)}}const o=Array.from(i.values());if(0===o.length)return{success:!0,count:0,results:[]};const l=[];for(const p of o){const t=p.tags.find(e=>"d"===e[0])[1];try{const r={_deleted:!0,_deletedAt:Date.now()},s=await X(e,t,r,n);if(l.push(s),e.persistentStorage)try{await e.persistentStorage.delete(t)}catch(u){}e.clearCache&&e.clearCache(t)}catch(d){console.error(`Failed to delete item ${t}:`,d)}}const c=o.map(t=>{const r=t.tags.find(e=>"d"===e[0])[1];return`${n}:${e.publicKey}:${r}`});try{const t={kind:5,created_at:Math.floor(Date.now()/1e3),tags:c.map(e=>["a",e]),content:""};await e.publish(t)}catch(d){}return{success:!0,count:o.length,results:l}}(e,t);return n}catch(n){throw console.error("Nostr deleteAll error:",n),n}}async function ae(e,t,n,r={}){return t.split("/").length<=3?await async function(e,t,n,r={}){const s=r.kind||3e4,a=`${e.publicKey}:${s}:${t}`,i=Y.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(),Y.delete(a))}};const o=new Set,l=[n];let c=0,u=0,d=Date.now();const p=n=>{if(o.has(n.id))return;if(o.add(n.id),n.pubkey!==e.publicKey){c++;const t=Date.now();return void(t-d>1e4&&(console.warn("[nostrSubscribeMany] ⚠️ Relay not respecting authors filter!",{rejectedCount:c,acceptedCount:u,expected:e.publicKey,message:"Consider using a different relay or implementing private relay"}),d=t))}const r=n.tags.find(e=>"d"===e[0]),s=r?.[1];if(s&&s.startsWith(t))try{const e=JSON.parse(n.content);if(e._deleted)return;u++;for(const t of l)t(e,s,n)}catch(a){console.error("[nostrSubscribeMany] Failed to parse event:",a)}},h=Math.floor(Date.now()/1e3),y={kinds:[s],authors:[e.publicKey],since:h},m=await e.subscribe(y,p);let f="undefined"!=typeof document&&document.hidden,g=h;const b=async()=>{if("undefined"==typeof document)return;const t=f;if(f=document.hidden,t&&!f){const t=Math.floor(Date.now()/1e3);try{const n={...y,since:g,until:t},r=await e.query(n,{timeout:3e4});for(const e of r)p(e);g=t}catch(n){}}};"undefined"!=typeof document&&document.addEventListener("visibilitychange",b);const w={unsubscribe:()=>{m&&m.unsubscribe&&m.unsubscribe(),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",b),Y.delete(a)}},v={callbacks:l,actualSubscription:w};return Y.set(a,v),w}(e,t+"/",(e,t)=>{const r=t.split("/").pop();n(e,r)},r):function(e,t,n,r={}){const s=r.kind||3e4;r.includeInitial;const a={kinds:[s],authors:[e.publicKey],"#d":[t],limit:10};return e.subscribe(a,t=>{if(t.pubkey===e.publicKey)try{const e=JSON.parse(t.content);if(e._deleted)return;n(e,t)}catch(r){console.error("Failed to parse event in subscription:",r)}else console.warn("[nostrSubscribe] Rejecting event from different author:",{expected:e.publicKey,received:t.pubkey,eventId:t.id})},{onEOSE:()=>{}})}(e,t,e=>{n(e,t.split("/").pop())},r)}function ie(e,t,n,r=null){return function(e,t,n,r=null){const s=ne(t),a=ne(n);if(r)return`${e}/${s}/${a}/${ne(r)}`;return`${e}/${s}/${a}`}(e,t,n,r)}async function oe(e,t,n){return e.gun?v(e.gun,t,n):async function(e,t,n){try{const r=await X(e,t,n);return 0===r.results.length||r.results.some(e=>"fulfilled"===e.status)}catch(r){throw console.error("Nostr write error:",r),r}}(e,t,n)}async function le(e,t,n={}){return e.gun?_(e.gun,t):async function(e,t,n={}){const r=await Q(e,t,3e4,n);return!r||r._deleted?null:r}(e,t,n)}async function ce(e,t,n={}){return e.gun?T(e.gun,t):async function(e,t,n={}){const r=n.hybrid&&"function"==typeof e.queryHybrid?te:ee;return(await r(e,t,3e4,n)).filter(e=>!(!e||"object"!=typeof e||e._deleted))}(e,t,n)}async function ue(e,t,n){return e.gun?x(e.gun,t,n):async function(e,t,n){try{const r=await Q(e,t);if(!r||!r.id||r._deleted)return!1;const s={...r,...n};s._meta||(s._meta={}),s._meta.timestamp=Date.now();const a=await X(e,t,s);return 0===a.results.length||a.results.some(e=>"fulfilled"===e.status)}catch(r){throw console.error("Nostr update error:",r),r}}(e,t,n)}async function de(e,t){return e.gun?A(e.gun,t):re(e,t)}async function pe(e,t){return e.gun?S(e.gun,t):se(e,t)}function he(e,t,n,r={}){return e.gun?k(e.gun,t,n,r):ae(e,t,n,r)}const ye=Object.freeze(Object.defineProperty({__proto__:null,buildPath:ie,deleteAll:pe,deleteData:de,read:le,readAll:ce,subscribe:he,update:ue,write:oe},Symbol.toStringTag,{value:"Module"}));async function me(e,t,n,r){r.id||(r.id=`${Date.now()}-${Math.random().toString(36).substr(2,9)}`);return oe(e,`${t}/${n}/${r.id}`,r)}async function fe(e,t,n,r=null){if(r){return le(e,`${t}/${n}/${r}`)}return ce(e,`${t}/${n}`)}const ge=new n({allErrors:!0,strict:!1}),be=new Map;let we=class extends Error{constructor(e,t=[]){super(e),this.name="ValidationError",this.errors=t}};function ve(e,t){const n=t,r=be.get(n);if(r&&Date.now()-r.timestamp<36e5)return r.validator;try{const t=ge.compile(e);return be.set(n,{validator:t,timestamp:Date.now()}),t}catch(s){throw new Error(`Schema compilation failed: ${s.message}`)}}function _e(e,t,n,r=!1){const s=ve(t,n);if(!s(e)){const e=s.errors||[],t=e.map(e=>`${e.instancePath} ${e.message}`).join("; ");if(r)throw new we(`ValidationError: Validation failed: ${t}`,e);return console.warn(`[Schema Validation Warning] ${n}: ${t}`),!1}return!0}const Te=Object.freeze(Object.defineProperty({__proto__:null,ValidationError:we,clearAllCaches:function(){be.clear()},clearSchemaCache:function(e){be.delete(e)},compileSchema:ve,validate:_e},Symbol.toStringTag,{value:"Module"})),xe="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;
2
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3
+ function Ae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Se(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ke(e,...t){if(!Ae(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 Ne(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 Ee(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ie(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Oe(e,t){return e<<32-t|e>>>t}const Ce=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Re=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function $e(e){if(ke(e),Ce)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Re[e[n]];return t}const Me=48,Pe=57,Fe=65,De=70,He=97,Be=102;function je(e){return e>=Me&&e<=Pe?e-Me:e>=Fe&&e<=De?e-(Fe-10):e>=He&&e<=Be?e-(He-10):void 0}function Ue(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)),ke(e),e}let qe=class{};function Le(e){const t=t=>e().update(Ue(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Je(e,t,n){return e&t^~e&n}function Ge(e,t,n){return e&t^e&n^t&n}class ze extends qe{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Ie(this.buffer)}update(e){Ne(this),ke(e=Ue(e));const{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let a=0;a<s;){const i=Math.min(r-this.pos,s-a);if(i===r){const t=Ie(e);for(;r<=s-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+i),this.pos),this.pos+=i,a+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ne(this),function(e,t){ke(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:r,isLE:s}=this;let{pos:a}=this;t[a++]=128,Ee(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let u=a;u<r;u++)t[u]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const s=BigInt(32),a=BigInt(4294967295),i=Number(n>>s&a),o=Number(n&a),l=r?4:0,c=r?0:4;e.setUint32(t+l,i,r),e.setUint32(t+c,o,r)}(n,r-8,BigInt(8*this.length),s),this.process(n,0);const i=Ie(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=o/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)i.setUint32(4*u,c[u],s)}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:r,finished:s,destroyed:a,pos:i}=this;return e.destroyed=a,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Ve=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ke=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]),We=new Uint32Array(64);class Ze extends ze{constructor(e=32){super(64,e,8,!1),this.A=0|Ve[0],this.B=0|Ve[1],this.C=0|Ve[2],this.D=0|Ve[3],this.E=0|Ve[4],this.F=0|Ve[5],this.G=0|Ve[6],this.H=0|Ve[7]}get(){const{A:e,B:t,C:n,D:r,E:s,F:a,G:i,H:o}=this;return[e,t,n,r,s,a,i,o]}set(e,t,n,r,s,a,i,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|s,this.F=0|a,this.G=0|i,this.H=0|o}process(e,t){for(let u=0;u<16;u++,t+=4)We[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const e=We[u-15],t=We[u-2],n=Oe(e,7)^Oe(e,18)^e>>>3,r=Oe(t,17)^Oe(t,19)^t>>>10;We[u]=r+We[u-7]+n+We[u-16]|0}let{A:n,B:r,C:s,D:a,E:i,F:o,G:l,H:c}=this;for(let u=0;u<64;u++){const e=c+(Oe(i,6)^Oe(i,11)^Oe(i,25))+Je(i,o,l)+Ke[u]+We[u]|0,t=(Oe(n,2)^Oe(n,13)^Oe(n,22))+Ge(n,r,s)|0;c=l,l=o,o=i,i=a+e|0,a=s,s=r,r=n,n=e+t|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,a=a+this.D|0,i=i+this.E|0,o=o+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(n,r,s,a,i,o,l,c)}roundClean(){Ee(We)}destroy(){this.set(0,0,0,0,0,0,0,0),Ee(this.buffer)}}const Ye=Le(()=>new Ze),Xe=Ye;let Qe=null;async function et(){if(!Qe){const e=await Promise.resolve().then(()=>require("./secp256k1-0kPdAVkK.cjs"));Qe=e.secp256k1}return Qe}async function tt(e){return $e((await et()).getPublicKey(e))}async function nt(e,t){try{const n=await et(),r=ot(e);return n.sign(r,t).toCompactHex()}catch(n){throw new Error(`Signature generation failed: ${n.message}`)}}async function rt(e,t,n){try{if(!n||"string"!=typeof n||n.length<64)throw new Error("Invalid public key format");const r=await et(),s=ot(e);return r.verify(t,s,n)}catch(r){if("Invalid public key format"===r.message)throw r;return!1}}function st(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 at(e,t,n,r={}){const{expiresIn:s=36e5,issuer:a="holosphere",issuerKey:i}=r;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()+s},l=JSON.stringify(o),c=Buffer.from?Buffer.from(l).toString("base64"):btoa(l);if(i){return`${c}.${await nt(l,i)}`}return c}async function it(e,t,n){try{let r;if("string"==typeof e){const t=e.split(".")[0],n=Buffer.from?Buffer.from(t,"base64").toString("utf8"):atob(t);r=JSON.parse(n)}else r=e;return!(!r||"capability"!==r.type)&&(!(Date.now()>r.expires)&&(!!st(r.scope,n)&&!!r.permissions.includes(t)))}catch(r){return!1}}function ot(e){const t="string"==typeof e?e:JSON.stringify(e),n=(new TextEncoder).encode(t);return $e(Xe(n))}const lt=Object.freeze(Object.defineProperty({__proto__:null,getPublicKey:tt,issueCapability:at,matchScope:st,sign:nt,verify:rt,verifyCapability:it},Symbol.toStringTag,{value:"Module"})),ct="federations";async function ut(e,t){return await fe(e,t,ct,e.publicKey)||{id:e.publicKey,federatedWith:[],discoveryEnabled:!1,autoAccept:!1,defaultScope:{holonId:"*",lensName:"*"},defaultPermissions:["read"]}}async function dt(e,t,n){return me(e,t,ct,n)}async function pt(e,t,n,r={}){const s=await ut(e,t),a=s.federatedWith.findIndex(e=>e.pubKey===n);if(a>=0){const e=s.federatedWith[a];r.alias&&(e.alias=r.alias),r.inboundCapabilities&&(e.inboundCapabilities=[...e.inboundCapabilities||[],...r.inboundCapabilities]),e.updatedAt=Date.now(),s.federatedWith[a]=e}else s.federatedWith.push({pubKey:n,alias:r.alias||null,addedAt:Date.now(),addedVia:r.addedVia||"manual",inboundCapabilities:r.inboundCapabilities||[],outboundCapabilities:[]});return dt(e,t,s)}async function ht(e,t,n,r){const s=(await ut(e,t)).federatedWith.find(e=>e.pubKey===n);return s&&s.inboundCapabilities&&s.inboundCapabilities.find(e=>!(e.expires&&e.expires<Date.now())&&st(e.scope,r))||null}async function yt(e,t,n,r){const s=await ut(e,t),a=s.federatedWith.find(e=>e.pubKey===n);if(!a)return pt(e,t,n,{addedVia:"capability_received",inboundCapabilities:[r]});a.inboundCapabilities||(a.inboundCapabilities=[]);const i=a.inboundCapabilities.findIndex(e=>JSON.stringify(e.scope)===JSON.stringify(r.scope));return i>=0?a.inboundCapabilities[i]={...r,updatedAt:Date.now()}:a.inboundCapabilities.push({...r,receivedAt:Date.now()}),dt(e,t,s)}async function mt(e,t,n,r,s,a){const i=new Set,o=[];let l=n,c=s,u=a,d=t;for(;i.size<10;){const t=`${d}:${l}:${c}:${u}`;if(i.has(t))return{isCircular:!0,chain:o,reason:"existing_cycle"};if(i.add(t),o.push({holon:l,lens:c,dataId:u}),l===r)return{isCircular:!0,chain:o,reason:"would_create_cycle"};const n=ie(d,l,c,u),s=await le(e,n);if(!s)return{isCircular:!1,chain:o};if(!s.hologram||!s.target)return{isCircular:!1,chain:o};d=s.target.appname||d,l=s.target.holonId,c=s.target.lensName||c,u=s.target.dataId||u}return{isCircular:!0,chain:o,reason:"max_depth_exceeded"}}function ft(e,t,n,r,s,a={}){const{authorPubKey:i=null,capability:o=null}=a,l={id:r,hologram:!0,soul:ie(s,e,n,r),target:{appname:s,holonId:e,lensName:n,dataId:r},_meta:{created:Date.now(),sourceHolon:e,source:e}};return i&&(l.crossHolosphere=!0,l.target.authorPubKey=i,l._meta.sourcePubKey=i),o&&(l.capability=o,l._meta.grantedAt=Date.now()),l}async function gt(e,t,n=new Set,r=[],s={}){const{deleteCircular:a=!0,hologramPath:i=null}=s;if(!t||!t.hologram)return t;const{soul:o}=t,l=t.target||{};if(n.has(o)){const s=[...r,o].join(" → ");return console.warn("🔄 Circular reference detected - removing hologram"),console.warn(` Soul: ${o}`),console.warn(` Chain: ${s}`),console.warn(` Source holon: ${l.holonId||"unknown"}`),console.warn(` Lens: ${l.lensName||"unknown"}`),console.warn(` Data ID: ${l.dataId||t.id||"unknown"}`),console.warn(` Resolution depth: ${n.size}`),a&&i&&(console.info(` 🗑️ Deleting circular hologram at: ${i}`),await oe(e,i,null)),null}if(n.size>=10){const t=[...r,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: ${l.holonId||"unknown"}`),console.warn(` Lens: ${l.lensName||"unknown"}`),a&&i&&(console.info(` 🗑️ Deleting deep chain hologram at: ${i}`),await oe(e,i,null)),null}let c;if(n.add(o),r.push(o),t.crossHolosphere&&l.authorPubKey){let n=t.capability;if(!n&&s.appname){const t=await ht(e,s.appname,l.authorPubKey,{holonId:l.holonId,lensName:l.lensName,dataId:l.dataId});t&&(n=t.token)}if(!n)return console.warn(`❌ Cross-holosphere hologram missing capability: ${o}`),null;if(!(await it(n,"read",{holonId:l.holonId,lensName:l.lensName,dataId:l.dataId})))return console.warn(`❌ Capability verification failed for cross-holosphere hologram: ${o}`),null;c=await le(e,o,{authors:[l.authorPubKey]})}else c=await le(e,o);return c?c.hologram?gt(e,c,n,r,{...s,hologramPath:o}):function(e,t){const n=["hologram","soul","target","_meta","id","capability","crossHolosphere"],r={},s=[];for(const o of Object.keys(e))n.includes(o)||(r[o]=e[o],s.push(o));const a=e._meta?.sourceHolon||e._meta?.source||e.target?.holonId,i={...t,...r,_hologram:{isHologram:!0,soul:e.soul,sourceHolon:a,localOverrides:s,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 bt(e,t,n,r,s,a={}){const{direction:i="outbound",mode:o="reference"}=a,l={sourceHolon:n,targetHolon:r,lensName:s,direction:i,mode:o,created:Date.now()};return oe(e,ie(t,n,s,"_federation"),l)}async function wt(e,t,n,r,s,a,i="reference"){const o=n.id;if(r===s)return console.info(`⏭️ Skipping propagation - source and target are the same holon: ${r}`),!0;if(!0===n.hologram){if(n.target&&n.target.holonId===s)return console.info("🔄 Skipping propagation - would create circular reference:"),console.info(` Data ID: ${o}`),console.info(` Source holon: ${r}`),console.info(` Target holon: ${s}`),console.info(` Hologram points to: ${n.target.holonId}`),console.info(` Lens: ${a}`),console.info(` Original soul: ${n.soul||"unknown"}`),!0;if(n.target){const r=ie(n.target.appname||t,n.target.holonId,n.target.lensName||a,n.target.dataId||o),i=await le(e,r);if(i?._meta?.activeHolograms){if(i._meta.activeHolograms.some(e=>e.targetHolon===s))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: ${s}`),!0}}const i=n.target.holonId,l=n.target.dataId||o,c=n.target.lensName||a,u=n.target.appname||t,d=await mt(e,u,i,s,c,l);if(d.isCircular){const e=d.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: ${s}`),console.warn(` Existing chain: ${e}`),console.warn(` Reason: ${d.reason}`),!1}const p=ie(t,s,a,o),h={...n,_meta:{...n._meta,copiedFrom:r,copiedAt:Date.now()}},y=await oe(e,p,h);return y&&n.target&&(await At(e,n.target.appname||t,n.target.holonId,n.target.lensName||a,n.target.dataId||o,s),console.info(`📋 Copied hologram to ${s}:`),console.info(` Data ID: ${o}`),console.info(` Original source: ${n.target.holonId}`),console.info(` Copied from: ${r}`)),y}if("reference"===i&&n._meta?.activeHolograms){if(n._meta.activeHolograms.some(e=>e.targetHolon===s))return console.info("⏭️ Skipping propagation - target already in activeHolograms:"),console.info(` Data ID: ${o}`),console.info(` Source holon: ${r}`),console.info(` Target holon: ${s}`),!0}if("reference"===i){const n=await mt(e,t,r,s,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: ${r} → ${s}`),console.warn(` Existing chain: ${e}`),console.warn(` Reason: ${n.reason}`),!1}const i=ft(r,0,a,o,t),l=ie(t,s,a,o),c=await oe(e,l,i);return c&&await At(e,t,r,a,o,s),c}return oe(e,ie(t,s,a,o),{...n,_meta:{...n._meta,source:r}})}async function vt(e,t,n,r,s,a){const i=ie(t,n,r,s),o=await le(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 l=["hologram","soul","target","_meta","id"],c={};for(const[u,d]of Object.entries(a))l.includes(u)||(c[u]=d);return oe(e,i,{...o,...c})}function _t(e){return e&&!0===e.hologram}function Tt(e){return e&&e._hologram&&!0===e._hologram.isHologram}function xt(e){return Tt(e)?{soul:e._hologram.soul,sourceHolon:e._hologram.sourceHolon,localOverrides:e._hologram.localOverrides||[]}:null}async function At(e,t,n,r,s,a){let i=t,o=n,l=r,c=s,u=ie(i,o,l,c),d=await le(e,u);if(!d)return console.warn(`Source data not found at ${u}`),!1;let p=0;for(;!0===d.hologram&&d.target&&p<10;)if(p++,i=d.target.appname||i,o=d.target.holonId,l=d.target.lensName||l,c=d.target.dataId||c,u=ie(i,o,l,c),d=await le(e,u),!d)return console.warn(`Real source data not found at ${u}`),!1;p>0&&console.info(`📍 Followed hologram chain (depth: ${p}) to real source: ${o}/${l}/${c}`),d._meta||(d._meta={}),Array.isArray(d._meta.activeHolograms)||(d._meta.activeHolograms=[]);const h=Date.now(),y=d._meta.activeHolograms.findIndex(e=>e.targetHolon===a);return y>=0?d._meta.activeHolograms[y].lastUpdated=h:d._meta.activeHolograms.push({targetHolon:a,created:h,lastUpdated:h}),oe(e,u,d)}async function St(e,t,n,r,s,a){let i=t,o=n,l=r,c=s,u=ie(i,o,l,c),d=await le(e,u);if(!d)return!1;let p=0;for(;!0===d.hologram&&d.target&&p<10;)if(p++,i=d.target.appname||i,o=d.target.holonId,l=d.target.lensName||l,c=d.target.dataId||c,u=ie(i,o,l,c),d=await le(e,u),!d)return!1;if(!d._meta||!Array.isArray(d._meta.activeHolograms))return!1;const h=d._meta.activeHolograms.length;return d._meta.activeHolograms=d._meta.activeHolograms.filter(e=>e.targetHolon!==a),d._meta.activeHolograms.length<h&&oe(e,u,d)}async function kt(e,t,n,r,s,a=null){if(!a){const i=ie(t,n,r,s);a=await le(e,i)}if(!a||!a._meta||!Array.isArray(a._meta.activeHolograms))return{refreshed:0,holograms:[]};const i=Date.now(),o=[];for(const l of a._meta.activeHolograms){l.lastUpdated=i;const n=ie(t,l.targetHolon,r,s),a=await le(e,n);a&&!0===a.hologram&&(a._meta||(a._meta={}),a._meta.lastUpdated=i,await oe(e,n,a),o.push({targetHolon:l.targetHolon,dataId:s,timestamp:i}))}return{refreshed:o.length,holograms:o,sourceData:a}}async function Nt(e,t,n,r,s,a={}){const{deleteData:i=!0}=a,o=ie(t,n,r,s),l={success:!1,wasHologram:!1,sourceHolon:null,activeHologramsUpdated:!1,error:null};try{const a=await le(e,o);if(!a)return console.warn(`🗑️ Hologram not found at ${o}`),l.error="Hologram not found",l;if(!0===a.hologram&&a.target){l.wasHologram=!0,l.sourceHolon=a.target.holonId,console.info("🗑️ Deleting hologram:"),console.info(` Path: ${o}`),console.info(` Data ID: ${s}`),console.info(` From holon: ${n}`),console.info(` Source holon: ${a.target.holonId}`),console.info(` Lens: ${r}`);const i=await St(e,a.target.appname||t,a.target.holonId,a.target.lensName||r,a.target.dataId||s,n);l.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 oe(e,o,null);l.success=t,t?console.info(" ✓ Hologram deleted successfully"):(console.warn(" ⚠️ Failed to delete hologram data"),l.error="Failed to delete hologram data")}else l.success=!0;return l}catch(c){return console.error(`❌ Error deleting hologram at ${o}:`,c),l.error=c.message||"Unknown error",l}}async function Et(e,t,n,r,s={}){const{dryRun:a=!1}=s,i={scanned:0,circularFound:0,deleted:0,errors:[],details:[]};console.info(`🧹 ${a?"[DRY RUN] ":""}Cleaning up circular holograms in ${n}/${r}...`);try{ie(t,n,r);const s=ie(t,n,r,"_index"),o=await le(e,s);if(!o||!Array.isArray(o.items))return console.warn(` No index found for ${n}/${r}, cannot scan for circular references`),console.info(" Tip: Provide specific IDs to check using cleanupCircularHologramsByIds()"),i;for(const l of o.items){i.scanned++;const s=ie(t,n,r,l),o=await le(e,s);if(!o||!0!==o.hologram||!o.target)continue;const c=o.target.holonId,u=o.target.dataId||l,d=o.target.lensName||r,p=ie(o.target.appname||t,c,d,u),h=await le(e,p);if(h&&!0===h.hologram&&h.target&&h.target.holonId===n){i.circularFound++;const o={itemId:l,path:s,pointsTo:`${c}/${d}/${u}`,circularWith:`${h.target.holonId}/${h.target.lensName}/${h.target.dataId}`};if(i.details.push(o),console.warn(" 🔄 Found circular hologram:"),console.warn(` ${n}/${r}/${l} → ${c}/${d}/${u} → ${n}`),!a){const s=await Nt(e,t,n,r,l);s.success?(i.deleted++,console.info(" ✓ Deleted circular hologram")):(i.errors.push({itemId:l,error:s.error}),console.error(` ❌ Failed to delete: ${s.error}`))}}}return console.info(`🧹 Cleanup complete for ${n}/${r}:`),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 It(e,t,n,r,s,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 ${s.length} IDs in ${n}/${r}...`);for(const l of s){o.scanned++;const s=ie(t,n,r,l),a=await le(e,s);if(!a||!0!==a.hologram||!a.target)continue;const c=a.target.holonId,u=a.target.dataId||l,d=a.target.lensName||r,p=ie(a.target.appname||t,c,d,u),h=await le(e,p);if(h&&!0===h.hologram&&h.target&&h.target.holonId===n){o.circularFound++;const a={itemId:l,path:s,pointsTo:`${c}/${d}/${u}`,circularWith:`${h.target.holonId}/${h.target.lensName}/${h.target.dataId}`};if(o.details.push(a),console.warn(` 🔄 Found circular hologram: ${l}`),console.warn(` Chain: ${n} → ${c} → ${n}`),!i){const s=await Nt(e,t,n,r,l);s.success?(o.deleted++,console.info(" ✓ Deleted")):(o.errors.push({itemId:l,error:s.error}),console.error(` ❌ Failed: ${s.error}`))}}}return console.info(`🧹 Cleanup complete: scanned=${o.scanned}, circular=${o.circularFound}, deleted=${o.deleted}`),o}const Ot=Object.freeze(Object.defineProperty({__proto__:null,addActiveHologram:At,cleanupCircularHolograms:Et,cleanupCircularHologramsByIds:It,createHologram:ft,deleteHologram:Nt,getHologramSource:xt,isHologram:_t,isResolvedHologram:Tt,propagateData:wt,refreshActiveHolograms:kt,removeActiveHologram:St,resolveHologram:gt,setupFederation:bt,updateHologramOverrides:vt,wouldCreateCircularHologram:mt},Symbol.toStringTag,{value:"Module"}));function Ct(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 Rt(t){try{return e.nip19.npubEncode(t)}catch(n){return console.error("Failed to encode hex to npub:",n),t}}async function $t(t,n,r){return await e.nip04.encrypt(t,n,r)}async function Mt(t,n,r){return await e.nip04.decrypt(t,n,r)}function Pt(t,n,r,s){const a={kind:t,content:n,tags:r,created_at:Math.floor(Date.now()/1e3)};return e.finalizeEvent(a,Ct(s))}function Ft(e,t,n){return Pt(4,t,[["p",e]],n)}function Dt(){return Date.now().toString(36)+Math.random().toString(36).substring(2,15)}function Ht(t,n){const r={kind:t.kind,content:t.content,tags:t.tags||[],created_at:t.created_at||Math.floor(Date.now()/1e3)};return e.finalizeEvent(r,Ct(n))}function Bt(t){return e.verifyEvent(t)}const jt=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex:function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},createDMEvent:Ft,createSignedEvent:Pt,decryptNIP04:Mt,encryptNIP04:$t,generateNonce:Dt,getPublicKey:function(t){return e.getPublicKey(Ct(t))},hexToBytes:Ct,hexToNpub:Rt,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 r=n;if(r.startsWith("nostr:")&&(r=r.slice(6)),r.startsWith("npub1"))try{const t=e.nip19.decode(r);return"npub"===t.type?{valid:!0,hexPubKey:t.data}:{valid:!1,error:"Invalid npub format"}}catch(s){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:Ht,verifyEvent:Bt},Symbol.toStringTag,{value:"Module"}));function Ut({senderHolonId:e,senderHolonName:t,senderPubKey:n,lensConfig:r={inbound:[],outbound:[]},capabilities:s=[],message:a}){return{type:"federation_request",version:"1.0",requestId:Dt(),timestamp:Date.now(),senderHolonId:e,senderHolonName:t,senderNpub:Rt(n),lensConfig:r,capabilities:s,message:a}}function qt({requestId:e,status:t,responderHolonId:n,responderHolonName:r,responderPubKey:s,lensConfig:a,capabilities:i,message:o}){return{type:"federation_response",version:"1.0",requestId:e,timestamp:Date.now(),status:t,responderHolonId:n,responderHolonName:r,responderNpub:s?Rt(s):void 0,lensConfig:a,capabilities:i,message:o}}async function Lt(e,t,n,r){try{const s=JSON.stringify(r),a=Ft(n,await $t(t,n,s),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(s){return console.error("[Handshake] Failed to send federation request:",s),!1}}async function Jt(e,t,n,r){try{const s=JSON.stringify(r),a=Ft(n,await $t(t,n,s),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(s){return console.error("[Handshake] Failed to send federation response:",s),!1}}const Gt=Object.freeze(Object.defineProperty({__proto__:null,acceptFederationRequest:async function(e,t,n){const{request:r,senderPubKey:s,holonId:a,holonName:i,lensConfig:o={inbound:[],outbound:[]},message:l}=n;try{const{getPublicKeyFromPrivate:n}=await Promise.resolve().then(()=>jt),c=n(t);if(e.client&&(await pt(e.client,e.config.appName,s,{alias:r.senderHolonName,addedVia:"handshake_accepted"}),r.capabilities&&r.capabilities.length>0))for(const t of r.capabilities)await yt(e.client,e.config.appName,s,t);const u=qt({requestId:r.requestId,status:"accepted",responderHolonId:a,responderHolonName:i,responderPubKey:c,lensConfig:o,capabilities:[],message:l});return await Jt(e.client,t,s,u)?{success:!0}:{success:!1,error:"Failed to send response DM"}}catch(c){return{success:!1,error:c.message}}},createFederationRequest:Ut,createFederationResponse:qt,initiateFederationHandshake:async function(e,t,n){const{partnerPubKey:r,holonId:s,holonName:a,lensConfig:i={inbound:[],outbound:[]},message:o}=n;try{const{getPublicKeyFromPrivate:n}=await Promise.resolve().then(()=>jt),l=Ut({senderHolonId:s,senderHolonName:a,senderPubKey:n(t),lensConfig:i,capabilities:[],message:o});e.client&&await pt(e.client,e.config.appName,r,{alias:null,addedVia:"handshake_initiated"});return await Lt(e.client,t,r,l)?{success:!0,requestId:l.requestId}:{success:!1,error:"Failed to send DM"}}catch(l){return{success:!1,error:l.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:r,senderPubKey:s,message:a}=n;try{const n=qt({requestId:r,status:"rejected",message:a}),i=await Jt(e.client,t,s,n);return{success:i,error:i?void 0:"Failed to send response DM"}}catch(i){return{success:!1,error:i.message}}},sendFederationRequest:Lt,sendFederationResponse:Jt,subscribeToFederationDMs:function(e,t,n,r){const{onRequest:s,onResponse:a}=r;let i=!0;const o=new Set,l=async e=>{if(!i)return;if(o.has(e.id))return;if(o.add(e.id),4!==e.kind)return;const r=e.tags?.find(e=>"p"===e[0]);if(r&&r[1]===n)try{const n=await Mt(t,e.pubkey,e.content),r=JSON.parse(n);"federation_request"===r.type&&"1.0"===r.version?(console.log("[Handshake] Received federation request from:",e.pubkey.substring(0,8)+"..."),s?.(r,e.pubkey)):"federation_response"===r.type&&"1.0"===r.version&&(console.log("[Handshake] Received federation response from:",e.pubkey.substring(0,8)+"..."),a?.(r,e.pubkey))}catch(l){}};let c=null;return(async()=>{const t=e?.client;if(!t?.subscribe)return void console.warn("[Handshake] No NostrClient subscribe method available");const r={kinds:[4],"#p":[n],since:Math.floor(Date.now()/1e3)-86400};try{c=await t.subscribe(r,l,{}),console.log("[Handshake] Federation DM subscription started")}catch(s){console.error("[Handshake] Failed to subscribe:",s)}})(),()=>{i=!1,c?.unsubscribe?c.unsubscribe():c?.close&&c.close()}}},Symbol.toStringTag,{value:"Module"}));function zt(e,t=!0,n=!1){if(!e||"object"!=typeof e){if(n)throw new we("ValidationError: Invalid Nostr event format");return!1}if("number"!=typeof e.kind){if(n)throw new we("ValidationError: Invalid Nostr event format - kind must be a number");return!1}if(!Array.isArray(e.tags)){if(n)throw new we("ValidationError: Invalid Nostr event format - tags must be an array");return!1}if("string"!=typeof e.content){if(n)throw new we("ValidationError: Invalid Nostr event format - content must be a string");return!1}if("number"!=typeof e.created_at){if(n)throw new we("ValidationError: Invalid Nostr event format - created_at must be a number");return!1}if(!t){if("string"!=typeof e.id){if(n)throw new we("ValidationError: Invalid Nostr event format - id must be a string");return!1}if("string"!=typeof e.pubkey){if(n)throw new we("ValidationError: Invalid Nostr event format - pubkey must be a string");return!1}if("string"!=typeof e.sig){if(n)throw new we("ValidationError: Invalid Nostr event format - sig must be a string");return!1}}return!0}function Vt(e,t=!1,n=!1){if(!e||"object"!=typeof e){if(t)throw new we("ValidationError: Invalid ActivityPub object format");return!1}if(!e["@context"]){if(t)throw new we("ValidationError: Invalid ActivityPub object format - @context is required");return!1}if("string"!=typeof e.type){if(t)throw new we("ValidationError: Invalid ActivityPub object format - type must be a string");return!1}if(n&&"string"!=typeof e.id){if(t)throw new we("ValidationError: Invalid ActivityPub object format - id must be a string");return!1}return!0}function Kt(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 Wt=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:Kt,transformNostrEvent:function(e){const t=e.id||`nostr-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n=e.pubkey||"anonymous",r=e.sig||"";return{id:t,protocol:"nostr",originalFormat:"nip-01",pubkey:n,sig:r,created_at:e.created_at,kind:e.kind,tags:JSON.stringify(e.tags),content:e.content,signature:r,_meta:{timestamp:1e3*e.created_at,protocol:"nostr"}}},validateActivityPubObject:Vt,validateNostrEvent:zt},Symbol.toStringTag,{value:"Module"}));async function Zt(e,t,n,r={}){const{throttle:s=0,filter:a=null,includeFederated:i=!1,triggerInitial:o=!1,realtimeOnly:l=!0,resolveHolograms:c=!0}=r;let u=0,d=null;const p=new Set;let h=!0;const y=await he(e,t,async(t,r)=>{if(!h)return;const i=`${r}-${t?.id||""}-${t?._meta?.timestamp||Date.now()}`;if(p.has(i))return;p.add(i);let o=t;if(c&&t&&!0===t.hologram)try{if(o=await gt(e,t),!o)return}catch(y){return void console.warn("Failed to resolve hologram in subscription:",y)}if(a&&!a(o,r))return;const l=Date.now();if(s>0&&l-u<s)return d&&clearTimeout(d),void(d=setTimeout(()=>{u=Date.now(),n(o,r)},s-(l-u)));u=l,n(o,r)},{});return{path:t,unsubscribe:()=>{h=!1,d&&clearTimeout(d),y&&y.unsubscribe&&y.unsubscribe(),p.clear()}}}class Yt{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 Xt=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionRegistry:Yt,createSubscription:Zt},Symbol.toStringTag,{value:"Module"}));async function Qt(e,t,n,r,s={}){const{maxLevel:a=3,operation:i="concatenate"}=s,o=e.client,l=e.config.appName;if(!W(t))throw new Error("Upcast only supported for geographic (H3) holons, not noospheric holons");const c=V(t).slice(0,a);if(0===c.length)return!0;const u=c.map(async e=>async function(e,t,n,r,s,a,i){const o=ft(n,0,s,a,t);o._meta.operation=i,o._meta.upcast=!0;const l=`${t}/${r}/${s}/${a}`;return oe(e,l,o)}(o,l,t,e,n,r,i));return await Promise.all(u),!0}const en=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:Qt},Symbol.toStringTag,{value:"Module"})),tn="RFC3986",nn={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},rn=Array.isArray,sn=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),an=1024;function on(e,t){if(rn(e)){const n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const ln=Object.prototype.hasOwnProperty,cn={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},un=Array.isArray,dn=Array.prototype.push,pn=function(e,t){dn.apply(e,un(t)?t:[t])},hn=Date.prototype.toISOString,yn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,n,r,s)=>{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+=an){const e=a.length>=an?a.slice(o,o+an):a,t=[];for(let n=0;n<e.length;++n){let r=e.charCodeAt(n);45===r||46===r||95===r||126===r||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||"RFC1738"===s&&(40===r||41===r)?t[t.length]=e.charAt(n):r<128?t[t.length]=sn[r]:r<2048?t[t.length]=sn[192|r>>6]+sn[128|63&r]:r<55296||r>=57344?t[t.length]=sn[224|r>>12]+sn[128|r>>6&63]+sn[128|63&r]:(n+=1,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),t[t.length]=sn[240|r>>18]+sn[128|r>>12&63]+sn[128|r>>6&63]+sn[128|63&r])}i+=t.join("")}return i},encodeValuesOnly:!1,format:tn,formatter:nn[tn],indices:!1,serializeDate:e=>hn.call(e),skipNulls:!1,strictNullHandling:!1};const mn={};function fn(e,t,n,r,s,a,i,o,l,c,u,d,p,h,y,m,f,g){let b=e,w=g,v=0,_=!1;for(;void 0!==(w=w.get(mn))&&!_;){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(mn)&&(v=0)}if("function"==typeof c?b=c(t,b):b instanceof Date?b=p?.(b):"comma"===n&&un(b)&&(b=on(b,function(e){return e instanceof Date?p?.(e):e})),null===b){if(a)return l&&!m?l(t,yn.encoder,f,"key",h):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(l){const e=m?t:l(t,yn.encoder,f,"key",h);return[y?.(e)+"="+y?.(l(b,yn.encoder,f,"value",h))]}return[y?.(t)+"="+y?.(String(b))]}var T;const x=[];if(void 0===b)return x;let A;if("comma"===n&&un(b))m&&l&&(b=on(b,l)),A=[{value:b.length>0?b.join(",")||null:void 0}];else if(un(c))A=c;else{const e=Object.keys(b);A=u?e.sort(u):e}const S=o?String(t).replace(/\./g,"%2E"):String(t),k=r&&un(b)&&1===b.length?S+"[]":S;if(s&&un(b)&&0===b.length)return k+"[]";for(let N=0;N<A.length;++N){const t=A[N],w="object"==typeof t&&void 0!==t.value?t.value:b[t];if(i&&null===w)continue;const _=d&&o?t.replace(/\./g,"%2E"):t,T=un(b)?"function"==typeof n?n(k,_):k:k+(d?"."+_:"["+_+"]");g.set(e,v);const S=new WeakMap;S.set(mn,g),pn(x,fn(w,T,n,r,s,a,i,o,"comma"===n&&m&&un(b)?null:l,c,u,d,p,h,y,m,f,S))}return x}function gn(e,t={}){let n=e;const r=function(e=yn){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||yn.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=tn;if(void 0!==e.format){if(!ln.call(nn,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const r=nn[n];let s,a=yn.filter;if(("function"==typeof e.filter||un(e.filter))&&(a=e.filter),s=e.arrayFormat&&e.arrayFormat in cn?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":yn.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||yn.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:yn.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:yn.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:yn.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?yn.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:yn.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:yn.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:yn.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:yn.encodeValuesOnly,filter:a,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:yn.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:yn.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:yn.strictNullHandling}}(t);let s,a;"function"==typeof r.filter?(a=r.filter,n=a("",n)):un(r.filter)&&(a=r.filter,s=a);const i=[];if("object"!=typeof n||null===n)return"";const o=cn[r.arrayFormat],l="comma"===o&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const c=new WeakMap;for(let p=0;p<s.length;++p){const e=s[p];r.skipNulls&&null===n[e]||pn(i,fn(n[e],e,o,l,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}const u=i.join(r.delimiter);let d=!0===r.addQueryPrefix?"?":"";return r.charsetSentinel&&("iso-8859-1"===r.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}const bn="4.104.0";let wn,vn,_n,Tn,xn,An,Sn,kn,Nn,En=!1;class In{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}const On=()=>{wn||function(e,t={auto:!1}){if(En)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(wn)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${wn}'\``);En=t.auto,wn=e.kind,vn=e.fetch,_n=e.FormData,Tn=e.File,xn=e.ReadableStream,An=e.getMultipartRequestOptions,Sn=e.getDefaultAgent,kn=e.fileFromPath,Nn=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,r,s,a;try{n=fetch,r=Request,s=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:r,Response:s,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 In(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})};On();class Cn extends Error{}class Rn extends Cn{constructor(e,t,n,r){super(`${Rn.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.request_id=r?.["x-request-id"],this.error=t;const s=t;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new Mn({message:n,cause:Cr(t)});const s=t?.error;return 400===e?new Fn(e,s,n,r):401===e?new Dn(e,s,n,r):403===e?new Hn(e,s,n,r):404===e?new Bn(e,s,n,r):409===e?new jn(e,s,n,r):422===e?new Un(e,s,n,r):429===e?new qn(e,s,n,r):e>=500?new Ln(e,s,n,r):new Rn(e,s,n,r)}}class $n extends Rn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Mn extends Rn{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Pn extends Mn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Fn extends Rn{}class Dn extends Rn{}class Hn extends Rn{}class Bn extends Rn{}class jn extends Rn{}class Un extends Rn{}class qn extends Rn{}class Ln extends Rn{}class Jn extends Cn{constructor(){super("Could not parse response content as the length limit was reached")}}class Gn extends Cn{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var zn,Vn=function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},Kn=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Wn{constructor(){zn.set(this,void 0),this.buffer=new Uint8Array,Vn(this,zn,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 r=[];let s;for(;null!=(s=Zn(this.buffer,Kn(this,zn,"f")));){if(s.carriage&&null==Kn(this,zn,"f")){Vn(this,zn,s.index,"f");continue}if(null!=Kn(this,zn,"f")&&(s.index!==Kn(this,zn,"f")+1||s.carriage)){r.push(this.decodeText(this.buffer.slice(0,Kn(this,zn,"f")-1))),this.buffer=this.buffer.slice(Kn(this,zn,"f")),Vn(this,zn,null,"f");continue}const e=null!==Kn(this,zn,"f")?s.preceding-1:s.preceding,t=this.decodeText(this.buffer.slice(0,e));r.push(t),this.buffer=this.buffer.slice(s.index),Vn(this,zn,null,"f")}return r}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 Cn(`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 Cn(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Cn("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function Zn(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 Yn(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 Xn(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}}}zn=new WeakMap,Wn.NEWLINE_CHARS=new Set(["\n","\r"]),Wn.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class Qn{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;return new Qn(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let r=!1;try{for await(const n of async function*(e,t){if(!e.body)throw t.abort(),new Cn("Attempted to iterate over a response with no body");const n=new er,r=new Wn,s=Xn(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 r,s=new Uint8Array(t.length+e.length);for(s.set(t),s.set(e,t.length),t=s;-1!==(r=Yn(t));)yield t.slice(0,r),t=t.slice(r)}t.length>0&&(yield t)}(s))for(const e of r.decode(a)){const t=n.decode(e);t&&(yield t)}for(const a of r.flush()){const e=n.decode(a);e&&(yield e)}}(e,t))if(!r)if(n.data.startsWith("[DONE]"))r=!0;else if(null===n.event||n.event.startsWith("response.")||n.event.startsWith("transcript.")){let t;try{t=JSON.parse(n.data)}catch(s){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),s}if(t&&t.error)throw new Rn(void 0,t.error,void 0,br(e.headers));yield t}else{let e;try{e=JSON.parse(n.data)}catch(s){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),s}if("error"==n.event)throw new Rn(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}r=!0}catch(s){if(s instanceof Error&&"AbortError"===s.name)return;throw s}finally{r||t.abort()}},t)}static fromReadableStream(e,t){let n=!1;return new Qn(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let r=!1;try{for await(const t of async function*(){const t=new Wn,n=Xn(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())r||t&&(yield JSON.parse(t));r=!0}catch(s){if(s instanceof Error&&"AbortError"===s.name)return;throw s}finally{r||t.abort()}},t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=r=>({next:()=>{if(0===r.length){const r=n.next();e.push(r),t.push(r)}return r.shift()}});return[new Qn(()=>r(e),this.controller),new Qn(()=>r(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new xn({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:r,done:s}=await t.next();if(s)return e.close();const a=n.encode(JSON.stringify(r)+"\n");e.enqueue(a)}catch(r){e.error(r)}},async cancel(){await(t.return?.())}})}}class er{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,r]=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 r.startsWith(" ")&&(r=r.substring(1)),"event"===t?this.event=r:"data"===t&&this.data.push(r),null}}const tr=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,nr=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&rr(e),rr=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 sr(e,t,n){if(e=await e,nr(e))return e;if(tr(e)){const r=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const s=rr(r)?[await r.arrayBuffer()]:[r];return new Tn(s,t,n)}const r=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(rr(e))t.push(await e.arrayBuffer());else{if(!ir(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 ar(e.name)||ar(e.filename)||ar(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!n?.type){const e=r[0]?.type;"string"==typeof e&&(n={...n,type:e})}return new Tn(r,t,n)}const ar=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,ir=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],or=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],lr=async e=>{const t=await cr(e.body);return An(t,e)},cr=async e=>{const t=new _n;return await Promise.all(Object.entries(e||{}).map(([e,n])=>ur(t,e,n))),t},ur=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=>nr(e)||tr(e)||Nn(e))(n)){const r=await sr(n);e.append(t,r)}else if(Array.isArray(n))await Promise.all(n.map(n=>ur(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,r])=>ur(e,`${t}[${n}]`,r)))}}};var dr;async function pr(e){const{response:t}=e;if(e.options.stream)return Dr("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Qn.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const n=t.headers.get("content-type"),r=n?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){const e=await t.json();return Dr("response",t.status,t.url,t.headers,e),hr(e,t)}const s=await t.text();return Dr("response",t.status,t.url,t.headers,s),s}function hr(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})}On();class yr extends Promise{constructor(e,t=pr){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new yr(this.responsePromise,async t=>hr(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 mr{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:r,fetch:s}){this.baseURL=e,this.maxRetries=Or("maxRetries",t),this.timeout=Or("timeout",n),this.httpAgent=r,this.fetch=s??vn}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Sr(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}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 r=n&&rr(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:r}}))}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:r,path:s,query:a,headers:i={}}=n,o=ArrayBuffer.isView(n.body)||n.__binaryRequest&&"string"==typeof n.body?n.body:or(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,l=this.calculateContentLength(o),c=this.buildURL(s,a);"timeout"in n&&Or("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const u=n.httpAgent??this.httpAgent??Sn(c),d=n.timeout+1e3;"number"==typeof u?.options?.timeout&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:r,...o&&{body:o},headers:this.buildHeaders({options:n,headers:i,contentLength:l,retryCount:t}),...u&&{agent:u},signal:n.signal??null},url:c,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:r}){const s={};n&&(s["content-length"]=n);const a=this.defaultHeaders(e);return Pr(s,a),Pr(s,t),or(e.body)&&"node"!==wn&&delete s["content-type"],void 0===Br(a,"x-stainless-retry-count")&&void 0===Br(t,"x-stainless-retry-count")&&(s["x-stainless-retry-count"]=String(r)),void 0===Br(a,"x-stainless-timeout")&&void 0===Br(t,"x-stainless-timeout")&&e.timeout&&(s["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(s,t),s}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,r){return Rn.generate(e,t,n,r)}request(e,t=null){return new yr(this.makeRequest(e,t))}async makeRequest(e,t){const n=await e,r=n.maxRetries??this.maxRetries;null==t&&(t=r),await this.prepareOptions(n);const{req:s,url:a,timeout:i}=this.buildRequest(n,{retryCount:r-t});if(await this.prepareRequest(s,{url:a,options:n}),Dr("request",a,n,s.headers),n.signal?.aborted)throw new $n;const o=new AbortController,l=await this.fetchWithTimeout(a,s,i,o).catch(Cr);if(l instanceof Error){if(n.signal?.aborted)throw new $n;if(t)return this.retryRequest(n,t);if("AbortError"===l.name)throw new Pn;throw new Mn({cause:l})}const c=br(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){return Dr(`response (error; ${`retrying, ${t} attempts remaining`})`,l.status,a,c),this.retryRequest(n,t,c)}const e=await l.text().catch(e=>Cr(e).message),r=kr(e),s=r?void 0:e;Dr(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,a,c,s);throw this.makeStatusError(l.status,r,s,c)}return{response:l,options:n,controller:o}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new gr(this,n,e)}buildURL(e,t){const n=Er(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery();return $r(r)||(t={...r,...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 Cn(`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,r){const{signal:s,...a}=t||{};s&&s.addEventListener("abort",()=>r.abort());const i=setTimeout(()=>r.abort(),n),o={signal:r.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 r;const s=n?.["retry-after-ms"];if(s){const e=parseFloat(s);Number.isNaN(e)||(r=e)}const a=n?.["retry-after"];if(a&&!r){const e=parseFloat(a);r=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(r&&0<=r&&r<6e4)){const n=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Ir(r),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 ${bn}`}}class fr{constructor(e,t,n,r){dr.set(this,void 0),function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?s.call(e,n):s?s.value=n:t.set(e,n)}(this,dr,e,"f"),this.options=r,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new Cn("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,r]of n)e.url.searchParams.set(t,r);t.query=void 0,t.path=e.url.toString()}return await function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,dr,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(dr=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class gr extends yr{constructor(e,t,n){super(t,async t=>new n(e,t.response,await pr(t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const br=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),wr={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},vr=e=>"object"==typeof e&&null!==e&&!$r(e)&&Object.keys(e).every(e=>Mr(wr,e)),_r=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bn,"X-Stainless-OS":xr(Deno.build.os),"X-Stainless-Arch":Tr(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":bn,"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":bn,"X-Stainless-OS":xr(process.platform),"X-Stainless-Arch":Tr(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":bn,"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":bn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Tr=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",xr=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 Ar;const Sr=()=>Ar??(Ar=_r()),kr=e=>{try{return JSON.parse(e)}catch(t){return}},Nr=/^[a-z][a-z0-9+.-]*:/i,Er=e=>Nr.test(e),Ir=e=>new Promise(t=>setTimeout(t,e)),Or=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Cn(`${e} must be an integer`);if(t<0)throw new Cn(`${e} must be a positive integer`);return t},Cr=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)},Rr=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function $r(e){if(!e)return!0;for(const t in e)return!1;return!0}function Mr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Pr(e,t){for(const n in t){if(!Mr(t,n))continue;const r=n.toLowerCase();if(!r)continue;const s=t[n];null===s?delete e[r]:void 0!==s&&(e[r]=s)}}const Fr=new Set(["authorization","api-key"]);function Dr(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)Fr.has(n.toLowerCase())&&(t.headers[n]="REDACTED");return t}let t=null;for(const n in e)Fr.has(n.toLowerCase())&&(t??(t={...e}),t[n]="REDACTED");return t??e});console.log(`OpenAI:DEBUG:${e}`,...n)}}const Hr=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),Br=(e,t)=>{const n=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const r=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,(e,t,n)=>t+n.toUpperCase());for(const s of[t,n,t.toUpperCase(),r]){const t=e.get(s);if(t)return t}}for(const[r,s]of Object.entries(e))if(r.toLowerCase()===n)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${t} header, using the first entry.`),s[0]):s};function jr(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class Ur extends fr{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class qr extends fr{constructor(e,t,n,r){super(e,t,n,r),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 Lr{constructor(e){this._client=e}}let Jr=class extends Lr{list(e,t={},n){return vr(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Vr,{query:t,...n})}},Gr=class extends Lr{constructor(){super(...arguments),this.messages=new Jr(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 vr(e)?this.list({},e):this._client.getAPIList("/chat/completions",zr,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class zr extends qr{}class Vr extends qr{}Gr.ChatCompletionsPage=zr,Gr.Messages=Jr;let Kr=class extends Lr{constructor(){super(...arguments),this.completions=new Gr(this._client)}};Kr.Completions=Gr,Kr.ChatCompletionsPage=zr;class Wr extends Lr{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class Zr extends Lr{create(e,t){return this._client.post("/audio/transcriptions",lr({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Yr extends Lr{create(e,t){return this._client.post("/audio/translations",lr({body:e,...t,__metadata:{model:e.model}}))}}class Xr extends Lr{constructor(){super(...arguments),this.transcriptions=new Zr(this._client),this.translations=new Yr(this._client),this.speech=new Wr(this._client)}}Xr.Transcriptions=Zr,Xr.Translations=Yr,Xr.Speech=Wr;class Qr extends Lr{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 vr(e)?this.list({},e):this._client.getAPIList("/batches",es,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class es extends qr{}Qr.BatchesPage=es;var ts,ns,rs,ss,as,is,os,ls,cs,us,ds,ps,hs,ys=function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},ms=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class fs{constructor(){ts.add(this),this.controller=new AbortController,ns.set(this,void 0),rs.set(this,()=>{}),ss.set(this,()=>{}),as.set(this,void 0),is.set(this,()=>{}),os.set(this,()=>{}),ls.set(this,{}),cs.set(this,!1),us.set(this,!1),ds.set(this,!1),ps.set(this,!1),ys(this,ns,new Promise((e,t)=>{ys(this,rs,e,"f"),ys(this,ss,t,"f")}),"f"),ys(this,as,new Promise((e,t)=>{ys(this,is,e,"f"),ys(this,os,t,"f")}),"f"),ms(this,ns,"f").catch(()=>{}),ms(this,as,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ms(this,ts,"m",hs).bind(this))},0)}_connected(){this.ended||(ms(this,rs,"f").call(this),this._emit("connect"))}get ended(){return ms(this,cs,"f")}get errored(){return ms(this,us,"f")}get aborted(){return ms(this,ds,"f")}abort(){this.controller.abort()}on(e,t){return(ms(this,ls,"f")[e]||(ms(this,ls,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=ms(this,ls,"f")[e];if(!n)return this;const r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(ms(this,ls,"f")[e]||(ms(this,ls,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{ys(this,ps,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)})}async done(){ys(this,ps,!0,"f"),await ms(this,as,"f")}_emit(e,...t){if(ms(this,cs,"f"))return;"end"===e&&(ys(this,cs,!0,"f"),ms(this,is,"f").call(this));const n=ms(this,ls,"f")[e];if(n&&(ms(this,ls,"f")[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return ms(this,ps,"f")||n?.length||Promise.reject(e),ms(this,ss,"f").call(this,e),ms(this,os,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];ms(this,ps,"f")||n?.length||Promise.reject(e),ms(this,ss,"f").call(this,e),ms(this,os,"f").call(this,e),this._emit("end")}}_emitFinal(){}}ns=new WeakMap,rs=new WeakMap,ss=new WeakMap,as=new WeakMap,is=new WeakMap,os=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,ps=new WeakMap,ts=new WeakSet,hs=function(e){if(ys(this,us,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new $n),e instanceof $n)return ys(this,ds,!0,"f"),this._emit("abort",e);if(e instanceof Cn)return this._emit("error",e);if(e instanceof Error){const t=new Cn(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Cn(String(e)))};var gs,bs,ws,vs,_s,Ts,xs,As,Ss,ks,Ns,Es,Is,Os,Cs,Rs,$s,Ms,Ps,Fs,Ds,Hs,Bs=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)},js=function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n};class Us extends fs{constructor(){super(...arguments),gs.add(this),bs.set(this,[]),ws.set(this,{}),vs.set(this,{}),_s.set(this,void 0),Ts.set(this,void 0),xs.set(this,void 0),As.set(this,void 0),Ss.set(this,void 0),ks.set(this,void 0),Ns.set(this,void 0),Es.set(this,void 0),Is.set(this,void 0)}[(bs=new WeakMap,ws=new WeakMap,vs=new WeakMap,_s=new WeakMap,Ts=new WeakMap,xs=new WeakMap,As=new WeakMap,Ss=new WeakMap,ks=new WeakMap,Ns=new WeakMap,Es=new WeakMap,Is=new WeakMap,gs=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const r=t.shift();r?r.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 Us;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 r=Qn.fromReadableStream(e,this.controller);for await(const s of r)Bs(this,gs,"m",Os).call(this,s);if(r.controller.signal?.aborted)throw new $n;return this._addRun(Bs(this,gs,"m",Cs).call(this))}toReadableStream(){return new Qn(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r,s){const a=new Us;return a._run(()=>a._runToolAssistantStream(e,t,n,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.submitToolOutputs(t,n,i,{...s,signal:this.controller.signal});this._connected();for await(const l of o)Bs(this,gs,"m",Os).call(this,l);if(o.controller.signal?.aborted)throw new $n;return this._addRun(Bs(this,gs,"m",Cs).call(this))}static createThreadAssistantStream(e,t,n){const r=new Us;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,n,r){const s=new Us;return s._run(()=>s._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return Bs(this,Ns,"f")}currentRun(){return Bs(this,Es,"f")}currentMessageSnapshot(){return Bs(this,_s,"f")}currentRunStepSnapshot(){return Bs(this,Is,"f")}async finalRunSteps(){return await this.done(),Object.values(Bs(this,ws,"f"))}async finalMessages(){return await this.done(),Object.values(Bs(this,vs,"f"))}async finalRun(){if(await this.done(),!Bs(this,Ts,"f"))throw Error("Final run was not received.");return Bs(this,Ts,"f")}async _createThreadAssistantStream(e,t,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const s={...t,stream:!0},a=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(const i of a)Bs(this,gs,"m",Os).call(this,i);if(a.controller.signal?.aborted)throw new $n;return this._addRun(Bs(this,gs,"m",Cs).call(this))}async _createAssistantStream(e,t,n,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(const o of i)Bs(this,gs,"m",Os).call(this,o);if(i.controller.signal?.aborted)throw new $n;return this._addRun(Bs(this,gs,"m",Cs).call(this))}static accumulateDelta(e,t){for(const[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof r)t+=r;else if("number"==typeof t&&"number"==typeof r)t+=r;else{if(!jr(t)||!jr(r)){if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...r);continue}for(const e of r){if(!jr(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 r=t[n];null==r?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`)}t=this.accumulateDelta(t,r)}e[n]=t}else e[n]=r;else e[n]=r}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r,s){return await this._createToolAssistantStream(n,e,t,r,s)}}Os=function(e){if(!this.ended)switch(js(this,Ns,e,"f"),Bs(this,gs,"m",Ms).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":Bs(this,gs,"m",Hs).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":Bs(this,gs,"m",$s).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":Bs(this,gs,"m",Rs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Cs=function(){if(this.ended)throw new Cn("stream has ended, this shouldn't happen");if(!Bs(this,Ts,"f"))throw Error("Final run has not been received");return Bs(this,Ts,"f")},Rs=function(e){const[t,n]=Bs(this,gs,"m",Fs).call(this,e,Bs(this,_s,"f"));js(this,_s,t,"f"),Bs(this,vs,"f")[t.id]=t;for(const r of n){const e=t.content[r.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,r=t.content[n.index];if(!r||"text"!=r.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,r.text)}if(n.index!=Bs(this,xs,"f")){if(Bs(this,As,"f"))switch(Bs(this,As,"f").type){case"text":this._emit("textDone",Bs(this,As,"f").text,Bs(this,_s,"f"));break;case"image_file":this._emit("imageFileDone",Bs(this,As,"f").image_file,Bs(this,_s,"f"))}js(this,xs,n.index,"f")}js(this,As,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Bs(this,xs,"f")){const t=e.data.content[Bs(this,xs,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Bs(this,_s,"f"));break;case"text":this._emit("textDone",t.text,Bs(this,_s,"f"))}}Bs(this,_s,"f")&&this._emit("messageDone",e.data),js(this,_s,void 0,"f")}},$s=function(e){const t=Bs(this,gs,"m",Ps).call(this,e);switch(js(this,Is,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==Bs(this,Ss,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Bs(this,ks,"f")&&this._emit("toolCallDone",Bs(this,ks,"f")),js(this,Ss,e.index,"f"),js(this,ks,t.step_details.tool_calls[e.index],"f"),Bs(this,ks,"f")&&this._emit("toolCallCreated",Bs(this,ks,"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":js(this,Is,void 0,"f");"tool_calls"==e.data.step_details.type&&Bs(this,ks,"f")&&(this._emit("toolCallDone",Bs(this,ks,"f")),js(this,ks,void 0,"f")),this._emit("runStepDone",e.data,t)}},Ms=function(e){Bs(this,bs,"f").push(e),this._emit("event",e)},Ps=function(e){switch(e.event){case"thread.run.step.created":return Bs(this,ws,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Bs(this,ws,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const r=Us.accumulateDelta(t,n.delta);Bs(this,ws,"f")[e.data.id]=r}return Bs(this,ws,"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":Bs(this,ws,"f")[e.data.id]=e.data}if(Bs(this,ws,"f")[e.data.id])return Bs(this,ws,"f")[e.data.id];throw new Error("No snapshot available")},Fs=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 r=e.data;if(r.delta.content)for(const e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=Bs(this,gs,"m",Ds).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")},Ds=function(e,t){return Us.accumulateDelta(t,e)},Hs=function(e){switch(js(this,Es,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":js(this,Ts,e.data,"f"),Bs(this,ks,"f")&&(this._emit("toolCallDone",Bs(this,ks,"f")),js(this,ks,void 0,"f"))}};class qs extends Lr{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 vr(e)?this.list({},e):this._client.getAPIList("/assistants",Ls,{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 Ls extends qr{}function Js(e){return"function"==typeof e.parse}qs.AssistantsPage=Ls;const Gs=e=>"assistant"===e?.role,zs=e=>"function"===e?.role,Vs=e=>"tool"===e?.role;function Ks(e){return"auto-parseable-response-format"===e?.$brand}function Ws(e){return"auto-parseable-tool"===e?.$brand}function Zs(e,t){const n=e.choices.map(e=>{if("length"===e.finish_reason)throw new Jn;if("content_filter"===e.finish_reason)throw new Gn;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:Ws(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?Ys(t,e.message.content):null}}});return{...e,choices:n}}function Ys(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 Xs(e,t){if(!e)return!1;const n=e.tools?.find(e=>e.function?.name===t.function.name);return Ws(n)||n?.function.strict||!1}function Qs(e){return!!Ks(e.response_format)||(e.tools?.some(e=>Ws(e)||"function"===e.type&&!0===e.function.strict)??!1)}var ea,ta,na,ra,sa,aa,ia,oa,la=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};const ca=10;class ua extends fs{constructor(){super(...arguments),ea.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),(zs(e)||Vs(e))&&e.content)this._emit("functionCallResult",e.content);else if(Gs(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Gs(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 Cn("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),la(this,ea,"m",ta).call(this)}async finalMessage(){return await this.done(),la(this,ea,"m",na).call(this)}async finalFunctionCall(){return await this.done(),la(this,ea,"m",ra).call(this)}async finalFunctionCallResult(){return await this.done(),la(this,ea,"m",sa).call(this)}async totalUsage(){return await this.done(),la(this,ea,"m",aa).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=la(this,ea,"m",na).call(this);t&&this._emit("finalMessage",t);const n=la(this,ea,"m",ta).call(this);n&&this._emit("finalContent",n);const r=la(this,ea,"m",ra).call(this);r&&this._emit("finalFunctionCall",r);const s=la(this,ea,"m",sa).call(this);null!=s&&this._emit("finalFunctionCallResult",s),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",la(this,ea,"m",aa).call(this))}async _createChatCompletion(e,t,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),la(this,ea,"m",ia).call(this,t);const s=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Zs(s,t))}async _runChatCompletion(e,t,n){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){const r="function",{function_call:s="auto",stream:a,...i}=t,o="string"!=typeof s&&s?.name,{maxChatCompletions:l=ca}=n||{},c={};for(const p of t.functions)c[p.name||p.function.name]=p;const u=t.functions.map(e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description}));for(const p of t.messages)this._addMessage(p,!1);for(let p=0;p<l;++p){const t=await this._createChatCompletion(e,{...i,function_call:s,functions:u,messages:[...this.messages]},n),a=t.choices[0]?.message;if(!a)throw new Cn("missing message in ChatCompletion response");if(!a.function_call)return;const{name:l,arguments:p}=a.function_call,h=c[l];if(!h){const e=`Invalid function_call: ${JSON.stringify(l)}. Available options are: ${u.map(e=>JSON.stringify(e.name)).join(", ")}. Please try again`;this._addMessage({role:r,name:l,content:e});continue}if(o&&o!==l){const e=`Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:r,name:l,content:e});continue}let y;try{y=Js(h)?await h.parse(p):p}catch(d){this._addMessage({role:r,name:l,content:d instanceof Error?d.message:String(d)});continue}const m=await h.function(y,this),f=la(this,ea,"m",oa).call(this,m);if(this._addMessage({role:r,name:l,content:f}),o)return}}async _runTools(e,t,n){const r="tool",{tool_choice:s="auto",stream:a,...i}=t,o="string"!=typeof s&&s?.function?.name,{maxChatCompletions:l=ca}=n||{},c=t.tools.map(e=>{if(Ws(e)){if(!e.$callback)throw new Cn("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}),u={};for(const h of c)"function"===h.type&&(u[h.function.name||h.function.function.name]=h.function);const d="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 h of t.messages)this._addMessage(h,!1);for(let h=0;h<l;++h){const t=await this._createChatCompletion(e,{...i,tool_choice:s,tools:d,messages:[...this.messages]},n),a=t.choices[0]?.message;if(!a)throw new Cn("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:s}=e.function,a=u[n];if(!a){const e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:r,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:r,tool_call_id:t,content:e});continue}let i;try{i=Js(a)?await a.parse(s):s}catch(p){const e=p instanceof Error?p.message:String(p);this._addMessage({role:r,tool_call_id:t,content:e});continue}const l=await a.function(i,this),c=la(this,ea,"m",oa).call(this,l);if(this._addMessage({role:r,tool_call_id:t,content:c}),o)return}}}}ea=new WeakSet,ta=function(){return la(this,ea,"m",na).call(this).content??null},na=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Gs(t)){const{function_call:e,...n}=t,r={...n,content:t.content??null,refusal:t.refusal??null};return e&&(r.function_call=e),r}}throw new Cn("stream ended without producing a ChatCompletionMessage with role=assistant")},ra=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Gs(t)&&t?.function_call)return t.function_call;if(Gs(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},sa=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(zs(t)&&null!=t.content)return t.content;if(Vs(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}},aa=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},ia=function(e){if(null!=e.n&&e.n>1)throw new Cn("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},oa=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class da extends ua{static runFunctions(e,t,n){const r=new da,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return r._run(()=>r._runFunctions(e,t,s)),r}static runTools(e,t,n){const r=new da,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,s)),r}_addMessage(e,t=!0){super._addMessage(e,t),Gs(e)&&e.content&&this._emit("content",e.content)}}const pa=1,ha=2,ya=4,ma=8,fa=16,ga=32,ba=64,wa=128,va=256,_a=511;class Ta extends Error{}class xa extends Error{}const Aa=(e,t)=>{const n=e.length;let r=0;const s=e=>{throw new Ta(`${e} at position ${r}`)},a=e=>{throw new xa(`${e} at position ${r}`)},i=()=>(d(),r>=n&&s("Unexpected end of input"),'"'===e[r]?o():"{"===e[r]?l():"["===e[r]?c():"null"===e.substring(r,r+4)||fa&t&&n-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):"true"===e.substring(r,r+4)||ga&t&&n-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):"false"===e.substring(r,r+5)||ga&t&&n-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):"Infinity"===e.substring(r,r+8)||wa&t&&n-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):"-Infinity"===e.substring(r,r+9)||va&t&&1<n-r&&n-r<9&&"-Infinity".startsWith(e.substring(r))?(r+=9,-1/0):"NaN"===e.substring(r,r+3)||ba&t&&n-r<3&&"NaN".startsWith(e.substring(r))?(r+=3,NaN):u()),o=()=>{const i=r;let o=!1;for(r++;r<n&&('"'!==e[r]||o&&"\\"===e[r-1]);)o="\\"===e[r]&&!o,r++;if('"'==e.charAt(r))try{return JSON.parse(e.substring(i,++r-Number(o)))}catch(l){a(String(l))}else if(pa&t)try{return JSON.parse(e.substring(i,r-Number(o))+'"')}catch(l){return JSON.parse(e.substring(i,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},l=()=>{r++,d();const a={};try{for(;"}"!==e[r];){if(d(),r>=n&&ma&t)return a;const s=o();d(),r++;try{const e=i();Object.defineProperty(a,s,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(l){if(ma&t)return a;throw l}d(),","===e[r]&&r++}}catch(l){if(ma&t)return a;s("Expected '}' at end of object")}return r++,a},c=()=>{r++;const n=[];try{for(;"]"!==e[r];)n.push(i()),d(),","===e[r]&&r++}catch(a){if(ya&t)return n;s("Expected ']' at end of array")}return r++,n},u=()=>{if(0===r){"-"===e&&ha&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(o){if(ha&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(l){}a(String(o))}}const i=r;for("-"===e[r]&&r++;e[r]&&!",]}".includes(e[r]);)r++;r!=n||ha&t||s("Unterminated number literal");try{return JSON.parse(e.substring(i,r))}catch(o){"-"===e.substring(i,r)&&ha&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(l){a(String(l))}}},d=()=>{for(;r<n&&" \n\r\t".includes(e[r]);)r++};return i()},Sa=e=>function(e,t=_a){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return Aa(e.trim(),t)}(e,_a^ha);var ka,Na,Ea,Ia,Oa,Ca,Ra,$a,Ma,Pa,Fa,Da,Ha=function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},Ba=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class ja extends ua{constructor(e){super(),ka.add(this),Na.set(this,void 0),Ea.set(this,void 0),Ia.set(this,void 0),Ha(this,Na,e,"f"),Ha(this,Ea,[],"f")}get currentChatCompletionSnapshot(){return Ba(this,Ia,"f")}static fromReadableStream(e){const t=new ja(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const r=new ja(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,n){super._createChatCompletion;const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),Ba(this,ka,"m",Oa).call(this);const s=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const a of s)Ba(this,ka,"m",Ra).call(this,a);if(s.controller.signal?.aborted)throw new $n;return this._addChatCompletion(Ba(this,ka,"m",Pa).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ba(this,ka,"m",Oa).call(this),this._connected();const r=Qn.fromReadableStream(e,this.controller);let s;for await(const a of r)s&&s!==a.id&&this._addChatCompletion(Ba(this,ka,"m",Pa).call(this)),Ba(this,ka,"m",Ra).call(this,a),s=a.id;if(r.controller.signal?.aborted)throw new $n;return this._addChatCompletion(Ba(this,ka,"m",Pa).call(this))}[(Na=new WeakMap,Ea=new WeakMap,Ia=new WeakMap,ka=new WeakSet,Oa=function(){this.ended||Ha(this,Ia,void 0,"f")},Ca=function(e){let t=Ba(this,Ea,"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},Ba(this,Ea,"f")[e.index]=t,t)},Ra=function(e){if(this.ended)return;const t=Ba(this,ka,"m",Da).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 r=Ba(this,ka,"m",Ca).call(this,e);e.finish_reason&&(Ba(this,ka,"m",Ma).call(this,e),null!=r.current_tool_call_index&&Ba(this,ka,"m",$a).call(this,e,r.current_tool_call_index));for(const t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(Ba(this,ka,"m",Ma).call(this,e),null!=r.current_tool_call_index&&Ba(this,ka,"m",$a).call(this,e,r.current_tool_call_index)),r.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??""}):qa(n?.type))}}},$a=function(e,t){if(Ba(this,ka,"m",Ca).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=Ba(this,Na,"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:Ws(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},Ma=function(e){const t=Ba(this,ka,"m",Ca).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=Ba(this,ka,"m",Fa).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}))},Pa=function(){if(this.ended)throw new Cn("stream has ended, this shouldn't happen");const e=Ba(this,Ia,"f");if(!e)throw new Cn("request ended without sending any chunks");return Ha(this,Ia,void 0,"f"),Ha(this,Ea,[],"f"),function(e,t){const{id:n,choices:r,created:s,model:a,system_fingerprint:i,...o}=e,l={...o,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:s,...a})=>{if(!n)throw new Cn(`missing finish_reason for choice ${r}`);const{content:i=null,function_call:o,tool_calls:l,...c}=t,u=t.role;if(!u)throw new Cn(`missing role for choice ${r}`);if(o){const{arguments:e,name:l}=o;if(null==e)throw new Cn(`missing function_call.arguments for choice ${r}`);if(!l)throw new Cn(`missing function_call.name for choice ${r}`);return{...a,message:{content:i,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:s}}return l?{...a,index:r,finish_reason:n,logprobs:s,message:{...c,role:u,content:i,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{const{function:s,type:a,id:i,...o}=t,{arguments:l,name:c,...u}=s||{};if(null==i)throw new Cn(`missing choices[${r}].tool_calls[${n}].id\n${Ua(e)}`);if(null==a)throw new Cn(`missing choices[${r}].tool_calls[${n}].type\n${Ua(e)}`);if(null==c)throw new Cn(`missing choices[${r}].tool_calls[${n}].function.name\n${Ua(e)}`);if(null==l)throw new Cn(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Ua(e)}`);return{...o,id:i,type:a,function:{...u,name:c,arguments:l}}})}}:{...a,message:{...c,content:i,role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:s}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&Qs(t)?Zs(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}}))}}(l,t)}(e,Ba(this,Na,"f"))},Fa=function(){const e=Ba(this,Na,"f")?.response_format;return Ks(e)?e:null},Da=function(e){var t,n,r,s;let a=Ba(this,Ia,"f");const{choices:i,...o}=e;a?Object.assign(a,o):a=Ha(this,Ia,{...o,choices:[]},"f");for(const{delta:l,finish_reason:c,index:u,logprobs:d=null,...p}of e.choices){let e=a.choices[u];if(e||(e=a.choices[u]={finish_reason:c,index:u,message:{},logprobs:d,...p}),d)if(e.logprobs){const{content:r,refusal:s,...a}=d;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),s&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...s))}else e.logprobs=Object.assign({},d);if(c&&(e.finish_reason=c,Ba(this,Na,"f")&&Qs(Ba(this,Na,"f")))){if("length"===c)throw new Jn;if("content_filter"===c)throw new Gn}if(Object.assign(e,p),!l)continue;const{content:i,refusal:o,function_call:h,role:y,tool_calls:m,...f}=l;if(Object.assign(e.message,f),o&&(e.message.refusal=(e.message.refusal||"")+o),y&&(e.message.role=y),h&&(e.message.function_call?(h.name&&(e.message.function_call.name=h.name),h.arguments&&((r=e.message.function_call).arguments??(r.arguments=""),e.message.function_call.arguments+=h.arguments)):e.message.function_call=h),i&&(e.message.content=(e.message.content||"")+i,!e.message.refusal&&Ba(this,ka,"m",Fa).call(this)&&(e.message.parsed=Sa(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:r,function:a,...i}of m){const o=(s=e.message.tool_calls)[t]??(s[t]={});Object.assign(o,i),n&&(o.id=n),r&&(o.type=r),a&&(o.function??(o.function={name:a.name??"",arguments:""})),a?.name&&(o.function.name=a.name),a?.arguments&&(o.function.arguments+=a.arguments,Xs(Ba(this,Na,"f"),o)&&(o.function.parsed_arguments=Sa(o.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",n=>{const r=t.shift();r?r.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 Qn(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Ua(e){return JSON.stringify(e)}function qa(e){}class La extends ja{static fromReadableStream(e){const t=new La(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const r=new La(null),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return r._run(()=>r._runFunctions(e,t,s)),r}static runTools(e,t,n){const r=new La(t),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,s)),r}}let Ja=class extends Lr{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new Cn(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new Cn(`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=>Zs(t,e))}runFunctions(e,t){return e.stream?La.runFunctions(this._client,e,t):da.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?La.runTools(this._client,e,t):da.runTools(this._client,e,t)}stream(e,t){return ja.createChatCompletion(this._client,e,t)}};class Ga extends Lr{constructor(){super(...arguments),this.completions=new Ja(this._client)}}(Ga||(Ga={})).Completions=Ja;class za extends Lr{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Va extends Lr{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Ka extends Lr{constructor(){super(...arguments),this.sessions=new za(this._client),this.transcriptionSessions=new Va(this._client)}}Ka.Sessions=za,Ka.TranscriptionSessions=Va;class Wa extends Lr{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,r){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t={},n){return vr(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Za,{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 Za extends qr{}Wa.MessagesPage=Za;class Ya extends Lr{retrieve(e,t,n,r={},s){return vr(r)?this.retrieve(e,t,n,{},r):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:r,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t,n={},r){return vr(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Xa,{query:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class Xa extends qr{}Ya.RunStepsPage=Xa;let Qa=class extends Lr{constructor(){super(...arguments),this.steps=new Ya(this._client)}create(e,t,n){const{include:r,...s}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:r},body:s,...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,r){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t={},n){return vr(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,ei,{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 r=await this.create(e,t,n);return await this.poll(e,r.id,n)}createAndStream(e,t,n){return Us.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const r={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:s,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(s.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 Ir(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,t,n){return Us.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,r){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,r){const s=await this.submitToolOutputs(e,t,n,r);return await this.poll(e,s.id,r)}submitToolOutputsStream(e,t,n,r){return Us.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,r)}};class ei extends qr{}Qa.RunsPage=ei,Qa.Steps=Ya,Qa.RunStepsPage=Xa;class ti extends Lr{constructor(){super(...arguments),this.runs=new Qa(this._client),this.messages=new Wa(this._client)}create(e={},t){return vr(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 Us.createThreadAssistantStream(e,this._client.beta.threads,t)}}ti.Runs=Qa,ti.RunsPage=ei,ti.Messages=Wa,ti.MessagesPage=Za;class ni extends Lr{constructor(){super(...arguments),this.realtime=new Ka(this._client),this.chat=new Ga(this._client),this.assistants=new qs(this._client),this.threads=new ti(this._client)}}ni.Realtime=Ka,ni.Assistants=qs,ni.AssistantsPage=Ls,ni.Threads=ti;class ri extends Lr{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class si extends Lr{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n?.headers},__binaryResponse:!0})}}let ai=class extends Lr{constructor(){super(...arguments),this.content=new si(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,lr({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return vr(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,ii,{query:t,...n})}del(e,t,n){return this._client.delete(`/containers/${e}/files/${t}`,{...n,headers:{Accept:"*/*",...n?.headers}})}};class ii extends qr{}ai.FileListResponsesPage=ii,ai.Content=si;class oi extends Lr{constructor(){super(...arguments),this.files=new ai(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 vr(e)?this.list({},e):this._client.getAPIList("/containers",li,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class li extends qr{}oi.ContainerListResponsesPage=li,oi.Files=ai,oi.FileListResponsesPage=ii;let ci=class extends Lr{create(e,t){const n=!!e.encoding_format;let r=n?e.encoding_format:"base64";n&&Dr("Request","User defined encoding_format:",e.encoding_format);const s=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return n?s:(Dr("response","Decoding base64 embeddings to float32 array"),s._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,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}})(t)}),e)))}};class ui extends Lr{retrieve(e,t,n,r){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,r)}list(e,t,n={},r){return vr(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,di,{query:n,...r})}}class di extends qr{}ui.OutputItemListResponsesPage=di;class pi extends Lr{constructor(){super(...arguments),this.outputItems=new ui(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 vr(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,hi,{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 hi extends qr{}pi.RunListResponsesPage=hi,pi.OutputItems=ui,pi.OutputItemListResponsesPage=di;class yi extends Lr{constructor(){super(...arguments),this.runs=new pi(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 vr(e)?this.list({},e):this._client.getAPIList("/evals",mi,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class mi extends qr{}yi.EvalListResponsesPage=mi,yi.Runs=pi,yi.RunListResponsesPage=hi;let fi=class extends Lr{create(e,t){return this._client.post("/files",lr({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return vr(e)?this.list({},e):this._client.getAPIList("/files",gi,{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 r=new Set(["processed","error","deleted"]),s=Date.now();let a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Ir(t),a=await this.retrieve(e),Date.now()-s>n)throw new Pn({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};class gi extends qr{}fi.FileObjectsPage=gi;class bi extends Lr{}let wi=class extends Lr{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 vi extends Lr{constructor(){super(...arguments),this.graders=new wi(this._client)}}vi.Graders=wi;class _i extends Lr{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Ti,{body:t,method:"post",...n})}retrieve(e,t={},n){return vr(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 Ti extends Ur{}_i.PermissionCreateResponsesPage=Ti;let xi=class extends Lr{constructor(){super(...arguments),this.permissions=new _i(this._client)}};xi.Permissions=_i,xi.PermissionCreateResponsesPage=Ti;class Ai extends Lr{list(e,t={},n){return vr(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Si,{query:t,...n})}}class Si extends qr{}Ai.FineTuningJobCheckpointsPage=Si;class ki extends Lr{constructor(){super(...arguments),this.checkpoints=new Ai(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 vr(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Ni,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return vr(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Ei,{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 Ni extends qr{}class Ei extends qr{}ki.FineTuningJobsPage=Ni,ki.FineTuningJobEventsPage=Ei,ki.Checkpoints=Ai,ki.FineTuningJobCheckpointsPage=Si;class Ii extends Lr{constructor(){super(...arguments),this.methods=new bi(this._client),this.jobs=new ki(this._client),this.checkpoints=new xi(this._client),this.alpha=new vi(this._client)}}Ii.Methods=bi,Ii.Jobs=ki,Ii.FineTuningJobsPage=Ni,Ii.FineTuningJobEventsPage=Ei,Ii.Checkpoints=xi,Ii.Alpha=vi;class Oi extends Lr{}class Ci extends Lr{constructor(){super(...arguments),this.graderModels=new Oi(this._client)}}Ci.GraderModels=Oi;class Ri extends Lr{createVariation(e,t){return this._client.post("/images/variations",lr({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",lr({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class $i extends Lr{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Mi,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Mi extends Ur{}$i.ModelsPage=Mi;class Pi extends Lr{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Fi(e,t){return t&&function(e){if(Ks(e.text?.format))return!0;return!1}(t)?Di(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 Di(e,t){const n=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:Bi(t,e)};if("message"===e.type){const n=e.content.map(e=>"output_text"===e.type?{...e,parsed:Hi(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||ji(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const e of r.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),r}function Hi(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 Bi(e,t){const n=(r=e.tools??[],s=t.name,r.find(e=>"function"===e.type&&e.name===s));var r,s,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 ji(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 Ui extends Lr{list(e,t={},n){return vr(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,eo,{query:t,...n})}}var qi,Li,Ji,Gi,zi,Vi,Ki,Wi,Zi=function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},Yi=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Xi extends fs{constructor(e){super(),qi.add(this),Li.set(this,void 0),Ji.set(this,void 0),Gi.set(this,void 0),Zi(this,Li,e,"f")}static createResponse(e,t,n){const r=new Xi(t);return r._run(()=>r._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,t,n){const r=n?.signal;let s;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),Yi(this,qi,"m",zi).call(this);let a=null;"response_id"in t?(s=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):s=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const i of s)Yi(this,qi,"m",Vi).call(this,i,a);if(s.controller.signal?.aborted)throw new $n;return Yi(this,qi,"m",Ki).call(this)}[(Li=new WeakMap,Ji=new WeakMap,Gi=new WeakMap,qi=new WeakSet,zi=function(){this.ended||Zi(this,Ji,void 0,"f")},Vi=function(e,t){if(this.ended)return;const n=(e,n)=>{(null==t||n.sequence_number>t)&&this._emit(e,n)},r=Yi(this,qi,"m",Wi).call(this,e);switch(n("event",e),e.type){case"response.output_text.delta":{const t=r.output[e.output_index];if(!t)throw new Cn(`missing output at index ${e.output_index}`);if("message"===t.type){const r=t.content[e.content_index];if(!r)throw new Cn(`missing content at index ${e.content_index}`);if("output_text"!==r.type)throw new Cn(`expected content to be 'output_text', got ${r.type}`);n("response.output_text.delta",{...e,snapshot:r.text})}break}case"response.function_call_arguments.delta":{const t=r.output[e.output_index];if(!t)throw new Cn(`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)}},Ki=function(){if(this.ended)throw new Cn("stream has ended, this shouldn't happen");const e=Yi(this,Ji,"f");if(!e)throw new Cn("request ended without sending any events");Zi(this,Ji,void 0,"f");const t=function(e,t){return Fi(e,t)}(e,Yi(this,Li,"f"));return Zi(this,Gi,t,"f"),t},Wi=function(e){let t=Yi(this,Ji,"f");if(!t){if("response.created"!==e.type)throw new Cn(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=Zi(this,Ji,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 Cn(`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 Cn(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new Cn(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Cn(`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 Cn(`missing output at index ${e.output_index}`);"function_call"===n.type&&(n.arguments+=e.delta);break}case"response.completed":Zi(this,Ji,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const r=t.shift();r?r.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=Yi(this,Gi,"f");if(!e)throw new Cn("stream ended without producing a ChatCompletion");return e}}class Qi extends Lr{constructor(){super(...arguments),this.inputItems=new Ui(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&&ji(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=>Di(t,e))}stream(e,t){return Xi.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class eo extends qr{}Qi.InputItems=Ui;class to extends Lr{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,lr({body:t,...n}))}}class no extends Lr{constructor(){super(...arguments),this.parts=new to(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})}}no.Parts=to;class ro extends Lr{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,r){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t={},n){return vr(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,so,{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 r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){const r={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const s=await this.retrieve(e,t,{...n,headers:r}).withResponse(),a=s.data;switch(a.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=s.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Ir(e);break;case"failed":case"completed":return a}}}async upload(e,t,n){const r=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){const r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,ao,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class so extends qr{}class ao extends Ur{}ro.VectorStoreFilesPage=so,ro.FileContentResponsesPage=ao;class io extends Lr{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 r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n={},r){return vr(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,so,{query:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async poll(e,t,n){const r={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:s,response:a}=await this.retrieve(e,t,{...n,headers:r}).withResponse();switch(s.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 Ir(e);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){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 s=r?.maxConcurrency??5,a=Math.min(s,t.length),i=this._client,o=t.values(),l=[...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"},r);l.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 r=[];for(const s of t)"fulfilled"===s.status&&r.push(s.value);return r})(c),await this.createAndPoll(e,{file_ids:l})}}class oo extends Lr{constructor(){super(...arguments),this.files=new ro(this._client),this.fileBatches=new io(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 vr(e)?this.list({},e):this._client.getAPIList("/vector_stores",lo,{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`,co,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class lo extends qr{}class co extends Ur{}var uo;oo.VectorStoresPage=lo,oo.VectorStoreSearchResponsesPage=co,oo.Files=ro,oo.VectorStoreFilesPage=so,oo.FileContentResponsesPage=ao,oo.FileBatches=io;class po extends mr{constructor({baseURL:e=Rr("OPENAI_BASE_URL"),apiKey:t=Rr("OPENAI_API_KEY"),organization:n=Rr("OPENAI_ORG_ID")??null,project:r=Rr("OPENAI_PROJECT_ID")??null,...s}={}){if(void 0===t)throw new Cn("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:r,...s,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Cn("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 ri(this),this.chat=new Kr(this),this.embeddings=new ci(this),this.files=new fi(this),this.images=new Ri(this),this.audio=new Xr(this),this.moderations=new Pi(this),this.models=new $i(this),this.fineTuning=new Ii(this),this.graders=new Ci(this),this.vectorStores=new oo(this),this.beta=new ni(this),this.batches=new Qr(this),this.uploads=new no(this),this.responses=new Qi(this),this.evals=new yi(this),this.containers=new oi(this),this._options=a,this.apiKey=t,this.organization=n,this.project=r}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 gn(e,{arrayFormat:"brackets"})}}uo=po,po.OpenAI=uo,po.DEFAULT_TIMEOUT=6e5,po.OpenAIError=Cn,po.APIError=Rn,po.APIConnectionError=Mn,po.APIConnectionTimeoutError=Pn,po.APIUserAbortError=$n,po.NotFoundError=Bn,po.ConflictError=jn,po.RateLimitError=qn,po.BadRequestError=Fn,po.AuthenticationError=Dn,po.InternalServerError=Ln,po.PermissionDeniedError=Hn,po.UnprocessableEntityError=Un,po.toFile=sr,po.fileFromPath=kn,po.Completions=ri,po.Chat=Kr,po.ChatCompletionsPage=zr,po.Embeddings=ci,po.Files=fi,po.FileObjectsPage=gi,po.Images=Ri,po.Audio=Xr,po.Moderations=Pi,po.Models=$i,po.ModelsPage=Mi,po.FineTuning=Ii,po.Graders=Ci,po.VectorStores=oo,po.VectorStoresPage=lo,po.VectorStoreSearchResponsesPage=co,po.Beta=ni,po.Batches=Qr,po.BatchesPage=es,po.Uploads=no,po.Responses=Qi,po.Evals=yi,po.EvalListResponsesPage=mi,po.Containers=oi,po.ContainerListResponsesPage=li;class ho{constructor(e,t={}){if(!e)throw new Error("OpenAI API key is required");this.openai=new po({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 r=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 r.choices[0]?.message?.content?.trim()||""}catch(r){throw new Error(`LLM request failed: ${r.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"]`,r=await this.sendMessage(n,e,{temperature:.2});try{return JSON.parse(r)}catch{const e=r.match(/\[[\s\S]*\]/);return e?JSON.parse(e[0]):r.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"}`,r=await this.sendMessage(n,e,{temperature:.2});try{return JSON.parse(r)}catch{const e=r.match(/\{[\s\S]*\}/);return e?JSON.parse(e[0]):{category:t[0],confidence:.5,reasoning:r}}}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?"]`,r=await this.sendMessage(n,e,{temperature:.7});try{return JSON.parse(r)}catch{const e=r.match(/\[[\s\S]*\]/);return e?JSON.parse(e[0]):r.split("\n").filter(e=>e.trim().endsWith("?"))}}async getJSON(e,t,n={}){const r=await this.sendMessage(e+"\n\nReturn ONLY valid JSON, no additional text.",t,{...n,temperature:n.temperature??.2});try{return JSON.parse(r)}catch{const e=r.match(/[\[{][\s\S]*[\]}]/);if(e)return JSON.parse(e[0]);throw new Error(`Failed to parse JSON response: ${r.substring(0,100)}`)}}}class yo{constructor(e){this.llm=e}async extractToSchema(e,t,n={}){const r=this._describeSchema(t),s=`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${r}\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(s,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[r,s]of Object.entries(e.properties)){const a=t?`${t}.${r}`:r,i=s.type||"any",o=e.required?.includes(r)?" (required)":"",l=s.description||"";n.push(`- ${a} [${i}]${o}: ${l}`),"object"===s.type&&s.properties&&n.push(this._describeSchema(s,a)),"array"===s.type&&s.items&&s.items.properties&&n.push(this._describeSchema(s.items,`${a}[]`))}return n.join("\n")}async extractMultiple(e,t,n={}){const r=`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.`,s=await this.llm.getJSON(r,e,{temperature:.2,maxTokens:n.maxTokens||3e3});return Array.isArray(s)?s:[s]}async fillMissing(e,t,n){const r=this._findMissingFields(e,n);if(0===r.length)return e;const s=`You have existing data:\n${JSON.stringify(e,null,2)}\n\nExtract ONLY the following missing fields from the text:\n${r.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(s,t,{temperature:.2});return{...e,...a}}_findMissingFields(e,t,n=""){const r=[];if(t.properties)for(const[s,a]of Object.entries(t.properties)){const t=n?`${n}.${s}`:s,i=e[s];null==i?r.push(t):"object"===a.type&&a.properties&&r.push(...this._findMissingFields(i,a,t))}return r}validateExtraction(e,t){const n=[];if(t.required)for(const r of t.required)void 0!==e[r]&&null!==e[r]||n.push(`Missing required field: ${r}`);if(t.properties)for(const[r,s]of Object.entries(t.properties)){const t=e[r];if(null!=t){this._validateType(t,s.type)||n.push(`Invalid type for ${r}: expected ${s.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 mo{constructor(e){this.llm=e}async add(e,t,n={}){const r=`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`,s=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON(r,s,{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 fo{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,r=0,s=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],s+=t[a]*t[a];return n/(Math.sqrt(r)*Math.sqrt(s))}async storeWithEmbedding(e,t,n,r=null){if(!this.holosphere)throw new Error("HoloSphere instance required for storage");const s=r?n[r]:n.content||n.text||n.description||JSON.stringify(n);if(!s)throw new Error("No text found to embed");const a=await this.embed(s),i={...n,_embedding:a,_embeddedField:r||"auto",_embeddedAt:Date.now()};return await this.holosphere.put(e,t,i),i}async semanticSearch(e,t,n,r={}){if(!this.holosphere)throw new Error("HoloSphere instance required for search");const{limit:s=10,threshold:a=.5}=r,i=await this.embed(e),o=await this.holosphere.getAll(t,n),l=[];for(const c of o)if(c._embedding){const e=this.cosineSimilarity(i,c._embedding);e>=a&&l.push({item:{...c,_embedding:void 0},similarity:e})}return l.sort((e,t)=>t.similarity-e.similarity),l.slice(0,s)}async findSimilar(e,t,n,r={}){const s=e.content||e.text||e.description||JSON.stringify(e);return this.semanticSearch(s,t,n,r)}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 r=[...e].sort(()=>Math.random()-.5).slice(0,t).map(e=>[...e._embedding]),s=new Array(e.length);for(let i=0;i<n;i++){const n=e.map(e=>{let t=1/0,n=0;for(let s=0;s<r.length;s++){const a=1-this.cosineSimilarity(e._embedding,r[s]);a<t&&(t=a,n=s)}return n});if(JSON.stringify(n)===JSON.stringify(s))break;s=n;for(let a=0;a<t;a++){const t=e.filter((e,t)=>s[t]===a);if(t.length>0){r[a]=new Array(this.dimensions).fill(0);for(const e of t)for(let t=0;t<this.dimensions;t++)r[a][t]+=e._embedding[t];for(let e=0;e<this.dimensions;e++)r[a][e]/=t.length}}}const a=Array.from({length:t},()=>[]);return e.forEach((e,t)=>{a[s[t]].push(e)}),a.filter(e=>e.length>0)}}const go=[{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 bo{constructor(e,t=null){this.llm=e,this.perspectives=t||go}setPerspectives(e){this.perspectives=e}static getDefaultPerspectives(){return go}async ask(e,t={}){const{parallel:n=!0,includeSummary:r=!0}=t,s=t.perspectives||this.perspectives;let a;if(n)a=await Promise.all(s.map(async t=>{const n=await this._askPerspective(e,t);return{perspective:t.name,answer:n}}));else{a=[];for(const t of s){const n=await this._askPerspective(e,t);a.push({perspective:t.name,answer:n})}}let i=null;return r&&(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 r=bo.createPerspectives(t);return this.ask(e,{...n,perspectives:r})}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 r=t.map(e=>this.perspectives.find(t=>t.name===e)||{name:e,prompt:`Argue from the perspective of ${e}.`}),s=[];let a=`Topic: ${e}`;for(let i=0;i<n;i++)for(const e of r){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});s.push({perspective:e.name,round:i+1,response:n}),a+=`\n\n${e.name}: ${n}`}return{topic:e,perspectives:t,exchanges:s,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 wo={ALLOY:"alloy",ECHO:"echo",FABLE:"fable",ONYX:"onyx",NOVA:"nova",SHIMMER:"shimmer"},vo={TTS_1:"tts-1",TTS_1_HD:"tts-1-hd"};class _o{constructor(e){this.openai=e,this.defaultVoice=wo.ECHO,this.defaultModel=vo.TTS_1}async speak(e,t={}){const{voice:n=this.defaultVoice,model:r=this.defaultModel,speed:s=1,responseFormat:a="mp3"}=t;try{const t=await this.openai.audio.speech.create({model:r,voice:n,input:e,speed:s,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(wo).includes(e))throw new Error(`Invalid voice: ${e}. Use one of: ${Object.values(wo).join(", ")}`);this.defaultVoice=e}setDefaultModel(e){if(!Object.values(vo).includes(e))throw new Error(`Invalid model: ${e}. Use one of: ${Object.values(vo).join(", ")}`);this.defaultModel=e}static getVoices(){return Object.values(wo)}static getModels(){return Object.values(vo)}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=[],r=e.split(/(?<=[.!?])\s+/);let s="";for(const a of r)(s+a).length>t?(s&&n.push(s.trim()),s=a):s+=(s?" ":"")+a;return s&&n.push(s.trim()),n}async speakLong(e,t={}){const n=_o.splitText(e,t.maxChars||4e3);return await Promise.all(n.map(e=>this.speak(e,t)))}}class To{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 r=[];if(n.holon&&n.lens)r=await this.holosphere.getAll(n.holon,n.lens);else if(n.lens&&t.holons)for(const s of t.holons){const e=await this.holosphere.getAll(s,n.lens);r.push(...e.map(e=>({...e,_holon:s})))}return n.filters&&(r=this._applyFilters(r,n.filters)),n.sort&&(r=this._applySort(r,n.sort)),n.limit&&(r=r.slice(0,n.limit)),{query:e,parsed:n,results:r,count:r.length}}_applyFilters(e,t){return e.filter(e=>{for(const[n,r]of Object.entries(t)){const t=this._getNestedValue(e,n);if(!this._matchCondition(t,r))return!1}return!0})}_getNestedValue(e,t){return t.split(".").reduce((e,t)=>e?.[t],e)}_matchCondition(e,t){const{op:n,value:r}=t;switch(n){case"eq":return e===r;case"ne":return e!==r;case"gt":return e>r;case"gte":return e>=r;case"lt":return e<r;case"lte":return e<=r;case"contains":return String(e).toLowerCase().includes(String(r).toLowerCase());case"in":return Array.isArray(r)&&r.includes(e);default:return!0}}_applySort(e,t){const{field:n,order:r}=t,s="desc"===r?-1:1;return[...e].sort((e,t)=>{const r=this._getNestedValue(e,n),a=this._getNestedValue(t,n);return r<a?-1*s:r>a?1*s: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.`,r=t.slice(0,5);return this.llm.sendMessage(n,`Results sample: ${JSON.stringify(r,null,2)}`,{temperature:.5})}}class xo{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"),r="string"==typeof e?e:JSON.stringify(e,null,2),s=`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(s,r,{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 r=n.map(([e,t])=>`- ${e}: ${t.description}`).join("\n"),s="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${r}\n\nReturn JSON array: [{"lens": "name", "confidence": 0.0-1.0}, ...]\nOrder by confidence descending.`;return this.llm.getJSON(a,s,{temperature:.2})}async autoStore(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required for storage");const n=await this.classifyToLens(t),r=await this.holosphere.put(e,n.lens,t);return{lens:n.lens,confidence:n.confidence,reasoning:n.reasoning,stored:!0,result:r}}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 r=`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(r,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 r of t)n[r.lens]=(n[r.lens]||0)+1;return{total:e.length,byLens:n,classifications:t}}}class Ao{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 r=[];r=t?await this.holosphere.getAll(e,t):await this.holosphere.getAll(e,"default");const s=JSON.stringify(r.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: ${r.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,s,{temperature:.3});return{holon:e,lens:t,aspect:n,dataCount:r.length,analysis:i,timestamp:Date.now()}}async compareRegions(e,t,n){if(!this.holosphere)throw new Error("HoloSphere instance required");const r=await this.holosphere.getAll(e,n),s=await this.holosphere.getAll(t,n),a=`You are a comparative analyst. Compare data between two geographic regions.\n\nRegion 1 (${e}): ${r.length} items\nRegion 2 (${t}): ${s.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(r.slice(0,25),null,2)}\n\nRegion 2 data sample:\n${JSON.stringify(s.slice(0,25),null,2)}`,o=await this.llm.getJSON(a,i,{temperature:.3});return{regions:[e,t],lens:n,dataCounts:{[e]:r.length,[t]:s.length},comparison:o,timestamp:Date.now()}}async spatialTrends(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const r=await this.holosphere.getAll(e,t);let s=r;(n.start||n.end)&&(s=r.filter(e=>{const t=e.timestamp||e.created_at||e.date;if(!t)return!0;const r=new Date(t).getTime();return!(n.start&&r<new Date(n.start).getTime())&&!(n.end&&r>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: ${s.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(s.slice(0,50),null,2),{temperature:.3});return{holon:e,lens:t,timeRange:n,dataCount:s.length,trends:i,timestamp:Date.now()}}async findHotspots(e,t,n="count"){if(!this.holosphere)throw new Error("HoloSphere instance required");const r=await this.holosphere.getAll(e,t),s=`You are a spatial analyst. Identify hotspots (areas of high concentration/activity) in geographic data.\n\nRegion: ${e}\nLens: ${t}\nMetric: ${n}\nData points: ${r.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(s,JSON.stringify(r.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"],r={};for(const i of n)r[i]=await this.holosphere.getAll(e,i);const s=`You are a regional analyst. Generate a comprehensive report for this geographic region.\n\nRegion: ${e}\nData by lens: ${Object.entries(r).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(r))a[i]=o.slice(0,20);return this.llm.sendMessage(s,JSON.stringify(a,null,2),{temperature:.5,maxTokens:2e3})}}class So{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:r=5,storeResults:a=!0}=n,i=await this.holosphere.getAll(e,t),o=await this._generateSummary(i,e,t),l=s.getResolution(e);if(l<=0||r<=0)return{holon:e,lens:t,summary:o,level:l};const c=s.cellToParent(e,l-1);a&&await this.holosphere.put(c,`${t}_summaries`,{id:e,childHolon:e,summary:o,dataCount:i.length,timestamp:Date.now()});const u=await this.smartUpcast(c,t,{...n,maxLevels:r-1});return{holon:e,lens:t,summary:o,dataCount:i.length,parent:u}}async _generateSummary(e,t,n){if(0===e.length)return{text:"No data in this region",stats:{count:0}};const r=`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(r,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 r=`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}`,s={};for(const[a,i]of Object.entries(n))s[a]=i.slice(0,15);return{holon:e,summary:await this.llm.getJSON(r,JSON.stringify(s,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=s.getResolution(e),r=s.cellToChildren(e,n+1),a=[];for(const s of r.slice(0,7))try{const e=await this.holosphere.getAll(s,t);if(e.length>0){const n=await this._generateSummary(e,s,t);a.push({holon:s,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,r){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t),a=(e,t)=>e.filter(e=>{const n=e.timestamp||e.created_at;if(!n)return!1;const r=new Date(n).getTime();return r>=new Date(t.start).getTime()&&r<=new Date(t.end).getTime()}),i=a(s,n),o=a(s,r),l=`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(r)} - ${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(l,c,{temperature:.3})}}class ko{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:r="default",maxSuggestions:s=5}=t,a=await this.holosphere.getAll(e,r);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,r);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 ${s} suggestions.`,l=`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:r,suggestions:(await this.llm.getJSON(o,l,{temperature:.3})).slice(0,s),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 r=`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}`,s=await this.llm.getJSON(r,"",{temperature:.3});return{holon:e,federation:t.federation,analysis:s,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 r of e.slice(0,20))try{const e=await this.holosphere.getFederation(r);e&&t.push({holon:r,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 No{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 r=t?[t]:["projects","quests","events","resources","default"];for(const i of r)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 s=`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(s,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,r={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{limit:s=10,threshold:a=.5,useEmbeddings:i=!0}=r;if(i&&this.embeddings&&t&&n)return this.embeddings.findSimilar(e,t,n,{limit:s,threshold:a});if(!t)throw new Error("Holon required for LLM-based similarity");const o=n?[n]:["projects","quests","events","resources","default"];let l=[];for(const u of o)try{const e=await this.holosphere.getAll(t,u);l.push(...e.map(e=>({...e,_lens:u})))}catch{}if(0===l.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 ${s} items with similarity >= ${a}.`;return(await this.llm.getJSON(c,JSON.stringify(l.slice(0,50),null,2),{temperature:.2})).slice(0,s).filter(e=>e.similarity>=a)}async buildGraph(e,t){const n=await this.discoverRelationships(e,t),r=new Map,s=[];for(const a of n.relationships?.relationships||[])r.has(a.item1.id)||r.set(a.item1.id,{id:a.item1.id,label:a.item1.title}),r.has(a.item2.id)||r.set(a.item2.id,{id:a.item2.id,label:a.item2.title}),s.push({source:a.item1.id,target:a.item2.id,type:a.type,weight:a.strength});return{nodes:Array.from(r.values()),edges:s,clusters:n.relationships?.clusters||[]}}async findCrossHolonRelationships(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required");const n={};for(const s of e.slice(0,5))try{const e=await this.holosphere.getAll(s,t);e.length>0&&(n[s]=e.slice(0,15))}catch{}if(Object.keys(n).length<2)return{message:"Need at least 2 holons with data"};const r=`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(r,"",{temperature:.4})}async suggestConnections(e,t,n){const r=await this.findSimilar(e,t,n,{limit:10}),s=`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(r,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(s,"",{temperature:.5})}async detectPatterns(e,t){const n=await this.discoverRelationships(e,t),r=`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(r,"",{temperature:.3})}}class Eo{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async breakdown(e,t,n,r={}){if(!e||!e.id)throw new Error("Item must have an id property");const{depth:s=2,stepsPerLevel:a={min:3,max:5},useContext:i=!0,storeResults:o=!0,dependencyField:l="dependencies",parentField:c="parent"}=r,u="number"==typeof a?{min:a,max:a}:a;let d=[];if(i&&this.holosphere)try{d=(await this.holosphere.getAll(t,n)).filter(t=>t.id!==e.id).slice(0,10)}catch{}let p=null;if(this.holosphere)try{p=await this.holosphere.getSchema(n)}catch{}const h=await this._breakdownRecursive(e,t,n,s,u,d,p,l,c,o,0);return{original:e,holonId:t,lensName:n,breakdown:h,totalSubtasks:this._countSubtasks(h),maxDepth:s,timestamp:Date.now()}}async _breakdownRecursive(e,t,n,r,s,a,i,o,l,c,u){if(u>=r)return{item:e,children:[],depth:u};const d=await this._generateSubtasks(e,a,i,s,o,l);if(c&&this.holosphere&&d.length>0){for(const e of d)try{await this.holosphere.write(t,n,e)}catch(h){console.warn(`Failed to store subtask ${e.id}:`,h.message)}if(e._meta?.childTasks!==d.map(e=>e.id))try{await this.holosphere.update(t,n,e.id,{_meta:{...e._meta,childTasks:d.map(e=>e.id),breakdownTimestamp:Date.now()}})}catch{}}const p=[];for(const y of d){const e=await this._breakdownRecursive(y,t,n,r,s,a,i,o,l,c,u+1);p.push(e)}return{item:e,children:p,depth:u}}async _generateSubtasks(e,t,n,r,s,a){const{min:i,max:o}=r,l=`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 "${s}" 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- ${s}: 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 "${s}": [],\n "status": "pending"\n },\n {\n "id": "parent-2",\n "title": "Second subtask (depends on first)",\n "description": "Details...",\n "${a}": "parentId",\n "${s}": ["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(l,c,{temperature:.4,maxTokens:2e3})).map((t,n)=>({...t,id:t.id||`${e.id}-${n+1}`,[a]:e.id,[s]:t[s]||[],status:t.status||"pending",_meta:{...t._meta,generatedFrom:e.id,generatedAt:Date.now(),depth:(e._meta?.depth||0)+1}}))}catch(u){return console.error("Failed to generate subtasks:",u),[]}}_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,r=t._meta?.depth||0;if(n!==r)return n-r;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,r=this.flatten(e),s=`You are a task organization expert. Rebalance these tasks to have ${n.min}-${n.max} items per level.\n\nCurrent tasks:\n${JSON.stringify(r,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(s,"",{temperature:.3})}async getProgress(e,t,n){if(!this.holosphere)throw new Error("HoloSphere instance required");const r=await this.holosphere.getAll(e,t),s=r.find(e=>e.id===n);if(!s)throw new Error(`Item ${n} not found`);const a=this._findDescendants(n,r),i=a.length,o=a.filter(e=>"completed"===e.status||"done"===e.status).length,l=a.filter(e=>"in_progress"===e.status||"active"===e.status).length,c=i-o-l;return{itemId:n,title:s.title||s.name,total:i,completed:o,inProgress:l,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 r=[],s=t.filter(t=>t[n]===e);for(const a of s)r.push(a),r.push(...this._findDescendants(a.id,t,n));return r}_findBlockers(e,t="dependencies"){return e.filter(n=>{const r=n[t]||[];return 0!==r.length&&r.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 r=n[t]||[];return 0===r.length||r.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 Io{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async suggestResolution(e,t={}){const{currentResolution:n=null,context:r=null}=t,s=`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${r?`Context:\n${JSON.stringify(r,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(s,JSON.stringify(e,null,2),{temperature:.3})}async analyzeDistribution(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{includeChildren:r=!0,maxChildren:a=20}=n,i=await this.holosphere.getAll(e,t),o={};if(r&&s.isValidCell(e)){const n=s.getResolution(e);if(n<15){const r=s.cellToChildren(e,n+1);for(const e of r.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 l=`You are a geospatial analyst. Analyze the distribution of data across this H3 hexagonal region.\n\nParent holon: ${e}\nResolution: ${s.isValidCell(e)?s.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)}`,u=await this.llm.getJSON(l,c,{temperature:.3});return{holonId:e,lensName:t,resolution:s.isValidCell(e)?s.getResolution(e):null,parentDataCount:i.length,childrenAnalyzed:Object.keys(o).length,analysis:u,timestamp:Date.now()}}async findNeighborRelevance(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!s.isValidCell(e))throw new Error("Invalid H3 cell");const{ringSize:r=1,relevanceThreshold:a=.5}=n,i=await this.holosphere.getAll(e,t),o=s.gridDisk(e,r).filter(t=>t!==e),l={};for(const s of o)try{const e=await this.holosphere.getAll(s,t);e.length>0&&(l[s]=e.slice(0,5))}catch{}if(0===Object.keys(l).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: ${r} (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}`,u=`Center cell data:\n${JSON.stringify(i.slice(0,10),null,2)}\n\nNeighbor data:\n${JSON.stringify(l,null,2)}`,d=await this.llm.getJSON(c,u,{temperature:.4});return d.relevantNeighbors&&(d.relevantNeighbors=d.relevantNeighbors.filter(e=>e.relevanceScore>=a)),{holonId:e,lensName:t,ringSize:r,neighborsAnalyzed:Object.keys(l).length,analysis:d,timestamp:Date.now()}}async suggestGeographicScope(e,t,n,r={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!s.isValidCell(t))throw new Error("Invalid H3 cell");const a=s.getResolution(t);let i=[];if(a>0){const e=s.cellToParent(t,a-1);try{i=await this.holosphere.getAll(e,n)}catch{}}let o=[];if(a<15){const e=s.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 l=`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(l,c,{temperature:.3})}async analyzeCoverage(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!s.isValidCell(e))throw new Error("Invalid H3 cell");const{targetResolution:r=null}=n,a=s.getResolution(e),i=r||Math.min(a+1,15),o=s.cellToChildren(e,i),l={total:o.length,withData:0,withoutData:0,dataDistribution:{}},c=[],u=[];for(const s of o)try{const e=await this.holosphere.getAll(s,t);e.length>0?(l.withData++,l.dataDistribution[s]=e.length,c.push({holon:s,count:e.length})):(l.withoutData++,u.push(s))}catch{l.withoutData++,u.push(s)}const d=`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: ${l.total}\nChildren with data: ${l.withData}\nChildren without data: ${l.withoutData}\nCoverage ratio: ${(l.withData/l.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}`,p=await this.llm.getJSON(d,"",{temperature:.3});return{holonId:e,lensName:t,resolution:a,childResolution:i,coverage:{...l,ratio:l.withData/l.total},childrenWithData:c.slice(0,10),gapCount:u.length,analysis:p,timestamp:Date.now()}}async crossResolutionInsights(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!s.isValidCell(e))throw new Error("Invalid H3 cell");const{levels:r=3}=n,a=s.getResolution(e),i={},o=await this.holosphere.getAll(e,t);i[a]={holon:e,count:o.length,sample:o.slice(0,5)};let l=e;for(let u=0;u<r&&s.getResolution(l)>0;u++){const e=s.getResolution(l)-1;l=s.cellToParent(l,e);try{const n=await this.holosphere.getAll(l,t);i[e]={holon:l,count:n.length,sample:n.slice(0,5)}}catch{}}if(a<15){const n=a+1,r=s.cellToChildren(e,n);let o=0;const l=[];for(const e of r.slice(0,7))try{const n=await this.holosphere.getAll(e,t);o+=n.length,n.length>0&&l.push(...n.slice(0,2))}catch{}i[n]={holon:`${r.length} children`,count:o,sample:l.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,r={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!s.isValidCell(t))throw new Error("Invalid H3 cell");const{searchRadius:a=2}=r,i=s.gridDisk(t,a),o={};for(const s of i)if(s!==t)try{const e=await this.holosphere.getAll(s,n);e.length>0&&(o[s]={count:e.length,sample:e.slice(0,3)})}catch{}const l=s.getResolution(t);let c=null;if(l>0){const e=s.cellToParent(t,l-1);try{const t=await this.holosphere.getAll(e,n);c={holon:e,count:t.length,sample:t.slice(0,3)}}catch{}}const u=`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: ${l}\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}`,d=`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(u,d,{temperature:.3})}async generateGeographicReport(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{lenses:n=["projects","quests","events","resources","default"]}=t,r={};for(const s of n)try{const t=await this.holosphere.getAll(e,s);t.length>0&&(r[s]={count:t.length,sample:t.slice(0,5)})}catch{}let a={};if(s.isValidCell(e)){const t=s.getResolution(e),[n,r]=s.cellToLatLng(e),i=s.cellToBoundary(e);a={resolution:t,center:{lat:n,lng:r},areaKm2:s.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(r).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(r,null,2),{temperature:.4,maxTokens:2e3});return{holonId:e,geoContext:a,lensesAnalyzed:Object.keys(r),totalItems:Object.values(r).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(!s.isValidCell(e))throw new Error("Invalid H3 cell");const{clusterResolution:r=null}=n,a=s.getResolution(e),i=r||Math.min(a+1,15),o=s.cellToChildren(e,i),l={};for(const s of o)try{const e=await this.holosphere.getAll(s,t);e.length>0&&(l[s]=e)}catch{}if(Object.keys(l).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(l).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}`,u=await this.llm.getJSON(c,JSON.stringify(l,null,2),{temperature:.4});return{holonId:e,lensName:t,clusterResolution:i,cellsAnalyzed:Object.keys(l).length,analysis:u,timestamp:Date.now()}}async analyzeGeographicImpact(e,t,n,r={}){if(!s.isValidCell(t))throw new Error("Invalid H3 cell");const a=s.getResolution(t),[i,o]=s.cellToLatLng(t),l=s.cellArea(t,"km2");let c=null;if(a>0){const e=s.cellToParent(t,Math.max(0,a-2));c={holon:e,resolution:a-2,areaKm2:s.cellArea(e,"km2")}}const u=`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: ${l.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(u,JSON.stringify(e,null,2),{temperature:.3})}}const Oo={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 Co(e){if("string"==typeof e)return Oo[e]||null;for(const[t,n]of Object.entries(Oo))if(n.chainId===e)return{...n,key:t};return null}function Ro(e){return Object.fromEntries(Object.entries(Oo).filter(([t,n])=>n.type===e))}function $o(){return Object.keys(Oo)}function Mo(e){return e in Oo}function Po(e,t){const n=Oo[e];return n?.explorer?`${n.explorer}/tx/${t}`:null}function Fo(e,t){const n=Oo[e];return n?.explorer?`${n.explorer}/address/${t}`:null}const Do=Object.freeze(Object.defineProperty({__proto__:null,NETWORKS:Oo,default:Oo,getAddressUrl:Fo,getNetwork:Co,getNetworksByType:Ro,getTxUrl:Po,isNetworkSupported:Mo,listNetworks:$o},Symbol.toStringTag,{value:"Module"}));class Ho{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-CBitK71M.cjs"));this.ethers=e}return this.ethers}async connect(e,t,n){const r=await this._loadEthers();if(!Mo(e)&&!n)throw new Error(`Unsupported network: ${e}. Use a custom rpcUrl or choose from: ${Object.keys(Oo).join(", ")}`);const s=Co(e)||{chainId:0,name:e},a=n||s.rpc;if(this.provider=new r.JsonRpcProvider(a,{chainId:s.chainId,name:s.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 r.Wallet(e,this.provider)}return this._initialized=!0,{provider:this.provider,signer:this.signer,network:this.network,networkName:this.networkName,config:s}}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&&Mo(e)){const t=Co(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=Co(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(s){if(4902!==s.code)throw s;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 r=await this._loadEthers();this.provider=new r.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 r=await this.provider.getBalance(n);return t.formatEther(r)}getNetworkConfig(){return this._requireInitialized(),Co(this.networkName)}getChainId(){return this._requireInitialized(),Number(this.network.chainId)}isOnNetwork(e){if(!this._initialized)return!1;const t=Co(e);return!!t&&this.getChainId()===t.chainId}async getContract(e,t,n=!0){this._requireInitialized();const r=await this._loadEthers(),s=n&&this.signer?this.signer:this.provider;return new r.Contract(e,t,s)}async deployContract(e,t,n=[]){if(this._requireInitialized(),!this.signer)throw new Error("Signer required for contract deployment");const r=new((await this._loadEthers()).ContractFactory)(e,t,this.signer),s=await r.deploy(...n);await s.waitForDeployment();const a=await s.getAddress(),i=s.deploymentTransaction();return{contract:s,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 Bo=[{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"}]}],jo=[{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}],Uo=[{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}],qo=[{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}],Lo=[{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"}]}],Jo=[{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}],Go=[{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}],zo=[{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}],Vo=[{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}],Ko=[{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}],Wo=[{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}],Zo=[{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"}]}],Yo={Splitter:Bo,Managed:jo,Zoned:Uo,Appreciative:qo,Bundle:Lo,Holons:Jo,SplitterFactory:Go,ManagedFactory:zo,ZonedFactory:Vo,AppreciativeFactory:Ko,BundleFactory:Wo,TestToken:Zo};class Xo{constructor(e){this.chainManager=e,this.deployedContracts={},this.ethers=null}async _loadEthers(){return this.ethers||(this.ethers=await Promise.resolve().then(()=>require("./index-CBitK71M.cjs"))),this.ethers}async deployAll(e={}){const t=await this._loadEthers(),n=this.chainManager.getSigner(),r=await n.getAddress(),s=e.botAddress||r,a=e.testTokenSupply||"1000000",i=!1!==e.deployTestToken,o=e.onProgress||(()=>{}),l={network:this.chainManager.networkName,chainId:this.chainManager.getChainId(),deployer:r,botAddress:s,timestamp:(new Date).toISOString(),contracts:{}};try{o({step:1,total:i?8:7,message:"Deploying ManagedFactory..."});const e=await this._deployContract(zo.abi,zo.bytecode,[s]);l.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(Vo.abi,Vo.bytecode,[s]);l.contracts.zonedFactory=n.address,o({step:2,done:!0,address:n.address}),o({step:3,total:i?8:7,message:"Deploying SplitterFactory..."});const r=await this._deployContract(Go.abi,Go.bytecode,[]);l.contracts.splitterFactory=r.address,o({step:3,done:!0,address:r.address}),o({step:4,total:i?8:7,message:"Deploying AppreciativeFactory..."});const c=await this._deployContract(Ko.abi,Ko.bytecode,[]);l.contracts.appreciativeFactory=c.address,o({step:4,done:!0,address:c.address}),o({step:5,total:i?8:7,message:"Deploying BundleFactory..."});const u=await this._deployContract(Wo.abi,Wo.bytecode,[]);l.contracts.bundleFactory=u.address,o({step:5,done:!0,address:u.address}),o({step:6,total:i?8:7,message:"Deploying Holons Registry..."});const d=await this._deployContract(Jo.abi,Jo.bytecode,[]);if(l.contracts.holons=d.address,o({step:6,done:!0,address:d.address}),o({step:7,total:i?8:7,message:"Configuring Holons Registry..."}),await d.contract.setFactories(e.address,n.address),await d.contract.newFlavor("Splitter",r.address),await d.contract.newFlavor("Managed",e.address),await d.contract.newFlavor("Zoned",n.address),await d.contract.newFlavor("Appreciative",c.address),await d.contract.newFlavor("Bundle",u.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(Zo.abi,Zo.bytecode,[e]);l.contracts.testToken=n.address,o({step:8,done:!0,address:n.address})}this.deployedContracts=l.contracts,l.explorerUrls={};for(const[t,s]of Object.entries(l.contracts)){const e=Fo(l.network,s);e&&(l.explorerUrls[t]=e)}return l}catch(c){throw new Error(`Deployment failed: ${c.message}`)}}async deploySplitter(e,t,n=70,r={}){const s=this.chainManager.getSigner(),a=await s.getAddress(),i=r.creatorUserId||e,o=r.managedFactory||this.deployedContracts.managedFactory,l=r.zonedFactory||this.deployedContracts.zonedFactory;if(!o||!l)throw new Error("Factories not deployed. Run deployAll() first or provide factory addresses.");const c=await this._deployContract(Bo.abi,Bo.bytecode,[a,i,t,n,o,l]);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(),r=await n.getAddress(),s=t.botAddress||r;return{...await this._deployContract(jo.abi,jo.bytecode,[r,e,s]),type:"Managed"}}async deployZoned(e,t=6,n={}){const r=this.chainManager.getSigner(),s=await r.getAddress(),a=n.botAddress||s,i=n.creatorUserId||"creator";return{...await this._deployContract(Uo.abi,Uo.bytecode,[i,s,e,t,a]),type:"Zoned",nZones:t}}async deployAppreciative(e,t,n={}){const r=this.chainManager.getSigner(),s=await r.getAddress();return{...await this._deployContract(qo.abi,qo.bytecode,[e,t,s]),type:"Appreciative"}}async deployBundle(e,t,n=6,r={}){const s=await this._loadEthers(),a=this.chainManager.getSigner(),i=await a.getAddress(),o=r.creatorUserId||"creator",l=t||s.parseEther("0.5");return{...await this._deployContract(Lo.abi,Lo.bytecode,[i,o,e,l,n]),type:"Bundle",steepness:l,nZones:n}}async deployTestToken(e="1000000"){const t=(await this._loadEthers()).parseEther(e);return{...await this._deployContract(Zo.abi,Zo.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 r=await this.chainManager.getContract(this.deployedContracts.holons,Jo.abi),s=await r.newHolonBundle(e,t,n),a=await s.wait(),i=a.logs.find(e=>{try{const t=r.interface.parseLog(e);return"NewHolon"===t?.name}catch{return!1}});return{address:i?r.interface.parseLog(i).args.addr:await r.toAddress(t),txHash:a.hash,name:t,creatorUserId:e}}async getContract(e,t){const n=Yo[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 r=await this.chainManager.deployContract(e,t,n);return{contract:r.contract,address:r.address,txHash:r.txHash,explorerUrl:Fo(this.chainManager.networkName,r.address)}}}class Qo{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-CBitK71M.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(),r="string"==typeof t?n.parseUnits(t,18):t,s=await this.contract.reward(e,r),a=await s.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}),r=await n.wait();return{txHash:r.hash,receipt:r}}async sendEth(e){const t=await this._loadEthers(),n=this.chainManager.getSigner(),r=t.parseEther(e),s=await n.sendTransaction({to:await this.contract.getAddress(),value:r}),a=await s.wait();return{txHash:a.hash,receipt:a}}async claim(e,t){const n=await this.contract.claim(e,t),r=await n.wait();return{txHash:r.hash,receipt:r}}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(),r=await this.contract.tokenBalance(e,t);return n.formatUnits(r,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),r=await n.wait();return{txHash:r.hash,receipt:r}}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 r=await this.contract.createManagedContract(e,t,n),s=await r.wait();return{address:await this.contract.contractsByType(`${t}_managed`),txHash:s.hash,receipt:s}}async createZonedContract(e,t,n=6){this._requireType(["Splitter"]);const r=await this.contract.createZonedContract(e,t,n),s=await r.wait();return{address:await this.contract.contractsByType(`${t}_zoned`),txHash:s.hash,receipt:s}}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),r=await n.wait();return{txHash:r.hash,receipt:r}}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 r=await this.contract.addToZone(e,t,n),s=await r.wait();return{txHash:s.hash,receipt:s}}async removeFromZone(e,t){this._requireType(["Zoned"]);const n=await this.contract.removeFromZone(e,t),r=await n.wait();return{txHash:r.hash,receipt:r}}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,r){this._requireType(["Zoned"]);const s=await this.contract.setRewardFunction(e,t,n,r),a=await s.wait();return{txHash:a.hash,receipt:a}}async appreciate(e,t,n){this._requireType(["Appreciative"]);const r=await this.contract.appreciate(e,t,n),s=await r.wait();return{txHash:s.hash,receipt:s}}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,r=await this.contract.setSteepness(n),s=await r.wait();return{txHash:s.hash,receipt:s}}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),r=await n.wait();return{txHash:r.hash,receipt:r}}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),r=await n.wait();return{txHash:r.hash,receipt:r}}}class el{constructor(e,t){this.chainManager=e,this.deployer=t||new Xo(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 r=n.name||e,s=n.creatorUserId||e;let a;switch(t){case"Splitter":a=await this.deployer.deploySplitter(e,r,n.splitPercentage||70,{creatorUserId:s,...n});break;case"Managed":a=await this.deployer.deployManaged(r,n);break;case"Zoned":a=await this.deployer.deployZoned(r,n.nZones||6,n);break;case"Appreciative":a=await this.deployer.deployAppreciative(r,s,n);break;case"Bundle":a=await this.deployer.deployBundle(r,n.steepness,n.nZones||6,{creatorUserId:s,...n});break;default:throw new Error(`Unknown contract type: ${t}`)}const i=new Qo(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 r=Yo[n];if(!r)throw new Error(`Unknown contract type: ${n}`);const s=await this.chainManager.getContract(t,r.abi);try{await s.name()}catch(o){throw new Error(`Invalid contract at ${t}: ${o.message}`)}const a=new Qo(s,n,this.chainManager),i={holonId:e,address:t,type:n,contract:s,operations:a,linkedAt:(new Date).toISOString()};return this.holonContracts.set(e,i),await this._saveMapping(e,i),{contract:s,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,r]of this.holonContracts)r.type===e&&t.push({holonId:n,address:r.address});return t}async loadFromStorage(){if(!this.storage)return 0;const e=await(this.storage.get?.("holon_contracts_index"))||[];let t=0;for(const r of e)try{const e=await(this.storage.get?.(`holon_contract:${r}`));if(e&&e.address&&e.type){const n=Yo[e.type];if(n){const s=await this.chainManager.getContract(e.address,n.abi),a=new Qo(s,e.type,this.chainManager);this.holonContracts.set(r,{...e,contract:s,operations:a}),t++}}}catch(n){console.warn(`Failed to load contract for holon ${r}: ${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 tl="6.16.0";function nl(e,t,n){const r=t.split("|").map(e=>e.trim());for(let a=0;a<r.length;a++)switch(t){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof e===t)return}const s=new Error(`invalid value for type ${t}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${n}`,s.value=e,s}async function rl(e){const t=Object.keys(e);return(await Promise.all(t.map(t=>Promise.resolve(e[t])))).reduce((e,n,r)=>(e[t[r]]=n,e),{})}function sl(e,t,n){for(let r in t){let s=t[r];const a=n?n[r]:null;a&&nl(s,a,r),Object.defineProperty(e,r,{enumerable:!0,value:s,writable:!1})}}function al(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=>al(e,t)).join(", ")+" ]";if(e instanceof Uint8Array){const t="0123456789abcdef";let n="0x";for(let r=0;r<e.length;r++)n+=t[e[r]>>4],n+=t[15&e[r]];return n}if("object"==typeof e&&"function"==typeof e.toJSON)return al(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=>`${al(n,t)}: ${al(e[n],t)}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function il(e,t){return e&&e.code===t}function ol(e){return il(e,"CALL_EXCEPTION")}function ll(e,t,n){let r,s=e;{const r=[];if(n){if("message"in n||"code"in n||"name"in n)throw new Error(`value will overwrite populated values: ${al(n)}`);for(const e in n){if("shortMessage"===e)continue;const t=n[e];r.push(e+"="+al(t))}}r.push(`code=${t}`),r.push(`version=${tl}`),r.length&&(e+=" ("+r.join(", ")+")")}switch(t){case"INVALID_ARGUMENT":r=new TypeError(e);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":r=new RangeError(e);break;default:r=new Error(e)}return sl(r,{code:t}),n&&Object.assign(r,n),null==r.shortMessage&&sl(r,{shortMessage:s}),r}function cl(e,t,n,r){if(!e)throw ll(t,n,r)}function ul(e,t,n,r){cl(e,t,"INVALID_ARGUMENT",{argument:n,value:r})}function dl(e,t,n){null==n&&(n=""),n&&(n=": "+n),cl(e>=t,"missing argument"+n,"MISSING_ARGUMENT",{count:e,expectedCount:t}),cl(e<=t,"too many arguments"+n,"UNEXPECTED_ARGUMENT",{count:e,expectedCount:t})}const pl=["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 hl(e){cl(pl.indexOf(e)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:e}})}function yl(e,t,n){if(null==n&&(n=""),e!==t){let e=n,t="new";n&&(e+=".",t+=" "+n),cl(!1,`private constructor; use ${e}from* methods`,"UNSUPPORTED_OPERATION",{operation:t})}}function ml(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 r=0;r<t.length;r++)t[r]=parseInt(e.substring(n,n+2),16),n+=2;return t}ul(!1,"invalid BytesLike value",t||"value",e)}function fl(e,t){return ml(e,t,!1)}function gl(e,t){return ml(e,t,!0)}function bl(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 wl(e){return bl(e,!0)||e instanceof Uint8Array}const vl="0123456789abcdef";function _l(e){const t=fl(e);let n="0x";for(let r=0;r<t.length;r++){const e=t[r];n+=vl[(240&e)>>4]+vl[15&e]}return n}function Tl(e){return"0x"+e.map(e=>_l(e).substring(2)).join("")}function xl(e,t,n){const r=fl(e);return null!=n&&n>r.length&&cl(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:r,length:r.length,offset:n}),_l(r.slice(null==t?0:t,null==n?r.length:n))}function Al(e,t,n){const r=fl(e);cl(t>=r.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(r),length:t,offset:t+1});const s=new Uint8Array(t);return s.fill(0),n?s.set(r,t-r.length):s.set(r,0),_l(s)}function Sl(e,t){return Al(e,t,!0)}function kl(e,t){return Al(e,t,!1)}const Nl=BigInt(0),El=BigInt(1),Il=9007199254740991;function Ol(e,t){const n=Ml(e,"value"),r=BigInt(Dl(t,"width"));if(cl(n>>r===Nl,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:e}),n>>r-El){return-((~n&(El<<r)-El)+El)}return n}function Cl(e,t){let n=$l(e,"value");const r=BigInt(Dl(t,"width")),s=El<<r-El;if(n<Nl){n=-n,cl(n<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e});return(~n&(El<<r)-El)+El}return cl(n<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e}),n}function Rl(e,t){const n=Ml(e,"value"),r=BigInt(Dl(t,"bits"));return n&(El<<r)-El}function $l(e,t){switch(typeof e){case"bigint":return e;case"number":return ul(Number.isInteger(e),"underflow",t||"value",e),ul(e>=-Il&&e<=Il,"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){ul(!1,`invalid BigNumberish string: ${n.message}`,t||"value",e)}}ul(!1,"invalid BigNumberish value",t||"value",e)}function Ml(e,t){const n=$l(e,t);return cl(n>=Nl,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:e}),n}const Pl="0123456789abcdef";function Fl(e){if(e instanceof Uint8Array){let t="0x0";for(const n of e)t+=Pl[n>>4],t+=Pl[15&n];return BigInt(t)}return $l(e)}function Dl(e,t){switch(typeof e){case"bigint":return ul(e>=-Il&&e<=Il,"overflow",t||"value",e),Number(e);case"number":return ul(Number.isInteger(e),"underflow",t||"value",e),ul(e>=-Il&&e<=Il,"overflow",t||"value",e),e;case"string":try{if(""===e)throw new Error("empty string");return Dl(BigInt(e),t)}catch(n){ul(!1,`invalid numeric string: ${n.message}`,t||"value",e)}}ul(!1,"invalid numeric value",t||"value",e)}function Hl(e){return Dl(Fl(e))}function Bl(e,t){const n=Ml(e,"value");let r=n.toString(16);if(null==t)r.length%2&&(r="0"+r);else{const s=Dl(t,"width");if(0===s&&n===Nl)return"0x";for(cl(2*s>=r.length,`value exceeds width (${s} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:e});r.length<2*s;)r="0"+r}return"0x"+r}function jl(e,t){const n=Ml(e,"value");if(n===Nl){const e=null!=t?Dl(t,"width"):0;return new Uint8Array(e)}let r=n.toString(16);if(r.length%2&&(r="0"+r),null!=t){const n=Dl(t,"width");for(;r.length<2*n;)r="00"+r;cl(2*n===r.length,`value exceeds width (${n} bytes)`,"NUMERIC_FAULT",{operation:"toBeArray",fault:"overflow",value:e})}const s=new Uint8Array(r.length/2);for(let a=0;a<s.length;a++){const e=2*a;s[a]=parseInt(r.substring(e,e+2),16)}return s}class Ul{filter;emitter;#e;constructor(e,t,n){this.#e=t,sl(this,{emitter:e,filter:n})}async removeListener(){null!=this.#e&&await this.emitter.off(this.filter,this.#e)}}function ql(e,t,n,r,s){if("BAD_PREFIX"===e||"UNEXPECTED_CONTINUE"===e){let e=0;for(let r=t+1;r<n.length&&n[r]>>6==2;r++)e++;return e}return"OVERRUN"===e?n.length-t-1:0}const Ll=Object.freeze({error:function(e,t,n,r,s){ul(!1,`invalid codepoint at offset ${t}; ${e}`,"bytes",n)},ignore:ql,replace:function(e,t,n,r,s){return"OVERLONG"===e?(ul("number"==typeof s,"invalid bad code point for replacement","badCodepoint",s),r.push(s),0):(r.push(65533),ql(e,t,n))}});function Jl(e,t){null==t&&(t=Ll.error);const n=fl(e,"bytes"),r=[];let s=0;for(;s<n.length;){const e=n[s++];if(!(e>>7)){r.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)){s+=t(128==(192&e)?"UNEXPECTED_CONTINUE":"BAD_PREFIX",s-1,n,r);continue}a=3,i=65535}if(s-1+a>=n.length){s+=t("OVERRUN",s-1,n,r);continue}let o=e&(1<<8-a-1)-1;for(let l=0;l<a;l++){let e=n[s];if(128!=(192&e)){s+=t("MISSING_CONTINUE",s,n,r),o=null;break}o=o<<6|63&e,s++}null!==o&&(o>1114111?s+=t("OUT_OF_RANGE",s-1-a,n,r,o):o>=55296&&o<=57343?s+=t("UTF16_SURROGATE",s-1-a,n,r,o):o<=i?s+=t("OVERLONG",s-1-a,n,r,o):r.push(o))}return r}function Gl(e,t){ul("string"==typeof e,"invalid string value","str",e),null!=t&&(hl(t),e=e.normalize(t));let n=[];for(let r=0;r<e.length;r++){const t=e.charCodeAt(r);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)){r++;const s=e.charCodeAt(r);ul(r<e.length&&56320==(64512&s),"invalid surrogate pair","str",e);const a=65536+((1023&t)<<10)+(1023&s);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 zl(e,t){return Jl(e,t).map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10&1023),56320+(1023&e)))).join("")}const Vl=BigInt(-1),Kl=BigInt(0),Wl=BigInt(1),Zl=BigInt(5),Yl={};let Xl="0000";for(;Xl.length<80;)Xl+=Xl;function Ql(e){let t=Xl;for(;t.length<e;)t+=t;return BigInt("1"+t.substring(0,e))}function ec(e,t,n){const r=BigInt(t.width);if(t.signed){const t=Wl<<r-Wl;cl(null==n||e>=-t&&e<t,"overflow","NUMERIC_FAULT",{operation:n,fault:"overflow",value:e}),e=e>Kl?Ol(Rl(e,r),r):-Ol(Rl(-e,r),r)}else{const t=Wl<<r;cl(null==n||e>=0&&e<t,"overflow","NUMERIC_FAULT",{operation:n,fault:"overflow",value:e}),e=(e%t+t)%t&t-Wl}return e}function tc(e){"number"==typeof e&&(e=`fixed128x${e}`);let t=!0,n=128,r=18;if("string"==typeof e)if("fixed"===e);else if("ufixed"===e)t=!1;else{const s=e.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);ul(s,"invalid fixed format","format",e),t="u"!==s[1],n=parseInt(s[2]),r=parseInt(s[3])}else if(e){const s=e,a=(e,t,n)=>null==s[e]?n:(ul(typeof s[e]===t,"invalid fixed format ("+e+" not "+t+")","format."+e,s[e]),s[e]);t=a("signed","boolean",t),n=a("width","number",n),r=a("decimals","number",r)}ul(n%8==0,"invalid FixedNumber width (not byte aligned)","format.width",n),ul(r<=80,"invalid FixedNumber decimals (too large)","format.decimals",r);return{signed:t,width:n,decimals:r,name:(t?"":"u")+"fixed"+String(n)+"x"+String(r)}}class nc{format;#t;#n;#r;_value;constructor(e,t,n){yl(e,Yl,"FixedNumber"),this.#n=t,this.#t=n;const r=function(e,t){let n="";e<Kl&&(n="-",e*=Vl);let r=e.toString();if(0===t)return n+r;for(;r.length<=t;)r=Xl+r;const s=r.length-t;for(r=r.substring(0,s)+"."+r.substring(s);"0"===r[0]&&"."!==r[1];)r=r.substring(1);for(;"0"===r[r.length-1]&&"."!==r[r.length-2];)r=r.substring(0,r.length-1);return n+r}(t,n.decimals);sl(this,{format:n.name,_value:r}),this.#r=Ql(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}#s(e){ul(this.format===e.format,"incompatible format; use fixedNumber.toFormat","other",e)}#a(e,t){return e=ec(e,this.#t,t),new nc(Yl,e,this.#t)}#i(e,t){return this.#s(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.#s(e),this.#a(this.#n-e.#n,t)}subUnsafe(e){return this.#o(e)}sub(e){return this.#o(e,"sub")}#l(e,t){return this.#s(e),this.#a(this.#n*e.#n/this.#r,t)}mulUnsafe(e){return this.#l(e)}mul(e){return this.#l(e,"mul")}mulSignal(e){this.#s(e);const t=this.#n*e.#n;return cl(t%this.#r===Kl,"precision lost during signalling mul","NUMERIC_FAULT",{operation:"mulSignal",fault:"underflow",value:this}),this.#a(t/this.#r,"mulSignal")}#c(e,t){return cl(e.#n!==Kl,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#s(e),this.#a(this.#n*this.#r/e.#n,t)}divUnsafe(e){return this.#c(e)}div(e){return this.#c(e,"div")}divSignal(e){cl(e.#n!==Kl,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#s(e);const t=this.#n*this.#r;return cl(t%e.#n===Kl,"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 r=this.decimals-e.decimals;return r>0?n*=Ql(r):r<0&&(t*=Ql(-r)),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<Kl&&(e-=this.#r-Wl),e=this.#n/this.#r*this.#r,this.#a(e,"floor")}ceiling(){let e=this.#n;return this.#n>Kl&&(e+=this.#r-Wl),e=this.#n/this.#r*this.#r,this.#a(e,"ceiling")}round(e){if(null==e&&(e=0),e>=this.decimals)return this;const t=this.decimals-e,n=Zl*Ql(t-1);let r=this.value+n;const s=Ql(t);return r=r/s*s,ec(r,this.#t,"round"),new nc(Yl,r,this.#t)}isZero(){return this.#n===Kl}isNegative(){return this.#n<Kl}toString(){return this._value}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return nc.fromString(this.toString(),e)}static fromValue(e,t,n){const r=null==t?0:Dl(t),s=tc(n);let a=$l(e,"value");const i=r-s.decimals;if(i>0){const t=Ql(i);cl(a%t===Kl,"value loses precision for format","NUMERIC_FAULT",{operation:"fromValue",fault:"underflow",value:e}),a/=t}else i<0&&(a*=Ql(-i));return ec(a,s,"fromValue"),new nc(Yl,a,s)}static fromString(e,t){const n=e.match(/^(-?)([0-9]*)\.?([0-9]*)$/);ul(n&&n[2].length+n[3].length>0,"invalid FixedNumber string value","value",e);const r=tc(t);let s=n[2]||"0",a=n[3]||"";for(;a.length<r.decimals;)a+=Xl;cl(a.substring(r.decimals).match(/^0*$/),"too many decimals for format","NUMERIC_FAULT",{operation:"fromString",fault:"underflow",value:e}),a=a.substring(0,r.decimals);const i=BigInt(n[1]+s+a);return ec(i,r,"fromString"),new nc(Yl,i,r)}static fromBytes(e,t){let n=Fl(fl(e,"value"));const r=tc(t);return r.signed&&(n=Ol(n,r.width)),ec(n,r,"fromBytes"),new nc(Yl,n,r)}}const rc=["wei","kwei","mwei","gwei","szabo","finney","ether"];function sc(e,t){let n=18;if("string"==typeof t){const e=rc.indexOf(t);ul(e>=0,"invalid unit","unit",t),n=3*e}else null!=t&&(n=Dl(t,"unit"));return nc.fromValue(e,n,{decimals:n,width:512}).toString()}function ac(e,t){ul("string"==typeof e,"value must be a string","value",e);let n=18;if("string"==typeof t){const e=rc.indexOf(t);ul(e>=0,"invalid unit","unit",t),n=3*e}else null!=t&&(n=Dl(t,"unit"));return nc.fromString(e,{decimals:n,width:512}).value}function ic(e){return sc(e,18)}const oc=32,lc=new Uint8Array(oc),cc=["then"],uc={},dc=new WeakMap;function pc(e){return dc.get(e)}function hc(e,t){dc.set(e,t)}function yc(e,t){const n=new Error(`deferred error during ABI decoding triggered accessing ${e}`);throw n.error=t,n}function mc(e,t,n){return e.indexOf(null)>=0?t.map((e,t)=>e instanceof fc?mc(pc(e),e,n):e):e.reduce((e,r,s)=>{let a=t.getValue(r);return r in e||(n&&a instanceof fc&&(a=mc(pc(a),a,n)),e[r]=a),e},{})}class fc extends Array{#u;constructor(...e){const t=e[0];let n=e[1],r=(e[2]||[]).slice(),s=!0;t!==uc&&(n=e,r=[],s=!1),super(n.length),n.forEach((e,t)=>{this[t]=e});const a=r.reduce((e,t)=>("string"==typeof t&&e.set(t,(e.get(t)||0)+1),e),new Map);if(hc(this,Object.freeze(n.map((e,t)=>{const n=r[t];return null!=n&&1===a.get(n)?n:null}))),this.#u=[],null==this.#u&&this.#u,!s)return;Object.freeze(this);const i=new Proxy(this,{get:(e,t,n)=>{if("string"==typeof t){if(t.match(/^[0-9]+$/)){const n=Dl(t,"%index");if(n<0||n>=this.length)throw new RangeError("out of result range");const r=e[n];return r instanceof Error&&yc(`index ${n}`,r),r}if(cc.indexOf(t)>=0)return Reflect.get(e,t,n);const r=e[t];if(r instanceof Function)return function(...t){return r.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 hc(i,pc(this)),i}toArray(e){const t=[];return this.forEach((n,r)=>{n instanceof Error&&yc(`index ${r}`,n),e&&n instanceof fc&&(n=n.toArray(e)),t.push(n)}),t}toObject(e){const t=pc(this);return t.reduce((n,r,s)=>(cl(null!=r,`value at index ${s} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),mc(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=pc(this),r=[],s=[];for(let a=e;a<t;a++)r.push(this[a]),s.push(n[a]);return new fc(uc,r,s)}filter(e,t){const n=pc(this),r=[],s=[];for(let a=0;a<this.length;a++){const i=this[a];i instanceof Error&&yc(`index ${a}`,i),e.call(t,i,a,this)&&(r.push(i),s.push(n[a]))}return new fc(uc,r,s)}map(e,t){const n=[];for(let r=0;r<this.length;r++){const s=this[r];s instanceof Error&&yc(`index ${r}`,s),n.push(e.call(t,s,r,this))}return n}getValue(e){const t=pc(this).indexOf(e);if(-1===t)return;const n=this[t];return n instanceof Error&&yc(`property ${JSON.stringify(e)}`,n.error),n}static fromItems(e,t){return new fc(uc,e,t)}}function gc(e){let t=jl(e);return cl(t.length<=oc,"value out-of-bounds","BUFFER_OVERRUN",{buffer:t,length:oc,offset:t.length}),t.length!==oc&&(t=gl(Tl([lc.slice(t.length%oc),t]))),t}class bc{name;type;localName;dynamic;constructor(e,t,n,r){sl(this,{name:e,type:t,localName:n,dynamic:r},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){ul(!1,e,this.localName,t)}}class wc{#d;#p;constructor(){this.#d=[],this.#p=0}get data(){return Tl(this.#d)}get length(){return this.#p}#h(e){return this.#d.push(e),this.#p+=e.length,e.length}appendWriter(e){return this.#h(gl(e.data))}writeBytes(e){let t=gl(e);const n=t.length%oc;return n&&(t=gl(Tl([t,lc.slice(n)]))),this.#h(t)}writeValue(e){return this.#h(gc(e))}writeUpdatableValue(){const e=this.#d.length;return this.#d.push(lc),this.#p+=oc,t=>{this.#d[e]=gc(t)}}}class vc{allowLoose;#d;#y;#m;#f;#g;constructor(e,t,n){sl(this,{allowLoose:!!t}),this.#d=gl(e),this.#m=0,this.#f=null,this.#g=null!=n?n:1024,this.#y=0}get data(){return _l(this.#d)}get dataLength(){return this.#d.length}get consumed(){return this.#y}get bytes(){return new Uint8Array(this.#d)}#b(e){if(this.#f)return this.#f.#b(e);this.#m+=e,cl(this.#g<1||this.#m<=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:gl(this.#d),offset:this.#y,length:e,info:{bytesRead:this.#m,dataLength:this.dataLength}})}#w(e,t,n){let r=Math.ceil(t/oc)*oc;return this.#y+r>this.#d.length&&(this.allowLoose&&n&&this.#y+t<=this.#d.length?r=t:cl(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:gl(this.#d),length:this.#d.length,offset:this.#y+r})),this.#d.slice(this.#y,this.#y+r)}subReader(e){const t=new vc(this.#d.slice(this.#y+e),this.allowLoose,this.#g);return t.#f=this,t}readBytes(e,t){let n=this.#w(0,e,!!t);return this.#b(e),this.#y+=n.length,n.slice(0,e)}readValue(){return Fl(this.readBytes(oc))}readIndex(){return Hl(this.readBytes(oc))}}function _c(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Tc(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 xc(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 Ac(e,t){Tc(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Sc="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,kc=e=>e instanceof Uint8Array,Nc=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 Ec=async()=>{};function Ic(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)),!kc(e))throw new Error("expected Uint8Array, got "+typeof e);return e}class Oc{clone(){return this._cloneInto()}}const Cc={}.toString;function Rc(e){const t=t=>e().update(Ic(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}const $c=BigInt(2**32-1),Mc=BigInt(32);function Pc(e,t=!1){return t?{h:Number(e&$c),l:Number(e>>Mc&$c)}:{h:0|Number(e>>Mc&$c),l:0|Number(e&$c)}}function Fc(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const{h:a,l:i}=Pc(e[s],t);[n[s],r[s]]=[a,i]}return[n,r]}const Dc=(e,t,n)=>e<<n|t>>>32-n,Hc=(e,t,n)=>t<<n|e>>>32-n,Bc=(e,t,n)=>t<<n-32|e>>>64-n,jc=(e,t,n)=>e<<n-32|t>>>64-n;const Uc={fromBig:Pc,split:Fc,toBig:(e,t)=>BigInt(e>>>0)<<Mc|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:Dc,rotlSL:Hc,rotlBH:Bc,rotlBL:jc,add:function(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}},add3L:(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H:(e,t,n,r)=>t+n+r+(e/2**32|0)|0,add4L:(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),add4H:(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,add5H:(e,t,n,r,s,a)=>t+n+r+s+a+(e/2**32|0)|0,add5L:(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0)},[qc,Lc,Jc]=[[],[],[]],Gc=BigInt(0),zc=BigInt(1),Vc=BigInt(2),Kc=BigInt(7),Wc=BigInt(256),Zc=BigInt(113);for(let Up=0,qp=zc,Lp=1,Jp=0;Up<24;Up++){[Lp,Jp]=[Jp,(2*Lp+3*Jp)%5],qc.push(2*(5*Jp+Lp)),Lc.push((Up+1)*(Up+2)/2%64);let e=Gc;for(let t=0;t<7;t++)qp=(qp<<zc^(qp>>Kc)*Zc)%Wc,qp&Vc&&(e^=zc<<(zc<<BigInt(t))-zc);Jc.push(e)}const[Yc,Xc]=Fc(Jc,!0),Qc=(e,t,n)=>n>32?Bc(e,t,n):Dc(e,t,n),eu=(e,t,n)=>n>32?jc(e,t,n):Hc(e,t,n);class tu extends Oc{constructor(e,t,n,r=!1,s=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,_c(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Nc(this.state)}keccak(){!function(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let r=0;r<10;r++)n[r]=e[r]^e[r+10]^e[r+20]^e[r+30]^e[r+40];for(let r=0;r<10;r+=2){const t=(r+8)%10,s=(r+2)%10,a=n[s],i=n[s+1],o=Qc(a,i,1)^n[t],l=eu(a,i,1)^n[t+1];for(let n=0;n<50;n+=10)e[r+n]^=o,e[r+n+1]^=l}let t=e[2],s=e[3];for(let n=0;n<24;n++){const r=Lc[n],a=Qc(t,s,r),i=eu(t,s,r),o=qc[n];t=e[o],s=e[o+1],e[o]=a,e[o+1]=i}for(let r=0;r<50;r+=10){for(let t=0;t<10;t++)n[t]=e[r+t];for(let t=0;t<10;t++)e[r+t]^=~n[(t+2)%10]&n[(t+4)%10]}e[0]^=Yc[r],e[1]^=Xc[r]}n.fill(0)}(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){xc(this);const{blockLen:t,state:n}=this,r=(e=Ic(e)).length;for(let s=0;s<r;){const a=Math.min(t-this.pos,r-s);for(let t=0;t<a;t++)n[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){xc(this,!1),Tc(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,s=e.length;r<s;){this.posOut>=n&&this.keccak();const a=Math.min(n-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=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 _c(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ac(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:r,rounds:s,enableXOF:a}=this;return e||(e=new tu(t,n,r,a,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=r,e.enableXOF=a,e.destroyed=this.destroyed,e}}const nu=((e,t,n)=>Rc(()=>new tu(t,e,n)))(1,136,32);let ru=!1;const su=function(e){return nu(e)};let au=su;function iu(e){const t=fl(e,"data");return _l(au(t))}iu._=su,iu.lock=function(){ru=!0},iu.register=function(e){if(ru)throw new TypeError("keccak256 is locked");au=e},Object.freeze(iu);const ou="0x0000000000000000000000000000000000000000",lu=BigInt(0),cu=BigInt(36);function uu(e){const t=(e=e.toLowerCase()).substring(2).split(""),n=new Uint8Array(40);for(let s=0;s<40;s++)n[s]=t[s].charCodeAt(0);const r=fl(iu(n));for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&(t[s]=t[s].toUpperCase()),(15&r[s>>1])>=8&&(t[s+1]=t[s+1].toUpperCase());return"0x"+t.join("")}const du={};for(let Up=0;Up<10;Up++)du[String(Up)]=String(Up);for(let Up=0;Up<26;Up++)du[String.fromCharCode(65+Up)]=String(10+Up);function pu(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map(e=>du[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 hu=function(){const e={};for(let t=0;t<36;t++){e["0123456789abcdefghijklmnopqrstuvwxyz"[t]]=BigInt(t)}return e}();function yu(e){if(ul("string"==typeof e,"invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith("0x")||(e="0x"+e);const t=uu(e);return ul(!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}$/)){ul(e.substring(2,4)===pu(e),"bad icap checksum","address",e);let t=function(e){e=e.toLowerCase();let t=lu;for(let n=0;n<e.length;n++)t=t*cu+hu[e[n]];return t}(e.substring(4)).toString(16);for(;t.length<40;)t="0"+t;return uu("0x"+t)}ul(!1,"invalid address","address",e)}function mu(e){return e&&"function"==typeof e.getAddress}async function fu(e,t){const n=await t;return null!=n&&"0x0000000000000000000000000000000000000000"!==n||(cl("string"!=typeof e,"unconfigured name","UNCONFIGURED_NAME",{value:e}),ul(!1,"invalid AddressLike value; did not resolve to a value address","target",e)),yu(n)}function gu(e,t){return"string"==typeof e?e.match(/^0x[0-9a-f]{40}$/i)?yu(e):(cl(null!=t,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),fu(e,t.resolveName(e))):mu(e)?fu(e,e.getAddress()):e&&"function"==typeof e.then?fu(e,e):void ul(!1,"unsupported addressable value","target",e)}const bu={};function wu(e,t){let n=!1;return t<0&&(n=!0,t*=-1),new Tu(bu,`${n?"":"u"}int${t}`,e,{signed:n,width:t})}function vu(e,t){return new Tu(bu,`bytes${t||""}`,e,{size:t})}const _u=Symbol.for("_ethers_typed");class Tu{type;value;#v;_typedSymbol;constructor(e,t,n,r){null==r&&(r=null),yl(bu,e,"Typed"),sl(this,{_typedSymbol:_u,type:t,value:n}),this.#v=r,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 Tu(bu,e,t)}static uint8(e){return wu(e,8)}static uint16(e){return wu(e,16)}static uint24(e){return wu(e,24)}static uint32(e){return wu(e,32)}static uint40(e){return wu(e,40)}static uint48(e){return wu(e,48)}static uint56(e){return wu(e,56)}static uint64(e){return wu(e,64)}static uint72(e){return wu(e,72)}static uint80(e){return wu(e,80)}static uint88(e){return wu(e,88)}static uint96(e){return wu(e,96)}static uint104(e){return wu(e,104)}static uint112(e){return wu(e,112)}static uint120(e){return wu(e,120)}static uint128(e){return wu(e,128)}static uint136(e){return wu(e,136)}static uint144(e){return wu(e,144)}static uint152(e){return wu(e,152)}static uint160(e){return wu(e,160)}static uint168(e){return wu(e,168)}static uint176(e){return wu(e,176)}static uint184(e){return wu(e,184)}static uint192(e){return wu(e,192)}static uint200(e){return wu(e,200)}static uint208(e){return wu(e,208)}static uint216(e){return wu(e,216)}static uint224(e){return wu(e,224)}static uint232(e){return wu(e,232)}static uint240(e){return wu(e,240)}static uint248(e){return wu(e,248)}static uint256(e){return wu(e,256)}static uint(e){return wu(e,256)}static int8(e){return wu(e,-8)}static int16(e){return wu(e,-16)}static int24(e){return wu(e,-24)}static int32(e){return wu(e,-32)}static int40(e){return wu(e,-40)}static int48(e){return wu(e,-48)}static int56(e){return wu(e,-56)}static int64(e){return wu(e,-64)}static int72(e){return wu(e,-72)}static int80(e){return wu(e,-80)}static int88(e){return wu(e,-88)}static int96(e){return wu(e,-96)}static int104(e){return wu(e,-104)}static int112(e){return wu(e,-112)}static int120(e){return wu(e,-120)}static int128(e){return wu(e,-128)}static int136(e){return wu(e,-136)}static int144(e){return wu(e,-144)}static int152(e){return wu(e,-152)}static int160(e){return wu(e,-160)}static int168(e){return wu(e,-168)}static int176(e){return wu(e,-176)}static int184(e){return wu(e,-184)}static int192(e){return wu(e,-192)}static int200(e){return wu(e,-200)}static int208(e){return wu(e,-208)}static int216(e){return wu(e,-216)}static int224(e){return wu(e,-224)}static int232(e){return wu(e,-232)}static int240(e){return wu(e,-240)}static int248(e){return wu(e,-248)}static int256(e){return wu(e,-256)}static int(e){return wu(e,-256)}static bytes1(e){return vu(e,1)}static bytes2(e){return vu(e,2)}static bytes3(e){return vu(e,3)}static bytes4(e){return vu(e,4)}static bytes5(e){return vu(e,5)}static bytes6(e){return vu(e,6)}static bytes7(e){return vu(e,7)}static bytes8(e){return vu(e,8)}static bytes9(e){return vu(e,9)}static bytes10(e){return vu(e,10)}static bytes11(e){return vu(e,11)}static bytes12(e){return vu(e,12)}static bytes13(e){return vu(e,13)}static bytes14(e){return vu(e,14)}static bytes15(e){return vu(e,15)}static bytes16(e){return vu(e,16)}static bytes17(e){return vu(e,17)}static bytes18(e){return vu(e,18)}static bytes19(e){return vu(e,19)}static bytes20(e){return vu(e,20)}static bytes21(e){return vu(e,21)}static bytes22(e){return vu(e,22)}static bytes23(e){return vu(e,23)}static bytes24(e){return vu(e,24)}static bytes25(e){return vu(e,25)}static bytes26(e){return vu(e,26)}static bytes27(e){return vu(e,27)}static bytes28(e){return vu(e,28)}static bytes29(e){return vu(e,29)}static bytes30(e){return vu(e,30)}static bytes31(e){return vu(e,31)}static bytes32(e){return vu(e,32)}static address(e){return new Tu(bu,"address",e)}static bool(e){return new Tu(bu,"bool",!!e)}static bytes(e){return new Tu(bu,"bytes",e)}static string(e){return new Tu(bu,"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 Tu(bu,"overrides",Object.assign({},e))}static isTyped(e){return e&&"object"==typeof e&&"_typedSymbol"in e&&e._typedSymbol===_u}static dereference(e,t){if(Tu.isTyped(e)){if(e.type!==t)throw new Error(`invalid type: expecetd ${t}, got ${e.type}`);return e.value}return e}}class xu extends bc{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let n=Tu.dereference(t,"string");try{n=yu(n)}catch(r){return this._throwError(r.message,t)}return e.writeValue(n)}decode(e){return yu(Bl(e.readValue(),20))}}class Au extends bc{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 Su(e,t,n){let r=[];if(Array.isArray(n))r=n;else if(n&&"object"==typeof n){let e={};r=t.map(t=>{const r=t.localName;return cl(r,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),cl(!e[r],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),e[r]=!0,n[r]})}else ul(!1,"invalid tuple value","tuple",n);ul(t.length===r.length,"types/value length mismatch","tuple",n);let s=new wc,a=new wc,i=[];t.forEach((e,t)=>{let n=r[t];if(e.dynamic){let t=a.length;e.encode(a,n);let r=s.writeUpdatableValue();i.push(e=>{r(e+t)})}else e.encode(s,n)}),i.forEach(e=>{e(s.length)});let o=e.appendWriter(s);return o+=e.appendWriter(a),o}function ku(e,t){let n=[],r=[],s=e.subReader(0);return t.forEach(t=>{let a=null;if(t.dynamic){let n=e.readIndex(),r=s.subReader(n);try{a=t.decode(r)}catch(i){if(il(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(il(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),r.push(t.localName||null)}),fc.fromItems(n,r)}class Nu extends bc{coder;length;constructor(e,t,n){super("array",e.type+"["+(t>=0?t:"")+"]",n,-1===t||e.dynamic),sl(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=Tu.dereference(t,"array");Array.isArray(n)||this._throwError("expected array value",n);let r=this.length;-1===r&&(r=n.length,e.writeValue(n.length)),dl(n.length,r,"coder array"+(this.localName?" "+this.localName:""));let s=[];for(let a=0;a<n.length;a++)s.push(this.coder);return Su(e,s,n)}decode(e){let t=this.length;-1===t&&(t=e.readIndex(),cl(t*oc<=e.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:e.bytes,offset:t*oc,length:e.dataLength}));let n=[];for(let r=0;r<t;r++)n.push(new Au(this.coder));return ku(e,n)}}class Eu extends bc{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const n=Tu.dereference(t,"bool");return e.writeValue(n?1:0)}decode(e){return!!e.readValue()}}class Iu extends bc{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=gl(t);let n=e.writeValue(t.length);return n+=e.writeBytes(t),n}decode(e){return e.readBytes(e.readIndex(),!0)}}class Ou extends Iu{constructor(e){super("bytes",e)}decode(e){return _l(super.decode(e))}}class Cu extends bc{size;constructor(e,t){let n="bytes"+String(e);super(n,n,t,!1),sl(this,{size:e},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(e,t){let n=gl(Tu.dereference(t,this.type));return n.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(n)}decode(e){return _l(e.readBytes(this.size))}}const Ru=new Uint8Array([]);class $u extends bc{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return null!=t&&this._throwError("not null",t),e.writeBytes(Ru)}decode(e){return e.readBytes(0),null}}const Mu=BigInt(0),Pu=BigInt(1),Fu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class Du extends bc{size;signed;constructor(e,t,n){const r=(t?"int":"uint")+8*e;super(r,r,n,!1),sl(this,{size:e,signed:t},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(e,t){let n=$l(Tu.dereference(t,this.type)),r=Rl(Fu,256);if(this.signed){let e=Rl(r,8*this.size-1);(n>e||n<-(e+Pu))&&this._throwError("value out-of-bounds",t),n=Cl(n,256)}else(n<Mu||n>Rl(r,8*this.size))&&this._throwError("value out-of-bounds",t);return e.writeValue(n)}decode(e){let t=Rl(e.readValue(),8*this.size);return this.signed&&(t=Ol(t,8*this.size)),t}}class Hu extends Iu{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,Gl(Tu.dereference(t,"string")))}decode(e){return zl(super.decode(e))}}class Bu extends bc{coders;constructor(e,t){let n=!1;const r=[];e.forEach(e=>{e.dynamic&&(n=!0),r.push(e.type)});super("tuple","tuple("+r.join(",")+")",t,n),sl(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,r)=>{let s=n.localName;s&&1===t[s]&&("length"===s&&(s="_length"),null==e[s]&&(e[s]=e[r]))}),Object.freeze(e)}encode(e,t){const n=Tu.dereference(t,"tuple");return Su(e,this.coders,n)}decode(e){return ku(e,this.coders)}}function ju(e,t){return{address:yu(e),storageKeys:t.map((e,t)=>(ul(bl(e,32),"invalid slot",`storageKeys[${t}]`,e),e.toLowerCase()))}}function Uu(e){if(Array.isArray(e))return e.map((t,n)=>Array.isArray(t)?(ul(2===t.length,"invalid slot set",`value[${n}]`,t),ju(t[0],t[1])):(ul(null!=t&&"object"==typeof t,"invalid address-slot set","value",e),ju(t.address,t.storageKeys)));ul(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 ju(t,Object.keys(n).sort())});return t.sort((e,t)=>e.address.localeCompare(t.address)),t}function qu(e){return iu(Gl(e))}function Lu(e){const t=new Set;return e.forEach(e=>t.add(e)),Object.freeze(t)}const Ju=Lu("external public payable override".split(" ")),Gu="constant external internal payable private public pure view override",zu=Lu(Gu.split(" ")),Vu="constructor error event fallback function receive struct",Ku=Lu(Vu.split(" ")),Wu="calldata memory storage payable indexed",Zu=Lu(Wu.split(" ")),Yu=Lu([Vu,Wu,"tuple returns",Gu].join(" ").split(" ")),Xu={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},Qu=new RegExp("^(\\s*)"),ed=new RegExp("^([0-9]+)"),td=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),nd=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),rd=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class sd{#y;#_;get offset(){return this.#y}get length(){return this.#_.length-this.#y}constructor(e){this.#y=0,this.#_=e.slice()}clone(){return new sd(this.#_)}reset(){this.#y=0}#T(e=0,t=0){return new sd(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.#y+1,e.match+1);return this.#y=e.match+1,t}popParams(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=[];for(;this.#y<e.match-1;){const e=this.peek().linkNext;t.push(this.#T(this.#y+1,e)),this.#y=e}return this.#y=e.match+1,t}peek(){if(this.#y>=this.#_.length)throw new Error("out-of-bounds");return this.#_[this.#y]}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.#y++,e}toString(){const e=[];for(let t=this.#y;t<this.#_.length;t++){const n=this.#_[t];e.push(`${n.type}:${n.text}`)}return`<TokenString ${e.join(" ")}>`}}function ad(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 r=[],s=[],a=0;for(;a<e.length;){let i=e.substring(a),o=i.match(Qu);o&&(a+=o[1].length,i=e.substring(a));const l={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:a,value:-1};t.push(l);let c=Xu[i[0]]||"";if(c){if(l.type=c,l.text=i[0],a++,"OPEN_PAREN"===c)r.push(t.length-1),s.push(t.length-1);else if("CLOSE_PAREN"==c)0===r.length&&n("no matching open bracket"),l.match=r.pop(),t[l.match].match=t.length-1,l.depth--,l.linkBack=s.pop(),t[l.linkBack].linkNext=t.length-1;else if("COMMA"===c)l.linkBack=s.pop(),t[l.linkBack].linkNext=t.length-1,s.push(t.length-1);else if("OPEN_BRACKET"===c)l.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=Dl(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(td),o){if(l.text=o[1],a+=l.text.length,Yu.has(l.text)){l.type="KEYWORD";continue}if(l.text.match(rd)){l.type="TYPE";continue}l.type="ID"}else{if(o=i.match(ed),!o)throw new Error(`unexpected token ${JSON.stringify(i[0])} at position ${a}`);l.text=o[1],l.type="NUMBER",a+=l.text.length}}return new sd(t.map(e=>Object.freeze(e)))}function id(e,t){let n=[];for(const r in t.keys())e.has(r)&&n.push(r);if(n.length>1)throw new Error(`conflicting types: ${n.join(", ")}`)}function od(e,t){if(t.peekKeyword(Ku)){const n=t.pop().text;if(n!==e)throw new Error(`expected ${e}, got ${n}`)}return t.popType("ID")}function ld(e,t){const n=new Set;for(;;){const r=e.peekType("KEYWORD");if(null==r||t&&!t.has(r))break;if(e.pop(),n.has(r))throw new Error(`duplicate keywords: ${JSON.stringify(r)}`);n.add(r)}return Object.freeze(n)}function cd(e){let t=ld(e,zu);return id(t,Lu("constant payable nonpayable".split(" "))),id(t,Lu("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 ud(e,t){return e.popParams().map(e=>Ad.from(e,t))}function dd(e){if(e.peekType("AT")){if(e.pop(),e.peekType("NUMBER"))return $l(e.pop().text);throw new Error("invalid gas")}return null}function pd(e){if(e.length)throw new Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`)}const hd=new RegExp(/^(.*)\[([0-9]*)\]$/);function yd(e){const t=e.match(rd);if(ul(t,"invalid type","type",e),"uint"===e)return"uint256";if("int"===e)return"int256";if(t[2]){const n=parseInt(t[2]);ul(0!==n&&n<=32,"invalid bytes length","type",e)}else if(t[3]){const n=parseInt(t[3]);ul(0!==n&&n<=256&&n%8==0,"invalid numeric width","type",e)}return e}const md={},fd=Symbol.for("_ethers_internal"),gd="_ParamTypeInternal",bd="_ErrorInternal",wd="_EventInternal",vd="_ConstructorInternal",_d="_FallbackInternal",Td="_FunctionInternal",xd="_StructInternal";class Ad{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(e,t,n,r,s,a,i,o){if(yl(e,md,"ParamType"),Object.defineProperty(this,fd,{value:gd}),a&&(a=Object.freeze(a.slice())),"array"===r){if(null==i||null==o)throw new Error("")}else if(null!=i||null!=o)throw new Error("");if("tuple"===r){if(null==a)throw new Error("")}else if(null!=a)throw new Error("");sl(this,{name:t,type:n,baseType:r,indexed:s,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,r)=>n.components[r].walk(e,t))}return t(this.type,e)}#x(e,t,n,r){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 s=this.arrayChildren,a=t.slice();return a.forEach((t,r)=>{s.#x(e,t,n,e=>{a[r]=e})}),void r(a)}if(this.isTuple()){const s=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=s.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,r)=>{s[r].#x(e,t,n,e=>{a[r]=e})}),void r(a)}const s=n(this.type,t);s.then?e.push(async function(){r(await s)}()):r(s)}async walkAsync(e,t){const n=[],r=[e];return this.#x(n,e,t,e=>{r[0]=e}),n.length&&await Promise.all(n),r[0]}static from(e,t){if(Ad.isParamType(e))return e;if("string"==typeof e)try{return Ad.from(ad(e),t)}catch(i){ul(!1,"invalid param type","obj",e)}else if(e instanceof sd){let n="",r="",s=null;ld(e,Lu(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(r="tuple",s=e.popParams().map(e=>Ad.from(e)),n=`tuple(${s.map(e=>e.format()).join(",")})`):(n=yd(e.popType("TYPE")),r=n);let a=null,i=null;for(;e.length&&e.peekType("BRACKET");){const t=e.pop();a=new Ad(md,"",n,r,null,s,i,a),i=t.value,n+=t.text,r="array",s=null}let o=null;if(ld(e,Zu).has("indexed")){if(!t)throw new Error("");o=!0}const l=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new Ad(md,l,n,r,o,s,i,a)}const n=e.name;ul(!n||"string"==typeof n&&n.match(nd),"invalid name","obj.name",n);let r=e.indexed;null!=r&&(ul(t,"parameter cannot be indexed","obj.indexed",e.indexed),r=!!r);let s=e.type,a=s.match(hd);if(a){const t=parseInt(a[2]||"-1"),i=Ad.from({type:a[1],components:e.components});return new Ad(md,n||"",s,"array",r,null,t,i)}if("tuple"===s||s.startsWith("tuple(")||s.startsWith("(")){const t=null!=e.components?e.components.map(e=>Ad.from(e)):null;return new Ad(md,n||"",s,"tuple",r,t,null,null)}return s=yd(e.type),new Ad(md,n||"",s,s,r,null,null,null)}static isParamType(e){return e&&e[fd]===gd}}class Sd{type;inputs;constructor(e,t,n){yl(e,md,"Fragment"),sl(this,{type:t,inputs:n=Object.freeze(n.slice())})}static from(e){if("string"==typeof e){try{Sd.from(JSON.parse(e))}catch(t){}return Sd.from(ad(e))}if(e instanceof sd){switch(e.peekKeyword(Ku)){case"constructor":return Od.from(e);case"error":return Ed.from(e);case"event":return Id.from(e);case"fallback":case"receive":return Cd.from(e);case"function":return Rd.from(e);case"struct":return $d.from(e)}}else if("object"==typeof e){switch(e.type){case"constructor":return Od.from(e);case"error":return Ed.from(e);case"event":return Id.from(e);case"fallback":case"receive":return Cd.from(e);case"function":return Rd.from(e);case"struct":return $d.from(e)}cl(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}ul(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return Od.isFragment(e)}static isError(e){return Ed.isFragment(e)}static isEvent(e){return Id.isFragment(e)}static isFunction(e){return Rd.isFragment(e)}static isStruct(e){return $d.isFragment(e)}}class kd extends Sd{name;constructor(e,t,n,r){super(e,t,r),ul("string"==typeof n&&n.match(nd),"invalid identifier","name",n),r=Object.freeze(r.slice()),sl(this,{name:n})}}function Nd(e,t){return"("+t.map(t=>t.format(e)).join("full"===e?", ":",")+")"}class Ed extends kd{constructor(e,t,n){super(e,"error",t,n),Object.defineProperty(this,fd,{value:bd})}get selector(){return qu(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+Nd(e,this.inputs)),t.join(" ")}static from(e){if(Ed.isFragment(e))return e;if("string"==typeof e)return Ed.from(ad(e));if(e instanceof sd){const t=od("error",e),n=ud(e);return pd(e),new Ed(md,t,n)}return new Ed(md,e.name,e.inputs?e.inputs.map(Ad.from):[])}static isFragment(e){return e&&e[fd]===bd}}class Id extends kd{anonymous;constructor(e,t,n,r){super(e,"event",t,n),Object.defineProperty(this,fd,{value:wd}),sl(this,{anonymous:r})}get topicHash(){return qu(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+Nd(e,this.inputs)),"sighash"!==e&&this.anonymous&&t.push("anonymous"),t.join(" ")}static getTopicHash(e,t){t=(t||[]).map(e=>Ad.from(e));return new Id(md,e,t,!1).topicHash}static from(e){if(Id.isFragment(e))return e;if("string"==typeof e)try{return Id.from(ad(e))}catch(t){ul(!1,"invalid event fragment","obj",e)}else if(e instanceof sd){const t=od("event",e),n=ud(e,!0),r=!!ld(e,Lu(["anonymous"])).has("anonymous");return pd(e),new Id(md,t,n,r)}return new Id(md,e.name,e.inputs?e.inputs.map(e=>Ad.from(e,!0)):[],!!e.anonymous)}static isFragment(e){return e&&e[fd]===wd}}class Od extends Sd{payable;gas;constructor(e,t,n,r,s){super(e,t,n),Object.defineProperty(this,fd,{value:vd}),sl(this,{payable:r,gas:s})}format(e){if(cl(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${Nd(e,this.inputs)}`];return this.payable&&t.push("payable"),null!=this.gas&&t.push(`@${this.gas.toString()}`),t.join(" ")}static from(e){if(Od.isFragment(e))return e;if("string"==typeof e)try{return Od.from(ad(e))}catch(t){ul(!1,"invalid constuctor fragment","obj",e)}else if(e instanceof sd){ld(e,Lu(["constructor"]));const t=ud(e),n=!!ld(e,Ju).has("payable"),r=dd(e);return pd(e),new Od(md,"constructor",t,n,r)}return new Od(md,"constructor",e.inputs?e.inputs.map(Ad.from):[],!!e.payable,null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[fd]===vd}}class Cd extends Sd{payable;constructor(e,t,n){super(e,"fallback",t),Object.defineProperty(this,fd,{value:_d}),sl(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(Cd.isFragment(e))return e;if("string"==typeof e)try{return Cd.from(ad(e))}catch(t){ul(!1,"invalid fallback fragment","obj",e)}else if(e instanceof sd){const t=e.toString();ul(e.peekKeyword(Lu(["fallback","receive"])),"type must be fallback or receive","obj",t);if("receive"===e.popKeyword(Lu(["fallback","receive"]))){const t=ud(e);return ul(0===t.length,"receive cannot have arguments","obj.inputs",t),ld(e,Lu(["payable"])),pd(e),new Cd(md,[],!0)}let n=ud(e);n.length?ul(1===n.length&&"bytes"===n[0].type,"invalid fallback inputs","obj.inputs",n.map(e=>e.format("minimal")).join(", ")):n=[Ad.from("bytes")];const r=cd(e);if(ul("nonpayable"===r||"payable"===r,"fallback cannot be constants","obj.stateMutability",r),ld(e,Lu(["returns"])).has("returns")){const t=ud(e);ul(1===t.length&&"bytes"===t[0].type,"invalid fallback outputs","obj.outputs",t.map(e=>e.format("minimal")).join(", "))}return pd(e),new Cd(md,n,"payable"===r)}if("receive"===e.type)return new Cd(md,[],!0);if("fallback"===e.type){const t=[Ad.from("bytes")],n="payable"===e.stateMutability;return new Cd(md,t,n)}ul(!1,"invalid fallback description","obj",e)}static isFragment(e){return e&&e[fd]===_d}}class Rd extends kd{constant;outputs;stateMutability;payable;gas;constructor(e,t,n,r,s,a){super(e,"function",t,r),Object.defineProperty(this,fd,{value:Td});sl(this,{constant:"view"===n||"pure"===n,gas:a,outputs:s=Object.freeze(s.slice()),payable:"payable"===n,stateMutability:n})}get selector(){return qu(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+Nd(e,this.inputs)),"sighash"!==e&&("nonpayable"!==this.stateMutability&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push("returns"),t.push(Nd(e,this.outputs))),null!=this.gas&&t.push(`@${this.gas.toString()}`)),t.join(" ")}static getSelector(e,t){t=(t||[]).map(e=>Ad.from(e));return new Rd(md,e,"view",t,[],null).selector}static from(e){if(Rd.isFragment(e))return e;if("string"==typeof e)try{return Rd.from(ad(e))}catch(n){ul(!1,"invalid function fragment","obj",e)}else if(e instanceof sd){const t=od("function",e),n=ud(e),r=cd(e);let s=[];ld(e,Lu(["returns"])).has("returns")&&(s=ud(e));const a=dd(e);return pd(e),new Rd(md,t,r,n,s,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 Rd(md,e.name,t,e.inputs?e.inputs.map(Ad.from):[],e.outputs?e.outputs.map(Ad.from):[],null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[fd]===Td}}class $d extends kd{constructor(e,t,n){super(e,"struct",t,n),Object.defineProperty(this,fd,{value:xd})}format(){throw new Error("@TODO")}static from(e){if("string"==typeof e)try{return $d.from(ad(e))}catch(t){ul(!1,"invalid struct fragment","obj",e)}else if(e instanceof sd){const t=od("struct",e),n=ud(e);return pd(e),new $d(md,t,n)}return new $d(md,e.name,e.inputs?e.inputs.map(Ad.from):[])}static isFragment(e){return e&&e[fd]===xd}}const Md=new Map;Md.set(0,"GENERIC_PANIC"),Md.set(1,"ASSERT_FALSE"),Md.set(17,"OVERFLOW"),Md.set(18,"DIVIDE_BY_ZERO"),Md.set(33,"ENUM_RANGE_ERROR"),Md.set(34,"BAD_STORAGE_DATA"),Md.set(49,"STACK_UNDERFLOW"),Md.set(50,"ARRAY_RANGE_ERROR"),Md.set(65,"OUT_OF_MEMORY"),Md.set(81,"UNINITIALIZED_FUNCTION_CALL");const Pd=new RegExp(/^bytes([0-9]*)$/),Fd=new RegExp(/^(u?int)([0-9]*)$/);let Dd=null,Hd=1024;class Bd{#A(e){if(e.isArray())return new Nu(this.#A(e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new Bu(e.components.map(e=>this.#A(e)),e.name);switch(e.baseType){case"address":return new xu(e.name);case"bool":return new Eu(e.name);case"string":return new Hu(e.name);case"bytes":return new Ou(e.name);case"":return new $u(e.name)}let t=e.type.match(Fd);if(t){let n=parseInt(t[2]||"256");return ul(0!==n&&n<=256&&n%8==0,"invalid "+t[1]+" bit length","param",e),new Du(n/8,"int"===t[1],e.name)}if(t=e.type.match(Pd),t){let n=parseInt(t[1]);return ul(0!==n&&n<=32,"invalid bytes length","param",e),new Cu(n,e.name)}ul(!1,"invalid type","type",e.type)}getDefaultValue(e){const t=e.map(e=>this.#A(Ad.from(e)));return new Bu(t,"_").defaultValue()}encode(e,t){dl(t.length,e.length,"types/values length mismatch");const n=e.map(e=>this.#A(Ad.from(e))),r=new Bu(n,"_"),s=new wc;return r.encode(s,t),s.data}decode(e,t,n){const r=e.map(e=>this.#A(Ad.from(e)));return new Bu(r,"_").decode(new vc(t,n,Hd))}static _setDefaultMaxInflation(e){ul("number"==typeof e&&Number.isInteger(e),"invalid defaultMaxInflation factor","value",e),Hd=e}static defaultAbiCoder(){return null==Dd&&(Dd=new Bd),Dd}static getBuiltinCallException(e,t,n){return function(e,t,n,r){let s="missing revert data",a=null,i=null;if(n){s="execution reverted";const e=fl(n);if(n=_l(n),0===e.length)s+=" (no data present; likely require(false) occurred",a="require(false)";else if(e.length%32!=4)s+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===_l(e.slice(0,4)))try{a=r.decode(["string"],e.slice(4))[0],i={signature:"Error(string)",name:"Error",args:[a]},s+=`: ${JSON.stringify(a)}`}catch(l){s+=" (could not decode reason; invalid string data)"}else if("0x4e487b71"===_l(e.slice(0,4)))try{const t=Number(r.decode(["uint256"],e.slice(4))[0]);i={signature:"Panic(uint256)",name:"Panic",args:[t]},a=`Panic due to ${Md.get(t)||"UNKNOWN"}(${t})`,s+=`: ${a}`}catch(l){s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const o={to:t.to?yu(t.to):null,data:t.data||"0x"};return t.from&&(o.from=yu(t.from)),ll(s,"CALL_EXCEPTION",{action:e,data:n,reason:a,transaction:o,invocation:null,revert:i})}(e,t,n,Bd.defaultAbiCoder())}}class jd{fragment;name;signature;topic;args;constructor(e,t,n){const r=e.name,s=e.format();sl(this,{fragment:e,name:r,signature:s,topic:t,args:n})}}class Ud{fragment;name;args;signature;selector;value;constructor(e,t,n,r){const s=e.name,a=e.format();sl(this,{fragment:e,name:s,args:n,signature:a,selector:t,value:r})}}class qd{fragment;name;args;signature;selector;constructor(e,t,n){const r=e.name,s=e.format();sl(this,{fragment:e,name:r,args:n,signature:s,selector:t})}}class Ld{hash;_isIndexed;static isIndexed(e){return!(!e||!e._isIndexed)}constructor(e){sl(this,{hash:e,_isIndexed:!0})}}const Jd={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"},Gd={"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&&Jd[e.toString()]&&(t=Jd[e.toString()]),`reverted with panic code 0x${e.toString(16)} (${t})`}}};class zd{fragments;deploy;fallback;receive;#S;#k;#N;#E;constructor(e){let t=[];t="string"==typeof e?JSON.parse(e):e,this.#N=new Map,this.#S=new Map,this.#k=new Map;const n=[];for(const i of t)try{n.push(Sd.from(i))}catch(a){console.log(`[Warning] Invalid Fragment ${JSON.stringify(i)}:`,a.message)}sl(this,{fragments:Object.freeze(n)});let r=null,s=!1;this.#E=this.getAbiCoder(),this.fragments.forEach((e,t)=>{let n;switch(e.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void sl(this,{deploy:e});case"fallback":return void(0===e.inputs.length?s=!0:(ul(!r||e.payable!==r.payable,"conflicting fallback fragments",`fragments[${t}]`,e),r=e,s=r.payable));case"function":n=this.#N;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||sl(this,{deploy:Od.from("constructor()")}),sl(this,{fallback:r,receive:s})}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 Bd.defaultAbiCoder()}#I(e,t,n){if(bl(e)){const t=e.toLowerCase();for(const e of this.#N.values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const r=[];for(const[t,n]of this.#N)t.split("(")[0]===e&&r.push(n);if(t){const e=t.length>0?t[t.length-1]:null;let n=t.length,s=!0;Tu.isTyped(e)&&"overrides"===e.type&&(s=!1,n--);for(let t=r.length-1;t>=0;t--){const e=r[t].inputs.length;e===n||s&&e===n-1||r.splice(t,1)}for(let a=r.length-1;a>=0;a--){const e=r[a].inputs;for(let n=0;n<t.length;n++)if(Tu.isTyped(t[n])){if(n>=e.length){if("overrides"===t[n].type)continue;r.splice(a,1);break}if(t[n].type!==e[n].baseType){r.splice(a,1);break}}}}if(1===r.length&&t&&t.length!==r[0].inputs.length){const e=t[t.length-1];(null==e||Array.isArray(e)||"object"!=typeof e)&&r.splice(0,1)}if(0===r.length)return null;if(r.length>1&&n){ul(!1,`ambiguous function description (i.e. matches ${r.map(e=>JSON.stringify(e.format())).join(", ")})`,"key",e)}return r[0]}const r=this.#N.get(Rd.from(e).format());return r||null}getFunctionName(e){const t=this.#I(e,null,!1);return ul(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.#N.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){const r=t[n];e(this.#N.get(r),n)}}#O(e,t,n){if(bl(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 r=[];for(const[t,n]of this.#k)t.split("(")[0]===e&&r.push(n);if(t){for(let e=r.length-1;e>=0;e--)r[e].inputs.length<t.length&&r.splice(e,1);for(let e=r.length-1;e>=0;e--){const n=r[e].inputs;for(let s=0;s<t.length;s++)if(Tu.isTyped(t[s])&&t[s].type!==n[s].baseType){r.splice(e,1);break}}}if(0===r.length)return null;if(r.length>1&&n){ul(!1,`ambiguous event description (i.e. matches ${r.map(e=>JSON.stringify(e.format())).join(", ")})`,"key",e)}return r[0]}const r=this.#k.get(Id.from(e).format());return r||null}getEventName(e){const t=this.#O(e,null,!1);return ul(t,"no matching event","key",e),t.name}hasEvent(e){return!!this.#O(e,null,!1)}getEvent(e,t){return this.#O(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 r=t[n];e(this.#k.get(r),n)}}getError(e,t){if(bl(e)){const t=e.toLowerCase();if(Gd[t])return Ed.from(Gd[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,r]of this.#S)n.split("(")[0]===e&&t.push(r);if(0===t.length)return"Error"===e?Ed.from("error Error(string)"):"Panic"===e?Ed.from("error Panic(uint256)"):null;if(t.length>1){ul(!1,`ambiguous error description (i.e. ${t.map(e=>JSON.stringify(e.format())).join(", ")})`,"name",e)}return t[0]}if("Error(string)"===(e=Ed.from(e).format()))return Ed.from("error Error(string)");if("Panic(uint256)"===e)return Ed.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 r=t[n];e(this.#S.get(r),n)}}_decodeParams(e,t){return this.#E.decode(e,t)}_encodeParams(e,t){return this.#E.encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);ul(t,"unknown error","fragment",e),e=t}return ul(xl(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,xl(t,4))}encodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);ul(t,"unknown error","fragment",e),e=t}return Tl([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);ul(t,"unknown function","fragment",e),e=t}return ul(xl(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,xl(t,4))}encodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);ul(t,"unknown function","fragment",e),e=t}return Tl([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);ul(t,"unknown function","fragment",e),e=t}let n="invalid length for result data";const r=gl(t);if(r.length%32==0)try{return this.#E.decode(e.outputs,r)}catch(s){n="could not decode result data"}cl(!1,n,"BAD_DATA",{value:_l(r),info:{method:e.name,signature:e.format()}})}makeError(e,t){const n=fl(e,"data"),r=Bd.getBuiltinCallException("call",t,n);if(r.message.startsWith("execution reverted (unknown custom error)")){const e=_l(n.slice(0,4)),t=this.getError(e);if(t)try{const e=this.#E.decode(t.inputs,n.slice(4));r.revert={name:t.name,signature:t.format(),args:e},r.reason=r.revert.signature,r.message=`execution reverted: ${r.reason}`}catch(a){r.message="execution reverted (coult not decode custom error)"}}const s=this.parseTransaction(t);return s&&(r.invocation={method:s.name,signature:s.signature,args:s.args}),r}encodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);ul(t,"unknown function","fragment",e),e=t}return _l(this.#E.encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if("string"==typeof e){const t=this.getEvent(e);ul(t,"unknown event","eventFragment",e),e=t}cl(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 r=(e,t)=>"string"===e.type?qu(t):"bytes"===e.type?iu(_l(t)):("bool"===e.type&&"boolean"==typeof t?t=t?"0x01":"0x00":e.type.match(/^u?int/)?t=Bl(t):e.type.match(/^bytes/)?t=kl(t,32):"address"===e.type&&this.#E.encode(["address"],[t]),Sl(_l(t),32));for(t.forEach((t,s)=>{const a=e.inputs[s];a.indexed?null==t?n.push(null):"array"===a.baseType||"tuple"===a.baseType?ul(!1,"filtering with tuples or arrays not supported","contract."+a.name,t):Array.isArray(t)?n.push(t.map(e=>r(a,e))):n.push(r(a,t)):ul(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);ul(t,"unknown event","eventFragment",e),e=t}const n=[],r=[],s=[];return e.anonymous||n.push(e.topicHash),ul(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(qu(i));else if("bytes"===e.type)n.push(iu(i));else{if("tuple"===e.baseType||"array"===e.baseType)throw new Error("not implemented");n.push(this.#E.encode([e.type],[i]))}else r.push(e),s.push(i)}),{data:this.#E.encode(r,s),topics:n}}decodeEventLog(e,t,n){if("string"==typeof e){const t=this.getEvent(e);ul(t,"unknown event","eventFragment",e),e=t}if(null!=n&&!e.anonymous){const t=e.topicHash;ul(bl(n[0],32)&&n[0].toLowerCase()===t,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const r=[],s=[],a=[];e.inputs.forEach((e,t)=>{e.indexed?"string"===e.type||"bytes"===e.type||"tuple"===e.baseType||"array"===e.baseType?(r.push(Ad.from({type:"bytes32",name:e.name})),a.push(!0)):(r.push(e),a.push(!1)):(s.push(e),a.push(!1))});const i=null!=n?this.#E.decode(r,Tl(n)):null,o=this.#E.decode(s,t,!0),l=[],c=[];let u=0,d=0;return e.inputs.forEach((e,t)=>{let n=null;if(e.indexed)if(null==i)n=new Ld(null);else if(a[t])n=new Ld(i[d++]);else try{n=i[d++]}catch(r){n=r}else try{n=o[u++]}catch(r){n=r}l.push(n),c.push(e.name||null)}),fc.fromItems(l,c)}parseTransaction(e){const t=fl(e.data,"tx.data"),n=$l(null!=e.value?e.value:0,"tx.value"),r=this.getFunction(_l(t.slice(0,4)));if(!r)return null;const s=this.#E.decode(r.inputs,t.slice(4));return new Ud(r,r.selector,s,n)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new jd(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=_l(e),n=this.getError(xl(t,0,4));if(!n)return null;const r=this.#E.decode(n.inputs,xl(t,4));return new qd(n,n.selector,r)}static from(e){return e instanceof zd?e:"string"==typeof e?new zd(JSON.parse(e)):"function"==typeof e.formatJson?new zd(e.formatJson()):"function"==typeof e.format?new zd(e.format("json")):new zd(e)}}const Vd=BigInt(0);function Kd(e){return null==e?null:e}function Wd(e){return null==e?null:e.toString()}function Zd(e){const t={};e.to&&(t.to=e.to),e.from&&(t.from=e.from),e.data&&(t.data=_l(e.data));const n="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of n)s in e&&null!=e[s]&&(t[s]=$l(e[s],`request.${s}`));const r="type,nonce".split(/,/);for(const s of r)s in e&&null!=e[s]&&(t[s]=Dl(e[s],`request.${s}`));return e.accessList&&(t.accessList=Uu(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=>wl(e)?_l(e):Object.assign({},e))),t}class Yd{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#C;constructor(e,t){this.#C=e.transactions.map(e=>"string"!=typeof e?new ep(e,t):e),sl(this,{provider:t,hash:Kd(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:Kd(e.prevRandao),extraData:e.extraData,baseFeePerGas:Kd(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot})}get transactions(){return this.#C.map(e=>"string"==typeof e?e:e.hash)}get prefetchedTransactions(){const e=this.#C.slice();return 0===e.length?[]:(cl("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:r,gasUsed:s,hash:a,miner:i,prevRandao:o,nonce:l,number:c,parentHash:u,parentBeaconBlockRoot:d,stateRoot:p,receiptsRoot:h,timestamp:y,transactions:m}=this;return{_type:"Block",baseFeePerGas:Wd(e),difficulty:Wd(t),extraData:n,gasLimit:Wd(r),gasUsed:Wd(s),blobGasUsed:Wd(this.blobGasUsed),excessBlobGas:Wd(this.excessBlobGas),hash:a,miner:i,prevRandao:o,nonce:l,number:c,parentHash:u,timestamp:y,parentBeaconBlockRoot:d,stateRoot:p,receiptsRoot:h,transactions:m}}[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.#C.length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(e){let t;if("number"==typeof e)t=this.#C[e];else{const n=e.toLowerCase();for(const e of this.#C){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;ul(!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 Xd{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(e,t){this.provider=t;const n=Object.freeze(e.topics.slice());sl(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:r,index:s,removed:a,topics:i,transactionHash:o,transactionIndex:l}=this;return{_type:"log",address:e,blockHash:t,blockNumber:n,data:r,index:s,removed:a,topics:i,transactionHash:o,transactionIndex:l}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return cl(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return cl(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return cl(!!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 Qd{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 Xd(e,t)));let n=Vd;null!=e.effectiveGasPrice?n=e.effectiveGasPrice:null!=e.gasPrice&&(n=e.gasPrice),sl(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:r,index:s,blockHash:a,blockNumber:i,logsBloom:o,logs:l,status:c,root:u}=this;return{_type:"TransactionReceipt",blockHash:a,blockNumber:i,contractAddress:n,cumulativeGasUsed:Wd(this.cumulativeGasUsed),from:t,gasPrice:Wd(this.gasPrice),blobGasUsed:Wd(this.blobGasUsed),blobGasPrice:Wd(this.blobGasPrice),gasUsed:Wd(this.gasUsed),hash:r,index:s,logs:l,logsBloom:o,root:u,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 np(this)}reorderedEvent(e){return cl(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),tp(this,e)}}class ep{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:r,type:s,to:a,from:i,nonce:o,data:l,signature:c,accessList:u,blobVersionedHashes:d}=this;return{_type:"TransactionResponse",accessList:u,blockNumber:e,blockHash:t,blobVersionedHashes:d,chainId:Wd(this.chainId),data:l,from:i,gasLimit:Wd(this.gasLimit),gasPrice:Wd(this.gasPrice),hash:r,maxFeePerGas:Wd(this.maxFeePerGas),maxPriorityFeePerGas:Wd(this.maxPriorityFeePerGas),maxFeePerBlobGas:Wd(this.maxFeePerBlobGas),nonce:o,signature:c,to:a,index:n,type:s,value:Wd(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 rl({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,r=null==t?0:t;let s=this.#$,a=-1,i=-1===s;const o=async()=>{if(i)return null;const{blockNumber:e,nonce:t}=await rl({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(t<this.nonce)return void(s=e);if(i)return null;const r=await this.getTransaction();if(!r||null==r.blockNumber)for(-1===a&&(a=s-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 r=0;r<t.length;r++){const a=await t.getTransaction(r);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 r="replaced";a.data===this.data&&a.to===this.to&&a.value===this.value?r="repriced":"0x"===a.data&&a.from===a.to&&a.value===Vd&&(r="cancelled"),cl(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===r||"cancelled"===r,reason:r,replacement:a.replaceableTransaction(s),hash:a.hash,receipt:t})}}a++}},l=e=>{if(null==e||0!==e.status)return e;cl(!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 l(c);if(c){if(1===n||await c.confirmations()>=n)return l(c)}else if(await o(),0===n)return null;const u=new Promise((e,t)=>{const a=[],c=()=>{a.forEach(e=>e())};if(a.push(()=>{i=!0}),r>0){const e=setTimeout(()=>{c(),t(ll("wait for transaction timeout","TIMEOUT"))},r);a.push(()=>{clearTimeout(e)})}const u=async r=>{if(await r.confirmations()>=n){c();try{e(l(r))}catch(s){t(s)}}};if(a.push(()=>{this.provider.off(this.hash,u)}),this.provider.on(this.hash,u),s>=0){const e=async()=>{try{await o()}catch(n){if(il(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 u}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 cl(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),np(this)}reorderedEvent(e){return cl(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),cl(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),tp(this,e)}replaceableTransaction(e){ul(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const t=new ep(this,this.provider);return t.#$=e,t}}function tp(e,t){return{orphan:"reorder-transaction",tx:e,other:t}}function np(e){return{orphan:"drop-transaction",tx:e}}class rp extends Xd{interface;fragment;args;constructor(e,t,n){super(e,e.provider);sl(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 sp extends Xd{error;constructor(e,t){super(e,e.provider),sl(this,{error:t})}}class ap extends Qd{#M;constructor(e,t,n){super(n,t),this.#M=e}get logs(){return super.logs.map(e=>{const t=e.topics.length?this.#M.getEvent(e.topics[0]):null;if(t)try{return new rp(e,this.#M,t)}catch(n){return new sp(e,n)}return e})}}class ip extends ep{#M;constructor(e,t,n){super(n,t),this.#M=e}async wait(e,t){const n=await super.wait(e,t);return null==n?null:new ap(this.#M,this.provider,n)}}class op extends Ul{log;constructor(e,t,n,r){super(e,t,n),sl(this,{log:r})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class lp extends op{constructor(e,t,n,r,s){super(e,t,n,new rp(s,e.interface,r));sl(this,{args:e.interface.decodeEventLog(r,this.log.data,this.log.topics),fragment:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const cp=BigInt(0);function up(e){return e&&"function"==typeof e.call}function dp(e){return e&&"function"==typeof e.estimateGas}function pp(e){return e&&"function"==typeof e.resolveName}function hp(e){return e&&"function"==typeof e.sendTransaction}function yp(e){if(null!=e){if(pp(e))return e;if(e.provider)return e.provider}}class mp{#P;fragment;constructor(e,t,n){if(sl(this,{fragment:t}),t.inputs.length<n.length)throw new Error("too many arguments");const r=fp(e.runner,"resolveName"),s=pp(r)?r:null;this.#P=async function(){const r=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=>gu(e,s))):gu(t,s):t)));return e.interface.encodeFilterTopics(t,r)}()}getTopicFilter(){return this.#P}}function fp(e,t){return null==e?null:"function"==typeof e[t]?e:e.provider&&"function"==typeof e.provider[t]?e.provider:null}function gp(e){return null==e?null:e.provider||null}async function bp(e,t){const n=Tu.dereference(e,"overrides");ul("object"==typeof n,"invalid overrides parameter","overrides",e);const r=Zd(n);return ul(null==r.to||(t||[]).indexOf("to")>=0,"cannot override to","overrides.to",r.to),ul(null==r.data||(t||[]).indexOf("data")>=0,"cannot override data","overrides.data",r.data),r.from&&(r.from=r.from),r}async function wp(e,t,n){const r=fp(e,"resolveName"),s=pp(r)?r:null;return await Promise.all(t.map((e,t)=>e.walkAsync(n[t],(e,t)=>(t=Tu.dereference(t,e),"address"===e?gu(t,s):t))))}function vp(e){const t=async function(t){const n=await bp(t,["data"]);n.to=await e.getAddress(),n.from&&(n.from=await gu(n.from,yp(e.runner)));const r=e.interface,s=$l(n.value||cp,"overrides.value")===cp,a="0x"===(n.data||"0x");!r.fallback||r.fallback.payable||!r.receive||a||s||ul(!1,"cannot send data to receive or send value to non-payable fallback","overrides",t),ul(r.fallback||a,"cannot send data to receive-only contract","overrides.data",n.data);return ul(r.receive||r.fallback&&r.fallback.payable||s,"cannot send value to non-payable fallback","overrides.value",n.value),ul(r.fallback||a,"cannot send data to receive-only contract","overrides.data",n.data),n},n=async function(n){const r=e.runner;cl(hp(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await r.sendTransaction(await t(n)),a=gp(e.runner);return new ip(e.interface,a,s)},r=async e=>await n(e);return sl(r,{_contract:e,estimateGas:async function(n){const r=fp(e.runner,"estimateGas");return cl(dp(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await t(n))},populateTransaction:t,send:n,staticCall:async function(n){const r=fp(e.runner,"call");cl(up(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await t(n);try{return await r.call(s)}catch(a){if(ol(a)&&a.data)throw e.interface.makeError(a.data,s);throw a}}}),r}const _p=Symbol.for("_ethersInternal_contract"),Tp=new WeakMap;function xp(e){return Tp.get(e[_p])}async function Ap(e,t){let n,r=null;if(Array.isArray(t)){const r=function(t){if(bl(t,32))return t;const n=e.interface.getEvent(t);return ul(n,"unknown fragment","name",t),n.topicHash};n=t.map(e=>null==e?null:Array.isArray(e)?e.map(r):r(e))}else"*"===t?n=[null]:"string"==typeof t?bl(t,32)?n=[t]:(r=e.interface.getEvent(t),ul(r,"unknown fragment","event",t),n=[r.topicHash]):(s=t)&&"object"==typeof s&&"getTopicFilter"in s&&"function"==typeof s.getTopicFilter&&s.fragment?n=await t.getTopicFilter():"fragment"in t?(r=t.fragment,n=[r.topicHash]):ul(!1,"unknown event name","event",t);var s;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:r,tag:n.map(e=>null==e?"null":Array.isArray(e)?e.join("|"):e).join("&"),topics:n}}async function Sp(e,t){const{subs:n}=xp(e);return n.get((await Ap(e,t)).tag)||null}async function kp(e,t,n){const r=gp(e.runner);cl(r,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:t});const{fragment:s,tag:a,topics:i}=await Ap(e,n),{addr:o,subs:l}=xp(e);let c=l.get(a);if(!c){const t={address:o||e,topics:i},u=t=>{let r=s;if(null==r)try{r=e.interface.getEvent(t.topics[0])}catch(a){}if(r){const a=r,i=s?e.interface.decodeEventLog(s,t.data,t.topics):[];Ep(e,n,i,r=>new lp(e,r,n,a,t))}else Ep(e,n,[],r=>new op(e,r,n,t))};let d=[];c={tag:a,listeners:[],start:()=>{d.length||d.push(r.on(t,u))},stop:async()=>{if(0==d.length)return;let e=d;d=[],await Promise.all(e),r.off(t,u)}},l.set(a,c)}return c}let Np=Promise.resolve();async function Ep(e,t,n,r){try{await Np}catch(a){}const s=async function(e,t,n,r){await Np;const s=await Sp(e,t);if(!s)return!1;const i=s.listeners.length;return s.listeners=s.listeners.filter(({listener:t,once:s})=>{const i=Array.from(n);r&&i.push(r(s?null:t));try{t.call(e,...i)}catch(a){}return!s}),0===s.listeners.length&&(s.stop(),xp(e).subs.delete(s.tag)),i>0}(e,t,n,r);return Np=s,await s}const Ip=["then"];class Op{target;interface;runner;filters;[_p];fallback;constructor(e,t,n,r){ul("string"==typeof e||mu(e),"invalid value for Contract target","target",e),null==n&&(n=null);const s=zd.from(t);let a;sl(this,{target:e,runner:n,interface:s}),Object.defineProperty(this,_p,{value:{}});let i=null,o=null;if(r){const e=gp(n);o=new ip(this.interface,e,r)}let l=new Map;if("string"==typeof e)if(bl(e))i=e,a=Promise.resolve(e);else{const t=fp(n,"resolveName");if(!pp(t))throw ll("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});a=t.resolveName(e).then(t=>{if(null==t)throw ll("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:e});return xp(this).addr=t,t})}else a=e.getAddress().then(e=>{if(null==e)throw new Error("TODO");return xp(this).addr=e,e});var c,u;c=this,u={addrPromise:a,addr:i,deployTx:o,subs:l},Tp.set(c[_p],u);return sl(this,{filters:new Proxy({},{get:(e,t,n)=>{if("symbol"==typeof t||Ip.indexOf(t)>=0)return Reflect.get(e,t,n);try{return this.getEvent(t)}catch(r){if(!il(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(e,t)=>Ip.indexOf(t)>=0?Reflect.has(e,t):Reflect.has(e,t)||this.interface.hasEvent(String(t))})}),sl(this,{fallback:s.receive||s.fallback?vp(this):null}),new Proxy(this,{get:(e,t,n)=>{if("symbol"==typeof t||t in e||Ip.indexOf(t)>=0)return Reflect.get(e,t,n);try{return e.getFunction(t)}catch(r){if(!il(r,"INVALID_ARGUMENT")||"key"!==r.argument)throw r}},has:(e,t)=>"symbol"==typeof t||t in e||Ip.indexOf(t)>=0?Reflect.has(e,t):e.interface.hasFunction(t)})}connect(e){return new Op(this.target,this.interface,e)}attach(e){return new Op(e,this.interface,this.runner)}async getAddress(){return await xp(this).addrPromise}async getDeployedCode(){const e=gp(this.runner);cl(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=gp(this.runner);return cl(null!=t,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((e,n)=>{const r=async()=>{try{if(null!=await this.getDeployedCode())return e(this);t.once("block",r)}catch(s){n(s)}};r()})}deploymentTransaction(){return xp(this).deployTx}getFunction(e){"string"!=typeof e&&(e=e.format());const t=function(e,t){const n=function(...n){const r=e.interface.getFunction(t,n);return cl(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),r},r=async function(...t){const r=n(...t);let s={};if(r.inputs.length+1===t.length&&(s=await bp(t.pop()),s.from&&(s.from=await gu(s.from,yp(e.runner)))),r.inputs.length!==t.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const a=await wp(e.runner,r.inputs,t);return Object.assign({},s,await rl({to:e.getAddress(),data:e.interface.encodeFunctionData(r,a)}))},s=async function(...e){const t=await i(...e);return 1===t.length?t[0]:t},a=async function(...t){const n=e.runner;cl(hp(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await n.sendTransaction(await r(...t)),a=gp(e.runner);return new ip(e.interface,a,s)},i=async function(...t){const s=fp(e.runner,"call");cl(up(s),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const a=await r(...t);let i="0x";try{i=await s.call(a)}catch(l){if(ol(l)&&l.data)throw e.interface.makeError(l.data,a);throw l}const o=n(...t);return e.interface.decodeFunctionResult(o,i)},o=async(...e)=>n(...e).constant?await s(...e):await a(...e);return sl(o,{name:e.interface.getFunctionName(t),_contract:e,_key:t,getFragment:n,estimateGas:async function(...t){const n=fp(e.runner,"estimateGas");return cl(dp(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await r(...t))},populateTransaction:r,send:a,staticCall:s,staticCallResult:i}),Object.defineProperty(o,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getFunction(t);return cl(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 r=e.interface.getEvent(t,n);return cl(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),r},r=function(...t){return new mp(e,n(...t),t)};return sl(r,{name:e.interface.getEventName(t),_contract:e,_key:t,getFragment:n}),Object.defineProperty(r,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getEvent(t);return cl(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),r}(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,n){null==t&&(t=0),null==n&&(n="latest");const{addr:r,addrPromise:s}=xp(this),a=r||await s,{fragment:i,topics:o}=await Ap(this,e),l={address:a,topics:o,fromBlock:t,toBlock:n},c=gp(this.runner);return cl(c,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await c.getLogs(l)).map(e=>{let t=i;if(null==t)try{t=this.interface.getEvent(e.topics[0])}catch(n){}if(t)try{return new rp(e,this.interface,t)}catch(n){return new sp(e,n)}return new Xd(e,c)})}async on(e,t){const n=await kp(this,"on",e);return n.listeners.push({listener:t,once:!1}),n.start(),this}async once(e,t){const n=await kp(this,"once",e);return n.listeners.push({listener:t,once:!0}),n.start(),this}async emit(e,...t){return await Ep(this,e,t,null)}async listenerCount(e){if(e){const t=await Sp(this,e);return t?t.listeners.length:0}const{subs:t}=xp(this);let n=0;for(const{listeners:r}of t.values())n+=r.length;return n}async listeners(e){if(e){const t=await Sp(this,e);return t?t.listeners.map(({listener:e})=>e):[]}const{subs:t}=xp(this);let n=[];for(const{listeners:r}of t.values())n=n.concat(r.map(({listener:e})=>e));return n}async off(e,t){const n=await Sp(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(),xp(this).subs.delete(n.tag)),this}async removeAllListeners(e){if(e){const t=await Sp(this,e);if(!t)return this;t.stop(),xp(this).subs.delete(t.tag)}else{const{subs:e}=xp(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 Op{constructor(t,n=null){super(t,e,n)}}}static from(e,t,n){null==n&&(n=null);return new this(e,t,n)}}class Cp extends(function(){return Op}()){}const Rp={Splitter:Bo,Managed:jo,Zoned:Uo,Appreciative:qo,Bundle:Lo,Holons:Jo,TestToken:Zo};function $p(e){return Number(ic(e))}const Mp=30078,Pp=30079,Fp=30080;class Dp extends Error{constructor(e,t=null){super(e),this.name="AuthorizationError",this.requiredPermission=t}}class Hp extends Error{constructor(e){super(e),this.name="ValidationError"}}const Bp=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 Ho(e),n=await t.connect(e.network,e.privateKey,e.rpcUrl),r=new Xo(t),s=new el(t,r);return this._contracts={chainManager:t,deployer:r,holonContracts:s,network:e.network},{...n,address:e.privateKey?await t.getAddress():null}}async initContractsBrowser(e){const t=new Ho,n=await t.connectBrowser(e),r=new Xo(t),s=new el(t,r);return this._contracts={chainManager:t,deployer:r,holonContracts:s,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:r}=this._requireContracts();return r.deploy(e,t,n)}async linkHolonContract(e,t,n="Splitter"){const{holonContracts:r}=this._requireContracts();return r.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,r=6){return this.getHolonOperations(e).createZonedContract(t,n,r)}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,r){return this.getHolonOperations(e).addToZone(t,n,r)}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,r,s){return this.getHolonOperations(e).setZoneParameters(t,n,r,s)}async contractAppreciate(e,t,n,r){return this.getHolonOperations(e).appreciate(t,n,r)}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 Do}getChainManager(){return this._contracts?.chainManager||null}}}(function(e){return class extends e{async addFederatedHolosphere(e,t={}){if(!e||"string"!=typeof e)throw new Hp("pubKey must be a valid public key string");return pt(this.client,this.config.appName,e,t)}async removeFederatedHolosphere(e){return async function(e,t,n){const r=await ut(e,t),s=r.federatedWith.length;return r.federatedWith=r.federatedWith.filter(e=>e.pubKey!==n),r.federatedWith.length!==s&&dt(e,t,r)}(this.client,this.config.appName,e)}async getFederatedHolospheres(){return async function(e,t){return(await ut(e,t)).federatedWith.map(e=>e.pubKey)}(this.client,this.config.appName)}async getFederationRegistry(){return ut(this.client,this.config.appName)}async storeInboundCapability(e,t){return yt(this.client,this.config.appName,e,t)}async readFromFederatedSource(e,t,n,r=null){const s=await ht(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:r});if(!s)throw new Dp("No valid capability for federated source","read");if(!(await this.verifyCapability(s.token,"read",{holonId:t,lensName:n,dataId:r})))throw new Dp("Capability verification failed","read");if(r){const s=ie(this.config.appName,t,n,r);return Q(this.client,s,3e4,{authors:[e],includeAuthor:!0})}{const r=ie(this.config.appName,t,n);return ee(this.client,r,3e4,{authors:[e],includeAuthor:!0})}}async createCrossHolosphereHologram(e,t,n,r,s,a={}){const{embedCapability:i=!0}=a,o=await ht(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:r});if(!o)throw new Dp("No valid capability for cross-holosphere hologram","read");const l=ft(t,0,n,r,this.config.appName,{authorPubKey:e,capability:i?o.token:null}),c=ie(this.config.appName,s,n,r);return await oe(this.client,c,l),l}async issueCapabilityForFederation(e,t,n,r={}){const{expiresIn:s=36e5,trackInRegistry:a=!0}=r,i=await at(n,t,e,{expiresIn:s,issuerKey:this.client.privateKey});if(a){await async function(e,t,n){return(await ut(e,t)).federatedWith.find(e=>e.pubKey===n)||null}(this.client,this.config.appName,e)||await pt(this.client,this.config.appName,e,{addedVia:"capability_issued"}),await async function(e,t,n,r){const s=await ut(e,t),a=s.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:r.tokenHash,scope:r.scope,permissions:r.permissions,issuedAt:Date.now(),expires:r.expires}),dt(e,t,s)}(this.client,this.config.appName,e,{tokenHash:await this._hashToken(i),scope:t,permissions:n,expires:Date.now()+s})}return i}async _hashToken(e){const t=new TextEncoder;return $e(Xe(t.encode(e)))}async sendFederationRequest(e,t={}){return async function(e,t,n,r={}){const{scope:s={holonId:"*",lensName:"*"},permissions:a=["read"],message:i="Federation request",expiresIn:o=2592e6}=r,l=await at(a,s,n,{issuerKey:e.privateKey,expiresIn:o}),c={kind:Mp,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-request-${n.slice(0,16)}`],["p",n],["holosphere",t],["scope",JSON.stringify(s)],["permissions",a.join(",")]],content:JSON.stringify({message:i,offeredCapability:l,requestedScope:s,requestedPermissions:a})},u=await e.publish(c);return{eventId:u.id||null,targetPubKey:n,scope:s,permissions:a,offeredCapability:l,...u}}(this.client,this.config.appName,e,t)}async subscribeFederationRequests(e){return async function(e,t){const n={kinds:[Mp],"#p":[e.publicKey]};return e.subscribe(n,e=>{try{const n=JSON.parse(e.content),r=e.tags.find(e=>"scope"===e[0]),s=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:r?JSON.parse(r[1]):{holonId:"*",lensName:"*"},permissions:s?s[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,r={}){const{scope:s=n.scope,permissions:a=n.permissions,alias:i=null,expiresIn:o=2592e6}=r,l=await at(a,s,n.requesterPubKey,{issuerKey:e.privateKey,expiresIn:o});await pt(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:Pp,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(s)],["permissions",a.join(",")]],content:JSON.stringify({acceptedScope:s,grantedCapability:l})},u=await e.publish(c);return{eventId:u.id||null,requesterPubKey:n.requesterPubKey,grantedCapability:l,acceptedScope:s,...u}}(this.client,this.config.appName,e,t)}async declineFederationRequest(e,t=""){return async function(e,t,n,r=""){const s={kind:Fp,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:r})},a=await e.publish(s);return{eventId:a.id||null,requesterPubKey:n.requesterPubKey,reason:r,...a}}(this.client,this.config.appName,e,t)}async subscribeFederationAcceptances(e){return async function(e,t,n){const r={kinds:[Pp],"#p":[e.publicKey]};return e.subscribe(r,async r=>{try{const s=JSON.parse(r.content),a=r.tags.find(e=>"scope"===e[0]),i=r.tags.find(e=>"permissions"===e[0]);await yt(e,t,r.pubkey,{token:s.grantedCapability,scope:a?JSON.parse(a[1]):s.acceptedScope,permissions:i?i[1].split(","):["read"],expires:Date.now()+2592e6}),n({accepterPubKey:r.pubkey,originalRequestId:r.tags.find(e=>"e"===e[0])?.[1],acceptedScope:s.acceptedScope,grantedCapability:s.grantedCapability,timestamp:r.created_at})}catch(s){console.error("Failed to parse federation acceptance:",s)}})}(this.client,this.config.appName,e)}async subscribeFederationDeclines(e){return async function(e,t){const n={kinds:[Fp],"#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),r={kinds:[Mp],authors:[e.publicKey],since:n},s=await e.query(r),a={kinds:[Pp,Fp],"#p":[e.publicKey],since:n},i=await e.query(a),o=new Set;for(const u of i){const e=u.tags.find(e=>"e"===e[0]);e&&o.add(e[1])}const l=[];for(const u of s)if(!o.has(u.id))try{const e=JSON.parse(u.content),t=u.tags.find(e=>"p"===e[0]),n=u.tags.find(e=>"scope"===e[0]),r=u.tags.find(e=>"permissions"===e[0]);l.push({eventId:u.id,targetPubKey:t?.[1],scope:n?JSON.parse(n[1]):{holonId:"*",lensName:"*"},permissions:r?r[1].split(","):["read"],message:e.message,timestamp:u.created_at})}catch(c){console.error("Failed to parse pending request:",c)}return l}(this.client,e)}}}((jp=class extends G{constructor(e){super(e),this.schemas=new Map,this._cache=new Map,this.subscriptionRegistry=new Yt,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 ho(e,n)};const r=new(0,require("openai").default)({apiKey:e});this._ai.openai=r,this._ai.embeddings=new fo(r,this),this._ai.schemaExtractor=new yo(this._ai.llm),this._ai.jsonOps=new mo(this._ai.llm),this._ai.council=new bo(this._ai.llm),this._ai.tts=new _o(r),this._ai.nlQuery=new To(this._ai.llm,this),this._ai.classifier=new xo(this._ai.llm,this),this._ai.spatial=new Ao(this._ai.llm,this),this._ai.aggregation=new So(this._ai.llm,this),this._ai.federationAdvisor=new ko(this._ai.llm,this,this._ai.embeddings),this._ai.relationships=new No(this._ai.llm,this,this._ai.embeddings),this._ai.taskBreakdown=new Eo(this._ai.llm,this),this._ai.h3ai=new Io(this._ai.llm,this)}hasAI(){return null!==this._ai}getAIServices(){return this._ai}async toHolon(e,t,n){return z(e,t,n)}async getParents(e,t){return V(e,t)}async getChildren(e){return K(e)}isValidH3(e){return W(e)}async write(e,t,n,r={}){if(!e||"string"!=typeof e)throw new we("ValidationError: holonId must be a non-empty string");if(!t||"string"!=typeof t)throw new we("ValidationError: lensName must be a non-empty string");if(!n||"object"!=typeof n)throw new we("ValidationError: data must be an object");const s=r.capabilityToken||r.capability;if(s&&!(await this.verifyCapability(s,"write",{holonId:e,lensName:t})))throw new Dp("AuthorizationError: Invalid capability token for write operation","write");n.id||(n.id=`${Date.now()}-${Math.random().toString(36).substr(2,9)}`);const a=ie(this.config.appName,e,t,n.id),i=await le(this.client,a);if(i&&!0===i.hologram&&i.target){const e=["hologram","soul","target","id","_meta"],s=Object.keys(i).filter(t=>!e.includes(t)),o={...i},l={};for(const[t,r]of Object.entries(n))e.includes(t)||"_hologram"===t||(s.includes(t)?o[t]=r:l[t]=r);if(Object.keys(l).length>0&&!1!==r.validate&&this.schemas.has(t)){const e=ie(i.target.appname||this.config.appName,i.target.holonId,i.target.lensName,i.target.dataId),n={...await le(this.client,e),...l},s=this.schemas.get(t),a=void 0!==r.strict?r.strict:s.strict;s.schema&&"object"==typeof s.schema&&!s.schema.$ref&&_e(n,s.schema,t,a)}const c=Date.now();if(await oe(this.client,a,o),Object.keys(l).length>0){const e=ie(i.target.appname||this.config.appName,i.target.holonId,i.target.lensName,i.target.dataId);await ue(this.client,e,l),await kt(this.client,i.target.appname||this.config.appName,i.target.holonId,i.target.lensName,i.target.dataId)}const u=Date.now();return this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=u-c,!0}if(n._meta||(n._meta={}),n._meta.createdAt=n._meta.createdAt||Date.now(),n._meta.updatedAt=Date.now(),!1!==r.validate&&this.schemas.has(t)){const e=this.schemas.get(t),s=void 0!==r.strict?r.strict:e.strict;e.schema&&"object"==typeof e.schema&&!e.schema.$ref&&_e(n,e.schema,t,s)}const o=Date.now();await oe(this.client,a,n);const l=Date.now();this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=l-o;const{autoPropagate:c=!0}=r;return c&&!n.hologram&&await this.propagate(e,t,n,r.propagationOptions||{}),!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=ie(e.target.appname||this.config.appName,e.target.holonId,e.target.lensName,e.target.dataId);if(t.has(n))return console.warn(`Circular hologram reference detected: ${n}`),null;t.add(n);let r={};e.target.authorPubKey&&(r.authors=[e.target.authorPubKey],r.includeAuthor=!0);const s=await le(this.client,n,r);if(s){let n=s;if(!0===s.hologram&&s.target&&(n=await this._resolveHolograms(s,t),null===n))return null;const r=["hologram","soul","target","_meta","id","capability","crossHolosphere"],a={};for(const[t,s]of Object.entries(e))r.includes(t)||(a[t]=s);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,r={}){if(!e||"string"!=typeof e)throw new we("ValidationError: holonId must be a non-empty string");if(!t||"string"!=typeof t)throw new we("ValidationError: lensName must be a non-empty string");const s=r.capabilityToken||r.capability;if(s&&!(await this.verifyCapability(s,"read",{holonId:e,lensName:t,dataId:n})))throw new Dp("AuthorizationError: Invalid capability token for read operation","read");const a=Date.now();let i;if(n){const r=ie(this.config.appName,e,t,n);i=await le(this.client,r)}else{const n=ie(this.config.appName,e,t);i=await ce(this.client,n)}const{resolveHolograms:o=!0}=r;o&&(i=await this._resolveHolograms(i));const l=Date.now();return this._metrics.reads++,this._metrics.totalReadTime||(this._metrics.totalReadTime=0),this._metrics.totalReadTime+=l-a,i}async update(e,t,n,r,s={}){if(!e||"string"!=typeof e)throw new we("ValidationError: holonId must be a non-empty string");if(!t||"string"!=typeof t)throw new we("ValidationError: lensName must be a non-empty string");if(!n||"string"!=typeof n)throw new we("ValidationError: dataId must be a non-empty string");if(!r||"object"!=typeof r)throw new we("ValidationError: updates must be an object");const a=s.capabilityToken||s.capability;if(a&&!(await this.verifyCapability(a,"write",{holonId:e,lensName:t,dataId:n})))throw new Dp("AuthorizationError: Invalid capability token for update operation","write");const i=ie(this.config.appName,e,t,n),o=await le(this.client,i);if(!o)return!1;if(!0===o.hologram&&o.target)return this.write(e,t,{...o,...r,id:n},s);const l={...o,...r};if(l._meta=l._meta||{},l._meta.updatedAt=Date.now(),!1!==s.validate&&this.schemas.has(t)){const e=this.schemas.get(t),n=void 0!==s.strict?s.strict:e.strict;e.schema&&"object"==typeof e.schema&&!e.schema.$ref&&_e(l,e.schema,t,n)}const c=Date.now();await oe(this.client,i,l);const u=Date.now();return this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=u-c,o._meta&&o._meta.activeHolograms&&await kt(this.client,this.config.appName,e,t,n),!0}async delete(e,t,n,r={}){if(!e||"string"!=typeof e)throw new we("ValidationError: holonId must be a non-empty string");if(!t||"string"!=typeof t)throw new we("ValidationError: lensName must be a non-empty string");if(!n||"string"!=typeof n)throw new we("ValidationError: dataId must be a non-empty string");const s=ie(this.config.appName,e,t,n),a=await le(this.client,s);if(!a)return!1;const i=a.owner||a._creator,o=!i||i===this.client.publicKey,l=r.capabilityToken||r.capability;if(o){if(l&&!(await this.verifyCapability(l,"delete",{holonId:e,lensName:t,dataId:n})))throw new Dp("AuthorizationError: Invalid capability token for delete operation","delete")}else{if(!l)throw new Dp("AuthorizationError: Capability token required for delete operation","delete");if(!(await this.verifyCapability(l,"delete",{holonId:e,lensName:t,dataId:n})))throw new Dp("AuthorizationError: Invalid capability token for delete operation","delete")}return!0===a.hologram?this.deleteHologram(e,t,n,r):(await de(this.client,s),this._metrics.deletes++,!0)}async writeGlobal(e,t){return me(this.client,this.config.appName,e,t)}async readGlobal(e,t=null){return fe(this.client,this.config.appName,e,t)}async updateGlobal(e,t,n){return async function(e,t,n,r,s){return ue(e,`${t}/${n}/${r}`,s)}(this.client,this.config.appName,e,t,n)}async deleteGlobal(e,t){return async function(e,t,n,r){return de(e,`${t}/${n}/${r}`)}(this.client,this.config.appName,e,t)}async getAllGlobal(e){return async function(e,t,n){return ce(e,`${t}/${n}`)}(this.client,this.config.appName,e)}async deleteAllGlobal(e){return async function(e,t,n){return pe(e,`${t}/${n}`)}(this.client,this.config.appName,e)}async getAll(e,t){return this.read(e,t,null)}async deleteAll(e,t){const n=ie(this.config.appName,e,t);return pe(this.client,n)}async setSchema(e,t,n=!1){if(!e||"string"!=typeof e)throw new we("ValidationError: lensName must be a non-empty string");if(null==t)throw new we("ValidationError: schema cannot be null or undefined");let r;if("string"==typeof t)r={$ref:t};else{if("object"!=typeof t)throw new we("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 we("ValidationError: Invalid JSON Schema format");r=t}this.schemas.set(e,{schema:r,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,r={}){const{direction:s="outbound",mode:a="reference",filter:i=null}=r;if(e===t)throw new Error("Cannot federate a holon with itself");if(!["inbound","outbound","bidirectional"].includes(s))throw new Error(`Invalid direction: ${s}. Must be 'inbound', 'outbound', or 'bidirectional'`);return await bt(this.client,this.config.appName,e,t,n,r),"outbound"!==s&&"bidirectional"!==s||await this._propagateExistingData(e,t,n,{mode:a,filter:i}),"inbound"!==s&&"bidirectional"!==s||await this._propagateExistingData(t,e,n,{mode:a,filter:i}),this._metrics.federations=(this._metrics.federations||0)+1,!0}async _propagateExistingData(e,t,n,r={}){const{mode:s="reference",filter:a=null}=r,i=await this.read(e,n,null,{resolveHolograms:!1});if(!i)return;const o=Array.isArray(i)?i:[i];for(const l of o)!0!==l.hologram&&(a&&!a(l)||await wt(this.client,this.config.appName,l,e,t,n,s))}async getFederatedData(e,t,n={}){const{resolveHolograms:r=!0}=n,s=ie(this.config.appName,e,t),a=await ce(this.client,s);return a&&r?this._resolveHolograms(a):a}async unfederate(e,t,n){const r=ie(this.config.appName,e,n,"_federation");try{await de(this.client,r)}catch(s){}return!0}async updateHologramOverrides(e,t,n,r){return vt(this.client,this.config.appName,e,t,n,r)}createHologram(e,t,n,r=null){return ft(e,0,t,n.id,this.config.appName)}async getActiveHolograms(e,t,n){const r=ie(this.config.appName,e,t,n),s=await le(this.client,r);return s&&s._meta&&s._meta.activeHolograms?s._meta.activeHolograms:[]}async removeActiveHologram(e,t,n,r){return St(this.client,this.config.appName,e,t,n,r)}async deleteHologram(e,t,n,r={}){return Nt(this.client,this.config.appName,e,t,n,r)}async propagateData(e,t,n,r,s={}){const a=s.mode||"reference";return wt(this.client,this.config.appName,e,t,n,r,a)}async resolveHologram(e,t={}){return gt(this.client,e,new Set,[],{...t,appname:this.config.appName})}isHologram(e){return _t(e)}isResolvedHologram(e){return Tt(e)}getHologramSource(e){return xt(e)}async cleanupCircularHolograms(e,t,n={}){return Et(this.client,this.config.appName,e,t,n)}async cleanupCircularHologramsByIds(e,t,n,r={}){return It(this.client,this.config.appName,e,t,n,r)}async propagate(e,t,n,r={}){const s=await this.getFederation(e),a=s?.federated||s?.outbound||[];if(!a||0===a.length)return;const{useHolograms:i=!0,resolveExisting:o=!0}=r,l=[];for(const c of a){const r=await this.propagateData(n,e,c,t,{useHolograms:i,resolveExisting:o});l.push({parent:c,...r})}return l}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={}),!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:r={inbound:[],outbound:[]}}=n;if(e===t)throw new Error("Cannot federate a holon with itself");let s=await this.readGlobal("federation",e)||{id:e,name:e,federated:[],inbound:[],outbound:[],lensConfig:{},timestamp:Date.now()};Array.isArray(s.federated)||(s.federated=[]),Array.isArray(s.inbound)||(s.inbound=[]),Array.isArray(s.outbound)||(s.outbound=[]),s.lensConfig&&"object"==typeof s.lensConfig||(s.lensConfig={}),s.federated.includes(t)||s.federated.push(t),r.outbound&&r.outbound.length>0?s.outbound.includes(t)||s.outbound.push(t):s.outbound=s.outbound.filter(e=>e!==t),r.inbound&&r.inbound.length>0?s.inbound.includes(t)||s.inbound.push(t):s.inbound=s.inbound.filter(e=>e!==t),s.lensConfig[t]={inbound:r.inbound||[],outbound:r.outbound||[],timestamp:Date.now()};const a=await this.writeGlobal("federation",s);if(this.clearCache("federation"),a){for(const n of r.inbound||[])await this.federate(t,e,n,{direction:"outbound",mode:"reference"});for(const n of r.outbound||[])await this.federate(e,t,n,{direction:"outbound",mode:"reference"})}return a}async unfederateHolon(e,t){const n=await this.readGlobal("federation",e);if(!n)return!1;const r=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 s=await this.writeGlobal("federation",n);if(this.clearCache("federation"),s&&r){for(const n of r.inbound||[])await this.unfederate(t,e,n);for(const n of r.outbound||[])await this.unfederate(e,t,n)}return s}async getFederatedConfig(e,t){const n=await this.readGlobal("federation",e);return n&&n.lensConfig&&n.lensConfig[t]||null}async upcast(e,t,n,r={}){return Qt(this,e,t,n,r)}subscribe(e,t,n,r={}){if("function"!=typeof n)throw new TypeError("callback must be a function");const s=ie(this.config.appName,e,t),a={realtimeOnly:!0,...r},i=`${e}-${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;let o=null,l=!1;return Zt(this.client,s,n,a).then(e=>{o=e,l?e.unsubscribe():this.subscriptionRegistry.register(i,e)}).catch(e=>{this._log("ERROR","Subscription setup failed",{path:s,error:e.message})}),this._metrics.subscriptions=(this._metrics.subscriptions||0)+1,{unsubscribe:()=>{l=!0,o&&this.subscriptionRegistry.unregister(i)}}}async subscribeGlobal(e,t,n,r={}){return async function(e,t,n,r,s,a={}){return he(e,r?`${t}/${n}/${r}`:`${t}/${n}`,s,a)}(this.client,this.config.appName,e,t,n,r)}async getPublicKey(e){return tt(e)}async sign(e,t){return nt(e,t)}async verify(e,t,n){return rt(e,t,n)}async issueCapability(e,t,n,r){return at(e,t,n,r)}async verifyCapability(e,t,n){return it(e,t,n)}async publishNostr(e,t,n="social"){zt(e,!0,!0);const r=Ht({...e,tags:[...e.tags||[],["h",t],["l",n]]},this.client.privateKey),s={...r,protocol:"nostr"},a=ie(this.config.appName,t,n,r.id);return await oe(this.client,a,s),!0}async publishActivityPub(e,t,n="social"){Vt(e,!0);const r=Kt({...e,actor:e.actor||this.client.publicKey});return this.write(t,n,r)}async querySocial(e,t={}){const n=t.lens||"social",r=await this.read(e,n);return r?(Array.isArray(r)?r:[r]).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:r,kind:s,tags:a,content:i,sig:o}=e;return Bt({id:t,pubkey:n,created_at:r,kind:s,tags:a,content:i,sig:o})}metrics(){const e=this._metrics.reads||0,t=this._metrics.writes||0,n=this._metrics.totalReadTime||0,r=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?r/t:0}}async put(e,t,n,r={}){return this.write(e,t,n,r)}async get(e,t,n=null,r={}){return this.read(e,t,n,r)}async remove(e,t,n,r={}){return this.delete(e,t,n,r)}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,r={}){return this.write(e,t,n,r)}async fetch(e,t,n=null,r={}){return this.read(e,t,n,r)}async save(e,t,n,r={}){return this.write(e,t,n,r)}async load(e,t,n=null,r={}){return this.read(e,t,n,r)}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 jp{_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 r=await this.getSchema(t);if(!r)throw new Error(`No schema found for lens: ${t}`);return this._ai.schemaExtractor.extractToSchema(e,r,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,r={}){return this._requireAI(),this._ai.embeddings.semanticSearch(e,t,n,r)}async storeWithEmbedding(e,t,n,r="description"){return this._requireAI(),this._ai.embeddings.storeWithEmbedding(e,t,n,r)}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,r={}){return this._requireAI(),this._ai.nlQuery.execute(e,t,n,r)}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,r={}){return this._requireAI(),this._ai.spatial.analyzeRegion(e,t,n,r)}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,r={}){return this._requireAI(),this._ai.relationships.findSimilar(e,t,n,r)}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,r={}){return this._requireAI(),this._ai.taskBreakdown.breakdown(e,t,n,r)}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,r={}){return this._requireAI(),this._ai.h3ai.suggestGeographicScope(e,t,n,r)}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,r={}){return this._requireAI(),this._ai.h3ai.suggestMigration(e,t,n,r)}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,r={}){return this._requireAI(),this._ai.h3ai.analyzeGeographicImpact(e,t,n,r)}})));var jp;exports.ABIs=Yo,exports.AbiCoder=Bd,exports.AuthorizationError=Dp,exports.BaseContract=Op,exports.Block=Yd,exports.ChainManager=Ho,exports.Classifier=xo,exports.ConstructorFragment=Od,exports.Contract=Cp,exports.ContractDeployer=Xo,exports.ContractEventPayload=lp,exports.ContractOperations=Qo,exports.ContractQueries=class{constructor(e){this.provider=e}getContract(e,t){const n=Rp[t];if(!n)throw new Error(`Unknown contract flavor: ${t}`);return new Cp(e,n,this.provider)}async detectFlavor(e){const t=new Cp(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),[r,s,a,i,o]=await Promise.all([n.name().catch(()=>""),n.flavor().catch(()=>t),n.version().catch(()=>""),n.creator().catch(()=>ou),n.getSize().catch(()=>0n)]);return{address:e,name:r,flavor:s,version:a,creator:i,memberCount:Number(o)}}async getMembers(e,t){const n=this.getContract(e,t),r=await n.getSize(),s=[];for(let a=0;a<r;a++){const e=await n.userIds(a);s.push(e)}return s}async getUserEthBalance(e,t,n){const r=this.getContract(e,t),s=await r.etherBalance(n);return{wei:s.toString(),eth:$p(s)}}async getUserTokenBalance(e,t,n,r){const s=this.getContract(e,t),a=await s.tokenBalance(n,r);return{wei:a.toString(),formatted:$p(a)}}async getTotalDeposited(e,t,n){const r=this.getContract(e,t),s=n||ou,a=await r.totalDeposited(s);return{wei:a.toString(),formatted:$p(a)}}async hasClaimed(e,t,n){return this.getContract(e,t).hasClaimed(n)}async getSplitterSplit(e){const t=this.getContract(e,"Splitter"),[n,r]=await Promise.all([t.internalContractSplitPercentage(),t.externalContractSplitPercentage()]);return{internalPercentage:Number(n),externalPercentage:Number(r),internalPercent:Number(n)/100,externalPercent:Number(r)/100}}async getSplitterChildren(e){const t=this.getContract(e,"Splitter"),[n,r]=await t.getContractAddresses(),s=[];for(let a=0;a<n.length;a++)s.push({key:n[a],address:r[a]});return s}async getSplitterUserPercentage(e,t){const n=this.getContract(e,"Splitter"),r=await n.percentages(t);return{basisPoints:Number(r),percent:Number(r)/100}}async getSplitterAllPercentages(e){const t=await this.getMembers(e,"Splitter"),n=this.getContract(e,"Splitter"),r=[];for(const s of t){const e=await n.percentages(s);r.push({userId:s,basisPoints:Number(e),percent:Number(e)/100})}return r}async getZonedConfig(e){const t=this.getContract(e,"Zoned"),[n,r,s,a]=await Promise.all([t.nzones(),t.a(),t.b(),t.c()]);return{numberOfZones:Number(n),rewardFunction:{a:Number(r),b:Number(s),c:Number(a)}}}async getUserZone(e,t){const n=this.getContract(e,"Zoned"),r=await n.zone(t);return Number(r)}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"),r=[];for(let s=1;s<=t.numberOfZones;s++){const e=await n.getZoneMembers(s);r.push({zone:s,members:e,memberCount:e.length})}return{config:t,zones:r,rewardWeights:(await n.calculateRewards()).map((e,t)=>({zone:t+1,weight:Number(e)}))}}async getManagedAppreciation(e,t){const n=this.getContract(e,"Managed"),r=await n.appreciation(t),s=await n.totalappreciation();return{userAppreciation:Number(r),totalAppreciation:Number(s),sharePercent:Number(s)>0?Number(r)/Number(s)*100:0}}async getManagedAllAppreciation(e){const t=await this.getMembers(e,"Managed"),n=this.getContract(e,"Managed"),r=await n.totalappreciation(),s=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(r)>0?Number(e)/Number(r)*100:0})}return{members:a,totalAppreciation:Number(r),maxAppreciation:Number(s)}}async getAppreciativePeer(e,t){const n=this.getContract(e,"Appreciative"),[r,s,a]=await Promise.all([n.appreciation(t),n.remainingappreciation(t),n.totalappreciation()]);return{received:Number(r),remainingToGive:Number(s),totalPool:Number(a),sharePercent:Number(a)>0?Number(r)/Number(a)*100:0}}async getAppreciativeAll(e){const t=await this.getMembers(e,"Appreciative"),n=this.getContract(e,"Appreciative"),r=await n.totalappreciation(),s=[];for(const a of t){const[e,t]=await Promise.all([n.appreciation(a),n.remainingappreciation(a)]);s.push({userId:a,received:Number(e),remainingToGive:Number(t),sharePercent:Number(r)>0?Number(e)/Number(r)*100:0})}return{members:s,totalAppreciation:Number(r)}}async getBundleConfig(e){const t=this.getContract(e,"Bundle"),[n,r,s,a,i]=await Promise.all([t.steepness(),t.nzones(),t.interiorPercentage(),t.exteriorPercentage(),t.electionActive()]);return{steepness:Number(n),numberOfZones:Number(r),interiorPercentage:Number(s)/100,exteriorPercentage:Number(a)/100,electionActive:i}}async getBundleSplit(e){const t=this.getContract(e,"Bundle"),[n,r]=await Promise.all([t.interiorPercentage(),t.exteriorPercentage()]);return{interiorBasisPoints:Number(n),exteriorBasisPoints:Number(r),interiorPercent:Number(n)/100,exteriorPercent:Number(r)/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"),[r,s,a,i,o]=await Promise.all([n.zone(t),n.interiorShare(t),n.isInteriorMember(t),n.isExteriorMember(t),n.isBundleMember(t)]);return{zone:Number(r),interiorShareBasisPoints:Number(s),interiorSharePercent:Number(s)/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"),r=[];for(let s=1;s<=t.numberOfZones;s++){const e=await n.getZoneMembers(s);r.push({zone:s,members:e,memberCount:e.length})}return{config:t,zones:r,zoneWeights:await this.getBundleZoneWeights(e)}}async getBundleElection(e){const t=this.getContract(e,"Bundle"),[n,r]=await Promise.all([t.electionActive(),t.getCandidates()]);if(!n)return{active:!1,candidates:[]};const s=[];for(const a of r){const e=await t.votes(a);s.push({userId:a,votes:Number(e)})}return{active:!0,candidates:s.sort((e,t)=>t.votes-e.votes)}}async getFullSnapshot(e){const t=await this.detectFlavor(e),n=await this.getContractInfo(e,t),r=await this.getMembers(e,t),s={...n,members:r,memberDetails:[]};for(const a of r){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));s.memberDetails.push(n)}return"Splitter"===t?(s.split=await this.getSplitterSplit(e),s.children=await this.getSplitterChildren(e)):"Zoned"===t?s.zoneConfig=await this.getZonedBreakdown(e):"Managed"===t?s.appreciationSummary=await this.getManagedAllAppreciation(e):"Appreciative"===t?s.appreciationSummary=await this.getAppreciativeAll(e):"Bundle"===t&&(s.bundleConfig=await this.getBundleConfig(e),s.bundleSplit=await this.getBundleSplit(e),s.bundleZones=await this.getBundleZoneBreakdown(e),s.election=await this.getBundleElection(e)),s}},exports.ContractTransactionReceipt=ap,exports.ContractTransactionResponse=ip,exports.ContractUnknownEventPayload=op,exports.Council=bo,exports.Embeddings=fo,exports.ErrorDescription=qd,exports.ErrorFragment=Ed,exports.EventFragment=Id,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 r=["FundsReceived","FundsCascaded","FundsAllocated","FundsClaimed","FundsTransferred","DistributionCompleted","MemberAdded","WeightChanged","ZoneAssigned","AppreciationGiven"];for(const a of r)try{const r=n.filters[a]?.();r&&n.on(a,(...n)=>{this._handleEvent(a,n,e,t)})}catch(s){}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,r){const s=t[t.length-1],a={type:e,contractAddress:n,holonId:r,timestamp:Date.now(),blockNumber:s?.blockNumber,transactionHash:s?.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:r,minValue:s}=e;let a=[...this.sankeyLinks];if(t&&(a=a.filter(e=>e.token===t)),s){const e=BigInt(s);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}}),l=new Map;o.forEach((e,t)=>l.set(e.id,t));return{nodes:o,links:a.map(e=>({source:l.get(e.source),target:l.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:r=0,toBlock:s="latest"}=n;try{const n=e.filters[t]?.();if(!n)return[];return(await e.queryFilter(n,r,s)).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 r=["FundsReceived","FundsCascaded","FundsAllocated","FundsClaimed","FundsTransferred","MemberAdded"];for(const s of r){const r=await this.queryPastEvents(e,s,n);for(const e of r)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=rp,exports.EventPayload=Ul,exports.FallbackFragment=Cd,exports.FederationAdvisor=ko,exports.FeeData=class{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(e,t,n){sl(this,{gasPrice:Kd(e),maxFeePerGas:Kd(t),maxPriorityFeePerGas:Kd(n)})}toJSON(){const{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:Wd(e),maxFeePerGas:Wd(t),maxPriorityFeePerGas:Wd(n)}}},exports.FixedNumber=nc,exports.Fragment=Sd,exports.FunctionFragment=Rd,exports.H3AI=Io,exports.Hash=qe,exports.Hash$1=Oc,exports.HoloSphere=Bp,exports.HolonContracts=el,exports.Indexed=Ld,exports.Interface=zd,exports.JSONOps=mo,exports.LLMService=ho,exports.Log=Xd,exports.LogDescription=jd,exports.MODELS=vo,exports.NETWORKS=Oo,exports.NLQuery=To,exports.NamedFragment=kd,exports.ParamType=Ad,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=No,exports.Result=fc,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=yo,exports.SmartAggregation=So,exports.SpatialAnalysis=Ao,exports.StructFragment=$d,exports.TTS=_o,exports.TaskBreakdown=Eo,exports.TransactionDescription=Ud,exports.TransactionReceipt=Qd,exports.TransactionResponse=ep,exports.Typed=Tu,exports.UndecodedEventLog=sp,exports.Utf8ErrorFuncs=Ll,exports.VOICES=wo,exports.ValidationError=we,exports.ZeroAddress=ou,exports.abytes=ke,exports.accessListify=Uu,exports.aexists=Ne,exports.ahash=function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Se(e.outputLen),Se(e.blockLen)},exports.anumber=Se,exports.assert=cl,exports.assertArgument=ul,exports.assertArgumentCount=dl,exports.assertNormalize=hl,exports.assertPrivate=yl,exports.asyncLoop=async function(e,t,n){let r=Date.now();for(let s=0;s<e;s++){n(s);const e=Date.now()-r;e>=0&&e<t||(await Ec(),r+=e)}},exports.bytes=Tc,exports.bytesToHex=$e,exports.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==Cc.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,r){if(Array.isArray(r))for(let a in r){const i=e.slice();i.push(a);try{n(i,r[a])}catch(s){t.push({path:i,error:s})}}};return n([],e),t},exports.clean=Ee,exports.concat=Tl,exports.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];ke(n),t+=n.length}const n=new Uint8Array(t);for(let r=0,s=0;r<e.length;r++){const t=e[r];n.set(t,s),s+=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(!kc(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length}),t},exports.copyOverrides=bp,exports.copyRequest=Zd,exports.createAIServices=function(e,t=null,n={},r=null){const s=new ho(e,n.llm),a=r,i=new fo(a,t);return{llm:s,openai:a,embeddings:i,schemaExtractor:new yo(s),jsonOps:new mo(s),council:new bo(s),tts:new _o(a),nlQuery:new To(s,t),classifier:new xo(s,t),spatial:new Ao(s,t),aggregation:new So(s,t),federationAdvisor:new ko(s,t,i),relationships:new No(s,t,i),taskBreakdown:new Eo(s,t),h3ai:new Io(s,t)}},exports.createHologram=ft,exports.createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),exports.dataLength=function(e){return bl(e,!0)?(e.length-2)/2:fl(e).length},exports.dataSlice=xl,exports.defineProperties=sl,exports.exists=xc,exports.formatEther=ic,exports.formatUnits=sc,exports.fromTwos=Ol,exports.getAddress=yu,exports.getAddressUrl=Fo,exports.getBigInt=$l,exports.getBytes=fl,exports.getBytesCopy=gl,exports.getIcapAddress=function(e){let t=BigInt(yu(e)).toString(36).toUpperCase();for(;t.length<30;)t="0"+t;return"XE"+pu("XE00"+t)+t},exports.getNetwork=Co,exports.getNetworksByType=Ro,exports.getNumber=Dl,exports.getTxUrl=Po,exports.getUint=Ml,exports.h3Operations=Z,exports.handshake=Gt,exports.hash=function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");_c(e.outputLen),_c(e.blockLen)},exports.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Ce)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 r=new Uint8Array(n);for(let s=0,a=0;s<n;s++,a+=2){const t=je(e.charCodeAt(a)),n=je(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)}r[s]=16*t+n}return r},exports.hexlify=_l,exports.hologram=Ot,exports.id=qu,exports.isAddress=function(e){try{return yu(e),!0}catch(t){}return!1},exports.isAddressable=mu,exports.isBytes=Ae,exports.isBytesLike=wl,exports.isCallException=ol,exports.isError=il,exports.isHexString=bl,exports.isNetworkSupported=Mo,exports.keccak256=iu,exports.listNetworks=$o,exports.makeError=ll,exports.manager=Xt,exports.mask=Rl,exports.matchScope=st,exports.networks=Do,exports.nostrUtils=jt,exports.number=_c,exports.output=Ac,exports.parseEther=function(e){return ac(e,18)},exports.parseUnits=ac,exports.randomBytes=function(e=32){if(xe&&"function"==typeof xe.getRandomValues)return xe.getRandomValues(new Uint8Array(e));if(xe&&"function"==typeof xe.randomBytes)return Uint8Array.from(xe.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")},exports.randomBytes$1=function(e=32){if(Sc&&"function"==typeof Sc.getRandomValues)return Sc.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")},exports.resolveAddress=gu,exports.resolveArgs=wp,exports.resolveProperties=rl,exports.rotr=(e,t)=>e<<32-t|e>>>t,exports.secp256k1=lt,exports.sha256=Ye,exports.socialProtocols=Wt,exports.stripZerosLeft=function(e){let t=_l(e).substring(2);for(;t.startsWith("00");)t=t.substring(2);return"0x"+t},exports.toBeArray=jl,exports.toBeHex=Bl,exports.toBigInt=Fl,exports.toBytes=Ue,exports.toBytes$1=Ic,exports.toNumber=Hl,exports.toQuantity=function(e){let t=_l(wl(e)?e:jl(e)).substring(2);for(;t.startsWith("0");)t=t.substring(1);return""===t&&(t="0"),"0x"+t},exports.toTwos=Cl,exports.toUtf8Bytes=Gl,exports.toUtf8CodePoints=function(e,t){return Jl(Gl(e,t))},exports.toUtf8String=zl,exports.u32=Nc,exports.u64=Uc,exports.unifiedStorage=ye,exports.upcast=en,exports.validator=Te,exports.version=tl,exports.wrapConstructor=Rc,exports.zeroPadBytes=kl,exports.zeroPadValue=Sl;
5
+ //# sourceMappingURL=index-BB_vVJgv.cjs.map