@asaidimu/utils-workspace 3.0.0 → 3.1.0

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 (6) hide show
  1. package/README.md +297 -277
  2. package/index.d.mts +566 -127
  3. package/index.d.ts +566 -127
  4. package/index.js +288 -1
  5. package/index.mjs +287 -1
  6. package/package.json +1 -1
package/index.js CHANGED
@@ -1 +1,288 @@
1
- "use strict";var e,t,s=require("uuid"),r=Object.create,n=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,i=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,d=(e,t,s)=>(s=null!=e?r(i(e)):{},((e,t,s,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of a(t))c.call(e,i)||i===s||n(e,i,{get:()=>t[i],enumerable:!(r=o(t,i))||r.enumerable});return e})(e&&e.__esModule?s:n(s,"default",{value:e,enumerable:!0}),e)),l=(e={"node_modules/@asaidimu/events/index.js"(e,t){var s,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,i={};((e,t)=>{for(var s in t)r(e,s,{get:t[s],enumerable:!0})})(i,{createEventBus:()=>c}),t.exports=(s=i,((e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))a.call(e,c)||c===s||r(e,c,{get:()=>t[c],enumerable:!(i=n(t,c))||i.enumerable});return e})(r({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],r=0,n=0;const o=new Map,a=new Map;let i=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?i=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{r++,n+=t,o.set(e,(o.get(e)||0)+1)},d=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const r=performance.now();try{(a.get(t)||[]).forEach((e=>e(s)))}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-r)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(d,e.batchDelay)}})(),u=e=>{const s=t.get(e);s?a.set(e,Array.from(s)):a.delete(e)};return i&&(i.onmessage=e=>{const{name:t,payload:s}=e.data;(a.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const r=t.get(e);return r.add(s),u(e),()=>{r.delete(s),0===r.size?(t.delete(e),a.delete(e)):u(e)}},emit:({name:t,payload:r})=>{if(e.async)return s.push({name:t,payload:r}),s.length>=e.batchSize?d():l(),void(i&&i.postMessage({name:t,payload:r}));const n=performance.now();try{(a.get(t)||[]).forEach((e=>e(r))),i&&i.postMessage({name:t,payload:r})}catch(s){e.errorHandler({...s,eventName:t,payload:r})}c(t,performance.now()-n)},getMetrics:()=>({totalEvents:r,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:o,averageEmitDuration:r>0?n/r:0}),clear:()=>{t.clear(),a.clear(),s=[],r=0,n=0,o.clear(),i&&(i.close(),i=null)}}}}},function(){return t||(0,e[a(e)[0]])((t={exports:{}}).exports,t),t.exports}),u=[{name:"role",version:"1.0.0",description:"AI persona with a system prompt and associated preference defaults.",fields:{name:{name:"name",type:"string",required:!0},label:{name:"label",type:"string",required:!0},description:{name:"description",type:"string",required:!1},persona:{name:"persona",type:"string",required:!0},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"}},indexes:[{name:"by_name",fields:["name"],type:"unique"},{name:"by_label",fields:["label"],type:"normal"}],constraints:[],migrations:[]},{name:"preference",version:"1.0.0",description:"A user behavioural instruction, scoped to zero or more topics.",fields:{id:{name:"id",type:"string",required:!0},content:{name:"content",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},timestamp:{name:"timestamp",type:"string",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"context",version:"1.0.0",description:"Injected background knowledge, scoped to topics. Content is a discriminated union.",fields:{key:{name:"key",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},content:{name:"content",type:"record",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_key",fields:["key"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"session",version:"1.0.0",description:"Session metadata. The head field tracks the current tip of the turn DAG.",fields:{id:{name:"id",type:"string",required:!0},label:{name:"label",type:"string",required:!0},role:{name:"role",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"},metadata:{name:"metadata",type:"record",required:!1},flushedTurnCount:{name:"flushedTurnCount",type:"number",required:!0},head:{name:"head",type:"record",required:!1}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_role",fields:["role"],type:"normal"}],constraints:[],migrations:[]},{name:"turn",version:"1.0.0",description:["A single message in a session transcript, stored as a flat document.","The DAG is reconstructed in memory by TurnTree.buildNodeGraph() at session open time.","$id is a composite key: `${sessionId}:${id}:${version}`."].join(" "),fields:{id:{name:"id",type:"string",required:!0},sessionId:{name:"sessionId",type:"string",required:!0},version:{name:"version",type:"number",required:!0},owner:{name:"owner",type:"enum",required:!0,values:["user","assistant","tool"]},blocks:{name:"blocks",type:"array",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},role:{name:"role",type:"string",required:!1},parent:{name:"parent",type:"record",required:!1}},indexes:[{name:"by_session",fields:["sessionId"],type:"normal"},{name:"by_session_parent",fields:["sessionId","parent"],type:"composite"},{name:"by_session_id_ver",fields:["sessionId","id","version"],type:"composite",unique:!0}],constraints:[],migrations:[]},{name:"task",version:"1.0.0",description:"A first-class task entity with status, steps, and topics.",fields:{id:{name:"id",type:"string",required:!0},title:{name:"title",type:"string",required:!0},description:{name:"description",type:"string",required:!1},status:{name:"status",type:"enum",required:!0,values:["todo","active","done","blocked","defered"]},steps:{name:"steps",type:"array",required:!0,itemsType:"record"},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},metadata:{name:"metadata",type:"record",required:!1},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_status",fields:["status"],type:"normal"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_updated",fields:["updated"],type:"btree"}],constraints:[],migrations:[]}],p=class e extends Error{constructor(t,s){super(t,{cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},h=class extends p{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},f=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const s=new Promise((e=>t=e));this.waiters.push(t),null!=e?await Promise.race([s,new Promise(((s,r)=>setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),r(new h("Mutex lock timed out"))}),e)))]):await s}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},m=class{mutex=new f({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.promise=null}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new Error("Cannot execute doSync: lock is currently held.");if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this._done}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){this._done=!1,this.promise=null,this._value=null,this._error=void 0}resolved(){return this.promise}done(){return this._done}_awaitWithTimeout(e,t,s="Operation timed out"){return null==t?e:Promise.race([e,new Promise(((e,r)=>setTimeout((()=>r(new h(s))),t)))])}};var y={ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",TASK:"task"};d(l());var b=Symbol.for("delete"),w=e=>Array.isArray(e)?[...e]:{...e};function g(){return b}d(l()),d(l()),d(l()),d(l()),d(l()),d(l());var v=function(e){const t=e?.deleteMarker||b;function s(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e:s(e)));if("object"==typeof e){const r={};for(const[n,o]of Object.entries(e))if(o!==t)if("object"==typeof o&&null!==o){const e=s(o);void 0!==e&&(r[n]=e)}else r[n]=o;return r}return e===t?void 0:e}return function(e,r){if("object"!=typeof e||null===e)return"object"==typeof r&&null!==r?s(r):r===t?{}:r;if("object"!=typeof r||null===r)return e;const n=w(e),o=[{target:n,source:r}];for(;o.length>0;){const{target:e,source:s}=o.pop();for(const r of Object.keys(s)){const n=s[r];if(n!==t)if(Array.isArray(n))e[r]=n;else if("object"==typeof n&&null!==n){const t=r in e&&"object"==typeof e[r]&&null!==e[r]?e[r]:{};e[r]=w(t),o.push({target:e[r],source:n})}else e[r]=n;else delete e[r]}}return n}}({deleteMarker:b});function k(e){return{ok:!0,value:e}}function x(e){return{ok:!1,error:e}}function T(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))}var S=class{db;constructor(e){this.db=e}async turns(){return this.db.collection(y.TURN)}async sessions(){return this.db.collection(y.SESSION)}turnFilter(e,t,s){return{operator:"and",conditions:[{field:"sessionId",operator:"eq",value:e},{field:"id",operator:"eq",value:t},{field:"version",operator:"eq",value:s}]}}async loadRaw(e){const[t,s]=await Promise.all([this.loadAllTurns(e),this.getHead(e)]);return{turns:t,head:s}}async getHead(e){const t=await this.sessions(),s=await t.find({field:"id",operator:"eq",value:e});return s?.head??null}async setHead(e,t){const s=await this.sessions(),r=await s.find({field:"id",operator:"eq",value:e});if(!r)return;const n={...r.state(),head:t??void 0};await r.update(n)}async save(e,t,s){const r={...t,sessionId:e,version:t.version??0,parent:t.parent?t.parent:s?{id:s.id,version:s.version}:null},n=await this.turns();return await n.create(T(r)),r}async append(e,t){const s=await this.getHead(e),r=this.save(e,t,s);return await this.setHead(e,{id:t.id,version:t.version}),r}async appendBatch(e,t,s){const r=await this.getHead(e);if(0!==t.length){for(const s of t)await this.save(e,s,r);await this.setHead(e,s)}}async replaceVersion(e,t){const s=await this.turns(),r=await s.find(this.turnFilter(e,t.id,t.version)),n=T(t);r?await r.update({...n,sessionId:e}):await s.create({...n,sessionId:e})}async branch(e,t){const s=await this.turns();await s.create(T({...t,sessionId:e})),await this.setHead(e,{id:t.id,version:t.version})}async loadAllTurns(e){const t=await this.turns();return(await t.filter({field:"sessionId",operator:"eq",value:e})).map((e=>e.state()))}async loadTurnVersions(e,t){const s=await this.turns();return(await s.filter({operator:"and",conditions:[{field:"sessionId",operator:"eq",value:e},{field:"id",operator:"eq",value:t}]})).map((e=>e.state()))}buildNodes(e,t,s=[]){const r=function(e,t){if(!t)return new Set;const s=new Map;for(const t of e)s.set(`${t.id}:${t.version}`,t);const r=new Set;let n=t;for(;n;){const e=`${n.id}:${n.version}`;if(r.has(e))break;r.add(e);const t=s.get(e);if(!t)break;n=t.parent}return r}(e,t),n={},o={},a=[...e,...s];for(const e of a){n[e.id]||(n[e.id]={id:e.id,versions:{},activeVersion:e.version,role:e.owner,blocks:e.blocks,timestamp:e.timestamp,roleSnapshot:e.role,parent:e.parent,children:{}},o[e.id]=new Set);const t=n[e.id];t.versions[e.version]=e;const s=r.has(`${e.id}:${e.version}`),a=r.has(`${e.id}:${t.activeVersion}`);if(s&&(!a||e.version>=t.activeVersion)&&(t.activeVersion=e.version,t.blocks=e.blocks,t.timestamp=e.timestamp,t.roleSnapshot=e.role,t.parent=e.parent),e.parent){const t=`${e.parent.id}:${e.parent.version}`;if(o[e.parent.id]||(o[e.parent.id]=new Set),!o[e.parent.id].has(t+":"+e.id)){o[e.parent.id].add(t+":"+e.id),n[e.parent.id]||(n[e.parent.id]={id:e.parent.id,versions:{},activeVersion:e.parent.version,role:"user",blocks:[],timestamp:"",roleSnapshot:void 0,parent:null,children:{}});const s=n[e.parent.id],r=e.parent.version;s.children[r]||(s.children[r]=[]),s.children[r].push(e.id)}}}return n}async buildNodeGraph(e,t=[]){const{turns:s,head:r}=await this.loadRaw(e);return this.buildNodes(s,r,t)}async getActiveChain(e,t=[]){const{turns:s,head:r}=await this.loadRaw(e);if(!r&&0===t.length)return[];return[...r?O(s,r):[],...t]}async buildActiveChain(e){const{turns:t,head:s}=await this.loadRaw(e);if(!s)return[];const r=this.buildNodes(t,s),n=[];let o=s.id;for(;null!==o;){const e=r[o];if(!e)break;n.push(e),o=e.parent?.id??null}return n.reverse()}async getTurnSiblings(e,t){const{turns:s,head:r}=await this.loadRaw(t),n=this.buildNodes(s,r),o=n[e];if(!o)return[];if(!o.parent)return Object.values(n).filter((e=>null===e.parent));const a=n[o.parent.id];if(!a)return[o];const i=o.parent.version,c=a.children[i];return c?c.map((e=>n[e])).filter((e=>void 0!==e)):[o]}async branchInfo(e,t){const{turns:s,head:r}=await this.loadRaw(t),n=this.buildNodes(s,r)[e];if(!n)return{versions:[],currentIndex:-1,total:0,hasPrev:!1,hasNext:!1};const o=Object.keys(n.versions).map(Number).sort(((e,t)=>e-t)),a=o.indexOf(n.activeVersion);return{versions:o,currentIndex:a,total:o.length,hasPrev:a>0,hasNext:a<o.length-1}}async deleteSubtree(e,t,s,r){const n=function(e,t,s){const r=new Map;for(const t of e)if(t.parent){const e=`${t.parent.id}:${t.parent.version}`;let s=r.get(e);s||(s=new Set,r.set(e,s)),s.add(`${t.id}:${t.version}`)}const n=new Set,o=[`${t}:${s}`];for(;o.length>0;){const e=o.pop();n.add(e);const t=r.get(e);if(t)for(const e of t)n.has(e)||o.push(e)}return n}(await this.loadAllTurns(e),t,s),o=await this.turns();await Promise.all(Array.from(n).map((async t=>{const[s,r]=t.split(":"),n=await o.find(this.turnFilter(e,s,Number(r)));n&&await n.delete()}))),await this.setHead(e,r)}async copyTranscript(e,t){const{turns:s,head:r}=await this.loadRaw(e),n=r?O(s,r):[],o=await this.turns();for(const e of n)await o.create(T({...e,sessionId:t}));await this.setHead(t,r?{...r}:null)}};function O(e,t){const s=new Map;for(const t of e)s.set(`${t.id}:${t.version}`,t);const r=[];let n=t;for(;n;){const e=s.get(`${n.id}:${n.version}`);if(!e)break;r.push(e),n=e.parent}return r.reverse()}async function _(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}var N=class{storage;config;bus;recordCache=new Map;constructor(e,t,s={}){this.storage=e,this.bus=t,this.config={eagerEviction:s.eagerEviction??!1}}subscribe(e,t){return this.bus.subscribe(e,t)}async init(){const e=await this.storage.listRecords();for(const t of e)this.recordCache.set(t.sha256,t)}async register(e,t,s){try{const r=await _(e),n=(new Date).toISOString(),o=this.recordCache.get(r);if(o){const e={...o,refCount:o.refCount+1,lastUsedAt:n};await this.storage.saveRecord(e),this.recordCache.set(r,e)}else{const o={sha256:r,mediaType:t,sizeBytes:e.byteLength,filename:s,refCount:1,remoteIds:{},createdAt:n,lastUsedAt:n};"function"==typeof this.storage.registerBlob?await this.storage.registerBlob(o,e):(await this.storage.storeBytes(r,e),await this.storage.saveRecord(o)),this.recordCache.set(r,o)}const a=this.recordCache.get(r);return k({sha256:r,mediaType:t,sizeBytes:a.sizeBytes,filename:a.filename,previewUrl:a.previewUrl})}catch(e){return x({code:"BLOB_ERROR",reason:e instanceof Error?e.message:String(e)})}}async retain(e){const t=this.recordCache.get(e);if(!t)return x({code:"NOT_FOUND",resource:"blob",id:e});const s={...t,refCount:t.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(s),this.recordCache.set(e,s),k(void 0)}async release(e){const t=this.recordCache.get(e);if(!t)return x({code:"NOT_FOUND",resource:"blob",id:e});const s=Math.max(0,t.refCount-1),r={...t,refCount:s,lastUsedAt:(new Date).toISOString()};return 0===s&&this.config.eagerEviction?(await this.storage.deleteBytes(e),await this.storage.deleteRecord(e),this.recordCache.delete(e)):(await this.storage.saveRecord(r),this.recordCache.set(e,r)),k(void 0)}async recordRemoteId(e,t,s){const r=this.recordCache.get(e);if(!r)return x({code:"NOT_FOUND",resource:"blob",id:e});if(r.remoteIds[t]===s)return k(void 0);const n={...r,remoteIds:{...r.remoteIds,[t]:s}};return await this.storage.saveRecord(n),this.recordCache.set(e,n),k(void 0)}getRemoteId(e,t){return this.recordCache.get(e)?.remoteIds[t]??null}async resolveRef(e,t){try{if(t){const s=this.getRemoteId(e.sha256,t);if(s)return k({kind:"remote",sha256:e.sha256,mediaType:e.mediaType,fileId:s,providerId:t})}const s=await this.storage.loadBytes(e.sha256);return s?k({kind:"inline",sha256:e.sha256,mediaType:e.mediaType,data:s}):x({code:"BLOB_ERROR",reason:`Blob bytes not found locally for sha256=${e.sha256}. The blob may have been evicted. Re-register it before resolving.`})}catch(e){return x({code:"BLOB_ERROR",reason:e instanceof Error?e.message:String(e)})}}async resolveRefs(e,t){const s=function(e){const t=new Set,s=[];for(const r of e)t.has(r.sha256)||(t.add(r.sha256),s.push(r));return s}(e),r=await Promise.all(s.map((async e=>({ref:e,result:await this.resolveRef(e,t)})))),n=new Map,o=[];for(const{ref:e,result:t}of r)t.ok?n.set(e.sha256,t.value):o.push({ref:e,error:t.error});return{resolved:n,errors:o}}async gc(){const e=Array.from(this.recordCache.values()).filter((e=>0===e.refCount));return await Promise.all(e.map((async e=>{await this.storage.deleteBytes(e.sha256),await this.storage.deleteRecord(e.sha256),this.recordCache.delete(e.sha256),this.bus.emit({name:"blobs:changed",payload:{sha256:e.sha256,record:null}})}))),e.length}async purge(e){return this.recordCache.has(e)?(await this.storage.deleteBytes(e),await this.storage.deleteRecord(e),this.recordCache.delete(e),k(void 0)):x({code:"NOT_FOUND",resource:"blob",id:e})}getRecord(e){return this.recordCache.get(e)??null}getAllRecords(){const e={};for(const[t,s]of this.recordCache)e[t]=s;return e}};var I=10,C=50,R=20,E=10,B=class{map=new Map;max;constructor(e){this.max=e}get(e){if(!this.map.has(e))return;const t=this.map.get(e);return this.map.delete(e),this.map.set(e,t),t}set(e,t){if(this.map.has(e)&&this.map.delete(e),this.map.set(e,t),this.map.size>this.max){const e=this.map.keys().next().value;void 0!==e&&this.map.delete(e)}}has(e){return this.map.has(e)}delete(e){this.map.delete(e)}};function D({index:e},t){switch(t.type){case"role:add":{const s=t.payload;if(e.roles[s.name])return x({code:"DUPLICATE_KEY",resource:"role",key:s.name});const r={name:s.name,label:s.label,description:s.description,preferences:s.preferences.length};return k({index:{roles:{[s.name]:r}}})}case"role:update":{const{name:s,...r}=t.payload;if(!e.roles[s])return x({code:"NOT_FOUND",resource:"role",id:s});const n=e.roles[s],o={...n,...r,preferences:r.preferences?.length??n.preferences};return k({index:{roles:{[s]:o}}})}case"role:delete":{const{name:s}=t.payload;if(!e.roles[s])return x({code:"NOT_FOUND",resource:"role",id:s});return Object.values(e.sessions).some((e=>e.role===s))?x({code:"INVALID_COMMAND",reason:`Cannot delete role "${s}" — it is still referenced by one or more sessions`}):k({index:{roles:{[s]:g()}}})}case"preference:add":{const s=t.payload,r={id:s.id,topics:s.topics,timestamp:s.timestamp,snippet:s.content.substring(0,100)},n={};return s.topics.forEach((r=>{const o=e.topics[r],a=[...o?.preferences??[],s.id],i=o?.contextKeys??[],c=o?.tasks??[],d=i.length+a.length+c.length;n[r]={topic:r,contextKeys:i,preferences:a,tasks:c,metadata:{created:o?.metadata?.created??t.timestamp,updated:t.timestamp,entries:d}}})),k({index:{preferences:{[s.id]:r},topics:n}})}case"preference:update":{const{id:s,...r}=t.payload;if(!e.preferences[s])return x({code:"NOT_FOUND",resource:"preference",id:s});const n=e.preferences[s],o={...n,...r,snippet:r.content?r.content.substring(0,100):n.snippet},a={};return r.topics&&(n.topics.forEach((r=>{const n=e.topics[r];if(n){const e=n.preferences.filter((e=>e!==s)),o=n.contextKeys.length+e.length+n.tasks.length;a[r]={preferences:e,metadata:{...n.metadata,updated:t.timestamp,entries:o}}}})),r.topics.forEach((r=>{const n=e.topics[r]??{contextKeys:[],preferences:[],tasks:[],metadata:{created:t.timestamp}},o=[...n.preferences,s],i=n.contextKeys.length+o.length+n.tasks.length;a[r]={topic:r,contextKeys:n.contextKeys,preferences:o,tasks:n.tasks,metadata:{created:n.metadata?.created??t.timestamp,updated:t.timestamp,entries:i}}}))),k({index:{preferences:{[s]:o},topics:a}})}case"preference:delete":{const{id:s}=t.payload;if(!e.preferences[s])return x({code:"NOT_FOUND",resource:"preference",id:s});const r=e.preferences[s],n={};return r.topics.forEach((r=>{const o=e.topics[r];if(o){const e=o.preferences.filter((e=>e!==s)),a=o.contextKeys.length+e.length+o.tasks.length;n[r]={preferences:e,metadata:{...o.metadata,updated:t.timestamp,entries:a}}}})),k({index:{preferences:{[s]:g()},topics:n}})}case"context:add":{const s=t.payload;if(e.context[s.key])return x({code:"DUPLICATE_KEY",resource:"context",key:s.key});const r=s.content,n={key:s.key,topics:s.topics,timestamp:s.timestamp,source:s.key.split(":")[0],preview:"text"===r.kind?r.value.substring(0,200):"json"===r.kind?JSON.stringify(r.value).substring(0,200):void 0,metadata:s.metadata},o={};return s.topics.forEach((r=>{const n=e.topics[r],a=[...n?.contextKeys??[],s.key],i=n?.preferences??[],c=n?.tasks??[],d=a.length+i.length+c.length;o[r]={topic:r,contextKeys:a,preferences:i,tasks:c,metadata:{created:n?.metadata?.created??t.timestamp,updated:t.timestamp,entries:d}}})),k({index:{context:{[s.key]:n},topics:o}})}case"context:update":{const{key:s,...r}=t.payload;if(!e.context[s])return x({code:"NOT_FOUND",resource:"context",id:s});const n=e.context[s],o=r.content,a={...n,...r,preview:o?"text"===o.kind?o.value.substring(0,200):"json"===o.kind?JSON.stringify(o.value).substring(0,200):void 0:n.preview},i={};return r.topics&&(n.topics.forEach((r=>{const n=e.topics[r];if(n){const e=n.contextKeys.filter((e=>e!==s)),o=e.length+n.preferences.length+n.tasks.length;i[r]={contextKeys:e,metadata:{...n.metadata,updated:t.timestamp,entries:o}}}})),r.topics.forEach((r=>{const n=e.topics[r]??{contextKeys:[],preferences:[],tasks:[],metadata:{created:t.timestamp}},o=n.contextKeys.includes(s)?n.contextKeys:[...n.contextKeys,s],a=o.length+n.preferences.length+n.tasks.length;i[r]={topic:r,contextKeys:o,preferences:n.preferences,tasks:n.tasks,metadata:{created:n.metadata?.created??t.timestamp,updated:t.timestamp,entries:a}}}))),k({index:{context:{[s]:a},topics:i}})}case"context:delete":{const{key:s}=t.payload;if(!e.context[s])return x({code:"NOT_FOUND",resource:"context",id:s});const r=e.context[s],n={};return r.topics.forEach((r=>{const o=e.topics[r];if(o){const e=o.contextKeys.filter((e=>e!==s)),a=e.length+o.preferences.length+o.tasks.length;n[r]={contextKeys:e,metadata:{...o.metadata,updated:t.timestamp,entries:a}}}})),k({index:{context:{[s]:g()},topics:n}})}case"session:create":{const{id:s,label:r,role:n,topics:o,preferences:a=[]}=t.payload;if(e.sessions[s])return x({code:"DUPLICATE_KEY",resource:"session",key:s});if(!e.roles[n])return x({code:"NOT_FOUND",resource:"role",id:n});const i={id:s,label:r,role:n,topics:o,preferences:a,metadata:{created:t.timestamp,updated:t.timestamp},flushedTurnCount:0,head:null,task:null};return k({index:{sessions:{[s]:i}}})}case"session:role:switch":{const{sessionId:s,role:r}=t.payload;return e.sessions[s]?k({index:{sessions:{[s]:{role:r,metadata:{updated:t.timestamp}}}}}):x({code:"NOT_FOUND",resource:"session",id:s})}case"session:topics:add":{const{sessionId:s,topics:r}=t.payload;if(!e.sessions[s])return x({code:"NOT_FOUND",resource:"session",id:s});const n=e.sessions[s],o=[...new Set([...n.topics,...r])];return k({index:{sessions:{[s]:{topics:o,metadata:{updated:t.timestamp}}}}})}case"session:preferences:override":{const{sessionId:s,preferences:r}=t.payload;return e.sessions[s]?k({index:{sessions:{[s]:{preferences:r,metadata:{updated:t.timestamp}}}}}):x({code:"NOT_FOUND",resource:"session",id:s})}case"session:fork":{const{sourceSessionId:s,newSessionId:r,label:n,role:o,topics:a}=t.payload;if(!e.sessions[s])return x({code:"NOT_FOUND",resource:"session",id:s});if(e.sessions[r])return x({code:"DUPLICATE_KEY",resource:"session",key:r});const i=e.sessions[s],c={id:r,label:n,role:o??i.role,topics:a??[...i.topics],preferences:[...i.preferences],metadata:{created:t.timestamp,updated:t.timestamp},flushedTurnCount:i.flushedTurnCount,head:i.head,task:i.task};return k({index:{sessions:{[r]:c}}})}case"session:delete":{const{sessionId:s}=t.payload;return e.sessions[s]?k({index:{sessions:{[s]:g()}}}):x({code:"NOT_FOUND",resource:"session",id:s})}case"task:add":{const s=t.payload;if(e.tasks[s.id])return x({code:"DUPLICATE_KEY",resource:"task",key:s.id});const r={id:s.id,title:s.title,status:s.status,steps:{completed:s.steps.filter((e=>e.completed)).length,total:s.steps.length},topics:s.topics},n={};return s.topics.forEach((r=>{const o=e.topics[r],a=[...o?.tasks??[],s.id],i=o?.contextKeys??[],c=o?.preferences??[],d=i.length+c.length+a.length;n[r]={topic:r,contextKeys:i,preferences:c,tasks:a,metadata:{created:o?.metadata?.created??t.timestamp,updated:t.timestamp,entries:d}}})),k({index:{tasks:{[s.id]:r},topics:n}})}case"task:update":{const{id:s,...r}=t.payload;if(!e.tasks[s])return x({code:"NOT_FOUND",resource:"task",id:s});const n=e.tasks[s],o={...n,...r,steps:r.steps?{completed:r.steps.filter((e=>e.completed)).length,total:r.steps.length}:n.steps},a={};return r.topics&&(n.topics.forEach((r=>{const n=e.topics[r];if(n){const e=n.tasks.filter((e=>e!==s)),o=n.contextKeys.length+n.preferences.length+e.length;a[r]={tasks:e,metadata:{...n.metadata,updated:t.timestamp,entries:o}}}})),r.topics.forEach((r=>{const n=e.topics[r]??{contextKeys:[],preferences:[],tasks:[],metadata:{created:t.timestamp}},o=[...new Set([...n.tasks,s])],i=n.contextKeys.length+n.preferences.length+o.length;a[r]={topic:r,contextKeys:n.contextKeys,preferences:n.preferences,tasks:o,metadata:{created:n.metadata?.created??t.timestamp,updated:t.timestamp,entries:i}}}))),k({index:{tasks:{[s]:o},topics:a}})}case"task:delete":{const{id:s}=t.payload;if(!e.tasks[s])return x({code:"NOT_FOUND",resource:"task",id:s});const r=e.tasks[s],n={};return r.topics.forEach((r=>{const o=e.topics[r];if(o){const e=o.tasks.filter((e=>e!==s)),a=o.contextKeys.length+o.preferences.length+e.length;n[r]={tasks:e,metadata:{...o.metadata,updated:t.timestamp,entries:a}}}})),k({index:{tasks:{[s]:g()},topics:n}})}case"turn:save":case"turn:add":{const{sessionId:s,turn:r}=t.payload;return e.sessions[s]?k({index:{sessions:{[s]:{head:{id:r.id,version:r.version},metadata:{updated:t.timestamp},flushedTurnCount:(e.sessions[s]?.flushedTurnCount??0)+1}}}}):x({code:"NOT_FOUND",resource:"session",id:s})}case"turn:edit":{const{sessionId:s,turnId:r,newVersion:n}=t.payload;return e.sessions[s]?k({index:{sessions:{[s]:{head:{id:r,version:n},metadata:{updated:t.timestamp}}}}}):x({code:"NOT_FOUND",resource:"session",id:s})}case"turn:branch":{const{sessionId:s,turn:r}=t.payload;return e.sessions[s]?k({index:{sessions:{[s]:{head:{id:r.id,version:r.version},metadata:{updated:t.timestamp}}}}}):x({code:"NOT_FOUND",resource:"session",id:s})}case"turn:delete":{const{sessionId:s,newHead:r}=t.payload;return e.sessions[s]?k({index:{sessions:{[s]:{head:r,metadata:{updated:t.timestamp}}}}}):x({code:"NOT_FOUND",resource:"session",id:s})}case"blob:register":case"tool:call":default:return k({});case"blob:retain":{const{sha256:s}=t.payload;return e.blobs[s]?k({}):x({code:"NOT_FOUND",resource:"blob",id:s})}case"blob:release":{const{sha256:s}=t.payload;return e.blobs[s]?k({}):x({code:"NOT_FOUND",resource:"blob",id:s})}case"blob:purge":{const{sha256:s}=t.payload;return e.blobs[s]?k({}):x({code:"NOT_FOUND",resource:"blob",id:s})}case"blob:record_remote_id":{const{sha256:s}=t.payload;return e.blobs[s]?k({}):x({code:"NOT_FOUND",resource:"blob",id:s})}}}function q(e){return Math.ceil(e.length/4)}function j(e,t){return Math.ceil(e/1024*t)}function U(e){if("text"===e.kind)return e.value;if("json"===e.kind){const t=[],s=e=>{"string"==typeof e?t.push(e):e&&"object"==typeof e&&Object.values(e).forEach(s)};return s(e.value),t.join(" ")}return""}function A(e,t){return{id:crypto.randomUUID(),version:0,owner:e,blocks:t,timestamp:(new Date).toISOString(),parent:null}}var M=class{rank(e){const{entries:t,recentMessages:s,config:r}=e,n=r.recentMessageWindow??3,o=r.minScore??0,a=r.freshnessHalfLifeDays??30;if(0===s.length)return[...t].sort(((e,t)=>this.freshnessWeight(t.timestamp,a)-this.freshnessWeight(e.timestamp,a)));const i=this.tokenize(s.slice(-n).join(" "));return t.map((e=>{const t=U(e.content);return{entry:e,score:.7*this.jaccardSimilarity(i,this.tokenize(t))+.3*this.freshnessWeight(e.timestamp,a)}})).filter((e=>e.score>o)).sort(((e,t)=>t.score-e.score)).map((e=>e.entry))}tokenize(e){return new Set(e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter((e=>e.length>2)))}jaccardSimilarity(e,t){if(0===e.size&&0===t.size)return 0;let s=0;for(const r of e)t.has(r)&&s++;const r=e.size+t.size-s;return 0===r?0:s/r}freshnessWeight(e,t){const s=(Date.now()-new Date(e).getTime())/864e5;return Math.pow(.5,s/t)}},P=class{plan(e){const{systemInstructions:t,persona:s,preferences:r,context:n,task:o,transcript:a,budget:i}=e;if(!i)return{preferences:r,context:n,task:o,transcript:a,truncated:{preferences:0,interactions:0,context:0},breakdown:{system:0,persona:0,preferences:0,transcript:0,context:0,tasks:0},totalUsed:0,lastRoleBeforeTruncation:null};const c=i.estimator??q,d=i.blobTokensPerKB??.25;let l=i.total;const u={system:0,persona:0,preferences:0,transcript:0,context:0,tasks:0},p=c(t??""),h=c(s);l-=p+h,u.system+=p,u.persona+=h;const f=[];let m=0;for(const e of r){const t=c(e.content);l>=t?(l-=t,u.preferences+=t,f.push(e)):m++}const y=[];let b=0,w=null;for(let e=a.length-1;e>=0;e--){const t=a[e],s=this.estimateTurnTokens(t,c,d);l>=s?(l-=s,u.transcript+=s,y.unshift(t)):(b++,"user"!==t.owner||w||(w=t.role??null))}const g=[];let v=0;for(const e of n){let t=c(U(e.content));"blob"===e.content.kind&&(t+=j(e.content.sizeBytes,d)),l>=t?(l-=t,u.context+=t,g.push(e)):v++}return{preferences:f,context:g,task:o,transcript:y,truncated:{preferences:m,interactions:b,context:v},breakdown:u,totalUsed:i.total-Math.max(0,l),lastRoleBeforeTruncation:w}}estimateTurnTokens(e,t,s){return e.blocks.reduce(((e,r)=>{switch(r.type){case"text":return e+t(r.text);case"tool:use":return e+t(JSON.stringify(r.input));case"tool:result":return e+t("string"==typeof r.content?r.content:JSON.stringify(r.content));case"thinking":return e+t(r.thinking);case"image":case"document":{const t=r.ref;return t?e+j(t.sizeBytes,s):e}default:return e}}),0)}},F=class{assemble(e){const{session:t,plan:r,resolvedBlobs:n,summaryBlockText:o,warnings:a,conflicts:i,budgetTotal:c}=e,d=[],l=[];for(const e of r.context)if("text"===e.content.kind||"json"===e.content.kind)d.push(e);else if("blob"===e.content.kind){const t=n.get(e.content.sha256);t&&l.push(this.buildReferentialBlock(e.content,t))}const u=[];if(l.length>0&&u.push(A("user",l)),o||r.truncated.interactions>0){const e=[];o&&e.push({type:"summary",text:o,id:"summary"}),r.truncated.interactions>0&&e.push({id:"notice",type:"text",text:`[${r.truncated.interactions} earlier turn(s) omitted due to token budget]`}),u.push(A("user",e)),u.push(A("assistant",[{id:s.v7(),type:"text",text:"Understood."}]))}let p=r.lastRoleBeforeTruncation,h=null!==r.lastRoleBeforeTruncation;for(const e of r.transcript){const t=this.resolveTurnBlocks(e,n);"user"===e.owner&&e.role&&h&&e.role!==p&&t.unshift({type:"role:transition",previousRole:p,newRole:e.role}),"user"===e.owner&&(p=e.role??null,h=!0),u.push({...e,blocks:t})}return{system:{instructions:t.instructions,persona:t.role.persona,preferences:r.preferences,context:d,task:r.task},context:r.context,transcript:{turns:u},budget:{total:c,used:r.totalUsed,breakdown:r.breakdown},truncated:r.truncated,warnings:a,conflicts:i}}buildReferentialBlock(e,t){return e.mediaType.startsWith("image/")?{type:"image",blob:t}:{type:"document",blob:t,title:e.filename}}resolveTurnBlocks(e,t){return e.blocks.map((e=>{if("image"===e.type||"document"===e.type){const s=e.ref;if(s){const r=t.get(s.sha256);if(r)return{...e,blob:r}}}return e}))}},$=class{constructor(e,t){this._owner=e,this._turn=t?structuredClone(t):{id:s.v7(),version:0,owner:this._owner,blocks:[],timestamp:(new Date).toISOString(),role:void 0,parent:null}}_turn;addText(e){const t={id:s.v7(),type:"text",text:e};return this._turn.blocks.push(t),this}addImage(e,t){const r={id:s.v7(),type:"image",ref:e,altText:t};return this._turn.blocks.push(r),this}addDocument(e,t){const r={id:s.v7(),type:"document",ref:e,title:t};return this._turn.blocks.push(r),this}addToolUse(e,t){const r={id:s.v7(),type:"tool:use",name:e,input:t};return this._turn.blocks.push(r),this}addToolResult(e,t,r){const n={id:s.v7(),type:"tool:result",useId:e,content:t,isError:r};return this._turn.blocks.push(n),this}addSummary(e){const t={id:s.v7(),type:"summary",text:e};return this._turn.blocks.push(t),this}addRoleTransition(e,t){const r={id:s.v7(),type:"role:transition",previousRole:e,newRole:t};return this._turn.blocks.push(r),this}addThinking(e){const t={id:s.v7(),type:"thinking",thinking:e};return this._turn.blocks.push(t),this}addTaskProposal(e,t,r="create",n){const o=t.map((e=>({id:e.id??s.v7(),text:e.text,status:e.status??"todo"}))),a={id:s.v7(),type:"task:proposal",title:e,steps:o,action:r,taskId:n};return this._turn.blocks.push(a),this}addBlock(e){return this._turn.blocks.push(e),this}deleteBlock(e){return this._turn.blocks=this._turn.blocks.filter((t=>t.id!==e)),this}editTextBlock(e,t){const s=this._turn.blocks.findIndex((t=>t.id===e));if(-1===s)throw new Error(`Block with ID ${e} not found.`);const r=this._turn.blocks[s];if("text"!==r.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[s]={...r,text:t},this}withId(e){return this._turn.id=e,this}withVersion(e){return this._turn.version=e,this}withTimestamp(e){return this._turn.timestamp=e,this}withParent(e){return this._turn.parent=e,this}withRoleSnapshot(e){return this._turn.role=e,this}build(){return structuredClone(this._turn)}},K=class{constructor(e,t,s){this.sessionId=e,this.tree=t,this.manager=s}async turns(){return this.tree.buildActiveChain(this.sessionId)}async siblings(e){return this.tree.getTurnSiblings(e,this.sessionId)}async branchInfo(e){return this.tree.branchInfo(e,this.sessionId)}id(){return this.sessionId}startTurn(e){return new $(e)}async addTurn(e,t){if(!e.index.sessions[this.sessionId])return x({code:"NOT_FOUND",resource:"session",id:this.sessionId});const s={...t,version:t.version??0};return this.manager.dispatch(e,{type:"turn:add",payload:{sessionId:this.sessionId,turn:s},timestamp:s.timestamp})}async editTurn(e,t,s,r){if(!e.index.sessions[this.sessionId])return x({code:"NOT_FOUND",resource:"session",id:this.sessionId});const n=await this.tree.loadTurnVersions(this.sessionId,t);if(0===n.length)return x({code:"NOT_FOUND",resource:"turn",id:t});const o=Math.max(...n.map((e=>e.version))),a=n.find((e=>e.version===o)),i=o+1,c=(new Date).toISOString();return this.manager.dispatch(e,{type:"turn:edit",payload:{sessionId:this.sessionId,turnId:t,newBlocks:s,roleSnapshot:r??a.role,newVersion:i},timestamp:c})}async branch(e,t){return e.index.sessions[this.sessionId]?t.parent?this.manager.dispatch(e,{type:"turn:branch",payload:{sessionId:this.sessionId,turn:t},timestamp:t.timestamp}):x({code:"INVALID_COMMAND",reason:"branchFrom requires turn.parent to be set"}):x({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async deleteTurn(e,t,s,r){if(!e.index.sessions[this.sessionId])return x({code:"NOT_FOUND",resource:"session",id:this.sessionId});const n=await this.tree.loadTurnVersions(this.sessionId,t);if(0===n.length)return x({code:"NOT_FOUND",resource:"turn",id:t});return n.some((e=>e.version===s))?this.manager.dispatch(e,{type:"turn:delete",payload:{sessionId:this.sessionId,turnId:t,version:s,newHead:r},timestamp:(new Date).toISOString()}):x({code:"NOT_FOUND",resource:"turn version",id:`${t}:${s}`})}async switchVersionLeft(e,t){return this.switchVersion(e,t,-1)}async switchVersionRight(e,t){return this.switchVersion(e,t,1)}async switchVersion(e,t,s){if(!e.index.sessions[this.sessionId])return x({code:"NOT_FOUND",resource:"session",id:this.sessionId});const r=await this.tree.buildNodeGraph(this.sessionId),n=r[t];if(!n)return x({code:"NOT_FOUND",resource:"turn",id:t});const o=Object.keys(n.versions).map(Number).sort(((e,t)=>e-t)),a=o.indexOf(n.activeVersion);if(-1===a)return x({code:"INVALID_COMMAND",reason:"Active version not found in version list"});const i=a+s;if(i<0||i>=o.length)return x({code:"INVALID_COMMAND",reason:`No ${s<0?"previous":"next"} version available for turn ${t}`});const c=function(e,t,s){let r=t,n=s;for(;;){const t=e[r];if(!t)break;const s=t.children[n];if(!s||0===s.length)break;const o=s[0],a=e[o];if(!a)break;r=o,n=a.activeVersion}return{id:r,version:n}}(r,t,o[i]);await this.tree.setHead(this.sessionId,c);const d=(new Date).toISOString();return k({index:{sessions:{[this.sessionId]:{head:c,metadata:{updated:d}}}}})}async resolve(e){if(!e.index.sessions[this.sessionId])return x({code:"NOT_FOUND",resource:"session",id:this.sessionId});const t=(await this.turns()).map((e=>e.versions[e.activeVersion]));return this.manager.resolveSession(e,this.sessionId,t)}};var z="blob_bytes",V="blob_records";function L(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}function H(e){return new Promise(((t,s)=>{e.oncomplete=()=>t(),e.onerror=()=>s(e.error),e.onabort=()=>s(new Error("Transaction aborted"))}))}exports.BlobStore=N,exports.COLLECTIONS=y,exports.ContentStore=class e{db;tree;blobs;roleCache;preferenceCache;contextCache;taskCache;bus;subscribe(e,t){return this.bus.subscribe(e,t)}constructor(e,t,s,r={}){this.db=e,this.tree=new S(e),this.blobs=new N(t,s);const n={roles:r.cache?.roles??I,preferences:r.cache?.preferences??C,context:r.cache?.context??R,tasks:r.cache?.tasks??E};this.roleCache=new B(n.roles),this.preferenceCache=new B(n.preferences),this.contextCache=new B(n.context),this.taskCache=new B(n.tasks),this.bus=s}static async create(t,s,r,n){const o=new e(t,s,r,n);return await o.init(),o}async init(e){await this.db.open(e),await this.blobs.init()}getTurnTree(){return this.tree}async getRole(e){const t=this.roleCache.get(e);if(t)return k(t);const s=await this.db.collection(y.ROLE),r=await s.find({field:"name",operator:"eq",value:e});if(!r)return x({code:"NOT_FOUND",resource:"role",id:e});const n=r.state();return this.roleCache.set(e,n),k(n)}async saveRole(e){const t=await this.db.collection(y.ROLE),s=await t.find({field:"name",operator:"eq",value:e.name});s?await s.update(e):await t.create(e),this.roleCache.set(e.name,e)}async deleteRole(e){const t=await this.db.collection(y.ROLE),s=await t.find({field:"name",operator:"eq",value:e});s&&await s.delete(),this.roleCache.delete(e)}async getPreference(e){const t=this.preferenceCache.get(e);if(t)return k(t);const s=await this.db.collection(y.PREFERENCE),r=await s.find({field:"id",operator:"eq",value:e});if(!r)return x({code:"NOT_FOUND",resource:"preference",id:e});const n=r.state();return this.preferenceCache.set(e,n),k(n)}async savePreference(e){const t=await this.db.collection(y.PREFERENCE),s=await t.find({field:"id",operator:"eq",value:e.id});s?await s.update(e):await t.create(e),this.preferenceCache.set(e.id,e)}async deletePreference(e){const t=await this.db.collection(y.PREFERENCE),s=await t.find({field:"id",operator:"eq",value:e});s&&await s.delete(),this.preferenceCache.delete(e)}async getContext(e){const t=this.contextCache.get(e);if(t)return k(t);const s=await this.db.collection(y.CONTEXT),r=await s.find({field:"key",operator:"eq",value:e});if(!r)return x({code:"NOT_FOUND",resource:"context",id:e});const n=r.state();return this.contextCache.set(e,n),k(n)}async saveContext(e){const t=await this.db.collection(y.CONTEXT),s=await t.find({field:"key",operator:"eq",value:e.key});s?await s.update(e):await t.create(e),this.contextCache.set(e.key,e)}async deleteContext(e){const t=await this.db.collection(y.CONTEXT),s=await t.find({field:"key",operator:"eq",value:e});s&&await s.delete(),this.contextCache.delete(e)}async getContextByTopics(e,t){const s=new Set;for(const r of t){const t=e.topics[r];t&&t.contextKeys.forEach((e=>s.add(e)))}if(0===s.size)return[];const r=[],n=[];for(const e of s){const t=this.contextCache.get(e);t?n.push(t):r.push(e)}let o=[];if(r.length>0){const e=await this.db.collection(y.CONTEXT),t=await e.filter({operator:"or",conditions:r.map((e=>({field:"key",operator:"eq",value:e})))});for(const e of t){const t=e.state();this.contextCache.set(t.key,t),o.push(t)}}return[...n,...o].sort(((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime()))}async getTask(e){const t=this.taskCache.get(e);if(t)return k(t);const s=await this.db.collection(y.TASK),r=await s.find({field:"id",operator:"eq",value:e});if(!r)return x({code:"NOT_FOUND",resource:"task",id:e});const n=r.state();return this.taskCache.set(e,n),k(n)}async saveTask(e){const t=await this.db.collection(y.TASK),s=await t.find({field:"id",operator:"eq",value:e.id});s?await s.update(e):await t.create(e),this.taskCache.set(e.id,e)}async deleteTask(e){const t=await this.db.collection(y.TASK),s=await t.find({field:"id",operator:"eq",value:e});s&&await s.delete(),this.taskCache.delete(e)}async getTasksByTopics(e,t){const s=new Set;for(const r of t){const t=e.topics[r];t&&t.tasks&&t.tasks.forEach((e=>s.add(e)))}if(0===s.size)return[];const r=[],n=[];for(const e of s){const t=this.taskCache.get(e);t?n.push(t):r.push(e)}let o=[];if(r.length>0){const e=await this.db.collection(y.TASK),t=await e.filter({operator:"or",conditions:r.map((e=>({field:"id",operator:"eq",value:e})))});for(const e of t){const t=e.state();this.taskCache.set(t.id,t),o.push(t)}}return[...n,...o].sort(((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()))}async saveSession(e){const t=await this.db.collection(y.SESSION),s=await t.find({field:"id",operator:"eq",value:e.id}),r=T(e);s?await s.update(r):await t.create(r)}async updateSessionMeta(e,t){const s=await this.db.collection(y.SESSION),r=await s.find({field:"id",operator:"eq",value:e});if(!r)return;const n=r.state(),o=v(n,t);await r.update(T(o))}async deleteSession(e){const t=await this.db.collection(y.SESSION),s=await t.find({field:"id",operator:"eq",value:e});s&&await s.delete()}async registerBlob(e,t,s){return this.blobs.register(e,t,s)}async retainBlob(e){return this.blobs.retain(e)}async releaseBlob(e){return this.blobs.release(e)}async purgeBlob(e){return this.blobs.purge(e)}async recordBlobRemoteId(e,t,s){return this.blobs.recordRemoteId(e,t,s)}getBlobRecord(e){return this.blobs.getRecord(e)}getAllBlobRecords(){return this.blobs.getAllRecords()}getBlobResolver(){return this.blobs.resolveRefs.bind(this.blobs)}async appendTurn(e,t){return k(await this.tree.append(e,t))}async saveTurn(e,t){return k(await this.tree.save(e,t))}async editTurn(e,t,s,r,n){const o=(await this.tree.loadTurnVersions(e,t)).find((e=>e.version===r-1));if(!o)return x({code:"NOT_FOUND",resource:"turn",id:t});const a={id:t,version:r,owner:o.owner,blocks:s,timestamp:(new Date).toISOString(),role:n??o.role,parent:o.parent};await this.tree.replaceVersion(e,a);const i=await this.tree.getHead(e);return i?.id===t&&await this.tree.setHead(e,{id:a.id,version:a.version}),k(void 0)}async branchTurn(e,t){return await this.tree.branch(e,t),k(void 0)}async deleteTurnSubtree(e,t,s,r){return await this.tree.deleteSubtree(e,t,s,r),k(void 0)}async copyTranscript(e,t){await this.tree.copyTranscript(e,t)}async resolveSession(e,t,s){const r=e.index.sessions[t];if(!r)return x({code:"NOT_FOUND",resource:"session",id:t});const n=await this.getRole(r.role);if(!n.ok)return n;const o=n.value,a=function(e,t){return e.preferences.length>0?e.preferences:t.preferences}(r,o),i=function(e,t){return e.filter((e=>0===e.topics.length||e.topics.some((e=>t.includes(e)))))}((await Promise.all(a.map((e=>this.getPreference(e))))).filter((e=>e.ok)).map((e=>e.value)),r.topics),c=await this.getContextByTopics(e.index,r.topics),d=await this.getTasksByTopics(e.index,r.topics);let l=null;if(r.task&&!d.find((e=>e.id===r.task))){const e=await this.getTask(r.task);e.ok&&(l=e.value)}const u=s??await this.tree.getActiveChain(t),p={session:r,role:o,preferences:i,context:c,task:l,transcript:u,instructions:e.settings?.prompt};return k({...p,preferences:Object.freeze([...p.preferences]),context:Object.freeze([...p.context]),transcript:Object.freeze([...p.transcript])})}async gc(){return this.blobs.gc()}},exports.IndexedDBBlobStorage=class{dbName;db=null;constructor(e={}){this.dbName=e.dbName??"aiworkspace-blobs"}async open(){this.db||(this.db=await new Promise(((e,t)=>{const s=indexedDB.open(this.dbName,1);s.onupgradeneeded=e=>{const t=e.target.result;this.createSchema(t)},s.onsuccess=()=>e(s.result),s.onerror=()=>t(s.error),s.onblocked=()=>t(new Error(`[IndexedDBBlobStorage] Database "${this.dbName}" blocked.`))})),this.db.onversionchange=()=>{this.db?.close(),this.db=null})}createSchema(e){e.objectStoreNames.contains(z)||e.createObjectStore(z,{keyPath:"sha256"}),e.objectStoreNames.contains(V)||e.createObjectStore(V,{keyPath:"sha256"})}close(){this.db?.close(),this.db=null}async deleteDatabase(){this.close(),await new Promise(((e,t)=>{const s=indexedDB.deleteDatabase(this.dbName);s.onsuccess=()=>e(),s.onerror=()=>t(s.error)}))}getDB(){if(!this.db)throw new Error("[IndexedDBBlobStorage] Database not open. Call open() first.");return this.db}readTx(...e){return this.getDB().transaction(e,"readonly")}writeTx(...e){return this.getDB().transaction(e,"readwrite")}async storeBytes(e,t){const s=this.readTx(z);if(await L(s.objectStore(z).get(e)))return;const r=this.writeTx(z);r.objectStore(z).put({sha256:e,data:t}),await H(r)}async loadBytes(e){const t=this.readTx(z),s=await L(t.objectStore(z).get(e));return s?.data??null}async hasBytes(e){const t=this.readTx(z);return await L(t.objectStore(z).count(e))>0}async deleteBytes(e){const t=this.writeTx(z);t.objectStore(z).delete(e),await H(t)}async saveRecord(e){const t=this.writeTx(V);t.objectStore(V).put(e),await H(t)}async loadRecord(e){const t=this.readTx(V);return await L(t.objectStore(V).get(e))??null}async deleteRecord(e){const t=this.writeTx(V);t.objectStore(V).delete(e),await H(t)}async listRecords(){return L(this.readTx(V).objectStore(V).getAll())}async exportAllBytes(){const e=this.readTx(z);return(await L(e.objectStore(z).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((s,r)=>{const n=this.getDB().transaction([z,V],"readwrite"),o=n.objectStore(z),a=n.objectStore(V),i=o.count(e.sha256);i.onsuccess=()=>{0===i.result&&o.put({sha256:e.sha256,data:t}),a.put(e)},i.onerror=()=>r(i.error),n.oncomplete=()=>s(),n.onerror=()=>r(n.error),n.onabort=()=>r(new Error("registerBlob transaction aborted"))}))}},exports.MemoryBlobStorage=class{bytes=new Map;records=new Map;async storeBytes(e,t){this.bytes.has(e)||this.bytes.set(e,t)}async loadBytes(e){return this.bytes.get(e)??null}async hasBytes(e){return this.bytes.has(e)}async deleteBytes(e){this.bytes.delete(e)}async saveRecord(e){this.records.set(e.sha256,{...e})}async loadRecord(e){return this.records.get(e)??null}async deleteRecord(e){this.records.delete(e)}async listRecords(){return Array.from(this.records.values()).map((e=>({...e})))}async exportAllBytes(){return Array.from(this.bytes.entries()).map((([e,t])=>[e,new Uint8Array(t)]))}async registerBlob(e,t){this.bytes.has(e.sha256)||this.bytes.set(e.sha256,t),this.records.set(e.sha256,{...e})}},exports.PromptBuilder=class{retriever;planner;assembler;summarizer;blobResolver;constructor(e){this.blobResolver=e.blobResolver,this.retriever=e.retriever??new M,this.planner=e.planner??new P,this.assembler=e.assembler??new F,this.summarizer=e.summarizer}async build(e,t={}){const s=[],{resolved:r,conflicts:n}=this.resolvePreferenceConflicts(e.preferences);n.length>0&&s.push(`${n.length} preference conflict(s) resolved.`);const o=this.extractRecentUserQueries(e.transcript,t.relevanceConfig),a=this.retriever.rank({entries:e.context,recentMessages:o,config:t.relevanceConfig??{}});let i=e.transcript,c=null;if(this.summarizer&&i.length>0){const e=t.tokenBudget?Math.floor(.25*t.tokenBudget.total):2e3,s=await this.summarizer.summarize(i,e);c=s.summary,i=s.remaining}const d=this.planner.plan({systemInstructions:e.instructions,persona:e.role.persona,preferences:r,context:a,task:e.task,transcript:i,budget:t.tokenBudget}),l=this.collectUsedBlobRefs(d.context,d.transcript),u=this.deduplicateBlobRefs(l),{resolved:p,errors:h}=await this.blobResolver(u,t.providerId??null);for(const e of h)s.push(`Failed to resolve blob ${e.ref.sha256.slice(0,8)}: ${e.error.code}`);const f=u.filter((e=>!p.has(e.sha256)));return f.length>0&&s.push(`${f.length} blob(s) unresolved and omitted: `+f.map((e=>e.sha256.slice(0,8))).join(", ")),d.truncated.preferences>0&&s.push(`${d.truncated.preferences} preference(s) dropped.`),d.truncated.interactions>0&&s.push(`${d.truncated.interactions} turn(s) trimmed.`),d.truncated.context>0&&s.push(`${d.truncated.context} context entry/entries dropped.`),this.assembler.assemble({session:e,plan:d,resolvedBlobs:p,summaryBlockText:c,warnings:s,conflicts:n,budgetTotal:t.tokenBudget?.total??0})}collectUsedBlobRefs(e,t){const s=[];for(const t of e)"blob"===t.content.kind&&s.push(t.content);for(const e of t)for(const t of e.blocks)if("image"===t.type||"document"===t.type){const e=t.ref;e&&s.push(e)}return s}deduplicateBlobRefs(e){const t=new Set,s=[];for(const r of e)t.has(r.sha256)||(t.add(r.sha256),s.push(r));return s}extractRecentUserQueries(e,t){const s=t?.recentMessageWindow??3;return e.filter((e=>"user"===e.owner)).slice(-s).flatMap((e=>e.blocks.filter((e=>"text"===e.type)).map((e=>e.text))))}resolvePreferenceConflicts(e){const t=[],s=new Map;for(const r of e)if(0!==r.topics.length)for(const e of r.topics){const n=s.get(e);if(!n){s.set(e,r);continue}const o=new Date(n.timestamp).getTime(),a=new Date(r.timestamp).getTime();a>o?(t.push({topic:e,kept:r.id,dropped:n.id,reason:"superseded_by_newer"}),s.set(e,r)):o>a&&t.push({topic:e,kept:n.id,dropped:r.id,reason:"superseded_by_newer"})}const r=new Set(t.map((e=>e.dropped)));return{resolved:e.filter((e=>!r.has(e.id))),conflicts:Array.from(new Set(t))}}},exports.Session=K,exports.SessionManager=class{workspaceManager;contentStore;constructor(e,t){this.workspaceManager=e,this.contentStore=t}async open(e,t){if(!e.index.sessions[t])return x({code:"NOT_FOUND",resource:"session",id:t});try{return k({session:new K(t,this.contentStore.getTurnTree(),this.workspaceManager),patch:{}})}catch(e){return x({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}}get workspace(){return this.workspaceManager}async close(e){}},exports.TurnTree=S,exports.WorkspaceManager=class{contentStore;permissionGuard;toolRegistry;bus;subscribe(e,t){return this.bus.subscribe(e,t)}constructor(e){this.contentStore=e.contentStore,this.permissionGuard=e.permissionGuard,this.toolRegistry=e.toolRegistry,this.bus=e.eventBus,this.bus.subscribe("blobs:changed",(({sha256:e,record:t})=>{const s={index:{blobs:{[e]:t??void 0}}};this.bus.emit({name:"workspace:changed",payload:s})})),this.toolRegistry&&this.toolRegistry.onRegistryChanged((e=>{this.bus.emit({name:"workspace:changed",payload:{index:{tools:e.reduce(((e,t)=>(e[t.name]=t,e)),{})}}})}))}init(e){if(!this.toolRegistry)return{};const t={};for(const e of this.toolRegistry.list())t[e.name]=e;return{index:{tools:t}}}reduce(e,t){return D(e,t)}async dispatch(e,t){if(this.permissionGuard){const e="tool:call"===t.type?{type:"tool",payload:t.payload}:{type:"command",payload:t},s=await this.permissionGuard.authenticate(e);if(!s.ok)return s}const s=D(e,t);if(!s.ok)return s;let r={};try{r=await this.handleContentSideEffects(e,t)}catch(e){return x({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}return k(v(s.value,r))}async resolveSession(e,t,s){return this.contentStore.resolveSession(e,t,s)}async handleContentSideEffects(e,t){switch(t.type){case"blob:register":{const{data:e,mediaType:s,filename:r}=t.payload,n=await this.contentStore.registerBlob(e,s,r);if(!n.ok)throw Object.assign(new Error(n.error.code),{wsError:n.error});const o=n.value,a=this.contentStore.getBlobRecord(o.sha256);if(!a)throw new Error("Record missing after register");return{index:{blobs:{[o.sha256]:a}}}}case"blob:retain":{const{sha256:e}=t.payload,s=await this.contentStore.retainBlob(e);if(!s.ok)throw Object.assign(new Error(s.error.code),{wsError:s.error});const r=this.contentStore.getBlobRecord(e);return{index:{blobs:{[e]:r??void 0}}}}case"blob:release":{const{sha256:e}=t.payload,s=await this.contentStore.releaseBlob(e);if(!s.ok)throw Object.assign(new Error(s.error.code),{wsError:s.error});const r=this.contentStore.getBlobRecord(e);return{index:{blobs:{[e]:r??void 0}}}}case"blob:purge":{const{sha256:e}=t.payload,s=await this.contentStore.purgeBlob(e);if(!s.ok)throw Object.assign(new Error(s.error.code),{wsError:s.error});return{index:{blobs:{[e]:void 0}}}}case"blob:record_remote_id":{const{sha256:e,providerId:s,fileId:r}=t.payload,n=await this.contentStore.recordBlobRemoteId(e,s,r);if(!n.ok)throw Object.assign(new Error(n.error.code),{wsError:n.error});const o=this.contentStore.getBlobRecord(e);return{index:{blobs:{[e]:o??void 0}}}}case"role:add":return await this.contentStore.saveRole(t.payload),{};case"role:update":{const{name:e,...s}=t.payload,r=await this.contentStore.getRole(e);if(!r.ok)throw new Error(`role:update — "${e}" not found`);return await this.contentStore.saveRole({...r.value,...s,name:e}),{}}case"role:delete":return await this.contentStore.deleteRole(t.payload.name),{};case"preference:add":return await this.contentStore.savePreference(t.payload),{};case"preference:update":{const{id:e,...s}=t.payload,r=await this.contentStore.getPreference(e);if(!r.ok)throw new Error(`preference:update — "${e}" not found`);return await this.contentStore.savePreference({...r.value,...s,id:e}),{}}case"preference:delete":return await this.contentStore.deletePreference(t.payload.id),{};case"context:add":case"context:update":return await this.contentStore.saveContext(t.payload),{};case"context:delete":return await this.contentStore.deleteContext(t.payload.key),{};case"task:add":return await this.contentStore.saveTask(t.payload),{};case"task:update":{const{id:e,...s}=t.payload,r=await this.contentStore.getTask(e);if(!r.ok)throw new Error(`task:update — "${e}" not found`);return await this.contentStore.saveTask({...r.value,...s,id:e}),{}}case"task:delete":return await this.contentStore.deleteTask(t.payload.id),{};case"session:create":{const{id:e,label:s,role:r,topics:n,preferences:o=[]}=t.payload;return await this.contentStore.saveSession({id:e,label:s,role:r,topics:n,preferences:o,metadata:{created:t.timestamp,updated:t.timestamp},flushedTurnCount:0,head:null,task:null}),{}}case"session:fork":{const{sourceSessionId:s,newSessionId:r,label:n,role:o,topics:a}=t.payload;if(!e.index.sessions[s])throw new Error(`session:fork — source session "${s}" not found`);await this.contentStore.copyTranscript(s,r);const i=e.index.sessions[s],c={id:r,label:n,role:o??i.role,topics:a??[...i.topics],preferences:[...i.preferences],metadata:{created:t.timestamp,updated:t.timestamp},flushedTurnCount:i.flushedTurnCount,head:i.head?{...i.head}:null,task:i.task};return await this.contentStore.saveSession(c),{}}case"session:delete":return await this.contentStore.deleteSession(t.payload.sessionId),{};case"session:role:switch":case"session:topics:add":case"session:preferences:override":{const e=t.payload.sessionId,s=await this.contentStore.db.collection("session"),r=await s.find({field:"id",operator:"eq",value:e});if(!r)return{};if("session:role:switch"===t.type)await this.contentStore.updateSessionMeta(e,{role:t.payload.role});else if("session:topics:add"===t.type){const s=r.state();await this.contentStore.updateSessionMeta(e,{topics:[...new Set([...s.topics,...t.payload.topics])]})}else await this.contentStore.updateSessionMeta(e,{preferences:t.payload.preferences});return{}}case"turn:add":return await this.contentStore.appendTurn(t.payload.sessionId,t.payload.turn),{};case"turn:save":return await this.contentStore.saveTurn(t.payload.sessionId,t.payload.turn),{};case"turn:edit":{const{sessionId:e,turnId:s,newBlocks:r,newVersion:n,roleSnapshot:o}=t.payload;return await this.contentStore.editTurn(e,s,r,n,o),{}}case"turn:branch":return await this.contentStore.branchTurn(t.payload.sessionId,t.payload.turn),{};case"turn:delete":{const{sessionId:e,turnId:s,version:r,newHead:n}=t.payload;return await this.contentStore.deleteTurnSubtree(e,s,r,n),{}}case"tool:call":{if(!this.toolRegistry)throw new Error("tool:call — no toolRegistry configured");const e=await this.toolRegistry.execute(t.payload);if(!e.ok)throw Object.assign(new Error(e.error.code),{wsError:e.error});return{}}default:return{}}}},exports.computeSHA256=_,exports.createProjectWorkspace=function({project:e,language:t}){const r={...e,id:s.v7()};return{id:s.v7(),settings:{language:t},project:r,index:{roles:{},topics:{},preferences:{},context:{},sessions:{},blobs:{},tasks:{},tools:{}}}},exports.createSimpleWorkspace=function({name:e,owner:t,language:r}){return{id:s.v7(),settings:{language:r},project:{id:s.v7(),name:e,owner:t},index:{roles:{},topics:{},preferences:{},context:{},sessions:{},blobs:{},tasks:{},tools:{}}}},exports.createWorkspaceDatabase=function(e){const t=new m({retry:!0,throws:!0}),s=new m({retry:!0,throws:!0});return{open:async(s=[])=>(await t.do((async()=>{const t=[...u,...s];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await s.do((()=>{e.close()}))).value}},exports.del=g,exports.err=x,exports.extractBlobRecord=function(e){const t=e?.index?.blobs;if(!t)return null;const s=t[Object.keys(t)[0]];return s||null},exports.extractBlobRef=function(e){return{sha256:e.sha256,mediaType:e.mediaType,sizeBytes:e.sizeBytes,filename:e.filename,previewUrl:e.previewUrl}},exports.merge=v,exports.ok=k,exports.omitNullUndefined=T,exports.workspaceReducer=D;
1
+ "use strict";var e=require("fs"),t=require("path"),r=require("stream"),n=require("util"),s=require("buffer"),o=require("http"),i=require("net"),a=require("url"),c=require("https"),l=require("zlib"),u=require("uuid");function d(e){return e&&e.__esModule?e:{default:e}}var h,f=d(r),p=d(o),m=d(c),y=d(l),_=Object.create,g=Object.defineProperty,b=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,w=Object.getPrototypeOf,T=Object.prototype.hasOwnProperty,v=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)((function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})),S=(e,t)=>function(){return e&&(t=(0,e[E(e)[0]])(e=0)),t},A=(e,t)=>function(){return t||(0,e[E(e)[0]])((t={exports:{}}).exports,t),t.exports},O=(e,t)=>{for(var r in t)g(e,r,{get:t[r],enumerable:!0})},I=(e,t,r)=>(r=null!=e?_(w(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of E(t))T.call(e,s)||s===r||g(e,s,{get:()=>t[s],enumerable:!(n=b(t,s))||n.enumerable});return e})(!t&&e&&e.__esModule?r:g(r,"default",{value:e,enumerable:!0}),e)),C=A({"node_modules/@asaidimu/events/index.js"(e,t){var r,n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(a,{createEventBus:()=>c}),t.exports=(r=a,((e,t,r,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))i.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(a=s(t,c))||a.enumerable});return e})(n({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],n=0,s=0;const o=new Map,i=new Map;let a=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?a=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{n++,s+=t,o.set(e,(o.get(e)||0)+1)},l=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const n=performance.now();try{(i.get(t)||[]).forEach((e=>e(r)))}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-n)}))},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?i.set(e,Array.from(r)):i.delete(e)};return a&&(a.onmessage=e=>{const{name:t,payload:r}=e.data;(i.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const n=t.get(e);return n.add(r),d(e),()=>{n.delete(r),0===n.size?(t.delete(e),i.delete(e)):d(e)}},emit:({name:t,payload:n})=>{if(e.async)return r.push({name:t,payload:n}),r.length>=e.batchSize?l():u(),void(a&&a.postMessage({name:t,payload:n}));const s=performance.now();try{(i.get(t)||[]).forEach((e=>e(n))),a&&a.postMessage({name:t,payload:n})}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-s)},getMetrics:()=>({totalEvents:n,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:o,averageEmitDuration:n>0?s/n:0}),clear:()=>{t.clear(),i.clear(),r=[],n=0,s=0,o.clear(),a&&(a.close(),a=null)}}}}}),R=A({"node_modules/retry/lib/retry_operation.js"(e,t){function r(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},r.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},r.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var s=this._errors[n],o=s.message,i=(e[o]||0)+1;e[o]=i,i>=r&&(t=s,r=i)}return t}}}),k=A({"node_modules/retry/lib/retry.js"(e){var t=R();e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<t.retries;s++)n.push(this.createTimeout(s,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(s,t)),n.sort((function(e,t){return e-t})),n},e.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var s in n=[],t)"function"==typeof t[s]&&n.push(s);for(var o=0;o<n.length;o++){var i=n[o],a=t[i];t[i]=function(n){var s=e.operation(r),o=Array.prototype.slice.call(arguments,1),i=o.pop();o.push((function(e){s.retry(e)||(e&&(arguments[0]=s.mainError()),i.apply(this,arguments))})),s.attempt((function(){n.apply(t,o)}))}.bind(t,a),t[i].options=r}}}}),N=A({"node_modules/retry/index.js"(e,t){t.exports=k()}}),P=A({"node_modules/p-retry/index.js"(e,t){var r=N(),n=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],s=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},o=(e,t)=>new Promise(((o,i)=>{t={onFailedAttempt:()=>{},retries:10,...t};const a=r.operation(t);a.attempt((async r=>{try{o(await e(r))}catch(e){if(!(e instanceof Error))return void i(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof s)a.stop(),i(e.originalError);else if(e instanceof TypeError&&(c=e.message,!n.includes(c)))a.stop(),i(e);else{((e,t,r)=>{const n=r.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(e,r,t);try{await t.onFailedAttempt(e)}catch(e){return void i(e)}a.retry(e)||i(a.mainError())}}var c}))}));t.exports=o,t.exports.default=o,t.exports.AbortError=s}}),x=A({"node_modules/extend/index.js"(e,t){var r=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,o=Object.getOwnPropertyDescriptor,i=function(e){return"function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===n.call(e)},a=function(e){if(!e||"[object Object]"!==n.call(e))return!1;var t,s=r.call(e,"constructor"),o=e.constructor&&e.constructor.prototype&&r.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!s&&!o)return!1;for(t in e);return void 0===t||r.call(e,t)},c=function(e,t){s&&"__proto__"===t.name?s(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if("__proto__"===t){if(!r.call(e,t))return;if(o)return o(e,t).value}return e[t]};t.exports=function e(){var t,r,n,s,o,u,d=arguments[0],h=1,f=arguments.length,p=!1;for("boolean"==typeof d&&(p=d,d=arguments[1]||{},h=2),(null==d||"object"!=typeof d&&"function"!=typeof d)&&(d={});h<f;++h)if(null!=(t=arguments[h]))for(r in t)n=l(d,r),d!==(s=l(t,r))&&(p&&s&&(a(s)||(o=i(s)))?(o?(o=!1,u=n&&i(n)?n:[]):u=n&&a(n)?n:{},c(d,{name:r,newValue:e(p,u,s)})):void 0!==s&&c(d,{name:r,newValue:s}));return d}}}),D=A({"node_modules/gaxios/package.json"(e,t){t.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}}),U=A({"node_modules/gaxios/build/cjs/src/util.cjs"(e,t){var r=D();t.exports={pkg:r}}}),L=A({"node_modules/gaxios/build/cjs/src/common.js"(e){var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=function e(t){const r="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(e){e&&e.forEach(((t,n)=>{(/^authentication$/i.test(n)||/^authorization$/i.test(n)||/secret/i.test(n))&&e.set(n,r)}))}function s(e,t){if("object"==typeof e&&null!==e&&"string"==typeof e[t]){const n=e[t];(/grant_type=/i.test(n)||/assertion=/i.test(n)||/secret/i.test(n))&&(e[t]=r)}}function o(e){e&&"object"==typeof e&&(e instanceof FormData||e instanceof URLSearchParams||"forEach"in e&&"set"in e?e.forEach(((t,n)=>{(["grant_type","assertion"].includes(n)||/secret/.test(n))&&e.set(n,r)})):("grant_type"in e&&(e.grant_type=r),"assertion"in e&&(e.assertion=r),"client_secret"in e&&(e.client_secret=r)))}t.config&&(n(t.config.headers),s(t.config,"data"),o(t.config.data),s(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",r),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",r));t.response&&(e({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(s(t.response,"data"),o(t.response.data)));return t};var r=t(x()),n=t(U()).default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${n.name}-gaxios-error`);var s=class t extends Error{config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=n.version;static[Symbol.hasInstance](r){return!(!r||"object"!=typeof r||!(e.GAXIOS_ERROR_SYMBOL in r)||r[e.GAXIOS_ERROR_SYMBOL]!==n.version)||Function.prototype[Symbol.hasInstance].call(t,r)}constructor(e,t,n,s){if(super(e,{cause:s}),this.config=t,this.response=n,this.error=s instanceof Error?s:void 0,this.config=(0,r.default)(!0,{},t),this.response&&(this.response.config=(0,r.default)(!0,{},this.response.config)),this.response){try{this.response.data=function(e,t){switch(e){case"stream":default:return t;case"json":return JSON.parse(JSON.stringify(t));case"arraybuffer":return JSON.parse(Buffer.from(t).toString("utf8"));case"blob":return JSON.parse(t.text())}}(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}s instanceof DOMException?this.code=s.name:s&&"object"==typeof s&&"code"in s&&("string"==typeof s.code||"number"==typeof s.code)&&(this.code=s.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let r=t;if("string"==typeof e.data&&(r=e.data),e.data&&"object"==typeof e.data&&"error"in e.data&&e.data.error&&!e.ok){if("string"==typeof e.data.error)return{message:e.data.error,code:e.status,status:e.statusText};if("object"==typeof e.data.error){r="message"in e.data.error&&"string"==typeof e.data.error.message?e.data.error.message:r;const t="status"in e.data.error&&"string"==typeof e.data.error.status?e.data.error.status:e.statusText,n="code"in e.data.error&&"number"==typeof e.data.error.code?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){const s=[];for(const t of e.data.error.errors)"object"==typeof t&&"message"in t&&"string"==typeof t.message&&s.push(t.message);return Object.assign({message:s.join("\n")||r,code:n,status:t},e.data.error)}return Object.assign({message:r,code:n,status:t},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};e.GaxiosError=s}}),j=A({"node_modules/gaxios/build/cjs/src/retry.js"(e){function t(e){const t=r(e);if(e.config.signal?.aborted&&"TimeoutError"!==e.code||"AbortError"===e.code)return!1;if(!t||0===t.retry)return!1;if(!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries)return!1;if(!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||"GET"))return!1;if(e.response&&e.response.status){let r=!1;for(const[n,s]of t.statusCodesToRetry){const t=e.response.status;if(t>=n&&t<=s){r=!0;break}}if(!r)return!1}return t.currentRetryAttempt=t.currentRetryAttempt||0,!(t.currentRetryAttempt>=t.retry)}function r(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig}Object.defineProperty(e,"__esModule",{value:!0}),e.getRetryConfig=async function(e){let n=r(e);if(!e||!e.config||!n&&!e.config.retry)return{shouldRetry:!1};n=n||{},n.currentRetryAttempt=n.currentRetryAttempt||0,n.retry=void 0===n.retry||null===n.retry?3:n.retry,n.httpMethodsToRetry=n.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],n.noResponseRetries=void 0===n.noResponseRetries||null===n.noResponseRetries?2:n.noResponseRetries,n.retryDelayMultiplier=n.retryDelayMultiplier?n.retryDelayMultiplier:2,n.timeOfFirstRequest=n.timeOfFirstRequest?n.timeOfFirstRequest:Date.now(),n.totalTimeout=n.totalTimeout?n.totalTimeout:Number.MAX_SAFE_INTEGER,n.maxRetryDelay=n.maxRetryDelay?n.maxRetryDelay:Number.MAX_SAFE_INTEGER;n.statusCodesToRetry=n.statusCodesToRetry||[[100,199],[408,408],[429,429],[500,599]],e.config.retryConfig=n;const s=n.shouldRetry||t;if(!await s(e))return{shouldRetry:!1,config:e.config};const o=function(e){const t=e.currentRetryAttempt?0:e.retryDelay??100,r=t+(Math.pow(e.retryDelayMultiplier,e.currentRetryAttempt)-1)/2*1e3,n=e.totalTimeout-(Date.now()-e.timeOfFirstRequest);return Math.min(r,n,e.maxRetryDelay)}(n);e.config.retryConfig.currentRetryAttempt+=1;const i=n.retryBackoff?n.retryBackoff(e,o):new Promise((e=>{setTimeout(e,o)}));n.onRetryAttempt&&await n.onRetryAttempt(e);return await i,{shouldRetry:!0,config:e.config}}}}),M=A({"node_modules/gaxios/build/cjs/src/interceptor.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosInterceptorManager=void 0;var t=class extends Set{};e.GaxiosInterceptorManager=t}}),F=A({"node_modules/ms/index.js"(e,t){var r=1e3,n=6e4,s=60*n,o=24*s,i=7*o,a=365.25*o;function c(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}t.exports=function(e,t){t=t||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var c=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*a;case"weeks":case"week":case"w":return c*i;case"days":case"day":case"d":return c*o;case"hours":case"hour":case"hrs":case"hr":case"h":return c*s;case"minutes":case"minute":case"mins":case"min":case"m":return c*n;case"seconds":case"second":case"secs":case"sec":case"s":return c*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=o)return c(e,t,o,"day");if(t>=s)return c(e,t,s,"hour");if(t>=n)return c(e,t,n,"minute");if(t>=r)return c(e,t,r,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=o)return Math.round(e/o)+"d";if(t>=s)return Math.round(e/s)+"h";if(t>=n)return Math.round(e/n)+"m";if(t>=r)return Math.round(e/r)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}}),B=A({"node_modules/debug/src/common.js"(e,t){t.exports=function(e){function t(e){let n,s,o,i=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),o=s-(n||s);r.diff=o,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";i++;const o=t.formatters[s];if("function"==typeof o){const t=e[i];n=o.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,s=-1,o=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,o=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,o++,r=o}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=F(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}}}),G=A({"node_modules/debug/src/browser.js"(e,t){e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;e.splice(1,0,r,"color: inherit");let n=0,s=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),e.splice(s,0,r)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(e){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(e){}!t&&"undefined"!=typeof process&&"env"in process&&(t=process.env.DEBUG);return t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(e){}}(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=B()(e);var{formatters:r}=t.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}}),H=A({"node_modules/has-flag/index.js"(e,t){t.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),s=t.indexOf("--");return-1!==n&&(-1===s||n<s)}}}),q=A({"node_modules/supports-color/index.js"(e,t){var r,n=v("os"),s=v("tty"),o=H(),{env:i}=process;function a(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(0===r)return 0;if(o("color=16m")||o("color=full")||o("color=truecolor"))return 3;if(o("color=256"))return 2;if(e&&!t&&void 0===r)return 0;const s=r||0;if("dumb"===i.TERM)return s;if("win32"===process.platform){const e=n.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in i)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in i))||"codeship"===i.CI_NAME?1:s;if("TEAMCITY_VERSION"in i)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0;if("truecolor"===i.COLORTERM)return 3;if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(i.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)||"COLORTERM"in i?1:s}o("no-color")||o("no-colors")||o("color=false")||o("color=never")?r=0:(o("color")||o("colors")||o("color=true")||o("color=always"))&&(r=1),"FORCE_COLOR"in i&&(r="true"===i.FORCE_COLOR?1:"false"===i.FORCE_COLOR?0:0===i.FORCE_COLOR.length?1:Math.min(parseInt(i.FORCE_COLOR,10),3)),t.exports={supportsColor:function(e){return a(c(e,e&&e.isTTY))},stdout:a(c(!0,s.isatty(1))),stderr:a(c(!0,s.isatty(2)))}}}),$=A({"node_modules/debug/src/node.js"(e,t){var r=v("tty"),n=v("util");e.init=function(t){t.inspectOpts={};const r=Object.keys(e.inspectOpts);for(let n=0;n<r.length;n++)t.inspectOpts[r[n]]=e.inspectOpts[r[n]]},e.log=function(...t){return process.stderr.write(n.formatWithOptions(e.inspectOpts,...t)+"\n")},e.formatArgs=function(r){const{namespace:n,useColors:s}=this;if(s){const e=this.color,s="[3"+(e<8?e:"8;5;"+e),o=` ${s};1m${n} `;r[0]=o+r[0].split("\n").join("\n"+o),r.push(s+"m+"+t.exports.humanize(this.diff)+"")}else r[0]=function(){if(e.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+n+" "+r[0]},e.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},e.load=function(){return process.env.DEBUG},e.useColors=function(){return"colors"in e.inspectOpts?Boolean(e.inspectOpts.colors):r.isatty(process.stderr.fd)},e.destroy=n.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const t=q();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}e.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[r]=n,e}),{}),t.exports=B()(e);var{formatters:s}=t.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts)}}}),W=A({"node_modules/debug/src/index.js"(e,t){"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?t.exports=G():t.exports=$()}}),V=A({"node_modules/agent-base/dist/helpers.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&t(n,e,s);return r(n,e),n};Object.defineProperty(e,"__esModule",{value:!0}),e.req=e.json=e.toBuffer=void 0;var s=n(v("http")),o=n(v("https"));async function i(e){let t=0;const r=[];for await(const n of e)t+=n.length,r.push(n);return Buffer.concat(r,t)}e.toBuffer=i,e.json=async function(e){const t=(await i(e)).toString("utf8");try{return JSON.parse(t)}catch(e){const r=e;throw r.message+=` (input: ${t})`,r}},e.req=function(e,t={}){const r=(("string"==typeof e?e:e.href).startsWith("https:")?o:s).request(e,t),n=new Promise(((e,t)=>{r.once("response",e).once("error",t).end()}));return r.then=n.then.bind(n),r}}}),Y=A({"node_modules/agent-base/dist/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&t(n,e,s);return r(n,e),n},s=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Agent=void 0;var o=n(v("net")),i=n(v("http")),a=v("https");s(V(),e);var c=Symbol("AgentBaseInternalState"),l=class extends i.Agent{constructor(e){super(e),this[c]={}}isSecureEndpoint(e){if(e){if("boolean"==typeof e.secureEndpoint)return e.secureEndpoint;if("string"==typeof e.protocol)return"https:"===e.protocol}const{stack:t}=new Error;return"string"==typeof t&&t.split("\n").some((e=>-1!==e.indexOf("(https.js:")||-1!==e.indexOf("node:https:")))}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);const t=new o.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||null===t)return;const r=this.sockets[e],n=r.indexOf(t);-1!==n&&(r.splice(n,1),this.totalSocketCount--,0===r.length&&delete this.sockets[e])}getName(e){return("boolean"==typeof e.secureEndpoint?e.secureEndpoint:this.isSecureEndpoint(e))?a.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,r){const n={...t,secureEndpoint:this.isSecureEndpoint(t)},s=this.getName(n),o=this.incrementSockets(s);Promise.resolve().then((()=>this.connect(e,n))).then((a=>{if(this.decrementSockets(s,o),a instanceof i.Agent)try{return a.addRequest(e,n)}catch(e){return r(e)}this[c].currentSocket=a,super.createSocket(e,t,r)}),(e=>{this.decrementSockets(s,o),r(e)}))}createConnection(){const e=this[c].currentSocket;if(this[c].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[c].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(e){this[c]&&(this[c].defaultPort=e)}get protocol(){return this[c].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[c]&&(this[c].protocol=e)}};e.Agent=l}}),z=A({"node_modules/https-proxy-agent/dist/parse-proxy-response.js"(e){var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.parseProxyResponse=void 0;var r=(0,t(W()).default)("https-proxy-agent:parse-proxy-response");e.parseProxyResponse=function(e){return new Promise(((t,n)=>{let s=0;const o=[];function i(){const c=e.read();c?function(c){o.push(c),s+=c.length;const l=Buffer.concat(o,s),u=l.indexOf("\r\n\r\n");if(-1===u)return r("have not received end of HTTP headers yet..."),void i();const d=l.slice(0,u).toString("ascii").split("\r\n"),h=d.shift();if(!h)return e.destroy(),n(new Error("No header received from proxy CONNECT response"));const f=h.split(" "),p=+f[1],m=f.slice(2).join(" "),y={};for(const t of d){if(!t)continue;const r=t.indexOf(":");if(-1===r)return e.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${t}"`));const s=t.slice(0,r).toLowerCase(),o=t.slice(r+1).trimStart(),i=y[s];"string"==typeof i?y[s]=[i,o]:Array.isArray(i)?i.push(o):y[s]=o}r("got proxy server response: %o %o",h,y),a(),t({connect:{statusCode:p,statusText:m,headers:y},buffered:l})}(c):e.once("readable",i)}function a(){e.removeListener("end",c),e.removeListener("error",l),e.removeListener("readable",i)}function c(){a(),r("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(e){a(),r("onerror %o",e),n(e)}e.on("error",l),e.on("end",c),i()}))}}}),K=A({"node_modules/https-proxy-agent/dist/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&t(n,e,s);return r(n,e),n},s=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.HttpsProxyAgent=void 0;var o=n(v("net")),i=n(v("tls")),a=s(v("assert")),c=s(W()),l=Y(),u=v("url"),d=z(),h=(0,c.default)("https-proxy-agent"),f=e=>void 0===e.servername&&e.host&&!o.isIP(e.host)?{...e,servername:e.host}:e,p=class extends l.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy="string"==typeof e?new u.URL(e):e,this.proxyHeaders=t?.headers??{},h("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),n=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?y(t,"headers"):null,host:r,port:n}}async connect(e,t){const{proxy:r}=this;if(!t.host)throw new TypeError('No "host" provided');let n;"https:"===r.protocol?(h("Creating `tls.Socket`: %o",this.connectOpts),n=i.connect(f(this.connectOpts))):(h("Creating `net.Socket`: %o",this.connectOpts),n=o.connect(this.connectOpts));const s="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},c=o.isIPv6(t.host)?`[${t.host}]`:t.host;let l=`CONNECT ${c}:${t.port} HTTP/1.1\r\n`;if(r.username||r.password){const e=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(e).toString("base64")}`}s.Host=`${c}:${t.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const e of Object.keys(s))l+=`${e}: ${s[e]}\r\n`;const u=(0,d.parseProxyResponse)(n);n.write(`${l}\r\n`);const{connect:p,buffered:_}=await u;if(e.emit("proxyConnect",p),this.emit("proxyConnect",p,e),200===p.statusCode)return e.once("socket",m),t.secureEndpoint?(h("Upgrading socket connection to TLS"),i.connect({...y(f(t),"host","path","port"),socket:n})):n;n.destroy();const g=new o.Socket({writable:!1});return g.readable=!0,e.once("socket",(e=>{h("Replaying proxy buffer for failed request"),(0,a.default)(e.listenerCount("data")>0),e.push(_),e.push(null)})),g}};function m(e){e.resume()}function y(e,...t){const r={};let n;for(n in e)t.includes(n)||(r[n]=e[n]);return r}p.protocols=["http","https"],e.HttpsProxyAgent=p}});function J(e){if(!/^data:/i.test(e))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');const t=(e=e.replace(/\r?\n/g,"")).indexOf(",");if(-1===t||t<=4)throw new TypeError("malformed data: URI");const r=e.substring(5,t).split(";");let n="",s=!1;const o=r[0]||"text/plain";let i=o;for(let e=1;e<r.length;e++)"base64"===r[e]?s=!0:r[e]&&(i+=`;${r[e]}`,0===r[e].indexOf("charset=")&&(n=r[e].substring(8)));r[0]||n.length||(i+=";charset=US-ASCII",n="US-ASCII");const a=s?"base64":"ascii",c=unescape(e.substring(t+1)),l=Buffer.from(c,a);return l.type=o,l.typeFull=i,l.charset=n,l}var X,Q,Z,ee=S({"node_modules/data-uri-to-buffer/dist/index.js"(){h=J}}),te=A({"node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(e,t){var r,n;r=e,n=function(e){function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const n=t;function s(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const o=Promise,i=Promise.prototype.then,a=Promise.reject.bind(o);function c(e){return new o(e)}function l(e){return c((t=>t(e)))}function u(e){return a(e)}function d(e,t,r){return i.call(e,t,r)}function h(e,t,r){d(d(e,t,r),void 0,n)}function f(e,t){h(e,t)}function p(e,t){h(e,void 0,t)}function m(e,t,r){return d(e,t,r)}function y(e){d(e,void 0,n)}let _=e=>{if("function"==typeof queueMicrotask)_=queueMicrotask;else{const e=l(void 0);_=t=>d(e,t)}return _(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function b(e,t,r){try{return l(g(e,t,r))}catch(e){return u(e)}}class E{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let n=r+1;const s=e._elements,o=s[r];return 16384===n&&(t=e._next,n=0),--this._size,this._cursor=n,e!==t&&(this._front=t),s[r]=void 0,o}forEach(e){let t=this._cursor,r=this._front,n=r._elements;for(;!(t===n.length&&void 0===r._next||t===n.length&&(r=r._next,n=r._elements,t=0,0===n.length));)e(n[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const w=Symbol("[[AbortSteps]]"),T=Symbol("[[ErrorSteps]]"),v=Symbol("[[CancelSteps]]"),S=Symbol("[[PullSteps]]"),A=Symbol("[[ReleaseSteps]]");function O(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?k(e):"closed"===t._state?function(e){k(e),x(e)}(e):N(e,t._storedError)}function I(e,t){return jr(e._ownerReadableStream,t)}function C(e){const t=e._ownerReadableStream;"readable"===t._state?P(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){N(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[A](),t._reader=void 0,e._ownerReadableStream=void 0}function R(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function k(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function N(e,t){k(e),P(e,t)}function P(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function x(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const D=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},U=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function L(e,t){if(void 0!==e&&"object"!=typeof(r=e)&&"function"!=typeof r)throw new TypeError(`${t} is not an object.`);var r}function j(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function M(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function F(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function B(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function G(e){return Number(e)}function H(e){return 0===e?0:e}function q(e,t){const r=Number.MAX_SAFE_INTEGER;let n=Number(e);if(n=H(n),!D(n))throw new TypeError(`${t} is not a finite number`);if(n=function(e){return H(U(e))}(n),n<0||n>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return D(n)&&0!==n?n:0}function $(e,t){if(!Ur(e))throw new TypeError(`${t} is not a ReadableStream.`)}function W(e){return new J(e)}function V(e,t){e._reader._readRequests.push(t)}function Y(e,t,r){const n=e._reader._readRequests.shift();r?n._closeSteps():n._chunkSteps(t)}function z(e){return e._reader._readRequests.length}function K(e){const t=e._reader;return void 0!==t&&!!X(t)}class J{constructor(e){if(F(e,1,"ReadableStreamDefaultReader"),$(e,"First parameter"),Lr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");O(this,e),this._readRequests=new E}get closed(){return X(this)?this._closedPromise:u(ee("closed"))}cancel(e=void 0){return X(this)?void 0===this._ownerReadableStream?u(R("cancel")):I(this,e):u(ee("cancel"))}read(){if(!X(this))return u(ee("read"));if(void 0===this._ownerReadableStream)return u(R("read from"));let e,t;const r=c(((r,n)=>{e=r,t=n}));return Q(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!X(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){C(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function X(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof J}function Q(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[S](t)}function Z(e,t){const r=e._readRequests;e._readRequests=new E,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(J.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(J.prototype.cancel,"cancel"),s(J.prototype.read,"read"),s(J.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(J.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});const te=Object.getPrototypeOf(Object.getPrototypeOf((async function*(){})).prototype);class re{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?m(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?m(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;let t,r;const n=c(((e,n)=>{t=e,r=n}));return Q(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,_((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),r(t)}}),n}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(!this._preventCancel){const r=I(t,e);return C(t),m(r,(()=>({value:e,done:!0})))}return C(t),l({value:e,done:!0})}}const ne={next(){return se(this)?this._asyncIteratorImpl.next():u(oe("next"))},return(e){return se(this)?this._asyncIteratorImpl.return(e):u(oe("return"))}};function se(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof re}catch(e){return!1}}function oe(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}Object.setPrototypeOf(ne,te);const ie=Number.isNaN||function(e){return e!=e};var ae,ce,le;function ue(e){return e.slice()}function de(e,t,r,n,s){new Uint8Array(e).set(new Uint8Array(r,n,s),t)}let he=e=>(he="function"==typeof e.transfer?e=>e.transfer():"function"==typeof structuredClone?e=>structuredClone(e,{transfer:[e]}):e=>e,he(e)),fe=e=>(fe="boolean"==typeof e.detached?e=>e.detached:e=>0===e.byteLength,fe(e));function pe(e,t,r){if(e.slice)return e.slice(t,r);const n=r-t,s=new ArrayBuffer(n);return de(s,0,e,t,n),s}function me(e,t){const r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(`${String(t)} is not a function`);return r}}const ye=null!==(le=null!==(ae=Symbol.asyncIterator)&&void 0!==ae?ae:null===(ce=Symbol.for)||void 0===ce?void 0:ce.call(Symbol,"Symbol.asyncIterator"))&&void 0!==le?le:"@@asyncIterator";function _e(e,t="sync",n){if(void 0===n)if("async"===t){if(void 0===(n=me(e,ye)))return function(e){const t={[Symbol.iterator]:()=>e.iterator},r=async function*(){return yield*t}();return{iterator:r,nextMethod:r.next,done:!1}}(_e(e,"sync",me(e,Symbol.iterator)))}else n=me(e,Symbol.iterator);if(void 0===n)throw new TypeError("The object is not iterable");const s=g(n,e,[]);if(!r(s))throw new TypeError("The iterator method must return an object");return{iterator:s,nextMethod:s.next,done:!1}}function ge(e){const t=pe(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function be(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function Ee(e,t,r){if("number"!=typeof(n=r)||ie(n)||n<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var n;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function we(e){e._queue=new E,e._queueTotalSize=0}function Te(e){return e===DataView}class ve{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Oe(this))throw Qe("view");return this._view}respond(e){if(!Oe(this))throw Qe("respond");if(F(e,1,"respond"),e=q(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(fe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ke(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Oe(this))throw Qe("respondWithNewView");if(F(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(fe(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Je(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ve.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(ve.prototype.respond,"respond"),s(ve.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ve.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Se{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Ae(this))throw Ze("byobRequest");return Ye(this)}get desiredSize(){if(!Ae(this))throw Ze("desiredSize");return ze(this)}close(){if(!Ae(this))throw Ze("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);qe(this)}enqueue(e){if(!Ae(this))throw Ze("enqueue");if(F(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);$e(this,e)}error(e=void 0){if(!Ae(this))throw Ze("error");We(this,e)}[v](e){Ce(this),we(this);const t=this._cancelAlgorithm(e);return He(this),t}[S](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Ve(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const n={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(n)}V(t,e),Ie(this)}[A](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new E,this._pendingPullIntos.push(e)}}}function Ae(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof Se}function Oe(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ve}function Ie(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(K(t)&&z(t)>0)return!0;if(st(t)&&nt(t)>0)return!0;const r=ze(e);return r>0}(e);t&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,h(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Ie(e)),null)),(t=>(We(e,t),null)))))}function Ce(e){je(e),e._pendingPullIntos=new E}function Re(e,t){let r=!1;"closed"===e._state&&(r=!0);const n=ke(t);"default"===t.readerType?Y(e,n,r):function(e,t,r){const n=e._reader,s=n._readIntoRequests.shift();r?s._closeSteps(t):s._chunkSteps(t)}(e,n,r)}function ke(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Ne(e,t,r,n){e._queue.push({buffer:t,byteOffset:r,byteLength:n}),e._queueTotalSize+=n}function Pe(e,t,r,n){let s;try{s=pe(t,r,r+n)}catch(t){throw We(e,t),t}Ne(e,s,0,n)}function xe(e,t){t.bytesFilled>0&&Pe(e,t.buffer,t.byteOffset,t.bytesFilled),Ge(e)}function De(e,t){const r=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),n=t.bytesFilled+r;let s=r,o=!1;const i=n-n%t.elementSize;i>=t.minimumFill&&(s=i-t.bytesFilled,o=!0);const a=e._queue;for(;s>0;){const r=a.peek(),n=Math.min(s,r.byteLength),o=t.byteOffset+t.bytesFilled;de(t.buffer,o,r.buffer,r.byteOffset,n),r.byteLength===n?a.shift():(r.byteOffset+=n,r.byteLength-=n),e._queueTotalSize-=n,Ue(0,n,t),s-=n}return o}function Ue(e,t,r){r.bytesFilled+=t}function Le(e){0===e._queueTotalSize&&e._closeRequested?(He(e),Mr(e._controlledReadableByteStream)):Ie(e)}function je(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Me(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();De(e,t)&&(Ge(e),Re(e._controlledReadableByteStream,t))}}function Fe(e,t,r,n){const s=e._controlledReadableByteStream,o=t.constructor,i=function(e){return Te(e)?1:e.BYTES_PER_ELEMENT}(o),{byteOffset:a,byteLength:c}=t,l=r*i;let u;try{u=he(t.buffer)}catch(e){return void n._errorSteps(e)}const d={buffer:u,bufferByteLength:u.byteLength,byteOffset:a,byteLength:c,bytesFilled:0,minimumFill:l,elementSize:i,viewConstructor:o,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(d),void rt(s,n);if("closed"!==s._state){if(e._queueTotalSize>0){if(De(e,d)){const t=ke(d);return Le(e),void n._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return We(e,t),void n._errorSteps(t)}}e._pendingPullIntos.push(d),rt(s,n),Ie(e)}else{const e=new o(d.buffer,d.byteOffset,0);n._closeSteps(e)}}function Be(e,t){const r=e._pendingPullIntos.peek();je(e),"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ge(e);const r=e._controlledReadableByteStream;if(st(r))for(;nt(r)>0;)Re(r,Ge(e))}(e,r):function(e,t,r){if(Ue(0,t,r),"none"===r.readerType)return xe(e,r),void Me(e);if(r.bytesFilled<r.minimumFill)return;Ge(e);const n=r.bytesFilled%r.elementSize;if(n>0){const t=r.byteOffset+r.bytesFilled;Pe(e,r.buffer,t-n,n)}r.bytesFilled-=n,Re(e._controlledReadableByteStream,r),Me(e)}(e,t,r),Ie(e)}function Ge(e){return e._pendingPullIntos.shift()}function He(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function qe(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!==0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw We(e,t),t}}He(e),Mr(t)}}function $e(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const{buffer:n,byteOffset:s,byteLength:o}=t;if(fe(n))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");const i=he(n);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(fe(t.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");je(e),t.buffer=he(t.buffer),"none"===t.readerType&&xe(e,t)}K(r)?(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Ve(e,t._readRequests.shift())}}(e),0===z(r)?Ne(e,i,s,o):(e._pendingPullIntos.length>0&&Ge(e),Y(r,new Uint8Array(i,s,o),!1))):st(r)?(Ne(e,i,s,o),Me(e)):Ne(e,i,s,o),Ie(e)}function We(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(Ce(e),we(e),He(e),Fr(r,t))}function Ve(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,Le(e);const n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(n)}function Ye(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),n=Object.create(ve.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(n,e,r),e._byobRequest=n}return e._byobRequest}function ze(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ke(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=he(r.buffer),Be(e,t)}function Je(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const n=t.byteLength;r.buffer=he(t.buffer),Be(e,n)}function Xe(e,t,r,n,s,o,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,we(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=o,t._pullAlgorithm=n,t._cancelAlgorithm=s,t._autoAllocateChunkSize=i,t._pendingPullIntos=new E,e._readableStreamController=t,h(l(r()),(()=>(t._started=!0,Ie(t),null)),(e=>(We(t,e),null)))}function Qe(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ze(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function et(e,t){if("byob"!=(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function tt(e){return new ot(e)}function rt(e,t){e._reader._readIntoRequests.push(t)}function nt(e){return e._reader._readIntoRequests.length}function st(e){const t=e._reader;return void 0!==t&&!!it(t)}Object.defineProperties(Se.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Se.prototype.close,"close"),s(Se.prototype.enqueue,"enqueue"),s(Se.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Se.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ot{constructor(e){if(F(e,1,"ReadableStreamBYOBReader"),$(e,"First parameter"),Lr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Ae(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");O(this,e),this._readIntoRequests=new E}get closed(){return it(this)?this._closedPromise:u(lt("closed"))}cancel(e=void 0){return it(this)?void 0===this._ownerReadableStream?u(R("cancel")):I(this,e):u(lt("cancel"))}read(e,t={}){if(!it(this))return u(lt("read"));if(!ArrayBuffer.isView(e))return u(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return u(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return u(new TypeError("view's buffer must have non-zero byteLength"));if(fe(e.buffer))return u(new TypeError("view's buffer has been detached"));let r;try{r=function(e,t){var r;return L(e,t),{min:q(null!==(r=null==e?void 0:e.min)&&void 0!==r?r:1,`${t} has member 'min' that`)}}(t,"options")}catch(e){return u(e)}const n=r.min;if(0===n)return u(new TypeError("options.min must be greater than 0"));if(function(e){return Te(e.constructor)}(e)){if(n>e.byteLength)return u(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(n>e.length)return u(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return u(R("read from"));let s,o;const i=c(((e,t)=>{s=e,o=t}));return at(this,e,n,{_chunkSteps:e=>s({value:e,done:!1}),_closeSteps:e=>s({value:e,done:!0}),_errorSteps:e=>o(e)}),i}releaseLock(){if(!it(this))throw lt("releaseLock");void 0!==this._ownerReadableStream&&function(e){C(e);const t=new TypeError("Reader was released");ct(e,t)}(this)}}function it(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ot}function at(e,t,r,n){const s=e._ownerReadableStream;s._disturbed=!0,"errored"===s._state?n._errorSteps(s._storedError):Fe(s._readableStreamController,t,r,n)}function ct(e,t){const r=e._readIntoRequests;e._readIntoRequests=new E,r.forEach((e=>{e._errorSteps(t)}))}function lt(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function ut(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ie(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function dt(e){const{size:t}=e;return t||(()=>1)}function ht(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:G(r),size:void 0===n?void 0:ft(n,`${t} has member 'size' that`)}}function ft(e,t){return j(e,t),t=>G(e(t))}function pt(e,t,r){return j(e,r),r=>b(e,t,[r])}function mt(e,t,r){return j(e,r),()=>b(e,t,[])}function yt(e,t,r){return j(e,r),r=>g(e,t,[r])}function _t(e,t,r){return j(e,r),(r,n)=>b(e,t,[r,n])}function gt(e,t){if(!vt(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ot.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(ot.prototype.cancel,"cancel"),s(ot.prototype.read,"read"),s(ot.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ot.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const bt="function"==typeof AbortController;class Et{constructor(e={},t={}){void 0===e?e=null:M(e,"First parameter");const r=ht(t,"Second parameter"),n=function(e,t){L(e,t);const r=null==e?void 0:e.abort,n=null==e?void 0:e.close,s=null==e?void 0:e.start,o=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:pt(r,e,`${t} has member 'abort' that`),close:void 0===n?void 0:mt(n,e,`${t} has member 'close' that`),start:void 0===s?void 0:yt(s,e,`${t} has member 'start' that`),write:void 0===i?void 0:_t(i,e,`${t} has member 'write' that`),type:o}}(e,"First parameter");if(Tt(this),void 0!==n.type)throw new RangeError("Invalid type is specified");const s=dt(r);!function(e,t,r,n){const s=Object.create(Gt.prototype);let o,i,a,c;o=void 0!==t.start?()=>t.start(s):()=>{},i=void 0!==t.write?e=>t.write(e,s):()=>l(void 0),a=void 0!==t.close?()=>t.close():()=>l(void 0),c=void 0!==t.abort?e=>t.abort(e):()=>l(void 0),qt(e,s,o,i,a,c,r,n)}(this,n,ut(r,1),s)}get locked(){if(!vt(this))throw Jt("locked");return St(this)}abort(e=void 0){return vt(this)?St(this)?u(new TypeError("Cannot abort a stream that already has a writer")):At(this,e):u(Jt("abort"))}close(){return vt(this)?St(this)?u(new TypeError("Cannot close a stream that already has a writer")):kt(this)?u(new TypeError("Cannot close an already-closing stream")):Ot(this):u(Jt("close"))}getWriter(){if(!vt(this))throw Jt("getWriter");return wt(this)}}function wt(e){return new xt(e)}function Tt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new E,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function vt(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof Et}function St(e){return void 0!==e._writer}function At(e,t){var r;if("closed"===e._state||"errored"===e._state)return l(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const n=e._state;if("closed"===n||"errored"===n)return l(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let s=!1;"erroring"===n&&(s=!0,t=void 0);const o=c(((r,n)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:n,_reason:t,_wasAlreadyErroring:s}}));return e._pendingAbortRequest._promise=o,s||Ct(e,t),o}function Ot(e){const t=e._state;if("closed"===t||"errored"===t)return u(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=c(((t,r)=>{const n={_resolve:t,_reject:r};e._closeRequest=n})),n=e._writer;var s;return void 0!==n&&e._backpressure&&"writable"===t&&cr(n),Ee(s=e._writableStreamController,Bt,0),Vt(s),r}function It(e,t){"writable"!==e._state?Rt(e):Ct(e,t)}function Ct(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const n=e._writer;void 0!==n&&jt(n,t),!function(e){return void 0!==e._inFlightWriteRequest||void 0!==e._inFlightCloseRequest}(e)&&r._started&&Rt(e)}function Rt(e){e._state="errored",e._writableStreamController[T]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new E,void 0===e._pendingAbortRequest)return void Nt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Nt(e);h(e._writableStreamController[w](r._reason),(()=>(r._resolve(),Nt(e),null)),(t=>(r._reject(t),Nt(e),null)))}function kt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Nt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&rr(t,e._storedError)}function Pt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){sr(e)}(r):cr(r)),e._backpressure=t}Object.defineProperties(Et.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(Et.prototype.abort,"abort"),s(Et.prototype.close,"close"),s(Et.prototype.getWriter,"getWriter"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Et.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});class xt{constructor(e){if(F(e,1,"WritableStreamDefaultWriter"),gt(e,"First parameter"),St(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!kt(e)&&e._backpressure?sr(this):ir(this),er(this);else if("erroring"===t)or(this,e._storedError),er(this);else if("closed"===t)ir(this),er(r=this),nr(r);else{const t=e._storedError;or(this,t),tr(this,t)}var r}get closed(){return Dt(this)?this._closedPromise:u(Qt("closed"))}get desiredSize(){if(!Dt(this))throw Qt("desiredSize");if(void 0===this._ownerWritableStream)throw Zt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;return"errored"===r||"erroring"===r?null:"closed"===r?0:Wt(t._writableStreamController)}(this)}get ready(){return Dt(this)?this._readyPromise:u(Qt("ready"))}abort(e=void 0){return Dt(this)?void 0===this._ownerWritableStream?u(Zt("abort")):function(e,t){return At(e._ownerWritableStream,t)}(this,e):u(Qt("abort"))}close(){if(!Dt(this))return u(Qt("close"));const e=this._ownerWritableStream;return void 0===e?u(Zt("close")):kt(e)?u(new TypeError("Cannot close an already-closing stream")):Ut(this)}releaseLock(){if(!Dt(this))throw Qt("releaseLock");void 0!==this._ownerWritableStream&&Mt(this)}write(e=void 0){return Dt(this)?void 0===this._ownerWritableStream?u(Zt("write to")):Ft(this,e):u(Qt("write"))}}function Dt(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof xt}function Ut(e){return Ot(e._ownerWritableStream)}function Lt(e,t){"pending"===e._closedPromiseState?rr(e,t):function(e,t){tr(e,t)}(e,t)}function jt(e,t){"pending"===e._readyPromiseState?ar(e,t):function(e,t){or(e,t)}(e,t)}function Mt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");jt(e,r),Lt(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function Ft(e,t){const r=e._ownerWritableStream,n=r._writableStreamController,s=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Yt(e,t),1}}(n,t);if(r!==e._ownerWritableStream)return u(Zt("write to"));const o=r._state;if("errored"===o)return u(r._storedError);if(kt(r)||"closed"===o)return u(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===o)return u(r._storedError);const i=function(e){return c(((t,r)=>{const n={_resolve:t,_reject:r};e._writeRequests.push(n)}))}(r);return function(e,t,r){try{Ee(e,t,r)}catch(t){return void Yt(e,t)}const n=e._controlledWritableStream;kt(n)||"writable"!==n._state||Pt(n,zt(e)),Vt(e)}(n,t,s),i}Object.defineProperties(xt.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),s(xt.prototype.abort,"abort"),s(xt.prototype.close,"close"),s(xt.prototype.releaseLock,"releaseLock"),s(xt.prototype.write,"write"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(xt.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const Bt={};class Gt{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Ht(this))throw Xt("abortReason");return this._abortReason}get signal(){if(!Ht(this))throw Xt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!Ht(this))throw Xt("error");"writable"===this._controlledWritableStream._state&&Kt(this,e)}[w](e){const t=this._abortAlgorithm(e);return $t(this),t}[T](){we(this)}}function Ht(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof Gt}function qt(e,t,r,n,s,o,i,a){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,we(t),t._abortReason=void 0,t._abortController=function(){if(bt)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=a,t._strategyHWM=i,t._writeAlgorithm=n,t._closeAlgorithm=s,t._abortAlgorithm=o;const c=zt(t);Pt(e,c),h(l(r()),(()=>(t._started=!0,Vt(t),null)),(r=>(t._started=!0,It(e,r),null)))}function $t(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Wt(e){return e._strategyHWM-e._queueTotalSize}function Vt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void Rt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===Bt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),be(e);const r=e._closeAlgorithm();$t(e),h(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&nr(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),It(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const n=e._writeAlgorithm(t);h(n,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(be(e),!kt(r)&&"writable"===t){const t=zt(e);Pt(r,t)}return Vt(e),null}),(t=>("writable"===r._state&&$t(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,It(e,t)}(r,t),null)))}(e,r)}function Yt(e,t){"writable"===e._controlledWritableStream._state&&Kt(e,t)}function zt(e){return Wt(e)<=0}function Kt(e,t){const r=e._controlledWritableStream;$t(e),Ct(r,t)}function Jt(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Xt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Qt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Zt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function er(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function tr(e,t){er(e),rr(e,t)}function rr(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function nr(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function sr(e){e._readyPromise=c(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function or(e,t){sr(e),ar(e,t)}function ir(e){sr(e),cr(e)}function ar(e,t){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function cr(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(Gt.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Gt.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const lr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0,ur=function(){const e=null==lr?void 0:lr.DOMException;return function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(e)?e:void 0}()||function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return s(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function dr(e,r,n,s,o,i){const a=W(e),m=wt(r);e._disturbed=!0;let _=!1,g=l(void 0);return c(((b,E)=>{let w;if(void 0!==i){if(w=()=>{const t=void 0!==i.reason?i.reason:new ur("Aborted","AbortError"),n=[];s||n.push((()=>"writable"===r._state?At(r,t):l(void 0))),o||n.push((()=>"readable"===e._state?jr(e,t):l(void 0))),I((()=>Promise.all(n.map((e=>e())))),!0,t)},i.aborted)return void w();i.addEventListener("abort",w)}var T,v,S;if(O(e,a._closedPromise,(e=>(s?R(!0,e):I((()=>At(r,e)),!0,e),null))),O(r,m._closedPromise,(t=>(o?R(!0,t):I((()=>jr(e,t)),!0,t),null))),T=e,v=a._closedPromise,S=()=>(n?R():I((()=>function(e){const t=e._ownerWritableStream,r=t._state;return kt(t)||"closed"===r?l(void 0):"errored"===r?u(t._storedError):Ut(e)}(m))),null),"closed"===T._state?S():f(v,S),kt(r)||"closed"===r._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");o?R(!0,t):I((()=>jr(e,t)),!0,t)}function A(){const e=g;return d(g,(()=>e!==g?A():void 0))}function O(e,t,r){"errored"===e._state?r(e._storedError):p(t,r)}function I(e,t,n){function s(){return h(e(),(()=>k(t,n)),(e=>k(!0,e))),null}_||(_=!0,"writable"!==r._state||kt(r)?s():f(A(),s))}function R(e,t){_||(_=!0,"writable"!==r._state||kt(r)?k(e,t):f(A(),(()=>k(e,t))))}function k(e,t){return Mt(m),C(a),void 0!==i&&i.removeEventListener("abort",w),e?E(t):b(void 0),null}y(c(((e,r)=>{!function n(s){s?e():d(_?l(!0):d(m._readyPromise,(()=>c(((e,r)=>{Q(a,{_chunkSteps:r=>{g=d(Ft(m,r),void 0,t),e(!1)},_closeSteps:()=>e(!0),_errorSteps:r})})))),n,r)}(!1)})))}))}class hr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!fr(this))throw vr("desiredSize");return Er(this)}close(){if(!fr(this))throw vr("close");if(!wr(this))throw new TypeError("The stream is not in a state that permits close");_r(this)}enqueue(e=void 0){if(!fr(this))throw vr("enqueue");if(!wr(this))throw new TypeError("The stream is not in a state that permits enqueue");return gr(this,e)}error(e=void 0){if(!fr(this))throw vr("error");br(this,e)}[v](e){we(this);const t=this._cancelAlgorithm(e);return yr(this),t}[S](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=be(this);this._closeRequested&&0===this._queue.length?(yr(this),Mr(t)):pr(this),e._chunkSteps(r)}else V(t,e),pr(this)}[A](){}}function fr(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof hr}function pr(e){mr(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,h(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,pr(e)),null)),(t=>(br(e,t),null)))))}function mr(e){const t=e._controlledReadableStream;return!!wr(e)&&(!!e._started&&(!!(Lr(t)&&z(t)>0)||Er(e)>0))}function yr(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function _r(e){if(!wr(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(yr(e),Mr(t))}function gr(e,t){if(!wr(e))return;const r=e._controlledReadableStream;if(Lr(r)&&z(r)>0)Y(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw br(e,t),t}try{Ee(e,t,r)}catch(t){throw br(e,t),t}}pr(e)}function br(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(we(e),yr(e),Fr(r,t))}function Er(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function wr(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Tr(e,t,r,n,s,o,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,we(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=o,t._pullAlgorithm=n,t._cancelAlgorithm=s,e._readableStreamController=t,h(l(r()),(()=>(t._started=!0,pr(t),null)),(e=>(br(t,e),null)))}function vr(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function Sr(e,t){return Ae(e._readableStreamController)?function(e){let t,r,n,s,o,i=W(e),a=!1,u=!1,d=!1,h=!1,f=!1;const m=c((e=>{o=e}));function y(e){p(e._closedPromise,(t=>(e!==i||(We(n._readableStreamController,t),We(s._readableStreamController,t),h&&f||o(void 0)),null)))}function g(){it(i)&&(C(i),i=W(e),y(i)),Q(i,{_chunkSteps:t=>{_((()=>{u=!1,d=!1;const r=t;let i=t;if(!h&&!f)try{i=ge(t)}catch(t){return We(n._readableStreamController,t),We(s._readableStreamController,t),void o(jr(e,t))}h||$e(n._readableStreamController,r),f||$e(s._readableStreamController,i),a=!1,u?E():d&&w()}))},_closeSteps:()=>{a=!1,h||qe(n._readableStreamController),f||qe(s._readableStreamController),n._readableStreamController._pendingPullIntos.length>0&&Ke(n._readableStreamController,0),s._readableStreamController._pendingPullIntos.length>0&&Ke(s._readableStreamController,0),h&&f||o(void 0)},_errorSteps:()=>{a=!1}})}function b(t,r){X(i)&&(C(i),i=tt(e),y(i));const c=r?s:n,l=r?n:s;at(i,t,1,{_chunkSteps:t=>{_((()=>{u=!1,d=!1;const n=r?f:h;if(r?h:f)n||Je(c._readableStreamController,t);else{let r;try{r=ge(t)}catch(t){return We(c._readableStreamController,t),We(l._readableStreamController,t),void o(jr(e,t))}n||Je(c._readableStreamController,t),$e(l._readableStreamController,r)}a=!1,u?E():d&&w()}))},_closeSteps:e=>{a=!1;const t=r?f:h,n=r?h:f;t||qe(c._readableStreamController),n||qe(l._readableStreamController),void 0!==e&&(t||Je(c._readableStreamController,e),!n&&l._readableStreamController._pendingPullIntos.length>0&&Ke(l._readableStreamController,0)),t&&n||o(void 0)},_errorSteps:()=>{a=!1}})}function E(){if(a)return u=!0,l(void 0);a=!0;const e=Ye(n._readableStreamController);return null===e?g():b(e._view,!1),l(void 0)}function w(){if(a)return d=!0,l(void 0);a=!0;const e=Ye(s._readableStreamController);return null===e?g():b(e._view,!0),l(void 0)}function T(n){if(h=!0,t=n,f){const n=ue([t,r]),s=jr(e,n);o(s)}return m}function v(n){if(f=!0,r=n,h){const n=ue([t,r]),s=jr(e,n);o(s)}return m}function S(){}return n=xr(S,E,T),s=xr(S,w,v),y(i),[n,s]}(e):function(e){const t=W(e);let r,n,s,o,i,a=!1,u=!1,d=!1,h=!1;const f=c((e=>{i=e}));function m(){return a?(u=!0,l(void 0)):(a=!0,Q(t,{_chunkSteps:e=>{_((()=>{u=!1;const t=e,r=e;d||gr(s._readableStreamController,t),h||gr(o._readableStreamController,r),a=!1,u&&m()}))},_closeSteps:()=>{a=!1,d||_r(s._readableStreamController),h||_r(o._readableStreamController),d&&h||i(void 0)},_errorSteps:()=>{a=!1}}),l(void 0))}function y(t){if(d=!0,r=t,h){const t=ue([r,n]),s=jr(e,t);i(s)}return f}function g(t){if(h=!0,n=t,d){const t=ue([r,n]),s=jr(e,t);i(s)}return f}function b(){}return s=Pr(b,m,y),o=Pr(b,m,g),p(t._closedPromise,(e=>(br(s._readableStreamController,e),br(o._readableStreamController,e),d&&h||i(void 0),null))),[s,o]}(e)}function Ar(e){return r(n=e)&&void 0!==n.getReader?function(e){let n;function s(){let t;try{t=e.read()}catch(e){return u(e)}return m(t,(e=>{if(!r(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)_r(n._readableStreamController);else{const t=e.value;gr(n._readableStreamController,t)}}))}function o(t){try{return l(e.cancel(t))}catch(e){return u(e)}}return n=Pr(t,s,o,0),n}(e.getReader()):function(e){let n;const s=_e(e,"async");function o(){let e;try{e=function(e){const t=g(e.nextMethod,e.iterator,[]);if(!r(t))throw new TypeError("The iterator.next() method must return an object");return t}(s)}catch(e){return u(e)}return m(l(e),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");const t=function(e){return Boolean(e.done)}(e);if(t)_r(n._readableStreamController);else{const t=function(e){return e.value}(e);gr(n._readableStreamController,t)}}))}function i(e){const t=s.iterator;let n,o;try{n=me(t,"return")}catch(e){return u(e)}if(void 0===n)return l(void 0);try{o=g(n,t,[e])}catch(e){return u(e)}return m(l(o),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return n=Pr(t,o,i,0),n}(e);var n}function Or(e,t,r){return j(e,r),r=>b(e,t,[r])}function Ir(e,t,r){return j(e,r),r=>b(e,t,[r])}function Cr(e,t,r){return j(e,r),r=>g(e,t,[r])}function Rr(e,t){if("bytes"!=(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function kr(e,t){L(e,t);const r=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,s=null==e?void 0:e.preventClose,o=null==e?void 0:e.signal;return void 0!==o&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(o,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(n),preventClose:Boolean(s),signal:o}}Object.defineProperties(hr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),s(hr.prototype.close,"close"),s(hr.prototype.enqueue,"enqueue"),s(hr.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(hr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class Nr{constructor(e={},t={}){void 0===e?e=null:M(e,"First parameter");const r=ht(t,"Second parameter"),n=function(e,t){L(e,t);const r=e,n=null==r?void 0:r.autoAllocateChunkSize,s=null==r?void 0:r.cancel,o=null==r?void 0:r.pull,i=null==r?void 0:r.start,a=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===n?void 0:q(n,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===s?void 0:Or(s,r,`${t} has member 'cancel' that`),pull:void 0===o?void 0:Ir(o,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Cr(i,r,`${t} has member 'start' that`),type:void 0===a?void 0:Rr(a,`${t} has member 'type' that`)}}(e,"First parameter");if(Dr(this),"bytes"===n.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const n=Object.create(Se.prototype);let s,o,i;s=void 0!==t.start?()=>t.start(n):()=>{},o=void 0!==t.pull?()=>t.pull(n):()=>l(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>l(void 0);const a=t.autoAllocateChunkSize;if(0===a)throw new TypeError("autoAllocateChunkSize must be greater than 0");Xe(e,n,s,o,i,r,a)}(this,n,ut(r,0))}else{const e=dt(r);!function(e,t,r,n){const s=Object.create(hr.prototype);let o,i,a;o=void 0!==t.start?()=>t.start(s):()=>{},i=void 0!==t.pull?()=>t.pull(s):()=>l(void 0),a=void 0!==t.cancel?e=>t.cancel(e):()=>l(void 0),Tr(e,s,o,i,a,r,n)}(this,n,ut(r,1),e)}}get locked(){if(!Ur(this))throw Br("locked");return Lr(this)}cancel(e=void 0){return Ur(this)?Lr(this)?u(new TypeError("Cannot cancel a stream that already has a reader")):jr(this,e):u(Br("cancel"))}getReader(e=void 0){if(!Ur(this))throw Br("getReader");return void 0===function(e,t){L(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:et(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?W(this):tt(this)}pipeThrough(e,t={}){if(!Ur(this))throw Br("pipeThrough");F(e,1,"pipeThrough");const r=function(e,t){L(e,t);const r=null==e?void 0:e.readable;B(r,"readable","ReadableWritablePair"),$(r,`${t} has member 'readable' that`);const n=null==e?void 0:e.writable;return B(n,"writable","ReadableWritablePair"),gt(n,`${t} has member 'writable' that`),{readable:r,writable:n}}(e,"First parameter"),n=kr(t,"Second parameter");if(Lr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(St(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(dr(this,r.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),r.readable}pipeTo(e,t={}){if(!Ur(this))return u(Br("pipeTo"));if(void 0===e)return u("Parameter 1 is required in 'pipeTo'.");if(!vt(e))return u(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=kr(t,"Second parameter")}catch(e){return u(e)}return Lr(this)?u(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):St(e)?u(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):dr(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Ur(this))throw Br("tee");return ue(Sr(this))}values(e=void 0){if(!Ur(this))throw Br("values");return function(e,t){const r=W(e),n=new re(r,t),s=Object.create(ne);return s._asyncIteratorImpl=n,s}(this,function(e,t){L(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}[ye](e){return this.values(e)}static from(e){return Ar(e)}}function Pr(e,t,r,n=1,s=()=>1){const o=Object.create(Nr.prototype);return Dr(o),Tr(o,Object.create(hr.prototype),e,t,r,n,s),o}function xr(e,t,r){const n=Object.create(Nr.prototype);return Dr(n),Xe(n,Object.create(Se.prototype),e,t,r,0,void 0),n}function Dr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Ur(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof Nr}function Lr(e){return void 0!==e._reader}function jr(e,r){if(e._disturbed=!0,"closed"===e._state)return l(void 0);if("errored"===e._state)return u(e._storedError);Mr(e);const n=e._reader;if(void 0!==n&&it(n)){const e=n._readIntoRequests;n._readIntoRequests=new E,e.forEach((e=>{e._closeSteps(void 0)}))}return m(e._readableStreamController[v](r),t)}function Mr(e){e._state="closed";const t=e._reader;if(void 0!==t&&(x(t),X(t))){const e=t._readRequests;t._readRequests=new E,e.forEach((e=>{e._closeSteps()}))}}function Fr(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(P(r,t),X(r)?Z(r,t):ct(r,t))}function Br(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Gr(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark;return B(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:G(r)}}Object.defineProperties(Nr,{from:{enumerable:!0}}),Object.defineProperties(Nr.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),s(Nr.from,"from"),s(Nr.prototype.cancel,"cancel"),s(Nr.prototype.getReader,"getReader"),s(Nr.prototype.pipeThrough,"pipeThrough"),s(Nr.prototype.pipeTo,"pipeTo"),s(Nr.prototype.tee,"tee"),s(Nr.prototype.values,"values"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Nr.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Nr.prototype,ye,{value:Nr.prototype.values,writable:!0,configurable:!0});const Hr=e=>e.byteLength;s(Hr,"size");class qr{constructor(e){F(e,1,"ByteLengthQueuingStrategy"),e=Gr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Wr(this))throw $r("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Wr(this))throw $r("size");return Hr}}function $r(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Wr(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof qr}Object.defineProperties(qr.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(qr.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const Vr=()=>1;s(Vr,"size");class Yr{constructor(e){F(e,1,"CountQueuingStrategy"),e=Gr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Kr(this))throw zr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Kr(this))throw zr("size");return Vr}}function zr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Kr(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof Yr}function Jr(e,t,r){return j(e,r),r=>b(e,t,[r])}function Xr(e,t,r){return j(e,r),r=>g(e,t,[r])}function Qr(e,t,r){return j(e,r),(r,n)=>b(e,t,[r,n])}function Zr(e,t,r){return j(e,r),r=>b(e,t,[r])}Object.defineProperties(Yr.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Yr.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class en{constructor(e={},t={},r={}){void 0===e&&(e=null);const n=ht(t,"Second parameter"),s=ht(r,"Third parameter"),o=function(e,t){L(e,t);const r=null==e?void 0:e.cancel,n=null==e?void 0:e.flush,s=null==e?void 0:e.readableType,o=null==e?void 0:e.start,i=null==e?void 0:e.transform,a=null==e?void 0:e.writableType;return{cancel:void 0===r?void 0:Zr(r,e,`${t} has member 'cancel' that`),flush:void 0===n?void 0:Jr(n,e,`${t} has member 'flush' that`),readableType:s,start:void 0===o?void 0:Xr(o,e,`${t} has member 'start' that`),transform:void 0===i?void 0:Qr(i,e,`${t} has member 'transform' that`),writableType:a}}(e,"First parameter");if(void 0!==o.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==o.writableType)throw new RangeError("Invalid writableType specified");const i=ut(s,0),a=dt(s),d=ut(n,1),f=dt(n);let p;!function(e,t,r,n,s,o){function i(){return t}function a(t){return function(e,t){const r=e._transformStreamController;return e._backpressure?m(e._backpressureChangePromise,(()=>{const n=e._writable;if("erroring"===n._state)throw n._storedError;return dn(r,t)})):dn(r,t)}(e,t)}function l(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const n=e._readable;r._finishPromise=c(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const s=r._cancelAlgorithm(t);return ln(r),h(s,(()=>("errored"===n._state?pn(r,n._storedError):(br(n._readableStreamController,t),fn(r)),null)),(e=>(br(n._readableStreamController,e),pn(r,e),null))),r._finishPromise}(e,t)}function u(){return function(e){const t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;const r=e._readable;t._finishPromise=c(((e,r)=>{t._finishPromise_resolve=e,t._finishPromise_reject=r}));const n=t._flushAlgorithm();return ln(t),h(n,(()=>("errored"===r._state?pn(t,r._storedError):(_r(r._readableStreamController),fn(t)),null)),(e=>(br(r._readableStreamController,e),pn(t,e),null))),t._finishPromise}(e)}function d(){return function(e){return on(e,!1),e._backpressureChangePromise}(e)}function f(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const n=e._writable;r._finishPromise=c(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const s=r._cancelAlgorithm(t);return ln(r),h(s,(()=>("errored"===n._state?pn(r,n._storedError):(Yt(n._writableStreamController,t),sn(e),fn(r)),null)),(t=>(Yt(n._writableStreamController,t),sn(e),pn(r,t),null))),r._finishPromise}(e,t)}e._writable=function(e,t,r,n,s=1,o=()=>1){const i=Object.create(Et.prototype);return Tt(i),qt(i,Object.create(Gt.prototype),e,t,r,n,s,o),i}(i,a,u,l,r,n),e._readable=Pr(i,d,f,s,o),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,on(e,!0),e._transformStreamController=void 0}(this,c((e=>{p=e})),d,f,i,a),function(e,t){const r=Object.create(an.prototype);let n,s,o;n=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return un(r,e),l(void 0)}catch(e){return u(e)}},s=void 0!==t.flush?()=>t.flush(r):()=>l(void 0),o=void 0!==t.cancel?e=>t.cancel(e):()=>l(void 0),function(e,t,r,n,s){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=n,t._cancelAlgorithm=s,t._finishPromise=void 0,t._finishPromise_resolve=void 0,t._finishPromise_reject=void 0}(e,r,n,s,o)}(this,o),void 0!==o.start?p(o.start(this._transformStreamController)):p(void 0)}get readable(){if(!tn(this))throw mn("readable");return this._readable}get writable(){if(!tn(this))throw mn("writable");return this._writable}}function tn(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof en}function rn(e,t){br(e._readable._readableStreamController,t),nn(e,t)}function nn(e,t){ln(e._transformStreamController),Yt(e._writable._writableStreamController,t),sn(e)}function sn(e){e._backpressure&&on(e,!1)}function on(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(en.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(en.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});class an{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!cn(this))throw hn("desiredSize");return Er(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!cn(this))throw hn("enqueue");un(this,e)}error(e=void 0){if(!cn(this))throw hn("error");var t;t=e,rn(this._controlledTransformStream,t)}terminate(){if(!cn(this))throw hn("terminate");!function(e){const t=e._controlledTransformStream;_r(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");nn(t,r)}(this)}}function cn(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof an}function ln(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function un(e,t){const r=e._controlledTransformStream,n=r._readable._readableStreamController;if(!wr(n))throw new TypeError("Readable side is not in a state that permits enqueue");try{gr(n,t)}catch(e){throw nn(r,e),r._readable._storedError}const s=function(e){return!mr(e)}(n);s!==r._backpressure&&on(r,!0)}function dn(e,t){return m(e._transformAlgorithm(t),void 0,(t=>{throw rn(e._controlledTransformStream,t),t}))}function hn(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function fn(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function pn(e,t){void 0!==e._finishPromise_reject&&(y(e._finishPromise),e._finishPromise_reject(t),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function mn(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(an.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(an.prototype.enqueue,"enqueue"),s(an.prototype.error,"error"),s(an.prototype.terminate,"terminate"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(an.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}),e.ByteLengthQueuingStrategy=qr,e.CountQueuingStrategy=Yr,e.ReadableByteStreamController=Se,e.ReadableStream=Nr,e.ReadableStreamBYOBReader=ot,e.ReadableStreamBYOBRequest=ve,e.ReadableStreamDefaultController=hr,e.ReadableStreamDefaultReader=J,e.TransformStream=en,e.TransformStreamDefaultController=an,e.WritableStream=Et,e.WritableStreamDefaultController=Gt,e.WritableStreamDefaultWriter=xt},"object"==typeof e&&void 0!==t?n(e):"function"==typeof define&&define.amd?define(["exports"],n):n((r="undefined"!=typeof globalThis?globalThis:r||self).WebStreamsPolyfill={})}}),re=A({"node_modules/fetch-blob/streams.cjs"(){if(!globalThis.ReadableStream)try{const e=v("process"),{emitWarning:t}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,v("stream/web")),e.emitWarning=t}catch(r){throw e.emitWarning=t,r}}catch(e){Object.assign(globalThis,te())}try{const{Blob:e}=v("buffer");e&&!e.prototype.stream&&(e.prototype.stream=function(e){let t=0;const r=this;return new ReadableStream({type:"bytes",async pull(e){const n=r.slice(t,Math.min(r.size,t+65536)),s=await n.arrayBuffer();t+=s.byteLength,e.enqueue(new Uint8Array(s)),t===r.size&&e.close()}})})}catch(e){}}});async function*ne(e,t=!0){for(const r of e)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(t){let e=r.byteOffset;const t=r.byteOffset+r.byteLength;for(;e!==t;){const n=Math.min(t-e,X),s=r.buffer.slice(e,e+n);e+=s.byteLength,yield new Uint8Array(s)}}else yield r;else{let e=0,t=r;for(;e!==t.size;){const r=t.slice(e,Math.min(t.size,e+X)),n=await r.arrayBuffer();e+=n.byteLength,yield new Uint8Array(n)}}}var se,oe,ie,ae,ce,le,ue,de,he,fe,pe,me=S({"node_modules/fetch-blob/index.js"(){I(re(),1),X=65536,Q=class e{#e=[];#t="";#r=0;#n="transparent";constructor(t=[],r={}){if("object"!=typeof t||null===t)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if("function"!=typeof t[Symbol.iterator])throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if("object"!=typeof r&&"function"!=typeof r)throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");null===r&&(r={});const n=new TextEncoder;for(const r of t){let t;t=ArrayBuffer.isView(r)?new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)):r instanceof ArrayBuffer?new Uint8Array(r.slice(0)):r instanceof e?r:n.encode(`${r}`),this.#r+=ArrayBuffer.isView(t)?t.byteLength:t.size,this.#e.push(t)}this.#n=`${void 0===r.endings?"transparent":r.endings}`;const s=void 0===r.type?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(s)?s:""}get size(){return this.#r}get type(){return this.#t}async text(){const e=new TextDecoder;let t="";for await(const r of ne(this.#e,!1))t+=e.decode(r,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){const e=new Uint8Array(this.size);let t=0;for await(const r of ne(this.#e,!1))e.set(r,t),t+=r.length;return e.buffer}stream(){const e=ne(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){const r=await e.next();r.done?t.close():t.enqueue(r.value)},async cancel(){await e.return()}})}slice(t=0,r=this.size,n=""){const{size:s}=this;let o=t<0?Math.max(s+t,0):Math.min(t,s),i=r<0?Math.max(s+r,0):Math.min(r,s);const a=Math.max(i-o,0),c=this.#e,l=[];let u=0;for(const e of c){if(u>=a)break;const t=ArrayBuffer.isView(e)?e.byteLength:e.size;if(o&&t<=o)o-=t,i-=t;else{let r;ArrayBuffer.isView(e)?(r=e.subarray(o,Math.min(t,i)),u+=r.byteLength):(r=e.slice(o,Math.min(t,i)),u+=r.size),i-=t,l.push(r),o=0}}const d=new e([],{type:String(n).toLowerCase()});return d.#r=a,d.#e=l,d}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&"object"==typeof e&&"function"==typeof e.constructor&&("function"==typeof e.stream||"function"==typeof e.arrayBuffer)&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}},Object.defineProperties(Q.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}}),Z=Q}}),ye=S({"node_modules/fetch-blob/file.js"(){me(),se=class extends Z{#s=0;#o="";constructor(e,t,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),null===r&&(r={});const n=void 0===r.lastModified?Date.now():Number(r.lastModified);Number.isNaN(n)||(this.#s=n),this.#o=String(t)}get name(){return this.#o}get lastModified(){return this.#s}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Z&&/^(File)$/.test(e[Symbol.toStringTag])}},oe=se}});var _e,ge,be,Ee,we,Te,ve,Se,Ae,Oe,Ie,Ce,Re,ke,Ne,Pe,xe,De,Ue,Le,je,Me,Fe,Be,Ge=S({"node_modules/formdata-polyfill/esm.min.js"(){me(),ye(),({toStringTag:ie,iterator:ae,hasInstance:ce}=Symbol),le=Math.random,ue="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),de=(e,t,r)=>(e+="",/^(Blob|File)$/.test(t&&t[ie])?[(r=void 0!==r?r+"":"File"==t[ie]?t.name:"blob",e),t.name!==r||"blob"==t[ie]?new oe([t],r,t):t]:[e,t+""]),he=(e,t)=>(t?e:e.replace(/\r?\n|\r/g,"\r\n")).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),fe=(e,t,r)=>{if(t.length<r)throw new TypeError(`Failed to execute '${e}' on 'FormData': ${r} arguments required, but only ${t.length} present.`)},pe=class{#i=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[ie](){return"FormData"}[ae](){return this.entries()}static[ce](e){return e&&"object"==typeof e&&"FormData"===e[ie]&&!ue.some((t=>"function"!=typeof e[t]))}append(...e){fe("append",arguments,2),this.#i.push(de(...e))}delete(e){fe("delete",arguments,1),e+="",this.#i=this.#i.filter((([t])=>t!==e))}get(e){fe("get",arguments,1),e+="";for(var t=this.#i,r=t.length,n=0;n<r;n++)if(t[n][0]===e)return t[n][1];return null}getAll(e,t){return fe("getAll",arguments,1),t=[],e+="",this.#i.forEach((r=>r[0]===e&&t.push(r[1]))),t}has(e){return fe("has",arguments,1),e+="",this.#i.some((t=>t[0]===e))}forEach(e,t){for(var[r,n]of(fe("forEach",arguments,1),this))e.call(t,n,r,this)}set(...e){fe("set",arguments,2);var t=[],r=!0;e=de(...e),this.#i.forEach((n=>{n[0]===e[0]?r&&(r=!t.push(e)):t.push(n)})),r&&t.push(e),this.#i=t}*entries(){yield*this.#i}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}}}),He=S({"node_modules/node-fetch/src/errors/base.js"(){_e=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}}}),qe=S({"node_modules/node-fetch/src/errors/fetch-error.js"(){He(),ge=class extends _e{constructor(e,t,r){super(e,t),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}}}}),$e=S({"node_modules/node-fetch/src/utils/is.js"(){be=Symbol.toStringTag,Ee=e=>"object"==typeof e&&"function"==typeof e.append&&"function"==typeof e.delete&&"function"==typeof e.get&&"function"==typeof e.getAll&&"function"==typeof e.has&&"function"==typeof e.set&&"function"==typeof e.sort&&"URLSearchParams"===e[be],we=e=>e&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.constructor&&/^(Blob|File)$/.test(e[be]),Te=e=>"object"==typeof e&&("AbortSignal"===e[be]||"EventTarget"===e[be]),ve=(e,t)=>{const r=new URL(t).hostname,n=new URL(e).hostname;return r===n||r.endsWith(`.${n}`)},Se=(e,t)=>new URL(t).protocol===new URL(e).protocol}}),We=A({"node_modules/node-domexception/index.js"(e,t){if(!globalThis.DOMException)try{const{MessageChannel:e}=v("worker_threads"),t=(new e).port1,r=new ArrayBuffer;t.postMessage(r,[r,r])}catch(e){"DOMException"===e.constructor.name&&(globalThis.DOMException=e.constructor)}t.exports=globalThis.DOMException}}),Ve=S({"node_modules/fetch-blob/from.js"(){Ae=I(We(),1),ye(),me(),({stat:Oe}=e.promises),Ie=(t,r)=>Ne(e.statSync(t),t,r),Ce=(e,t)=>Oe(e).then((r=>Ne(r,e,t))),Re=(e,t)=>Oe(e).then((r=>Pe(r,e,t))),ke=(t,r)=>Pe(e.statSync(t),t,r),Ne=(e,t,r="")=>new Z([new xe({path:t,size:e.size,lastModified:e.mtimeMs,start:0})],{type:r}),Pe=(e,r,n="")=>new oe([new xe({path:r,size:e.size,lastModified:e.mtimeMs,start:0})],t.basename(r),{type:n,lastModified:e.mtimeMs}),xe=class t{#a;#c;constructor(e){this.#a=e.path,this.#c=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,r){return new t({path:this.#a,lastModified:this.lastModified,size:r-e,start:this.#c+e})}async*stream(){const{mtimeMs:t}=await Oe(this.#a);if(t>this.lastModified)throw new Ae.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*e.createReadStream(this.#a,{start:this.#c,end:this.#c+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}}}),Ye={};async function ze(e,t){if(!/multipart/i.test(t))throw new TypeError("Failed to fetch");const r=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new TypeError("no or bad content-type header, no multipart boundary");const n=new Be(r[1]||r[2]);let s,o,i,a,c,l;const u=[],d=new pe,h=e=>{i+=y.decode(e,{stream:!0})},f=e=>{u.push(e)},p=()=>{const e=new oe(u,l,{type:c});d.append(a,e)},m=()=>{d.append(a,i)},y=new TextDecoder("utf-8");y.decode(),n.onPartBegin=function(){n.onPartData=h,n.onPartEnd=m,s="",o="",i="",a="",c="",l=null,u.length=0},n.onHeaderField=function(e){s+=y.decode(e,{stream:!0})},n.onHeaderValue=function(e){o+=y.decode(e,{stream:!0})},n.onHeaderEnd=function(){if(o+=y.decode(),s=s.toLowerCase(),"content-disposition"===s){const e=o.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);e&&(a=e[2]||e[3]||""),l=function(e){const t=e.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!t)return;const r=t[2]||t[3]||"";let n=r.slice(r.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,((e,t)=>String.fromCharCode(t))),n}(o),l&&(n.onPartData=f,n.onPartEnd=p)}else"content-type"===s&&(c=o);o="",s=""};for await(const t of e)n.write(t);return n.end(),d}O(Ye,{toFormData:()=>ze});var Ke,Je,Xe,Qe,Ze,et,tt,rt,nt=S({"node_modules/node-fetch/src/utils/multipart-parser.js"(){Ve(),Ge(),De=0,Ue={START_BOUNDARY:De++,HEADER_FIELD_START:De++,HEADER_FIELD:De++,HEADER_VALUE_START:De++,HEADER_VALUE:De++,HEADER_VALUE_ALMOST_DONE:De++,HEADERS_ALMOST_DONE:De++,PART_DATA_START:De++,PART_DATA:De++,END:De++},je={PART_BOUNDARY:Le=1,LAST_BOUNDARY:Le*=2},Me=e=>32|e,Fe=()=>{},Be=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Fe,this.onHeaderField=Fe,this.onHeadersEnd=Fe,this.onHeaderValue=Fe,this.onPartBegin=Fe,this.onPartData=Fe,this.onPartEnd=Fe,this.boundaryChars={},e="\r\n--"+e;const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r),this.boundaryChars[t[r]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Ue.START_BOUNDARY}write(e){let t=0;const r=e.length;let n=this.index,{lookbehind:s,boundary:o,boundaryChars:i,index:a,state:c,flags:l}=this;const u=this.boundary.length,d=u-1,h=e.length;let f,p;const m=e=>{this[e+"Mark"]=t},y=e=>{delete this[e+"Mark"]},_=(e,t,r,n)=>{void 0!==t&&t===r||this[e](n&&n.subarray(t,r))},g=(r,n)=>{const s=r+"Mark";s in this&&(n?(_(r,this[s],t,e),delete this[s]):(_(r,this[s],e.length,e),this[s]=0))};for(t=0;t<r;t++)switch(f=e[t],c){case Ue.START_BOUNDARY:if(a===o.length-2){if(45===f)l|=je.LAST_BOUNDARY;else if(13!==f)return;a++;break}if(a-1==o.length-2){if(l&je.LAST_BOUNDARY&&45===f)c=Ue.END,l=0;else{if(l&je.LAST_BOUNDARY||10!==f)return;a=0,_("onPartBegin"),c=Ue.HEADER_FIELD_START}break}f!==o[a+2]&&(a=-2),f===o[a+2]&&a++;break;case Ue.HEADER_FIELD_START:c=Ue.HEADER_FIELD,m("onHeaderField"),a=0;case Ue.HEADER_FIELD:if(13===f){y("onHeaderField"),c=Ue.HEADERS_ALMOST_DONE;break}if(a++,45===f)break;if(58===f){if(1===a)return;g("onHeaderField",!0),c=Ue.HEADER_VALUE_START;break}if(p=Me(f),p<97||p>122)return;break;case Ue.HEADER_VALUE_START:if(32===f)break;m("onHeaderValue"),c=Ue.HEADER_VALUE;case Ue.HEADER_VALUE:13===f&&(g("onHeaderValue",!0),_("onHeaderEnd"),c=Ue.HEADER_VALUE_ALMOST_DONE);break;case Ue.HEADER_VALUE_ALMOST_DONE:if(10!==f)return;c=Ue.HEADER_FIELD_START;break;case Ue.HEADERS_ALMOST_DONE:if(10!==f)return;_("onHeadersEnd"),c=Ue.PART_DATA_START;break;case Ue.PART_DATA_START:c=Ue.PART_DATA,m("onPartData");case Ue.PART_DATA:if(n=a,0===a){for(t+=d;t<h&&!(e[t]in i);)t+=u;t-=d,f=e[t]}if(a<o.length)o[a]===f?(0===a&&g("onPartData",!0),a++):a=0;else if(a===o.length)a++,13===f?l|=je.PART_BOUNDARY:45===f?l|=je.LAST_BOUNDARY:a=0;else if(a-1===o.length)if(l&je.PART_BOUNDARY){if(a=0,10===f){l&=~je.PART_BOUNDARY,_("onPartEnd"),_("onPartBegin"),c=Ue.HEADER_FIELD_START;break}}else l&je.LAST_BOUNDARY&&45===f?(_("onPartEnd"),c=Ue.END,l=0):a=0;if(a>0)s[a-1]=f;else if(n>0){const e=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);_("onPartData",0,n,e),n=0,m("onPartData"),t--}break;case Ue.END:break;default:throw new Error(`Unexpected state entered: ${c}`)}g("onHeaderField"),g("onHeaderValue"),g("onPartData"),this.index=a,this.state=c,this.flags=l}end(){if(this.state===Ue.HEADER_FIELD_START&&0===this.index||this.state===Ue.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Ue.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}}});async function st(e){if(e[Je].disturbed)throw new TypeError(`body used already for: ${e.url}`);if(e[Je].disturbed=!0,e[Je].error)throw e[Je].error;const{body:t}=e;if(null===t)return s.Buffer.alloc(0);if(!(t instanceof f.default))return s.Buffer.alloc(0);const r=[];let n=0;try{for await(const s of t){if(e.size>0&&n+s.length>e.size){const r=new ge(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(r),r}n+=s.length,r.push(s)}}catch(t){throw t instanceof _e?t:new ge(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,"system",t)}if(!0!==t.readableEnded&&!0!==t._readableState.ended)throw new ge(`Premature close of server response while trying to fetch ${e.url}`);try{return r.every((e=>"string"==typeof e))?s.Buffer.from(r.join("")):s.Buffer.concat(r,n)}catch(t){throw new ge(`Could not create Buffer from response body for ${e.url}: ${t.message}`,"system",t)}}var ot,it,at,ct=S({"node_modules/node-fetch/src/body.js"(){me(),Ge(),qe(),He(),$e(),Ke=n.promisify(f.default.pipeline),Je=Symbol("Body internals"),(Xe=class{constructor(e,{size:t=0}={}){let r=null;null===e?e=null:Ee(e)?e=s.Buffer.from(e.toString()):we(e)||s.Buffer.isBuffer(e)||(n.types.isAnyArrayBuffer(e)?e=s.Buffer.from(e):ArrayBuffer.isView(e)?e=s.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof f.default||(e instanceof pe?r=(e=function(e,t=Z){var r=`${le()}${le()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],s=`--${r}\r\nContent-Disposition: form-data; name="`;return e.forEach(((e,t)=>"string"==typeof e?n.push(s+he(t)+`"\r\n\r\n${e.replace(/\r(?!\n)|(?<!\r)\n/g,"\r\n")}\r\n`):n.push(s+he(t)+`"; filename="${he(e.name,1)}"\r\nContent-Type: ${e.type||"application/octet-stream"}\r\n\r\n`,e,"\r\n"))),n.push(`--${r}--`),new t(n,{type:"multipart/form-data; boundary="+r})}(e)).type.split("=")[1]:e=s.Buffer.from(String(e))));let o=e;s.Buffer.isBuffer(e)?o=f.default.Readable.from(e):we(e)&&(o=f.default.Readable.from(e.stream())),this[Je]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof f.default&&e.on("error",(e=>{const t=e instanceof _e?e:new ge(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,"system",e);this[Je].error=t}))}get body(){return this[Je].stream}get bodyUsed(){return this[Je].disturbed}async arrayBuffer(){const{buffer:e,byteOffset:t,byteLength:r}=await st(this);return e.slice(t,t+r)}async formData(){const e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){const e=new pe,t=new URLSearchParams(await this.text());for(const[r,n]of t)e.append(r,n);return e}const{toFormData:t}=await Promise.resolve().then((()=>(nt(),Ye)));return t(this.body,e)}async blob(){const e=this.headers&&this.headers.get("content-type")||this[Je].body&&this[Je].body.type||"",t=await this.arrayBuffer();return new Z([t],{type:e})}async json(){const e=await this.text();return JSON.parse(e)}async text(){const e=await st(this);return(new TextDecoder).decode(e)}buffer(){return st(this)}}).prototype.buffer=n.deprecate(Xe.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(Xe.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:n.deprecate((()=>{}),"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}}),Qe=(e,t)=>{let n,s,{body:o}=e[Je];if(e.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof f.default&&"function"!=typeof o.getBoundary&&(n=new r.PassThrough({highWaterMark:t}),s=new r.PassThrough({highWaterMark:t}),o.pipe(n),o.pipe(s),e[Je].stream=n,o=s),o},Ze=n.deprecate((e=>e.getBoundary()),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),et=(e,t)=>null===e?null:"string"==typeof e?"text/plain;charset=UTF-8":Ee(e)?"application/x-www-form-urlencoded;charset=UTF-8":we(e)?e.type||null:s.Buffer.isBuffer(e)||n.types.isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof pe?`multipart/form-data; boundary=${t[Je].boundary}`:e&&"function"==typeof e.getBoundary?`multipart/form-data;boundary=${Ze(e)}`:e instanceof f.default?null:"text/plain;charset=UTF-8",tt=e=>{const{body:t}=e[Je];return null===t?0:we(t)?t.size:s.Buffer.isBuffer(t)?t.length:t&&"function"==typeof t.getLengthSync&&t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null},rt=async(e,{body:t})=>{null===t?e.end():await Ke(t,e)}}});var lt,ut,dt,ht,ft,pt,mt,yt=S({"node_modules/node-fetch/src/headers.js"(){ot="function"==typeof p.default.validateHeaderName?p.default.validateHeaderName:e=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){const t=new TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),t}},it="function"==typeof p.default.validateHeaderValue?p.default.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){const t=new TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},at=class e extends URLSearchParams{constructor(t){let r=[];if(t instanceof e){const e=t.raw();for(const[t,n]of Object.entries(e))r.push(...n.map((e=>[t,e])))}else if(null==t);else{if("object"!=typeof t||n.types.isBoxedPrimitive(t))throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");{const e=t[Symbol.iterator];if(null==e)r.push(...Object.entries(t));else{if("function"!=typeof e)throw new TypeError("Header pairs must be iterable");r=[...t].map((e=>{if("object"!=typeof e||n.types.isBoxedPrimitive(e))throw new TypeError("Each header pair must be an iterable object");return[...e]})).map((e=>{if(2!==e.length)throw new TypeError("Each header pair must be a name/value tuple");return[...e]}))}}}return r=r.length>0?r.map((([e,t])=>(ot(e),it(e,String(t)),[String(e).toLowerCase(),String(t)]))):void 0,super(r),new Proxy(this,{get(e,t,r){switch(t){case"append":case"set":return(r,n)=>(ot(r),it(r,String(n)),URLSearchParams.prototype[t].call(e,String(r).toLowerCase(),String(n)));case"delete":case"has":case"getAll":return r=>(ot(r),URLSearchParams.prototype[t].call(e,String(r).toLowerCase()));case"keys":return()=>(e.sort(),new Set(URLSearchParams.prototype.keys.call(e)).keys());default:return Reflect.get(e,t,r)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){const t=this.getAll(e);if(0===t.length)return null;let r=t.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,t=void 0){for(const r of this.keys())Reflect.apply(e,t,[this.get(r),r,this])}*values(){for(const e of this.keys())yield this.get(e)}*entries(){for(const e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce(((e,t)=>(e[t]=this.getAll(t),e)),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce(((e,t)=>{const r=this.getAll(t);return e[t]="host"===t?r[0]:r.length>1?r:r[0],e}),{})}},Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce(((e,t)=>(e[t]={enumerable:!0},e)),{}))}}),_t=S({"node_modules/node-fetch/src/utils/is-redirect.js"(){lt=new Set([301,302,303,307,308]),ut=e=>lt.has(e)}}),gt=S({"node_modules/node-fetch/src/response.js"(){yt(),ct(),_t(),dt=Symbol("Response internals"),ht=class e extends Xe{constructor(e=null,t={}){super(e,t);const r=null!=t.status?t.status:200,n=new at(t.headers);if(null!==e&&!n.has("Content-Type")){const t=et(e,this);t&&n.append("Content-Type",t)}this[dt]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:n,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[dt].type}get url(){return this[dt].url||""}get status(){return this[dt].status}get ok(){return this[dt].status>=200&&this[dt].status<300}get redirected(){return this[dt].counter>0}get statusText(){return this[dt].statusText}get headers(){return this[dt].headers}get highWaterMark(){return this[dt].highWaterMark}clone(){return new e(Qe(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,r=302){if(!ut(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new e(null,{headers:{location:new URL(t).toString()},status:r})}static error(){const t=new e(null,{status:0,statusText:""});return t[dt].type="error",t}static json(t=void 0,r={}){const n=JSON.stringify(t);if(void 0===n)throw new TypeError("data is not JSON serializable");const s=new at(r&&r.headers);return s.has("content-type")||s.set("content-type","application/json"),new e(n,{...r,headers:s})}get[Symbol.toStringTag](){return"Response"}},Object.defineProperties(ht.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})}}),bt=S({"node_modules/node-fetch/src/utils/get-search.js"(){ft=e=>{if(e.search)return e.search;const t=e.href.length-1,r=e.hash||("#"===e.href[t]?"#":"");return"?"===e.href[t-r.length]?"?":""}}});function Et(e,t=!1){return null==e?"no-referrer":(e=new URL(e),/^(about|blob|data):$/.test(e.protocol)?"no-referrer":(e.username="",e.password="",e.hash="",t&&(e.pathname="",e.search=""),e))}function wt(e){return!!/^about:(blank|srcdoc)$/.test(e)||("data:"===e.protocol||(!!/^(blob|filesystem):$/.test(e.protocol)||function(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;const t=e.host.replace(/(^\[)|(]$)/g,""),r=i.isIP(t);return!(4!==r||!/^127\./.test(t))||!(6!==r||!/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t))||"localhost"!==e.host&&!e.host.endsWith(".localhost")&&"file:"===e.protocol}(e)))}var Tt,vt,St,At,Ot,It,Ct,Rt=S({"node_modules/node-fetch/src/utils/referrer.js"(){pt=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),mt="strict-origin-when-cross-origin"}}),kt=S({"node_modules/node-fetch/src/request.js"(){yt(),ct(),$e(),bt(),Rt(),Tt=Symbol("Request internals"),vt=e=>"object"==typeof e&&"object"==typeof e[Tt],St=n.deprecate((()=>{}),".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),At=class e extends Xe{constructor(e,t={}){let r;if(vt(e)?r=new URL(e.url):(r=new URL(e),e={}),""!==r.username||""!==r.password)throw new TypeError(`${r} is an url with embedded credentials.`);let n=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n)&&(n=n.toUpperCase()),!vt(t)&&"data"in t&&St(),(null!=t.body||vt(e)&&null!==e.body)&&("GET"===n||"HEAD"===n))throw new TypeError("Request with GET/HEAD method cannot have body");const s=t.body?t.body:vt(e)&&null!==e.body?Qe(e):null;super(s,{size:t.size||e.size||0});const o=new at(t.headers||e.headers||{});if(null!==s&&!o.has("Content-Type")){const e=et(s,this);e&&o.set("Content-Type",e)}let i=vt(e)?e.signal:null;if("signal"in t&&(i=t.signal),null!=i&&!Te(i))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let a=null==t.referrer?e.referrer:t.referrer;if(""===a)a="no-referrer";else if(a){const e=new URL(a);a=/^about:(\/\/)?client$/.test(e)?"client":e}else a=void 0;this[Tt]={method:n,redirect:t.redirect||e.redirect||"follow",headers:o,parsedURL:r,signal:i,referrer:a},this.follow=void 0===t.follow?void 0===e.follow?20:e.follow:t.follow,this.compress=void 0===t.compress?void 0===e.compress||e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[Tt].method}get url(){return a.format(this[Tt].parsedURL)}get headers(){return this[Tt].headers}get redirect(){return this[Tt].redirect}get signal(){return this[Tt].signal}get referrer(){return"no-referrer"===this[Tt].referrer?"":"client"===this[Tt].referrer?"about:client":this[Tt].referrer?this[Tt].referrer.toString():void 0}get referrerPolicy(){return this[Tt].referrerPolicy}set referrerPolicy(e){this[Tt].referrerPolicy=function(e){if(!pt.has(e))throw new TypeError(`Invalid referrerPolicy: ${e}`);return e}(e)}clone(){return new e(this)}get[Symbol.toStringTag](){return"Request"}},Object.defineProperties(At.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}}),Ot=e=>{const{parsedURL:t}=e[Tt],r=new at(e[Tt].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(null===e.body&&/^(post|put)$/i.test(e.method)&&(n="0"),null!==e.body){const t=tt(e);"number"!=typeof t||Number.isNaN(t)||(n=String(t))}n&&r.set("Content-Length",n),""===e.referrerPolicy&&(e.referrerPolicy=mt),e.referrer&&"no-referrer"!==e.referrer?e[Tt].referrer=function(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if("no-referrer"===e.referrer||""===e.referrerPolicy)return null;const n=e.referrerPolicy;if("about:client"===e.referrer)return"no-referrer";const s=e.referrer;let o=Et(s),i=Et(s,!0);o.toString().length>4096&&(o=i),t&&(o=t(o)),r&&(i=r(i));const a=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return i;case"unsafe-url":return o;case"strict-origin":return wt(o)&&!wt(a)?"no-referrer":i.toString();case"strict-origin-when-cross-origin":return o.origin===a.origin?o:wt(o)&&!wt(a)?"no-referrer":i;case"same-origin":return o.origin===a.origin?o:"no-referrer";case"origin-when-cross-origin":return o.origin===a.origin?o:i;case"no-referrer-when-downgrade":return wt(o)&&!wt(a)?"no-referrer":o;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}(e):e[Tt].referrer="no-referrer",e[Tt].referrer instanceof URL&&r.set("Referer",e.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:s}=e;"function"==typeof s&&(s=s(t));const o=ft(t);return{parsedURL:t,options:{path:t.pathname+o,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:s}}}}}),Nt=S({"node_modules/node-fetch/src/errors/abort-error.js"(){He(),It=class extends _e{constructor(e,t="aborted"){super(e,t)}}}}),Pt={};async function xt(e,t){return new Promise(((n,o)=>{const i=new At(e,t),{parsedURL:a,options:c}=Ot(i);if(!Ct.has(a.protocol))throw new TypeError(`node-fetch cannot load ${e}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if("data:"===a.protocol){const e=h(i.url),t=new ht(e,{headers:{"Content-Type":e.typeFull}});return void n(t)}const l=("https:"===a.protocol?m.default:p.default).request,{signal:u}=i;let d=null;const _=()=>{const e=new It("The operation was aborted.");o(e),i.body&&i.body instanceof f.default.Readable&&i.body.destroy(e),d&&d.body&&d.body.emit("error",e)};if(u&&u.aborted)return void _();const g=()=>{_(),E()},b=l(a.toString(),c);u&&u.addEventListener("abort",g);const E=()=>{b.abort(),u&&u.removeEventListener("abort",g)};b.on("error",(e=>{o(new ge(`request to ${i.url} failed, reason: ${e.message}`,"system",e)),E()})),function(e,t){const r=s.Buffer.from("0\r\n\r\n");let n,o=!1,i=!1;e.on("response",(e=>{const{headers:t}=e;o="chunked"===t["transfer-encoding"]&&!t["content-length"]})),e.on("socket",(a=>{const c=()=>{if(o&&!i){const e=new Error("Premature close");e.code="ERR_STREAM_PREMATURE_CLOSE",t(e)}},l=e=>{i=0===s.Buffer.compare(e.slice(-5),r),!i&&n&&(i=0===s.Buffer.compare(n.slice(-3),r.slice(0,3))&&0===s.Buffer.compare(e.slice(-2),r.slice(3))),n=e};a.prependListener("close",c),a.on("data",l),e.on("close",(()=>{a.removeListener("close",c),a.removeListener("data",l)}))}))}(b,(e=>{d&&d.body&&d.body.destroy(e)})),process.version<"v14"&&b.on("socket",(e=>{let t;e.prependListener("end",(()=>{t=e._eventsCount})),e.prependListener("close",(r=>{if(d&&t<e._eventsCount&&!r){const e=new Error("Premature close");e.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",e)}}))})),b.on("response",(e=>{b.setTimeout(0);const s=function(e=[]){return new at(e.reduce(((e,t,r,n)=>(r%2==0&&e.push(n.slice(r,r+2)),e)),[]).filter((([e,t])=>{try{return ot(e),it(e,String(t)),!0}catch{return!1}})))}(e.rawHeaders);if(ut(e.statusCode)){const r=s.get("Location");let a=null;try{a=null===r?null:new URL(r,i.url)}catch{if("manual"!==i.redirect)return o(new ge(`uri requested responds with an invalid redirect URL: ${r}`,"invalid-redirect")),void E()}switch(i.redirect){case"error":return o(new ge(`uri requested responds with a redirect, redirect mode is set to error: ${i.url}`,"no-redirect")),void E();case"manual":break;case"follow":{if(null===a)break;if(i.counter>=i.follow)return o(new ge(`maximum redirect reached at: ${i.url}`,"max-redirect")),void E();const r={headers:new at(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:Qe(i),signal:i.signal,size:i.size,referrer:i.referrer,referrerPolicy:i.referrerPolicy};if(!ve(i.url,a)||!Se(i.url,a))for(const e of["authorization","www-authenticate","cookie","cookie2"])r.headers.delete(e);if(303!==e.statusCode&&i.body&&t.body instanceof f.default.Readable)return o(new ge("Cannot follow redirect with body being a readable stream","unsupported-redirect")),void E();303!==e.statusCode&&(301!==e.statusCode&&302!==e.statusCode||"POST"!==i.method)||(r.method="GET",r.body=void 0,r.headers.delete("content-length"));const c=function(e){const t=(e.get("referrer-policy")||"").split(/[,\s]+/);let r="";for(const e of t)e&&pt.has(e)&&(r=e);return r}(s);return c&&(r.referrerPolicy=c),n(xt(new At(a,r))),void E()}default:return o(new TypeError(`Redirect option '${i.redirect}' is not a valid value of RequestRedirect`))}}u&&e.once("end",(()=>{u.removeEventListener("abort",g)}));let a=r.pipeline(e,new r.PassThrough,(e=>{e&&o(e)}));process.version<"v12.10"&&e.on("aborted",g);const c={url:i.url,status:e.statusCode,statusText:e.statusMessage,headers:s,size:i.size,counter:i.counter,highWaterMark:i.highWaterMark},l=s.get("Content-Encoding");if(!i.compress||"HEAD"===i.method||null===l||204===e.statusCode||304===e.statusCode)return d=new ht(a,c),void n(d);const h={flush:y.default.Z_SYNC_FLUSH,finishFlush:y.default.Z_SYNC_FLUSH};if("gzip"===l||"x-gzip"===l)return a=r.pipeline(a,y.default.createGunzip(h),(e=>{e&&o(e)})),d=new ht(a,c),void n(d);if("deflate"===l||"x-deflate"===l){const t=r.pipeline(e,new r.PassThrough,(e=>{e&&o(e)}));return t.once("data",(e=>{a=8==(15&e[0])?r.pipeline(a,y.default.createInflate(),(e=>{e&&o(e)})):r.pipeline(a,y.default.createInflateRaw(),(e=>{e&&o(e)})),d=new ht(a,c),n(d)})),void t.once("end",(()=>{d||(d=new ht(a,c),n(d))}))}if("br"===l)return a=r.pipeline(a,y.default.createBrotliDecompress(),(e=>{e&&o(e)})),d=new ht(a,c),void n(d);d=new ht(a,c),n(d)})),rt(b,i).catch(o)}))}O(Pt,{AbortError:()=>It,Blob:()=>Z,FetchError:()=>ge,File:()=>oe,FormData:()=>pe,Headers:()=>at,Request:()=>At,Response:()=>ht,blobFrom:()=>Ce,blobFromSync:()=>Ie,default:()=>xt,fileFrom:()=>Re,fileFromSync:()=>ke,isRedirect:()=>ut});var Dt=S({"node_modules/node-fetch/src/index.js"(){ee(),ct(),gt(),yt(),kt(),qe(),Nt(),_t(),Ge(),$e(),Rt(),Ve(),Ct=new Set(["data:","http:","https:"])}}),Ut=A({"node_modules/gaxios/build/cjs/src/gaxios.js"(e){var t,r=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.Gaxios=void 0;var n=r(x()),s=v("https"),o=L(),i=j(),a=v("stream"),c=M(),l=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new c.GaxiosInterceptorManager,response:new c.GaxiosInterceptorManager}}fetch(...e){const r=e[0],n=e[1];let s;const o=new Headers;return"string"==typeof r?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&"object"==typeof r&&"headers"in r&&t.mergeHeaders(o,r.headers),n&&t.mergeHeaders(o,new Headers(n.headers)),"object"!=typeof r||r instanceof URL?this.request({...n,headers:o,url:s}):this.request({...n,...r,headers:o,url:s})}async request(e={}){let t=await this.#l(e);return t=await this.#u(t),this.#d(this._request(t))}async _defaultAdapter(e){const r=e.fetchImplementation||this.defaults.fetchImplementation||await t.#h(),n={...e};delete n.data;const s=await r(e.url,n),o=await this.getResponseData(e,s);return Object.getOwnPropertyDescriptor(s,"data")?.configurable||Object.defineProperties(s,{data:{configurable:!0,writable:!0,enumerable:!0,value:o}}),Object.assign(s,{config:e,data:o})}async _request(e){try{let t;if(t=e.adapter?await e.adapter(e,this._defaultAdapter.bind(this)):await this._defaultAdapter(e),!e.validateStatus(t.status)){if("stream"===e.responseType){const e=[];for await(const r of t.data)e.push(r);t.data=e.toString()}const r=o.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new o.GaxiosError(r?.message,e,t,r)}return t}catch(t){let r;r=t instanceof o.GaxiosError?t:t instanceof Error?new o.GaxiosError(t.message,e,void 0,t):new o.GaxiosError("Unexpected Gaxios Error",e,void 0,t);const{shouldRetry:n,config:s}=await(0,i.getRetryConfig)(r);if(n&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#f(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,t){if(204===t.status)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new o.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{const e=await t.text();try{return JSON.parse(e)}catch{return e}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#p(e,t=[]){const r=new URL(e),n=[...t],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(const e of s)n.push(e.trim());for(const e of n)if(e instanceof RegExp){if(e.test(r.toString()))return!1}else if(e instanceof URL){if(e.origin===r.origin)return!1}else if(e.startsWith("*.")||e.startsWith(".")){const t=e.replace(/^\*\./,".");if(r.hostname.endsWith(t))return!1}else if(e===r.origin||e===r.hostname||e===r.href)return!1;return!0}async#u(e){let t=Promise.resolve(e);for(const e of this.interceptors.request.values())e&&(t=t.then(e.resolved,e.rejected));return t}async#d(e){let t=Promise.resolve(e);for(const e of this.interceptors.response.values())e&&(t=t.then(e.resolved,e.rejected));return t}async#l(e){const r=new Headers(this.defaults.headers);t.mergeHeaders(r,e.headers);const i=(0,n.default)(!0,{},this.defaults,e);if(!i.url)throw new Error("URL is required.");if(i.baseURL&&(i.url=new URL(i.url,i.baseURL)),i.url=new URL(i.url),i.params)if(i.paramsSerializer){let e=i.paramsSerializer(i.params);e.startsWith("?")&&(e=e.slice(1));const t=i.url.toString().includes("?")?"&":"?";i.url=i.url+t+e}else{const e=i.url instanceof URL?i.url:new URL(i.url);for(const[t,r]of new URLSearchParams(i.params))e.searchParams.append(t,r);i.url=e}"number"==typeof e.maxContentLength&&(i.size=e.maxContentLength),"number"==typeof e.maxRedirects&&(i.follow=e.maxRedirects);const c="string"==typeof i.data||i.data instanceof ArrayBuffer||i.data instanceof Blob||globalThis.File&&i.data instanceof File||i.data instanceof FormData||i.data instanceof a.Readable||i.data instanceof ReadableStream||i.data instanceof String||i.data instanceof URLSearchParams||ArrayBuffer.isView(i.data)||["Blob","File","FormData"].includes(i.data?.constructor?.name||"");if(i.multipart?.length){const e=await(async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID())();r.set("content-type",`multipart/related; boundary=${e}`),i.body=a.Readable.from(this.getMultipartRequest(i.multipart,e))}else c?i.body=i.data:"object"==typeof i.data?"application/x-www-form-urlencoded"===r.get("Content-Type")?i.body=i.paramsSerializer?i.paramsSerializer(i.data):new URLSearchParams(i.data):(r.has("content-type")||r.set("content-type","application/json"),i.body=JSON.stringify(i.data)):i.data&&(i.body=i.data);i.validateStatus=i.validateStatus||this.validateStatus,i.responseType=i.responseType||"unknown",r.has("accept")||"json"!==i.responseType||r.set("accept","application/json");const l=i.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(i.agent);else if(l&&this.#p(i.url,i.noProxy)){const e=await t.#m();this.agentCache.has(l)?i.agent=this.agentCache.get(l):(i.agent=new e(l,{cert:i.cert,key:i.key}),this.agentCache.set(l,i.agent))}else i.cert&&i.key&&(this.agentCache.has(i.key)?i.agent=this.agentCache.get(i.key):(i.agent=new s.Agent({cert:i.cert,key:i.key}),this.agentCache.set(i.key,i.agent)));return"function"!=typeof i.errorRedactor&&!1!==i.errorRedactor&&(i.errorRedactor=o.defaultErrorRedactor),i.body&&!("duplex"in i)&&(i.duplex="half"),this.#f(i),Object.assign(i,{headers:r,url:i.url instanceof URL?i.url:new URL(i.url)})}#f(e){if(e.timeout){const t=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,t]):e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(null===t)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let t=await e.text();try{t=JSON.parse(t)}catch{}return t}return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){const r=`--${t}--`;for(const r of e){const e=`--${t}\r\nContent-Type: ${r.headers.get("Content-Type")||"application/octet-stream"}\r\n\r\n`;yield e,"string"==typeof r.content?yield r.content:yield*r.content,yield"\r\n"}yield r}static#y;static#_;static async#m(){return this.#y||=(await Promise.resolve().then((()=>I(K())))).HttpsProxyAgent,this.#y}static async#h(){const e="undefined"!=typeof window&&!!window;return this.#_||=e?window.fetch:(await Promise.resolve().then((()=>(Dt(),Pt)))).default,this.#_}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(const r of t){(r instanceof Headers?r:new Headers(r)).forEach(((t,r)=>{"set-cookie"===r?e.append(r,t):e.set(r,t)}))}return e}};e.Gaxios=l,t=l}}),Lt=A({"node_modules/gaxios/build/cjs/src/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.instance=e.Gaxios=e.GaxiosError=void 0,e.request=async function(t){return e.instance.request(t)};var n=Ut();Object.defineProperty(e,"Gaxios",{enumerable:!0,get:function(){return n.Gaxios}});var s=L();Object.defineProperty(e,"GaxiosError",{enumerable:!0,get:function(){return s.GaxiosError}}),r(M(),e),e.instance=new n.Gaxios}}),jt=A({"node_modules/bignumber.js/bignumber.js"(e,t){!function(e){var r,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,s=Math.ceil,o=Math.floor,i="[BigNumber Error] ",a=i+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,u=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,f=1e9;function p(e){var t=0|e;return e>0||e===t?t:t-1}function m(e){for(var t,r,n=1,s=e.length,o=e[0]+"";n<s;){for(t=e[n++]+"",r=l-t.length;r--;t="0"+t);o+=t}for(s=o.length;48===o.charCodeAt(--s););return o.slice(0,s+1||1)}function y(e,t){var r,n,s=e.c,o=t.c,i=e.s,a=t.s,c=e.e,l=t.e;if(!i||!a)return null;if(r=s&&!s[0],n=o&&!o[0],r||n)return r?n?0:-a:i;if(i!=a)return i;if(r=i<0,n=c==l,!s||!o)return n?0:!s^r?1:-1;if(!n)return c>l^r?1:-1;for(a=(c=s.length)<(l=o.length)?c:l,i=0;i<a;i++)if(s[i]!=o[i])return s[i]>o[i]^r?1:-1;return c==l?0:c>l^r?1:-1}function _(e,t,r,n){if(e<t||e>r||e!==o(e))throw Error(i+(n||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function g(e){var t=e.c.length-1;return p(e.e/l)==t&&e.c[t]%2!=0}function b(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function E(e,t,r){var n,s;if(t<0){for(s=r+".";++t;s+=r);e=s+e}else if(++t>(n=e.length)){for(s=r,t-=n;--t;s+=r);e+=s}else t<n&&(e=e.slice(0,t)+"."+e.slice(t));return e}r=function e(t){var r,w,T,v,S,A=F.prototype={constructor:F,toString:null,valueOf:null},O=new F(1),I=20,C=4,R=-7,k=21,N=-1e7,P=1e7,x=!1,D=1,U=0,L={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},j="0123456789abcdefghijklmnopqrstuvwxyz",M=!0;function F(e,t){var r,s,i,c,d,h,f,p,m=this;if(!(m instanceof F))return new F(e,t);if(null==t){if(e&&!0===e._isBigNumber)return m.s=e.s,void(!e.c||e.e>P?m.c=m.e=null:e.e<N?m.c=[m.e=0]:(m.e=e.e,m.c=e.c.slice()));if((h="number"==typeof e)&&0*e==0){if(m.s=1/e<0?(e=-e,-1):1,e===~~e){for(c=0,d=e;d>=10;d/=10,c++);return void(c>P?m.c=m.e=null:(m.e=c,m.c=[e]))}p=String(e)}else{if(!n.test(p=String(e)))return T(m,p,h);m.s=45==p.charCodeAt(0)?(p=p.slice(1),-1):1}(c=p.indexOf("."))>-1&&(p=p.replace(".","")),(d=p.search(/e/i))>0?(c<0&&(c=d),c+=+p.slice(d+1),p=p.substring(0,d)):c<0&&(c=p.length)}else{if(_(t,2,j.length,"Base"),10==t&&M)return q(m=new F(e),I+m.e+1,C);if(p=String(e),h="number"==typeof e){if(0*e!=0)return T(m,p,h,t);if(m.s=1/e<0?(p=p.slice(1),-1):1,F.DEBUG&&p.replace(/^0\.0*|\./,"").length>15)throw Error(a+e)}else m.s=45===p.charCodeAt(0)?(p=p.slice(1),-1):1;for(r=j.slice(0,t),c=d=0,f=p.length;d<f;d++)if(r.indexOf(s=p.charAt(d))<0){if("."==s){if(d>c){c=f;continue}}else if(!i&&(p==p.toUpperCase()&&(p=p.toLowerCase())||p==p.toLowerCase()&&(p=p.toUpperCase()))){i=!0,d=-1,c=0;continue}return T(m,String(e),h,t)}h=!1,(c=(p=w(p,t,10,m.s)).indexOf("."))>-1?p=p.replace(".",""):c=p.length}for(d=0;48===p.charCodeAt(d);d++);for(f=p.length;48===p.charCodeAt(--f););if(p=p.slice(d,++f)){if(f-=d,h&&F.DEBUG&&f>15&&(e>u||e!==o(e)))throw Error(a+m.s*e);if((c=c-d-1)>P)m.c=m.e=null;else if(c<N)m.c=[m.e=0];else{if(m.e=c,m.c=[],d=(c+1)%l,c<0&&(d+=l),d<f){for(d&&m.c.push(+p.slice(0,d)),f-=l;d<f;)m.c.push(+p.slice(d,d+=l));d=l-(p=p.slice(d)).length}else d-=f;for(;d--;p+="0");m.c.push(+p)}}else m.c=[m.e=0]}function B(e,t,r,n){var s,o,i,a,c;if(null==r?r=C:_(r,0,8),!e.c)return e.toString();if(s=e.c[0],i=e.e,null==t)c=m(e.c),c=1==n||2==n&&(i<=R||i>=k)?b(c,i):E(c,i,"0");else if(o=(e=q(new F(e),t,r)).e,a=(c=m(e.c)).length,1==n||2==n&&(t<=o||o<=R)){for(;a<t;c+="0",a++);c=b(c,o)}else if(t-=i+(2===n&&o>i),c=E(c,o,"0"),o+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=o-a)>0)for(o+1==a&&(c+=".");t--;c+="0");return e.s<0&&s?"-"+c:c}function G(e,t){for(var r,n,s=1,o=new F(e[0]);s<e.length;s++)(!(n=new F(e[s])).s||(r=y(o,n))===t||0===r&&o.s===t)&&(o=n);return o}function H(e,t,r){for(var n=1,s=t.length;!t[--s];t.pop());for(s=t[0];s>=10;s/=10,n++);return(r=n+r*l-1)>P?e.c=e.e=null:r<N?e.c=[e.e=0]:(e.e=r,e.c=t),e}function q(e,t,r,n){var i,a,u,h,f,p,m,y=e.c,_=d;if(y){e:{for(i=1,h=y[0];h>=10;h/=10,i++);if((a=t-i)<0)a+=l,u=t,f=y[p=0],m=o(f/_[i-u-1]%10);else if((p=s((a+1)/l))>=y.length){if(!n)break e;for(;y.length<=p;y.push(0));f=m=0,i=1,u=(a%=l)-l+1}else{for(f=h=y[p],i=1;h>=10;h/=10,i++);m=(u=(a%=l)-l+i)<0?0:o(f/_[i-u-1]%10)}if(n=n||t<0||null!=y[p+1]||(u<0?f:f%_[i-u-1]),n=r<4?(m||n)&&(0==r||r==(e.s<0?3:2)):m>5||5==m&&(4==r||n||6==r&&(a>0?u>0?f/_[i-u]:0:y[p-1])%10&1||r==(e.s<0?8:7)),t<1||!y[0])return y.length=0,n?(t-=e.e+1,y[0]=_[(l-t%l)%l],e.e=-t||0):y[0]=e.e=0,e;if(0==a?(y.length=p,h=1,p--):(y.length=p+1,h=_[l-a],y[p]=u>0?o(f/_[i-u]%_[u])*h:0),n)for(;;){if(0==p){for(a=1,u=y[0];u>=10;u/=10,a++);for(u=y[0]+=h,h=1;u>=10;u/=10,h++);a!=h&&(e.e++,y[0]==c&&(y[0]=1));break}if(y[p]+=h,y[p]!=c)break;y[p--]=0,h=1}for(a=y.length;0===y[--a];y.pop());}e.e>P?e.c=e.e=null:e.e<N&&(e.c=[e.e=0])}return e}function $(e){var t,r=e.e;return null===r?e.toString():(t=m(e.c),t=r<=R||r>=k?b(t,r):E(t,r,"0"),e.s<0?"-"+t:t)}return F.clone=e,F.ROUND_UP=0,F.ROUND_DOWN=1,F.ROUND_CEIL=2,F.ROUND_FLOOR=3,F.ROUND_HALF_UP=4,F.ROUND_HALF_DOWN=5,F.ROUND_HALF_EVEN=6,F.ROUND_HALF_CEIL=7,F.ROUND_HALF_FLOOR=8,F.EUCLID=9,F.config=F.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(i+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(_(r=e[t],0,f,t),I=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(_(r=e[t],0,8,t),C=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(_(r[0],-f,0,t),_(r[1],0,f,t),R=r[0],k=r[1]):(_(r,-f,f,t),R=-(k=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)_(r[0],-f,-1,t),_(r[1],1,f,t),N=r[0],P=r[1];else{if(_(r,-f,f,t),!r)throw Error(i+t+" cannot be zero: "+r);N=-(P=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(i+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw x=!r,Error(i+"crypto unavailable");x=r}else x=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(_(r=e[t],0,9,t),D=r),e.hasOwnProperty(t="POW_PRECISION")&&(_(r=e[t],0,f,t),U=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(i+t+" not an object: "+r);L=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(i+t+" invalid: "+r);M="0123456789"==r.slice(0,10),j=r}}return{DECIMAL_PLACES:I,ROUNDING_MODE:C,EXPONENTIAL_AT:[R,k],RANGE:[N,P],CRYPTO:x,MODULO_MODE:D,POW_PRECISION:U,FORMAT:L,ALPHABET:j}},F.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!F.DEBUG)return!0;var t,r,n=e.c,s=e.e,a=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===a||-1===a)&&s>=-f&&s<=f&&s===o(s)){if(0===n[0]){if(0===s&&1===n.length)return!0;break e}if((t=(s+1)%l)<1&&(t+=l),String(n[0]).length==t){for(t=0;t<n.length;t++)if((r=n[t])<0||r>=c||r!==o(r))break e;if(0!==r)return!0}}}else if(null===n&&null===s&&(null===a||1===a||-1===a))return!0;throw Error(i+"Invalid BigNumber: "+e)},F.maximum=F.max=function(){return G(arguments,-1)},F.minimum=F.min=function(){return G(arguments,1)},F.random=(v=9007199254740992,S=Math.random()*v&2097151?function(){return o(Math.random()*v)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,a,c,u=0,h=[],p=new F(O);if(null==e?e=I:_(e,0,f),a=s(e/l),x)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(a*=2));u<a;)(c=131072*t[u]+(t[u+1]>>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[u]=r[0],t[u+1]=r[1]):(h.push(c%1e14),u+=2);u=a/2}else{if(!crypto.randomBytes)throw x=!1,Error(i+"crypto unavailable");for(t=crypto.randomBytes(a*=7);u<a;)(c=281474976710656*(31&t[u])+1099511627776*t[u+1]+4294967296*t[u+2]+16777216*t[u+3]+(t[u+4]<<16)+(t[u+5]<<8)+t[u+6])>=9e15?crypto.randomBytes(7).copy(t,u):(h.push(c%1e14),u+=7);u=a/7}if(!x)for(;u<a;)(c=S())<9e15&&(h[u++]=c%1e14);for(a=h[--u],e%=l,a&&e&&(c=d[l-e],h[u]=o(a/c)*c);0===h[u];h.pop(),u--);if(u<0)h=[n=0];else{for(n=-1;0===h[0];h.splice(0,1),n-=l);for(u=1,c=h[0];c>=10;c/=10,u++);u<l&&(n-=l-u)}return p.e=n,p.c=h,p}),F.sum=function(){for(var e=1,t=arguments,r=new F(t[0]);e<t.length;)r=r.plus(t[e++]);return r},w=function(){var e="0123456789";function t(e,t,r,n){for(var s,o,i=[0],a=0,c=e.length;a<c;){for(o=i.length;o--;i[o]*=t);for(i[0]+=n.indexOf(e.charAt(a++)),s=0;s<i.length;s++)i[s]>r-1&&(null==i[s+1]&&(i[s+1]=0),i[s+1]+=i[s]/r|0,i[s]%=r)}return i.reverse()}return function(n,s,o,i,a){var c,l,u,d,h,f,p,y,_=n.indexOf("."),g=I,b=C;for(_>=0&&(d=U,U=0,n=n.replace(".",""),f=(y=new F(s)).pow(n.length-_),U=d,y.c=t(E(m(f.c),f.e,"0"),10,o,e),y.e=y.c.length),u=d=(p=t(n,s,o,a?(c=j,e):(c=e,j))).length;0==p[--d];p.pop());if(!p[0])return c.charAt(0);if(_<0?--u:(f.c=p,f.e=u,f.s=i,p=(f=r(f,y,g,b,o)).c,h=f.r,u=f.e),_=p[l=u+g+1],d=o/2,h=h||l<0||null!=p[l+1],h=b<4?(null!=_||h)&&(0==b||b==(f.s<0?3:2)):_>d||_==d&&(4==b||h||6==b&&1&p[l-1]||b==(f.s<0?8:7)),l<1||!p[0])n=h?E(c.charAt(1),-g,c.charAt(0)):c.charAt(0);else{if(p.length=l,h)for(--o;++p[--l]>o;)p[l]=0,l||(++u,p=[1].concat(p));for(d=p.length;!p[--d];);for(_=0,n="";_<=d;n+=c.charAt(p[_++]));n=E(n,u,c.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,s,o,i,a=0,c=e.length,l=t%h,u=t/h|0;for(e=e.slice();c--;)a=((s=l*(o=e[c]%h)+(n=u*o+(i=e[c]/h|0)*l)%h*h+a)/r|0)+(n/h|0)+u*i,e[c]=s%r;return a&&(e=[a].concat(e)),e}function t(e,t,r,n){var s,o;if(r!=n)o=r>n?1:-1;else for(s=o=0;s<r;s++)if(e[s]!=t[s]){o=e[s]>t[s]?1:-1;break}return o}function r(e,t,r,n){for(var s=0;r--;)e[r]-=s,s=e[r]<t[r]?1:0,e[r]=s*n+e[r]-t[r];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(n,s,i,a,u){var d,h,f,m,y,_,g,b,E,w,T,v,S,A,O,I,C,R=n.s==s.s?1:-1,k=n.c,N=s.c;if(!(k&&k[0]&&N&&N[0]))return new F(n.s&&s.s&&(k?!N||k[0]!=N[0]:N)?k&&0==k[0]||!N?0*R:R/0:NaN);for(E=(b=new F(R)).c=[],R=i+(h=n.e-s.e)+1,u||(u=c,h=p(n.e/l)-p(s.e/l),R=R/l|0),f=0;N[f]==(k[f]||0);f++);if(N[f]>(k[f]||0)&&h--,R<0)E.push(1),m=!0;else{for(A=k.length,I=N.length,f=0,R+=2,(y=o(u/(N[0]+1)))>1&&(N=e(N,y,u),k=e(k,y,u),I=N.length,A=k.length),S=I,T=(w=k.slice(0,I)).length;T<I;w[T++]=0);C=N.slice(),C=[0].concat(C),O=N[0],N[1]>=u/2&&O++;do{if(y=0,(d=t(N,w,I,T))<0){if(v=w[0],I!=T&&(v=v*u+(w[1]||0)),(y=o(v/O))>1)for(y>=u&&(y=u-1),g=(_=e(N,y,u)).length,T=w.length;1==t(_,w,g,T);)y--,r(_,I<g?C:N,g,u),g=_.length,d=1;else 0==y&&(d=y=1),g=(_=N.slice()).length;if(g<T&&(_=[0].concat(_)),r(w,_,T,u),T=w.length,-1==d)for(;t(N,w,I,T)<1;)y++,r(w,I<T?C:N,T,u),T=w.length}else 0===d&&(y++,w=[0]);E[f++]=y,w[0]?w[T++]=k[S]||0:(w=[k[S]],T=1)}while((S++<A||null!=w[0])&&R--);m=null!=w[0],E[0]||E.splice(0,1)}if(u==c){for(f=1,R=E[0];R>=10;R/=10,f++);q(b,i+(b.e=f+h*l-1)+1,a,m)}else b.e=h,b.r=+m;return b}}(),T=function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,t=/^([^.]+)\.$/,r=/^\.([^.]+)$/,n=/^-?(Infinity|NaN)$/,s=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,a,c,l){var u,d=c?a:a.replace(s,"");if(n.test(d))o.s=isNaN(d)?null:d<0?-1:1;else{if(!c&&(d=d.replace(e,(function(e,t,r){return u="x"==(r=r.toLowerCase())?16:"b"==r?2:8,l&&l!=u?e:t})),l&&(u=l,d=d.replace(t,"$1").replace(r,"0.$1")),a!=d))return new F(d,u);if(F.DEBUG)throw Error(i+"Not a"+(l?" base "+l:"")+" number: "+a);o.s=null}o.c=o.e=null}}(),A.absoluteValue=A.abs=function(){var e=new F(this);return e.s<0&&(e.s=1),e},A.comparedTo=function(e,t){return y(this,new F(e,t))},A.decimalPlaces=A.dp=function(e,t){var r,n,s,o=this;if(null!=e)return _(e,0,f),null==t?t=C:_(t,0,8),q(new F(o),e+o.e+1,t);if(!(r=o.c))return null;if(n=((s=r.length-1)-p(this.e/l))*l,s=r[s])for(;s%10==0;s/=10,n--);return n<0&&(n=0),n},A.dividedBy=A.div=function(e,t){return r(this,new F(e,t),I,C)},A.dividedToIntegerBy=A.idiv=function(e,t){return r(this,new F(e,t),0,1)},A.exponentiatedBy=A.pow=function(e,t){var r,n,a,c,u,d,h,f,p=this;if((e=new F(e)).c&&!e.isInteger())throw Error(i+"Exponent not an integer: "+$(e));if(null!=t&&(t=new F(t)),u=e.e>14,!p.c||!p.c[0]||1==p.c[0]&&!p.e&&1==p.c.length||!e.c||!e.c[0])return f=new F(Math.pow(+$(p),u?e.s*(2-g(e)):+$(e))),t?f.mod(t):f;if(d=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new F(NaN);(n=!d&&p.isInteger()&&t.isInteger())&&(p=p.mod(t))}else{if(e.e>9&&(p.e>0||p.e<-1||(0==p.e?p.c[0]>1||u&&p.c[1]>=24e7:p.c[0]<8e13||u&&p.c[0]<=9999975e7)))return c=p.s<0&&g(e)?-0:0,p.e>-1&&(c=1/c),new F(d?1/c:c);U&&(c=s(U/l+2))}for(u?(r=new F(.5),d&&(e.s=1),h=g(e)):h=(a=Math.abs(+$(e)))%2,f=new F(O);;){if(h){if(!(f=f.times(p)).c)break;c?f.c.length>c&&(f.c.length=c):n&&(f=f.mod(t))}if(a){if(0===(a=o(a/2)))break;h=a%2}else if(q(e=e.times(r),e.e+1,1),e.e>14)h=g(e);else{if(0===(a=+$(e)))break;h=a%2}p=p.times(p),c?p.c&&p.c.length>c&&(p.c.length=c):n&&(p=p.mod(t))}return n?f:(d&&(f=O.div(f)),t?f.mod(t):c?q(f,U,C,undefined):f)},A.integerValue=function(e){var t=new F(this);return null==e?e=C:_(e,0,8),q(t,t.e+1,e)},A.isEqualTo=A.eq=function(e,t){return 0===y(this,new F(e,t))},A.isFinite=function(){return!!this.c},A.isGreaterThan=A.gt=function(e,t){return y(this,new F(e,t))>0},A.isGreaterThanOrEqualTo=A.gte=function(e,t){return 1===(t=y(this,new F(e,t)))||0===t},A.isInteger=function(){return!!this.c&&p(this.e/l)>this.c.length-2},A.isLessThan=A.lt=function(e,t){return y(this,new F(e,t))<0},A.isLessThanOrEqualTo=A.lte=function(e,t){return-1===(t=y(this,new F(e,t)))||0===t},A.isNaN=function(){return!this.s},A.isNegative=function(){return this.s<0},A.isPositive=function(){return this.s>0},A.isZero=function(){return!!this.c&&0==this.c[0]},A.minus=function(e,t){var r,n,s,o,i=this,a=i.s;if(t=(e=new F(e,t)).s,!a||!t)return new F(NaN);if(a!=t)return e.s=-t,i.plus(e);var u=i.e/l,d=e.e/l,h=i.c,f=e.c;if(!u||!d){if(!h||!f)return h?(e.s=-t,e):new F(f?i:NaN);if(!h[0]||!f[0])return f[0]?(e.s=-t,e):new F(h[0]?i:3==C?-0:0)}if(u=p(u),d=p(d),h=h.slice(),a=u-d){for((o=a<0)?(a=-a,s=h):(d=u,s=f),s.reverse(),t=a;t--;s.push(0));s.reverse()}else for(n=(o=(a=h.length)<(t=f.length))?a:t,a=t=0;t<n;t++)if(h[t]!=f[t]){o=h[t]<f[t];break}if(o&&(s=h,h=f,f=s,e.s=-e.s),(t=(n=f.length)-(r=h.length))>0)for(;t--;h[r++]=0);for(t=c-1;n>a;){if(h[--n]<f[n]){for(r=n;r&&!h[--r];h[r]=t);--h[r],h[n]+=c}h[n]-=f[n]}for(;0==h[0];h.splice(0,1),--d);return h[0]?H(e,h,d):(e.s=3==C?-1:1,e.c=[e.e=0],e)},A.modulo=A.mod=function(e,t){var n,s,o=this;return e=new F(e,t),!o.c||!e.s||e.c&&!e.c[0]?new F(NaN):!e.c||o.c&&!o.c[0]?new F(o):(9==D?(s=e.s,e.s=1,n=r(o,e,0,3),e.s=s,n.s*=s):n=r(o,e,0,D),(e=o.minus(n.times(e))).c[0]||1!=D||(e.s=o.s),e)},A.multipliedBy=A.times=function(e,t){var r,n,s,o,i,a,u,d,f,m,y,_,g,b,E,w=this,T=w.c,v=(e=new F(e,t)).c;if(!(T&&v&&T[0]&&v[0]))return!w.s||!e.s||T&&!T[0]&&!v||v&&!v[0]&&!T?e.c=e.e=e.s=null:(e.s*=w.s,T&&v?(e.c=[0],e.e=0):e.c=e.e=null),e;for(n=p(w.e/l)+p(e.e/l),e.s*=w.s,(u=T.length)<(m=v.length)&&(g=T,T=v,v=g,s=u,u=m,m=s),s=u+m,g=[];s--;g.push(0));for(b=c,E=h,s=m;--s>=0;){for(r=0,y=v[s]%E,_=v[s]/E|0,o=s+(i=u);o>s;)r=((d=y*(d=T[--i]%E)+(a=_*d+(f=T[i]/E|0)*y)%E*E+g[o]+r)/b|0)+(a/E|0)+_*f,g[o--]=d%b;g[o]=r}return r?++n:g.splice(0,1),H(e,g,n)},A.negated=function(){var e=new F(this);return e.s=-e.s||null,e},A.plus=function(e,t){var r,n=this,s=n.s;if(t=(e=new F(e,t)).s,!s||!t)return new F(NaN);if(s!=t)return e.s=-t,n.minus(e);var o=n.e/l,i=e.e/l,a=n.c,u=e.c;if(!o||!i){if(!a||!u)return new F(s/0);if(!a[0]||!u[0])return u[0]?e:new F(a[0]?n:0*s)}if(o=p(o),i=p(i),a=a.slice(),s=o-i){for(s>0?(i=o,r=u):(s=-s,r=a),r.reverse();s--;r.push(0));r.reverse()}for((s=a.length)-(t=u.length)<0&&(r=u,u=a,a=r,t=s),s=0;t;)s=(a[--t]=a[t]+u[t]+s)/c|0,a[t]=c===a[t]?0:a[t]%c;return s&&(a=[s].concat(a),++i),H(e,a,i)},A.precision=A.sd=function(e,t){var r,n,s,o=this;if(null!=e&&e!==!!e)return _(e,1,f),null==t?t=C:_(t,0,8),q(new F(o),e,t);if(!(r=o.c))return null;if(n=(s=r.length-1)*l+1,s=r[s]){for(;s%10==0;s/=10,n--);for(s=r[0];s>=10;s/=10,n++);}return e&&o.e+1>n&&(n=o.e+1),n},A.shiftedBy=function(e){return _(e,-9007199254740991,u),this.times("1e"+e)},A.squareRoot=A.sqrt=function(){var e,t,n,s,o,i=this,a=i.c,c=i.s,l=i.e,u=I+4,d=new F("0.5");if(1!==c||!a||!a[0])return new F(!c||c<0&&(!a||a[0])?NaN:a?i:1/0);if(0==(c=Math.sqrt(+$(i)))||c==1/0?(((t=m(a)).length+l)%2==0&&(t+="0"),c=Math.sqrt(+t),l=p((l+1)/2)-(l<0||l%2),n=new F(t=c==1/0?"5e"+l:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+l)):n=new F(c+""),n.c[0])for((c=(l=n.e)+u)<3&&(c=0);;)if(o=n,n=d.times(o.plus(r(i,o,u,1))),m(o.c).slice(0,c)===(t=m(n.c)).slice(0,c)){if(n.e<l&&--c,"9999"!=(t=t.slice(c-3,c+1))&&(s||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(q(n,n.e+I+2,1),e=!n.times(n).eq(i));break}if(!s&&(q(o,o.e+I+2,0),o.times(o).eq(i))){n=o;break}u+=4,c+=4,s=1}return q(n,n.e+I+1,C,e)},A.toExponential=function(e,t){return null!=e&&(_(e,0,f),e++),B(this,e,t,1)},A.toFixed=function(e,t){return null!=e&&(_(e,0,f),e=e+this.e+1),B(this,e,t)},A.toFormat=function(e,t,r){var n,s=this;if(null==r)null!=e&&t&&"object"==typeof t?(r=t,t=null):e&&"object"==typeof e?(r=e,e=t=null):r=L;else if("object"!=typeof r)throw Error(i+"Argument not an object: "+r);if(n=s.toFixed(e,t),s.c){var o,a=n.split("."),c=+r.groupSize,l=+r.secondaryGroupSize,u=r.groupSeparator||"",d=a[0],h=a[1],f=s.s<0,p=f?d.slice(1):d,m=p.length;if(l&&(o=c,c=l,l=o,m-=o),c>0&&m>0){for(o=m%c||c,d=p.substr(0,o);o<m;o+=c)d+=u+p.substr(o,c);l>0&&(d+=u+p.slice(o)),f&&(d="-"+d)}n=h?d+(r.decimalSeparator||"")+((l=+r.fractionGroupSize)?h.replace(new RegExp("\\d{"+l+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):h):d}return(r.prefix||"")+n+(r.suffix||"")},A.toFraction=function(e){var t,n,s,o,a,c,u,h,f,p,y,_,g=this,b=g.c;if(null!=e&&(!(u=new F(e)).isInteger()&&(u.c||1!==u.s)||u.lt(O)))throw Error(i+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+$(u));if(!b)return new F(g);for(t=new F(O),f=n=new F(O),s=h=new F(O),_=m(b),a=t.e=_.length-g.e-1,t.c[0]=d[(c=a%l)<0?l+c:c],e=!e||u.comparedTo(t)>0?a>0?t:f:u,c=P,P=1/0,u=new F(_),h.c[0]=0;p=r(u,t,0,1),1!=(o=n.plus(p.times(s))).comparedTo(e);)n=s,s=o,f=h.plus(p.times(o=f)),h=o,t=u.minus(p.times(o=t)),u=o;return o=r(e.minus(n),s,0,1),h=h.plus(o.times(f)),n=n.plus(o.times(s)),h.s=f.s=g.s,y=r(f,s,a*=2,C).minus(g).abs().comparedTo(r(h,n,a,C).minus(g).abs())<1?[f,s]:[h,n],P=c,y},A.toNumber=function(){return+$(this)},A.toPrecision=function(e,t){return null!=e&&_(e,1,f),B(this,e,t,2)},A.toString=function(e){var t,r=this,n=r.s,s=r.e;return null===s?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=s<=R||s>=k?b(m(r.c),s):E(m(r.c),s,"0"):10===e&&M?t=E(m((r=q(new F(r),I+s+1,C)).c),r.e,"0"):(_(e,2,j.length,"Base"),t=w(E(m(r.c),s,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},A.valueOf=A.toJSON=function(){return $(this)},A._isBigNumber=!0,null!=t&&F.set(t),F}(),r.default=r.BigNumber=r,"function"==typeof define&&define.amd?define((function(){return r})):void 0!==t&&t.exports?t.exports=r:(e||(e="undefined"!=typeof self&&self?self:window),e.BigNumber=r)}(e)}}),Mt=A({"node_modules/json-bigint/lib/stringify.js"(e,t){var r=jt(),n=t.exports;!function(){var e,t,s,o=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,i={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(e){return o.lastIndex=0,o.test(e)?'"'+e.replace(o,(function(e){var t=i[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}))+'"':'"'+e+'"'}function c(n,o){var i,l,u,d,h,f=e,p=o[n],m=null!=p&&(p instanceof r||r.isBigNumber(p));switch(p&&"object"==typeof p&&"function"==typeof p.toJSON&&(p=p.toJSON(n)),"function"==typeof s&&(p=s.call(o,n,p)),typeof p){case"string":return m?p:a(p);case"number":return isFinite(p)?String(p):"null";case"boolean":case"null":case"bigint":return String(p);case"object":if(!p)return"null";if(e+=t,h=[],"[object Array]"===Object.prototype.toString.apply(p)){for(d=p.length,i=0;i<d;i+=1)h[i]=c(i,p)||"null";return u=0===h.length?"[]":e?"[\n"+e+h.join(",\n"+e)+"\n"+f+"]":"["+h.join(",")+"]",e=f,u}if(s&&"object"==typeof s)for(d=s.length,i=0;i<d;i+=1)"string"==typeof s[i]&&(u=c(l=s[i],p))&&h.push(a(l)+(e?": ":":")+u);else Object.keys(p).forEach((function(t){var r=c(t,p);r&&h.push(a(t)+(e?": ":":")+r)}));return u=0===h.length?"{}":e?"{\n"+e+h.join(",\n"+e)+"\n"+f+"}":"{"+h.join(",")+"}",e=f,u}}"function"!=typeof n.stringify&&(n.stringify=function(r,n,o){var i;if(e="",t="","number"==typeof o)for(i=0;i<o;i+=1)t+=" ";else"string"==typeof o&&(t=o);if(s=n,n&&"function"!=typeof n&&("object"!=typeof n||"number"!=typeof n.length))throw new Error("JSON.stringify");return c("",{"":r})})}()}}),Ft=A({"node_modules/json-bigint/lib/parse.js"(e,t){var r=null,n=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,s=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;t.exports=function(e){var t={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(null!=e){if(!0===e.strict&&(t.strict=!0),!0===e.storeAsString&&(t.storeAsString=!0),t.alwaysParseAsBig=!0===e.alwaysParseAsBig&&e.alwaysParseAsBig,t.useNativeBigInt=!0===e.useNativeBigInt&&e.useNativeBigInt,void 0!==e.constructorAction){if("error"!==e.constructorAction&&"ignore"!==e.constructorAction&&"preserve"!==e.constructorAction)throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${e.constructorAction}`);t.constructorAction=e.constructorAction}if(void 0!==e.protoAction){if("error"!==e.protoAction&&"ignore"!==e.protoAction&&"preserve"!==e.protoAction)throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${e.protoAction}`);t.protoAction=e.protoAction}}var o,i,a,c,l={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},u=function(e){throw{name:"SyntaxError",message:e,at:o,text:a}},d=function(e){return e&&e!==i&&u("Expected '"+e+"' instead of '"+i+"'"),i=a.charAt(o),o+=1,i},h=function(){var e,n="";for("-"===i&&(n="-",d("-"));i>="0"&&i<="9";)n+=i,d();if("."===i)for(n+=".";d()&&i>="0"&&i<="9";)n+=i;if("e"===i||"E"===i)for(n+=i,d(),"-"!==i&&"+"!==i||(n+=i,d());i>="0"&&i<="9";)n+=i,d();if(e=+n,isFinite(e))return null==r&&(r=jt()),n.length>15?t.storeAsString?n:t.useNativeBigInt?BigInt(n):new r(n):t.alwaysParseAsBig?t.useNativeBigInt?BigInt(e):new r(e):e;u("Bad number")},f=function(){var e,t,r,n="";if('"'===i)for(var s=o;d();){if('"'===i)return o-1>s&&(n+=a.substring(s,o-1)),d(),n;if("\\"===i){if(o-1>s&&(n+=a.substring(s,o-1)),d(),"u"===i){for(r=0,t=0;t<4&&(e=parseInt(d(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof l[i])break;n+=l[i]}s=o}}u("Bad string")},p=function(){for(;i&&i<=" ";)d()};return c=function(){switch(p(),i){case"{":return function(){var e,r=Object.create(null);if("{"===i){if(d("{"),p(),"}"===i)return d("}"),r;for(;i;){if(e=f(),p(),d(":"),!0===t.strict&&Object.hasOwnProperty.call(r,e)&&u('Duplicate key "'+e+'"'),!0===n.test(e)?"error"===t.protoAction?u("Object contains forbidden prototype property"):"ignore"===t.protoAction?c():r[e]=c():!0===s.test(e)?"error"===t.constructorAction?u("Object contains forbidden constructor property"):"ignore"===t.constructorAction?c():r[e]=c():r[e]=c(),p(),"}"===i)return d("}"),r;d(","),p()}}u("Bad object")}();case"[":return function(){var e=[];if("["===i){if(d("["),p(),"]"===i)return d("]"),e;for(;i;){if(e.push(c()),p(),"]"===i)return d("]"),e;d(","),p()}}u("Bad array")}();case'"':return f();case"-":return h();default:return i>="0"&&i<="9"?h():function(){switch(i){case"t":return d("t"),d("r"),d("u"),d("e"),!0;case"f":return d("f"),d("a"),d("l"),d("s"),d("e"),!1;case"n":return d("n"),d("u"),d("l"),d("l"),null}u("Unexpected '"+i+"'")}()}},function(e,t){var r;return a=e+"",o=0,i=" ",r=c(),p(),i&&u("Syntax error"),"function"==typeof t?function e(r,n){var s,o=r[n];return o&&"object"==typeof o&&Object.keys(o).forEach((function(t){void 0!==(s=e(o,t))?o[t]=s:delete o[t]})),t.call(r,n,o)}({"":r},""):r}}}}),Bt=A({"node_modules/json-bigint/index.js"(e,t){var r=Mt().stringify,n=Ft();t.exports=function(e){return{parse:n(e),stringify:r}},t.exports.parse=n(),t.exports.stringify=r}}),Gt=A({"node_modules/gcp-metadata/build/src/gcp-residency.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GCE_LINUX_BIOS_PATHS=void 0,e.isGoogleCloudServerless=s,e.isGoogleComputeEngineLinux=o,e.isGoogleComputeEngineMACAddress=i,e.isGoogleComputeEngine=a,e.detectGCPResidency=function(){return s()||a()};var t=v("fs"),r=v("os");e.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var n=/^42:01/;function s(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function o(){if("linux"!==(0,r.platform)())return!1;try{(0,t.statSync)(e.GCE_LINUX_BIOS_PATHS.BIOS_DATE);const r=(0,t.readFileSync)(e.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(r)}catch{return!1}}function i(){const e=(0,r.networkInterfaces)();for(const t of Object.values(e))if(t)for(const{mac:e}of t)if(n.test(e))return!0;return!1}function a(){return o()||i()}}}),Ht=A({"node_modules/google-logging-utils/build/src/colours.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Colours=void 0;var t=class e{static isEnabled(e){return e&&e.isTTY&&("function"!=typeof e.getColorDepth||e.getColorDepth()>2)}static refresh(){e.enabled=e.isEnabled(null===process||void 0===process?void 0:process.stderr),this.enabled?(e.reset="",e.bright="",e.dim="",e.red="",e.green="",e.yellow="",e.blue="",e.magenta="",e.cyan="",e.white="",e.grey=""):(e.reset="",e.bright="",e.dim="",e.red="",e.green="",e.yellow="",e.blue="",e.magenta="",e.cyan="",e.white="",e.grey="")}};e.Colours=t,t.enabled=!1,t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="",t.refresh()}}),qt=A({"node_modules/google-logging-utils/build/src/logging-utils.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(){var e=function(t){return(e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(t)};return function(n){if(n&&n.__esModule)return n;var s={};if(null!=n)for(var o=e(n),i=0;i<o.length;i++)"default"!==o[i]&&t(s,n,o[i]);return r(s,n),s}}();Object.defineProperty(e,"__esModule",{value:!0}),e.env=e.DebugLogBackendBase=e.placeholder=e.AdhocDebugLogger=e.LogSeverity=void 0,e.getNodeBackend=f,e.getDebugBackend=function(e){return new p(e)},e.getStructuredBackend=function(e){return new m(e)},e.setBackend=function(e){_=e,y.clear()},e.log=g;var s,o,i=v("events"),a=n(v("process")),c=n(v("util")),l=Ht();(o=s||(e.LogSeverity=s={})).DEFAULT="DEFAULT",o.DEBUG="DEBUG",o.INFO="INFO",o.WARNING="WARNING",o.ERROR="ERROR";var u=class extends i.EventEmitter{constructor(e,t){super(),this.namespace=e,this.upstream=t,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(e,t)=>this.on(e,t)}),this.func.debug=(...e)=>this.invokeSeverity(s.DEBUG,...e),this.func.info=(...e)=>this.invokeSeverity(s.INFO,...e),this.func.warn=(...e)=>this.invokeSeverity(s.WARNING,...e),this.func.error=(...e)=>this.invokeSeverity(s.ERROR,...e),this.func.sublog=e=>g(e,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch(e){}try{this.emit("log",e,t)}catch(e){}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}};e.AdhocDebugLogger=u,e.placeholder=new u("",(()=>{})).func;var d=class{constructor(){var t;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=null!==(t=a.env[e.env.nodeEnables])&&void 0!==t?t:"*";"all"===r&&(r="*"),this.filters=r.split(",")}log(e,t,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let n=this.cached.get(e);n||(n=this.makeLogger(e),this.cached.set(e,n)),n(t,...r)}catch(e){console.error(e)}}};e.DebugLogBackendBase=d;var h=class extends d{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(t,...r)=>{var n;const o=`${l.Colours.green}${e}${l.Colours.reset}`,i=`${l.Colours.yellow}${a.pid}${l.Colours.reset}`;let u;switch(t.severity){case s.ERROR:u=`${l.Colours.red}${t.severity}${l.Colours.reset}`;break;case s.INFO:u=`${l.Colours.magenta}${t.severity}${l.Colours.reset}`;break;case s.WARNING:u=`${l.Colours.yellow}${t.severity}${l.Colours.reset}`;break;default:u=null!==(n=t.severity)&&void 0!==n?n:s.DEFAULT}const d=c.formatWithOptions({colors:l.Colours.enabled},...r),h=Object.assign({},t);delete h.severity;const f=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",p=f?`${l.Colours.grey}${f}${l.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",i,o,u,d,f?` ${p}`:"")}:()=>{}}setFilters(){const e=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${e}$`,"i")}};function f(){return new h}var p=class extends d{constructor(e){super(),this.debugPkg=e}makeLogger(e){const t=this.debugPkg(e);return(e,...r)=>{t(r[0],...r.slice(1))}}setFilters(){var e;const t=null!==(e=a.env.NODE_DEBUG)&&void 0!==e?e:"";a.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}};var m=class extends d{constructor(e){var t;super(),this.upstream=null!==(t=e)&&void 0!==t?t:void 0}makeLogger(e){var t;const r=null===(t=this.upstream)||void 0===t?void 0:t.makeLogger(e);return(e,...t)=>{var n;const o=null!==(n=e.severity)&&void 0!==n?n:s.INFO,i=Object.assign({severity:o,message:c.format(...t)},e),a=JSON.stringify(i);r?r(e,a):console.log("%s",a)}}setFilters(){var e;null===(e=this.upstream)||void 0===e||e.setFilters()}};e.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var y=new Map,_=void 0;function g(t,r){if(!_){if(!a.env[e.env.nodeEnables])return e.placeholder}if(!t)return e.placeholder;r&&(t=`${r.instance.namespace}:${t}`);const n=y.get(t);if(n)return n.func;if(null===_)return e.placeholder;void 0===_&&(_=f());const s=(()=>{let e;return new u(t,((r,...n)=>{if(e!==_){if(null===_)return;void 0===_&&(_=f()),e=_}null==_||_.log(t,r,...n)}))})();return y.set(t,s),s.func}}}),$t=A({"node_modules/google-logging-utils/build/src/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(qt(),e)}}),Wt=A({"node_modules/gcp-metadata/build/src/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(){var e=function(t){return(e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(t)};return function(n){if(n&&n.__esModule)return n;var s={};if(null!=n)for(var o=e(n),i=0;i<o.length;i++)"default"!==o[i]&&t(s,n,o[i]);return r(s,n),s}}(),s=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.gcpResidencyCache=e.METADATA_SERVER_DETECTION=e.HEADERS=e.HEADER_VALUE=e.HEADER_NAME=e.SECONDARY_HOST_ADDRESS=e.HOST_ADDRESS=e.BASE_PATH=void 0,e.instance=function(e){return h("instance",e)},e.project=function(e){return h("project",e)},e.universe=function(e){return h("universe",e)},e.bulk=async function(e){const t={};return await Promise.all(e.map((e=>(async()=>{const r=await h(e),n=e.metadataKey;t[n]=r})()))),t},e.isAvailable=async function(){if(process.env.METADATA_SERVER_DETECTION){const t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in e.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(e.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return p()}}try{return void 0===l&&(l=h("instance",void 0,process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0,!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await l,!0}catch(e){const t=e;if(process.env.DEBUG_AUTH&&console.info(t),"request-timeout"===t.type)return!1;if(t.response&&404===t.response.status)return!1;if(!(t.response&&404===t.response.status||t.code&&["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(t.code.toString()))){let e="UNKNOWN";t.code&&(e=t.code.toString()),process.emitWarning(`received unexpected error = ${t.message} code = ${e}`,"MetadataLookupWarning")}return!1}},e.resetIsAvailableCache=function(){l=void 0},e.getGCPResidency=p,e.setGCPResidency=m,e.requestTimeout=y;var o=Lt(),i=Bt(),a=Gt(),c=n($t());e.BASE_PATH="/computeMetadata/v1",e.HOST_ADDRESS="http://169.254.169.254",e.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.",e.HEADER_NAME="Metadata-Flavor",e.HEADER_VALUE="Google",e.HEADERS=Object.freeze({[e.HEADER_NAME]:e.HEADER_VALUE});var l,u=c.log("gcp-metadata");function d(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||e.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(e.BASE_PATH,t).href}async function h(t,r={},n=3,s=!1){const a=new Headers(e.HEADERS);let c="",l={};if("object"==typeof t){const e=t;new Headers(e.headers).forEach(((e,t)=>a.set(t,e))),c=e.metadataKey,l=e.params||l,n=e.noResponseRetries||n,s=e.fastFail||s}else c=t;"string"==typeof r?c+=`/${r}`:(!function(e){Object.keys(e).forEach((e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}}))}(r),r.property&&(c+=`/${r.property}`),new Headers(r.headers).forEach(((e,t)=>a.set(t,e))),l=r.params||l);const h=s?f:o.request,p={url:`${d()}/${c}`,headers:a,retryConfig:{noResponseRetries:n},params:l,responseType:"text",timeout:y()};u.info("instance request %j",p);const m=await h(p);u.info("instance metadata is %s",m.data);const _=m.headers.get(e.HEADER_NAME);if(_!==e.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${e.HEADER_NAME} header. Expected '${e.HEADER_VALUE}', got ${_?`'${_}'`:"no header"}`);if("string"==typeof m.data)try{return i.parse(m.data)}catch{}return m.data}async function f(t){const r={...t,url:t.url?.toString().replace(d(),d(e.SECONDARY_HOST_ADDRESS))},n=(0,o.request)(t),s=(0,o.request)(r);return Promise.any([n,s])}function p(){return null===e.gcpResidencyCache&&m(),e.gcpResidencyCache}function m(t=null){e.gcpResidencyCache=null!==t?t:(0,a.detectGCPResidency)()}function y(){return p()?0:3e3}e.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"}),e.gcpResidencyCache=null,s(Gt(),e)}}),Vt=A({"node_modules/base64-js/index.js"(e){e.byteLength=function(e){var t=i(e),r=t[0],n=t[1];return 3*(r+n)/4-n},e.toByteArray=function(e){var t,r,o=i(e),a=o[0],c=o[1],l=new s(function(e,t,r){return 3*(t+r)/4-r}(0,a,c)),u=0,d=c>0?a-4:a;for(r=0;r<d;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],l[u++]=t>>16&255,l[u++]=t>>8&255,l[u++]=255&t;2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[u++]=255&t);1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t);return l},e.fromByteArray=function(e){for(var t,n=e.length,s=n%3,o=[],i=16383,c=0,l=n-s;c<l;c+=i)o.push(a(e,c,c+i>l?l:c+i));1===s?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===s&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return o.join("")};var t,r=[],n=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(t=0,64;t<64;++t)r[t]=o[t],n[o.charCodeAt(t)]=t;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function a(e,t,n){for(var s,o,i=[],a=t;a<n;a+=3)s=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),i.push(r[(o=s)>>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63}}),Yt=A({"node_modules/google-auth-library/build/src/crypto/shared.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.fromArrayBufferToHex=function(e){return Array.from(new Uint8Array(e)).map((e=>e.toString(16).padStart(2,"0"))).join("")}}}),zt=A({"node_modules/google-auth-library/build/src/crypto/browser/crypto.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.BrowserCrypto=void 0;var t=Vt(),r=Yt();e.BrowserCrypto=class e{constructor(){if("undefined"==typeof window||void 0===window.crypto||void 0===window.crypto.subtle)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){const r=(new TextEncoder).encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return t.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){const r=new Uint8Array(e);return window.crypto.getRandomValues(r),t.fromByteArray(r)}static padBase64(e){for(;e.length%4!=0;)e+="=";return e}async verify(r,n,s){const o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=(new TextEncoder).encode(n),a=t.toByteArray(e.padBase64(s)),c=await window.crypto.subtle.importKey("jwk",r,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,Buffer.from(a),i)}async sign(e,r){const n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=(new TextEncoder).encode(r),o=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),i=await window.crypto.subtle.sign(n,o,s);return t.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(r){const n=t.toByteArray(e.padBase64(r));return(new TextDecoder).decode(n)}encodeBase64StringUtf8(e){const r=(new TextEncoder).encode(e);return t.fromByteArray(r)}async sha256DigestHex(e){const t=(new TextEncoder).encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return(0,r.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,t){const r="string"==typeof e?e:String.fromCharCode(...new Uint16Array(e)),n=new TextEncoder,s=await window.crypto.subtle.importKey("raw",n.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,n.encode(t))}}}}),Kt=A({"node_modules/google-auth-library/build/src/crypto/node/crypto.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NodeCrypto=void 0;var t=v("crypto");e.NodeCrypto=class{async sha256DigestBase64(e){return t.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return t.randomBytes(e).toString("base64")}async verify(e,r,n){const s=t.createVerify("RSA-SHA256");return s.update(r),s.end(),s.verify(e,n,"base64")}async sign(e,r){const n=t.createSign("RSA-SHA256");return n.update(r),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return t.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){const n="string"==typeof e?e:(s=e,Buffer.from(s));var s;return function(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;++t)r[t]=e[t];return t}(t.createHmac("sha256",n).update(r).digest())}}}}),Jt=A({"node_modules/google-auth-library/build/src/crypto/crypto.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.createCrypto=function(){if(o())return new n.BrowserCrypto;return new s.NodeCrypto},e.hasBrowserCrypto=o;var n=zt(),s=Kt();function o(){return"undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle}r(Yt(),e)}}),Xt=A({"node_modules/safe-buffer/index.js"(e,t){var r=v("buffer"),n=r.Buffer;function s(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(s(r,e),e.Buffer=o),s(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var s=n(e);return void 0!==t?"string"==typeof r?s.fill(t,r):s.fill(t):s.fill(0),s},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}}),Qt=A({"node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js"(e,t){function r(e){return(e/8|0)+(e%8==0?0:1)}var n={ES256:r(256),ES384:r(384),ES512:r(521)};t.exports=function(e){var t=n[e];if(t)return t;throw new Error('Unknown algorithm "'+e+'"')}}}),Zt=A({"node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js"(e,t){var r=Xt().Buffer,n=Qt(),s=128;function o(e){if(r.isBuffer(e))return e;if("string"==typeof e)return r.from(e,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function i(e,t,r){for(var n=0;t+n<r&&0===e[t+n];)++n;return e[t+n]>=s&&--n,n}t.exports={derToJose:function(e,t){e=o(e);var s=n(t),i=s+1,a=e.length,c=0;if(48!==e[c++])throw new Error('Could not find expected "seq"');var l=e[c++];if(129===l&&(l=e[c++]),a-c<l)throw new Error('"seq" specified length of "'+l+'", only "'+(a-c)+'" remaining');if(2!==e[c++])throw new Error('Could not find expected "int" for "r"');var u=e[c++];if(a-c-2<u)throw new Error('"r" specified length of "'+u+'", only "'+(a-c-2)+'" available');if(i<u)throw new Error('"r" specified length of "'+u+'", max of "'+i+'" is acceptable');var d=c;if(c+=u,2!==e[c++])throw new Error('Could not find expected "int" for "s"');var h=e[c++];if(a-c!==h)throw new Error('"s" specified length of "'+h+'", expected "'+(a-c)+'"');if(i<h)throw new Error('"s" specified length of "'+h+'", max of "'+i+'" is acceptable');var f=c;if((c+=h)!==a)throw new Error('Expected to consume entire buffer, but "'+(a-c)+'" bytes remain');var p=s-u,m=s-h,y=r.allocUnsafe(p+u+m+h);for(c=0;c<p;++c)y[c]=0;e.copy(y,c,d+Math.max(-p,0),d+u);for(var _=c=s;c<_+m;++c)y[c]=0;return e.copy(y,c,f+Math.max(-m,0),f+h),y=(y=y.toString("base64")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},joseToDer:function(e,t){e=o(e);var a=n(t),c=e.length;if(c!==2*a)throw new TypeError('"'+t+'" signatures must be "'+2*a+'" bytes, saw "'+c+'"');var l=i(e,0,a),u=i(e,a,e.length),d=a-l,h=a-u,f=2+d+1+1+h,p=f<s,m=r.allocUnsafe((p?2:3)+f),y=0;return m[y++]=48,p?m[y++]=f:(m[y++]=129,m[y++]=255&f),m[y++]=2,m[y++]=d,l<0?(m[y++]=0,y+=e.copy(m,y,0,a)):y+=e.copy(m,y,l,a),m[y++]=2,m[y++]=h,u<0?(m[y++]=0,e.copy(m,y,a)):e.copy(m,y,a+u),m}}}}),er=A({"node_modules/google-auth-library/build/src/util.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.LRUCache=void 0,e.snakeToCamel=o,e.originalOrCamelOptions=function(e){return{get:function(t){const r=e||{};return r[t]??r[o(t)]}}},e.removeUndefinedValuesInObject=function(e){return Object.entries(e).forEach((([t,r])=>{void 0!==r&&"undefined"!==r||delete e[t]})),e},e.isValidFile=async function(e){try{return(await t.promises.lstat(e)).isFile()}catch(e){return!1}},e.getWellKnownCertificateConfigFileLocation=function(){const e=process.env.CLOUDSDK_CONFIG||(r.platform().startsWith("win")?n.join(process.env.APPDATA||"",s):n.join(process.env.HOME||"",".config",s));return n.join(e,"certificate_config.json")};var t=v("fs"),r=v("os"),n=v("path"),s="gcloud";function o(e){return e.replace(/([_][^_])/g,(e=>e.slice(1).toUpperCase()))}e.LRUCache=class{capacity;#g=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#b(e,t){this.#g.delete(e),this.#g.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#b(e,t),this.#E()}get(e){const t=this.#g.get(e);if(t)return this.#b(e,t.value),this.#E(),t.value}#E(){const e=this.maxAge?Date.now()-this.maxAge:0;let t=this.#g.entries().next();for(;!t.done&&(this.#g.size>this.capacity||t.value[1].lastAccessed<e);)this.#g.delete(t.value[0]),t=this.#g.entries().next()}}}}),tr=A({"node_modules/google-auth-library/package.json"(e,t){t.exports={name:"google-auth-library",version:"10.6.2",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"echo 'disabled until linkinator is fixed'","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/google-auth-library-nodejs"}}}),rr=A({"node_modules/google-auth-library/build/src/shared.cjs"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.USER_AGENT=e.PRODUCT_NAME=e.pkg=void 0;var t=tr();e.pkg=t;var r="google-api-nodejs-client";e.PRODUCT_NAME=r;var n=`${r}/${t.version}`;e.USER_AGENT=n}}),nr=A({"node_modules/google-auth-library/build/src/auth/authclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AuthClient=e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=e.DEFAULT_UNIVERSE=void 0;var t=v("events"),r=Lt(),n=er(),s=$t(),o=rr();e.DEFAULT_UNIVERSE="googleapis.com",e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=3e5;var i=class i extends t.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=e.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(t={}){super();const s=(0,n.originalOrCamelOptions)(t);this.apiKey=t.apiKey,this.projectId=s.get("project_id")??null,this.quotaProjectId=s.get("quota_project_id"),this.credentials=s.get("credentials")??{},this.universeDomain=s.get("universe_domain")??e.DEFAULT_UNIVERSE,this.transporter=t.transporter??new r.Gaxios(t.transporterOptions),!1!==s.get("useAuthRequestParameters")&&(this.transporter.interceptors.request.add(i.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(i.DEFAULT_RESPONSE_INTERCEPTOR)),t.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=t.forceRefreshOnFailure??!1}fetch(...e){const t=e[0],n=e[1];let s;const o=new Headers;return"string"==typeof t?s=new URL(t):t instanceof URL?s=t:t&&t.url&&(s=new URL(t.url)),t&&"object"==typeof t&&"headers"in t&&r.Gaxios.mergeHeaders(o,t.headers),n&&r.Gaxios.mergeHeaders(o,new Headers(n.headers)),"object"!=typeof t||t instanceof URL?this.request({...n,headers:o,url:s}):this.request({...n,...t,headers:o,url:s})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,t){const r=t.get("x-goog-user-project"),n=t.get("authorization");return r&&e.set("x-goog-user-project",r),n&&e.set("authorization",n),e}static log=(0,s.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){const t=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${t}`)}const t=e.headers.get("User-Agent");t?t.includes(`${o.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${t} ${o.USER_AGENT}`):e.headers.set("User-Agent",o.USER_AGENT);try{const t=e,r=t[i.RequestMethodNameSymbol],n=`${Math.floor(1e3*Math.random())}`;t[i.RequestLogIdSymbol]=n;const s={url:e.url,headers:e.headers};r?i.log.info("%s [%s] request %j",r,n,s):i.log.info("[%s] request %j",n,s)}catch(e){}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{const t=e.config,r=t[i.RequestMethodNameSymbol],n=t[i.RequestLogIdSymbol];r?i.log.info("%s [%s] response %j",r,n,e.data):i.log.info("[%s] response %j",n,e.data)}catch(e){}return e},rejected:async e=>{try{const t=e.config,r=t[i.RequestMethodNameSymbol],n=t[i.RequestLogIdSymbol];r?i.log.info("%s [%s] error %j",r,n,e.response?.data):i.log.error("[%s] error %j",n,e.response?.data)}catch(e){}throw e}};static setMethodName(e,t){try{e[i.RequestMethodNameSymbol]=t}catch(e){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};e.AuthClient=i}}),sr=A({"node_modules/google-auth-library/build/src/auth/loginticket.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.LoginTicket=void 0;e.LoginTicket=class{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){const e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}}}),or=A({"node_modules/google-auth-library/build/src/auth/oauth2client.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.OAuth2Client=e.ClientAuthentication=e.CertificateFormat=e.CodeChallengeMethod=void 0;var t,r,n,s,o,i,a=Lt(),c=v("querystring"),l=v("stream"),u=Zt(),d=er(),h=Jt(),f=nr(),p=sr();(r=t||(e.CodeChallengeMethod=t={})).Plain="plain",r.S256="S256",(s=n||(e.CertificateFormat=n={})).PEM="PEM",s.JWK="JWK",(i=o||(e.ClientAuthentication=o={})).ClientSecretPost="ClientSecretPost",i.ClientSecretBasic="ClientSecretBasic",i.None="None";var m=class e extends f.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=n.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,r){super("object"==typeof e?e:{}),"object"!=typeof e&&(e={clientId:e,clientSecret:t,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||o.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" "));return this.endpoints.oauth2AuthBaseUrl.toString()+"?"+c.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){const e=(0,h.createCrypto)(),t=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-");return{codeVerifier:t,codeChallenge:(await e.sha256DigestBase64(t)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_")}}getToken(e,t){const r="string"==typeof e?{code:e}:e;if(!t)return this.getTokenAsync(r);this.getTokenAsync(r).then((e=>t(null,e.tokens,e.res)),(e=>t(e,null,e.response)))}async getTokenAsync(t){const r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,s={client_id:t.client_id||this._clientId,code_verifier:t.codeVerifier,code:t.code,grant_type:"authorization_code",redirect_uri:t.redirect_uri||this.redirectUri};if(this.clientAuthentication===o.ClientSecretBasic){const e=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${e.toString("base64")}`)}this.clientAuthentication===o.ClientSecretPost&&(s.client_secret=this._clientSecret);const i={...e.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,d.removeUndefinedValuesInObject)(s)),headers:n};f.AuthClient.setMethodName(i,"getTokenAsync");const a=await this.transporter.request(i),c=a.data;return a.data&&a.data.expires_in&&(c.expiry_date=(new Date).getTime()+1e3*a.data.expires_in,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);const t=this.refreshTokenNoCache(e).then((t=>(this.refreshTokenPromises.delete(e),t)),(t=>{throw this.refreshTokenPromises.delete(e),t}));return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(t){if(!t)throw new Error("No refresh token is set.");const r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:t,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"};let s;try{const t={...e.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,d.removeUndefinedValuesInObject)(n))};f.AuthClient.setMethodName(t,"refreshTokenNoCache"),s=await this.transporter.request(t)}catch(e){throw e instanceof a.GaxiosError&&"invalid_grant"===e.message&&e.response?.data&&/ReAuth/i.test(e.response.data.error_description)&&(e.message=JSON.stringify(e.response.data)),e}const o=s.data;return s.data&&s.data.expires_in&&(o.expiry_date=(new Date).getTime()+1e3*s.data.expires_in,delete o.expires_in),this.emit("tokens",o),{tokens:o,res:s}}refreshAccessToken(e){if(!e)return this.refreshAccessTokenAsync();this.refreshAccessTokenAsync().then((t=>e(null,t.credentials,t.res)),e)}async refreshAccessTokenAsync(){const e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(!e)return this.getAccessTokenAsync();this.getAccessTokenAsync().then((t=>e(null,t.token,t.res)),e)}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token){if(!this.refreshHandler)throw new Error("No refresh token or refresh handler callback is set.");{const e=await this.processAndValidateRefreshHandler();if(e?.access_token)return this.setCredentials(e),{token:this.credentials.access_token}}}const e=await this.refreshAccessTokenAsync();if(!e.credentials||e.credentials&&!e.credentials.access_token)throw new Error("Could not refresh access token.");return{token:e.credentials.access_token,res:e.res}}return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){const t=this.credentials;if(!(t.access_token||t.refresh_token||this.apiKey||this.refreshHandler))throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";const e=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(e)}}if(this.refreshHandler){const e=await this.processAndValidateRefreshHandler();if(e?.access_token){this.setCredentials(e);const t=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(t)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,n=null;try{r=await this.refreshToken(t.refresh_token),n=r.tokens}catch(e){const t=e;throw!t.response||403!==t.response.status&&404!==t.response.status||(t.message=`Could not refresh access token: ${t.message}`),t}const s=this.credentials;s.token_type=s.token_type||"Bearer",n.refresh_token=s.refresh_token,this.credentials=n;const o=new Headers({authorization:s.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(o),res:r.res}}static getRevokeTokenUrl(t){return(new e).getRevokeTokenURL(t).toString()}getRevokeTokenURL(e){const t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(t,r){const n={...e.RETRY_CONFIG,url:this.getRevokeTokenURL(t).toString(),method:"POST"};if(f.AuthClient.setMethodName(n,"revokeToken"),!r)return this.transporter.request(n);this.transporter.request(n).then((e=>r(null,e)),r)}revokeCredentials(e){if(!e)return this.revokeCredentialsAsync();this.revokeCredentialsAsync().then((t=>e(null,t)),e)}async revokeCredentialsAsync(){const e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then((e=>t(null,e)),(e=>t(e,e.response)))}async requestAsync(e,t=!1){try{const t=await this.getRequestMetadataAsync();return e.headers=a.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){const n=r.response;if(n){const r=n.status,s=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),o=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,i=n.config.data instanceof l.Readable,a=401===r||403===r;if(!t&&a&&!i&&s)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!t&&a&&!i&&o){const t=await this.processAndValidateRefreshHandler();return t?.access_token&&this.setCredentials(t),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,t){if(t&&"function"!=typeof t)throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(!t)return this.verifyIdTokenAsync(e);this.verifyIdTokenAsync(e).then((e=>t(null,e)),t)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");const t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(t){const{data:r}=await this.transporter.request({...e.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${t}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:(new Date).getTime()+1e3*r.expires_in,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(!e)return this.getFederatedSignonCertsAsync();this.getFederatedSignonCertsAsync().then((t=>e(null,t.certs,t.res)),e)}async getFederatedSignonCertsAsync(){const t=(new Date).getTime(),r=(0,h.hasBrowserCrypto)()?n.JWK:n.PEM;if(this.certificateExpiry&&t<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let s,o;switch(r){case n.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case n.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{const t={...e.RETRY_CONFIG,url:o};f.AuthClient.setMethodName(t,"getFederatedSignonCertsAsync"),s=await this.transporter.request(t)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}const i=s?.headers.get("cache-control");let a=-1;if(i){const e=/max-age=(?<maxAge>[0-9]+)/.exec(i)?.groups?.maxAge;e&&(a=1e3*Number(e))}let c={};switch(r){case n.PEM:c=s.data;break;case n.JWK:for(const e of s.data.keys)c[e.kid]=e;break;default:throw new Error(`Unsupported certificate format ${r}`)}const l=new Date;return this.certificateExpiry=-1===a?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=r,{certs:c,format:r,res:s}}getIapPublicKeys(e){if(!e)return this.getIapPublicKeysAsync();this.getIapPublicKeysAsync().then((t=>e(null,t.pubkeys,t.res)),e)}async getIapPublicKeysAsync(){let t;const r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{const n={...e.RETRY_CONFIG,url:r};f.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),t=await this.transporter.request(n)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}return{pubkeys:t.data,res:t}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(t,r,n,s,o){const i=(0,h.createCrypto)();o||(o=e.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);const a=t.split(".");if(3!==a.length)throw new Error("Wrong number of segments in token: "+t);const c=a[0]+"."+a[1];let l,d,f=a[2];try{l=JSON.parse(i.decodeBase64StringUtf8(a[0]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token envelope: ${a[0]}': ${e.message}`),e}if(!l)throw new Error("Can't parse token envelope: "+a[0]);try{d=JSON.parse(i.decodeBase64StringUtf8(a[1]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token payload '${a[0]}`),e}if(!d)throw new Error("Can't parse token payload: "+a[1]);if(!Object.prototype.hasOwnProperty.call(r,l.kid))throw new Error("No pem found for envelope: "+JSON.stringify(l));const m=r[l.kid];"ES256"===l.alg&&(f=u.joseToDer(f,"ES256").toString("base64"));if(!await i.verify(m,c,f))throw new Error("Invalid token signature: "+t);if(!d.iat)throw new Error("No issue time in token: "+JSON.stringify(d));if(!d.exp)throw new Error("No expiration time in token: "+JSON.stringify(d));const y=Number(d.iat);if(isNaN(y))throw new Error("iat field using invalid format");const _=Number(d.exp);if(isNaN(_))throw new Error("exp field using invalid format");const g=(new Date).getTime()/1e3;if(_>=g+o)throw new Error("Expiration time too far in future: "+JSON.stringify(d));const b=y-e.CLOCK_SKEW_SECS_,E=_+e.CLOCK_SKEW_SECS_;if(g<b)throw new Error("Token used too early, "+g+" < "+b+": "+JSON.stringify(d));if(g>E)throw new Error("Token used too late, "+g+" > "+E+": "+JSON.stringify(d));if(s&&s.indexOf(d.iss)<0)throw new Error("Invalid issuer, expected one of ["+s+"], but got "+d.iss);if(null!=n){const e=d.aud;let t=!1;if(t=n.constructor===Array?n.indexOf(e)>-1:e===n,!t)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new p.LoginTicket(l,d)}async processAndValidateRefreshHandler(){if(this.refreshHandler){const e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){const e=this.credentials.expiry_date;return!!e&&e<=(new Date).getTime()+this.eagerRefreshThresholdMillis}};e.OAuth2Client=m}}),ir=A({"node_modules/google-auth-library/build/src/auth/computeclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Compute=void 0;var t=Lt(),r=Wt(),n=or(),s=class extends n.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){const e=`service-accounts/${this.serviceAccountEmail}/token`;let n;try{const t={property:e};this.scopes.length>0&&(t.params={scopes:this.scopes.join(",")}),n=await r.instance(t)}catch(e){throw e instanceof t.GaxiosError&&(e.message=`Could not refresh access token: ${e.message}`,this.wrapError(e)),e}const s=n;return n&&n.expires_in&&(s.expiry_date=(new Date).getTime()+1e3*n.expires_in,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:null}}async fetchIdToken(e){const t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`;let n;try{const e={property:t};n=await r.instance(e)}catch(e){throw e instanceof Error&&(e.message=`Could not fetch ID token: ${e.message}`),e}return n}wrapError(e){const t=e.response;t&&t.status&&(e.status=t.status,403===t.status?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:404===t.status&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};e.Compute=s}}),ar=A({"node_modules/google-auth-library/build/src/auth/idtokenclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.IdTokenClient=void 0;var t=or(),r=class extends t.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){const e=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:e,expiry_date:this.getIdTokenExpiryDate(e)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){const t=e.split(".")[1];if(t){return 1e3*JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp}}};e.IdTokenClient=r}}),cr=A({"node_modules/google-auth-library/build/src/auth/envDetect.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GCPEnv=void 0,e.clear=function(){n=void 0},e.getEnv=async function(){if(n)return n;return n=async function(){let e=t.NONE;e=process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME?t.APP_ENGINE:process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET?t.CLOUD_FUNCTIONS:await async function(){return s.isAvailable()}()?await async function(){try{return await s.instance("attributes/cluster-name"),!0}catch(e){return!1}}()?t.KUBERNETES_ENGINE:process.env.K_CONFIGURATION?t.CLOUD_RUN:process.env.CLOUD_RUN_JOB?t.CLOUD_RUN_JOBS:t.COMPUTE_ENGINE:t.NONE;return e}()};var t,r,n,s=Wt();(r=t||(e.GCPEnv=t={})).APP_ENGINE="APP_ENGINE",r.KUBERNETES_ENGINE="KUBERNETES_ENGINE",r.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",r.COMPUTE_ENGINE="COMPUTE_ENGINE",r.CLOUD_RUN="CLOUD_RUN",r.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",r.NONE="NONE"}}),lr=A({"node_modules/jws/lib/data-stream.js"(e,t){var r=Xt().Buffer,n=v("stream");function s(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=r.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=r.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof e+")")}v("util").inherits(s,n),s.prototype.write=function(e){this.buffer=r.concat([this.buffer,r.from(e)]),this.emit("data",e)},s.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},t.exports=s}}),ur=A({"node_modules/buffer-equal-constant-time/index.js"(e,t){var r=v("buffer").Buffer,n=v("buffer").SlowBuffer;function s(e,t){if(!r.isBuffer(e)||!r.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(var n=0,s=0;s<e.length;s++)n|=e[s]^t[s];return 0===n}t.exports=s,s.install=function(){r.prototype.equal=n.prototype.equal=function(e){return s(this,e)}};var o=r.prototype.equal,i=n.prototype.equal;s.restore=function(){r.prototype.equal=o,n.prototype.equal=i}}}),dr=A({"node_modules/jwa/index.js"(e,t){var r,n=Xt().Buffer,s=v("crypto"),o=Zt(),i=v("util"),a="secret must be a string or buffer",c="key must be a string or a buffer",l="function"==typeof s.createPublicKey;function u(e){if(!n.isBuffer(e)&&"string"!=typeof e){if(!l)throw p(c);if("object"!=typeof e)throw p(c);if("string"!=typeof e.type)throw p(c);if("string"!=typeof e.asymmetricKeyType)throw p(c);if("function"!=typeof e.export)throw p(c)}}function d(e){if(!n.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw p("key must be a string, a buffer or an object")}function h(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function f(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function p(e){var t=[].slice.call(arguments,1),r=i.format.bind(i,e).apply(null,t);return new TypeError(r)}function m(e){var t;return t=e,n.isBuffer(t)||"string"==typeof t||(e=JSON.stringify(e)),e}function y(e){return function(t,r){!function(e){if(!n.isBuffer(e)){if("string"==typeof e)return e;if(!l)throw p(a);if("object"!=typeof e)throw p(a);if("secret"!==e.type)throw p(a);if("function"!=typeof e.export)throw p(a)}}(r),t=m(t);var o=s.createHmac("sha"+e,r);return h((o.update(t),o.digest("base64")))}}l&&(c+=" or a KeyObject",a+="or a KeyObject");var _="timingSafeEqual"in s?function(e,t){return e.byteLength===t.byteLength&&s.timingSafeEqual(e,t)}:function(e,t){return r||(r=ur()),r(e,t)};function g(e){return function(t,r,s){var o=y(e)(t,s);return _(n.from(r),n.from(o))}}function b(e){return function(t,r){d(r),t=m(t);var n=s.createSign("RSA-SHA"+e);return h((n.update(t),n.sign(r,"base64")))}}function E(e){return function(t,r,n){u(n),t=m(t),r=f(r);var o=s.createVerify("RSA-SHA"+e);return o.update(t),o.verify(n,r,"base64")}}function w(e){return function(t,r){d(r),t=m(t);var n=s.createSign("RSA-SHA"+e);return h((n.update(t),n.sign({key:r,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}function T(e){return function(t,r,n){u(n),t=m(t),r=f(r);var o=s.createVerify("RSA-SHA"+e);return o.update(t),o.verify({key:n,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function S(e){var t=b(e);return function(){var r=t.apply(null,arguments);return r=o.derToJose(r,"ES"+e)}}function A(e){var t=E(e);return function(r,n,s){return n=o.joseToDer(n,"ES"+e).toString("base64"),t(r,n,s)}}function O(){return function(){return""}}function I(){return function(e,t){return""===t}}t.exports=function(e){var t={hs:y,rs:b,ps:w,es:S,none:O},r={hs:g,rs:E,ps:T,es:A,none:I},n=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!n)throw p('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);var s=(n[1]||n[3]).toLowerCase(),o=n[2];return{sign:t[s](o),verify:r[s](o)}}}}),hr=A({"node_modules/jws/lib/tostring.js"(e,t){var r=v("buffer").Buffer;t.exports=function(e){return"string"==typeof e?e:"number"==typeof e||r.isBuffer(e)?e.toString():JSON.stringify(e)}}}),fr=A({"node_modules/jws/lib/sign-stream.js"(e,t){var r=Xt().Buffer,n=lr(),s=dr(),o=v("stream"),i=hr(),a=v("util");function c(e,t){return r.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function l(e){var t=e.header,r=e.payload,n=e.secret||e.privateKey,o=e.encoding,l=s(t.alg),u=function(e,t,r){r=r||"utf8";var n=c(i(e),"binary"),s=c(i(t),r);return a.format("%s.%s",n,s)}(t,r,o),d=l.sign(u,n);return a.format("%s.%s",u,d)}function u(e){var t=e.secret;if(t=null==(t=null==t?e.privateKey:t)?e.key:t,!0===/^hs/i.test(e.header.alg)&&null==t)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new n(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new n(e.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}a.inherits(u,o),u.prototype.sign=function(){try{var e=l({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},u.sign=l,t.exports=u}}),pr=A({"node_modules/jws/lib/verify-stream.js"(e,t){var r=Xt().Buffer,n=lr(),s=dr(),o=v("stream"),i=hr(),a=v("util"),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){if(function(e){return"[object Object]"===Object.prototype.toString.call(e)}(e))return e;try{return JSON.parse(e)}catch(e){return}}function u(e){var t=e.split(".",1)[0];return l(r.from(t,"base64").toString("binary"))}function d(e){return e.split(".")[2]}function h(e){return c.test(e)&&!!u(e)}function f(e,t,r){if(!t){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}var o=d(e=i(e)),a=function(e){return e.split(".",2).join(".")}(e);return s(t).verify(a,o,r)}function p(e,t){if(t=t||{},!h(e=i(e)))return null;var n=u(e);if(!n)return null;var s=function(e,t){t=t||"utf8";var n=e.split(".")[1];return r.from(n,"base64").toString(t)}(e);return("JWT"===n.typ||t.json)&&(s=JSON.parse(s,t.encoding)),{header:n,payload:s,signature:d(e)}}function m(e){var t=(e=e||{}).secret;if(t=null==(t=null==t?e.publicKey:t)?e.key:t,!0===/^hs/i.test(e.algorithm)&&null==t)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new n(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new n(e.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}a.inherits(m,o),m.prototype.verify=function(){try{var e=f(this.signature.buffer,this.algorithm,this.key.buffer),t=p(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},m.decode=p,m.isValid=h,m.verify=f,t.exports=m}}),mr=A({"node_modules/jws/index.js"(e){var t=fr(),r=pr();e.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],e.sign=t.sign,e.verify=r.verify,e.decode=r.decode,e.isValid=r.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new r(e)}}}),yr=A({"node_modules/google-auth-library/build/src/gtoken/jwsSign.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPayloadForJwsSign=r,e.getJwsSign=function(e){const n=r(e);return(0,t.sign)({header:{alg:"RS256"},payload:n,secret:e.key})};var t=mr();function r(e){const t=Math.floor((new Date).getTime()/1e3);return{iss:e.iss,scope:e.scope,aud:"https://oauth2.googleapis.com/token",exp:t+3600,iat:t,sub:e.sub,...e.additionalClaims}}}}),_r=A({"node_modules/google-auth-library/build/src/gtoken/getToken.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getToken=async function(e){if(!e.transporter)throw new Error("No transporter set.");try{const s=(e=>({method:"POST",url:r,data:new URLSearchParams({grant_type:n,assertion:(0,t.getJwsSign)(e)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}}))(e);return(await e.transporter.request(s)).data}catch(e){const t=e,r=t.response?.data;throw r?.error&&(t.message=`${r.error}: ${r.error_description}`),t}};var t=yr(),r="https://oauth2.googleapis.com/token",n="urn:ietf:params:oauth:grant-type:jwt-bearer"}}),gr=A({"node_modules/google-auth-library/build/src/gtoken/errorWithCode.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ErrorWithCode=void 0;var t=class extends Error{code;constructor(e,t){super(e),this.code=t}};e.ErrorWithCode=t}}),br=A({"node_modules/google-auth-library/build/src/gtoken/getCredentials.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getCredentials=async function(e){return d.create(e).getCredentials()};var t,r,n=v("path"),s=v("fs"),o=v("util"),i=gr(),a=s.readFile?(0,o.promisify)(s.readFile):async()=>{throw new i.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")};(r=t||(t={})).JSON=".json",r.DER=".der",r.CRT=".crt",r.PEM=".pem",r.P12=".p12",r.PFX=".pfx";var c=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){const e=await a(this.keyFilePath,"utf8");let t;try{t=JSON.parse(e)}catch(e){throw new Error(`Invalid JSON key file: ${e.message}`)}const r=t.private_key,n=t.client_email;if(!r||!n)throw new i.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:n}}},l=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await a(this.keyFilePath,"utf8")}}},u=class{async getCredentials(){throw new i.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}},d=class{static create(e){switch(n.extname(e)){case t.JSON:return new c(e);case t.DER:case t.CRT:case t.PEM:return new l(e);case t.P12:case t.PFX:return new u;default:throw new i.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}}}}),Er=A({"node_modules/google-auth-library/build/src/gtoken/tokenHandler.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.TokenHandler=void 0;var t=_r(),r=br();e.TokenHandler=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){const e=await(0,r.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;const e=(new Date).getTime(),t=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+t}hasExpired(){if((new Date).getTime(),this.token&&this.tokenExpiresAt){return(new Date).getTime()>=this.tokenExpiresAt}return!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,t.getToken)(this.tokenOptions);const e=await this.inFlightRequest;return this.token=e,this.tokenExpiresAt=(new Date).getTime()+1e3*(e.expires_in??0),e}finally{this.inFlightRequest=void 0}}}}}),wr=A({"node_modules/google-auth-library/build/src/gtoken/revokeToken.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.revokeToken=async function(e,t){const r="https://oauth2.googleapis.com/revoke?token="+e;return await t.request({url:r,retry:true})}}}),Tr=A({"node_modules/google-auth-library/build/src/gtoken/googleToken.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GoogleToken=void 0;var t=Lt(),r=Er(),n=wr();e.GoogleToken=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:e=>(0,t.request)(e)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),"object"==typeof this.tokenOptions.scope&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new r.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,t={forceRefresh:!1}){let r;"function"==typeof e?r=e:"object"==typeof e&&(t=e);const n=this.tokenHandler.getToken(t.forceRefresh??!1);return r&&n.then((e=>r(null,e)),r),n}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));const t=(0,n.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&t.then((()=>e()),e),this.tokenHandler=new r.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}}}),vr=A({"node_modules/google-auth-library/build/src/auth/jwtaccess.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.JWTAccess=void 0;var t=mr(),r=er(),n={alg:"RS256",typ:"JWT"};e.JWTAccess=class e{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new r.LRUCache({capacity:500,maxAge:36e5});constructor(e,t,r,n){this.email=e,this.key=t,this.keyId=r,this.eagerRefreshThresholdMillis=n??3e5}getCachedKey(e,t){let r=e;if(t&&Array.isArray(t)&&t.length?r=e?`${e}_${t.join("_")}`:`${t.join("_")}`:"string"==typeof t&&(r=e?`${e}_${t}`:t),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(r,s,o){const i=this.getCachedKey(r,o),a=this.cache.get(i),c=Date.now();if(a&&a.expiration-c>this.eagerRefreshThresholdMillis)return new Headers(a.headers);const l=Math.floor(Date.now()/1e3),u=e.getExpirationTime(l);let d;if(Array.isArray(o)&&(o=o.join(" ")),d=o?{iss:this.email,sub:this.email,scope:o,exp:u,iat:l}:{iss:this.email,sub:this.email,aud:r,exp:u,iat:l},s)for(const e in d)if(s[e])throw new Error(`The '${e}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);const h=this.keyId?{...n,kid:this.keyId}:n,f=Object.assign(d,s),p=t.sign({header:h,payload:f,secret:this.key}),m=new Headers({authorization:`Bearer ${p}`});return this.cache.set(i,{expiration:1e3*u,headers:m}),m}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then((()=>t()),t)}fromStreamAsync(e){return new Promise(((t,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let n="";e.setEncoding("utf8").on("data",(e=>n+=e)).on("error",r).on("end",(()=>{try{const e=JSON.parse(n);this.fromJSON(e),t()}catch(e){r(e)}}))}))}}}}),Sr=A({"node_modules/google-auth-library/build/src/auth/jwtclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.JWT=void 0;var t=Tr(),r=br(),n=vr(),s=or(),o=nr(),i=class e extends s.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(t){const r=new e(this);return r.scopes=t,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;const t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==o.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==o.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${o.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t){if(this.additionalClaims&&this.additionalClaims.target_audience){const{tokens:e}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${e.id_token}`}))}}{let t;this.access||(this.access=new n.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis)),this.hasUserScopes()?t=this.scopes:e||(t=this.defaultScopes);const r=this.useJWTAccessWithScope||this.universeDomain!==o.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,r?t:void 0);return{headers:this.addSharedMetadataHeaders(s)}}}return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){const r=new t.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.idToken}hasUserScopes(){return!!this.scopes&&this.scopes.length>0}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0)||!!(this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(!e)return this.authorizeAsync();this.authorizeAsync().then((t=>e(null,t)),e)}async authorizeAsync(){const e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){const e=this.createGToken(),t={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",t),{res:null,tokens:t}}createGToken(){return this.gtoken||(this.gtoken=new t.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then((()=>t()),t)}fromStreamAsync(e){return new Promise(((t,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let n="";e.setEncoding("utf8").on("error",r).on("data",(e=>n+=e)).on("end",(()=>{try{const e=JSON.parse(n);this.fromJSON(e),t()}catch(e){r(e)}}))}))}fromAPIKey(e){if("string"!=typeof e)throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){this.createGToken();const e=await(0,r.getCredentials)(this.keyFile);return{private_key:e.privateKey,client_email:e.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};e.JWT=i}}),Ar=A({"node_modules/google-auth-library/build/src/auth/refreshclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.UserRefreshClient=e.USER_REFRESH_ACCOUNT_TYPE=void 0;var t=or(),r=nr();e.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var n=class e extends t.OAuth2Client{_refreshToken;constructor(e,t,r,n,s){const o=e&&"object"==typeof e?e:{clientId:e,clientSecret:t,refreshToken:r,eagerRefreshThresholdMillis:n,forceRefreshOnFailure:s};super(o),this._refreshToken=o.refreshToken,this.credentials.refresh_token=o.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(t){const n={...e.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:t}),responseType:"json"};r.AuthClient.setMethodName(n,"fetchIdToken");return(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if("authorized_user"!==e.type)throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then((()=>t()),t)}async fromStreamAsync(e){return new Promise(((t,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let n="";e.setEncoding("utf8").on("error",r).on("data",(e=>n+=e)).on("end",(()=>{try{const e=JSON.parse(n);return this.fromJSON(e),t()}catch(e){return r(e)}}))}))}static fromJSON(t){const r=new e;return r.fromJSON(t),r}};e.UserRefreshClient=n}}),Or=A({"node_modules/google-auth-library/build/src/auth/impersonated.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Impersonated=e.IMPERSONATED_ACCOUNT_TYPE=void 0;var t=or(),r=Lt(),n=er();e.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var s=class e extends t.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new t.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600;if(!!(0,n.originalOrCamelOptions)(e).get("universe_domain")){if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`)}else this.universeDomain=this.sourceClient.universeDomain;this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(t){await this.sourceClient.getAccessToken();const r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,s={delegates:this.delegates,payload:Buffer.from(t).toString("base64")};return(await this.sourceClient.request({...e.RETRY_CONFIG,url:n,data:s,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();const t="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${t}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},s=await this.sourceClient.request({...e.RETRY_CONFIG,url:r,data:n,method:"POST"}),o=s.data;return this.credentials.access_token=o.accessToken,this.credentials.expiry_date=Date.parse(o.expireTime),{tokens:this.credentials,res:s}}catch(e){if(!(e instanceof Error))throw e;let t=0,n="";throw e instanceof r.GaxiosError&&(t=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),t&&n?(e.message=`${t}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(t,r){await this.sourceClient.getAccessToken();const n=`projects/-/serviceAccounts/${this.targetPrincipal}`,s=`${this.endpoint}/v1/${n}:generateIdToken`,o={delegates:this.delegates,audience:t,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...e.RETRY_CONFIG,url:s,data:o,method:"POST"})).data.token}};e.Impersonated=s}}),Ir=A({"node_modules/google-auth-library/build/src/auth/oauth2common.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.OAuthClientAuthHandler=void 0,e.getErrorFromOAuthErrorResponse=function(e,t){const r=e.error,n=e.error_description,s=e.error_uri;let o=`Error code ${r}`;void 0!==n&&(o+=`: ${n}`);void 0!==s&&(o+=` - ${s}`);const i=new Error(o);if(t){const e=Object.keys(t);t.stack&&e.push("stack"),e.forEach((e=>{"message"!==e&&Object.defineProperty(i,e,{value:t[e],writable:!1,enumerable:!0})}))}return i};var t=Lt(),r=Jt(),n=["PUT","POST","PATCH"];e.OAuthClientAuthHandler=class{#w=(0,r.createCrypto)();#T;transporter;constructor(e){e&&"clientId"in e?(this.#T=e,this.transporter=new t.Gaxios):(this.#T=e?.clientAuthentication,this.transporter=e?.transporter||new t.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=t.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=t.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if("basic"===this.#T?.confidentialClientType){e.headers=t.Gaxios.mergeHeaders(e.headers);const r=this.#T.clientId,n=this.#T.clientSecret||"",s=this.#w.encodeBase64StringUtf8(`${r}:${n}`);t.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if("request-body"===this.#T?.confidentialClientType){const t=(e.method||"GET").toUpperCase();if(!n.includes(t))throw new Error(`${t} HTTP method does not support ${this.#T.confidentialClientType} client authentication`);const r=new Headers(e.headers).get("content-type");if(r?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){const t=new URLSearchParams(e.data??"");t.append("client_id",this.#T.clientId),t.append("client_secret",this.#T.clientSecret||""),e.data=t}else{if(!r?.startsWith("application/json"))throw new Error(`${r} content-types are not supported with ${this.#T.confidentialClientType} client authentication`);e.data=e.data||{},Object.assign(e.data,{client_id:this.#T.clientId,client_secret:this.#T.clientSecret||""})}}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}}}),Cr=A({"node_modules/google-auth-library/build/src/auth/stscredentials.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.StsCredentials=void 0;var t=Lt(),r=nr(),n=Ir(),s=er(),o=class e extends n.OAuthClientAuthHandler{#v;constructor(e={tokenExchangeEndpoint:""},t){("object"!=typeof e||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:t}),super(e),this.#v=e.tokenExchangeEndpoint}async exchangeToken(o,i,a){const c={grant_type:o.grantType,resource:o.resource,audience:o.audience,scope:o.scope?.join(" "),requested_token_type:o.requestedTokenType,subject_token:o.subjectToken,subject_token_type:o.subjectTokenType,actor_token:o.actingParty?.actorToken,actor_token_type:o.actingParty?.actorTokenType,options:a&&JSON.stringify(a)},l={...e.RETRY_CONFIG,url:this.#v.toString(),method:"POST",headers:i,data:new URLSearchParams((0,s.removeUndefinedValuesInObject)(c)),responseType:"json"};r.AuthClient.setMethodName(l,"exchangeToken"),this.applyClientAuthenticationOptions(l);try{const e=await this.transporter.request(l),t=e.data;return t.res=e,t}catch(e){if(e instanceof t.GaxiosError&&e.response)throw(0,n.getErrorFromOAuthErrorResponse)(e.response.data,e);throw e}}};e.StsCredentials=o}}),Rr=A({"node_modules/google-auth-library/build/src/auth/baseexternalclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.BaseExternalAccountClient=e.CLOUD_RESOURCE_MANAGER=e.EXTERNAL_ACCOUNT_TYPE=e.EXPIRATION_TIME_OFFSET=void 0;var t=Lt(),r=v("stream"),n=nr(),s=Cr(),o=er(),i=rr(),a="https://www.googleapis.com/auth/cloud-platform";e.EXPIRATION_TIME_OFFSET=3e5,e.EXTERNAL_ACCOUNT_TYPE="external_account",e.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var c=class c extends n.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#S=null;constructor(t){super(t);const r=(0,o.originalOrCamelOptions)(t),n=r.get("type");if(n&&n!==e.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${e.EXTERNAL_ACCOUNT_TYPE}" type but received "${t.type}"`);const i=r.get("client_id"),c=r.get("client_secret");this.tokenUrl=r.get("token_url")??"https://sts.{universeDomain}/v1/token".replace("{universeDomain}",this.universeDomain);const l=r.get("subject_token_type"),u=r.get("workforce_pool_user_project"),d=r.get("service_account_impersonation_url"),h=r.get("service_account_impersonation"),f=(0,o.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i&&(this.clientAuth={confidentialClientType:"basic",clientId:i,clientSecret:c}),this.stsCredential=new s.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[a],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=l,this.workforcePoolUserProject=u;const p=new RegExp("//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+");if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=d,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=3600),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);const e=/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl);return e?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return this.cachedAccessToken&&!this.isExpired(this.cachedAccessToken)||await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then((e=>t(null,e)),(e=>t(e,e.response)))}async getProjectId(){const e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){const t=await this.getRequestHeaders(),r={...c.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};n.AuthClient.setMethodName(r,"getProjectId");const s=await this.transporter.request(r);return this.projectId=s.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let s;try{const r=await this.getRequestHeaders();e.headers=t.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r),s=await this.transporter.request(e)}catch(t){const s=t.response;if(s){const t=s.status,o=s.config.data instanceof r.Readable;if(!n&&(401===t||403===t)&&!o&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw t}return s}async refreshAccessTokenAsync(){this.#S=this.#S||this.#A();try{return await this.#S}finally{this.#S=null}}async#A(){const e=await this.retrieveSubjectToken(),t={grantType:"urn:ietf:params:oauth:grant-type:token-exchange",audience:this.audience,requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[a]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,n=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(t,n,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:(new Date).getTime()+1e3*s.expires_in,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){const t=e.match(/\/projects\/([^/]+)/);return t?t[1]:null}async getImpersonatedAccessToken(e){const t={...c.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};n.AuthClient.setMethodName(t,"getImpersonatedAccessToken");const r=await this.transporter.request(t),s=r.data;return{access_token:s.accessToken,expiry_date:new Date(s.expireTime).getTime(),res:r}}isExpired(e){const t=(new Date).getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}getScopesArray(){return"string"==typeof this.scopes?[this.scopes]:this.scopes||[a]}getMetricsHeaderValue(){const e=process.version.replace(/^v/,""),t=void 0!==this.serviceAccountImpersonationUrl,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${i.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};e.BaseExternalAccountClient=c}}),kr=A({"node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.FileSubjectTokenSupplier=void 0;var t=v("util"),r=v("fs"),n=(0,t.promisify)(r.readFile??(()=>{})),s=(0,t.promisify)(r.realpath??(()=>{})),o=(0,t.promisify)(r.lstat??(()=>{}));e.FileSubjectTokenSupplier=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e,t=this.filePath;try{if(t=await s(t),!(await o(t)).isFile())throw new Error}catch(e){throw e instanceof Error&&(e.message=`The file at ${t} does not exist, or it is not a file. ${e.message}`),e}const r=await n(t,{encoding:"utf8"});if("text"===this.formatType)e=r;else if("json"===this.formatType&&this.subjectTokenFieldName){e=JSON.parse(r)[this.subjectTokenFieldName]}if(!e)throw new Error("Unable to parse the subject_token from the credential_source file");return e}}}}),Nr=A({"node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.UrlSubjectTokenSupplier=void 0;var t=nr();e.UrlSubjectTokenSupplier=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){const r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};let n;if(t.AuthClient.setMethodName(r,"getSubjectToken"),"text"===this.formatType){n=(await e.transporter.request(r)).data}else if("json"===this.formatType&&this.subjectTokenFieldName){n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]}if(!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}}}}),Pr=A({"node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CertificateSubjectTokenSupplier=e.InvalidConfigurationError=e.CertificateSourceUnavailableError=e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var t=er(),r=v("fs"),n=v("crypto"),s=v("https");e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var o=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};e.CertificateSourceUnavailableError=o;var i=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};e.InvalidConfigurationError=i;e.CertificateSubjectTokenSupplier=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new i("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new i("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new i("Cannot create mTLS Agent with missing certificate or key");return new s.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#O();const{certPath:e,keyPath:t}=await this.#I();return({cert:this.cert,key:this.key}=await this.#C(e,t)),await this.#R(this.cert)}async#O(){const r=this.certificateConfigPath;if(r){if(await(0,t.isValidFile)(r))return r;throw new o(`Provided certificate config path is invalid: ${r}`)}const n=process.env[e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,t.isValidFile)(n))return n;throw new o(`Path from environment variable "${e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}const s=(0,t.getWellKnownCertificateConfigFileLocation)();if(await(0,t.isValidFile)(s))return s;throw new o(`Could not find certificate configuration file. Searched override path, the "${e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${s}).`)}async#I(){const e=this.certificateConfigPath;let t;try{t=await r.promises.readFile(e,"utf8")}catch(t){throw new o(`Failed to read certificate config file at: ${e}`)}try{const r=JSON.parse(t),n=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!n||!s)throw new i(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:n,keyPath:s}}catch(t){if(t instanceof i)throw t;throw new i(`Failed to parse certificate config from ${e}: ${t.message}`)}}async#C(e,t){let s,i;try{s=await r.promises.readFile(e),new n.X509Certificate(s)}catch(t){const r=t instanceof Error?t.message:String(t);throw new o(`Failed to read certificate file at ${e}: ${r}`)}try{i=await r.promises.readFile(t),(0,n.createPrivateKey)(i)}catch(e){const r=e instanceof Error?e.message:String(e);throw new o(`Failed to read private key file at ${t}: ${r}`)}return{cert:s,key:i}}async#R(e){const t=new n.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{const e=await r.promises.readFile(this.trustChainPath,"utf8"),s=(e.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map(((e,t)=>{try{return new n.X509Certificate(e)}catch(e){const r=e instanceof Error?e.message:String(e);throw new i(`Failed to parse certificate at index ${t} in trust chain file ${this.trustChainPath}: ${r}`)}})),o=s.findIndex((e=>t.raw.equals(e.raw)));let a;if(-1===o)a=[t,...s];else{if(0!==o)throw new i(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${o}).`);a=s}return JSON.stringify(a.map((e=>e.raw.toString("base64"))))}catch(e){if(e instanceof i)throw e;const t=e instanceof Error?e.message:String(e);throw new o(`Failed to process certificate chain from ${this.trustChainPath}: ${t}`)}}}}}),xr=A({"node_modules/google-auth-library/build/src/auth/identitypoolclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.IdentityPoolClient=void 0;var t=Rr(),r=er(),n=kr(),s=Nr(),o=Pr(),i=Cr(),a=Lt(),c=class e extends t.BaseExternalAccountClient{subjectTokenSupplier;constructor(t){super(t);const i=(0,r.originalOrCamelOptions)(t),a=i.get("credential_source"),c=i.get("subject_token_supplier");if(!a&&!c)throw new Error("A credential source or subject token supplier must be specified.");if(a&&c)throw new Error("Only one of credential source or subject token supplier can be specified.");if(c)this.subjectTokenSupplier=c,this.credentialSourceType="programmatic";else{const t=(0,r.originalOrCamelOptions)(a),i=(0,r.originalOrCamelOptions)(t.get("format")),c=i.get("type")||"text",l=i.get("subject_token_field_name");if("json"!==c&&"text"!==c)throw new Error(`Invalid credential_source format "${c}"`);if("json"===c&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");const u=t.get("file"),d=t.get("url"),h=t.get("certificate"),f=t.get("headers");if(u&&d||d&&h||u&&h)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(u)this.credentialSourceType="file",this.subjectTokenSupplier=new n.FileSubjectTokenSupplier({filePath:u,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new s.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:f,additionalGaxiosOptions:e.RETRY_CONFIG});else{if(!h)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');{this.credentialSourceType="certificate";const e=new o.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:h.use_default_certificate_config,certificateConfigLocation:h.certificate_config_location,trustChainPath:h.trust_chain_path});this.subjectTokenSupplier=e}}}}async retrieveSubjectToken(){const e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof o.CertificateSubjectTokenSupplier){const e=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new i.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new a.Gaxios({agent:e})}),this.transporter=new a.Gaxios({...this.transporter.defaults||{},agent:e})}return e}};e.IdentityPoolClient=c}}),Dr=A({"node_modules/google-auth-library/build/src/auth/awsrequestsigner.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwsRequestSigner=void 0;var t=Lt(),r=Jt(),n="AWS4-HMAC-SHA256",s="aws4_request";async function o(e,t,r){return await e.signWithHmacSha256(t,r)}e.AwsRequestSigner=class{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=(0,r.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');const i="object"==typeof e.data?JSON.stringify(e.data):e.data,a=e.url,c=e.method||"GET",l=e.body||i,u=e.headers,d=await this.getCredentials(),h=new URL(a);if("string"!=typeof l&&void 0!==l)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${l}`);const f=await async function(e){const i=t.Gaxios.mergeHeaders(e.additionalAmzHeaders),a=e.requestPayload||"",c=e.host.split(".")[0],l=new Date,u=l.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),d=l.toISOString().replace(/[-]/g,"").replace(/T.*/,"");e.securityCredentials.token&&i.set("x-amz-security-token",e.securityCredentials.token);const h=t.Gaxios.mergeHeaders({host:e.host},i.has("date")?{}:{"x-amz-date":u},i);let f="";const p=[...h.keys()].sort();p.forEach((e=>{f+=`${e}:${h.get(e)}\n`}));const m=p.join(";"),y=await e.crypto.sha256DigestHex(a),_=`${e.method.toUpperCase()}\n${e.canonicalUri}\n${e.canonicalQuerystring}\n${f}\n${m}\n${y}`,g=`${d}/${e.region}/${c}/${s}`,b=`${n}\n${u}\n${g}\n`+await e.crypto.sha256DigestHex(_),E=await async function(e,t,r,n,s){const i=await o(e,`AWS4${t}`,r),a=await o(e,i,n),c=await o(e,a,s);return await o(e,c,"aws4_request")}(e.crypto,e.securityCredentials.secretAccessKey,d,e.region,c),w=await o(e.crypto,E,b),T=`${n} Credential=${e.securityCredentials.accessKeyId}/${g}, SignedHeaders=${m}, Signature=${(0,r.fromArrayBufferToHex)(w)}`;return{amzDate:i.has("date")?void 0:u,authorizationHeader:T,canonicalQuerystring:e.canonicalQuerystring}}({crypto:this.crypto,host:h.host,canonicalUri:h.pathname,canonicalQuerystring:h.search.slice(1),method:c,region:this.region,securityCredentials:d,requestPayload:l,additionalAmzHeaders:u}),p=t.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:h.host},u||{});d.token&&t.Gaxios.mergeHeaders(p,{"x-amz-security-token":d.token});const m={url:a,method:c,headers:p};return void 0!==l&&(m.body=l),m}}}}),Ur=A({"node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultAwsSecurityCredentialsSupplier=void 0;var t=nr();e.DefaultAwsSecurityCredentialsSupplier=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#k)return this.#k;const r=new Headers;if(!this.#k&&this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#N(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');const n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:r};t.AuthClient.setMethodName(n,"getAwsRegion");const s=await e.transporter.request(n);return s.data.substr(0,s.data.length-1)}async getAwsSecurityCredentials(e){if(this.#P)return this.#P;const t=new Headers;this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#N(e.transporter));const r=await this.#x(t,e.transporter),n=await this.#D(r,t,e.transporter);return{accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,token:n.Token}}async#N(e){const r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};t.AuthClient.setMethodName(r,"#getImdsV2SessionToken");return(await e.request(r)).data}async#x(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');const n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};t.AuthClient.setMethodName(n,"#getAwsRoleName");return(await r.request(n)).data}async#D(e,r,n){const s={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r,responseType:"json"};t.AuthClient.setMethodName(s,"#retrieveAwsSecurityCredentials");return(await n.request(s)).data}get#k(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#P(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}}}}),Lr=A({"node_modules/google-auth-library/build/src/auth/awsclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwsClient=void 0;var t=Dr(),r=Rr(),n=Ur(),s=er(),o=Lt(),i=class e extends r.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#U="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(t){super(t);const r=(0,s.originalOrCamelOptions)(t),o=r.get("credential_source"),i=r.get("aws_security_credentials_supplier");if(!o&&!i)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(o&&i)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(i)this.awsSecurityCredentialsSupplier=i,this.regionalCredVerificationUrl=e.#U,this.credentialSourceType="programmatic";else{const e=(0,s.originalOrCamelOptions)(o);this.environmentId=e.get("environment_id");const t=e.get("region_url"),r=e.get("url"),i=e.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new n.DefaultAwsSecurityCredentialsSupplier({regionUrl:t,securityCredentialsUrl:r,imdsV2SessionTokenUrl:i}),this.regionalCredVerificationUrl=e.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){const e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(1!==parseInt(e[2],10))throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new t.AwsRequestSigner((async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext)),this.region));const r=await this.awsRequestSigner.getRequestOptions({...e.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return o.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},r.headers).forEach(((e,t)=>n.push({key:t,value:e}))),encodeURIComponent(JSON.stringify({url:r.url,method:r.method,headers:n}))}};e.AwsClient=i}}),jr=A({"node_modules/google-auth-library/build/src/auth/executable-response.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.InvalidSubjectTokenError=e.InvalidMessageFieldError=e.InvalidCodeFieldError=e.InvalidTokenTypeFieldError=e.InvalidExpirationTimeFieldError=e.InvalidSuccessFieldError=e.InvalidVersionFieldError=e.ExecutableResponseError=e.ExecutableResponse=void 0;var t="urn:ietf:params:oauth:token-type:saml2",r="urn:ietf:params:oauth:token-type:id_token",n="urn:ietf:params:oauth:token-type:jwt";e.ExecutableResponse=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new o("Executable response must contain a 'version' field.");if(void 0===e.success)throw new i("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==t&&this.tokenType!==r&&this.tokenType!==n)throw new a(`Executable response must contain a 'token_type' field when successful and it must be one of ${r}, ${n}, or ${t}.`);if(this.tokenType===t){if(!e.saml_response)throw new u(`Executable response must contain a 'saml_response' field when token_type=${t}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new u(`Executable response must contain a 'id_token' field when token_type=${r} or ${n}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new c("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new l("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return void 0!==this.expirationTime&&this.expirationTime<Math.round(Date.now()/1e3)}};var s=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};e.ExecutableResponseError=s;var o=class extends s{};e.InvalidVersionFieldError=o;var i=class extends s{};e.InvalidSuccessFieldError=i;e.InvalidExpirationTimeFieldError=class extends s{};var a=class extends s{};e.InvalidTokenTypeFieldError=a;var c=class extends s{};e.InvalidCodeFieldError=c;var l=class extends s{};e.InvalidMessageFieldError=l;var u=class extends s{};e.InvalidSubjectTokenError=u}}),Mr=A({"node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.PluggableAuthHandler=e.ExecutableError=void 0;var t=jr(),r=v("child_process"),n=v("fs"),s=class extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}};e.ExecutableError=s;e.PluggableAuthHandler=class e{commandComponents;timeoutMillis;outputFile;constructor(t){if(!t.command)throw new Error("No command provided.");if(this.commandComponents=e.parseCommand(t.command),this.timeoutMillis=t.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=t.outputFile}retrieveResponseFromExecutable(e){return new Promise(((n,o)=>{const i=r.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}});let a="";i.stdout.on("data",(e=>{a+=e})),i.stderr.on("data",(e=>{a+=e}));const c=setTimeout((()=>(i.removeAllListeners(),i.kill(),o(new Error("The executable failed to finish within the timeout specified.")))),this.timeoutMillis);i.on("close",(e=>{if(clearTimeout(c),0!==e)return o(new s(a,e.toString()));try{const e=JSON.parse(a),r=new t.ExecutableResponse(e);return n(r)}catch(e){return e instanceof t.ExecutableResponseError?o(e):o(new t.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}}))}))}async retrieveCachedResponse(){if(!this.outputFile||0===this.outputFile.length)return;let e;try{e=await n.promises.realpath(this.outputFile)}catch{return}if(!(await n.promises.lstat(e)).isFile())return;const r=await n.promises.readFile(e,{encoding:"utf8"});if(""!==r)try{const e=JSON.parse(r);return new t.ExecutableResponse(e).isValid()?new t.ExecutableResponse(e):void 0}catch(e){if(e instanceof t.ExecutableResponseError)throw e;throw new t.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){const t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let e=0;e<t.length;e++)'"'===t[e][0]&&'"'===t[e].slice(-1)&&(t[e]=t[e].slice(1,-1));return t}}}}),Fr=A({"node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.PluggableAuthClient=e.ExecutableError=void 0;var t=Rr(),r=jr(),n=Mr(),s=Mr();Object.defineProperty(e,"ExecutableError",{enumerable:!0,get:function(){return s.ExecutableError}});var o=12e4,i=class extends t.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(void 0===e.credential_source.executable.timeout_millis)this.timeoutMillis=3e4;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<5e3||this.timeoutMillis>o)throw new Error("Timeout must be between 5000 and 120000 milliseconds.");this.outputFile=e.credential_source.executable.output_file,this.handler=new n.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if("1"!==process.env.GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES)throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){const t=new Map;t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);const r=this.getServiceAccountEmail();r&&t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>1)throw new Error("Version of executable is not currently supported, maximum supported version is 1.");if(!e.success)throw new n.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new r.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};e.PluggableAuthClient=i}}),Br=A({"node_modules/google-auth-library/build/src/auth/externalclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ExternalAccountClient=void 0;var t=Rr(),r=xr(),n=Lr(),s=Fr();e.ExternalAccountClient=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===t.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new n.AwsClient(e):e.credential_source?.executable?new s.PluggableAuthClient(e):new r.IdentityPoolClient(e):null}}}}),Gr=A({"node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ExternalAccountAuthorizedUserClient=e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var t=nr(),r=Ir(),n=Lt(),s=v("stream"),o=Rr();e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var i=class e extends r.OAuthClientAuthHandler{#L;constructor(e){super(e),this.#L=e.tokenRefreshEndpoint}async refreshToken(s,o){const i={...e.RETRY_CONFIG,url:this.#L,method:"POST",headers:o,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:s}),responseType:"json"};t.AuthClient.setMethodName(i,"refreshToken"),this.applyClientAuthenticationOptions(i);try{const e=await this.transporter.request(i),t=e.data;return t.res=e,t}catch(e){if(e instanceof n.GaxiosError&&e.response)throw(0,r.getErrorFromOAuthErrorResponse)(e.response.data,e);throw e}}},a=class extends t.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;const t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new i({tokenRefreshEndpoint:e.token_url??"https://sts.{universeDomain}/v1/oauthtoken".replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,this.eagerRefreshThresholdMillis="number"!=typeof e?.eagerRefreshThresholdMillis?o.EXPIRATION_TIME_OFFSET:e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return this.cachedAccessToken&&!this.isExpired(this.cachedAccessToken)||await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then((e=>t(null,e)),(e=>t(e,e.response)))}async requestAsync(e,t=!1){let r;try{const t=await this.getRequestHeaders();e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),r=await this.transporter.request(e)}catch(r){const n=r.response;if(n){const r=n.status,o=n.config.data instanceof s.Readable;if(!t&&(401===r||403===r)&&!o&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw r}return r}async refreshAccessTokenAsync(){const e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:(new Date).getTime()+1e3*e.expires_in,res:e.res},void 0!==e.refresh_token&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){const t=(new Date).getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}};e.ExternalAccountAuthorizedUserClient=a}}),Hr=A({"node_modules/google-auth-library/build/src/auth/googleauth.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GoogleAuth=e.GoogleAuthExceptionMessages=void 0;var t=v("child_process"),r=v("fs"),n=Lt(),s=Wt(),o=v("os"),i=v("path"),a=Jt(),c=ir(),l=ar(),u=cr(),d=Sr(),h=Ar(),f=Or(),p=Br(),m=Rr(),y=nr(),_=Gr(),g=er();e.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:"Unable to detect a Project Id in the current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_CREDENTIALS_FOUND:"Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:"Unable to detect a Universe Domain in the current environment.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"};e.GoogleAuth=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#j=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(t={}){if(this._cachedProjectId=t.projectId||null,this.cachedCredential=t.authClient||null,this.keyFilename=t.keyFilename||t.keyFile,this.scopes=t.scopes,this.clientOptions=t.clientOptions||{},this.jsonContent=t.credentials||null,this.apiKey=t.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(e.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);t.universeDomain&&(this.clientOptions.universeDomain=t.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(!e)return this.getProjectIdAsync();this.getProjectIdAsync().then((t=>e(null,t)),e)}async getProjectIdOptional(){try{return await this.getProjectId()}catch(t){if(t instanceof Error&&t.message===e.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw t}}async findAndCacheProjectId(){let t=null;if(t||=await this.getProductionProjectId(),t||=await this.getFileProjectId(),t||=await this.getDefaultServiceProjectId(),t||=await this.getGCEProjectId(),t||=await this.getExternalAccountClientProjectId(),t)return this._cachedProjectId=t,t;throw new Error(e.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await s.universe("universe-domain"),e||=y.DEFAULT_UNIVERSE}catch(t){if(!t||404!==t?.response?.status)throw t;e=y.DEFAULT_UNIVERSE}return e}async getUniverseDomain(){let e=(0,g.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=y.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let r;if("function"==typeof e?t=e:r=e,!t)return this.getApplicationDefaultAsync(r);this.getApplicationDefaultAsync(r).then((e=>t(null,e.credential,e.projectId)),t)}async getApplicationDefaultAsync(t={}){if(this.cachedCredential)return await this.#M(this.cachedCredential,null);let r;if(r=await this._tryGetApplicationCredentialsFromEnvironmentVariable(t),r)return r instanceof d.JWT?r.scopes=this.scopes:r instanceof m.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#M(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(t),r)return r instanceof d.JWT?r.scopes=this.scopes:r instanceof m.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#M(r);if(await this._checkIsGCE())return t.scopes=this.getAnyScopes(),await this.#M(new c.Compute(t));throw new Error(e.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#M(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){const r=await this.getProjectIdOptional();return t&&(e.quotaProjectId=t),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return void 0===this.checkIsGCE&&(this.checkIsGCE=s.getGCPResidency()||await s.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){const t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||0===t.length)return null;try{return this._getApplicationCredentialsFromFilePath(t,e)}catch(e){throw e instanceof Error&&(e.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`),e}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=null;if(this._isWindows())t=process.env.APPDATA;else{const e=process.env.HOME;e&&(t=i.join(e,".config"))}if(t&&(t=i.join(t,"gcloud","application_default_credentials.json"),r.existsSync(t)||(t=null)),!t)return null;return await this._getApplicationCredentialsFromFilePath(t,e)}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||0===e.length)throw new Error("The file path is invalid.");try{if(e=r.realpathSync(e),!r.lstatSync(e).isFile())throw new Error}catch(t){throw t instanceof Error&&(t.message=`The file at ${e} does not exist, or it is not a file. ${t.message}`),t}const n=r.createReadStream(e);return this.fromStream(n,t)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==f.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${f.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");const t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);const r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);const n=(this.scopes||e.scopes||this.defaultScopes)??[];return new f.Impersonated({...e,sourceClient:t,targetPrincipal:r,targetScopes:Array.isArray(n)?n:[n]})}fromJSON(e,t={}){let r;const n=(0,g.originalOrCamelOptions)(t).get("universe_domain");return e.type===h.USER_REFRESH_ACCOUNT_TYPE?(r=new h.UserRefreshClient(t),r.fromJSON(e)):e.type===f.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===m.EXTERNAL_ACCOUNT_TYPE?(r=p.ExternalAccountClient.fromJSON({...e,...t}),r.scopes=this.getAnyScopes()):e.type===_.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new _.ExternalAccountAuthorizedUserClient({...e,...t}):(t.scopes=this.scopes,r=new d.JWT(t),this.setGapicJWTValues(r),r.fromJSON(e)),n&&(r.universeDomain=n),r}_cacheClientFromJSON(e,t){const r=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,t={},r){let n={};if("function"==typeof t?r=t:n=t,!r)return this.fromStreamAsync(e,n);this.fromStreamAsync(e,n).then((e=>r(null,e)),r)}fromStreamAsync(e,t){return new Promise(((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");const s=[];e.setEncoding("utf8").on("error",n).on("data",(e=>s.push(e))).on("end",(()=>{try{try{const e=JSON.parse(s.join("")),n=this._cacheClientFromJSON(e,t);return r(n)}catch(e){if(!this.keyFilename)throw e;const t=new d.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=t,this.setGapicJWTValues(t),r(t)}}catch(e){return n(e)}}))}))}fromAPIKey(e,t={}){return new d.JWT({...t,apiKey:e})}_isWindows(){const e=o.platform();return!!(e&&e.length>=3&&"win"===e.substring(0,3).toLowerCase())}async getDefaultServiceProjectId(){return new Promise((e=>{(0,t.exec)("gcloud config config-helper --format json",((t,r)=>{if(!t&&r)try{const t=JSON.parse(r).configuration.properties.core.project;return void e(t)}catch(e){}e(null)}))}))}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){const e=await this.getClient();if(e&&e.projectId)return e.projectId}const e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==m.EXTERNAL_ACCOUNT_TYPE)return null;const e=await this.getClient();return await e.getProjectId()}async getGCEProjectId(){try{return await s.project("project-id")}catch(e){return null}}getCredentials(e){if(!e)return this.getCredentialsAsync();this.getCredentialsAsync().then((t=>e(null,t)),e)}async getCredentialsAsync(){const t=await this.getClient();if(t instanceof f.Impersonated)return{client_email:t.getTargetPrincipal()};if(t instanceof m.BaseExternalAccountClient){const e=t.getServiceAccountEmail();if(e)return{client_email:e,universe_domain:t.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){const[e,t]=await Promise.all([s.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:e,universe_domain:t}}throw new Error(e.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#j=this.#j||this.#F();try{return await this.#j}finally{this.#j=null}}async#F(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){const e=i.resolve(this.keyFilename),t=r.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}if(this.apiKey){const e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;const{credential:t}=await this.#M(e);return t}{const{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){const t=await this.getClient();if(!("fetchIdToken"in t))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new l.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){const e=await this.getClient();return(await e.getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){const t=e.url,r=await this.getClient(),s=await r.getRequestHeaders(t);return e.headers=n.Gaxios.mergeHeaders(e.headers,s),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,u.getEnv)()}async sign(e,t){const r=await this.getClient(),n=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${n}/v1/projects/-/serviceAccounts/`,r instanceof f.Impersonated){return(await r.sign(e)).signedBlob}const s=(0,a.createCrypto)();if(r instanceof d.JWT&&r.key){return await s.sign(r.key,e)}const o=await this.getCredentials();if(!o.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,o.client_email,e,t)}async signBlob(e,t,r,n){const s=new URL(n+`${t}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}}}),qr=A({"node_modules/google-auth-library/build/src/auth/iam.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.IAMAuth=void 0;e.IAMAuth=class{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}}}),$r=A({"node_modules/google-auth-library/build/src/auth/downscopedclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DownscopedClient=e.EXPIRATION_TIME_OFFSET=e.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var t=Lt(),r=v("stream"),n=nr(),s=Cr();e.MAX_ACCESS_BOUNDARY_RULES_COUNT=10,e.EXPIRATION_TIME_OFFSET=3e5;var o=class extends n.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(t,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(t instanceof n.AuthClient?{}:t),t instanceof n.AuthClient?(this.authClient=t,this.credentialAccessBoundary=r):(this.authClient=t.authClient,this.credentialAccessBoundary=t.credentialAccessBoundary),0===this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>e.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${e.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(const e of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(0===e.availablePermissions.length)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new s.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return this.cachedDownscopedAccessToken&&!this.isExpired(this.cachedDownscopedAccessToken)||await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then((e=>t(null,e)),(e=>t(e,e.response)))}async requestAsync(e,n=!1){let s;try{const r=await this.getRequestHeaders();e.headers=t.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r),s=await this.transporter.request(e)}catch(t){const s=t.response;if(s){const t=s.status,o=s.config.data instanceof r.Readable;if(!n&&(401===t||403===t)&&!o&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw t}return s}async refreshAccessTokenAsync(){const e={grantType:"urn:ietf:params:oauth:grant-type:token-exchange",requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:(await this.authClient.getAccessToken()).token,subjectTokenType:"urn:ietf:params:oauth:token-type:access_token"},t=await this.stsCredential.exchangeToken(e,void 0,this.credentialAccessBoundary),r=this.authClient.credentials?.expiry_date||null,n=t.expires_in?(new Date).getTime()+1e3*t.expires_in:r;return this.cachedDownscopedAccessToken={access_token:t.access_token,expiry_date:n,res:t.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){const t=(new Date).getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}};e.DownscopedClient=o}}),Wr=A({"node_modules/google-auth-library/build/src/auth/passthrough.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.PassThroughClient=void 0;var t=nr(),r=class extends t.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};e.PassThroughClient=r}}),Vr=A({"node_modules/google-auth-library/build/src/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.GoogleAuth=e.auth=e.PassThroughClient=e.ExternalAccountAuthorizedUserClient=e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=e.ExecutableError=e.PluggableAuthClient=e.DownscopedClient=e.BaseExternalAccountClient=e.ExternalAccountClient=e.IdentityPoolClient=e.AwsRequestSigner=e.AwsClient=e.UserRefreshClient=e.LoginTicket=e.ClientAuthentication=e.OAuth2Client=e.CodeChallengeMethod=e.Impersonated=e.JWT=e.JWTAccess=e.IdTokenClient=e.IAMAuth=e.GCPEnv=e.Compute=e.DEFAULT_UNIVERSE=e.AuthClient=e.gaxios=e.gcpMetadata=void 0;var n=Hr();Object.defineProperty(e,"GoogleAuth",{enumerable:!0,get:function(){return n.GoogleAuth}}),e.gcpMetadata=Wt(),e.gaxios=Lt();var s=nr();Object.defineProperty(e,"AuthClient",{enumerable:!0,get:function(){return s.AuthClient}}),Object.defineProperty(e,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return s.DEFAULT_UNIVERSE}});var o=ir();Object.defineProperty(e,"Compute",{enumerable:!0,get:function(){return o.Compute}});var i=cr();Object.defineProperty(e,"GCPEnv",{enumerable:!0,get:function(){return i.GCPEnv}});var a=qr();Object.defineProperty(e,"IAMAuth",{enumerable:!0,get:function(){return a.IAMAuth}});var c=ar();Object.defineProperty(e,"IdTokenClient",{enumerable:!0,get:function(){return c.IdTokenClient}});var l=vr();Object.defineProperty(e,"JWTAccess",{enumerable:!0,get:function(){return l.JWTAccess}});var u=Sr();Object.defineProperty(e,"JWT",{enumerable:!0,get:function(){return u.JWT}});var d=Or();Object.defineProperty(e,"Impersonated",{enumerable:!0,get:function(){return d.Impersonated}});var h=or();Object.defineProperty(e,"CodeChallengeMethod",{enumerable:!0,get:function(){return h.CodeChallengeMethod}}),Object.defineProperty(e,"OAuth2Client",{enumerable:!0,get:function(){return h.OAuth2Client}}),Object.defineProperty(e,"ClientAuthentication",{enumerable:!0,get:function(){return h.ClientAuthentication}});var f=sr();Object.defineProperty(e,"LoginTicket",{enumerable:!0,get:function(){return f.LoginTicket}});var p=Ar();Object.defineProperty(e,"UserRefreshClient",{enumerable:!0,get:function(){return p.UserRefreshClient}});var m=Lr();Object.defineProperty(e,"AwsClient",{enumerable:!0,get:function(){return m.AwsClient}});var y=Dr();Object.defineProperty(e,"AwsRequestSigner",{enumerable:!0,get:function(){return y.AwsRequestSigner}});var _=xr();Object.defineProperty(e,"IdentityPoolClient",{enumerable:!0,get:function(){return _.IdentityPoolClient}});var g=Br();Object.defineProperty(e,"ExternalAccountClient",{enumerable:!0,get:function(){return g.ExternalAccountClient}});var b=Rr();Object.defineProperty(e,"BaseExternalAccountClient",{enumerable:!0,get:function(){return b.BaseExternalAccountClient}});var E=$r();Object.defineProperty(e,"DownscopedClient",{enumerable:!0,get:function(){return E.DownscopedClient}});var w=Fr();Object.defineProperty(e,"PluggableAuthClient",{enumerable:!0,get:function(){return w.PluggableAuthClient}}),Object.defineProperty(e,"ExecutableError",{enumerable:!0,get:function(){return w.ExecutableError}});var T=Gr();Object.defineProperty(e,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return T.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}}),Object.defineProperty(e,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return T.ExternalAccountAuthorizedUserClient}});var v=Wr();Object.defineProperty(e,"PassThroughClient",{enumerable:!0,get:function(){return v.PassThroughClient}}),r(Tr(),e);var S=new n.GoogleAuth;e.auth=S}}),Yr=A({"node_modules/ws/lib/constants.js"(e,t){var r=["nodebuffer","arraybuffer","fragments"],n="undefined"!=typeof Blob;n&&r.push("blob"),t.exports={BINARY_TYPES:r,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:n,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}}),zr=A({"node_modules/ws/lib/buffer-util.js"(e,t){var{EMPTY_BUFFER:r}=Yr(),n=Buffer[Symbol.species];function s(e,t,r,n,s){for(let o=0;o<s;o++)r[n+o]=e[o]^t[3&o]}function o(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(t.exports={concat:function(e,t){if(0===e.length)return r;if(1===e.length)return e[0];const s=Buffer.allocUnsafe(t);let o=0;for(let t=0;t<e.length;t++){const r=e[t];s.set(r,o),o+=r.length}return o<t?new n(s.buffer,s.byteOffset,o):s},mask:s,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new n(t):ArrayBuffer.isView(t)?r=new n(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{const e=v("bufferutil");t.exports.mask=function(t,r,n,o,i){i<48?s(t,r,n,o,i):e.mask(t,r,n,o,i)},t.exports.unmask=function(t,r){t.length<32?o(t,r):e.unmask(t,r)}}catch(e){}}}),Kr=A({"node_modules/ws/lib/limiter.js"(e,t){var r=Symbol("kDone"),n=Symbol("kRun");t.exports=class{constructor(e){this[r]=()=>{this.pending--,this[n]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[n]()}[n](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[r])}}}}}),Jr=A({"node_modules/ws/lib/permessage-deflate.js"(e,t){var r,n=v("zlib"),s=zr(),o=Kr(),{kStatusCode:i}=Yr(),a=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol("permessage-deflate"),u=Symbol("total-length"),d=Symbol("callback"),h=Symbol("buffers"),f=Symbol("error");function p(e){this[h].push(e),this[u]+=e.length}function m(e){this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload?this[h].push(e):(this[f]=new RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][i]=1009,this.removeListener("data",m),this.reset())}function y(e){this[l]._inflate=null,this[f]?this[d](this[f]):(e[i]=1007,this[d](e))}t.exports=class{constructor(e,t,n){if(this._maxPayload=0|n,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!r){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;r=new o(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,n){r.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){r.add((r=>{this._compress(e,t,((e,t)=>{r(),n(e,t)}))}))}_decompress(e,t,r){const o=this._isServer?"client":"server";if(!this._inflate){const e=`${o}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[h]=[],this._inflate.on("error",y),this._inflate.on("data",m)}this._inflate[d]=r,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush((()=>{const e=this._inflate[f];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=s.concat(this._inflate[h],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[h]=[],t&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const o=this._isServer?"server":"client";if(!this._deflate){const e=`${o}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[h]=[],this._deflate.on("data",p)}this._deflate[d]=r,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=s.concat(this._deflate[h],this._deflate[u]);t&&(e=new a(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[h]=[],t&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}}}}),Xr=A({"node_modules/ws/lib/validation.js"(e,t){var{isUtf8:r}=v("buffer"),{hasBlob:n}=Yr();function s(e){const t=e.length;let r=0;for(;r<t;)if(128&e[r])if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}else r++;return!0}if(t.exports={isBlob:function(e){return n&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:s,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},r)t.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=v("utf-8-validate");t.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch(e){}}}),Qr=A({"node_modules/ws/lib/receiver.js"(e,t){var{Writable:r}=v("stream"),n=Jr(),{BINARY_TYPES:s,EMPTY_BUFFER:o,kStatusCode:i,kWebSocket:a}=Yr(),{concat:c,toArrayBuffer:l,unmask:u}=zr(),{isValidStatusCode:d,isValidUTF8:h}=Xr(),f=Buffer[Symbol.species];t.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||s[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[a]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new f(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=!(64&~t[0]);if(!r||this._extensions[n.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!==(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&u(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[n.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let n;n="nodebuffer"===this._binaryType?c(r,t):"arraybuffer"===this._binaryType?l(c(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)})))}else{const n=c(r,t);if(!this._skipUTF8Validation&&!h(n)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,o),this.end();else{const r=e.readUInt16BE(0);if(!d(r)){const e=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const n=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!h(n)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",r,n),this.end()}this._state=0}}createError(e,t,r,n,s){this._loop=!1,this._errored=!0;const o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=s,o[i]=n,o}}}}),Zr=A({"node_modules/ws/lib/sender.js"(e,t){v("stream");var r,{randomFillSync:n}=v("crypto"),s=Jr(),{EMPTY_BUFFER:o,kWebSocket:i,NOOP:a}=Yr(),{isBlob:c,isValidStatusCode:l}=Xr(),{mask:u,toBuffer:d}=zr(),h=Symbol("kByteLength"),f=Buffer.alloc(4),p=8192,m=p;function y(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){const n=e._queue[r],s=n[n.length-1];"function"==typeof s&&s(t)}}function _(e,t,r){y(e,t,r),e.onerror(t)}t.exports=class e{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=a,this[i]=void 0}static frame(e,t){let s,o,i=!1,a=2,c=!1;t.mask&&(s=t.maskBuffer||f,t.generateMask?t.generateMask(s):(m===p&&(void 0===r&&(r=Buffer.alloc(p)),n(r,0,p),m=0),s[0]=r[m++],s[1]=r[m++],s[2]=r[m++],s[3]=r[m++]),c=0===(s[0]|s[1]|s[2]|s[3]),a=6),"string"==typeof e?o=t.mask&&!c||void 0===t[h]?(e=Buffer.from(e)).length:t[h]:(o=e.length,i=t.mask&&t.readOnly&&!c);let l=o;o>=65536?(a+=8,l=127):o>125&&(a+=2,l=126);const d=Buffer.allocUnsafe(i?o+a:a);return d[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(d[0]|=64),d[1]=l,126===l?d.writeUInt16BE(o,2):127===l&&(d[2]=d[3]=0,d.writeUIntBE(o,4,6)),t.mask?(d[1]|=128,d[a-4]=s[0],d[a-3]=s[1],d[a-2]=s[2],d[a-1]=s[3],c?[d,e]:i?(u(e,s,d,a,o),[d]):(u(e,s,e,0,o),[d,e])):[d,e]}close(t,r,n,s){let i;if(void 0===t)i=o;else{if("number"!=typeof t||!l(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==r&&r.length){const e=Buffer.byteLength(r);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+e),i.writeUInt16BE(t,0),"string"==typeof r?i.write(r,2):i.set(r,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0)}const a={[h]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,a,s]):this.sendFrame(e.frame(i,a),s)}ping(t,r,n){let s,o;if("string"==typeof t?(s=Buffer.byteLength(t),o=!1):c(t)?(s=t.size,o=!1):(s=(t=d(t)).length,o=d.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[h]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};c(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,i,n]):this.getBlobData(t,!1,i,n):0!==this._state?this.enqueue([this.dispatch,t,!1,i,n]):this.sendFrame(e.frame(t,i),n)}pong(t,r,n){let s,o;if("string"==typeof t?(s=Buffer.byteLength(t),o=!1):c(t)?(s=t.size,o=!1):(s=(t=d(t)).length,o=d.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[h]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};c(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,i,n]):this.getBlobData(t,!1,i,n):0!==this._state?this.enqueue([this.dispatch,t,!1,i,n]):this.sendFrame(e.frame(t,i),n)}send(e,t,r){const n=this._extensions[s.extensionName];let o,i,a=t.binary?2:1,l=t.compress;"string"==typeof e?(o=Buffer.byteLength(e),i=!1):c(e)?(o=e.size,i=!1):(o=(e=d(e)).length,i=d.readOnly),this._firstFragment?(this._firstFragment=!1,l&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=o>=n._threshold),this._compress=l):(l=!1,a=0),t.fin&&(this._firstFragment=!0);const u={[h]:o,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:i,rsv1:l};c(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(t,r,n,s){this._bufferedBytes+=n[h],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(y,this,e,s)}this._bufferedBytes-=n[h];const o=d(t);r?this.dispatch(o,r,n,s):(this._state=0,this.sendFrame(e.frame(o,n),s),this.dequeue())})).catch((e=>{process.nextTick(_,this,e,s)}))}dispatch(t,r,n,o){if(!r)return void this.sendFrame(e.frame(t,n),o);const i=this._extensions[s.extensionName];this._bufferedBytes+=n[h],this._state=1,i.compress(t,n.fin,((t,r)=>{if(this._socket.destroyed){y(this,new Error("The socket was closed while data was being compressed"),o)}else this._bufferedBytes-=n[h],this._state=0,n.readOnly=!1,this.sendFrame(e.frame(r,n),o),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][h],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][h],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}}}),en=A({"node_modules/ws/lib/event-target.js"(e,t){var{kForOnEventAttribute:r,kListener:n}=Yr(),s=Symbol("kCode"),o=Symbol("kData"),i=Symbol("kError"),a=Symbol("kMessage"),c=Symbol("kReason"),l=Symbol("kTarget"),u=Symbol("kType"),d=Symbol("kWasClean"),h=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(h.prototype,"target",{enumerable:!0}),Object.defineProperty(h.prototype,"type",{enumerable:!0});var f=class extends h{constructor(e,t={}){super(e),this[s]=void 0===t.code?0:t.code,this[c]=void 0===t.reason?"":t.reason,this[d]=void 0!==t.wasClean&&t.wasClean}get code(){return this[s]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});var p=class extends h{constructor(e,t={}){super(e),this[i]=void 0===t.error?null:t.error,this[a]=void 0===t.message?"":t.message}get error(){return this[i]}get message(){return this[a]}};Object.defineProperty(p.prototype,"error",{enumerable:!0}),Object.defineProperty(p.prototype,"message",{enumerable:!0});var m=class extends h{constructor(e,t={}){super(e),this[o]=void 0===t.data?null:t.data}get data(){return this[o]}};Object.defineProperty(m.prototype,"data",{enumerable:!0});var y={addEventListener(e,t,s={}){for(const o of this.listeners(e))if(!s[r]&&o[n]===t&&!o[r])return;let o;if("message"===e)o=function(e,r){const n=new m("message",{data:r?e:e.toString()});n[l]=this,_(t,this,n)};else if("close"===e)o=function(e,r){const n=new f("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[l]=this,_(t,this,n)};else if("error"===e)o=function(e){const r=new p("error",{error:e,message:e.message});r[l]=this,_(t,this,r)};else{if("open"!==e)return;o=function(){const e=new h("open");e[l]=this,_(t,this,e)}}o[r]=!!s[r],o[n]=t,s.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(const s of this.listeners(e))if(s[n]===t&&!s[r]){this.removeListener(e,s);break}}};function _(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}t.exports={CloseEvent:f,ErrorEvent:p,Event:h,EventTarget:y,MessageEvent:m}}}),tn=A({"node_modules/ws/lib/extension.js"(e,t){var{tokenChars:r}=Xr();function n(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}t.exports={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let s,o,i=Object.create(null),a=!1,c=!1,l=!1,u=-1,d=-1,h=-1,f=0;for(;f<e.length;f++)if(d=e.charCodeAt(f),void 0===s)if(-1===h&&1===r[d])-1===u&&(u=f);else if(0===f||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);const r=e.slice(u,h);44===d?(n(t,r,i),i=Object.create(null)):s=r,u=h=-1}}else-1===h&&-1!==u&&(h=f);else if(void 0===o)if(-1===h&&1===r[d])-1===u&&(u=f);else if(32===d||9===d)-1===h&&-1!==u&&(h=f);else if(59===d||44===d){if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),n(i,e.slice(u,h),!0),44===d&&(n(t,s,i),i=Object.create(null),s=void 0),u=h=-1}else{if(61!==d||-1===u||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);o=e.slice(u,f),u=h=-1}else if(c){if(1!==r[d])throw new SyntaxError(`Unexpected character at index ${f}`);-1===u?u=f:a||(a=!0),c=!1}else if(l)if(1===r[d])-1===u&&(u=f);else if(34===d&&-1!==u)l=!1,h=f;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${f}`);c=!0}else if(34===d&&61===e.charCodeAt(f-1))l=!0;else if(-1===h&&1===r[d])-1===u&&(u=f);else if(-1===u||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);let r=e.slice(u,h);a&&(r=r.replace(/\\/g,""),a=!1),n(i,o,r),44===d&&(n(t,s,i),i=Object.create(null),s=void 0),o=void 0,u=h=-1}}else-1===h&&(h=f);if(-1===u||l||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const p=e.slice(u,h);return void 0===s?n(t,p,i):(void 0===o?n(i,p,!0):n(i,o,a?p.replace(/\\/g,""):p),n(t,s,i)),t}}}}),rn=A({"node_modules/ws/lib/websocket.js"(e,t){var r=v("events"),n=v("https"),s=v("http"),o=v("net"),i=v("tls"),{randomBytes:a,createHash:c}=v("crypto");v("stream");var{URL:l}=v("url"),u=Jr(),d=Qr(),h=Zr(),{isBlob:f}=Xr(),{BINARY_TYPES:p,EMPTY_BUFFER:m,GUID:y,kForOnEventAttribute:_,kListener:g,kStatusCode:b,kWebSocket:E,NOOP:w}=Yr(),{EventTarget:{addEventListener:T,removeEventListener:S}}=en(),{format:A,parse:O}=tn(),{toBuffer:I}=zr(),C=Symbol("kAborted"),R=[8,13],k=["CONNECTING","OPEN","CLOSING","CLOSED"],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class e extends r{constructor(t,r,n){super(),this._binaryType=p[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=m,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==t?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===r?r=[]:Array.isArray(r)||("object"==typeof r&&null!==r?(n=r,r=[]):r=[r]),x(this,t,r,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){p.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){const s=new d({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),o=new h(t,this._extensions,n.generateMask);this._receiver=s,this._sender=o,this._socket=t,s[E]=this,o[E]=this,t[E]=this,s.on("conclude",F),s.on("drain",B),s.on("error",G),s.on("message",q),s.on("ping",$),s.on("pong",W),o.onerror=Y,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",K),t.on("data",J),t.on("end",X),t.on("error",Q),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=e.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[u.extensionName]&&this._extensions[u.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this.readyState!==e.CLOSING?(this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),z(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";j(this,this._req,e)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(n=t,t=r=void 0):"function"==typeof r&&(n=r,r=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===r&&(r=!this._isServer),this._sender.ping(t||m,r,n)):M(this,t,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(n=t,t=r=void 0):"function"==typeof r&&(n=r,r=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===r&&(r=!this._isServer),this._sender.pong(t||m,r,n)):M(this,t,n)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof r&&(n=r,r={}),"number"==typeof t&&(t=t.toString()),this.readyState!==e.OPEN)return void M(this,t,n);const s={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[u.extensionName]||(s.compress=!1),this._sender.send(t||m,s,n)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";j(this,this._req,e)}}};function x(e,t,r,o){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:R[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!R.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${R.join(", ")})`);let d;if(t instanceof l)d=t;else try{d=new l(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===d.protocol?d.protocol="ws:":"https:"===d.protocol&&(d.protocol="wss:"),e._url=d.href;const h="wss:"===d.protocol,f="ws+unix:"===d.protocol;let p;if("ws:"===d.protocol||h||f?f&&!d.pathname?p="The URL's pathname is empty":d.hash&&(p="The URL contains a fragment identifier"):p='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',p){const t=new SyntaxError(p);if(0===e._redirects)throw t;return void D(e,t)}const m=h?443:80,_=a(16).toString("base64"),g=h?n.request:s.request,b=new Set;let E,w;if(i.createConnection=i.createConnection||(h?L:U),i.defaultPort=i.defaultPort||m,i.port=d.port||m,i.host=d.hostname.startsWith("[")?d.hostname.slice(1,-1):d.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":_,Connection:"Upgrade",Upgrade:"websocket"},i.path=d.pathname+d.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(E=new u(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=A({[u.extensionName]:E.offer()})),r.length){for(const e of r){if("string"!=typeof e||!N.test(e)||b.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(e)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(d.username||d.password)&&(i.auth=`${d.username}:${d.password}`),f){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=f,e._originalSecure=h,e._originalHostOrSocketPath=f?i.socketPath:d.host;const t=o&&o.headers;if(o={...o,headers:{}},t)for(const[e,r]of Object.entries(t))o.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=f?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&d.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!h)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),w=e._req=g(i),e._redirects&&e.emit("redirect",e.url,w)}else w=e._req=g(i);i.timeout&&w.on("timeout",(()=>{j(e,w,"Opening handshake has timed out")})),w.on("error",(t=>{null===w||w[C]||(w=e._req=null,D(e,t))})),w.on("response",(n=>{const s=n.headers.location,a=n.statusCode;if(s&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void j(e,w,"Maximum redirects exceeded");let n;w.abort();try{n=new l(s,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${s}`);return void D(e,r)}x(e,n,r,o)}else e.emit("unexpected-response",w,n)||j(e,w,`Unexpected server response: ${n.statusCode}`)})),w.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==P.CONNECTING)return;w=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void j(e,r,"Invalid Upgrade header");const o=c("sha1").update(_+y).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void j(e,r,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let l;if(void 0!==a?b.size?b.has(a)||(l="Server sent an invalid subprotocol"):l="Server sent a subprotocol but none was requested":b.size&&(l="Server sent no subprotocol"),l)return void j(e,r,l);a&&(e._protocol=a);const d=t.headers["sec-websocket-extensions"];if(void 0!==d){if(!E){return void j(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=O(d)}catch(t){return void j(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==u.extensionName){return void j(e,r,"Server indicated an extension that was not requested")}try{E.accept(t[u.extensionName])}catch(t){return void j(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[u.extensionName]=E}e.setSocket(r,n,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(w,e):w.end()}function D(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function U(e){return e.path=e.socketPath,o.connect(e)}function L(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=o.isIP(e.host)?"":e.host),i.connect(e)}function j(e,t,r){e._readyState=P.CLOSING;const n=new Error(r);Error.captureStackTrace(n,j),t.setHeader?(t[C]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(D,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function M(e,t,r){if(t){const r=f(t)?t.size:I(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${k[e.readyState]})`);process.nextTick(r,t)}}function F(e,t){const r=this[E];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[E]&&(r._socket.removeListener("data",J),process.nextTick(V,r._socket),1005===e?r.close():r.close(e,t))}function B(){const e=this[E];e.isPaused||e._socket.resume()}function G(e){const t=this[E];void 0!==t._socket[E]&&(t._socket.removeListener("data",J),process.nextTick(V,t._socket),t.close(e[b])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function H(){this[E].emitClose()}function q(e,t){this[E].emit("message",e,t)}function $(e){const t=this[E];t._autoPong&&t.pong(e,!this._isServer,w),t.emit("ping",e)}function W(e){this[E].emit("pong",e)}function V(e){e.resume()}function Y(e){const t=this[E];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,z(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function z(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function K(){const e=this[E];let t;this.removeListener("close",K),this.removeListener("data",J),this.removeListener("end",X),e._readyState=P.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[E]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",H),e._receiver.on("finish",H))}function J(e){this[E]._receiver.write(e)||this.pause()}function X(){const e=this[E];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function Q(){const e=this[E];this.removeListener("error",Q),this.on("error",w),e&&(e._readyState=P.CLOSING,this.destroy())}Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:k.indexOf("CONNECTING")}),Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:k.indexOf("CONNECTING")}),Object.defineProperty(P,"OPEN",{enumerable:!0,value:k.indexOf("OPEN")}),Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:k.indexOf("OPEN")}),Object.defineProperty(P,"CLOSING",{enumerable:!0,value:k.indexOf("CLOSING")}),Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:k.indexOf("CLOSING")}),Object.defineProperty(P,"CLOSED",{enumerable:!0,value:k.indexOf("CLOSED")}),Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:k.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[_])return t[g];return null},set(t){for(const t of this.listeners(e))if(t[_]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[_]:!0})}})})),P.prototype.addEventListener=T,P.prototype.removeEventListener=S,t.exports=P}}),nn=A({"node_modules/ws/lib/stream.js"(e,t){rn();var{Duplex:r}=v("stream");function n(e){e.emit("close")}function s(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener("error",o),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let i=!0;const a=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const n=!r&&a._readableState.objectMode?t.toString():t;a.push(n)||e.pause()})),e.once("error",(function(e){a.destroyed||(i=!1,a.destroy(e))})),e.once("close",(function(){a.destroyed||a.push(null)})),a._destroy=function(t,r){if(e.readyState===e.CLOSED)return r(t),void process.nextTick(n,a);let s=!1;e.once("error",(function(e){s=!0,r(e)})),e.once("close",(function(){s||r(t),process.nextTick(n,a)})),i&&e.terminate()},a._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){a._final(t)}))},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",(function(){a._write(t,r,n)}))},a.on("end",s),a.on("error",o),a}}}),sn=A({"node_modules/ws/lib/subprotocol.js"(e,t){var{tokenChars:r}=Xr();t.exports={parse:function(e){const t=new Set;let n=-1,s=-1,o=0;for(;o<e.length;o++){const i=e.charCodeAt(o);if(-1===s&&1===r[i])-1===n&&(n=o);else if(0===o||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${o}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${o}`);-1===s&&(s=o);const r=e.slice(n,s);if(t.has(r))throw new SyntaxError(`The "${r}" subprotocol is duplicated`);t.add(r),n=s=-1}}else-1===s&&-1!==n&&(s=o)}if(-1===n||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(n,o);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}}}}),on=A({"node_modules/ws/lib/websocket-server.js"(e,t){var r=v("events"),n=v("http");v("stream");var{createHash:s}=v("crypto"),o=tn(),i=Jr(),a=sn(),c=rn(),{GUID:l,kWebSocket:u}=Yr(),d=/^[+/0-9A-Za-z]{22}==$/;function h(e){e._state=2,e.emit("close")}function f(){this.destroy()}function p(e,t,r,s){r=r||n.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${n.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function m(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,m),e.emit("wsClientError",n,r,t)}else p(r,n,s)}t.exports=class extends r{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:c,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=n.createServer(((e,t)=>{const r=n.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(h,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{h(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",f);const s=e.headers["sec-websocket-key"],c=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void m(this,e,t,405,"Invalid HTTP method")}if(void 0===c||"websocket"!==c.toLowerCase()){return void m(this,e,t,400,"Invalid Upgrade header")}if(void 0===s||!d.test(s)){return void m(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==l&&13!==l){return void m(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void p(t,400);const u=e.headers["sec-websocket-protocol"];let h=new Set;if(void 0!==u)try{h=a.parse(u)}catch(r){return void m(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const y=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&void 0!==y){const r=new i(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=o.parse(y);e[i.extensionName]&&(r.accept(e[i.extensionName]),_[i.extensionName]=r)}catch(r){return void m(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===l?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((o,i,a,c)=>{if(!o)return p(t,i||401,a,c);this.completeUpgrade(_,s,h,e,t,r,n)}));if(!this.options.verifyClient(o))return p(t,401)}this.completeUpgrade(_,s,h,e,t,r,n)}completeUpgrade(e,t,r,n,a,c,d){if(!a.readable||!a.writable)return a.destroy();if(a[u])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return p(a,503);const m=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s("sha1").update(t+l).digest("base64")}`],y=new this.options.WebSocket(null,void 0,this.options);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(m.push(`Sec-WebSocket-Protocol: ${e}`),y._protocol=e)}if(e[i.extensionName]){const t=e[i.extensionName].params,r=o.format({[i.extensionName]:[t]});m.push(`Sec-WebSocket-Extensions: ${r}`),y._extensions=e}this.emit("headers",m,n),a.write(m.concat("\r\n").join("\r\n")),a.removeListener("error",f),y.setSocket(a,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(y),y.on("close",(()=>{this.clients.delete(y),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)}))),d(y,n)}}}}),an="__system__",cn=[{name:"role",version:"1.0.0",description:"AI persona with a system prompt and associated preference defaults.",fields:{name:{name:"name",type:"string",required:!0},label:{name:"label",type:"string",required:!0},description:{name:"description",type:"string",required:!1},persona:{name:"persona",type:"string",required:!0},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"}},indexes:[{name:"by_name",fields:["name"],type:"unique"},{name:"by_label",fields:["label"],type:"normal"}],constraints:[],migrations:[]},{name:"preference",version:"1.0.0",description:"A user behavioural instruction, scoped to zero or more topics.",fields:{id:{name:"id",type:"string",required:!0},content:{name:"content",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},timestamp:{name:"timestamp",type:"string",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"context",version:"1.0.0",description:"Injected background knowledge, scoped to topics. Content is a discriminated union.",fields:{key:{name:"key",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},content:{name:"content",type:"record",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_key",fields:["key"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"session",version:"1.0.0",description:"Session metadata. The head field tracks the current tip of the turn DAG.",fields:{id:{name:"id",type:"string",required:!0},label:{name:"label",type:"string",required:!0},role:{name:"role",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"},metadata:{name:"metadata",type:"record",required:!1},flushedTurnCount:{name:"flushedTurnCount",type:"number",required:!0},head:{name:"head",type:"record",required:!1}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_role",fields:["role"],type:"normal"}],constraints:[],migrations:[]},{name:"turn",version:"1.0.0",description:["A single message in a session transcript, stored as a flat document.","The DAG is reconstructed in memory by TurnTree.buildNodeGraph() at session open time.","$id is a composite key: `${sessionId}:${id}:${version}`."].join(" "),fields:{id:{name:"id",type:"string",required:!0},sessionId:{name:"sessionId",type:"string",required:!0},version:{name:"version",type:"number",required:!0},actor:{name:"actor",type:"enum",required:!0,values:["user","assistant","tool"]},blocks:{name:"blocks",type:"array",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},role:{name:"role",type:"string",required:!1},parent:{name:"parent",type:"record",required:!1}},indexes:[{name:"by_session",fields:["sessionId"],type:"normal"},{name:"by_session_parent",fields:["sessionId","parent"],type:"composite"},{name:"by_session_id_ver",fields:["sessionId","id","version"],type:"composite",unique:!0}],constraints:[],migrations:[]},{name:"task",version:"1.0.0",description:"A first-class task entity with status, steps, and topics.",fields:{id:{name:"id",type:"string",required:!0},title:{name:"title",type:"string",required:!0},description:{name:"description",type:"string",required:!1},status:{name:"status",type:"enum",required:!0,values:["todo","active","done","blocked","defered"]},steps:{name:"steps",type:"array",required:!0,itemsType:"record"},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},metadata:{name:"metadata",type:"record",required:!1},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_status",fields:["status"],type:"normal"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_updated",fields:["updated"],type:"btree"}],constraints:[],migrations:[]}],ln=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},un=class extends ln{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},dn=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));this.waiters.push(t),null!=e?await Promise.race([r,new Promise(((r,n)=>setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),n(new un("Mutex lock timed out"))}),e)))]):await r}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},hn=class{mutex=new dn({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.promise=null}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new Error("Cannot execute doSync: lock is currently held.");if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this._done}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){this._done=!1,this.promise=null,this._value=null,this._error=void 0}resolved(){return this.promise}done(){return this._done}_awaitWithTimeout(e,t,r="Operation timed out"){return null==t?e:Promise.race([e,new Promise(((e,n)=>setTimeout((()=>n(new un(r))),t)))])}};var fn={ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",TASK:"task"};I(C());var pn=Symbol.for("delete"),mn=e=>Array.isArray(e)?[...e]:{...e};function yn(){return pn}I(C()),I(C()),I(C()),I(C()),I(C()),I(C());var _n=function(e){const t=e?.deleteMarker||pn;function r(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e:r(e)));if("object"==typeof e){const n={};for(const[s,o]of Object.entries(e))if(o!==t)if("object"==typeof o&&null!==o){const e=r(o);void 0!==e&&(n[s]=e)}else n[s]=o;return n}return e===t?void 0:e}return function(e,n){if("object"!=typeof e||null===e)return"object"==typeof n&&null!==n?r(n):n===t?{}:n;if("object"!=typeof n||null===n)return e;const s=mn(e),o=[{target:s,source:n}];for(;o.length>0;){const{target:e,source:r}=o.pop();for(const n of Object.keys(r)){const s=r[n];if(s!==t)if(Array.isArray(s))e[n]=s;else if("object"==typeof s&&null!==s){const t=n in e&&"object"==typeof e[n]&&null!==e[n]?e[n]:{};e[n]=mn(t),o.push({target:e[n],source:s})}else e[n]=s;else delete e[n]}}return s}}({deleteMarker:pn});function gn(e){return{ok:!0,value:e}}function bn(e){return{ok:!1,error:e}}function En(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))}async function wn(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}var Tn=(e,t)=>({name:e,label:t,persona:"",preferences:[]});function vn(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);if("undefined"!=typeof Buffer)return Buffer.from(t).toString("base64");let r="";const n=t.byteLength;for(let e=0;e<n;e++)r+=String.fromCharCode(t[e]);return btoa(r)}var Sn=class{db;constructor(e){this.db=e}async turns(){return this.db.collection(fn.TURN)}async sessions(){return this.db.collection(fn.SESSION)}turnFilter(e,t,r){return{operator:"and",conditions:[{field:"sessionId",operator:"eq",value:e},{field:"id",operator:"eq",value:t},{field:"version",operator:"eq",value:r}]}}async loadRaw(e){const[t,r]=await Promise.all([this.loadAllTurns(e),this.getHead(e)]);return{turns:t,head:r}}async getHead(e){const t=await this.sessions(),r=await t.find({field:"id",operator:"eq",value:e});return r?.head??null}async setHead(e,t){const r=await this.sessions(),n=await r.find({field:"id",operator:"eq",value:e});if(!n)return;const s={...n.state(),head:t??void 0};await n.update(s)}async save(e,t,r){const n={...t,sessionId:e,version:t.version??0,parent:t.parent?t.parent:r?{id:r.id,version:r.version}:null},s=await this.turns();return await s.create(En(n)),n}async append(e,t){const r=await this.getHead(e),n=this.save(e,t,r);return await this.setHead(e,{id:t.id,version:t.version}),n}async appendBatch(e,t,r){const n=await this.getHead(e);if(0!==t.length){for(const r of t)await this.save(e,r,n);await this.setHead(e,r)}}async replaceVersion(e,t){const r=await this.turns(),n=await r.find(this.turnFilter(e,t.id,t.version)),s=En(t);n?await n.update({...s,sessionId:e}):await r.create({...s,sessionId:e})}async branch(e,t){const r=await this.turns();await r.create(En({...t,sessionId:e})),await this.setHead(e,{id:t.id,version:t.version})}async loadAllTurns(e){const t=await this.turns();return(await t.filter({field:"sessionId",operator:"eq",value:e})).map((e=>e.state()))}async loadTurnVersions(e,t){const r=await this.turns();return(await r.filter({operator:"and",conditions:[{field:"sessionId",operator:"eq",value:e},{field:"id",operator:"eq",value:t}]})).map((e=>e.state()))}buildNodes(e,t,r=[]){const n=function(e,t){if(!t)return new Set;const r=new Map;for(const t of e)r.set(`${t.id}:${t.version}`,t);const n=new Set;let s=t;for(;s;){const e=`${s.id}:${s.version}`;if(n.has(e))break;n.add(e);const t=r.get(e);if(!t)break;s=t.parent}return n}(e,t),s={},o={},i=[...e,...r];for(const e of i){s[e.id]||(s[e.id]={id:e.id,versions:{},activeVersion:e.version,role:e.actor,blocks:e.blocks,timestamp:e.timestamp,roleSnapshot:e.role,parent:e.parent,children:{}},o[e.id]=new Set);const t=s[e.id];t.versions[e.version]=e;const r=n.has(`${e.id}:${e.version}`),i=n.has(`${e.id}:${t.activeVersion}`);if(r&&(!i||e.version>=t.activeVersion)&&(t.activeVersion=e.version,t.blocks=e.blocks,t.timestamp=e.timestamp,t.roleSnapshot=e.role,t.parent=e.parent),e.parent){const t=`${e.parent.id}:${e.parent.version}`;if(o[e.parent.id]||(o[e.parent.id]=new Set),!o[e.parent.id].has(t+":"+e.id)){o[e.parent.id].add(t+":"+e.id),s[e.parent.id]||(s[e.parent.id]={id:e.parent.id,versions:{},activeVersion:e.parent.version,role:"user",blocks:[],timestamp:"",roleSnapshot:void 0,parent:null,children:{}});const r=s[e.parent.id],n=e.parent.version;r.children[n]||(r.children[n]=[]),r.children[n].push(e.id)}}}return s}async buildNodeGraph(e,t=[]){const{turns:r,head:n}=await this.loadRaw(e);return this.buildNodes(r,n,t)}async getActiveChain(e,t=[]){const{turns:r,head:n}=await this.loadRaw(e);if(!n&&0===t.length)return[];return[...n?An(r,n):[],...t]}async buildActiveChain(e){const{turns:t,head:r}=await this.loadRaw(e);if(!r)return[];const n=this.buildNodes(t,r),s=[];let o=r.id;for(;null!==o;){const e=n[o];if(!e)break;s.push(e),o=e.parent?.id??null}return s.reverse()}async getTurnSiblings(e,t){const{turns:r,head:n}=await this.loadRaw(t),s=this.buildNodes(r,n),o=s[e];if(!o)return[];if(!o.parent)return Object.values(s).filter((e=>null===e.parent));const i=s[o.parent.id];if(!i)return[o];const a=o.parent.version,c=i.children[a];return c?c.map((e=>s[e])).filter((e=>void 0!==e)):[o]}async branchInfo(e,t){const{turns:r,head:n}=await this.loadRaw(t),s=this.buildNodes(r,n)[e];if(!s)return{versions:[],currentIndex:-1,total:0,hasPrev:!1,hasNext:!1};const o=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),i=o.indexOf(s.activeVersion);return{versions:o,currentIndex:i,total:o.length,hasPrev:i>0,hasNext:i<o.length-1}}async deleteSubtree(e,t,r,n){const s=function(e,t,r){const n=new Map;for(const t of e)if(t.parent){const e=`${t.parent.id}:${t.parent.version}`;let r=n.get(e);r||(r=new Set,n.set(e,r)),r.add(`${t.id}:${t.version}`)}const s=new Set,o=[`${t}:${r}`];for(;o.length>0;){const e=o.pop();s.add(e);const t=n.get(e);if(t)for(const e of t)s.has(e)||o.push(e)}return s}(await this.loadAllTurns(e),t,r),o=await this.turns();await Promise.all(Array.from(s).map((async t=>{const[r,n]=t.split(":"),s=await o.find(this.turnFilter(e,r,Number(n)));s&&await s.delete()}))),await this.setHead(e,n)}async copyTranscript(e,t){const{turns:r,head:n}=await this.loadRaw(e),s=n?An(r,n):[],o=await this.turns();for(const e of s)await o.create(En({...e,sessionId:t}));await this.setHead(t,n?{...n}:null)}};function An(e,t){const r=new Map;for(const t of e)r.set(`${t.id}:${t.version}`,t);const n=[];let s=t;for(;s;){const e=r.get(`${s.id}:${s.version}`);if(!e)break;n.push(e),s=e.parent}return n.reverse()}var On=class{storage;config;bus;recordCache=new Map;constructor(e,t,r={}){this.storage=e,this.bus=t,this.config={eagerEviction:r.eagerEviction??!1}}subscribe(e,t){return this.bus.subscribe(e,t)}async init(){const e=await this.storage.listRecords();for(const t of e)this.recordCache.set(t.sha256,t)}async register(e,t,r){try{const n=await wn(e),s=(new Date).toISOString(),o=this.recordCache.get(n);if(o){const e={...o,refCount:o.refCount+1,lastUsedAt:s};await this.storage.saveRecord(e),this.recordCache.set(n,e)}else{const o={sha256:n,mediaType:t,sizeBytes:e.byteLength,filename:r,refCount:1,remoteIds:{},createdAt:s,lastUsedAt:s};"function"==typeof this.storage.registerBlob?await this.storage.registerBlob(o,e):(await this.storage.storeBytes(n,e),await this.storage.saveRecord(o)),this.recordCache.set(n,o)}const i=this.recordCache.get(n);return gn({sha256:n,mediaType:t,sizeBytes:i.sizeBytes,filename:i.filename,previewUrl:i.previewUrl})}catch(e){return bn({code:"BLOB_ERROR",reason:e instanceof Error?e.message:String(e)})}}async retain(e){const t=this.recordCache.get(e);if(!t)return bn({code:"NOT_FOUND",resource:"blob",id:e});const r={...t,refCount:t.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(r),this.recordCache.set(e,r),gn(void 0)}async release(e){const t=this.recordCache.get(e);if(!t)return bn({code:"NOT_FOUND",resource:"blob",id:e});const r=Math.max(0,t.refCount-1),n={...t,refCount:r,lastUsedAt:(new Date).toISOString()};return 0===r&&this.config.eagerEviction?(await this.storage.deleteBytes(e),await this.storage.deleteRecord(e),this.recordCache.delete(e)):(await this.storage.saveRecord(n),this.recordCache.set(e,n)),gn(void 0)}async recordRemoteId(e,t,r){const n=this.recordCache.get(e);if(!n)return bn({code:"NOT_FOUND",resource:"blob",id:e});if(n.remoteIds[t]?.id===r)return gn(void 0);const s={...n,remoteIds:{...n.remoteIds,[t]:{id:r,timestamp:(new Date).toISOString()}}};return await this.storage.saveRecord(s),this.recordCache.set(e,s),gn(void 0)}getRemoteId(e,t){return this.recordCache.get(e)?.remoteIds[t].id??null}getRemoteRecord(e,t){return this.recordCache.get(e)?.remoteIds[t]??null}async resolveRef(e,t){try{if(t){const r=this.getRemoteRecord(e.sha256,t);if(r)return gn({kind:"remote",sha256:e.sha256,mediaType:e.mediaType,fileId:r.id,providerId:t,timestamp:r.timestamp})}const r=await this.storage.loadBytes(e.sha256);return r?gn({kind:"inline",sha256:e.sha256,mediaType:e.mediaType,data:r}):bn({code:"BLOB_ERROR",reason:`Blob bytes not found locally for sha256=${e.sha256}. The blob may have been evicted. Re-register it before resolving.`})}catch(e){return bn({code:"BLOB_ERROR",reason:e instanceof Error?e.message:String(e)})}}async resolveRefs(e,t){const r=function(e){const t=new Set,r=[];for(const n of e)t.has(n.sha256)||(t.add(n.sha256),r.push(n));return r}(e),n=await Promise.all(r.map((async e=>({ref:e,result:await this.resolveRef(e,t)})))),s=new Map,o=[];for(const{ref:e,result:t}of n)t.ok?s.set(e.sha256,t.value):o.push({ref:e,error:t.error});return{resolved:s,errors:o}}async gc(){const e=Array.from(this.recordCache.values()).filter((e=>0===e.refCount));return await Promise.all(e.map((async e=>{await this.storage.deleteBytes(e.sha256),await this.storage.deleteRecord(e.sha256),this.recordCache.delete(e.sha256),this.bus.emit({name:"blobs:changed",payload:{sha256:e.sha256,record:null}})}))),e.length}async purge(e){return this.recordCache.has(e)?(await this.storage.deleteBytes(e),await this.storage.deleteRecord(e),this.recordCache.delete(e),gn(void 0)):bn({code:"NOT_FOUND",resource:"blob",id:e})}getRecord(e){return this.recordCache.get(e)??null}getAllRecords(){const e={};for(const[t,r]of this.recordCache)e[t]=r;return e}};var In=10,Cn=50,Rn=20,kn=10,Nn=class{map=new Map;max;constructor(e){this.max=e}get(e){if(!this.map.has(e))return;const t=this.map.get(e);return this.map.delete(e),this.map.set(e,t),t}set(e,t){if(this.map.has(e)&&this.map.delete(e),this.map.set(e,t),this.map.size>this.max){const e=this.map.keys().next().value;void 0!==e&&this.map.delete(e)}}has(e){return this.map.has(e)}delete(e){this.map.delete(e)}};function Pn({index:e},t){switch(t.type){case"role:add":{const r=t.payload;if(e.roles[r.name]||r.name===an)return bn({code:"DUPLICATE_KEY",resource:"role",key:r.name});const n={name:r.name,label:r.label,description:r.description,preferences:r.preferences.length};return gn({index:{roles:{[r.name]:n}}})}case"role:update":{const{name:r,...n}=t.payload;if(!e.roles[r])return bn({code:"NOT_FOUND",resource:"role",id:r});const s=e.roles[r],o={...s,...n,preferences:n.preferences?.length??s.preferences};return gn({index:{roles:{[r]:o}}})}case"role:delete":{const{name:r}=t.payload;if(!e.roles[r])return bn({code:"NOT_FOUND",resource:"role",id:r});return Object.values(e.sessions).some((e=>e.role===r))?bn({code:"INVALID_COMMAND",reason:`Cannot delete role "${r}" — it is still referenced by one or more sessions`}):gn({index:{roles:{[r]:yn()}}})}case"preference:add":{const r=t.payload,n={id:r.id,topics:r.topics,timestamp:r.timestamp,snippet:r.content.substring(0,100)},s={};return r.topics.forEach((n=>{const o=e.topics[n],i=[...o?.preferences??[],r.id],a=o?.contextKeys??[],c=o?.tasks??[],l=a.length+i.length+c.length;s[n]={topic:n,contextKeys:a,preferences:i,tasks:c,metadata:{created:o?.metadata?.created??t.timestamp,updated:t.timestamp,entries:l}}})),gn({index:{preferences:{[r.id]:n},topics:s}})}case"preference:update":{const{id:r,...n}=t.payload;if(!e.preferences[r])return bn({code:"NOT_FOUND",resource:"preference",id:r});const s=e.preferences[r],o={...s,...n,snippet:n.content?n.content.substring(0,100):s.snippet},i={};return n.topics&&(s.topics.forEach((n=>{const s=e.topics[n];if(s){const e=s.preferences.filter((e=>e!==r)),o=s.contextKeys.length+e.length+s.tasks.length;i[n]={preferences:e,metadata:{...s.metadata,updated:t.timestamp,entries:o}}}})),n.topics.forEach((n=>{const s=e.topics[n]??{contextKeys:[],preferences:[],tasks:[],metadata:{created:t.timestamp}},o=[...s.preferences,r],a=s.contextKeys.length+o.length+s.tasks.length;i[n]={topic:n,contextKeys:s.contextKeys,preferences:o,tasks:s.tasks,metadata:{created:s.metadata?.created??t.timestamp,updated:t.timestamp,entries:a}}}))),gn({index:{preferences:{[r]:o},topics:i}})}case"preference:delete":{const{id:r}=t.payload;if(!e.preferences[r])return bn({code:"NOT_FOUND",resource:"preference",id:r});const n=e.preferences[r],s={};return n.topics.forEach((n=>{const o=e.topics[n];if(o){const e=o.preferences.filter((e=>e!==r)),i=o.contextKeys.length+e.length+o.tasks.length;s[n]={preferences:e,metadata:{...o.metadata,updated:t.timestamp,entries:i}}}})),gn({index:{preferences:{[r]:yn()},topics:s}})}case"context:add":{const r=t.payload;if(e.context[r.key])return bn({code:"DUPLICATE_KEY",resource:"context",key:r.key});const n=r.content,s={key:r.key,topics:r.topics,timestamp:r.timestamp,source:r.key.split(":")[0],preview:"text"===n.kind?n.value.substring(0,200):"json"===n.kind?JSON.stringify(n.value).substring(0,200):void 0,metadata:r.metadata},o={};return r.topics.forEach((n=>{const s=e.topics[n],i=[...s?.contextKeys??[],r.key],a=s?.preferences??[],c=s?.tasks??[],l=i.length+a.length+c.length;o[n]={topic:n,contextKeys:i,preferences:a,tasks:c,metadata:{created:s?.metadata?.created??t.timestamp,updated:t.timestamp,entries:l}}})),gn({index:{context:{[r.key]:s},topics:o}})}case"context:update":{const{key:r,...n}=t.payload;if(!e.context[r])return bn({code:"NOT_FOUND",resource:"context",id:r});const s=e.context[r],o=n.content,i={...s,...n,preview:o?"text"===o.kind?o.value.substring(0,200):"json"===o.kind?JSON.stringify(o.value).substring(0,200):void 0:s.preview},a={};return n.topics&&(s.topics.forEach((n=>{const s=e.topics[n];if(s){const e=s.contextKeys.filter((e=>e!==r)),o=e.length+s.preferences.length+s.tasks.length;a[n]={contextKeys:e,metadata:{...s.metadata,updated:t.timestamp,entries:o}}}})),n.topics.forEach((n=>{const s=e.topics[n]??{contextKeys:[],preferences:[],tasks:[],metadata:{created:t.timestamp}},o=s.contextKeys.includes(r)?s.contextKeys:[...s.contextKeys,r],i=o.length+s.preferences.length+s.tasks.length;a[n]={topic:n,contextKeys:o,preferences:s.preferences,tasks:s.tasks,metadata:{created:s.metadata?.created??t.timestamp,updated:t.timestamp,entries:i}}}))),gn({index:{context:{[r]:i},topics:a}})}case"context:delete":{const{key:r}=t.payload;if(!e.context[r])return bn({code:"NOT_FOUND",resource:"context",id:r});const n=e.context[r],s={};return n.topics.forEach((n=>{const o=e.topics[n];if(o){const e=o.contextKeys.filter((e=>e!==r)),i=e.length+o.preferences.length+o.tasks.length;s[n]={contextKeys:e,metadata:{...o.metadata,updated:t.timestamp,entries:i}}}})),gn({index:{context:{[r]:yn()},topics:s}})}case"session:create":{const{id:r,label:n,role:s,topics:o,preferences:i=[]}=t.payload;if(e.sessions[r])return bn({code:"DUPLICATE_KEY",resource:"session",key:r});if(!e.roles[s]&&s!==an)return bn({code:"NOT_FOUND",resource:"role",id:s});const a={id:r,label:n,role:s,topics:o,preferences:i,metadata:{created:t.timestamp,updated:t.timestamp},flushedTurnCount:0,head:null,task:null};return gn({index:{sessions:{[r]:a}}})}case"session:update":{const{sessionId:r,...n}=t.payload;if(!e.sessions[r])return bn({code:"NOT_FOUND",resource:"session",id:r});if(void 0!==n.role&&n.role!==an&&!e.roles[n.role])return bn({code:"NOT_FOUND",resource:"role",id:n.role});const s={metadata:{updated:t.timestamp}};return void 0!==n.label&&(s.label=n.label),void 0!==n.role&&(s.role=n.role),void 0!==n.topics&&(s.topics=n.topics),void 0!==n.preferences&&(s.preferences=n.preferences),void 0!==n.task&&(s.task=n.task),gn({index:{sessions:{[r]:s}}})}case"session:role:switch":{const{sessionId:r,role:n}=t.payload;return e.sessions[r]?gn({index:{sessions:{[r]:{role:n,metadata:{updated:t.timestamp}}}}}):bn({code:"NOT_FOUND",resource:"session",id:r})}case"session:topics:add":{const{sessionId:r,topics:n}=t.payload;if(!e.sessions[r])return bn({code:"NOT_FOUND",resource:"session",id:r});const s=e.sessions[r],o=[...new Set([...s.topics,...n])];return gn({index:{sessions:{[r]:{topics:o,metadata:{updated:t.timestamp}}}}})}case"session:preferences:override":{const{sessionId:r,preferences:n}=t.payload;return e.sessions[r]?gn({index:{sessions:{[r]:{preferences:n,metadata:{updated:t.timestamp}}}}}):bn({code:"NOT_FOUND",resource:"session",id:r})}case"session:fork":{const{sourceSessionId:r,newSessionId:n,label:s,role:o,topics:i}=t.payload;if(!e.sessions[r])return bn({code:"NOT_FOUND",resource:"session",id:r});if(e.sessions[n])return bn({code:"DUPLICATE_KEY",resource:"session",key:n});const a=e.sessions[r],c={id:n,label:s,role:o??a.role,topics:i??[...a.topics],preferences:[...a.preferences],metadata:{created:t.timestamp,updated:t.timestamp},flushedTurnCount:a.flushedTurnCount,head:a.head,task:a.task};return gn({index:{sessions:{[n]:c}}})}case"session:delete":{const{sessionId:r}=t.payload;return e.sessions[r]?gn({index:{sessions:{[r]:yn()}}}):bn({code:"NOT_FOUND",resource:"session",id:r})}case"task:add":{const r=t.payload;if(e.tasks[r.id])return bn({code:"DUPLICATE_KEY",resource:"task",key:r.id});const n={id:r.id,title:r.title,status:r.status,steps:{completed:r.steps.filter((e=>e.completed)).length,total:r.steps.length},topics:r.topics},s={};return r.topics.forEach((n=>{const o=e.topics[n],i=[...o?.tasks??[],r.id],a=o?.contextKeys??[],c=o?.preferences??[],l=a.length+c.length+i.length;s[n]={topic:n,contextKeys:a,preferences:c,tasks:i,metadata:{created:o?.metadata?.created??t.timestamp,updated:t.timestamp,entries:l}}})),gn({index:{tasks:{[r.id]:n},topics:s}})}case"task:update":{const{id:r,...n}=t.payload;if(!e.tasks[r])return bn({code:"NOT_FOUND",resource:"task",id:r});const s=e.tasks[r],o={...s,...n,steps:n.steps?{completed:n.steps.filter((e=>e.completed)).length,total:n.steps.length}:s.steps},i={};return n.topics&&(s.topics.forEach((n=>{const s=e.topics[n];if(s){const e=s.tasks.filter((e=>e!==r)),o=s.contextKeys.length+s.preferences.length+e.length;i[n]={tasks:e,metadata:{...s.metadata,updated:t.timestamp,entries:o}}}})),n.topics.forEach((n=>{const s=e.topics[n]??{contextKeys:[],preferences:[],tasks:[],metadata:{created:t.timestamp}},o=[...new Set([...s.tasks,r])],a=s.contextKeys.length+s.preferences.length+o.length;i[n]={topic:n,contextKeys:s.contextKeys,preferences:s.preferences,tasks:o,metadata:{created:s.metadata?.created??t.timestamp,updated:t.timestamp,entries:a}}}))),gn({index:{tasks:{[r]:o},topics:i}})}case"task:delete":{const{id:r}=t.payload;if(!e.tasks[r])return bn({code:"NOT_FOUND",resource:"task",id:r});const n=e.tasks[r],s={};return n.topics.forEach((n=>{const o=e.topics[n];if(o){const e=o.tasks.filter((e=>e!==r)),i=o.contextKeys.length+o.preferences.length+e.length;s[n]={tasks:e,metadata:{...o.metadata,updated:t.timestamp,entries:i}}}})),gn({index:{tasks:{[r]:yn()},topics:s}})}case"turn:save":case"turn:add":{const{sessionId:r,turn:n}=t.payload;return e.sessions[r]?gn({index:{sessions:{[r]:{head:{id:n.id,version:n.version},metadata:{updated:t.timestamp},flushedTurnCount:(e.sessions[r]?.flushedTurnCount??0)+1}}}}):bn({code:"NOT_FOUND",resource:"session",id:r})}case"turn:edit":{const{sessionId:r,turnId:n,newVersion:s}=t.payload;return e.sessions[r]?gn({index:{sessions:{[r]:{head:{id:n,version:s},metadata:{updated:t.timestamp}}}}}):bn({code:"NOT_FOUND",resource:"session",id:r})}case"turn:branch":{const{sessionId:r,turn:n}=t.payload;return e.sessions[r]?gn({index:{sessions:{[r]:{head:{id:n.id,version:n.version},metadata:{updated:t.timestamp}}}}}):bn({code:"NOT_FOUND",resource:"session",id:r})}case"turn:delete":{const{sessionId:r,newHead:n}=t.payload;return e.sessions[r]?gn({index:{sessions:{[r]:{head:n,metadata:{updated:t.timestamp}}}}}):bn({code:"NOT_FOUND",resource:"session",id:r})}case"blob:register":case"tool:call":default:return gn({});case"blob:retain":{const{sha256:r}=t.payload;return e.blobs[r]?gn({}):bn({code:"NOT_FOUND",resource:"blob",id:r})}case"blob:release":{const{sha256:r}=t.payload;return e.blobs[r]?gn({}):bn({code:"NOT_FOUND",resource:"blob",id:r})}case"blob:purge":{const{sha256:r}=t.payload;return e.blobs[r]?gn({}):bn({code:"NOT_FOUND",resource:"blob",id:r})}case"blob:record_remote_id":{const{sha256:r}=t.payload;return e.blobs[r]?gn({}):bn({code:"NOT_FOUND",resource:"blob",id:r})}}}function xn(){return crypto.randomUUID()}var Dn=class{handlers={"task:proposal":(e,t,r)=>{const n=e,s=[];if("create"===n.action){const e=n.taskId||xn();return s.push({type:"task:add",timestamp:t,description:`Create task "${n.title}"`,synthetic:!1,payload:{id:e,title:n.title,description:"",status:"todo",steps:n.steps.map((e=>({id:xn(),text:e.text,completed:"done"===e.status?t:void 0}))),topics:[],created:t,updated:t}}),r&&s.push({type:"session:update",timestamp:t,description:`Link task "${n.title}" to current session`,synthetic:!0,payload:{sessionId:r,task:e}}),s}return"update"===n.action||"complete"===n.action?n.taskId?[{type:"task:update",timestamp:t,payload:{id:n.taskId,title:n.title,status:"complete"===n.action?"done":"todo",steps:n.steps.map((e=>({id:e.id||xn(),text:e.text,completed:"done"===e.status?t:void 0}))),updated:t}}]:(console.warn("TaskProposalBlock with update/complete action is missing an ID."),[]):[]},"tool:use":(e,t)=>{const r=e;return[{type:"tool:call",timestamp:t,payload:{id:r.id,tool:r.name,arguments:r.input}}]}};process(e,t){const r=(new Date).toISOString();return e.blocks.flatMap((e=>{const n=this.handlers[e.type];return n?n(e,r,t):[]}))}};function Un(e){return Math.ceil(e.length/4)}function Ln(e,t){return Math.ceil(e/1024*t)}function jn(e){if("text"===e.kind)return e.value;if("json"===e.kind){const t=[],r=e=>{"string"==typeof e?t.push(e):e&&"object"==typeof e&&Object.values(e).forEach(r)};return r(e.value),t.join(" ")}return""}function Mn(e,t){return{id:crypto.randomUUID(),version:0,actor:e,blocks:t,timestamp:(new Date).toISOString(),parent:null}}var Fn=class{rank(e){const{entries:t,recentMessages:r,config:n}=e,s=n.recentMessageWindow??3,o=n.minScore??0,i=n.freshnessHalfLifeDays??30;if(0===r.length)return[...t].sort(((e,t)=>this.freshnessWeight(t.timestamp,i)-this.freshnessWeight(e.timestamp,i)));const a=this.tokenize(r.slice(-s).join(" "));return t.map((e=>{const t=jn(e.content);return{entry:e,score:.7*this.jaccardSimilarity(a,this.tokenize(t))+.3*this.freshnessWeight(e.timestamp,i)}})).filter((e=>e.score>o)).sort(((e,t)=>t.score-e.score)).map((e=>e.entry))}tokenize(e){return new Set(e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter((e=>e.length>2)))}jaccardSimilarity(e,t){if(0===e.size&&0===t.size)return 0;let r=0;for(const n of e)t.has(n)&&r++;const n=e.size+t.size-r;return 0===n?0:r/n}freshnessWeight(e,t){const r=(Date.now()-new Date(e).getTime())/864e5;return Math.pow(.5,r/t)}},Bn=class{plan(e){const{systemInstructions:t,persona:r,preferences:n,context:s,task:o,transcript:i,budget:a}=e;if(!a)return{preferences:n,context:s,task:o,transcript:i,truncated:{preferences:0,interactions:0,context:0},breakdown:{system:0,persona:0,preferences:0,transcript:0,context:0,tasks:0},totalUsed:0,lastRoleBeforeTruncation:null};const c=a.estimator??Un,l=a.blobTokensPerKB??.25;let u=a.total;const d={system:0,persona:0,preferences:0,transcript:0,context:0,tasks:0},h=c(t??""),f=c(r);u-=h+f,d.system+=h,d.persona+=f;const p=[];let m=0;for(const e of n){const t=c(e.content);u>=t?(u-=t,d.preferences+=t,p.push(e)):m++}const y=[];let _=0,g=null;for(let e=i.length-1;e>=0;e--){const t=i[e],r=this.estimateTurnTokens(t,c,l);u>=r?(u-=r,d.transcript+=r,y.unshift(t)):(_++,"user"!==t.actor||g||(g=t.role??null))}const b=[];let E=0;for(const e of s){let t=c(jn(e.content));"blob"===e.content.kind&&(t+=Ln(e.content.sizeBytes,l)),u>=t?(u-=t,d.context+=t,b.push(e)):E++}return{preferences:p,context:b,task:o,transcript:y,truncated:{preferences:m,interactions:_,context:E},breakdown:d,totalUsed:a.total-Math.max(0,u),lastRoleBeforeTruncation:g}}estimateTurnTokens(e,t,r){return e.blocks.reduce(((e,n)=>{switch(n.type){case"text":return e+t(n.text);case"tool:use":return e+t(JSON.stringify(n.input));case"tool:result":return e+t("string"==typeof n.content?n.content:JSON.stringify(n.content));case"thinking":return e+t(n.thinking);case"image":case"document":{const t=n.ref;return t?e+Ln(t.sizeBytes,r):e}default:return e}}),0)}},Gn=class{assemble(e){const{session:t,plan:r,resolvedBlobs:n,summaryBlockText:s,warnings:o,conflicts:i,budgetTotal:a}=e,c=[],l=[];for(const e of r.context)if("text"===e.content.kind||"json"===e.content.kind)c.push(e);else if("blob"===e.content.kind){const t=n.get(e.content.sha256);t&&l.push(this.buildReferentialBlock(e.content,t))}const d=[];if(l.length>0&&d.push(Mn("user",l)),s||r.truncated.interactions>0){const e=[];s&&e.push({type:"summary",text:s,id:"summary"}),r.truncated.interactions>0&&e.push({id:"notice",type:"text",text:`[${r.truncated.interactions} earlier turn(s) omitted due to token budget]`}),d.push(Mn("user",e)),d.push(Mn("assistant",[{id:u.v7(),type:"text",text:"Understood."}]))}let h=r.lastRoleBeforeTruncation,f=null!==r.lastRoleBeforeTruncation;for(const e of r.transcript){const t=this.resolveTurnBlocks(e,n);"user"===e.actor&&e.role&&f&&e.role!==h&&t.unshift({type:"role:transition",previousRole:h,newRole:e.role}),"user"===e.actor&&(h=e.role??null,f=!0),d.push({...e,blocks:t})}return{system:{instructions:t.instructions||"",persona:t.role.persona,preferences:r.preferences,context:c,task:r.task},context:r.context,transcript:{turns:d},budget:{total:a,used:r.totalUsed,breakdown:r.breakdown},truncated:r.truncated,warnings:o,conflicts:i}}buildReferentialBlock(e,t){return e.mediaType.startsWith("image/")?{type:"image",blob:t}:{type:"document",blob:t,title:e.filename}}resolveTurnBlocks(e,t){return e.blocks.map((e=>{if("image"===e.type||"document"===e.type){const r=e.ref;if(r){const n=t.get(r.sha256);if(n)return{...e,blob:n}}}return e}))}},Hn=class{constructor(e,t){this._actor=e,this._turn=t?structuredClone(t):{id:u.v7(),version:0,actor:this._actor,blocks:[],timestamp:(new Date).toISOString(),role:void 0,parent:null}}_turn;addText(e){const t={id:u.v7(),type:"text",text:e};return this._turn.blocks.push(t),this}addImage(e,t){const r={id:u.v7(),type:"image",ref:e,altText:t};return this._turn.blocks.push(r),this}addDocument(e,t){const r={id:u.v7(),type:"document",ref:e,title:t};return this._turn.blocks.push(r),this}addToolUse(e,t){const r={id:u.v7(),type:"tool:use",name:e,input:t};return this._turn.blocks.push(r),this}addToolResult(e,t,r){const n={id:u.v7(),type:"tool:result",useId:e,content:t,isError:r};return this._turn.blocks.push(n),this}addSummary(e){const t={id:u.v7(),type:"summary",text:e};return this._turn.blocks.push(t),this}addRoleTransition(e,t){const r={id:u.v7(),type:"role:transition",previousRole:e,newRole:t};return this._turn.blocks.push(r),this}addThinking(e){const t={id:u.v7(),type:"thinking",thinking:e};return this._turn.blocks.push(t),this}addTaskProposal(e,t,r="create",n){const s=t.map((e=>({id:e.id??u.v7(),text:e.text,status:e.status??"todo"}))),o={id:u.v7(),type:"task:proposal",title:e,steps:s,action:r,taskId:n};return this._turn.blocks.push(o),this}addBlock(e){return this._turn.blocks.push(e),this}deleteBlock(e){return this._turn.blocks=this._turn.blocks.filter((t=>t.id!==e)),this}editTextBlock(e,t){const r=this._turn.blocks.findIndex((t=>t.id===e));if(-1===r)throw new Error(`Block with ID ${e} not found.`);const n=this._turn.blocks[r];if("text"!==n.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[r]={...n,text:t},this}withId(e){return this._turn.id=e,this}withVersion(e){return this._turn.version=e,this}withTimestamp(e){return this._turn.timestamp=e,this}withParent(e){return this._turn.parent=e,this}withRoleSnapshot(e){return this._turn.role=e,this}build(){return structuredClone(this._turn)}},qn=class{constructor(e,t,r){this.sessionId=e,this.tree=t,this.manager=r}id(){return this.sessionId}meta(e){return e.index.sessions[this.sessionId]}label(e){return this.meta(e)?.label}roleName(e){return this.meta(e)?.role}role(e){const t=this.roleName(e);return t?e.index.roles[t]:void 0}topics(e){return this.meta(e)?.topics??[]}preferences(e){return this.meta(e)?.preferences??[]}head(e){return this.meta(e)?.head??null}async task(e){const t=this.meta(e)?.task;if(!t)return;const r=await this.manager.store().getTask(t);return r.ok?r.value:void 0}taskSummary(e){const t=this.meta(e)?.task;return t?e.index.tasks[t]:void 0}hasTask(e){const t=this.meta(e)?.task;return null!=t}async turns(){return this.tree.buildActiveChain(this.sessionId)}async siblings(e){return this.tree.getTurnSiblings(e,this.sessionId)}async branchInfo(e){return this.tree.branchInfo(e,this.sessionId)}async getTurn(e){return(await this.tree.buildNodeGraph(this.sessionId))[e]}async rename(e,t){return this.meta(e)?this.manager.dispatch(e,{type:"session:update",payload:{sessionId:this.sessionId,label:t},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async setTopics(e,t){return this.meta(e)?this.manager.dispatch(e,{type:"session:update",payload:{sessionId:this.sessionId,topics:t},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async addTopics(e,t){return this.meta(e)?this.manager.dispatch(e,{type:"session:topics:add",payload:{sessionId:this.sessionId,topics:t},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async setPreferences(e,t){return this.meta(e)?this.manager.dispatch(e,{type:"session:preferences:override",payload:{sessionId:this.sessionId,preferences:t},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async setActiveTask(e,t){return this.meta(e)?null===t||e.index.tasks[t]?this.manager.dispatch(e,{type:"session:update",payload:{sessionId:this.sessionId,task:t},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"task",id:t}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async unsetTask(e){return this.setActiveTask(e,null)}async createTask(e,t,r,n,s){const o={id:crypto.randomUUID(),title:t,description:r,status:"todo",steps:n.map((e=>({id:crypto.randomUUID(),text:e.text}))),topics:s,created:(new Date).toISOString(),updated:(new Date).toISOString()};return this.manager.dispatch(e,{type:"task:add",payload:o,timestamp:o.created})}async fork(e,t,r,n,s){return this.meta(e)?this.manager.dispatch(e,{type:"session:fork",payload:{sourceSessionId:this.sessionId,newSessionId:t,label:r,role:n,topics:s},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async delete(e){return this.meta(e)?this.manager.dispatch(e,{type:"session:delete",payload:{sessionId:this.sessionId},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async dispatch(e,t){return this.manager.dispatch(e,t)}async switchRole(e,t){return this.meta(e)?t===an||e.index.roles[t]?this.manager.dispatch(e,{type:"session:update",payload:{sessionId:this.sessionId,role:t},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"role",id:t}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}listRoles(e){return Object.values(e.index.roles)}getRole(e,t){return e.index.roles[t]}async createRole(e,t,r,n,s,o=[]){if(e.index.roles[t])return bn({code:"DUPLICATE_KEY",resource:"role",key:t});const i={name:t,label:r,description:s,persona:n,preferences:o};return this.manager.dispatch(e,{type:"role:add",payload:i,timestamp:(new Date).toISOString()})}async updateRole(e,t,r){return e.index.roles[t]?this.manager.dispatch(e,{type:"role:update",payload:{name:t,...r},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"role",id:t})}async deleteRole(e,t){if(!e.index.roles[t])return bn({code:"NOT_FOUND",resource:"role",id:t});return Object.values(e.index.sessions).some((e=>e.role===t))?bn({code:"INVALID_COMMAND",reason:`Cannot delete role "${t}" — it is still referenced by one or more sessions`}):this.manager.dispatch(e,{type:"role:delete",payload:{name:t},timestamp:(new Date).toISOString()})}async addTurn(e,t){if(!this.meta(e))return bn({code:"NOT_FOUND",resource:"session",id:this.sessionId});const r={...t,version:t.version??0};return this.manager.dispatch(e,{type:"turn:add",payload:{sessionId:this.sessionId,turn:r},timestamp:r.timestamp})}async recordUserTurn(e,t){return e.index.sessions[this.sessionId]?this.addTurn(e,t):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async recordAssistantTurn(e,t,r){if(!e.index.sessions[this.sessionId])return bn({code:"NOT_FOUND",resource:"session",id:this.sessionId});const n=this.manager.turnProcessor().process(t,this.sessionId);let s={},o=e;const i=[];for(const e of n){const t=await this.manager.dispatch(o,e);if(t.ok)s=_n(s,t.value),o=_n(o,t.value);else{if("PERMISSION_DENIED"!==t.error.code||e.synthetic)return t;{const t=this.describeCommand(e);i.push({cmd:e,description:t})}}}const a=await this.addTurn(o,t);if(!a.ok)return a;if(s=_n(s,a.value),r){const e=this.buildDenialTurn(i),t=await this.addTurn(o,e);t.ok&&(s=_n(s,t.value))}return gn(s)}buildDenialTurn(e){const t=new Hn("user");for(const r of e)t.addText(`[System] User denied: ${r.description}.`);return t.build()}describeCommand(e){switch(e.type){case"task:add":return`task creation: "${e.payload.title}"`;case"task:update":return`task update: "${e.payload.title}" (status: ${e.payload.status})`;case"task:delete":return`task deletion: ID ${e.payload.id}`;case"tool:call":return`tool execution: ${e.payload.tool}`;default:return`command: ${e.type}`}}async editTurn(e,t,r,n){if(!this.meta(e))return bn({code:"NOT_FOUND",resource:"session",id:this.sessionId});const s=await this.tree.loadTurnVersions(this.sessionId,t);if(0===s.length)return bn({code:"NOT_FOUND",resource:"turn",id:t});const o=Math.max(...s.map((e=>e.version))),i=s.find((e=>e.version===o)),a=o+1;return this.manager.dispatch(e,{type:"turn:edit",payload:{sessionId:this.sessionId,turnId:t,newBlocks:r,roleSnapshot:n??i.role,newVersion:a},timestamp:(new Date).toISOString()})}async branch(e,t){return this.meta(e)?t.parent?this.manager.dispatch(e,{type:"turn:branch",payload:{sessionId:this.sessionId,turn:t},timestamp:t.timestamp}):bn({code:"INVALID_COMMAND",reason:"branch requires turn.parent to be set"}):bn({code:"NOT_FOUND",resource:"session",id:this.sessionId})}async deleteTurn(e,t,r,n){if(!this.meta(e))return bn({code:"NOT_FOUND",resource:"session",id:this.sessionId});const s=await this.tree.loadTurnVersions(this.sessionId,t);if(0===s.length)return bn({code:"NOT_FOUND",resource:"turn",id:t});return s.some((e=>e.version===r))?this.manager.dispatch(e,{type:"turn:delete",payload:{sessionId:this.sessionId,turnId:t,version:r,newHead:n},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"turn version",id:`${t}:${r}`})}async switchVersionLeft(e,t){return this.switchVersion(e,t,-1)}async switchVersionRight(e,t){return this.switchVersion(e,t,1)}async switchVersion(e,t,r){if(!this.meta(e))return bn({code:"NOT_FOUND",resource:"session",id:this.sessionId});const n=await this.tree.buildNodeGraph(this.sessionId),s=n[t];if(!s)return bn({code:"NOT_FOUND",resource:"turn",id:t});const o=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),i=o.indexOf(s.activeVersion);if(-1===i)return bn({code:"INVALID_COMMAND",reason:"Active version not found in version list"});const a=i+r;if(a<0||a>=o.length)return bn({code:"INVALID_COMMAND",reason:`No ${r<0?"previous":"next"} version available for turn ${t}`});const c=o[a],l=this.findSubtreeTip(n,t,c);return await this.tree.setHead(this.sessionId,l),gn({index:{sessions:{[this.sessionId]:{head:l,metadata:{updated:(new Date).toISOString()}}}}})}async addPreference(e,t,r){const n={id:crypto.randomUUID(),content:t,topics:r,timestamp:(new Date).toISOString()};return this.manager.dispatch(e,{type:"preference:add",payload:n,timestamp:n.timestamp})}async listPreferences(e){return Object.values(e.index.preferences)}async addContext(e,t,r,n,s){const o={key:t,topics:n,content:r,timestamp:(new Date).toISOString(),metadata:s};return this.manager.dispatch(e,{type:"context:add",payload:o,timestamp:o.timestamp})}async listContextSummaries(e){return Object.values(e.index.context)}async registerBlob(e,t,r,n){const s=await this.manager.dispatch(e,{type:"blob:register",payload:{data:t,mediaType:r,filename:n},timestamp:(new Date).toISOString()});if(!s.ok)return bn(s.error);const o=s.value,i=o?.index?.blobs;if(!i)return bn({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no blobs patch returned"});const a=Object.keys(i)[0];if(!a)return bn({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no SHA256 in patch"});const c=i[a];if(!c)return bn({code:"BACKEND_ERROR",reason:"Blob record missing after registration"});return gn({sha256:a,ref:{sha256:a,mediaType:c.mediaType,sizeBytes:c.sizeBytes,filename:c.filename,previewUrl:c.previewUrl}})}async resolve(e){if(!this.meta(e))return bn({code:"NOT_FOUND",resource:"session",id:this.sessionId});const t=(await this.turns()).map((e=>e.versions[e.activeVersion]));return this.manager.resolveSession(e,this.sessionId,t)}findSubtreeTip(e,t,r){let n=t,s=r;for(;;){const t=e[n];if(!t)break;const r=t.children[s];if(!r||0===r.length)break;const o=r[0],i=e[o];if(!i)break;n=o,s=i.activeVersion}return{id:n,version:s}}},$n="blob_bytes",Wn="blob_records";function Vn(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}function Yn(e){return new Promise(((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error),e.onabort=()=>r(new Error("Transaction aborted"))}))}var zn,Kn,Jn,Xn,Qn,Zn,es,ts,rs,ns,ss,os,is,as,cs,ls,us,ds,hs,fs,ps,ms,ys,_s,gs,bs,Es,ws,Ts,vs,Ss,As,Os,Is,Cs,Rs,ks,Ns,Ps,xs,Ds,Us,Ls,js,Ms,Fs,Bs,Gs,Hs,qs,$s,Ws,Vs,Ys,zs,Ks,Js,Xs,Qs,Zs,eo,to,ro,no,so,oo,io,ao,co,lo,uo,ho,fo,po,mo,yo,_o,go,bo,Eo,wo,To,vo,So,Ao,Oo,Io,Co,Ro,ko,No,Po,xo,Do,Uo,Lo,jo,Mo,Fo,Bo,Go,Ho,qo,$o,Wo,Vo,Yo,zo,Ko,Jo,Xo,Qo,Zo,ei,ti,ri,ni,si,oi,ii,ai,ci,li,ui,di,hi,fi,pi,mi,yi,_i;function gi(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]])}return r}function bi(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ei(e){return this instanceof Ei?(this.v=e,this):new Ei(e)}function wi(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(e,t||[]),o=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),i("next"),i("throw"),i("return",(function(e){return function(t){return Promise.resolve(t).then(e,l)}})),n[Symbol.asyncIterator]=function(){return this},n;function i(e,t){s[e]&&(n[e]=function(t){return new Promise((function(r,n){o.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=s[e](t)).value instanceof Ei?Promise.resolve(r.value.v).then(c,l):u(o[0][2],r)}catch(e){u(o[0][3],e)}var r}function c(e){a("next",e)}function l(e){a("throw",e)}function u(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}}function Ti(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=bi(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,s){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,s,(t=e[r](t)).done,t.value)}))}}}I(P(),1),I(Vr(),1),I(nn(),1),I(Qr(),1),I(Zr(),1),I(rn(),1),I(on(),1),(Kn=zn||(zn={})).LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",Kn.PYTHON="PYTHON",(Xn=Jn||(Jn={})).OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",Xn.OUTCOME_OK="OUTCOME_OK",Xn.OUTCOME_FAILED="OUTCOME_FAILED",Xn.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED",(Zn=Qn||(Qn={})).SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",Zn.SILENT="SILENT",Zn.WHEN_IDLE="WHEN_IDLE",Zn.INTERRUPT="INTERRUPT",(ts=es||(es={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",ts.STRING="STRING",ts.NUMBER="NUMBER",ts.INTEGER="INTEGER",ts.BOOLEAN="BOOLEAN",ts.ARRAY="ARRAY",ts.OBJECT="OBJECT",ts.NULL="NULL",(ns=rs||(rs={})).ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",ns.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",(os=ss||(ss={})).AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",os.NO_AUTH="NO_AUTH",os.API_KEY_AUTH="API_KEY_AUTH",os.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",os.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",os.OAUTH="OAUTH",os.OIDC_AUTH="OIDC_AUTH",(as=is||(is={})).HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",as.HTTP_IN_QUERY="HTTP_IN_QUERY",as.HTTP_IN_HEADER="HTTP_IN_HEADER",as.HTTP_IN_PATH="HTTP_IN_PATH",as.HTTP_IN_BODY="HTTP_IN_BODY",as.HTTP_IN_COOKIE="HTTP_IN_COOKIE",(ls=cs||(cs={})).API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",ls.SIMPLE_SEARCH="SIMPLE_SEARCH",ls.ELASTIC_SEARCH="ELASTIC_SEARCH",(ds=us||(us={})).PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",ds.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",ds.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",ds.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",ds.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",ds.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",ds.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH",(fs=hs||(hs={})).UNSPECIFIED="UNSPECIFIED",fs.BLOCKING="BLOCKING",fs.NON_BLOCKING="NON_BLOCKING",(ms=ps||(ps={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",ms.MODE_DYNAMIC="MODE_DYNAMIC",(_s=ys||(ys={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",_s.AUTO="AUTO",_s.ANY="ANY",_s.NONE="NONE",_s.VALIDATED="VALIDATED",(bs=gs||(gs={})).THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",bs.MINIMAL="MINIMAL",bs.LOW="LOW",bs.MEDIUM="MEDIUM",bs.HIGH="HIGH",(ws=Es||(Es={})).DONT_ALLOW="DONT_ALLOW",ws.ALLOW_ADULT="ALLOW_ADULT",ws.ALLOW_ALL="ALLOW_ALL",(vs=Ts||(Ts={})).PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",vs.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",vs.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE",(As=Ss||(Ss={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",As.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",As.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",As.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",As.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",As.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",As.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",As.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",As.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",As.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",As.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",(Is=Os||(Os={})).HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",Is.SEVERITY="SEVERITY",Is.PROBABILITY="PROBABILITY",(Rs=Cs||(Cs={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",Rs.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",Rs.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",Rs.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",Rs.BLOCK_NONE="BLOCK_NONE",Rs.OFF="OFF",(Ns=ks||(ks={})).FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",Ns.STOP="STOP",Ns.MAX_TOKENS="MAX_TOKENS",Ns.SAFETY="SAFETY",Ns.RECITATION="RECITATION",Ns.LANGUAGE="LANGUAGE",Ns.OTHER="OTHER",Ns.BLOCKLIST="BLOCKLIST",Ns.PROHIBITED_CONTENT="PROHIBITED_CONTENT",Ns.SPII="SPII",Ns.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",Ns.IMAGE_SAFETY="IMAGE_SAFETY",Ns.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",Ns.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",Ns.NO_IMAGE="NO_IMAGE",Ns.IMAGE_RECITATION="IMAGE_RECITATION",Ns.IMAGE_OTHER="IMAGE_OTHER",(xs=Ps||(Ps={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",xs.NEGLIGIBLE="NEGLIGIBLE",xs.LOW="LOW",xs.MEDIUM="MEDIUM",xs.HIGH="HIGH",(Us=Ds||(Ds={})).HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",Us.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",Us.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",Us.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",Us.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH",(js=Ls||(Ls={})).URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",js.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",js.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",js.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",js.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE",(Fs=Ms||(Ms={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",Fs.SAFETY="SAFETY",Fs.OTHER="OTHER",Fs.BLOCKLIST="BLOCKLIST",Fs.PROHIBITED_CONTENT="PROHIBITED_CONTENT",Fs.IMAGE_SAFETY="IMAGE_SAFETY",Fs.MODEL_ARMOR="MODEL_ARMOR",Fs.JAILBREAK="JAILBREAK",(Gs=Bs||(Bs={})).TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",Gs.ON_DEMAND="ON_DEMAND",Gs.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",Gs.ON_DEMAND_FLEX="ON_DEMAND_FLEX",Gs.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT",(qs=Hs||(Hs={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",qs.TEXT="TEXT",qs.IMAGE="IMAGE",qs.AUDIO="AUDIO",qs.VIDEO="VIDEO",(Ws=$s||($s={})).MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",Ws.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",Ws.EXPERIMENTAL="EXPERIMENTAL",Ws.PREVIEW="PREVIEW",Ws.STABLE="STABLE",Ws.LEGACY="LEGACY",Ws.DEPRECATED="DEPRECATED",Ws.RETIRED="RETIRED",(Ys=Vs||(Vs={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",Ys.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",Ys.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",Ys.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",(Ks=zs||(zs={})).TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",Ks.TUNING_MODE_FULL="TUNING_MODE_FULL",Ks.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER",(Xs=Js||(Js={})).ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",Xs.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",Xs.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",Xs.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",Xs.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",Xs.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",Xs.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO",(Zs=Qs||(Qs={})).JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",Zs.JOB_STATE_QUEUED="JOB_STATE_QUEUED",Zs.JOB_STATE_PENDING="JOB_STATE_PENDING",Zs.JOB_STATE_RUNNING="JOB_STATE_RUNNING",Zs.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",Zs.JOB_STATE_FAILED="JOB_STATE_FAILED",Zs.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",Zs.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",Zs.JOB_STATE_PAUSED="JOB_STATE_PAUSED",Zs.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",Zs.JOB_STATE_UPDATING="JOB_STATE_UPDATING",Zs.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED",(to=eo||(eo={})).TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",to.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",to.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",to.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",to.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",to.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING",(no=ro||(ro={})).AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",no.AVERAGE="AVERAGE",no.MODE="MODE",no.STANDARD_DEVIATION="STANDARD_DEVIATION",no.VARIANCE="VARIANCE",no.MINIMUM="MINIMUM",no.MAXIMUM="MAXIMUM",no.MEDIAN="MEDIAN",no.PERCENTILE_P90="PERCENTILE_P90",no.PERCENTILE_P95="PERCENTILE_P95",no.PERCENTILE_P99="PERCENTILE_P99",(oo=so||(so={})).PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",oo.BASELINE="BASELINE",oo.CANDIDATE="CANDIDATE",oo.TIE="TIE",(ao=io||(io={})).TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",ao.TUNING_TASK_I2V="TUNING_TASK_I2V",ao.TUNING_TASK_T2V="TUNING_TASK_T2V",ao.TUNING_TASK_R2V="TUNING_TASK_R2V",(lo=co||(co={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",lo.STATE_PENDING="STATE_PENDING",lo.STATE_ACTIVE="STATE_ACTIVE",lo.STATE_FAILED="STATE_FAILED",(ho=uo||(uo={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",ho.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",ho.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",ho.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",ho.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH",(po=fo||(fo={})).TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",po.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",po.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",po.URL_CONTEXT="URL_CONTEXT",po.GOOGLE_MAPS="GOOGLE_MAPS",po.FILE_SEARCH="FILE_SEARCH",(mo||(mo={})).COLLECTION="COLLECTION",(_o=yo||(yo={})).UNSPECIFIED="unspecified",_o.FLEX="flex",_o.STANDARD="standard",_o.PRIORITY="priority",(bo=go||(go={})).FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",bo.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",bo.BALANCED="BALANCED",bo.PRIORITIZE_COST="PRIORITIZE_COST",(wo=Eo||(Eo={})).PREDICT="PREDICT",wo.EMBED_CONTENT="EMBED_CONTENT",(vo=To||(To={})).BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",vo.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",vo.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",vo.BLOCK_NONE="BLOCK_NONE",(Ao=So||(So={})).auto="auto",Ao.en="en",Ao.ja="ja",Ao.ko="ko",Ao.hi="hi",Ao.zh="zh",Ao.pt="pt",Ao.es="es",(Io=Oo||(Oo={})).MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",Io.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",Io.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",Io.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",Io.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC",(Ro=Co||(Co={})).CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",Ro.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",Ro.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",Ro.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH",(No=ko||(ko={})).SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",No.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",No.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",No.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT",(xo=Po||(Po={})).EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",xo.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",xo.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",xo.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",xo.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",xo.EDIT_MODE_STYLE="EDIT_MODE_STYLE",xo.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",xo.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE",(Uo=Do||(Do={})).FOREGROUND="FOREGROUND",Uo.BACKGROUND="BACKGROUND",Uo.PROMPT="PROMPT",Uo.SEMANTIC="SEMANTIC",Uo.INTERACTIVE="INTERACTIVE",(jo=Lo||(Lo={})).ASSET="ASSET",jo.STYLE="STYLE",(Fo=Mo||(Mo={})).INSERT="INSERT",Fo.REMOVE="REMOVE",Fo.REMOVE_STATIC="REMOVE_STATIC",Fo.OUTPAINT="OUTPAINT",(Go=Bo||(Bo={})).OPTIMIZED="OPTIMIZED",Go.LOSSLESS="LOSSLESS",(qo=Ho||(Ho={})).SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",qo.PREFERENCE_TUNING="PREFERENCE_TUNING",qo.DISTILLATION="DISTILLATION",(Wo=$o||($o={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",Wo.PROCESSING="PROCESSING",Wo.ACTIVE="ACTIVE",Wo.FAILED="FAILED",(Yo=Vo||(Vo={})).SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",Yo.UPLOADED="UPLOADED",Yo.GENERATED="GENERATED",Yo.REGISTERED="REGISTERED",(Ko=zo||(zo={})).TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",Ko.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",Ko.RESPONSE_REJECTED="RESPONSE_REJECTED",Ko.NEED_MORE_INPUT="NEED_MORE_INPUT",Ko.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",Ko.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",Ko.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",Ko.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",Ko.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",Ko.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",Ko.INPUT_OTHER="INPUT_OTHER",Ko.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",Ko.BLOCKLIST="BLOCKLIST",Ko.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",Ko.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",Ko.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",Ko.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",Ko.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",Ko.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",Ko.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",Ko.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",Ko.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",Ko.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",Ko.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",Ko.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",Ko.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",Ko.GENERATED_OTHER="GENERATED_OTHER",Ko.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED",(Xo=Jo||(Jo={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Xo.TEXT="TEXT",Xo.IMAGE="IMAGE",Xo.VIDEO="VIDEO",Xo.AUDIO="AUDIO",Xo.DOCUMENT="DOCUMENT",(Zo=Qo||(Qo={})).VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",Zo.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",Zo.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS",(ti=ei||(ei={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",ti.ACTIVITY_START="ACTIVITY_START",ti.ACTIVITY_END="ACTIVITY_END",(ni=ri||(ri={})).START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",ni.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",ni.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW",(oi=si||(si={})).END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",oi.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",oi.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW",(ai=ii||(ii={})).ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",ai.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",ai.NO_INTERRUPTION="NO_INTERRUPTION",(li=ci||(ci={})).TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",li.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",li.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",li.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO",(di=ui||(ui={})).SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",di.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",di.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",di.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",di.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",di.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",di.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",di.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",di.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",di.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",di.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",di.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",di.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR",(fi=hi||(hi={})).MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",fi.QUALITY="QUALITY",fi.DIVERSITY="DIVERSITY",fi.VOCALIZATION="VOCALIZATION",(mi=pi||(pi={})).PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",mi.PLAY="PLAY",mi.PAUSE="PAUSE",mi.STOP="STOP",mi.RESET_CONTEXT="RESET_CONTEXT",(_i=yi||(yi={})).PAGED_ITEM_BATCH_JOBS="batchJobs",_i.PAGED_ITEM_MODELS="models",_i.PAGED_ITEM_TUNING_JOBS="tuningJobs",_i.PAGED_ITEM_FILES="files",_i.PAGED_ITEM_CACHED_CONTENTS="cachedContents",_i.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",_i.PAGED_ITEM_DOCUMENTS="documents";var vi=function(){const{crypto:e}=globalThis;if(null==e?void 0:e.randomUUID)return vi=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^r()&15>>+e/4).toString(16)))};function Si(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Ai=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch(e){}try{return new Error(JSON.stringify(e))}catch(e){}}return new Error(e)},Oi=class extends Error{},Ii=class e extends Oi{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(e,t,r){const n=(null==t?void 0:t.message)?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new Ri({message:n,cause:Ai(r)});const o=r;return 400===t?new Ni(t,o,n,s):401===t?new Pi(t,o,n,s):403===t?new xi(t,o,n,s):404===t?new Di(t,o,n,s):409===t?new Ui(t,o,n,s):422===t?new Li(t,o,n,s):429===t?new ji(t,o,n,s):t>=500?new Mi(t,o,n,s):new e(t,o,n,s)}},Ci=class extends Ii{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Ri=class extends Ii{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ki=class extends Ri{constructor({message:e}={}){super({message:null!=e?e:"Request timed out."})}},Ni=class extends Ii{},Pi=class extends Ii{},xi=class extends Ii{},Di=class extends Ii{},Ui=class extends Ii{},Li=class extends Ii{},ji=class extends Ii{},Mi=class extends Ii{},Fi=/^[a-z][a-z0-9+.-]*:/i,Bi=e=>(Bi=Array.isArray)(e),Gi=Bi;function Hi(e){if(!e)return!0;for(const t in e)return!1;return!0}function qi(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function $i(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return qi({start(){},async pull(e){const{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){var e;await(null===(e=t.return)||void 0===e?void 0:e.call(t))}})}function Wi(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return(null==e?void 0: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}}}var Vi=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Yi=()=>{var e;if("undefined"==typeof File){const{process:t}=globalThis,r="string"==typeof(null===(e=null==t?void 0:t.versions)||void 0===e?void 0:e.node)&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(r?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function zi(e,t,r){return Yi(),new File(e,null!=t?t:"unknown_file",r)}var Ki=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 Ji(e){var t,r,n,s,o;let i=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)i.push(e);else if(Ki(e))i.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!(e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator])(e)){const t=null===(o=null==e?void 0:e.constructor)||void 0===o?void 0:o.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`)}try{for(var a,c=!0,l=Ti(e);!(t=(a=await l.next()).done);c=!0){s=a.value,c=!1;const e=s;i.push(...await Ji(e))}}catch(e){r={error:e}}finally{try{c||t||!(n=l.return)||await n.call(l)}finally{if(r)throw r.error}}}return i}var Xi=class{constructor(e){this._client=e}};function Qi(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}Xi._key=[];var Zi=Object.freeze(Object.create(null)),ea=((e=Qi)=>function(t,...r){if(1===t.length)return t[0];let n=!1;const s=[],o=t.reduce(((t,o,i)=>{var a,c,l;/[?#]/.test(o)&&(n=!0);const u=r[i];let d=(n?encodeURIComponent:e)(""+u);return i!==r.length&&(null==u||"object"==typeof u&&u.toString===(null===(l=Object.getPrototypeOf(null!==(c=Object.getPrototypeOf(null!==(a=u.hasOwnProperty)&&void 0!==a?a:Zi))&&void 0!==c?c:Zi))||void 0===l?void 0:l.toString))&&(d=u+"",s.push({start:t.length+o.length,length:d.length,error:`Value of type ${Object.prototype.toString.call(u).slice(8,-1)} is not a valid path parameter`})),t+o+(i===r.length?"":d)}),""),i=o.split(/[?#]/,1)[0],a=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=a.exec(i));){const e=c[0].startsWith("/"),t=e?1:0,r=e?c[0].slice(1):c[0];s.push({start:c.index+t,length:r.length,error:`Value "${r}" can't be safely passed as a path parameter`})}if(s.sort(((e,t)=>e.start-t.start)),s.length>0){let e=0;const t=s.reduce(((t,r)=>{const n=" ".repeat(r.start-e),s="^".repeat(r.length);return e=r.start+r.length,t+n+s}),"");throw new Oi(`Path parameters result in path with invalid segments:\n${s.map((e=>e.error)).join("\n")}\n${o}\n${t}`)}return o})(Qi),ta=class extends Xi{create(e,t){var r;const{api_version:n=this._client.apiVersion}=e,s=gi(e,["api_version"]);if("model"in s&&"agent_config"in s)throw new Oi("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in s&&"generation_config"in s)throw new Oi("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(ea`/${n}/interactions`,Object.assign(Object.assign({body:s},t),{stream:null!==(r=e.stream)&&void 0!==r&&r}))}delete(e,t={},r){const{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(ea`/${n}/interactions/${e}`,r)}cancel(e,t={},r){const{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.post(ea`/${n}/interactions/${e}/cancel`,r)}get(e,t={},r){var n;const s=null!=t?t:{},{api_version:o=this._client.apiVersion}=s,i=gi(s,["api_version"]);return this._client.get(ea`/${o}/interactions/${e}`,Object.assign(Object.assign({query:i},r),{stream:null!==(n=null==t?void 0:t.stream)&&void 0!==n&&n}))}};ta._key=Object.freeze(["interactions"]);var ra=class extends ta{},na=class extends Xi{create(e,t){const{api_version:r=this._client.apiVersion,webhook_id:n}=e,s=gi(e,["api_version","webhook_id"]);return this._client.post(ea`/${r}/webhooks`,Object.assign({query:{webhook_id:n},body:s},t))}update(e,t,r){const{api_version:n=this._client.apiVersion,update_mask:s}=t,o=gi(t,["api_version","update_mask"]);return this._client.patch(ea`/${n}/webhooks/${e}`,Object.assign({query:{update_mask:s},body:o},r))}list(e={},t){const r=null!=e?e:{},{api_version:n=this._client.apiVersion}=r,s=gi(r,["api_version"]);return this._client.get(ea`/${n}/webhooks`,Object.assign({query:s},t))}delete(e,t={},r){const{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(ea`/${n}/webhooks/${e}`,r)}get(e,t={},r){const{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.get(ea`/${n}/webhooks/${e}`,r)}ping(e,t=void 0,r){const{api_version:n=this._client.apiVersion,body:s}=null!=t?t:{};return this._client.post(ea`/${n}/webhooks/${e}:ping`,Object.assign({body:s},r))}rotateSigningSecret(e,t={},r){const n=null!=t?t:{},{api_version:s=this._client.apiVersion}=n,o=gi(n,["api_version"]);return this._client.post(ea`/${s}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:o},r))}};na._key=Object.freeze(["webhooks"]);var sa,oa,ia=class extends na{};function aa(e){let t;return(null!=sa?sa:(t=new globalThis.TextEncoder,sa=t.encode.bind(t)))(e)}function ca(e){let t;return(null!=oa?oa:(t=new globalThis.TextDecoder,oa=t.decode.bind(t)))(e)}var la=class{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var t;if(null==e)return[];const r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?aa(e):e;this.buffer=function(e){let t=0;for(const r of e)t+=r.length;const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}([this.buffer,r]);const n=[];let s;for(;null!=(s=ua(this.buffer,null!==(t=this.carriageReturnIndex)&&void 0!==t?t:this.searchIndex));){if(s.carriage&&null==this.carriageReturnIndex){this.carriageReturnIndex=s.index;continue}if(null!=this.carriageReturnIndex&&(s.index!==this.carriageReturnIndex+1||s.carriage)){n.push(ca(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}const e=null!==this.carriageReturnIndex?s.preceding-1:s.preceding,t=ca(this.buffer.subarray(0,e));n.push(t),this.buffer=this.buffer.subarray(s.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),n}flush(){return this.buffer.length?this.decode("\n"):[]}};function ua(e,t){const r=null!=t?t:0,n=e.indexOf(10,r),s=e.indexOf(13,r);if(-1===n&&-1===s)return null;let o;return o=-1!==n&&-1!==s?Math.min(n,s):-1!==n?n:s,10===e[o]?{preceding:o,index:o+1,carriage:!1}:{preceding:o,index:o+1,carriage:!0}}la.NEWLINE_CHARS=new Set(["\n","\r"]),la.NEWLINE_REGEXP=/\r\n|[\n\r]/g;var da={off:0,error:200,warn:300,info:400,debug:500},ha=(e,t,r)=>{var n,s;if(e)return n=da,s=e,Object.prototype.hasOwnProperty.call(n,s)?e:void _a(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(da))}`)};function fa(){}function pa(e,t,r){return!t||da[e]>da[r]?fa:t[e].bind(t)}var ma={error:fa,warn:fa,info:fa,debug:fa},ya=new WeakMap;function _a(e){var t;const r=e.logger,n=null!==(t=e.logLevel)&&void 0!==t?t:"off";if(!r)return ma;const s=ya.get(r);if(s&&s[0]===n)return s[1];const o={error:pa("error",r,n),warn:pa("warn",r,n),info:pa("info",r,n),debug:pa("debug",r,n)};return ya.set(r,[n,o]),o}var ga=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map((([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t])))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),ba=class e{constructor(e,t,r){this.iterator=e,this.controller=t,this.client=r}static fromSSEResponse(t,r,n){let s=!1;const o=n?_a(n):console;return new e((function(){return wi(this,arguments,(function*(){var e,n,i,a;if(s)throw new Oi("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{try{for(var l,u=!0,d=Ti(function(e,t){return wi(this,arguments,(function*(){var r,n,s,o;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new Oi("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new Oi("Attempted to iterate over a response with no body")}const i=new Ea,a=new la,c=Wi(e.body);try{for(var l,u=!0,d=Ti(function(e){return wi(this,arguments,(function*(){var t,r,n,s;try{for(var o,i=!0,a=Ti(e);!(t=(o=yield Ei(a.next())).done);i=!0){s=o.value,i=!1;const e=s;if(null==e)continue;const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?aa(e):e;yield yield Ei(t)}}catch(e){r={error:e}}finally{try{i||t||!(n=a.return)||(yield Ei(n.call(a)))}finally{if(r)throw r.error}}}))}(c));!(r=(l=yield Ei(d.next())).done);u=!0){o=l.value,u=!1;const e=o;for(const t of a.decode(e)){const e=i.decode(t);e&&(yield yield Ei(e))}}}catch(e){n={error:e}}finally{try{u||r||!(s=d.return)||(yield Ei(s.call(d)))}finally{if(n)throw n.error}}for(const e of a.flush()){const t=i.decode(e);t&&(yield yield Ei(t))}}))}(t,r));!(e=(l=yield Ei(d.next())).done);u=!0){a=l.value,u=!1;const e=a;if(!c)if(e.data.startsWith("[DONE]"))c=!0;else try{yield yield Ei(JSON.parse(e.data))}catch(t){throw o.error("Could not parse message into JSON:",e.data),o.error("From chunk:",e.raw),t}}}catch(e){n={error:e}}finally{try{u||e||!(i=d.return)||(yield Ei(i.call(d)))}finally{if(n)throw n.error}}c=!0}catch(e){if(Si(e))return yield Ei(void 0);throw e}finally{c||r.abort()}}))}),r,n)}static fromReadableStream(t,r,n){let s=!1;return new e((function(){return wi(this,arguments,(function*(){var e,n,o,i;if(s)throw new Oi("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{try{for(var c,l=!0,u=Ti(function(){return wi(this,arguments,(function*(){var e,r,n,s;const o=new la,i=Wi(t);try{for(var a,c=!0,l=Ti(i);!(e=(a=yield Ei(l.next())).done);c=!0){s=a.value,c=!1;const e=s;for(const t of o.decode(e))yield yield Ei(t)}}catch(e){r={error:e}}finally{try{c||e||!(n=l.return)||(yield Ei(n.call(l)))}finally{if(r)throw r.error}}for(const e of o.flush())yield yield Ei(e)}))}());!(e=(c=yield Ei(u.next())).done);l=!0){i=c.value,l=!1;const e=i;a||e&&(yield yield Ei(JSON.parse(e)))}}catch(e){n={error:e}}finally{try{l||e||!(o=u.return)||(yield Ei(o.call(u)))}finally{if(n)throw n.error}}a=!0}catch(e){if(Si(e))return yield Ei(void 0);throw e}finally{a||r.abort()}}))}),r,n)}[Symbol.asyncIterator](){return this.iterator()}tee(){const t=[],r=[],n=this.iterator(),s=e=>({next:()=>{if(0===e.length){const e=n.next();t.push(e),r.push(e)}return e.shift()}});return[new e((()=>s(t)),this.controller,this.client),new e((()=>s(r)),this.controller,this.client)]}toReadableStream(){const e=this;let t;return qi({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:r,done:n}=await t.next();if(n)return e.close();const s=aa(JSON.stringify(r)+"\n");e.enqueue(s)}catch(t){e.error(t)}},async cancel(){var e;await(null===(e=t.return)||void 0===e?void 0:e.call(t))}})}};var Ea=class{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,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}};async function wa(e,t){const{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,i=await(async()=>{var n;if(t.options.stream)return _a(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller,e):ba.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;const s=r.headers.get("content-type"),o=null===(n=null==s?void 0:s.split(";")[0])||void 0===n?void 0:n.trim();if((null==o?void 0:o.includes("application/json"))||(null==o?void 0:o.endsWith("+json"))){if("0"===r.headers.get("content-length"))return;return await r.json()}return await r.text()})();return _a(e).debug(`[${n}] response parsed`,ga({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}var Ta=class e extends Promise{constructor(e,t,r=wa){super((e=>{e(null)})),this.responsePromise=t,this.parseResponse=r,this.client=e}_thenUnwrap(t){return new e(this.client,this.responsePromise,(async(e,r)=>t(await this.parseResponse(e,r),r)))}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}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then((e=>this.parseResponse(this.client,e)))),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)}},va=Symbol("brand.privateNullableHeaders");function*Sa(e){if(!e)return;if(va in e){const{values:t,nulls:r}=e;yield*t.entries();for(const e of r)yield[e,null];return}let t,r=!1;e instanceof Headers?t=e.entries():Gi(e)?t=e:(r=!0,t=Object.entries(null!=e?e:{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=Gi(e[1])?e[1]:[e[1]];let s=!1;for(const e of n)void 0!==e&&(r&&!s&&(s=!0,yield[t,null]),yield[t,e])}}var Aa,Oa=e=>{const t=new Headers,r=new Set;for(const n of e){const e=new Set;for(const[s,o]of Sa(n)){const n=s.toLowerCase();e.has(n)||(t.delete(s),e.add(n)),null===o?(t.delete(s),r.add(n)):(t.append(s,o),r.delete(n))}}return{[va]:!0,values:t,nulls:r}},Ia=e=>{var t,r,n,s,o;return void 0!==globalThis.process?(null===(r=null===(t=globalThis.process.env)||void 0===t?void 0:t[e])||void 0===r?void 0:r.trim())||void 0:void 0!==globalThis.Deno&&(null===(o=null===(s=null===(n=globalThis.Deno.env)||void 0===n?void 0:n.get)||void 0===s?void 0:s.call(n,e))||void 0===o?void 0:o.trim())||void 0},Ca=class e{constructor(t){var r,n,s,o,i,a,c,{baseURL:l=Ia("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=(null!==(r=Ia("GEMINI_API_KEY"))&&void 0!==r?r:null),apiVersion:d="v1beta"}=t,h=gi(t,["baseURL","apiKey","apiVersion"]);const f=Object.assign(Object.assign({apiKey:u,apiVersion:d},h),{baseURL:l||"https://generativelanguage.googleapis.com"});this.baseURL=f.baseURL,this.timeout=null!==(n=f.timeout)&&void 0!==n?n:e.DEFAULT_TIMEOUT,this.logger=null!==(s=f.logger)&&void 0!==s?s:console;const p="warn";this.logLevel=p,this.logLevel=null!==(i=null!==(o=ha(f.logLevel,"ClientOptions.logLevel",this))&&void 0!==o?o:ha(Ia("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))&&void 0!==i?i:p,this.fetchOptions=f.fetchOptions,this.maxRetries=null!==(a=f.maxRetries)&&void 0!==a?a:2,this.fetch=null!==(c=f.fetch)&&void 0!==c?c:function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),this.encoder=Vi,this._options=f,this.apiKey=u,this.apiVersion=d,this.clientAdapter=f.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!e.has("authorization")&&!e.has("x-goog-api-key")&&!(this.apiKey&&e.get("x-goog-api-key")||t.has("x-goog-api-key")))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){const t=Oa([e.headers]);if(!t.values.has("authorization")&&!t.values.has("x-goog-api-key"))return this.apiKey?Oa([{"x-goog-api-key":this.apiKey}]):this.clientAdapter&&this.clientAdapter.isVertexAI()?Oa([await this.clientAdapter.getAuthHeaders()]):void 0}stringifyQuery(e){return function(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 Oi(`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("&")}(e)}getUserAgent(){return`${this.constructor.name}/JS 0.0.1`}defaultIdempotencyKey(){return`stainless-node-retry-${vi()}`}makeStatusError(e,t,r,n){return Ii.generate(e,t,r,n)}buildURL(e,t,r){const n=!this.baseURLOverridden()&&r||this.baseURL,s=(e=>Fi.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return Hi(o)&&Hi(i)||(t=Object.assign(Object.assign(Object.assign({},i),o),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){const t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then((r=>Object.assign({method:e,path:t},r))))}request(e,t=null){return new Ta(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var n,s,o;const i=await e,a=null!==(n=i.maxRetries)&&void 0!==n?n:this.maxRetries;null==t&&(t=a),await this.prepareOptions(i);const{req:c,url:l,timeout:u}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(c,{url:l,options:i});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),h=void 0===r?"":`, retryOf: ${r}`,f=Date.now();if(_a(this).debug(`[${d}] sending request`,ga({retryOfRequestLogID:r,method:i.method,url:l,options:i,headers:c.headers})),null===(s=i.signal)||void 0===s?void 0:s.aborted)throw new Ci;const p=new AbortController,m=await this.fetchWithTimeout(l,c,u,p).catch(Ai),y=Date.now();if(m instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(null===(o=i.signal)||void 0===o?void 0:o.aborted)throw new Ci;const n=Si(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return _a(this).info(`[${d}] connection ${n?"timed out":"failed"} - ${e}`),_a(this).debug(`[${d}] connection ${n?"timed out":"failed"} (${e})`,ga({retryOfRequestLogID:r,url:l,durationMs:y-f,message:m.message})),this.retryRequest(i,t,null!=r?r:d);if(_a(this).info(`[${d}] connection ${n?"timed out":"failed"} - error; no more retries left`),_a(this).debug(`[${d}] connection ${n?"timed out":"failed"} (error; no more retries left)`,ga({retryOfRequestLogID:r,url:l,durationMs:y-f,message:m.message})),n)throw new ki;throw new Ri({cause:m})}const _=`[${d}${h}] ${c.method} ${l} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${y-f}ms`;if(!m.ok){const e=await this.shouldRetry(m);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){var t,r;if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(null===(r=(t=e[Symbol.asyncIterator]()).return)||void 0===r?void 0:r.call(t));const n=e.getReader(),s=n.cancel();n.releaseLock(),await s}(m.body),_a(this).info(`${_} - ${e}`),_a(this).debug(`[${d}] response error (${e})`,ga({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:y-f})),this.retryRequest(i,t,null!=r?r:d,m.headers)}const n=e?"error; no more retries left":"error; not retryable";_a(this).info(`${_} - ${n}`);const s=await m.text().catch((e=>Ai(e).message)),o=(e=>{try{return JSON.parse(e)}catch(e){return}})(s),a=o?void 0:s;_a(this).debug(`[${d}] response error (${n})`,ga({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:a,durationMs:Date.now()-f}));throw this.makeStatusError(m.status,o,a,m.headers)}return _a(this).info(_),_a(this).debug(`[${d}] response start`,ga({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:y-f})),{response:m,options:i,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:f}}async fetchWithTimeout(e,t,r,n){const s=t||{},{signal:o,method:i}=s,a=gi(s,["signal","method"]),c=this._makeAbort(n);o&&o.addEventListener("abort",c,{once:!0});const l=setTimeout(c,r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,d=Object.assign(Object.assign(Object.assign({signal:n.signal},u?{duplex:"half"}:{}),{method:"GET"}),a);i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async 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,r,n){var s;let o;const i=null==n?void 0:n.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(o=e)}const a=null==n?void 0:n.get("retry-after");if(a&&!o){const e=parseFloat(a);o=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(void 0===o){const r=null!==(s=e.maxRetries)&&void 0!==s?s:this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,r)}var c;return await(c=o,new Promise((e=>setTimeout(e,c)))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var r,n,s;const o=Object.assign({},e),{method:i,path:a,query:c,defaultBaseURL:l}=o,u=this.buildURL(a,c,l);"timeout"in o&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Oi(`${e} must be an integer`);if(t<0)throw new Oi(`${e} must be a positive integer`)})("timeout",o.timeout),o.timeout=null!==(r=o.timeout)&&void 0!==r?r:this.timeout;const{bodyHeaders:d,body:h}=this.buildBody({options:o}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:d,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:i,headers:f},o.signal&&{signal:o.signal}),globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"}),h&&{body:h}),null!==(n=this.fetchOptions)&&void 0!==n?n:{}),null!==(s=o.fetchOptions)&&void 0!==s?s:{}),url:u,timeout:o.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let s={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const o=await this.authHeaders(e);let i=Oa([s,{Accept:"application/json","User-Agent":this.getUserAgent()},this._options.defaultHeaders,r,e.headers,o]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=Oa([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:$i(e)}:"object"==typeof e&&"application/x-www-form-urlencoded"===r.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:r})}};Ca.DEFAULT_TIMEOUT=6e4;var Ra=class extends Ca{constructor(){super(...arguments),this.interactions=new ra(this),this.webhooks=new ia(this)}};Aa=Ra,Ra.GeminiNextGenAPIClient=Aa,Ra.GeminiNextGenAPIClientError=Oi,Ra.APIError=Ii,Ra.APIConnectionError=Ri,Ra.APIConnectionTimeoutError=ki,Ra.APIUserAbortError=Ci,Ra.NotFoundError=Di,Ra.ConflictError=Ui,Ra.RateLimitError=ji,Ra.BadRequestError=Ni,Ra.AuthenticationError=Pi,Ra.InternalServerError=Mi,Ra.PermissionDeniedError=xi,Ra.UnprocessableEntityError=Li,Ra.toFile=async function(e,t,r){if(Yi(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Ki(e))(e=await e))return e instanceof File?e:zi([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),zi(await Ji(n),t,r)}const n=await Ji(e);if(t||(t=function(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}(e)),!(null==r?void 0:r.type)){const e=n.find((e=>"object"==typeof e&&"type"in e&&e.type));"string"==typeof e&&(r=Object.assign(Object.assign({},r),{type:e}))}return zi(n,t,r)},Ra.Interactions=ra,Ra.Webhooks=ia;var ka="\n## BLOCK TYPES & USAGE RULES\n1. **text**:\n - Purpose: Primary communication.\n - Rule: Use for all conversational elements. Can be interleaved with other blocks.\n\n2. **task:proposal**:\n - Purpose: Structural project management.\n - Action 'create': Use when the user identifies a new goal.\n - Action 'update': Use to modify existing steps in the 'Current Task' context.\n - Action 'complete': Use only when the user confirms the objective is met.\n - Rule: Each step must be a concrete, actionable item.\n\n3. **summary**:\n - Purpose: Context compression.\n - Rule: Generate automatically after long turns or when the conversation switches topics significantly.\n\n## CONSTRAINTS\n- **No ID Generation**: Never attempt to generate UUIDs or IDs. The system handles this.\n- **Atomic Responses**: You can output multiple blocks in one turn.\n- **Strict Formatting**: Only output valid JSON. No prose before or after the JSON block.\n".trim();function Na(e){switch(e.content.kind){case"text":return`[${e.key}] ${e.content.value}`;case"json":return`[${e.key}] JSON: ${JSON.stringify(e.content.value)}`;case"blob":return`[${e.key}] Blob: ${e.content.filename??"unnamed"} (${e.content.mediaType}, ${e.content.sizeBytes} bytes)`;case"remote":return`[${e.key}] Remote: ${e.content.uri}`;default:return`[${e.key}] Unsupported context type`}}function Pa(e,t){const r=["\n# WORKSPACE OPERATING SYSTEM\nYou are operating within a structured workspace. Your output MUST be a JSON object matching the provided schema.\n"];e.persona&&r.push(`Persona: ${e.persona}`),e.instructions&&r.push(`Instructions: ${e.instructions}`);const n=0===(s=e.preferences).length?"":`User Preferences:\n${s.map((e=>`- ${e.content}`)).join("\n")}`;var s;n&&r.push(n),e.task&&r.push(function(e){let t=`Current Task: ${e.title}\nStatus: ${e.status}`;return e.description&&(t+=`\nDescription: ${e.description}`),e.steps?.length&&(t+=`\nSteps:\n${e.steps.map((e=>` - [${e.completed?"x":" "}] ${e.text}`)).join("\n")}`),t}(e.task));const o=[...e.context,...t];if(o.length>0){const e=o.map(Na);r.push(`Context:\n${e.join("\n")}`)}return r.push(ka),{role:"system",parts:[{text:r.join("\n\n---\n\n")}]}}var xa="text",Da="task:proposal",Ua="summary";function La(e){const t=e.candidates?.[0];if(!t?.content?.parts)throw new Error("No valid content parts in response");const r=[];let n;for(const e of t.content.parts)if(e.thought)r.push((s=e.text??"",{id:u.v7(),type:"thinking",thinking:s}));else if(e.text){n=e;break}var s;if(!n)throw new Error("Response missing JSON part");const o=function(e){try{const t=JSON.parse(e);if(!t.blocks||!Array.isArray(t.blocks))throw new Error('Invalid response: missing or malformed "blocks" array');return t.blocks}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to parse response JSON: ${t}`)}}(n.text);for(const e of o)r.push(ja(e));return r}function ja(e){if(!e.type)throw new Error('Block missing "type" field');switch(e.type){case xa:if("string"!=typeof e.text)throw new Error('Text block missing "text" property');return{id:u.v7(),type:"text",text:e.text};case Da:const t=e;if(!t.title||!t.action||!Array.isArray(t.steps))throw new Error("Task proposal block missing required fields");return{id:u.v7(),type:"task:proposal",title:t.title,action:t.action,steps:t.steps.map((e=>({id:e.id??u.v7(),text:e.text,status:e.status})))};case Ua:if("string"!=typeof e.text)throw new Error('Summary block missing "text" property');return{id:u.v7(),type:"summary",text:e.text};default:return console.warn(`Unknown block type from model: ${e.type}`),{id:u.v7(),type:"text",text:`[Unsupported block: ${e.type}]`}}}var Ma={type:es.OBJECT,description:"The structured response containing a sequence of content blocks.",properties:{blocks:{type:es.ARRAY,description:"An array of blocks representing the model's actions and text.",items:{anyOf:[{type:es.OBJECT,properties:{type:{type:es.STRING,enum:[xa]},text:{type:es.STRING,description:"Standard conversational reply to the user."}},required:["type","text"]},{type:es.OBJECT,properties:{type:{type:es.STRING,enum:[Da]},title:{type:es.STRING,description:"The title of the proposed task."},action:{type:es.STRING,enum:["create","update","complete"]},steps:{type:es.ARRAY,items:{type:es.OBJECT,properties:{text:{type:es.STRING,description:"Description of the task step."},status:{type:es.STRING,enum:["todo","done"]}},required:["text","status"]}}},required:["type","title","action","steps"]},{type:es.OBJECT,properties:{type:{type:es.STRING,enum:[Ua]},text:{type:es.STRING,description:"A summarized version of the context or conversation."}},required:["type","text"]}]}}},required:["blocks"]};function Fa(e){return{role:"assistant"===e.actor?"model":"user",parts:e.blocks.map((e=>function(e){if(t=e,"text"===t.type)return{text:e.text};var t;if("image"===e.type||"document"===e.type)return function(e){if(!e)return null;if("inline"===e.kind)return{inlineData:{data:vn(e.data),mimeType:e.mediaType}};return{fileData:{fileUri:e.fileId,mimeType:e.mediaType}}}(e.blob);if((e=>"tool:use"===e.type)(e))return{functionCall:{name:e.name,args:e.input}};if((e=>"tool:result"===e.type)(e))return{functionResponse:{name:e.useId,response:{result:e.content}}};if((e=>"thinking"===e.type)(e))return{thought:!0,text:e.thinking};if((e=>"task:proposal"===e.type)(e)){const t=e.steps.map((e=>`[${e.status}] ${e.text}`)).join("\n");return{text:`[Task Proposal: ${e.title} (${e.action})]\n${t}`}}if((e=>"summary"===e.type)(e))return{text:`[Summary]: ${e.text}`};if((e=>"role:transition"===e.type)(e))return{text:`[Role transition: ${e.previousRole??"none"} → ${e.newRole}]`};return console.warn(`Unmapped block type: ${e.type}`),{text:`[Unsupported block: ${e.type}]`}}(e))).filter((e=>null!==e))}}
2
+ /*! Bundled license information:
3
+
4
+ web-streams-polyfill/dist/ponyfill.es2018.js:
5
+ (**
6
+ * @license
7
+ * web-streams-polyfill v3.3.3
8
+ * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
9
+ * This code is released under the MIT license.
10
+ * SPDX-License-Identifier: MIT
11
+ *)
12
+
13
+ fetch-blob/index.js:
14
+ (*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
15
+
16
+ formdata-polyfill/esm.min.js:
17
+ (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
18
+
19
+ node-domexception/index.js:
20
+ (*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
21
+
22
+ @google/genai/dist/node/index.mjs:
23
+ (**
24
+ * @license
25
+ * Copyright 2025 Google LLC
26
+ * SPDX-License-Identifier: Apache-2.0
27
+ *)
28
+
29
+ @google/genai/dist/node/index.mjs:
30
+ (**
31
+ * @license
32
+ * Copyright 2025 Google LLC
33
+ * SPDX-License-Identifier: Apache-2.0
34
+ *)
35
+
36
+ @google/genai/dist/node/index.mjs:
37
+ (**
38
+ * @license
39
+ * Copyright 2025 Google LLC
40
+ * SPDX-License-Identifier: Apache-2.0
41
+ *)
42
+
43
+ @google/genai/dist/node/index.mjs:
44
+ (**
45
+ * @license
46
+ * Copyright 2025 Google LLC
47
+ * SPDX-License-Identifier: Apache-2.0
48
+ *)
49
+
50
+ @google/genai/dist/node/index.mjs:
51
+ (**
52
+ * @license
53
+ * Copyright 2025 Google LLC
54
+ * SPDX-License-Identifier: Apache-2.0
55
+ *)
56
+
57
+ @google/genai/dist/node/index.mjs:
58
+ (**
59
+ * @license
60
+ * Copyright 2025 Google LLC
61
+ * SPDX-License-Identifier: Apache-2.0
62
+ *)
63
+
64
+ @google/genai/dist/node/index.mjs:
65
+ (**
66
+ * @license
67
+ * Copyright 2025 Google LLC
68
+ * SPDX-License-Identifier: Apache-2.0
69
+ *)
70
+
71
+ @google/genai/dist/node/index.mjs:
72
+ (**
73
+ * @license
74
+ * Copyright 2025 Google LLC
75
+ * SPDX-License-Identifier: Apache-2.0
76
+ *)
77
+
78
+ @google/genai/dist/node/index.mjs:
79
+ (**
80
+ * @license
81
+ * Copyright 2025 Google LLC
82
+ * SPDX-License-Identifier: Apache-2.0
83
+ *)
84
+
85
+ @google/genai/dist/node/index.mjs:
86
+ (**
87
+ * @license
88
+ * Copyright 2025 Google LLC
89
+ * SPDX-License-Identifier: Apache-2.0
90
+ *)
91
+
92
+ @google/genai/dist/node/index.mjs:
93
+ (**
94
+ * @license
95
+ * Copyright 2025 Google LLC
96
+ * SPDX-License-Identifier: Apache-2.0
97
+ *)
98
+
99
+ @google/genai/dist/node/index.mjs:
100
+ (**
101
+ * @license
102
+ * Copyright 2025 Google LLC
103
+ * SPDX-License-Identifier: Apache-2.0
104
+ *)
105
+
106
+ @google/genai/dist/node/index.mjs:
107
+ (**
108
+ * @license
109
+ * Copyright 2025 Google LLC
110
+ * SPDX-License-Identifier: Apache-2.0
111
+ *)
112
+
113
+ @google/genai/dist/node/index.mjs:
114
+ (**
115
+ * @license
116
+ * Copyright 2025 Google LLC
117
+ * SPDX-License-Identifier: Apache-2.0
118
+ *)
119
+
120
+ @google/genai/dist/node/index.mjs:
121
+ (**
122
+ * @license
123
+ * Copyright 2025 Google LLC
124
+ * SPDX-License-Identifier: Apache-2.0
125
+ *)
126
+
127
+ @google/genai/dist/node/index.mjs:
128
+ (**
129
+ * @license
130
+ * Copyright 2025 Google LLC
131
+ * SPDX-License-Identifier: Apache-2.0
132
+ *)
133
+
134
+ @google/genai/dist/node/index.mjs:
135
+ (**
136
+ * @license
137
+ * Copyright 2025 Google LLC
138
+ * SPDX-License-Identifier: Apache-2.0
139
+ *)
140
+
141
+ @google/genai/dist/node/index.mjs:
142
+ (**
143
+ * @license
144
+ * Copyright 2025 Google LLC
145
+ * SPDX-License-Identifier: Apache-2.0
146
+ *)
147
+
148
+ @google/genai/dist/node/index.mjs:
149
+ (**
150
+ * @license
151
+ * Copyright 2025 Google LLC
152
+ * SPDX-License-Identifier: Apache-2.0
153
+ *)
154
+
155
+ @google/genai/dist/node/index.mjs:
156
+ (**
157
+ * @license
158
+ * Copyright 2025 Google LLC
159
+ * SPDX-License-Identifier: Apache-2.0
160
+ *)
161
+
162
+ @google/genai/dist/node/index.mjs:
163
+ (**
164
+ * @license
165
+ * Copyright 2025 Google LLC
166
+ * SPDX-License-Identifier: Apache-2.0
167
+ *)
168
+
169
+ @google/genai/dist/node/index.mjs:
170
+ (**
171
+ * @license
172
+ * Copyright 2025 Google LLC
173
+ * SPDX-License-Identifier: Apache-2.0
174
+ *)
175
+
176
+ @google/genai/dist/node/index.mjs:
177
+ (**
178
+ * @license
179
+ * Copyright 2025 Google LLC
180
+ * SPDX-License-Identifier: Apache-2.0
181
+ *)
182
+
183
+ @google/genai/dist/node/index.mjs:
184
+ (**
185
+ * @license
186
+ * Copyright 2025 Google LLC
187
+ * SPDX-License-Identifier: Apache-2.0
188
+ *)
189
+
190
+ @google/genai/dist/node/index.mjs:
191
+ (**
192
+ * @license
193
+ * Copyright 2025 Google LLC
194
+ * SPDX-License-Identifier: Apache-2.0
195
+ *)
196
+
197
+ @google/genai/dist/node/index.mjs:
198
+ (**
199
+ * @license
200
+ * Copyright 2025 Google LLC
201
+ * SPDX-License-Identifier: Apache-2.0
202
+ *)
203
+
204
+ @google/genai/dist/node/index.mjs:
205
+ (**
206
+ * @license
207
+ * Copyright 2025 Google LLC
208
+ * SPDX-License-Identifier: Apache-2.0
209
+ *)
210
+
211
+ @google/genai/dist/node/index.mjs:
212
+ (**
213
+ * @license
214
+ * Copyright 2025 Google LLC
215
+ * SPDX-License-Identifier: Apache-2.0
216
+ *)
217
+
218
+ @google/genai/dist/node/index.mjs:
219
+ (**
220
+ * @license
221
+ * Copyright 2025 Google LLC
222
+ * SPDX-License-Identifier: Apache-2.0
223
+ *)
224
+
225
+ @google/genai/dist/node/index.mjs:
226
+ (**
227
+ * @license
228
+ * Copyright 2025 Google LLC
229
+ * SPDX-License-Identifier: Apache-2.0
230
+ *)
231
+
232
+ @google/genai/dist/node/index.mjs:
233
+ (**
234
+ * @license
235
+ * Copyright 2025 Google LLC
236
+ * SPDX-License-Identifier: Apache-2.0
237
+ *)
238
+
239
+ @google/genai/dist/node/index.mjs:
240
+ (**
241
+ * @license
242
+ * Copyright 2025 Google LLC
243
+ * SPDX-License-Identifier: Apache-2.0
244
+ *)
245
+
246
+ @google/genai/dist/node/index.mjs:
247
+ (**
248
+ * @license
249
+ * Copyright 2025 Google LLC
250
+ * SPDX-License-Identifier: Apache-2.0
251
+ *)
252
+
253
+ @google/genai/dist/node/index.mjs:
254
+ (**
255
+ * @license
256
+ * Copyright 2025 Google LLC
257
+ * SPDX-License-Identifier: Apache-2.0
258
+ *)
259
+
260
+ @google/genai/dist/node/index.mjs:
261
+ (**
262
+ * @license
263
+ * Copyright 2025 Google LLC
264
+ * SPDX-License-Identifier: Apache-2.0
265
+ *)
266
+
267
+ @google/genai/dist/node/index.mjs:
268
+ (**
269
+ * @license
270
+ * Copyright 2025 Google LLC
271
+ * SPDX-License-Identifier: Apache-2.0
272
+ *)
273
+
274
+ @google/genai/dist/node/index.mjs:
275
+ (**
276
+ * @license
277
+ * Copyright 2025 Google LLC
278
+ * SPDX-License-Identifier: Apache-2.0
279
+ *)
280
+
281
+ @google/genai/dist/node/index.mjs:
282
+ (**
283
+ * @license
284
+ * Copyright 2025 Google LLC
285
+ * SPDX-License-Identifier: Apache-2.0
286
+ *)
287
+ */
288
+ exports.BlobStore=On,exports.COLLECTIONS=fn,exports.ContentStore=class e{db;tree;blobs;roleCache;preferenceCache;contextCache;taskCache;bus;subscribe(e,t){return this.bus.subscribe(e,t)}constructor(e,t,r,n={}){this.db=e,this.tree=new Sn(e),this.blobs=new On(t,r);const s={roles:n.cache?.roles??In,preferences:n.cache?.preferences??Cn,context:n.cache?.context??Rn,tasks:n.cache?.tasks??kn};this.roleCache=new Nn(s.roles),this.preferenceCache=new Nn(s.preferences),this.contextCache=new Nn(s.context),this.taskCache=new Nn(s.tasks),this.bus=r}static async create(t,r,n,s){const o=new e(t,r,n,s);return await o.init(),o}async init(e){await this.db.open(e),await this.blobs.init()}getTurnTree(){return this.tree}async getRole(e){const t=this.roleCache.get(e);if(t)return gn(t);if(e===an)return gn(Tn(an,"Empty Role"));const r=await this.db.collection(fn.ROLE),n=await r.find({field:"name",operator:"eq",value:e});if(!n)return bn({code:"NOT_FOUND",resource:"role",id:e});const s=n.state();return this.roleCache.set(e,s),gn(s)}async saveRole(e){const t=await this.db.collection(fn.ROLE),r=await t.find({field:"name",operator:"eq",value:e.name});r?await r.update(e):await t.create(e),this.roleCache.set(e.name,e)}async deleteRole(e){const t=await this.db.collection(fn.ROLE),r=await t.find({field:"name",operator:"eq",value:e});r&&await r.delete(),this.roleCache.delete(e)}async getPreference(e){const t=this.preferenceCache.get(e);if(t)return gn(t);const r=await this.db.collection(fn.PREFERENCE),n=await r.find({field:"id",operator:"eq",value:e});if(!n)return bn({code:"NOT_FOUND",resource:"preference",id:e});const s=n.state();return this.preferenceCache.set(e,s),gn(s)}async savePreference(e){const t=await this.db.collection(fn.PREFERENCE),r=await t.find({field:"id",operator:"eq",value:e.id});r?await r.update(e):await t.create(e),this.preferenceCache.set(e.id,e)}async deletePreference(e){const t=await this.db.collection(fn.PREFERENCE),r=await t.find({field:"id",operator:"eq",value:e});r&&await r.delete(),this.preferenceCache.delete(e)}async getContext(e){const t=this.contextCache.get(e);if(t)return gn(t);const r=await this.db.collection(fn.CONTEXT),n=await r.find({field:"key",operator:"eq",value:e});if(!n)return bn({code:"NOT_FOUND",resource:"context",id:e});const s=n.state();return this.contextCache.set(e,s),gn(s)}async saveContext(e){const t=await this.db.collection(fn.CONTEXT),r=await t.find({field:"key",operator:"eq",value:e.key});r?await r.update(e):await t.create(e),this.contextCache.set(e.key,e)}async deleteContext(e){const t=await this.db.collection(fn.CONTEXT),r=await t.find({field:"key",operator:"eq",value:e});r&&await r.delete(),this.contextCache.delete(e)}async getContextByTopics(e,t){const r=new Set;for(const n of t){const t=e.topics[n];t&&t.contextKeys.forEach((e=>r.add(e)))}if(0===r.size)return[];const n=[],s=[];for(const e of r){const t=this.contextCache.get(e);t?s.push(t):n.push(e)}let o=[];if(n.length>0){const e=await this.db.collection(fn.CONTEXT),t=await e.filter({operator:"or",conditions:n.map((e=>({field:"key",operator:"eq",value:e})))});for(const e of t){const t=e.state();this.contextCache.set(t.key,t),o.push(t)}}return[...s,...o].sort(((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime()))}async getTask(e){const t=this.taskCache.get(e);if(t)return gn(t);const r=await this.db.collection(fn.TASK),n=await r.find({field:"id",operator:"eq",value:e});if(!n)return bn({code:"NOT_FOUND",resource:"task",id:e});const s=n.state();return this.taskCache.set(e,s),gn(s)}async saveTask(e){const t=await this.db.collection(fn.TASK),r=await t.find({field:"id",operator:"eq",value:e.id});r?await r.update(e):await t.create(e),this.taskCache.set(e.id,e)}async deleteTask(e){const t=await this.db.collection(fn.TASK),r=await t.find({field:"id",operator:"eq",value:e});r&&await r.delete(),this.taskCache.delete(e)}async getTasksByTopics(e,t){const r=new Set;for(const n of t){const t=e.topics[n];t&&t.tasks&&t.tasks.forEach((e=>r.add(e)))}if(0===r.size)return[];const n=[],s=[];for(const e of r){const t=this.taskCache.get(e);t?s.push(t):n.push(e)}let o=[];if(n.length>0){const e=await this.db.collection(fn.TASK),t=await e.filter({operator:"or",conditions:n.map((e=>({field:"id",operator:"eq",value:e})))});for(const e of t){const t=e.state();this.taskCache.set(t.id,t),o.push(t)}}return[...s,...o].sort(((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()))}async saveSession(e){const t=await this.db.collection(fn.SESSION),r=await t.find({field:"id",operator:"eq",value:e.id}),n=En(e);r?await r.update(n):await t.create(n)}async updateSessionMeta(e,t){const r=await this.db.collection(fn.SESSION),n=await r.find({field:"id",operator:"eq",value:e});if(!n)return;const s=n.state(),o=_n(s,t);await n.update(En(o))}async deleteSession(e){const t=await this.db.collection(fn.SESSION),r=await t.find({field:"id",operator:"eq",value:e});r&&await r.delete()}async registerBlob(e,t,r){return this.blobs.register(e,t,r)}async retainBlob(e){return this.blobs.retain(e)}async releaseBlob(e){return this.blobs.release(e)}async purgeBlob(e){return this.blobs.purge(e)}async recordBlobRemoteId(e,t,r){return this.blobs.recordRemoteId(e,t,r)}getBlobRecord(e){return this.blobs.getRecord(e)}getAllBlobRecords(){return this.blobs.getAllRecords()}getBlobResolver(){return this.blobs.resolveRefs.bind(this.blobs)}async appendTurn(e,t){return gn(await this.tree.append(e,t))}async saveTurn(e,t){return gn(await this.tree.save(e,t))}async editTurn(e,t,r,n,s){const o=(await this.tree.loadTurnVersions(e,t)).find((e=>e.version===n-1));if(!o)return bn({code:"NOT_FOUND",resource:"turn",id:t});const i={id:t,version:n,actor:o.actor,blocks:r,timestamp:(new Date).toISOString(),role:s??o.role,parent:o.parent};await this.tree.replaceVersion(e,i);const a=await this.tree.getHead(e);return a?.id===t&&await this.tree.setHead(e,{id:i.id,version:i.version}),gn(void 0)}async branchTurn(e,t){return await this.tree.branch(e,t),gn(void 0)}async deleteTurnSubtree(e,t,r,n){return await this.tree.deleteSubtree(e,t,r,n),gn(void 0)}async copyTranscript(e,t){await this.tree.copyTranscript(e,t)}async resolveSession(e,t,r){const n=e.index.sessions[t];if(!n)return bn({code:"NOT_FOUND",resource:"session",id:t});const s=await this.getRole(n.role);if(!s.ok)return s;const o=s.value,i=function(e,t){return e.preferences.length>0?e.preferences:t.preferences}(n,o),a=function(e,t){return e.filter((e=>0===e.topics.length||e.topics.some((e=>t.includes(e)))))}((await Promise.all(i.map((e=>this.getPreference(e))))).filter((e=>e.ok)).map((e=>e.value)),n.topics),c=await this.getContextByTopics(e.index,n.topics),l=await this.getTasksByTopics(e.index,n.topics);let u=null;if(n.task&&!l.find((e=>e.id===n.task))){const e=await this.getTask(n.task);e.ok&&(u=e.value)}const d=r??await this.tree.getActiveChain(t),h={session:n,role:o,preferences:a,context:c,task:u,transcript:d,instructions:e.settings?.prompt};return gn({...h,preferences:Object.freeze([...h.preferences]),context:Object.freeze([...h.context]),transcript:Object.freeze([...h.transcript])})}async gc(){return this.blobs.gc()}},exports.DefaultTurnProcessor=Dn,exports.EMPTY_SYSTEM_ROLE=an,exports.GoogleGenAIAdapter=class{constructor(e){this._=e}async prepare({prompt:e,model:t}){return{request:{model:t,contents:e.transcript.turns.map((e=>Fa(e))),config:{systemInstruction:Pa(e.system,e.context),thinkingConfig:{includeThoughts:!0},responseMimeType:"application/json",responseSchema:Ma}}}}parse({response:e}){const t=La(e),r=new Hn("assistant");for(const e of t)r.addBlock(e);return r.build()}},exports.IndexedDBBlobStorage=class{dbName;db=null;constructor(e={}){this.dbName=e.dbName??"aiworkspace-blobs"}async open(){this.db||(this.db=await new Promise(((e,t)=>{const r=indexedDB.open(this.dbName,1);r.onupgradeneeded=e=>{const t=e.target.result;this.createSchema(t)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error),r.onblocked=()=>t(new Error(`[IndexedDBBlobStorage] Database "${this.dbName}" blocked.`))})),this.db.onversionchange=()=>{this.db?.close(),this.db=null})}createSchema(e){e.objectStoreNames.contains($n)||e.createObjectStore($n,{keyPath:"sha256"}),e.objectStoreNames.contains(Wn)||e.createObjectStore(Wn,{keyPath:"sha256"})}close(){this.db?.close(),this.db=null}async deleteDatabase(){this.close(),await new Promise(((e,t)=>{const r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>e(),r.onerror=()=>t(r.error)}))}getDB(){if(!this.db)throw new Error("[IndexedDBBlobStorage] Database not open. Call open() first.");return this.db}readTx(...e){return this.getDB().transaction(e,"readonly")}writeTx(...e){return this.getDB().transaction(e,"readwrite")}async storeBytes(e,t){const r=this.readTx($n);if(await Vn(r.objectStore($n).get(e)))return;const n=this.writeTx($n);n.objectStore($n).put({sha256:e,data:t}),await Yn(n)}async loadBytes(e){const t=this.readTx($n),r=await Vn(t.objectStore($n).get(e));return r?.data??null}async hasBytes(e){const t=this.readTx($n);return await Vn(t.objectStore($n).count(e))>0}async deleteBytes(e){const t=this.writeTx($n);t.objectStore($n).delete(e),await Yn(t)}async saveRecord(e){const t=this.writeTx(Wn);t.objectStore(Wn).put(e),await Yn(t)}async loadRecord(e){const t=this.readTx(Wn);return await Vn(t.objectStore(Wn).get(e))??null}async deleteRecord(e){const t=this.writeTx(Wn);t.objectStore(Wn).delete(e),await Yn(t)}async listRecords(){return Vn(this.readTx(Wn).objectStore(Wn).getAll())}async exportAllBytes(){const e=this.readTx($n);return(await Vn(e.objectStore($n).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((r,n)=>{const s=this.getDB().transaction([$n,Wn],"readwrite"),o=s.objectStore($n),i=s.objectStore(Wn),a=o.count(e.sha256);a.onsuccess=()=>{0===a.result&&o.put({sha256:e.sha256,data:t}),i.put(e)},a.onerror=()=>n(a.error),s.oncomplete=()=>r(),s.onerror=()=>n(s.error),s.onabort=()=>n(new Error("registerBlob transaction aborted"))}))}},exports.MemoryBlobStorage=class{bytes=new Map;records=new Map;async storeBytes(e,t){this.bytes.has(e)||this.bytes.set(e,t)}async loadBytes(e){return this.bytes.get(e)??null}async hasBytes(e){return this.bytes.has(e)}async deleteBytes(e){this.bytes.delete(e)}async saveRecord(e){this.records.set(e.sha256,{...e})}async loadRecord(e){return this.records.get(e)??null}async deleteRecord(e){this.records.delete(e)}async listRecords(){return Array.from(this.records.values()).map((e=>({...e})))}async exportAllBytes(){return Array.from(this.bytes.entries()).map((([e,t])=>[e,new Uint8Array(t)]))}async registerBlob(e,t){this.bytes.has(e.sha256)||this.bytes.set(e.sha256,t),this.records.set(e.sha256,{...e})}},exports.PromptBuilder=class{retriever;planner;assembler;summarizer;blobResolver;constructor(e){this.blobResolver=e.blobResolver,this.retriever=e.retriever??new Fn,this.planner=e.planner??new Bn,this.assembler=e.assembler??new Gn,this.summarizer=e.summarizer}async build(e,t={}){const r=[],{resolved:n,conflicts:s}=this.resolvePreferenceConflicts(e.preferences);s.length>0&&r.push(`${s.length} preference conflict(s) resolved.`);const o=this.extractRecentUserQueries(e.transcript,t.relevanceConfig),i=this.retriever.rank({entries:e.context,recentMessages:o,config:t.relevanceConfig??{}});let a=e.transcript,c=null;if(this.summarizer&&a.length>0){const e=t.tokenBudget?Math.floor(.25*t.tokenBudget.total):2e3,r=await this.summarizer.summarize(a,e);c=r.summary,a=r.remaining}const l=this.planner.plan({systemInstructions:e.instructions,persona:e.role.persona,preferences:n,context:i,task:e.task,transcript:a,budget:t.tokenBudget}),u=this.collectUsedBlobRefs(l.context,l.transcript),d=this.deduplicateBlobRefs(u),{resolved:h,errors:f}=await this.blobResolver(d,t.providerId??null);for(const e of f)r.push(`Failed to resolve blob ${e.ref.sha256.slice(0,8)}: ${e.error.code}`);const p=d.filter((e=>!h.has(e.sha256)));return p.length>0&&r.push(`${p.length} blob(s) unresolved and omitted: `+p.map((e=>e.sha256.slice(0,8))).join(", ")),l.truncated.preferences>0&&r.push(`${l.truncated.preferences} preference(s) dropped.`),l.truncated.interactions>0&&r.push(`${l.truncated.interactions} turn(s) trimmed.`),l.truncated.context>0&&r.push(`${l.truncated.context} context entry/entries dropped.`),this.assembler.assemble({session:e,plan:l,resolvedBlobs:h,summaryBlockText:c,warnings:r,conflicts:s,budgetTotal:t.tokenBudget?.total??0})}collectUsedBlobRefs(e,t){const r=[];for(const t of e)"blob"===t.content.kind&&r.push(t.content);for(const e of t)for(const t of e.blocks)if("image"===t.type||"document"===t.type){const e=t.ref;e&&r.push(e)}return r}deduplicateBlobRefs(e){const t=new Set,r=[];for(const n of e)t.has(n.sha256)||(t.add(n.sha256),r.push(n));return r}extractRecentUserQueries(e,t){const r=t?.recentMessageWindow??3;return e.filter((e=>"user"===e.actor)).slice(-r).flatMap((e=>e.blocks.filter((e=>"text"===e.type)).map((e=>e.text))))}resolvePreferenceConflicts(e){const t=[],r=new Map;for(const n of e)if(0!==n.topics.length)for(const e of n.topics){const s=r.get(e);if(!s){r.set(e,n);continue}const o=new Date(s.timestamp).getTime(),i=new Date(n.timestamp).getTime();i>o?(t.push({topic:e,kept:n.id,dropped:s.id,reason:"superseded_by_newer"}),r.set(e,n)):o>i&&t.push({topic:e,kept:s.id,dropped:n.id,reason:"superseded_by_newer"})}const n=new Set(t.map((e=>e.dropped)));return{resolved:e.filter((e=>!n.has(e.id))),conflicts:Array.from(new Set(t))}}},exports.Session=qn,exports.SessionManager=class{workspaceManager;contentStore;constructor(e,t){this.workspaceManager=e,this.contentStore=t}list(e){return Object.values(e.index.sessions)}meta(e,t){return e.index.sessions[t]}async create(e,t){const r={id:u.v7(),label:t.label,role:t.role||e.settings.defaultRole||an,topics:t.topics??[],preferences:t.preferences??[]},n={type:"session:create",timestamp:(new Date).toISOString(),payload:r},s=await this.workspaceManager.dispatch(e,n);return s.ok?gn({session:new qn(r.id,this.contentStore.getTurnTree(),this.workspaceManager),patch:s.value}):s}async open(e,t){if(!e.index.sessions[t])return bn({code:"NOT_FOUND",resource:"session",id:t});try{return gn({session:new qn(t,this.contentStore.getTurnTree(),this.workspaceManager),patch:{}})}catch(e){return bn({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}}get workspace(){return this.workspaceManager}async close(e){}},exports.TurnBuilder=Hn,exports.TurnTree=Sn,exports.WorkspaceManager=class{contentStore;permissionGuard;toolRegistry;processor;bus;constructor(e){this.contentStore=e.contentStore,this.permissionGuard=e.permissionGuard,this.toolRegistry=e.toolRegistry,this.bus=e.eventBus,this.processor=e.turnProcessor??new Dn,this.bus.subscribe("blobs:changed",(({sha256:e,record:t})=>{const r={index:{blobs:{[e]:t??void 0}}};this.bus.emit({name:"workspace:changed",payload:r})})),this.toolRegistry&&this.toolRegistry.onRegistryChanged((e=>{this.bus.emit({name:"workspace:changed",payload:{index:{tools:e.reduce(((e,t)=>(e[t.name]=t,e)),{})}}})}))}store(){return this.contentStore}turnProcessor(){return this.processor}initTools(e){if(!this.toolRegistry)return{};const t={};for(const e of this.toolRegistry.list())t[e.name]=e;return{index:{tools:t}}}subscribe(e,t){return this.bus.subscribe(e,t)}reduce(e,t){return Pn(e,t)}async dispatch(e,t){if(this.permissionGuard){const e="tool:call"===t.type?{type:"tool",payload:t.payload}:{type:"command",payload:t},r=await this.permissionGuard.authenticate(e);if(!r.ok)return r}const r=Pn(e,t);if(!r.ok)return r;let n={};try{n=await this.handleContentSideEffects(e,t)}catch(e){return bn({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}return gn(_n(r.value,n))}async resolveSession(e,t,r){return this.contentStore.resolveSession(e,t,r)}async handleContentSideEffects(e,t){switch(t.type){case"blob:register":{const{data:e,mediaType:r,filename:n}=t.payload,s=await this.contentStore.registerBlob(e,r,n);if(!s.ok)throw Object.assign(new Error(s.error.code),{wsError:s.error});const o=s.value,i=this.contentStore.getBlobRecord(o.sha256);if(!i)throw new Error("Record missing after register");return{index:{blobs:{[o.sha256]:i}}}}case"blob:retain":{const{sha256:e}=t.payload,r=await this.contentStore.retainBlob(e);if(!r.ok)throw Object.assign(new Error(r.error.code),{wsError:r.error});const n=this.contentStore.getBlobRecord(e);return{index:{blobs:{[e]:n??void 0}}}}case"blob:release":{const{sha256:e}=t.payload,r=await this.contentStore.releaseBlob(e);if(!r.ok)throw Object.assign(new Error(r.error.code),{wsError:r.error});const n=this.contentStore.getBlobRecord(e);return{index:{blobs:{[e]:n??void 0}}}}case"blob:purge":{const{sha256:e}=t.payload,r=await this.contentStore.purgeBlob(e);if(!r.ok)throw Object.assign(new Error(r.error.code),{wsError:r.error});return{index:{blobs:{[e]:void 0}}}}case"blob:record_remote_id":{const{sha256:e,providerId:r,fileId:n}=t.payload,s=await this.contentStore.recordBlobRemoteId(e,r,n);if(!s.ok)throw Object.assign(new Error(s.error.code),{wsError:s.error});const o=this.contentStore.getBlobRecord(e);return{index:{blobs:{[e]:o??void 0}}}}case"role:add":return await this.contentStore.saveRole(t.payload),{};case"role:update":{const{name:e,...r}=t.payload,n=await this.contentStore.getRole(e);if(!n.ok)throw new Error(`role:update — "${e}" not found`);return await this.contentStore.saveRole({...n.value,...r,name:e}),{}}case"role:delete":return await this.contentStore.deleteRole(t.payload.name),{};case"preference:add":return await this.contentStore.savePreference(t.payload),{};case"preference:update":{const{id:e,...r}=t.payload,n=await this.contentStore.getPreference(e);if(!n.ok)throw new Error(`preference:update — "${e}" not found`);return await this.contentStore.savePreference({...n.value,...r,id:e}),{}}case"preference:delete":return await this.contentStore.deletePreference(t.payload.id),{};case"context:add":case"context:update":return await this.contentStore.saveContext(t.payload),{};case"context:delete":return await this.contentStore.deleteContext(t.payload.key),{};case"task:add":return await this.contentStore.saveTask(t.payload),{};case"task:update":{const{id:e,...r}=t.payload,n=await this.contentStore.getTask(e);if(!n.ok)throw new Error(`task:update — "${e}" not found`);return await this.contentStore.saveTask({...n.value,...r,id:e}),{}}case"task:delete":return await this.contentStore.deleteTask(t.payload.id),{};case"session:create":{const{id:e,label:r,role:n,topics:s,preferences:o=[]}=t.payload;return await this.contentStore.saveSession({id:e,label:r,role:n,topics:s,preferences:o,metadata:{created:t.timestamp,updated:t.timestamp},flushedTurnCount:0,head:null,task:null}),{}}case"session:update":{const{sessionId:e,...r}=t.payload;return await this.contentStore.updateSessionMeta(e,r),{}}case"session:fork":{const{sourceSessionId:r,newSessionId:n,label:s,role:o,topics:i}=t.payload;if(!e.index.sessions[r])throw new Error(`session:fork — source session "${r}" not found`);await this.contentStore.copyTranscript(r,n);const a=e.index.sessions[r],c={id:n,label:s,role:o??a.role,topics:i??[...a.topics],preferences:[...a.preferences],metadata:{created:t.timestamp,updated:t.timestamp},flushedTurnCount:a.flushedTurnCount,head:a.head?{...a.head}:null,task:a.task};return await this.contentStore.saveSession(c),{}}case"session:delete":return await this.contentStore.deleteSession(t.payload.sessionId),{};case"session:role:switch":case"session:topics:add":case"session:preferences:override":{const e=t.payload.sessionId,r=await this.contentStore.db.collection("session"),n=await r.find({field:"id",operator:"eq",value:e});if(!n)return{};if("session:role:switch"===t.type)await this.contentStore.updateSessionMeta(e,{role:t.payload.role});else if("session:topics:add"===t.type){const r=n.state();await this.contentStore.updateSessionMeta(e,{topics:[...new Set([...r.topics,...t.payload.topics])]})}else await this.contentStore.updateSessionMeta(e,{preferences:t.payload.preferences});return{}}case"turn:add":return await this.contentStore.appendTurn(t.payload.sessionId,t.payload.turn),{};case"turn:save":return await this.contentStore.saveTurn(t.payload.sessionId,t.payload.turn),{};case"turn:edit":{const{sessionId:e,turnId:r,newBlocks:n,newVersion:s,roleSnapshot:o}=t.payload;return await this.contentStore.editTurn(e,r,n,s,o),{}}case"turn:branch":return await this.contentStore.branchTurn(t.payload.sessionId,t.payload.turn),{};case"turn:delete":{const{sessionId:e,turnId:r,version:n,newHead:s}=t.payload;return await this.contentStore.deleteTurnSubtree(e,r,n,s),{}}case"tool:call":{if(!this.toolRegistry)throw new Error("tool:call — no toolRegistry configured");const e=await this.toolRegistry.execute(t.payload);if(!e.ok)throw Object.assign(new Error(e.error.code),{wsError:e.error});return{}}default:return{}}}},exports.bufferToBase64=vn,exports.computeSHA256=wn,exports.createEmptyRole=Tn,exports.createProjectWorkspace=function({project:e,language:t}){const r={...e,id:u.v7()};return{id:u.v7(),settings:{language:t},project:r,index:{roles:{},topics:{},preferences:{},context:{},sessions:{},blobs:{},tasks:{},tools:{}}}},exports.createSimpleWorkspace=function({name:e,actor:t,language:r}){return{id:u.v7(),settings:{language:r},project:{id:u.v7(),name:e,actor:t},index:{roles:{},topics:{},preferences:{},context:{},sessions:{},blobs:{},tasks:{},tools:{}}}},exports.createWorkspaceDatabase=function(e){const t=new hn({retry:!0,throws:!0}),r=new hn({retry:!0,throws:!0});return{open:async(r=[])=>(await t.do((async()=>{const t=[...cn,...r];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await r.do((()=>{e.close()}))).value}},exports.del=yn,exports.err=bn,exports.extractBlobRecord=function(e){const t=e?.index?.blobs;if(!t)return null;const r=t[Object.keys(t)[0]];return r||null},exports.extractBlobRef=function(e){return{sha256:e.sha256,mediaType:e.mediaType,sizeBytes:e.sizeBytes,filename:e.filename,previewUrl:e.previewUrl}},exports.merge=_n,exports.ok=gn,exports.omitNullUndefined=En;