evolve-sdk 0.0.52.dev880__tar.gz → 0.0.52.dev892__tar.gz
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.
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/PKG-INFO +1 -1
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/bridge/dist/bridge.bundle.cjs +2 -2
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/__init__.py +1 -1
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/hosted.py +15 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve_sdk.egg-info/PKG-INFO +1 -1
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/pyproject.toml +1 -1
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/LICENSE +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/MANIFEST.in +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/README.md +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/bridge/__init__.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/_http.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/agent.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/bridge.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/browser_credentials.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/browser_profiles.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/config.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/integrations.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/managed_secrets.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/pipeline/__init__.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/pipeline/pipeline.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/pipeline/types.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/prompts/__init__.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/prompts/agent_md/judge.md +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/prompts/agent_md/reduce.md +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/prompts/agent_md/verify.md +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/prompts/user/judge.md +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/prompts/user/retry_feedback.md +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/prompts/user/verify.md +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/results.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/retry.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/schema.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/sessions_client.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/storage_client.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/swarm/__init__.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/swarm/results.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/swarm/swarm.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/swarm/types.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve/utils.py +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve_sdk.egg-info/SOURCES.txt +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve_sdk.egg-info/dependency_links.txt +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve_sdk.egg-info/requires.txt +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve_sdk.egg-info/top_level.txt +0 -0
- {evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/setup.cfg +0 -0
|
@@ -210,7 +210,7 @@ ${e}
|
|
|
210
210
|
|
|
211
211
|
}; __evolve_eos=$?; printf '%s' '${t}'; (exit $__evolve_eos)`:e}function RAe(e,t){return e.endsWith(`${t}
|
|
212
212
|
`)?e.slice(0,-(t.length+1)):e.endsWith(t)?e.slice(0,-t.length):e}function Lb(e,t){let n=qAe(e);return{stdout:RAe(n.stdout,t),stderr:n.stderr}}function J8(e,t){let n=`${e}
|
|
213
|
-
`,r="",a=i=>{for(let s=Math.min(i.length,n.length);s>0;s--)if(n.startsWith(i.slice(i.length-s)))return s;return 0};return{push(i){r+=i;let s=a(r);s!==r.length&&(t(r.slice(0,r.length-s)),r=r.slice(r.length-s))},flush(){let i=r===n||r===e?"":r;r="",i&&t(i)}}}function H8(e,t,n,r){let a=e;return t&&(a=`cd '${t.replace(/'/g,"'\\''")}' && ${a}`),n&&Object.keys(n).length>0&&(a=`${Object.entries(n).filter(([,i])=>i!=null).map(([i,s])=>`export ${i}='${String(s).replace(/'/g,"'\\''")}'`).join("; ")}; ${a}`),r==="root"&&(a=`echo ${Buffer.from(a).toString("base64")} | base64 -d | sudo -n bash`),a}function NAe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function gNt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!NAe(e)}function yNt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function vNt(e){return/^[^:]+:\d+$/.test(e)}async function dM(e,t=CAe){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return e?{networkBlockAll:!1}:{}}let n=e.allowedDestinations??[];if(n.length===0)return{networkBlockAll:!0};let r=[],a=[];for(let s of n)if(NAe(s))r.push(s.includes("/")?s:`${s}/32`);else{if(gNt(s))throw new rp("invalid-ipv4",`"${s}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,s);if(yNt(s))throw new rp("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${s}".`,s);if(vNt(s))throw new rp("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${s}" and list just the host or IP.`,s);if(s.includes("*"))throw new rp("wildcard-hostname",`Daytona cannot enforce wildcard hostname "${s}": its allowlist is kernel-level IPv4 CIDR filtering with no DNS/domain layer. List concrete hostnames or IPv4 CIDRs instead.`,s);a.push(s)}for(let s of a){let o=[];try{o=await t(s)}catch(c){throw new rp("unresolvable-hostname",`Cannot pin hostname "${s}" to stable IPv4 addresses at create time (${c instanceof Error?c.message:String(c)}). Daytona enforces IPv4 CIDRs only; use an IPv4 CIDR for this destination instead.`,s)}if(o.length===0)throw new rp("unresolvable-hostname",`Hostname "${s}" resolved to no IPv4 addresses. Daytona enforces IPv4 CIDRs only; use an IPv4 CIDR for this destination instead.`,s);console.warn(`[daytona] Network allowlist: pinning "${s}" to [${o.join(", ")}] (DNS resolved at create time). Daytona enforces IPv4 CIDRs only \u2014 if this host rotates DNS (CDNs and cloud APIs often do), traffic to its new IPs will be BLOCKED for the sandbox's lifetime.`);for(let c of o)r.push(`${c}/32`)}let i=[...new Set(r)];if(i.length>L8)throw new rp("allowlist-too-large",`Daytona allows at most ${L8} entries in its network allowlist; this policy resolved to ${i.length} CIDRs (${i.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return{networkBlockAll:!1,networkAllowList:i.join(",")}}async function MAe(e,t=CAe){let n=await dM(e,t);return n.networkAllowList!==void 0?{networkBlockAll:!1,networkAllowList:n.networkAllowList,domainAllowList:""}:{networkBlockAll:n.networkBlockAll===!0,networkAllowList:"",domainAllowList:""}}function DAe(e){let t=j8(e),n=(e instanceof Error?e.message:String(e)).toLowerCase(),r=n.includes("network policy")||n.includes("network settings")||n.includes("network configuration"),a=n.includes("tier")||n.includes("plan")||n.includes("upgrade")||n.includes("not allowed")||n.includes("not permitted")||n.includes("cannot override");return(t===402||t===403)&&(a||r)?!0:r&&a}function UAe(e){let t=e.indexOf("/");if(t<0)return;let n=e.substring(0,t);return n.includes(".")||n.includes(":")||n==="localhost"?n:void 0}function X8(e){return{sandboxId:e.id,image:e.snapshot??"",name:e.name,metadata:e.labels??{},startedAt:e.createdAt??""}}function BAe(e){if(e==="started")return"running";if(e==="stopped"||e==="archived"||e==="paused")return"paused"}function FAe(e,t){if(!e||typeof e!="object")return;let n=e;if(typeof n.toolboxProxyUrl=="string"&&(n.toolboxProxyUrl=t),Array.isArray(n.items))for(let r of n.items)FAe(r,t)}function bNt(e,t){return new Proxy(e,{get(n,r,a){if(r==="getToolboxProxyUrl")return async()=>({data:{url:t}});let i=Reflect.get(n,r,a);return typeof i!="function"?i:function(...s){let o=i.apply(n,s);return o instanceof Promise?o.then(c=>(FAe(c?.data,t),c)):o}}})}function _Nt(e,t){let n=new Uint8Array(new ArrayBuffer(e.length+t.length));return n.set(e,0),n.set(t,e.length),n}function yAe(e,t,n){e:for(let r=n;r+t.length<=e.length;r++){for(let a=0;a<t.length;a++)if(e[r+a]!==t[a])continue e;return r}return-1}function LAe(e,t){let n=new TextDecoder("utf-8"),r=new TextDecoder("utf-8"),a=new Uint8Array(0),i="stdout",s=o=>{o.length!==0&&(i==="stdout"?e(n.decode(o,{stream:!0})):t(r.decode(o,{stream:!0})))};return{push(o){for(a=_Nt(a,o);;){let c=yAe(a,Xg,0),l=yAe(a,Zg,0),u=-1,d="stdout",f=0;if(c!==-1&&(l===-1||c<l)?(u=c,d="stdout",f=Xg.length):l!==-1&&(u=l,d="stderr",f=Zg.length),u===-1){let h=Math.max(0,a.length-(wh-1));s(a.subarray(0,h)),a=a.slice(h);return}s(a.subarray(0,u)),i=d,a=a.slice(u+f)}},flush(){s(a),a=new Uint8Array(0);let o=n.decode();o&&e(o);let c=r.decode();c&&t(c)}}}async function VAe(e,t,n,r,a,i,s){let o=`${e.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(n)}/command/${encodeURIComponent(r)}/logs?follow=true`,c=await fetch(o,{headers:{Authorization:`Bearer ${e.apiKey}`,accept:"application/octet-stream"},...s?{signal:s}:{}});if(!c.ok)throw new Error(`Daytona managed log follow failed: ${c.status} ${await c.text()}`);if(!c.body)return;let l=LAe(a,i),u=c.body.getReader();try{for(;;){let{done:d,value:f}=await u.read();if(d)break;f&&l.push(f)}}finally{l.flush(),await u.cancel().catch(()=>{})}}function qAe(e){let t=e.stdout||"",n=e.stderr||"",r=e.output||"";return!t&&!n&&r?{stdout:r,stderr:""}:{stdout:t,stderr:n}}function wNt(e){let t=[];for(let n of e)n==="running"&&t.push("started"),n==="paused"&&t.push("stopped","archived","paused");return t}async function GAe(e,t){let n=t?.limit,r=[],a=0,i=new Set;try{for await(let s of e){if(n!==void 0&&r.length>=n)return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!0,error:`stopped at the requested limit of ${n} with more sandboxes available`};if(a+=1,a>cM)return{sandboxes:r,complete:!1,pagesFetched:cM,stoppedAtLimit:!1,error:`sandbox list exceeded ${cM} sandboxes scanned`};if(t?.state){let o=BAe(s.state);if(o===void 0||!t.state.includes(o))continue}i.has(s.id)||(i.add(s.id),r.push(X8(s)))}}catch(s){return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!1,error:`sandbox list failed: ${s instanceof Error?s.message:String(s)}`}}return{sandboxes:r,complete:!0,pagesFetched:a,stoppedAtLimit:!1}}function fM(e={}){let t=e.apiKey??process.env.DAYTONA_API_KEY;if(!t)throw new Error("Daytona API key required. Set DAYTONA_API_KEY environment variable or pass apiKey in config. Get your key at https://app.daytona.io/dashboard/keys");return new Z8({...e,apiKey:t})}var vAe,uM,W8,bAe,L8,SAe,lNt,Y8,_Ae,wAe,py,IAe,cM,rp,xAe,fNt,lM,EAe,hy,ST,K8,TAe,pNt,hAe,hNt,kAe,OAe,CAe,SNt,$Ae,zAe,F8,Z8,INt,xNt,ENt,TNt,kNt,ONt,ANt,PNt,RNt,CNt,NNt,MNt,DNt,UNt,BNt,FNt,LNt,VNt,qNt,$Nt,zNt,_T=Q(()=>{"use strict";pAe();vAe=require("dns/promises"),uM="c-7bcda3467a79",W8={[`evolve-all-${uM}`]:`evolvingmachines/evolve-all:${uM}`,"evolve-all":"evolvingmachines/evolve-all"},bAe=10,L8=10,SAe=18e4,lNt=2e3,Y8=6e5,_Ae=5e3,wAe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},py=e=>new Promise(t=>setTimeout(t,Math.max(0,e))),IAe=100,cM=1e4;rp=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="DaytonaNetworkPolicyError",this.reason=e,this.destination=n}},xAe=class extends Error{image;constructor(e,t){let n=t instanceof Error?t.message:String(t??"unknown error");super(`Failed to pull image "${e}" on Daytona: ${n}. Private registry images (e.g. AWS ECR) require registry credentials pre-registered in the Daytona dashboard (Registries page) before sandbox creation \u2014 Daytona has no per-call image pull secret. Register the registry at https://app.daytona.io, then retry. Also ensure the image is linux/amd64 and pinned to a tag or digest (floating tags like "latest" are rejected by Daytona's snapshot builder).`),this.name="DaytonaImagePullError",this.image=e}},fNt=class extends Error{snapshot;constructor(e){super(`Daytona cannot constrain the GPU type for "${e}": the snapshot already exists and pins its resources \u2014 pre-build a snapshot with the desired GPU type under its own name.`),this.name="DaytonaGpuTypeError",this.snapshot=e}},lM=class extends Error{snapshot;constructor(e){super(`Daytona snapshot "${e}" already exists and pins its cpu/memory/disk sizing \u2014 create-from-snapshot cannot resize it, so the requested \`resources\` cannot be enforced. Pre-build a snapshot with the desired sizing under its own name (sizing-addressed), or omit \`resources\` to accept the snapshot's pinned sizing.`),this.name="DaytonaResourcesError",this.snapshot=e}},EAe=class extends Error{constructor(){super("Daytona has no separate idle timeout: auto-stop IS its only clock and it already measures inactivity, so `timeoutMs` is what sets it (autoStopInterval). Set the inactivity bound with `timeoutMs`; a hard bound on the process itself is enforced in-box instead (see withInBoxTimeout)."),this.name="DaytonaIdleTimeoutError"}},hy=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" exists but could not be activated: ${t}. Daytona deactivates snapshots unused for 2 weeks; activation normally completes in seconds. Retry, or activate it manually in the Daytona dashboard (Snapshots page).`),this.name="DaytonaSnapshotActivationError",this.snapshot=e}};ST=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" is being created by another process and this run could not wait it out: ${t}.`),this.name="DaytonaSnapshotConflictError",this.snapshot=e}},K8=Symbol("daytona-snapshot-gone"),TAe=new Set(["pending","pulling","building","snapshotting"]),pNt=3;hAe=new Set(["error","build_failed"]),hNt=new Set(["latest","lts","stable"]);kAe=6e4,OAe=2e3;CAe=e=>(0,vAe.resolve4)(e);SNt=class extends sy{constructor(e,t){super(e);let n=this;n.sandboxApi=bNt(n.sandboxApi,t)}};$Ae=class{constructor(e,t,n){this.sandbox=e,this.user=t,this.managedStream=n}streamTimings=wAe;followLogs(e,t,n,r,a){return this.managedStream?VAe(this.managedStream,this.sandbox.id,e,t,n,r,a):this.sandbox.process.getSessionCommandLogs(e,t,n,r)}async run(e,t){let n=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(r);try{let a=!!(t?.onStdout||t?.onStderr),i=gAe(),s=await this.sandbox.process.executeSessionCommand(r,{command:z8(H8(G8(e,i),t?.cwd,t?.envs,this.user),n),runAsync:a},n),o=s.cmdId;if(a&&!o)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(a&&o){let u="",d="",f=!0,h=Date.now(),g=J8(i,T=>{u+=T,t?.onStdout?.(T)}),v=new AbortController,b=this.followLogs(r,o,T=>{f&&(h=Date.now(),g.push(T))},T=>{f&&(h=Date.now(),d+=T,t?.onStderr?.(T))},v.signal),y=!1,_,w=b.then(()=>{},T=>{y||(_=T)}),x;try{x=await this.awaitStreamedExit(r,o,b,()=>h,t?.timeoutMs)}finally{y=!0,v.abort(),await Promise.race([w,py(this.streamTimings.drainMs)]),f=!1,_===void 0&&g.flush()}if(_!==void 0){let T;try{let R=await this.sandbox.process.getSessionCommandLogs(r,o);T=Lb(R,i)}catch{throw _}if(!T.stdout.startsWith(u)||!T.stderr.startsWith(d))throw _;let k=T.stdout.slice(u.length),O=T.stderr.slice(d.length);u=T.stdout,d=T.stderr,k&&t?.onStdout?.(k),O&&t?.onStderr?.(O)}else if(!u&&!d)try{let T=await this.sandbox.process.getSessionCommandLogs(r,o),k=Lb(T,i);u=k.stdout,d=k.stderr,u&&t?.onStdout?.(u),d&&t?.onStderr?.(d)}catch{}return{exitCode:x,stdout:u,stderr:d}}let{stdout:c,stderr:l}=Lb(s,i);if(!c&&!l&&o)try{let u=await this.sandbox.process.getSessionCommandLogs(r,o),d=Lb(u,i);c=d.stdout,l=d.stderr||l}catch{}return{exitCode:s.exitCode??0,stdout:c,stderr:l}}finally{try{await this.sandbox.process.deleteSession(r)}catch{}}}async awaitStreamedExit(e,t,n,r,a){let i=this.streamTimings,s,o,c=n.then(()=>{s=Date.now()},d=>{s=Date.now(),o=d}),l=a!==void 0&&a>0?Date.now()+a+i.killGraceMs:void 0,u=i.pollMinMs;for(;;){let d=await this.sandbox.process.getSessionCommand(e,t);if(d.exitCode!==void 0&&d.exitCode!==null){for(;s===void 0;){let g=Date.now()-r();if(g>=i.drainMs)break;await Promise.race([c,py(i.drainMs-g)])}return d.exitCode}let f=s!==void 0?s+i.settleMs:void 0,h=l!==void 0&&f!==void 0?Math.min(l,f):l??f;if(h!==void 0&&Date.now()>=h)throw o!==void 0?o:new Error(`Daytona reported no exit code for command ${t} after `+(s!==void 0?"its log stream closed":`${a}ms`));await py(u),u=Math.min(u*2,i.pollMaxMs)}}async spawn(e,t){let n=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);let r=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,a=Date.now(),i=t?.timeoutMs,s=gAe(),o=(await this.sandbox.process.executeSessionCommand(n,{command:z8(H8(G8(e,s),t?.cwd,t?.envs,this.user),r),runAsync:!0},r)).cmdId;if(o&&(t?.onStdout||t?.onStderr)){let l=J8(s,t.onStdout||(()=>{}));this.followLogs(n,o,u=>l.push(u),t.onStderr||(()=>{})).catch(()=>{}).finally(()=>l.flush())}let c=this.sandbox;return{processId:n,wait:async()=>{if(!o)return{exitCode:0,stdout:"",stderr:""};for(;;){if(i&&Date.now()-a>=i){try{await c.process.deleteSession(n)}catch{}return{exitCode:124,stdout:"",stderr:"operation timed out"}}try{let l=await c.process.getSessionCommand(n,o);if(l.exitCode!==void 0)try{let u=await c.process.getSessionCommandLogs(n,o);return{exitCode:l.exitCode,...Lb(u,s)}}catch{return{exitCode:l.exitCode,stdout:"",stderr:""}}}catch(l){let u=l instanceof Error?l.message.toLowerCase():String(l).toLowerCase();if(u.includes("not found")){let d=u.includes("sandbox");try{await c.refreshData(),d=!1}catch(f){(f instanceof Error?f.message.toLowerCase():String(f).toLowerCase()).includes("not found")&&(d=!0)}return{exitCode:-1,stdout:"",stderr:d?"sandbox deleted during run":"session terminated"}}throw l}await py(500)}},kill:async()=>{try{return await c.process.deleteSession(n),!0}catch{return!1}}}}async list(){try{return(await this.sandbox.process.listSessions()).map(e=>({processId:e.sessionId||"",cmd:"",args:[],envs:{}}))}catch{return[]}}async kill(e){try{return await this.sandbox.process.deleteSession(e),!0}catch{return!1}}},zAe=class{constructor(e){this.sandbox=e}async read(e){let t=new Uint8Array(await this.sandbox.fs.downloadFile(e));if(!t.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{}return t}async write(e,t){let n;if(typeof t=="string")n=Buffer.from(t,"utf-8");else if(Buffer.isBuffer(t))n=t;else if(t instanceof ArrayBuffer)n=Buffer.from(t);else if(t instanceof Uint8Array)n=Buffer.from(t);else throw new Error(`Unsupported content type: ${typeof t}`);await this.sandbox.fs.uploadFile(n,e)}async writeBatch(e){let t=e.map(n=>{let r;if(typeof n.data=="string")r=Buffer.from(n.data,"utf-8");else if(Buffer.isBuffer(n.data))r=n.data;else if(n.data instanceof ArrayBuffer)r=Buffer.from(n.data);else if(n.data instanceof Uint8Array)r=Buffer.from(n.data);else throw new Error(`Unsupported content type: ${typeof n.data}`);return{source:r,destination:n.path}});await this.sandbox.fs.uploadFiles(t)}async writeFromPath(e,t){await this.sandbox.fs.uploadFile(t,e)}async makeDir(e){await this.sandbox.fs.createFolder(e,"755")}async exists(e){try{let t=uNt(e),n=dNt(e);return(await this.sandbox.fs.listFiles(t)).some(r=>r.name===n)}catch{return!1}}async list(e){return(await this.sandbox.fs.listFiles(e)).map(t=>({name:t.name,path:e.endsWith("/")?`${e}${t.name}`:`${e}/${t.name}`,type:t.isDir?"dir":"file"}))}async remove(e){await this.sandbox.fs.deleteFile(e,!0)}async rename(e,t){await this.sandbox.fs.moveFiles(e,t)}},F8=class{constructor(e,t,n){this.sandbox=e,this.commands=new $Ae(e,t,n),this.files=new zAe(e)}commands;files;get sandboxId(){return this.sandbox.id}async getHost(e){return(await this.sandbox.getPreviewLink(e)).url}async isRunning(){try{await this.sandbox.refreshData()}catch{return!1}return this.sandbox.state==="started"}async getInfo(){return await this.sandbox.refreshData(),X8(this.sandbox)}async updateNetwork(e){let t=await MAe(e);try{await this.sandbox.updateNetworkSettings(t)}catch(n){throw DAe(n)?new rp("org-tier-forbidden",`Daytona refused to change this sandbox's network policy: organizations on Tier 1 or Tier 2 cannot override network policy at the sandbox level. Raise the organization's tier, or run this workload on a provider whose plan permits runtime policy changes (underlying error: ${n instanceof Error?n.message:String(n)}).`):n}}async kill(){await this.sandbox.delete()}async pause(){await this.sandbox.stop()}},Z8=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:Y8,pollMs:_Ae};snapshotDeleteTiming={timeoutMs:kAe,pollMs:OAe};constructor(e){let t={apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target,useDeprecatedPolling:!0};this.client=e.managedToolboxUrl?new SNt(t,e.managedToolboxUrl):new sy(t),e.managedToolboxUrl&&(this.managedStream={toolboxUrl:e.managedToolboxUrl,apiKey:e.apiKey}),this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.snapshotName=e.snapshotName??(e.managedToolboxUrl?"evolve-all":`evolve-all-${uM}`)}async create(e){if(e.idleTimeoutMs!==void 0)throw new EAe;for(let f of e.phaseNetworkPolicies??[])await dM(f);let t=await dM(e.network),n=e.user,r=n&&n!=="root"?n:void 0,a=e.timeoutMs??this.defaultTimeoutMs,i=Math.max(1,Math.ceil(a/6e4)),s=e.image||this.snapshotName,o={envVars:e.envs,labels:e.metadata,autoStopInterval:i,autoDeleteInterval:bAe,...r?{user:r}:{},...t},c,l=e.resources!==void 0&&(e.resources.cpu!==void 0||e.resources.memory!==void 0||e.resources.disk!==void 0||e.resources.gpu!==void 0||e.resources.gpuTypes!==void 0);if(this.managedStream){if(l)throw new lM(s);let f=await this.client.create({snapshot:s,...o},{timeout:600});return e.workingDirectory&&await f.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(f.id,n),new F8(f,n,this.managedStream)}let u,d;try{let f=await this.client.snapshot.get(s),h=f?.state;if(f&&TAe.has(h??"")&&(u=h),f&&(h==="active"||h==="inactive")&&l)throw new lM(s);if(f&&h==="inactive"&&(h=(await V8(this.client,s,f)).state),f&&hAe.has(h??"")&&(q8(s)?d=await mAe(this.client,s,f,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${s}" is dead (state "${h}") but this provider cannot rebuild that name \u2014 delete it in the Daytona dashboard (Snapshots page), or rebuild it with the tooling that created it.`)),f&&h==="active")console.log(`[daytona] Using cached snapshot: ${s}`),c=await this.client.create({snapshot:s,...o},{timeout:600});else throw new Error("Snapshot not active")}catch(f){if(f instanceof lM||f instanceof hy)throw f;let h=W8[s]??s,g=u!==void 0&&!l;g?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") \u2014 joining that build rather than starting a second one.`):u!==void 0?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") and cannot carry the requested sizing \u2014 pulling image directly instead: ${h}`):(console.log(`[daytona] Snapshot "${s}" not found, building from image: ${h}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(d===!1)throw new Error(`dead snapshot "${s}" was not confirmed removed \u2014 not racing its removal`);let v=()=>this.client.snapshot.create({name:s,image:bh.base(h),resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{onLogs:y=>console.log(`[daytona] ${y}`)}),b=async()=>{await v(),console.log(`[daytona] Snapshot "${s}" ready (rebuilt here after a dead build).`)};if(u!==void 0){if(!g)throw new Error(`snapshot "${s}" is mid-build (state "${u}") and cannot be resized`);await this.joinInFlightSnapshotBuild(s)&&await b()}else try{await v(),console.log(`[daytona] Snapshot "${s}" ready (built here).`)}catch(y){if(!AAe(y)||l)throw y;await this.joinInFlightSnapshotBuild(s)&&await b()}c=await this.client.create({snapshot:s,...o},{timeout:600})}catch(v){if(v instanceof ST||v instanceof hy)throw v;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${v instanceof Error?v.message:v}`);try{c=await this.client.create({image:h,...o,resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{timeout:600,onSnapshotCreateLogs:b=>console.log(`[daytona] ${b}`)})}catch(b){throw UAe(h)?new xAe(h,b):b}}}return e.workingDirectory&&await c.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(c.id,n),new F8(c,n,this.managedStream)}async joinInFlightSnapshotBuild(e){let t=await PAe(this.client,e,this.snapshotConflictTiming);if(t===K8)return!0;if(t.state==="active")return console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(t.state==="inactive")return await V8(this.client,e,t),console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(hAe.has(t.state??"")&&q8(e)&&await mAe(this.client,e,t,this.snapshotDeleteTiming))return!0;throw new Error(`the in-flight build of snapshot "${e}" ended in state "${t.state??"unknown"}"`)}async connect(e,t){let n=await this.client.get(e);return n.state!=="started"&&await n.start(),new F8(n,this.sandboxUsers.get(e),this.managedStream)}async list(e){let t=await this.paginate(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.paginate(e);return n}async paginate(e){return GAe(this.listStream(e),e)}listStream(e){let t=e?.state?wNt(e.state):void 0,n={limit:IAe,...e?.metadata?{labels:e.metadata}:{},...t&&t.length>0?{states:t}:{}};return this.client.list(n)}};INt=GAe;xNt=H8,ENt=z8,TNt=dM,kNt=MAe,ONt=DAe,ANt=UAe,PNt=X8,RNt=BAe,CNt=V8,NNt=PAe,MNt=AAe,DNt=q8,UNt=W8,BNt=G8,FNt=RAe,LNt=Lb,VNt=J8,qNt=LAe,$Nt=VAe,zNt=qAe});var JAe=S(pM=>{"use strict";Object.defineProperty(pM,"__esModule",{value:!0});pM.Metadata=void 0;pM.Metadata=function(t){let n=new Map,r={set(a,i){if(a=Vb(a),Array.isArray(i))if(i.length===0)n.delete(a);else{for(let s of i)eW(a,s);n.set(a,a.endsWith("-bin")?i:[i.join(", ")])}else eW(a,i),n.set(a,[i]);return r},append(a,i){a=Vb(a),eW(a,i);let s=n.get(a);return s==null&&(s=[],n.set(a,s)),s.push(i),a.endsWith("-bin")||n.set(a,[s.join(", ")]),r},delete(a){a=Vb(a),n.delete(a)},get(a){var i;return a=Vb(a),(i=n.get(a))===null||i===void 0?void 0:i[0]},getAll(a){var i;return a=Vb(a),(i=n.get(a))!==null&&i!==void 0?i:[]},has(a){return a=Vb(a),n.has(a)},[Symbol.iterator](){return n[Symbol.iterator]()}};if(t!=null){let a=GNt(t)?t:Object.entries(t);for(let[i,s]of a)r.set(i,s)}return r};function Vb(e){return e.toLowerCase()}function eW(e,t){if(!/^[0-9a-z_.-]+$/.test(e))throw new Error(`Metadata key '${e}' contains illegal characters`);if(e.endsWith("-bin")){if(!(t instanceof Uint8Array))throw new Error(`Metadata key '${e}' ends with '-bin', thus it must have binary value`)}else{if(typeof t!="string")throw new Error(`Metadata key '${e}' doesn't end with '-bin', thus it must have string value`);if(!/^[ -~]*$/.test(t))throw new Error(`Metadata value '${t}' of key '${e}' contains illegal characters`)}}function GNt(e){return Symbol.iterator in e}});var hM=S(wT=>{"use strict";Object.defineProperty(wT,"__esModule",{value:!0});wT.Status=void 0;var JNt;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(JNt=wT.Status||(wT.Status={}))});var WAe=S(HAe=>{"use strict";Object.defineProperty(HAe,"__esModule",{value:!0})});var KAe=S(YAe=>{"use strict";Object.defineProperty(YAe,"__esModule",{value:!0})});var XAe=S(jAe=>{"use strict";Object.defineProperty(jAe,"__esModule",{value:!0})});var ZAe=S(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.composeClientMiddleware=void 0;function HNt(e,t){return(n,r)=>t(Object.assign(Object.assign({},n),{next:(a,i)=>e(Object.assign(Object.assign({},n),{request:a}),i)}),r)}mM.composeClientMiddleware=HNt});var tPe=S(Eh=>{"use strict";Eh.__esModule=void 0;Eh.__esModule=!0;var WNt=typeof Object.setPrototypeOf=="function",YNt=typeof Object.getPrototypeOf=="function",KNt=typeof Object.defineProperty=="function",jNt=typeof Object.create=="function",XNt=typeof Object.prototype.hasOwnProperty=="function",ZNt=function(t,n){WNt?Object.setPrototypeOf(t,n):t.__proto__=n};Eh.setPrototypeOf=ZNt;var QNt=function(t){return YNt?Object.getPrototypeOf(t):t.__proto__||t.prototype};Eh.getPrototypeOf=QNt;var QAe=!1,e1t=function e(t,n,r){if(KNt&&!QAe)try{Object.defineProperty(t,n,r)}catch{QAe=!0,e(t,n,r)}else t[n]=r.value};Eh.defineProperty=e1t;var ePe=function(t,n){return XNt?t.hasOwnProperty(t,n):t[n]===void 0};Eh.hasOwnProperty=ePe;var t1t=function(t,n){if(jNt)return Object.create(t,n);var r=function(){};r.prototype=t;var a=new r;if(typeof n>"u")return a;if(typeof n=="null")throw new Error("PropertyDescriptors must not be null.");if(typeof n=="object")for(var i in n)ePe(n,i)&&(a[i]=n[i].value);return a};Eh.objectCreate=t1t});var nW=S(qb=>{"use strict";qb.__esModule=void 0;qb.__esModule=!0;var yM=tPe(),n1t=yM.setPrototypeOf,r1t=yM.getPrototypeOf,tW=yM.defineProperty,i1t=yM.objectCreate,a1t=new Error().toString()==="[object Error]",gM="";function IT(e){var t=this.constructor,n=t.name||function(){var o=t.toString().match(/^function\s*([^\s(]+)/);return o===null?gM||"Error":o[1]}(),r=n==="Error",a=r?gM:n,i=Error.apply(this,arguments);if(n1t(i,r1t(this)),!(i instanceof t)||!(i instanceof IT)){var i=this;Error.apply(this,arguments),tW(i,"message",{configurable:!0,enumerable:!1,value:e,writable:!0})}if(tW(i,"name",{configurable:!0,enumerable:!1,value:a,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(i,r?IT:t),i.stack===void 0){var s=new Error(e);s.name=i.name,i.stack=s.stack}return a1t&&tW(i,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),i}gM=IT.name||"ExtendableError";IT.prototype=i1t(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}});qb.ExtendableError=IT;qb.default=qb.ExtendableError});var nPe=S(vM=>{"use strict";Object.defineProperty(vM,"__esModule",{value:!0});vM.ClientError=void 0;var s1t=nW(),o1t=hM(),rW=class e extends s1t.ExtendableError{constructor(t,n,r){super(`${t} ${o1t.Status[n]}: ${r}`),this.path=t,this.code=n,this.details=r,this.name="ClientError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ClientError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ClientError"]===!0||t.name==="ClientError"&&t["@@nice-grpc"]===!0)}};vM.ClientError=rW});var iPe=S(rPe=>{"use strict";Object.defineProperty(rPe,"__esModule",{value:!0})});var sPe=S(aPe=>{"use strict";Object.defineProperty(aPe,"__esModule",{value:!0})});var oPe=S(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0});bM.composeServerMiddleware=void 0;function c1t(e,t){return(n,r)=>e(Object.assign(Object.assign({},n),{next:(a,i)=>t(Object.assign(Object.assign({},n),{request:a}),i)}),r)}bM.composeServerMiddleware=c1t});var cPe=S(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0});SM.ServerError=void 0;var l1t=nW(),u1t=hM(),iW=class e extends l1t.ExtendableError{constructor(t,n){super(`${u1t.Status[t]}: ${n}`),this.code=t,this.details=n,this.name="ServerError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ServerError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ServerError"]===!0||t.name==="ServerError"&&t["@@nice-grpc"]===!0)}};SM.ServerError=iW});var Wc=S(qa=>{"use strict";var d1t=qa&&qa.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Jl=qa&&qa.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&d1t(t,e,n)};Object.defineProperty(qa,"__esModule",{value:!0});Jl(JAe(),qa);Jl(hM(),qa);Jl(WAe(),qa);Jl(KAe(),qa);Jl(XAe(),qa);Jl(ZAe(),qa);Jl(nPe(),qa);Jl(iPe(),qa);Jl(sPe(),qa);Jl(oPe(),qa);Jl(cPe(),qa)});var Kt=S(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=Yc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=Yc.Propagate=Yc.LogVerbosity=Yc.Status=void 0;var lPe;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(lPe||(Yc.Status=lPe={}));var uPe;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.NONE=3]="NONE"})(uPe||(Yc.LogVerbosity=uPe={}));var dPe;(function(e){e[e.DEADLINE=1]="DEADLINE",e[e.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",e[e.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",e[e.CANCELLATION=8]="CANCELLATION",e[e.DEFAULTS=65535]="DEFAULTS"})(dPe||(Yc.Propagate=dPe={}));Yc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;Yc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4*1024*1024});var aW=S((eSn,f1t)=>{f1t.exports={name:"@grpc/grpc-js",version:"1.14.3",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var hr=S(cc=>{"use strict";var sW,oW,cW,lW;Object.defineProperty(cc,"__esModule",{value:!0});cc.log=cc.setLoggerVerbosity=cc.setLogger=cc.getLogger=void 0;cc.trace=I1t;cc.isTracerEnabled=pPe;var Th=Kt(),p1t=require("process"),h1t=aW().version,m1t={error:(e,...t)=>{console.error("E "+e,...t)},info:(e,...t)=>{console.error("I "+e,...t)},debug:(e,...t)=>{console.error("D "+e,...t)}},my=m1t,$b=Th.LogVerbosity.ERROR,g1t=(oW=(sW=process.env.GRPC_NODE_VERBOSITY)!==null&&sW!==void 0?sW:process.env.GRPC_VERBOSITY)!==null&&oW!==void 0?oW:"";switch(g1t.toUpperCase()){case"DEBUG":$b=Th.LogVerbosity.DEBUG;break;case"INFO":$b=Th.LogVerbosity.INFO;break;case"ERROR":$b=Th.LogVerbosity.ERROR;break;case"NONE":$b=Th.LogVerbosity.NONE;break;default:}var y1t=()=>my;cc.getLogger=y1t;var v1t=e=>{my=e};cc.setLogger=v1t;var b1t=e=>{$b=e};cc.setLoggerVerbosity=b1t;var S1t=(e,...t)=>{let n;if(e>=$b){switch(e){case Th.LogVerbosity.DEBUG:n=my.debug;break;case Th.LogVerbosity.INFO:n=my.info;break;case Th.LogVerbosity.ERROR:n=my.error;break}n||(n=my.error),n&&n.bind(my)(...t)}};cc.log=S1t;var _1t=(lW=(cW=process.env.GRPC_NODE_TRACE)!==null&&cW!==void 0?cW:process.env.GRPC_TRACE)!==null&&lW!==void 0?lW:"",uW=new Set,fPe=new Set;for(let e of _1t.split(","))e.startsWith("-")?fPe.add(e.substring(1)):uW.add(e);var w1t=uW.has("all");function I1t(e,t,n){pPe(t)&&(0,cc.log)(e,new Date().toISOString()+" | v"+h1t+" "+p1t.pid+" | "+t+" | "+n)}function pPe(e){return!fPe.has(e)&&(w1t||uW.has(e))}});var wM=S(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0});_M.getErrorMessage=x1t;_M.getErrorCode=E1t;function x1t(e){return e instanceof Error?e.message:String(e)}function E1t(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"?e.code:null}});var ma=S(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.Metadata=void 0;var T1t=hr(),k1t=Kt(),O1t=wM(),A1t=/^[:0-9a-z_.-]+$/,P1t=/^[ -~]*$/;function R1t(e){return A1t.test(e)}function C1t(e){return P1t.test(e)}function mPe(e){return e.endsWith("-bin")}function N1t(e){return!e.startsWith("grpc-")}function IM(e){return e.toLowerCase()}function hPe(e,t){if(!R1t(e))throw new Error('Metadata key "'+e+'" contains illegal characters');if(t!=null)if(mPe(e)){if(!Buffer.isBuffer(t))throw new Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(t))throw new Error("keys that don't end with '-bin' must have String values");if(!C1t(t))throw new Error('Metadata string value "'+t+'" contains illegal characters')}}var dW=class e{constructor(t={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=t}set(t,n){t=IM(t),hPe(t,n),this.internalRepr.set(t,[n])}add(t,n){t=IM(t),hPe(t,n);let r=this.internalRepr.get(t);r===void 0?this.internalRepr.set(t,[n]):r.push(n)}remove(t){t=IM(t),this.internalRepr.delete(t)}get(t){return t=IM(t),this.internalRepr.get(t)||[]}getMap(){let t={};for(let[n,r]of this.internalRepr)if(r.length>0){let a=r[0];t[n]=Buffer.isBuffer(a)?Buffer.from(a):a}return t}clone(){let t=new e(this.options),n=t.internalRepr;for(let[r,a]of this.internalRepr){let i=a.map(s=>Buffer.isBuffer(s)?Buffer.from(s):s);n.set(r,i)}return t}merge(t){for(let[n,r]of t.internalRepr){let a=(this.internalRepr.get(n)||[]).concat(r);this.internalRepr.set(n,a)}}setOptions(t){this.options=t}getOptions(){return this.options}toHttp2Headers(){let t={};for(let[n,r]of this.internalRepr)n.startsWith(":")||(t[n]=r.map(M1t));return t}toJSON(){let t={};for(let[n,r]of this.internalRepr)t[n]=r;return t}setOpaque(t,n){this.opaqueData.set(t,n)}getOpaque(t){return this.opaqueData.get(t)}static fromHttp2Headers(t){let n=new e;for(let r of Object.keys(t)){if(r.charAt(0)===":")continue;let a=t[r];try{mPe(r)?Array.isArray(a)?a.forEach(i=>{n.add(r,Buffer.from(i,"base64"))}):a!==void 0&&(N1t(r)?a.split(",").forEach(i=>{n.add(r,Buffer.from(i.trim(),"base64"))}):n.add(r,Buffer.from(a,"base64"))):Array.isArray(a)?a.forEach(i=>{n.add(r,i)}):a!==void 0&&n.add(r,a)}catch(i){let s=`Failed to add metadata entry ${r}: ${a}. ${(0,O1t.getErrorMessage)(i)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,T1t.log)(k1t.LogVerbosity.ERROR,s)}}return n}};xM.Metadata=dW;var M1t=e=>Buffer.isBuffer(e)?e.toString("base64"):e});var TM=S(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0});EM.CallCredentials=void 0;var mW=ma();function D1t(e){return"getRequestHeaders"in e&&typeof e.getRequestHeaders=="function"}var zb=class e{static createFromMetadataGenerator(t){return new pW(t)}static createFromGoogleCredential(t){return e.createFromMetadataGenerator((n,r)=>{let a;D1t(t)?a=t.getRequestHeaders(n.service_url):a=new Promise((i,s)=>{t.getRequestMetadata(n.service_url,(o,c)=>{if(o){s(o);return}if(!c){s(new Error("Headers not set by metadata plugin"));return}i(c)})}),a.then(i=>{let s=new mW.Metadata;for(let o of Object.keys(i))s.add(o,i[o]);r(null,s)},i=>{r(i)})})}static createEmpty(){return new hW}};EM.CallCredentials=zb;var fW=class e extends zb{constructor(t){super(),this.creds=t}async generateMetadata(t){let n=new mW.Metadata,r=await Promise.all(this.creds.map(a=>a.generateMetadata(t)));for(let a of r)n.merge(a);return n}compose(t){return new e(this.creds.concat([t]))}_equals(t){return this===t?!0:t instanceof e?this.creds.every((n,r)=>n._equals(t.creds[r])):!1}},pW=class e extends zb{constructor(t){super(),this.metadataGenerator=t}generateMetadata(t){return new Promise((n,r)=>{this.metadataGenerator(t,(a,i)=>{i!==void 0?n(i):r(a)})})}compose(t){return new fW([this,t])}_equals(t){return this===t?!0:t instanceof e?this.metadataGenerator===t.metadataGenerator:!1}},hW=class e extends zb{generateMetadata(t){return Promise.resolve(new mW.Metadata)}compose(t){return t}_equals(t){return t instanceof e}}});var yW=S(xT=>{"use strict";Object.defineProperty(xT,"__esModule",{value:!0});xT.CIPHER_SUITES=void 0;xT.getDefaultRootsData=B1t;var U1t=require("fs");xT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var gPe=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,gW=null;function B1t(){return gPe?(gW===null&&(gW=U1t.readFileSync(gPe)),gW):null}});var eo=S(Gb=>{"use strict";Object.defineProperty(Gb,"__esModule",{value:!0});Gb.parseUri=L1t;Gb.splitHostPort=V1t;Gb.combineHostPort=q1t;Gb.uriToString=$1t;var F1t=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function L1t(e){let t=F1t.exec(e);return t===null?null:{scheme:t[1],authority:t[2],path:t[3]}}var yPe=/^\d+$/;function V1t(e){if(e.startsWith("[")){let t=e.indexOf("]");if(t===-1)return null;let n=e.substring(1,t);if(n.indexOf(":")===-1)return null;if(e.length>t+1)if(e[t+1]===":"){let r=e.substring(t+2);return yPe.test(r)?{host:n,port:+r}:null}else return null;else return{host:n}}else{let t=e.split(":");return t.length===2?yPe.test(t[1])?{host:t[0],port:+t[1]}:null:{host:e}}}function q1t(e){return e.port===void 0?e.host:e.host.includes(":")?`[${e.host}]:${e.port}`:`${e.host}:${e.port}`}function $1t(e){let t="";return e.scheme!==void 0&&(t+=e.scheme+":"),e.authority!==void 0&&(t+="//"+e.authority+"/"),t+=e.path,t}});var Hl=S(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});ip.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;ip.registerResolver=z1t;ip.registerDefaultScheme=G1t;ip.createResolver=J1t;ip.getDefaultAuthority=H1t;ip.mapUriDefaultScheme=W1t;var bW=eo();ip.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var Jb={},vW=null;function z1t(e,t){Jb[e]=t}function G1t(e){vW=e}function J1t(e,t,n){if(e.scheme!==void 0&&e.scheme in Jb)return new Jb[e.scheme](e,t,n);throw new Error(`No resolver could be created for target ${(0,bW.uriToString)(e)}`)}function H1t(e){if(e.scheme!==void 0&&e.scheme in Jb)return Jb[e.scheme].getDefaultAuthority(e);throw new Error(`Invalid target ${(0,bW.uriToString)(e)}`)}function W1t(e){return e.scheme===void 0||!(e.scheme in Jb)?vW!==null?{scheme:vW,authority:void 0,path:(0,bW.uriToString)(e)}:null:e}});var Hb=S(TT=>{"use strict";Object.defineProperty(TT,"__esModule",{value:!0});TT.ChannelCredentials=void 0;TT.createCertificateProviderChannelCredentials=X1t;var ET=require("tls"),AM=TM(),_W=yW(),vPe=eo(),Y1t=Hl(),K1t=hr(),j1t=Kt();function SW(e,t){if(e&&!(e instanceof Buffer))throw new TypeError(`${t}, if provided, must be a Buffer.`)}var gy=class{compose(t){return new xW(this,t)}static createSsl(t,n,r,a){var i;if(SW(t,"Root certificate"),SW(n,"Private key"),SW(r,"Certificate chain"),n&&!r)throw new Error("Private key must be given with accompanying certificate chain");if(!n&&r)throw new Error("Certificate chain must be given with accompanying private key");let s=(0,ET.createSecureContext)({ca:(i=t??(0,_W.getDefaultRootsData)())!==null&&i!==void 0?i:void 0,key:n??void 0,cert:r??void 0,ciphers:_W.CIPHER_SUITES});return new kM(s,a??{})}static createFromSecureContext(t,n){return new kM(t,n??{})}static createInsecure(){return new wW}};TT.ChannelCredentials=gy;var wW=class e extends gy{constructor(){super()}compose(t){throw new Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals(t){return t instanceof e}_createSecureConnector(t,n,r){return{connect(a){return Promise.resolve({socket:a,secure:!1})},waitForReady:()=>Promise.resolve(),getCallCredentials:()=>r??AM.CallCredentials.createEmpty(),destroy(){}}}};function bPe(e,t,n,r){var a,i;let s={secureContext:e},o=n;if("grpc.http_connect_target"in r){let d=(0,vPe.parseUri)(r["grpc.http_connect_target"]);d&&(o=d)}let c=(0,Y1t.getDefaultAuthority)(o),l=(0,vPe.splitHostPort)(c),u=(a=l?.host)!==null&&a!==void 0?a:c;if(s.host=u,t.checkServerIdentity&&(s.checkServerIdentity=t.checkServerIdentity),t.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=t.rejectUnauthorized),s.ALPNProtocols=["h2"],r["grpc.ssl_target_name_override"]){let d=r["grpc.ssl_target_name_override"],f=(i=s.checkServerIdentity)!==null&&i!==void 0?i:ET.checkServerIdentity;s.checkServerIdentity=(h,g)=>f(d,g),s.servername=d}else s.servername=u;return r["grpc-node.tls_enable_trace"]&&(s.enableTrace=!0),s}var IW=class{constructor(t,n){this.connectionOptions=t,this.callCredentials=n}connect(t){let n=Object.assign({socket:t},this.connectionOptions);return new Promise((r,a)=>{let i=(0,ET.connect)(n,()=>{var s;if((!((s=this.connectionOptions.rejectUnauthorized)!==null&&s!==void 0)||s)&&!i.authorized){a(i.authorizationError);return}r({socket:i,secure:!0})});i.on("error",s=>{a(s)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}},kM=class e extends gy{constructor(t,n){super(),this.secureContext=t,this.verifyOptions=n}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.secureContext===t.secureContext&&this.verifyOptions.checkServerIdentity===t.verifyOptions.checkServerIdentity:!1}_createSecureConnector(t,n,r){let a=bPe(this.secureContext,this.verifyOptions,t,n);return new IW(a,r??AM.CallCredentials.createEmpty())}},OM=class e extends gy{constructor(t,n,r){super(),this.caCertificateProvider=t,this.identityCertificateProvider=n,this.verifyOptions=r,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals(t){var n,r;return this===t?!0:t instanceof e?this.caCertificateProvider===t.caCertificateProvider&&this.identityCertificateProvider===t.identityCertificateProvider&&((n=this.verifyOptions)===null||n===void 0?void 0:n.checkServerIdentity)===((r=t.verifyOptions)===null||r===void 0?void 0:r.checkServerIdentity):!1}ref(){var t;this.refcount===0&&(this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.addIdentityCertificateListener(this.identityCertificateUpdateListener)),this.refcount+=1}unref(){var t;this.refcount-=1,this.refcount===0&&(this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.removeIdentityCertificateListener(this.identityCertificateUpdateListener))}_createSecureConnector(t,n,r){return this.ref(),new e.SecureConnectorImpl(this,t,n,r??AM.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let t of this.secureContextWatchers)t(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate(t){this.latestCaUpdate=t,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate(t){this.latestIdentityUpdate=t,this.maybeUpdateWatchers()}hasReceivedUpdates(){return!(this.latestCaUpdate===void 0||this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)}getSecureContext(){return this.hasReceivedUpdates()?Promise.resolve(this.getLatestSecureContext()):new Promise(t=>{this.secureContextWatchers.push(t)})}getLatestSecureContext(){var t,n;if(!this.latestCaUpdate||this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,ET.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:(t=this.latestIdentityUpdate)===null||t===void 0?void 0:t.privateKey,cert:(n=this.latestIdentityUpdate)===null||n===void 0?void 0:n.certificate,ciphers:_W.CIPHER_SUITES})}catch(r){return(0,K1t.log)(j1t.LogVerbosity.ERROR,"Failed to createSecureContext with error "+r.message),null}}};OM.SecureConnectorImpl=class{constructor(e,t,n,r){this.parent=e,this.channelTarget=t,this.options=n,this.callCredentials=r}connect(e){return new Promise((t,n)=>{let r=this.parent.getLatestSecureContext();if(!r){n(new Error("Failed to load credentials"));return}e.closed&&n(new Error("Socket closed while loading credentials"));let a=bPe(r,this.parent.verifyOptions,this.channelTarget,this.options),i=Object.assign({socket:e},a),s=()=>{n(new Error("Socket closed"))},o=l=>{n(l)},c=(0,ET.connect)(i,()=>{var l;if(c.removeListener("close",s),c.removeListener("error",o),(!((l=this.parent.verifyOptions.rejectUnauthorized)!==null&&l!==void 0)||l)&&!c.authorized){n(c.authorizationError);return}t({socket:c,secure:!0})});c.once("close",s),c.once("error",o)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function X1t(e,t,n){return new OM(e,t,n??{})}var xW=class e extends gy{constructor(t,n){if(super(),this.channelCredentials=t,this.callCredentials=n,!t._isSecure())throw new Error("Cannot compose insecure credentials")}compose(t){let n=this.callCredentials.compose(t);return new e(this.channelCredentials,n)}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.channelCredentials._equals(t.channelCredentials)&&this.callCredentials._equals(t.callCredentials):!1}_createSecureConnector(t,n,r){let a=this.callCredentials.compose(r??AM.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector(t,n,a)}}});var Oh=S(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});bd.createChildChannelControlHelper=e2t;bd.registerLoadBalancerType=t2t;bd.registerDefaultLoadBalancerType=n2t;bd.createLoadBalancer=r2t;bd.isLoadBalancerNameRegistered=i2t;bd.parseLoadBalancingConfig=SPe;bd.getDefaultConfig=a2t;bd.selectLbConfigFromList=s2t;var Z1t=hr(),Q1t=Kt();function e2t(e,t){var n,r,a,i,s,o,c,l,u,d;return{createSubchannel:(r=(n=t.createSubchannel)===null||n===void 0?void 0:n.bind(t))!==null&&r!==void 0?r:e.createSubchannel.bind(e),updateState:(i=(a=t.updateState)===null||a===void 0?void 0:a.bind(t))!==null&&i!==void 0?i:e.updateState.bind(e),requestReresolution:(o=(s=t.requestReresolution)===null||s===void 0?void 0:s.bind(t))!==null&&o!==void 0?o:e.requestReresolution.bind(e),addChannelzChild:(l=(c=t.addChannelzChild)===null||c===void 0?void 0:c.bind(t))!==null&&l!==void 0?l:e.addChannelzChild.bind(e),removeChannelzChild:(d=(u=t.removeChannelzChild)===null||u===void 0?void 0:u.bind(t))!==null&&d!==void 0?d:e.removeChannelzChild.bind(e)}}var kh={},kT=null;function t2t(e,t,n){kh[e]={LoadBalancer:t,LoadBalancingConfig:n}}function n2t(e){kT=e}function r2t(e,t){let n=e.getLoadBalancerName();return n in kh?new kh[n].LoadBalancer(t):null}function i2t(e){return e in kh}function SPe(e){let t=Object.keys(e);if(t.length!==1)throw new Error("Provided load balancing config has multiple conflicting entries");let n=t[0];if(n in kh)try{return kh[n].LoadBalancingConfig.createFromJson(e[n])}catch(r){throw new Error(`${n}: ${r.message}`)}else throw new Error(`Unrecognized load balancing config name ${n}`)}function a2t(){if(!kT)throw new Error("No default load balancer type registered");return new kh[kT].LoadBalancingConfig}function s2t(e,t=!1){for(let n of e)try{return SPe(n)}catch(r){(0,Z1t.log)(Q1t.LogVerbosity.DEBUG,"Config parsing failed with error",r.message);continue}return t&&kT?new kh[kT].LoadBalancingConfig:null}});var EW=S(OT=>{"use strict";Object.defineProperty(OT,"__esModule",{value:!0});OT.validateRetryThrottling=_Pe;OT.validateServiceConfig=wPe;OT.extractAndSelectServiceConfig=g2t;var o2t=require("os"),PM=Kt(),RM=/^\d+(\.\d{1,9})?s$/,c2t="node";function l2t(e){if("service"in e&&e.service!==""){if(typeof e.service!="string")throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof e.service}`);if("method"in e&&e.method!==""){if(typeof e.method!="string")throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof e.service}`);return{service:e.service,method:e.method}}else return{service:e.service}}else{if("method"in e&&e.method!==void 0)throw new Error("Invalid method config name: method set with empty or unset service");return{}}}function u2t(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in e)||typeof e.initialBackoff!="string"||!RM.test(e.initialBackoff))throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in e)||typeof e.maxBackoff!="string"||!RM.test(e.maxBackoff))throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in e)||typeof e.backoffMultiplier!="number"||e.backoffMultiplier<=0)throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!("retryableStatusCodes"in e&&Array.isArray(e.retryableStatusCodes)))throw new Error("Invalid method config retry policy: retryableStatusCodes is required");if(e.retryableStatusCodes.length===0)throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let t of e.retryableStatusCodes)if(typeof t=="number"){if(!Object.values(PM.Status).includes(t))throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof t=="string"){if(!Object.values(PM.Status).includes(t.toUpperCase()))throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:e.maxAttempts,initialBackoff:e.initialBackoff,maxBackoff:e.maxBackoff,backoffMultiplier:e.backoffMultiplier,retryableStatusCodes:e.retryableStatusCodes}}function d2t(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in e&&(typeof e.hedgingDelay!="string"||!RM.test(e.hedgingDelay)))throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in e&&Array.isArray(e.nonFatalStatusCodes))for(let n of e.nonFatalStatusCodes)if(typeof n=="number"){if(!Object.values(PM.Status).includes(n))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof n=="string"){if(!Object.values(PM.Status).includes(n.toUpperCase()))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let t={maxAttempts:e.maxAttempts};return e.hedgingDelay&&(t.hedgingDelay=e.hedgingDelay),e.nonFatalStatusCodes&&(t.nonFatalStatusCodes=e.nonFatalStatusCodes),t}function f2t(e){var t;let n={name:[]};if(!("name"in e)||!Array.isArray(e.name))throw new Error("Invalid method config: invalid name array");for(let r of e.name)n.name.push(l2t(r));if("waitForReady"in e){if(typeof e.waitForReady!="boolean")throw new Error("Invalid method config: invalid waitForReady");n.waitForReady=e.waitForReady}if("timeout"in e)if(typeof e.timeout=="object"){if(!("seconds"in e.timeout)||typeof e.timeout.seconds!="number")throw new Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in e.timeout)||typeof e.timeout.nanos!="number")throw new Error("Invalid method config: invalid timeout.nanos");n.timeout=e.timeout}else if(typeof e.timeout=="string"&&RM.test(e.timeout)){let r=e.timeout.substring(0,e.timeout.length-1).split(".");n.timeout={seconds:r[0]|0,nanos:((t=r[1])!==null&&t!==void 0?t:0)|0}}else throw new Error("Invalid method config: invalid timeout");if("maxRequestBytes"in e){if(typeof e.maxRequestBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxRequestBytes=e.maxRequestBytes}if("maxResponseBytes"in e){if(typeof e.maxResponseBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxResponseBytes=e.maxResponseBytes}if("retryPolicy"in e){if("hedgingPolicy"in e)throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");n.retryPolicy=u2t(e.retryPolicy)}else"hedgingPolicy"in e&&(n.hedgingPolicy=d2t(e.hedgingPolicy));return n}function _Pe(e){if(!("maxTokens"in e)||typeof e.maxTokens!="number"||e.maxTokens<=0||e.maxTokens>1e3)throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in e)||typeof e.tokenRatio!="number"||e.tokenRatio<=0)throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+e.maxTokens.toFixed(3),tokenRatio:+e.tokenRatio.toFixed(3)}}function p2t(e){if(!(typeof e=="object"&&e!==null))throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof e}`);let t=Object.keys(e);if(t.length>1)throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${t}`);if(t.length===0)throw new Error("Invalid loadBalancingConfig: load balancing policy name required");return{[t[0]]:e[t[0]]}}function wPe(e){let t={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in e)if(typeof e.loadBalancingPolicy=="string")t.loadBalancingPolicy=e.loadBalancingPolicy;else throw new Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in e)if(Array.isArray(e.loadBalancingConfig))for(let r of e.loadBalancingConfig)t.loadBalancingConfig.push(p2t(r));else throw new Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in e&&Array.isArray(e.methodConfig))for(let r of e.methodConfig)t.methodConfig.push(f2t(r));"retryThrottling"in e&&(t.retryThrottling=_Pe(e.retryThrottling));let n=[];for(let r of t.methodConfig)for(let a of r.name){for(let i of n)if(a.service===i.service&&a.method===i.method)throw new Error(`Invalid service config: duplicate name ${a.service}/${a.method}`);n.push(a)}return t}function h2t(e){if(!("serviceConfig"in e))throw new Error("Invalid service config choice: missing service config");let t={serviceConfig:wPe(e.serviceConfig)};if("clientLanguage"in e)if(Array.isArray(e.clientLanguage)){t.clientLanguage=[];for(let r of e.clientLanguage)if(typeof r=="string")t.clientLanguage.push(r);else throw new Error("Invalid service config choice: invalid clientLanguage")}else throw new Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in e)if(Array.isArray(e.clientHostname)){t.clientHostname=[];for(let r of e.clientHostname)if(typeof r=="string")t.clientHostname.push(r);else throw new Error("Invalid service config choice: invalid clientHostname")}else throw new Error("Invalid service config choice: invalid clientHostname");if("percentage"in e)if(typeof e.percentage=="number"&&0<=e.percentage&&e.percentage<=100)t.percentage=e.percentage;else throw new Error("Invalid service config choice: invalid percentage");let n=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let r in e)if(!n.includes(r))throw new Error(`Invalid service config choice: unexpected field ${r}`);return t}function m2t(e,t){if(!Array.isArray(e))throw new Error("Invalid service config list");for(let n of e){let r=h2t(n);if(!(typeof r.percentage=="number"&&t>r.percentage)){if(Array.isArray(r.clientHostname)){let a=!1;for(let i of r.clientHostname)i===o2t.hostname()&&(a=!0);if(!a)continue}if(Array.isArray(r.clientLanguage)){let a=!1;for(let i of r.clientLanguage)i===c2t&&(a=!0);if(!a)continue}return r.serviceConfig}}throw new Error("No matching service config found")}function g2t(e,t){for(let n of e)if(n.length>0&&n[0].startsWith("grpc_config=")){let r=n.join("").substring(12),a=JSON.parse(r);return m2t(a,t)}return null}});var to=S(CM=>{"use strict";Object.defineProperty(CM,"__esModule",{value:!0});CM.ConnectivityState=void 0;var IPe;(function(e){e[e.IDLE=0]="IDLE",e[e.CONNECTING=1]="CONNECTING",e[e.READY=2]="READY",e[e.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",e[e.SHUTDOWN=4]="SHUTDOWN"})(IPe||(CM.ConnectivityState=IPe={}))});var ap=S(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});Ah.QueuePicker=Ah.UnavailablePicker=Ah.PickResultType=void 0;var y2t=ma(),v2t=Kt(),NM;(function(e){e[e.COMPLETE=0]="COMPLETE",e[e.QUEUE=1]="QUEUE",e[e.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",e[e.DROP=3]="DROP"})(NM||(Ah.PickResultType=NM={}));var TW=class{constructor(t){this.status=Object.assign({code:v2t.Status.UNAVAILABLE,details:"No connection established",metadata:new y2t.Metadata},t)}pick(t){return{pickResultType:NM.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}};Ah.UnavailablePicker=TW;var kW=class{constructor(t,n){this.loadBalancer=t,this.childPicker=n,this.calledExitIdle=!1}pick(t){return this.calledExitIdle||(process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0),this.childPicker?this.childPicker.pick(t):{pickResultType:NM.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}};Ah.QueuePicker=kW});var Wb=S(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0});DM.BackoffTimeout=void 0;var b2t=Kt(),S2t=hr(),_2t="backoff",w2t=1e3,I2t=1.6,x2t=12e4,E2t=.2;function T2t(e,t){return Math.random()*(t-e)+e}var MM=class e{constructor(t,n){this.callback=t,this.initialDelay=w2t,this.multiplier=I2t,this.maxDelay=x2t,this.jitter=E2t,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=e.getNextId(),n&&(n.initialDelay&&(this.initialDelay=n.initialDelay),n.multiplier&&(this.multiplier=n.multiplier),n.jitter&&(this.jitter=n.jitter),n.maxDelay&&(this.maxDelay=n.maxDelay)),this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace(t){S2t.trace(b2t.LogVerbosity.DEBUG,_2t,"{"+this.id+"} "+t)}runTimer(t){var n,r;this.trace("runTimer(delay="+t+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+t),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},t),this.hasRef||(r=(n=this.timerId).unref)===null||r===void 0||r.call(n)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let t=Math.min(this.nextDelay*this.multiplier,this.maxDelay),n=t*this.jitter;this.nextDelay=t+T2t(-n,n)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let t=new Date,n=this.startTime;n.setMilliseconds(n.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),t<n?this.runTimer(n.getTime()-t.getTime()):this.running=!1}}isRunning(){return this.running}ref(){var t,n;this.hasRef=!0,(n=(t=this.timerId).ref)===null||n===void 0||n.call(t)}unref(){var t,n;this.hasRef=!1,(n=(t=this.timerId).unref)===null||n===void 0||n.call(t)}getEndTime(){return this.endTime}};DM.BackoffTimeout=MM;MM.nextId=0});var BM=S(UM=>{"use strict";Object.defineProperty(UM,"__esModule",{value:!0});UM.ChildLoadBalancerHandler=void 0;var k2t=Oh(),O2t=to(),A2t="child_load_balancer_helper",OW=class{constructor(t){this.channelControlHelper=t,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(n){this.parent=n,this.child=null}createSubchannel(n,r){return this.parent.channelControlHelper.createSubchannel(n,r)}updateState(n,r,a){var i;if(this.calledByPendingChild()){if(n===O2t.ConnectivityState.CONNECTING)return;(i=this.parent.currentChild)===null||i===void 0||i.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(n,r,a)}requestReresolution(){var n;let r=(n=this.parent.pendingChild)!==null&&n!==void 0?n:this.parent.currentChild;this.child===r&&this.parent.channelControlHelper.requestReresolution()}setChild(n){this.child=n}addChannelzChild(n){this.parent.channelControlHelper.addChannelzChild(n)}removeChannelzChild(n){this.parent.channelControlHelper.removeChannelzChild(n)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance(t,n){return t.getLoadBalancerName()!==n.getLoadBalancerName()}updateAddressList(t,n,r,a){let i;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,n)){let s=new this.ChildPolicyHelper(this),o=(0,k2t.createLoadBalancer)(n,s);s.setChild(o),this.currentChild===null?(this.currentChild=o,i=this.currentChild):(this.pendingChild&&this.pendingChild.destroy(),this.pendingChild=o,i=this.pendingChild)}else this.pendingChild===null?i=this.currentChild:i=this.pendingChild;return this.latestConfig=n,i.updateAddressList(t,n,r,a)}exitIdle(){this.currentChild&&(this.currentChild.exitIdle(),this.pendingChild&&this.pendingChild.exitIdle())}resetBackoff(){this.currentChild&&(this.currentChild.resetBackoff(),this.pendingChild&&this.pendingChild.resetBackoff())}destroy(){this.currentChild&&(this.currentChild.destroy(),this.currentChild=null),this.pendingChild&&(this.pendingChild.destroy(),this.pendingChild=null)}getTypeName(){return A2t}};UM.ChildLoadBalancerHandler=OW});var TPe=S(FM=>{"use strict";Object.defineProperty(FM,"__esModule",{value:!0});FM.ResolvingLoadBalancer=void 0;var P2t=Oh(),R2t=EW(),Oo=to(),xPe=Hl(),AT=ap(),C2t=Wb(),AW=Kt(),N2t=ma(),M2t=hr(),D2t=Kt(),U2t=eo(),B2t=BM(),F2t="resolving_load_balancer";function EPe(e){M2t.trace(D2t.LogVerbosity.DEBUG,F2t,e)}var L2t=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function V2t(e,t,n,r){for(let a of n.name)switch(r){case"EMPTY":if(!a.service&&!a.method)return!0;break;case"SERVICE":if(a.service===e&&!a.method)return!0;break;case"SERVICE_AND_METHOD":if(a.service===e&&a.method===t)return!0}return!1}function q2t(e,t,n,r){for(let a of n)if(V2t(e,t,a,r))return a;return null}function $2t(e){return{invoke(t,n){var r,a;let i=t.split("/").filter(c=>c.length>0),s=(r=i[0])!==null&&r!==void 0?r:"",o=(a=i[1])!==null&&a!==void 0?a:"";if(e&&e.methodConfig)for(let c of L2t){let l=q2t(s,o,e.methodConfig,c);if(l)return{methodConfig:l,pickInformation:{},status:AW.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:AW.Status.OK,dynamicFilterFactories:[]}},unref(){}}}var PW=class{constructor(t,n,r,a,i){this.target=t,this.channelControlHelper=n,this.channelOptions=r,this.onSuccessfulResolution=a,this.onFailedResolution=i,this.latestChildState=Oo.ConnectivityState.IDLE,this.latestChildPicker=new AT.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=Oo.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,r["grpc.service_config"]?this.defaultServiceConfig=(0,R2t.validateServiceConfig)(JSON.parse(r["grpc.service_config"])):this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]},this.updateState(Oo.ConnectivityState.IDLE,new AT.QueuePicker(this),null),this.childLoadBalancer=new B2t.ChildLoadBalancerHandler({createSubchannel:n.createSubchannel.bind(n),requestReresolution:()=>{this.backoffTimeout.isRunning()?(EPe("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0):this.updateResolution()},updateState:(o,c,l)=>{this.latestChildState=o,this.latestChildPicker=c,this.latestChildErrorMessage=l,this.updateState(o,c,l)},addChannelzChild:n.addChannelzChild.bind(n),removeChannelzChild:n.removeChannelzChild.bind(n)}),this.innerResolver=(0,xPe.createResolver)(t,this.handleResolverResult.bind(this),r);let s={initialDelay:r["grpc.initial_reconnect_backoff_ms"],maxDelay:r["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new C2t.BackoffTimeout(()=>{this.continueResolving?(this.updateResolution(),this.continueResolving=!1):this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},s),this.backoffTimeout.unref()}handleResolverResult(t,n,r,a){var i,s;this.backoffTimeout.stop(),this.backoffTimeout.reset();let o=!0,c=null;if(r===null?c=this.defaultServiceConfig:r.ok?c=r.value:this.previousServiceConfig!==null?c=this.previousServiceConfig:(o=!1,this.handleResolutionFailure(r.error)),c!==null){let l=(i=c?.loadBalancingConfig)!==null&&i!==void 0?i:[],u=(0,P2t.selectLbConfigFromList)(l,!0);u===null?(o=!1,this.handleResolutionFailure({code:AW.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new N2t.Metadata})):o=this.childLoadBalancer.updateAddressList(t,u,Object.assign(Object.assign({},this.channelOptions),n),a)}return o&&this.onSuccessfulResolution(c,(s=n[xPe.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&s!==void 0?s:$2t(c)),o}updateResolution(){this.innerResolver.updateResolution(),this.currentState===Oo.ConnectivityState.IDLE&&this.updateState(Oo.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage),this.backoffTimeout.runOnce()}updateState(t,n,r){EPe((0,U2t.uriToString)(this.target)+" "+Oo.ConnectivityState[this.currentState]+" -> "+Oo.ConnectivityState[t]),t===Oo.ConnectivityState.IDLE&&(n=new AT.QueuePicker(this,n)),this.currentState=t,this.channelControlHelper.updateState(t,n,r)}handleResolutionFailure(t){this.latestChildState===Oo.ConnectivityState.IDLE&&(this.updateState(Oo.ConnectivityState.TRANSIENT_FAILURE,new AT.UnavailablePicker(t),t.details),this.onFailedResolution(t))}exitIdle(){(this.currentState===Oo.ConnectivityState.IDLE||this.currentState===Oo.ConnectivityState.TRANSIENT_FAILURE)&&(this.backoffTimeout.isRunning()?this.continueResolving=!0:this.updateResolution()),this.childLoadBalancer.exitIdle()}updateAddressList(t,n){throw new Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=Oo.ConnectivityState.IDLE,this.latestChildPicker=new AT.QueuePicker(this),this.currentState=Oo.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}};FM.ResolvingLoadBalancer=PW});var kPe=S(PT=>{"use strict";Object.defineProperty(PT,"__esModule",{value:!0});PT.recognizedOptions=void 0;PT.channelOptionsEqual=z2t;PT.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function z2t(e,t){let n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let a=0;a<n.length;a+=1)if(n[a]!==r[a]||e[n[a]]!==t[r[a]])return!1;return!0}});var Ao=S(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});Wl.EndpointMap=void 0;Wl.isTcpSubchannelAddress=CT;Wl.subchannelAddressEqual=LM;Wl.subchannelAddressToString=APe;Wl.stringToSubchannelAddress=J2t;Wl.endpointEqual=H2t;Wl.endpointToString=W2t;Wl.endpointHasAddress=PPe;var OPe=require("net");function CT(e){return"port"in e}function LM(e,t){return!e&&!t?!0:!e||!t?!1:CT(e)?CT(t)&&e.host===t.host&&e.port===t.port:!CT(t)&&e.path===t.path}function APe(e){return CT(e)?(0,OPe.isIPv6)(e.host)?"["+e.host+"]:"+e.port:e.host+":"+e.port:e.path}var G2t=443;function J2t(e,t){return(0,OPe.isIP)(e)?{host:e,port:t??G2t}:{path:e}}function H2t(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n=0;n<e.addresses.length;n++)if(!LM(e.addresses[n],t.addresses[n]))return!1;return!0}function W2t(e){return"["+e.addresses.map(APe).join(", ")+"]"}function PPe(e,t){for(let n of e.addresses)if(LM(n,t))return!0;return!1}function RT(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n of e.addresses){let r=!1;for(let a of t.addresses)if(LM(n,a)){r=!0;break}if(!r)return!1}return!0}var RW=class{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress(t){for(let n of this.map)if(PPe(n.key,t))return n.value}deleteMissing(t){let n=[];for(let r of this.map){let a=!1;for(let i of t)RT(i,r.key)&&(a=!0);a||(n.push(r.value),this.map.delete(r))}return n}get(t){for(let n of this.map)if(RT(t,n.key))return n.value}set(t,n){for(let r of this.map)if(RT(t,r.key)){r.value=n;return}this.map.add({key:t,value:n})}delete(t){for(let n of this.map)if(RT(t,n.key)){this.map.delete(n);return}}has(t){for(let n of this.map)if(RT(t,n.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let t of this.map)yield t.key}*values(){for(let t of this.map)yield t.value}*entries(){for(let t of this.map)yield[t.key,t.value]}};Wl.EndpointMap=RW});var RPe=S(LW=>{"use strict";Object.defineProperty(LW,"t",{value:!0});var VM=class{constructor(t,n,r=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=t,this.l=n,this.p=r}I(){let t=this,n=t.o.o===t;if(n&&t.p===1)t=t.h;else if(t.i)for(t=t.i;t.h;)t=t.h;else{if(n)return t.o;let r=t.o;for(;r.i===t;)t=r,r=t.o;t=r}return t}B(){let t=this;if(t.h){for(t=t.h;t.i;)t=t.i;return t}else{let n=t.o;for(;n.h===t;)t=n,n=t.o;return t.h!==n?n:t}}_(){let t=this.o,n=this.h,r=n.i;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.i=this,this.o=n,this.h=r,r&&(r.o=this),n}g(){let t=this.o,n=this.i,r=n.h;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.h=this,this.o=n,this.i=r,r&&(r.o=this),n}},CW=class extends VM{constructor(){super(...arguments),this.M=1}_(){let t=super._();return this.O(),t.O(),t}g(){let t=super.g();return this.O(),t.O(),t}O(){this.M=1,this.i&&(this.M+=this.i.M),this.h&&(this.M+=this.h.M)}},NW=class{constructor(t=0){this.iteratorType=t}equals(t){return this.T===t.T}},MW=class{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}},DW=class extends MW{};function yy(){throw new RangeError("Iterator access denied!")}var UW=class extends DW{constructor(t=function(r,a){return r<a?-1:r>a?1:0},n=!1){super(),this.v=void 0,this.A=t,this.enableIndex=n,this.N=n?CW:VM,this.C=new this.N}R(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)t=t.h;else if(a>0)r=t,t=t.i;else return t}return r}K(t,n){let r=this.C;for(;t;)this.A(t.u,n)<=0?t=t.h:(r=t,t=t.i);return r}L(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)r=t,t=t.h;else if(a>0)t=t.i;else return t}return r}k(t,n){let r=this.C;for(;t;)this.A(t.u,n)<0?(r=t,t=t.h):t=t.i;return r}P(t){for(;;){let n=t.o;if(n===this.C)return;if(t.p===1){t.p=0;return}if(t===n.i){let r=n.h;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n._():n._();else if(r.h&&r.h.p===1){r.p=n.p,n.p=0,r.h.p=0,n===this.v?this.v=n._():n._();return}else r.i&&r.i.p===1?(r.p=1,r.i.p=0,r.g()):(r.p=1,t=n)}else{let r=n.i;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n.g():n.g();else if(r.i&&r.i.p===1){r.p=n.p,n.p=0,r.i.p=0,n===this.v?this.v=n.g():n.g();return}else r.h&&r.h.p===1?(r.p=1,r.h.p=0,r._()):(r.p=1,t=n)}}}S(t){if(this.m===1){this.clear();return}let n=t;for(;n.i||n.h;){if(n.h)for(n=n.h;n.i;)n=n.i;else n=n.i;let a=t.u;t.u=n.u,n.u=a;let i=t.l;t.l=n.l,n.l=i,t=n}this.C.i===n?this.C.i=n.o:this.C.h===n&&(this.C.h=n.o),this.P(n);let r=n.o;if(n===r.i?r.i=void 0:r.h=void 0,this.m-=1,this.v.p=0,this.enableIndex)for(;r!==this.C;)r.M-=1,r=r.o}U(t){let n=typeof t=="number"?t:void 0,r=typeof t=="function"?t:void 0,a=typeof t>"u"?[]:void 0,i=0,s=this.v,o=[];for(;o.length||s;)if(s)o.push(s),s=s.i;else{if(s=o.pop(),i===n)return s;a&&a.push(s),r&&r(s,i,this),i+=1,s=s.h}return a}j(t){for(;;){let n=t.o;if(n.p===0)return;let r=n.o;if(n===r.i){let a=r.h;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.h){if(t.p=0,t.i&&(t.i.o=n),t.h&&(t.h.o=r),n.h=t.i,r.i=t.h,t.i=n,t.h=r,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r.g():r.g(),r.p=1;return}}else{let a=r.i;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.i){if(t.p=0,t.i&&(t.i.o=r),t.h&&(t.h.o=n),r.h=t.i,n.i=t.h,t.i=r,t.h=n,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r._():r._(),r.p=1;return}}this.enableIndex&&(n.O(),r.O(),t.O());return}}q(t,n,r){if(this.v===void 0)return this.m+=1,this.v=new this.N(t,n,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let a,i=this.C.i,s=this.A(i.u,t);if(s===0)return i.l=n,this.m;if(s>0)i.i=new this.N(t,n),i.i.o=i,a=i.i,this.C.i=a;else{let o=this.C.h,c=this.A(o.u,t);if(c===0)return o.l=n,this.m;if(c<0)o.h=new this.N(t,n),o.h.o=o,a=o.h,this.C.h=a;else{if(r!==void 0){let l=r.T;if(l!==this.C){let u=this.A(l.u,t);if(u===0)return l.l=n,this.m;if(u>0){let d=l.I(),f=this.A(d.u,t);if(f===0)return d.l=n,this.m;f<0&&(a=new this.N(t,n),d.h===void 0?(d.h=a,a.o=d):(l.i=a,a.o=l))}}}if(a===void 0)for(a=this.v;;){let l=this.A(a.u,t);if(l>0){if(a.i===void 0){a.i=new this.N(t,n),a.i.o=a,a=a.i;break}a=a.i}else if(l<0){if(a.h===void 0){a.h=new this.N(t,n),a.h.o=a,a=a.h;break}a=a.h}else return a.l=n,this.m}}}if(this.enableIndex){let o=a.o;for(;o!==this.C;)o.M+=1,o=o.o}return this.j(a),this.m+=1,this.m}H(t,n){for(;t;){let r=this.A(t.u,n);if(r<0)t=t.h;else if(r>0)t=t.i;else return t}return t||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator(t,n){let r=t.T;if(r===this.C&&yy(),this.m===1)return r.u=n,!0;let a=r.B().u;if(r===this.C.i)return this.A(a,n)>0?(r.u=n,!0):!1;let i=r.I().u;return r===this.C.h?this.A(i,n)<0?(r.u=n,!0):!1:this.A(i,n)>=0||this.A(a,n)<=0?!1:(r.u=n,!0)}eraseElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return this.S(n),this.m}eraseElementByKey(t){if(this.m===0)return!1;let n=this.H(this.v,t);return n===this.C?!1:(this.S(n),!0)}eraseElementByIterator(t){let n=t.T;n===this.C&&yy();let r=n.h===void 0;return t.iteratorType===0?r&&t.next():(!r||n.i===void 0)&&t.next(),this.S(n),t}getHeight(){if(this.m===0)return 0;function t(n){return n?Math.max(t(n.i),t(n.h))+1:0}return t(this.v)}},BW=class extends NW{constructor(t,n,r){super(r),this.T=t,this.C=n,this.iteratorType===0?(this.pre=function(){return this.T===this.C.i&&yy(),this.T=this.T.I(),this},this.next=function(){return this.T===this.C&&yy(),this.T=this.T.B(),this}):(this.pre=function(){return this.T===this.C.h&&yy(),this.T=this.T.B(),this},this.next=function(){return this.T===this.C&&yy(),this.T=this.T.I(),this})}get index(){let t=this.T,n=this.C.o;if(t===this.C)return n?n.M-1:0;let r=0;for(t.i&&(r+=t.i.M);t!==n;){let a=t.o;t===a.h&&(r+=1,a.i&&(r+=a.i.M)),t=a}return r}isAccessible(){return this.T!==this.C}},Yl=class e extends BW{constructor(t,n,r,a){super(t,n,a),this.container=r}get pointer(){this.T===this.C&&yy();let t=this;return new Proxy([],{get(n,r){return r==="0"?t.T.u:r==="1"?t.T.l:(n[0]=t.T.u,n[1]=t.T.l,n[r])},set(n,r,a){if(r!=="1")throw new TypeError("prop must be 1");return t.T.l=a,!0}})}copy(){return new e(this.T,this.C,this.container,this.iteratorType)}},FW=class extends UW{constructor(t=[],n,r){super(n,r);let a=this;t.forEach(function(i){a.setElement(i[0],i[1])})}begin(){return new Yl(this.C.i||this.C,this.C,this)}end(){return new Yl(this.C,this.C,this)}rBegin(){return new Yl(this.C.h||this.C,this.C,this,1)}rEnd(){return new Yl(this.C,this.C,this,1)}front(){if(this.m===0)return;let t=this.C.i;return[t.u,t.l]}back(){if(this.m===0)return;let t=this.C.h;return[t.u,t.l]}lowerBound(t){let n=this.R(this.v,t);return new Yl(n,this.C,this)}upperBound(t){let n=this.K(this.v,t);return new Yl(n,this.C,this)}reverseLowerBound(t){let n=this.L(this.v,t);return new Yl(n,this.C,this)}reverseUpperBound(t){let n=this.k(this.v,t);return new Yl(n,this.C,this)}forEach(t){this.U(function(n,r,a){t([n.u,n.l],r,a)})}setElement(t,n,r){return this.q(t,n,r)}getElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return[n.u,n.l]}find(t){let n=this.H(this.v,t);return new Yl(n,this.C,this)}getElementByKey(t){return this.H(this.v,t).l}union(t){let n=this;return t.forEach(function(r){n.setElement(r[0],r[1])}),this.m}*[Symbol.iterator](){let t=this.m,n=this.U();for(let r=0;r<t;++r){let a=n[r];yield[a.u,a.l]}}};LW.OrderedMap=FW});var $M=S(qM=>{"use strict";Object.defineProperty(qM,"__esModule",{value:!0});qM.registerAdminService=Y2t;qM.addAdminServicesToServer=K2t;var CPe=[];function Y2t(e,t){CPe.push({getServiceDefinition:e,getHandlers:t})}function K2t(e){for(let{getServiceDefinition:t,getHandlers:n}of CPe)e.addService(t(),n())}});var NPe=S(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});Kl.ClientDuplexStreamImpl=Kl.ClientWritableStreamImpl=Kl.ClientReadableStreamImpl=Kl.ClientUnaryCallImpl=void 0;Kl.callErrorFromStatus=X2t;var j2t=require("events"),GW=require("stream"),NT=Kt();function X2t(e,t){let n=`${e.code} ${NT.Status[e.code]}: ${e.details}`,a=`${new Error(n).stack}
|
|
213
|
+
`,r="",a=i=>{for(let s=Math.min(i.length,n.length);s>0;s--)if(n.startsWith(i.slice(i.length-s)))return s;return 0};return{push(i){r+=i;let s=a(r);s!==r.length&&(t(r.slice(0,r.length-s)),r=r.slice(r.length-s))},flush(){let i=r===n||r===e?"":r;r="",i&&t(i)}}}function H8(e,t,n,r){let a=e;return t&&(a=`cd '${t.replace(/'/g,"'\\''")}' && ${a}`),n&&Object.keys(n).length>0&&(a=`${Object.entries(n).filter(([,i])=>i!=null).map(([i,s])=>`export ${i}='${String(s).replace(/'/g,"'\\''")}'`).join("; ")}; ${a}`),r==="root"&&(a=`echo ${Buffer.from(a).toString("base64")} | base64 -d | sudo -n bash`),a}function NAe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function gNt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!NAe(e)}function yNt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function vNt(e){return/^[^:]+:\d+$/.test(e)}async function dM(e,t=CAe){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return e?{networkBlockAll:!1}:{}}let n=e.allowedDestinations??[];if(n.length===0)return{networkBlockAll:!0};let r=[],a=[];for(let s of n)if(NAe(s))r.push(s.includes("/")?s:`${s}/32`);else{if(gNt(s))throw new rp("invalid-ipv4",`"${s}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,s);if(yNt(s))throw new rp("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${s}".`,s);if(vNt(s))throw new rp("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${s}" and list just the host or IP.`,s);if(s.includes("*"))throw new rp("wildcard-hostname",`Daytona cannot enforce wildcard hostname "${s}": its allowlist is kernel-level IPv4 CIDR filtering with no DNS/domain layer. List concrete hostnames or IPv4 CIDRs instead.`,s);a.push(s)}for(let s of a){let o=[];try{o=await t(s)}catch(c){throw new rp("unresolvable-hostname",`Cannot pin hostname "${s}" to stable IPv4 addresses at create time (${c instanceof Error?c.message:String(c)}). Daytona enforces IPv4 CIDRs only; use an IPv4 CIDR for this destination instead.`,s)}if(o.length===0)throw new rp("unresolvable-hostname",`Hostname "${s}" resolved to no IPv4 addresses. Daytona enforces IPv4 CIDRs only; use an IPv4 CIDR for this destination instead.`,s);console.warn(`[daytona] Network allowlist: pinning "${s}" to [${o.join(", ")}] (DNS resolved at create time). Daytona enforces IPv4 CIDRs only \u2014 if this host rotates DNS (CDNs and cloud APIs often do), traffic to its new IPs will be BLOCKED for the sandbox's lifetime.`);for(let c of o)r.push(`${c}/32`)}let i=[...new Set(r)];if(i.length>L8)throw new rp("allowlist-too-large",`Daytona allows at most ${L8} entries in its network allowlist; this policy resolved to ${i.length} CIDRs (${i.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return{networkBlockAll:!1,networkAllowList:i.join(",")}}async function MAe(e,t=CAe){let n=await dM(e,t);return n.networkAllowList!==void 0?{networkBlockAll:!1,networkAllowList:n.networkAllowList,domainAllowList:""}:{networkBlockAll:n.networkBlockAll===!0,networkAllowList:"",domainAllowList:""}}function DAe(e){let t=j8(e),n=(e instanceof Error?e.message:String(e)).toLowerCase(),r=n.includes("network policy")||n.includes("network settings")||n.includes("network configuration"),a=n.includes("tier")||n.includes("plan")||n.includes("upgrade")||n.includes("not allowed")||n.includes("not permitted")||n.includes("cannot override");return(t===402||t===403)&&(a||r)?!0:r&&a}function UAe(e){let t=e.indexOf("/");if(t<0)return;let n=e.substring(0,t);return n.includes(".")||n.includes(":")||n==="localhost"?n:void 0}function X8(e){return{sandboxId:e.id,image:e.snapshot??"",name:e.name,metadata:e.labels??{},startedAt:e.createdAt??""}}function BAe(e){if(e==="started")return"running";if(e==="stopped"||e==="archived"||e==="paused")return"paused"}function FAe(e,t){if(!e||typeof e!="object")return;let n=e;if(typeof n.toolboxProxyUrl=="string"&&(n.toolboxProxyUrl=t),Array.isArray(n.items))for(let r of n.items)FAe(r,t)}function bNt(e,t){return new Proxy(e,{get(n,r,a){if(r==="getToolboxProxyUrl")return async()=>({data:{url:t}});let i=Reflect.get(n,r,a);return typeof i!="function"?i:function(...s){let o=i.apply(n,s);return o instanceof Promise?o.then(c=>(FAe(c?.data,t),c)):o}}})}function _Nt(e,t){let n=new Uint8Array(new ArrayBuffer(e.length+t.length));return n.set(e,0),n.set(t,e.length),n}function yAe(e,t,n){e:for(let r=n;r+t.length<=e.length;r++){for(let a=0;a<t.length;a++)if(e[r+a]!==t[a])continue e;return r}return-1}function LAe(e,t){let n=new TextDecoder("utf-8"),r=new TextDecoder("utf-8"),a=new Uint8Array(0),i="stdout",s=o=>{o.length!==0&&(i==="stdout"?e(n.decode(o,{stream:!0})):t(r.decode(o,{stream:!0})))};return{push(o){for(a=_Nt(a,o);;){let c=yAe(a,Xg,0),l=yAe(a,Zg,0),u=-1,d="stdout",f=0;if(c!==-1&&(l===-1||c<l)?(u=c,d="stdout",f=Xg.length):l!==-1&&(u=l,d="stderr",f=Zg.length),u===-1){let h=Math.max(0,a.length-(wh-1));s(a.subarray(0,h)),a=a.slice(h);return}s(a.subarray(0,u)),i=d,a=a.slice(u+f)}},flush(){s(a),a=new Uint8Array(0);let o=n.decode();o&&e(o);let c=r.decode();c&&t(c)}}}async function VAe(e,t,n,r,a,i,s){let o=`${e.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(n)}/command/${encodeURIComponent(r)}/logs?follow=true`,c=await fetch(o,{headers:{Authorization:`Bearer ${e.apiKey}`,accept:"application/octet-stream"},...s?{signal:s}:{}});if(!c.ok)throw new Error(`Daytona managed log follow failed: ${c.status} ${await c.text()}`);if(!c.body)return;let l=LAe(a,i),u=c.body.getReader();try{for(;;){let{done:d,value:f}=await u.read();if(d)break;f&&l.push(f)}}finally{l.flush(),await u.cancel().catch(()=>{})}}function qAe(e){let t=e.stdout||"",n=e.stderr||"",r=e.output||"";return!t&&!n&&r?{stdout:r,stderr:""}:{stdout:t,stderr:n}}function wNt(e){let t=[];for(let n of e)n==="running"&&t.push("started"),n==="paused"&&t.push("stopped","archived","paused");return t}async function GAe(e,t){let n=t?.limit,r=[],a=0,i=new Set;try{for await(let s of e){if(n!==void 0&&r.length>=n)return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!0,error:`stopped at the requested limit of ${n} with more sandboxes available`};if(a+=1,a>cM)return{sandboxes:r,complete:!1,pagesFetched:cM,stoppedAtLimit:!1,error:`sandbox list exceeded ${cM} sandboxes scanned`};if(t?.state){let o=BAe(s.state);if(o===void 0||!t.state.includes(o))continue}i.has(s.id)||(i.add(s.id),r.push(X8(s)))}}catch(s){return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!1,error:`sandbox list failed: ${s instanceof Error?s.message:String(s)}`}}return{sandboxes:r,complete:!0,pagesFetched:a,stoppedAtLimit:!1}}function fM(e={}){let t=e.apiKey??process.env.DAYTONA_API_KEY;if(!t)throw new Error("Daytona API key required. Set DAYTONA_API_KEY environment variable or pass apiKey in config. Get your key at https://app.daytona.io/dashboard/keys");return new Z8({...e,apiKey:t})}var vAe,uM,W8,bAe,L8,SAe,lNt,Y8,_Ae,wAe,py,IAe,cM,rp,xAe,fNt,lM,EAe,hy,ST,K8,TAe,pNt,hAe,hNt,kAe,OAe,CAe,SNt,$Ae,zAe,F8,Z8,INt,xNt,ENt,TNt,kNt,ONt,ANt,PNt,RNt,CNt,NNt,MNt,DNt,UNt,BNt,FNt,LNt,VNt,qNt,$Nt,zNt,_T=Q(()=>{"use strict";pAe();vAe=require("dns/promises"),uM="c-fae503a880ec",W8={[`evolve-all-${uM}`]:`evolvingmachines/evolve-all:${uM}`,"evolve-all":"evolvingmachines/evolve-all"},bAe=10,L8=10,SAe=18e4,lNt=2e3,Y8=6e5,_Ae=5e3,wAe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},py=e=>new Promise(t=>setTimeout(t,Math.max(0,e))),IAe=100,cM=1e4;rp=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="DaytonaNetworkPolicyError",this.reason=e,this.destination=n}},xAe=class extends Error{image;constructor(e,t){let n=t instanceof Error?t.message:String(t??"unknown error");super(`Failed to pull image "${e}" on Daytona: ${n}. Private registry images (e.g. AWS ECR) require registry credentials pre-registered in the Daytona dashboard (Registries page) before sandbox creation \u2014 Daytona has no per-call image pull secret. Register the registry at https://app.daytona.io, then retry. Also ensure the image is linux/amd64 and pinned to a tag or digest (floating tags like "latest" are rejected by Daytona's snapshot builder).`),this.name="DaytonaImagePullError",this.image=e}},fNt=class extends Error{snapshot;constructor(e){super(`Daytona cannot constrain the GPU type for "${e}": the snapshot already exists and pins its resources \u2014 pre-build a snapshot with the desired GPU type under its own name.`),this.name="DaytonaGpuTypeError",this.snapshot=e}},lM=class extends Error{snapshot;constructor(e){super(`Daytona snapshot "${e}" already exists and pins its cpu/memory/disk sizing \u2014 create-from-snapshot cannot resize it, so the requested \`resources\` cannot be enforced. Pre-build a snapshot with the desired sizing under its own name (sizing-addressed), or omit \`resources\` to accept the snapshot's pinned sizing.`),this.name="DaytonaResourcesError",this.snapshot=e}},EAe=class extends Error{constructor(){super("Daytona has no separate idle timeout: auto-stop IS its only clock and it already measures inactivity, so `timeoutMs` is what sets it (autoStopInterval). Set the inactivity bound with `timeoutMs`; a hard bound on the process itself is enforced in-box instead (see withInBoxTimeout)."),this.name="DaytonaIdleTimeoutError"}},hy=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" exists but could not be activated: ${t}. Daytona deactivates snapshots unused for 2 weeks; activation normally completes in seconds. Retry, or activate it manually in the Daytona dashboard (Snapshots page).`),this.name="DaytonaSnapshotActivationError",this.snapshot=e}};ST=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" is being created by another process and this run could not wait it out: ${t}.`),this.name="DaytonaSnapshotConflictError",this.snapshot=e}},K8=Symbol("daytona-snapshot-gone"),TAe=new Set(["pending","pulling","building","snapshotting"]),pNt=3;hAe=new Set(["error","build_failed"]),hNt=new Set(["latest","lts","stable"]);kAe=6e4,OAe=2e3;CAe=e=>(0,vAe.resolve4)(e);SNt=class extends sy{constructor(e,t){super(e);let n=this;n.sandboxApi=bNt(n.sandboxApi,t)}};$Ae=class{constructor(e,t,n){this.sandbox=e,this.user=t,this.managedStream=n}streamTimings=wAe;followLogs(e,t,n,r,a){return this.managedStream?VAe(this.managedStream,this.sandbox.id,e,t,n,r,a):this.sandbox.process.getSessionCommandLogs(e,t,n,r)}async run(e,t){let n=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(r);try{let a=!!(t?.onStdout||t?.onStderr),i=gAe(),s=await this.sandbox.process.executeSessionCommand(r,{command:z8(H8(G8(e,i),t?.cwd,t?.envs,this.user),n),runAsync:a},n),o=s.cmdId;if(a&&!o)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(a&&o){let u="",d="",f=!0,h=Date.now(),g=J8(i,T=>{u+=T,t?.onStdout?.(T)}),v=new AbortController,b=this.followLogs(r,o,T=>{f&&(h=Date.now(),g.push(T))},T=>{f&&(h=Date.now(),d+=T,t?.onStderr?.(T))},v.signal),y=!1,_,w=b.then(()=>{},T=>{y||(_=T)}),x;try{x=await this.awaitStreamedExit(r,o,b,()=>h,t?.timeoutMs)}finally{y=!0,v.abort(),await Promise.race([w,py(this.streamTimings.drainMs)]),f=!1,_===void 0&&g.flush()}if(_!==void 0){let T;try{let R=await this.sandbox.process.getSessionCommandLogs(r,o);T=Lb(R,i)}catch{throw _}if(!T.stdout.startsWith(u)||!T.stderr.startsWith(d))throw _;let k=T.stdout.slice(u.length),O=T.stderr.slice(d.length);u=T.stdout,d=T.stderr,k&&t?.onStdout?.(k),O&&t?.onStderr?.(O)}else if(!u&&!d)try{let T=await this.sandbox.process.getSessionCommandLogs(r,o),k=Lb(T,i);u=k.stdout,d=k.stderr,u&&t?.onStdout?.(u),d&&t?.onStderr?.(d)}catch{}return{exitCode:x,stdout:u,stderr:d}}let{stdout:c,stderr:l}=Lb(s,i);if(!c&&!l&&o)try{let u=await this.sandbox.process.getSessionCommandLogs(r,o),d=Lb(u,i);c=d.stdout,l=d.stderr||l}catch{}return{exitCode:s.exitCode??0,stdout:c,stderr:l}}finally{try{await this.sandbox.process.deleteSession(r)}catch{}}}async awaitStreamedExit(e,t,n,r,a){let i=this.streamTimings,s,o,c=n.then(()=>{s=Date.now()},d=>{s=Date.now(),o=d}),l=a!==void 0&&a>0?Date.now()+a+i.killGraceMs:void 0,u=i.pollMinMs;for(;;){let d=await this.sandbox.process.getSessionCommand(e,t);if(d.exitCode!==void 0&&d.exitCode!==null){for(;s===void 0;){let g=Date.now()-r();if(g>=i.drainMs)break;await Promise.race([c,py(i.drainMs-g)])}return d.exitCode}let f=s!==void 0?s+i.settleMs:void 0,h=l!==void 0&&f!==void 0?Math.min(l,f):l??f;if(h!==void 0&&Date.now()>=h)throw o!==void 0?o:new Error(`Daytona reported no exit code for command ${t} after `+(s!==void 0?"its log stream closed":`${a}ms`));await py(u),u=Math.min(u*2,i.pollMaxMs)}}async spawn(e,t){let n=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);let r=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,a=Date.now(),i=t?.timeoutMs,s=gAe(),o=(await this.sandbox.process.executeSessionCommand(n,{command:z8(H8(G8(e,s),t?.cwd,t?.envs,this.user),r),runAsync:!0},r)).cmdId;if(o&&(t?.onStdout||t?.onStderr)){let l=J8(s,t.onStdout||(()=>{}));this.followLogs(n,o,u=>l.push(u),t.onStderr||(()=>{})).catch(()=>{}).finally(()=>l.flush())}let c=this.sandbox;return{processId:n,wait:async()=>{if(!o)return{exitCode:0,stdout:"",stderr:""};for(;;){if(i&&Date.now()-a>=i){try{await c.process.deleteSession(n)}catch{}return{exitCode:124,stdout:"",stderr:"operation timed out"}}try{let l=await c.process.getSessionCommand(n,o);if(l.exitCode!==void 0)try{let u=await c.process.getSessionCommandLogs(n,o);return{exitCode:l.exitCode,...Lb(u,s)}}catch{return{exitCode:l.exitCode,stdout:"",stderr:""}}}catch(l){let u=l instanceof Error?l.message.toLowerCase():String(l).toLowerCase();if(u.includes("not found")){let d=u.includes("sandbox");try{await c.refreshData(),d=!1}catch(f){(f instanceof Error?f.message.toLowerCase():String(f).toLowerCase()).includes("not found")&&(d=!0)}return{exitCode:-1,stdout:"",stderr:d?"sandbox deleted during run":"session terminated"}}throw l}await py(500)}},kill:async()=>{try{return await c.process.deleteSession(n),!0}catch{return!1}}}}async list(){try{return(await this.sandbox.process.listSessions()).map(e=>({processId:e.sessionId||"",cmd:"",args:[],envs:{}}))}catch{return[]}}async kill(e){try{return await this.sandbox.process.deleteSession(e),!0}catch{return!1}}},zAe=class{constructor(e){this.sandbox=e}async read(e){let t=new Uint8Array(await this.sandbox.fs.downloadFile(e));if(!t.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{}return t}async write(e,t){let n;if(typeof t=="string")n=Buffer.from(t,"utf-8");else if(Buffer.isBuffer(t))n=t;else if(t instanceof ArrayBuffer)n=Buffer.from(t);else if(t instanceof Uint8Array)n=Buffer.from(t);else throw new Error(`Unsupported content type: ${typeof t}`);await this.sandbox.fs.uploadFile(n,e)}async writeBatch(e){let t=e.map(n=>{let r;if(typeof n.data=="string")r=Buffer.from(n.data,"utf-8");else if(Buffer.isBuffer(n.data))r=n.data;else if(n.data instanceof ArrayBuffer)r=Buffer.from(n.data);else if(n.data instanceof Uint8Array)r=Buffer.from(n.data);else throw new Error(`Unsupported content type: ${typeof n.data}`);return{source:r,destination:n.path}});await this.sandbox.fs.uploadFiles(t)}async writeFromPath(e,t){await this.sandbox.fs.uploadFile(t,e)}async makeDir(e){await this.sandbox.fs.createFolder(e,"755")}async exists(e){try{let t=uNt(e),n=dNt(e);return(await this.sandbox.fs.listFiles(t)).some(r=>r.name===n)}catch{return!1}}async list(e){return(await this.sandbox.fs.listFiles(e)).map(t=>({name:t.name,path:e.endsWith("/")?`${e}${t.name}`:`${e}/${t.name}`,type:t.isDir?"dir":"file"}))}async remove(e){await this.sandbox.fs.deleteFile(e,!0)}async rename(e,t){await this.sandbox.fs.moveFiles(e,t)}},F8=class{constructor(e,t,n){this.sandbox=e,this.commands=new $Ae(e,t,n),this.files=new zAe(e)}commands;files;get sandboxId(){return this.sandbox.id}async getHost(e){return(await this.sandbox.getPreviewLink(e)).url}async isRunning(){try{await this.sandbox.refreshData()}catch{return!1}return this.sandbox.state==="started"}async getInfo(){return await this.sandbox.refreshData(),X8(this.sandbox)}async updateNetwork(e){let t=await MAe(e);try{await this.sandbox.updateNetworkSettings(t)}catch(n){throw DAe(n)?new rp("org-tier-forbidden",`Daytona refused to change this sandbox's network policy: organizations on Tier 1 or Tier 2 cannot override network policy at the sandbox level. Raise the organization's tier, or run this workload on a provider whose plan permits runtime policy changes (underlying error: ${n instanceof Error?n.message:String(n)}).`):n}}async kill(){await this.sandbox.delete()}async pause(){await this.sandbox.stop()}},Z8=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:Y8,pollMs:_Ae};snapshotDeleteTiming={timeoutMs:kAe,pollMs:OAe};constructor(e){let t={apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target,useDeprecatedPolling:!0};this.client=e.managedToolboxUrl?new SNt(t,e.managedToolboxUrl):new sy(t),e.managedToolboxUrl&&(this.managedStream={toolboxUrl:e.managedToolboxUrl,apiKey:e.apiKey}),this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.snapshotName=e.snapshotName??(e.managedToolboxUrl?"evolve-all":`evolve-all-${uM}`)}async create(e){if(e.idleTimeoutMs!==void 0)throw new EAe;for(let f of e.phaseNetworkPolicies??[])await dM(f);let t=await dM(e.network),n=e.user,r=n&&n!=="root"?n:void 0,a=e.timeoutMs??this.defaultTimeoutMs,i=Math.max(1,Math.ceil(a/6e4)),s=e.image||this.snapshotName,o={envVars:e.envs,labels:e.metadata,autoStopInterval:i,autoDeleteInterval:bAe,...r?{user:r}:{},...t},c,l=e.resources!==void 0&&(e.resources.cpu!==void 0||e.resources.memory!==void 0||e.resources.disk!==void 0||e.resources.gpu!==void 0||e.resources.gpuTypes!==void 0);if(this.managedStream){if(l)throw new lM(s);let f=await this.client.create({snapshot:s,...o},{timeout:600});return e.workingDirectory&&await f.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(f.id,n),new F8(f,n,this.managedStream)}let u,d;try{let f=await this.client.snapshot.get(s),h=f?.state;if(f&&TAe.has(h??"")&&(u=h),f&&(h==="active"||h==="inactive")&&l)throw new lM(s);if(f&&h==="inactive"&&(h=(await V8(this.client,s,f)).state),f&&hAe.has(h??"")&&(q8(s)?d=await mAe(this.client,s,f,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${s}" is dead (state "${h}") but this provider cannot rebuild that name \u2014 delete it in the Daytona dashboard (Snapshots page), or rebuild it with the tooling that created it.`)),f&&h==="active")console.log(`[daytona] Using cached snapshot: ${s}`),c=await this.client.create({snapshot:s,...o},{timeout:600});else throw new Error("Snapshot not active")}catch(f){if(f instanceof lM||f instanceof hy)throw f;let h=W8[s]??s,g=u!==void 0&&!l;g?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") \u2014 joining that build rather than starting a second one.`):u!==void 0?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") and cannot carry the requested sizing \u2014 pulling image directly instead: ${h}`):(console.log(`[daytona] Snapshot "${s}" not found, building from image: ${h}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(d===!1)throw new Error(`dead snapshot "${s}" was not confirmed removed \u2014 not racing its removal`);let v=()=>this.client.snapshot.create({name:s,image:bh.base(h),resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{onLogs:y=>console.log(`[daytona] ${y}`)}),b=async()=>{await v(),console.log(`[daytona] Snapshot "${s}" ready (rebuilt here after a dead build).`)};if(u!==void 0){if(!g)throw new Error(`snapshot "${s}" is mid-build (state "${u}") and cannot be resized`);await this.joinInFlightSnapshotBuild(s)&&await b()}else try{await v(),console.log(`[daytona] Snapshot "${s}" ready (built here).`)}catch(y){if(!AAe(y)||l)throw y;await this.joinInFlightSnapshotBuild(s)&&await b()}c=await this.client.create({snapshot:s,...o},{timeout:600})}catch(v){if(v instanceof ST||v instanceof hy)throw v;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${v instanceof Error?v.message:v}`);try{c=await this.client.create({image:h,...o,resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{timeout:600,onSnapshotCreateLogs:b=>console.log(`[daytona] ${b}`)})}catch(b){throw UAe(h)?new xAe(h,b):b}}}return e.workingDirectory&&await c.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(c.id,n),new F8(c,n,this.managedStream)}async joinInFlightSnapshotBuild(e){let t=await PAe(this.client,e,this.snapshotConflictTiming);if(t===K8)return!0;if(t.state==="active")return console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(t.state==="inactive")return await V8(this.client,e,t),console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(hAe.has(t.state??"")&&q8(e)&&await mAe(this.client,e,t,this.snapshotDeleteTiming))return!0;throw new Error(`the in-flight build of snapshot "${e}" ended in state "${t.state??"unknown"}"`)}async connect(e,t){let n=await this.client.get(e);return n.state!=="started"&&await n.start(),new F8(n,this.sandboxUsers.get(e),this.managedStream)}async list(e){let t=await this.paginate(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.paginate(e);return n}async paginate(e){return GAe(this.listStream(e),e)}listStream(e){let t=e?.state?wNt(e.state):void 0,n={limit:IAe,...e?.metadata?{labels:e.metadata}:{},...t&&t.length>0?{states:t}:{}};return this.client.list(n)}};INt=GAe;xNt=H8,ENt=z8,TNt=dM,kNt=MAe,ONt=DAe,ANt=UAe,PNt=X8,RNt=BAe,CNt=V8,NNt=PAe,MNt=AAe,DNt=q8,UNt=W8,BNt=G8,FNt=RAe,LNt=Lb,VNt=J8,qNt=LAe,$Nt=VAe,zNt=qAe});var JAe=S(pM=>{"use strict";Object.defineProperty(pM,"__esModule",{value:!0});pM.Metadata=void 0;pM.Metadata=function(t){let n=new Map,r={set(a,i){if(a=Vb(a),Array.isArray(i))if(i.length===0)n.delete(a);else{for(let s of i)eW(a,s);n.set(a,a.endsWith("-bin")?i:[i.join(", ")])}else eW(a,i),n.set(a,[i]);return r},append(a,i){a=Vb(a),eW(a,i);let s=n.get(a);return s==null&&(s=[],n.set(a,s)),s.push(i),a.endsWith("-bin")||n.set(a,[s.join(", ")]),r},delete(a){a=Vb(a),n.delete(a)},get(a){var i;return a=Vb(a),(i=n.get(a))===null||i===void 0?void 0:i[0]},getAll(a){var i;return a=Vb(a),(i=n.get(a))!==null&&i!==void 0?i:[]},has(a){return a=Vb(a),n.has(a)},[Symbol.iterator](){return n[Symbol.iterator]()}};if(t!=null){let a=GNt(t)?t:Object.entries(t);for(let[i,s]of a)r.set(i,s)}return r};function Vb(e){return e.toLowerCase()}function eW(e,t){if(!/^[0-9a-z_.-]+$/.test(e))throw new Error(`Metadata key '${e}' contains illegal characters`);if(e.endsWith("-bin")){if(!(t instanceof Uint8Array))throw new Error(`Metadata key '${e}' ends with '-bin', thus it must have binary value`)}else{if(typeof t!="string")throw new Error(`Metadata key '${e}' doesn't end with '-bin', thus it must have string value`);if(!/^[ -~]*$/.test(t))throw new Error(`Metadata value '${t}' of key '${e}' contains illegal characters`)}}function GNt(e){return Symbol.iterator in e}});var hM=S(wT=>{"use strict";Object.defineProperty(wT,"__esModule",{value:!0});wT.Status=void 0;var JNt;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(JNt=wT.Status||(wT.Status={}))});var WAe=S(HAe=>{"use strict";Object.defineProperty(HAe,"__esModule",{value:!0})});var KAe=S(YAe=>{"use strict";Object.defineProperty(YAe,"__esModule",{value:!0})});var XAe=S(jAe=>{"use strict";Object.defineProperty(jAe,"__esModule",{value:!0})});var ZAe=S(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.composeClientMiddleware=void 0;function HNt(e,t){return(n,r)=>t(Object.assign(Object.assign({},n),{next:(a,i)=>e(Object.assign(Object.assign({},n),{request:a}),i)}),r)}mM.composeClientMiddleware=HNt});var tPe=S(Eh=>{"use strict";Eh.__esModule=void 0;Eh.__esModule=!0;var WNt=typeof Object.setPrototypeOf=="function",YNt=typeof Object.getPrototypeOf=="function",KNt=typeof Object.defineProperty=="function",jNt=typeof Object.create=="function",XNt=typeof Object.prototype.hasOwnProperty=="function",ZNt=function(t,n){WNt?Object.setPrototypeOf(t,n):t.__proto__=n};Eh.setPrototypeOf=ZNt;var QNt=function(t){return YNt?Object.getPrototypeOf(t):t.__proto__||t.prototype};Eh.getPrototypeOf=QNt;var QAe=!1,e1t=function e(t,n,r){if(KNt&&!QAe)try{Object.defineProperty(t,n,r)}catch{QAe=!0,e(t,n,r)}else t[n]=r.value};Eh.defineProperty=e1t;var ePe=function(t,n){return XNt?t.hasOwnProperty(t,n):t[n]===void 0};Eh.hasOwnProperty=ePe;var t1t=function(t,n){if(jNt)return Object.create(t,n);var r=function(){};r.prototype=t;var a=new r;if(typeof n>"u")return a;if(typeof n=="null")throw new Error("PropertyDescriptors must not be null.");if(typeof n=="object")for(var i in n)ePe(n,i)&&(a[i]=n[i].value);return a};Eh.objectCreate=t1t});var nW=S(qb=>{"use strict";qb.__esModule=void 0;qb.__esModule=!0;var yM=tPe(),n1t=yM.setPrototypeOf,r1t=yM.getPrototypeOf,tW=yM.defineProperty,i1t=yM.objectCreate,a1t=new Error().toString()==="[object Error]",gM="";function IT(e){var t=this.constructor,n=t.name||function(){var o=t.toString().match(/^function\s*([^\s(]+)/);return o===null?gM||"Error":o[1]}(),r=n==="Error",a=r?gM:n,i=Error.apply(this,arguments);if(n1t(i,r1t(this)),!(i instanceof t)||!(i instanceof IT)){var i=this;Error.apply(this,arguments),tW(i,"message",{configurable:!0,enumerable:!1,value:e,writable:!0})}if(tW(i,"name",{configurable:!0,enumerable:!1,value:a,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(i,r?IT:t),i.stack===void 0){var s=new Error(e);s.name=i.name,i.stack=s.stack}return a1t&&tW(i,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),i}gM=IT.name||"ExtendableError";IT.prototype=i1t(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}});qb.ExtendableError=IT;qb.default=qb.ExtendableError});var nPe=S(vM=>{"use strict";Object.defineProperty(vM,"__esModule",{value:!0});vM.ClientError=void 0;var s1t=nW(),o1t=hM(),rW=class e extends s1t.ExtendableError{constructor(t,n,r){super(`${t} ${o1t.Status[n]}: ${r}`),this.path=t,this.code=n,this.details=r,this.name="ClientError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ClientError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ClientError"]===!0||t.name==="ClientError"&&t["@@nice-grpc"]===!0)}};vM.ClientError=rW});var iPe=S(rPe=>{"use strict";Object.defineProperty(rPe,"__esModule",{value:!0})});var sPe=S(aPe=>{"use strict";Object.defineProperty(aPe,"__esModule",{value:!0})});var oPe=S(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0});bM.composeServerMiddleware=void 0;function c1t(e,t){return(n,r)=>e(Object.assign(Object.assign({},n),{next:(a,i)=>t(Object.assign(Object.assign({},n),{request:a}),i)}),r)}bM.composeServerMiddleware=c1t});var cPe=S(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0});SM.ServerError=void 0;var l1t=nW(),u1t=hM(),iW=class e extends l1t.ExtendableError{constructor(t,n){super(`${u1t.Status[t]}: ${n}`),this.code=t,this.details=n,this.name="ServerError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ServerError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ServerError"]===!0||t.name==="ServerError"&&t["@@nice-grpc"]===!0)}};SM.ServerError=iW});var Wc=S(qa=>{"use strict";var d1t=qa&&qa.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Jl=qa&&qa.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&d1t(t,e,n)};Object.defineProperty(qa,"__esModule",{value:!0});Jl(JAe(),qa);Jl(hM(),qa);Jl(WAe(),qa);Jl(KAe(),qa);Jl(XAe(),qa);Jl(ZAe(),qa);Jl(nPe(),qa);Jl(iPe(),qa);Jl(sPe(),qa);Jl(oPe(),qa);Jl(cPe(),qa)});var Kt=S(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=Yc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=Yc.Propagate=Yc.LogVerbosity=Yc.Status=void 0;var lPe;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(lPe||(Yc.Status=lPe={}));var uPe;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.NONE=3]="NONE"})(uPe||(Yc.LogVerbosity=uPe={}));var dPe;(function(e){e[e.DEADLINE=1]="DEADLINE",e[e.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",e[e.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",e[e.CANCELLATION=8]="CANCELLATION",e[e.DEFAULTS=65535]="DEFAULTS"})(dPe||(Yc.Propagate=dPe={}));Yc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;Yc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4*1024*1024});var aW=S((eSn,f1t)=>{f1t.exports={name:"@grpc/grpc-js",version:"1.14.3",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var hr=S(cc=>{"use strict";var sW,oW,cW,lW;Object.defineProperty(cc,"__esModule",{value:!0});cc.log=cc.setLoggerVerbosity=cc.setLogger=cc.getLogger=void 0;cc.trace=I1t;cc.isTracerEnabled=pPe;var Th=Kt(),p1t=require("process"),h1t=aW().version,m1t={error:(e,...t)=>{console.error("E "+e,...t)},info:(e,...t)=>{console.error("I "+e,...t)},debug:(e,...t)=>{console.error("D "+e,...t)}},my=m1t,$b=Th.LogVerbosity.ERROR,g1t=(oW=(sW=process.env.GRPC_NODE_VERBOSITY)!==null&&sW!==void 0?sW:process.env.GRPC_VERBOSITY)!==null&&oW!==void 0?oW:"";switch(g1t.toUpperCase()){case"DEBUG":$b=Th.LogVerbosity.DEBUG;break;case"INFO":$b=Th.LogVerbosity.INFO;break;case"ERROR":$b=Th.LogVerbosity.ERROR;break;case"NONE":$b=Th.LogVerbosity.NONE;break;default:}var y1t=()=>my;cc.getLogger=y1t;var v1t=e=>{my=e};cc.setLogger=v1t;var b1t=e=>{$b=e};cc.setLoggerVerbosity=b1t;var S1t=(e,...t)=>{let n;if(e>=$b){switch(e){case Th.LogVerbosity.DEBUG:n=my.debug;break;case Th.LogVerbosity.INFO:n=my.info;break;case Th.LogVerbosity.ERROR:n=my.error;break}n||(n=my.error),n&&n.bind(my)(...t)}};cc.log=S1t;var _1t=(lW=(cW=process.env.GRPC_NODE_TRACE)!==null&&cW!==void 0?cW:process.env.GRPC_TRACE)!==null&&lW!==void 0?lW:"",uW=new Set,fPe=new Set;for(let e of _1t.split(","))e.startsWith("-")?fPe.add(e.substring(1)):uW.add(e);var w1t=uW.has("all");function I1t(e,t,n){pPe(t)&&(0,cc.log)(e,new Date().toISOString()+" | v"+h1t+" "+p1t.pid+" | "+t+" | "+n)}function pPe(e){return!fPe.has(e)&&(w1t||uW.has(e))}});var wM=S(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0});_M.getErrorMessage=x1t;_M.getErrorCode=E1t;function x1t(e){return e instanceof Error?e.message:String(e)}function E1t(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"?e.code:null}});var ma=S(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.Metadata=void 0;var T1t=hr(),k1t=Kt(),O1t=wM(),A1t=/^[:0-9a-z_.-]+$/,P1t=/^[ -~]*$/;function R1t(e){return A1t.test(e)}function C1t(e){return P1t.test(e)}function mPe(e){return e.endsWith("-bin")}function N1t(e){return!e.startsWith("grpc-")}function IM(e){return e.toLowerCase()}function hPe(e,t){if(!R1t(e))throw new Error('Metadata key "'+e+'" contains illegal characters');if(t!=null)if(mPe(e)){if(!Buffer.isBuffer(t))throw new Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(t))throw new Error("keys that don't end with '-bin' must have String values");if(!C1t(t))throw new Error('Metadata string value "'+t+'" contains illegal characters')}}var dW=class e{constructor(t={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=t}set(t,n){t=IM(t),hPe(t,n),this.internalRepr.set(t,[n])}add(t,n){t=IM(t),hPe(t,n);let r=this.internalRepr.get(t);r===void 0?this.internalRepr.set(t,[n]):r.push(n)}remove(t){t=IM(t),this.internalRepr.delete(t)}get(t){return t=IM(t),this.internalRepr.get(t)||[]}getMap(){let t={};for(let[n,r]of this.internalRepr)if(r.length>0){let a=r[0];t[n]=Buffer.isBuffer(a)?Buffer.from(a):a}return t}clone(){let t=new e(this.options),n=t.internalRepr;for(let[r,a]of this.internalRepr){let i=a.map(s=>Buffer.isBuffer(s)?Buffer.from(s):s);n.set(r,i)}return t}merge(t){for(let[n,r]of t.internalRepr){let a=(this.internalRepr.get(n)||[]).concat(r);this.internalRepr.set(n,a)}}setOptions(t){this.options=t}getOptions(){return this.options}toHttp2Headers(){let t={};for(let[n,r]of this.internalRepr)n.startsWith(":")||(t[n]=r.map(M1t));return t}toJSON(){let t={};for(let[n,r]of this.internalRepr)t[n]=r;return t}setOpaque(t,n){this.opaqueData.set(t,n)}getOpaque(t){return this.opaqueData.get(t)}static fromHttp2Headers(t){let n=new e;for(let r of Object.keys(t)){if(r.charAt(0)===":")continue;let a=t[r];try{mPe(r)?Array.isArray(a)?a.forEach(i=>{n.add(r,Buffer.from(i,"base64"))}):a!==void 0&&(N1t(r)?a.split(",").forEach(i=>{n.add(r,Buffer.from(i.trim(),"base64"))}):n.add(r,Buffer.from(a,"base64"))):Array.isArray(a)?a.forEach(i=>{n.add(r,i)}):a!==void 0&&n.add(r,a)}catch(i){let s=`Failed to add metadata entry ${r}: ${a}. ${(0,O1t.getErrorMessage)(i)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,T1t.log)(k1t.LogVerbosity.ERROR,s)}}return n}};xM.Metadata=dW;var M1t=e=>Buffer.isBuffer(e)?e.toString("base64"):e});var TM=S(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0});EM.CallCredentials=void 0;var mW=ma();function D1t(e){return"getRequestHeaders"in e&&typeof e.getRequestHeaders=="function"}var zb=class e{static createFromMetadataGenerator(t){return new pW(t)}static createFromGoogleCredential(t){return e.createFromMetadataGenerator((n,r)=>{let a;D1t(t)?a=t.getRequestHeaders(n.service_url):a=new Promise((i,s)=>{t.getRequestMetadata(n.service_url,(o,c)=>{if(o){s(o);return}if(!c){s(new Error("Headers not set by metadata plugin"));return}i(c)})}),a.then(i=>{let s=new mW.Metadata;for(let o of Object.keys(i))s.add(o,i[o]);r(null,s)},i=>{r(i)})})}static createEmpty(){return new hW}};EM.CallCredentials=zb;var fW=class e extends zb{constructor(t){super(),this.creds=t}async generateMetadata(t){let n=new mW.Metadata,r=await Promise.all(this.creds.map(a=>a.generateMetadata(t)));for(let a of r)n.merge(a);return n}compose(t){return new e(this.creds.concat([t]))}_equals(t){return this===t?!0:t instanceof e?this.creds.every((n,r)=>n._equals(t.creds[r])):!1}},pW=class e extends zb{constructor(t){super(),this.metadataGenerator=t}generateMetadata(t){return new Promise((n,r)=>{this.metadataGenerator(t,(a,i)=>{i!==void 0?n(i):r(a)})})}compose(t){return new fW([this,t])}_equals(t){return this===t?!0:t instanceof e?this.metadataGenerator===t.metadataGenerator:!1}},hW=class e extends zb{generateMetadata(t){return Promise.resolve(new mW.Metadata)}compose(t){return t}_equals(t){return t instanceof e}}});var yW=S(xT=>{"use strict";Object.defineProperty(xT,"__esModule",{value:!0});xT.CIPHER_SUITES=void 0;xT.getDefaultRootsData=B1t;var U1t=require("fs");xT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var gPe=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,gW=null;function B1t(){return gPe?(gW===null&&(gW=U1t.readFileSync(gPe)),gW):null}});var eo=S(Gb=>{"use strict";Object.defineProperty(Gb,"__esModule",{value:!0});Gb.parseUri=L1t;Gb.splitHostPort=V1t;Gb.combineHostPort=q1t;Gb.uriToString=$1t;var F1t=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function L1t(e){let t=F1t.exec(e);return t===null?null:{scheme:t[1],authority:t[2],path:t[3]}}var yPe=/^\d+$/;function V1t(e){if(e.startsWith("[")){let t=e.indexOf("]");if(t===-1)return null;let n=e.substring(1,t);if(n.indexOf(":")===-1)return null;if(e.length>t+1)if(e[t+1]===":"){let r=e.substring(t+2);return yPe.test(r)?{host:n,port:+r}:null}else return null;else return{host:n}}else{let t=e.split(":");return t.length===2?yPe.test(t[1])?{host:t[0],port:+t[1]}:null:{host:e}}}function q1t(e){return e.port===void 0?e.host:e.host.includes(":")?`[${e.host}]:${e.port}`:`${e.host}:${e.port}`}function $1t(e){let t="";return e.scheme!==void 0&&(t+=e.scheme+":"),e.authority!==void 0&&(t+="//"+e.authority+"/"),t+=e.path,t}});var Hl=S(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});ip.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;ip.registerResolver=z1t;ip.registerDefaultScheme=G1t;ip.createResolver=J1t;ip.getDefaultAuthority=H1t;ip.mapUriDefaultScheme=W1t;var bW=eo();ip.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var Jb={},vW=null;function z1t(e,t){Jb[e]=t}function G1t(e){vW=e}function J1t(e,t,n){if(e.scheme!==void 0&&e.scheme in Jb)return new Jb[e.scheme](e,t,n);throw new Error(`No resolver could be created for target ${(0,bW.uriToString)(e)}`)}function H1t(e){if(e.scheme!==void 0&&e.scheme in Jb)return Jb[e.scheme].getDefaultAuthority(e);throw new Error(`Invalid target ${(0,bW.uriToString)(e)}`)}function W1t(e){return e.scheme===void 0||!(e.scheme in Jb)?vW!==null?{scheme:vW,authority:void 0,path:(0,bW.uriToString)(e)}:null:e}});var Hb=S(TT=>{"use strict";Object.defineProperty(TT,"__esModule",{value:!0});TT.ChannelCredentials=void 0;TT.createCertificateProviderChannelCredentials=X1t;var ET=require("tls"),AM=TM(),_W=yW(),vPe=eo(),Y1t=Hl(),K1t=hr(),j1t=Kt();function SW(e,t){if(e&&!(e instanceof Buffer))throw new TypeError(`${t}, if provided, must be a Buffer.`)}var gy=class{compose(t){return new xW(this,t)}static createSsl(t,n,r,a){var i;if(SW(t,"Root certificate"),SW(n,"Private key"),SW(r,"Certificate chain"),n&&!r)throw new Error("Private key must be given with accompanying certificate chain");if(!n&&r)throw new Error("Certificate chain must be given with accompanying private key");let s=(0,ET.createSecureContext)({ca:(i=t??(0,_W.getDefaultRootsData)())!==null&&i!==void 0?i:void 0,key:n??void 0,cert:r??void 0,ciphers:_W.CIPHER_SUITES});return new kM(s,a??{})}static createFromSecureContext(t,n){return new kM(t,n??{})}static createInsecure(){return new wW}};TT.ChannelCredentials=gy;var wW=class e extends gy{constructor(){super()}compose(t){throw new Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals(t){return t instanceof e}_createSecureConnector(t,n,r){return{connect(a){return Promise.resolve({socket:a,secure:!1})},waitForReady:()=>Promise.resolve(),getCallCredentials:()=>r??AM.CallCredentials.createEmpty(),destroy(){}}}};function bPe(e,t,n,r){var a,i;let s={secureContext:e},o=n;if("grpc.http_connect_target"in r){let d=(0,vPe.parseUri)(r["grpc.http_connect_target"]);d&&(o=d)}let c=(0,Y1t.getDefaultAuthority)(o),l=(0,vPe.splitHostPort)(c),u=(a=l?.host)!==null&&a!==void 0?a:c;if(s.host=u,t.checkServerIdentity&&(s.checkServerIdentity=t.checkServerIdentity),t.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=t.rejectUnauthorized),s.ALPNProtocols=["h2"],r["grpc.ssl_target_name_override"]){let d=r["grpc.ssl_target_name_override"],f=(i=s.checkServerIdentity)!==null&&i!==void 0?i:ET.checkServerIdentity;s.checkServerIdentity=(h,g)=>f(d,g),s.servername=d}else s.servername=u;return r["grpc-node.tls_enable_trace"]&&(s.enableTrace=!0),s}var IW=class{constructor(t,n){this.connectionOptions=t,this.callCredentials=n}connect(t){let n=Object.assign({socket:t},this.connectionOptions);return new Promise((r,a)=>{let i=(0,ET.connect)(n,()=>{var s;if((!((s=this.connectionOptions.rejectUnauthorized)!==null&&s!==void 0)||s)&&!i.authorized){a(i.authorizationError);return}r({socket:i,secure:!0})});i.on("error",s=>{a(s)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}},kM=class e extends gy{constructor(t,n){super(),this.secureContext=t,this.verifyOptions=n}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.secureContext===t.secureContext&&this.verifyOptions.checkServerIdentity===t.verifyOptions.checkServerIdentity:!1}_createSecureConnector(t,n,r){let a=bPe(this.secureContext,this.verifyOptions,t,n);return new IW(a,r??AM.CallCredentials.createEmpty())}},OM=class e extends gy{constructor(t,n,r){super(),this.caCertificateProvider=t,this.identityCertificateProvider=n,this.verifyOptions=r,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals(t){var n,r;return this===t?!0:t instanceof e?this.caCertificateProvider===t.caCertificateProvider&&this.identityCertificateProvider===t.identityCertificateProvider&&((n=this.verifyOptions)===null||n===void 0?void 0:n.checkServerIdentity)===((r=t.verifyOptions)===null||r===void 0?void 0:r.checkServerIdentity):!1}ref(){var t;this.refcount===0&&(this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.addIdentityCertificateListener(this.identityCertificateUpdateListener)),this.refcount+=1}unref(){var t;this.refcount-=1,this.refcount===0&&(this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.removeIdentityCertificateListener(this.identityCertificateUpdateListener))}_createSecureConnector(t,n,r){return this.ref(),new e.SecureConnectorImpl(this,t,n,r??AM.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let t of this.secureContextWatchers)t(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate(t){this.latestCaUpdate=t,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate(t){this.latestIdentityUpdate=t,this.maybeUpdateWatchers()}hasReceivedUpdates(){return!(this.latestCaUpdate===void 0||this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)}getSecureContext(){return this.hasReceivedUpdates()?Promise.resolve(this.getLatestSecureContext()):new Promise(t=>{this.secureContextWatchers.push(t)})}getLatestSecureContext(){var t,n;if(!this.latestCaUpdate||this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,ET.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:(t=this.latestIdentityUpdate)===null||t===void 0?void 0:t.privateKey,cert:(n=this.latestIdentityUpdate)===null||n===void 0?void 0:n.certificate,ciphers:_W.CIPHER_SUITES})}catch(r){return(0,K1t.log)(j1t.LogVerbosity.ERROR,"Failed to createSecureContext with error "+r.message),null}}};OM.SecureConnectorImpl=class{constructor(e,t,n,r){this.parent=e,this.channelTarget=t,this.options=n,this.callCredentials=r}connect(e){return new Promise((t,n)=>{let r=this.parent.getLatestSecureContext();if(!r){n(new Error("Failed to load credentials"));return}e.closed&&n(new Error("Socket closed while loading credentials"));let a=bPe(r,this.parent.verifyOptions,this.channelTarget,this.options),i=Object.assign({socket:e},a),s=()=>{n(new Error("Socket closed"))},o=l=>{n(l)},c=(0,ET.connect)(i,()=>{var l;if(c.removeListener("close",s),c.removeListener("error",o),(!((l=this.parent.verifyOptions.rejectUnauthorized)!==null&&l!==void 0)||l)&&!c.authorized){n(c.authorizationError);return}t({socket:c,secure:!0})});c.once("close",s),c.once("error",o)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function X1t(e,t,n){return new OM(e,t,n??{})}var xW=class e extends gy{constructor(t,n){if(super(),this.channelCredentials=t,this.callCredentials=n,!t._isSecure())throw new Error("Cannot compose insecure credentials")}compose(t){let n=this.callCredentials.compose(t);return new e(this.channelCredentials,n)}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.channelCredentials._equals(t.channelCredentials)&&this.callCredentials._equals(t.callCredentials):!1}_createSecureConnector(t,n,r){let a=this.callCredentials.compose(r??AM.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector(t,n,a)}}});var Oh=S(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});bd.createChildChannelControlHelper=e2t;bd.registerLoadBalancerType=t2t;bd.registerDefaultLoadBalancerType=n2t;bd.createLoadBalancer=r2t;bd.isLoadBalancerNameRegistered=i2t;bd.parseLoadBalancingConfig=SPe;bd.getDefaultConfig=a2t;bd.selectLbConfigFromList=s2t;var Z1t=hr(),Q1t=Kt();function e2t(e,t){var n,r,a,i,s,o,c,l,u,d;return{createSubchannel:(r=(n=t.createSubchannel)===null||n===void 0?void 0:n.bind(t))!==null&&r!==void 0?r:e.createSubchannel.bind(e),updateState:(i=(a=t.updateState)===null||a===void 0?void 0:a.bind(t))!==null&&i!==void 0?i:e.updateState.bind(e),requestReresolution:(o=(s=t.requestReresolution)===null||s===void 0?void 0:s.bind(t))!==null&&o!==void 0?o:e.requestReresolution.bind(e),addChannelzChild:(l=(c=t.addChannelzChild)===null||c===void 0?void 0:c.bind(t))!==null&&l!==void 0?l:e.addChannelzChild.bind(e),removeChannelzChild:(d=(u=t.removeChannelzChild)===null||u===void 0?void 0:u.bind(t))!==null&&d!==void 0?d:e.removeChannelzChild.bind(e)}}var kh={},kT=null;function t2t(e,t,n){kh[e]={LoadBalancer:t,LoadBalancingConfig:n}}function n2t(e){kT=e}function r2t(e,t){let n=e.getLoadBalancerName();return n in kh?new kh[n].LoadBalancer(t):null}function i2t(e){return e in kh}function SPe(e){let t=Object.keys(e);if(t.length!==1)throw new Error("Provided load balancing config has multiple conflicting entries");let n=t[0];if(n in kh)try{return kh[n].LoadBalancingConfig.createFromJson(e[n])}catch(r){throw new Error(`${n}: ${r.message}`)}else throw new Error(`Unrecognized load balancing config name ${n}`)}function a2t(){if(!kT)throw new Error("No default load balancer type registered");return new kh[kT].LoadBalancingConfig}function s2t(e,t=!1){for(let n of e)try{return SPe(n)}catch(r){(0,Z1t.log)(Q1t.LogVerbosity.DEBUG,"Config parsing failed with error",r.message);continue}return t&&kT?new kh[kT].LoadBalancingConfig:null}});var EW=S(OT=>{"use strict";Object.defineProperty(OT,"__esModule",{value:!0});OT.validateRetryThrottling=_Pe;OT.validateServiceConfig=wPe;OT.extractAndSelectServiceConfig=g2t;var o2t=require("os"),PM=Kt(),RM=/^\d+(\.\d{1,9})?s$/,c2t="node";function l2t(e){if("service"in e&&e.service!==""){if(typeof e.service!="string")throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof e.service}`);if("method"in e&&e.method!==""){if(typeof e.method!="string")throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof e.service}`);return{service:e.service,method:e.method}}else return{service:e.service}}else{if("method"in e&&e.method!==void 0)throw new Error("Invalid method config name: method set with empty or unset service");return{}}}function u2t(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in e)||typeof e.initialBackoff!="string"||!RM.test(e.initialBackoff))throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in e)||typeof e.maxBackoff!="string"||!RM.test(e.maxBackoff))throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in e)||typeof e.backoffMultiplier!="number"||e.backoffMultiplier<=0)throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!("retryableStatusCodes"in e&&Array.isArray(e.retryableStatusCodes)))throw new Error("Invalid method config retry policy: retryableStatusCodes is required");if(e.retryableStatusCodes.length===0)throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let t of e.retryableStatusCodes)if(typeof t=="number"){if(!Object.values(PM.Status).includes(t))throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof t=="string"){if(!Object.values(PM.Status).includes(t.toUpperCase()))throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:e.maxAttempts,initialBackoff:e.initialBackoff,maxBackoff:e.maxBackoff,backoffMultiplier:e.backoffMultiplier,retryableStatusCodes:e.retryableStatusCodes}}function d2t(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in e&&(typeof e.hedgingDelay!="string"||!RM.test(e.hedgingDelay)))throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in e&&Array.isArray(e.nonFatalStatusCodes))for(let n of e.nonFatalStatusCodes)if(typeof n=="number"){if(!Object.values(PM.Status).includes(n))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof n=="string"){if(!Object.values(PM.Status).includes(n.toUpperCase()))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let t={maxAttempts:e.maxAttempts};return e.hedgingDelay&&(t.hedgingDelay=e.hedgingDelay),e.nonFatalStatusCodes&&(t.nonFatalStatusCodes=e.nonFatalStatusCodes),t}function f2t(e){var t;let n={name:[]};if(!("name"in e)||!Array.isArray(e.name))throw new Error("Invalid method config: invalid name array");for(let r of e.name)n.name.push(l2t(r));if("waitForReady"in e){if(typeof e.waitForReady!="boolean")throw new Error("Invalid method config: invalid waitForReady");n.waitForReady=e.waitForReady}if("timeout"in e)if(typeof e.timeout=="object"){if(!("seconds"in e.timeout)||typeof e.timeout.seconds!="number")throw new Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in e.timeout)||typeof e.timeout.nanos!="number")throw new Error("Invalid method config: invalid timeout.nanos");n.timeout=e.timeout}else if(typeof e.timeout=="string"&&RM.test(e.timeout)){let r=e.timeout.substring(0,e.timeout.length-1).split(".");n.timeout={seconds:r[0]|0,nanos:((t=r[1])!==null&&t!==void 0?t:0)|0}}else throw new Error("Invalid method config: invalid timeout");if("maxRequestBytes"in e){if(typeof e.maxRequestBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxRequestBytes=e.maxRequestBytes}if("maxResponseBytes"in e){if(typeof e.maxResponseBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxResponseBytes=e.maxResponseBytes}if("retryPolicy"in e){if("hedgingPolicy"in e)throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");n.retryPolicy=u2t(e.retryPolicy)}else"hedgingPolicy"in e&&(n.hedgingPolicy=d2t(e.hedgingPolicy));return n}function _Pe(e){if(!("maxTokens"in e)||typeof e.maxTokens!="number"||e.maxTokens<=0||e.maxTokens>1e3)throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in e)||typeof e.tokenRatio!="number"||e.tokenRatio<=0)throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+e.maxTokens.toFixed(3),tokenRatio:+e.tokenRatio.toFixed(3)}}function p2t(e){if(!(typeof e=="object"&&e!==null))throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof e}`);let t=Object.keys(e);if(t.length>1)throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${t}`);if(t.length===0)throw new Error("Invalid loadBalancingConfig: load balancing policy name required");return{[t[0]]:e[t[0]]}}function wPe(e){let t={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in e)if(typeof e.loadBalancingPolicy=="string")t.loadBalancingPolicy=e.loadBalancingPolicy;else throw new Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in e)if(Array.isArray(e.loadBalancingConfig))for(let r of e.loadBalancingConfig)t.loadBalancingConfig.push(p2t(r));else throw new Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in e&&Array.isArray(e.methodConfig))for(let r of e.methodConfig)t.methodConfig.push(f2t(r));"retryThrottling"in e&&(t.retryThrottling=_Pe(e.retryThrottling));let n=[];for(let r of t.methodConfig)for(let a of r.name){for(let i of n)if(a.service===i.service&&a.method===i.method)throw new Error(`Invalid service config: duplicate name ${a.service}/${a.method}`);n.push(a)}return t}function h2t(e){if(!("serviceConfig"in e))throw new Error("Invalid service config choice: missing service config");let t={serviceConfig:wPe(e.serviceConfig)};if("clientLanguage"in e)if(Array.isArray(e.clientLanguage)){t.clientLanguage=[];for(let r of e.clientLanguage)if(typeof r=="string")t.clientLanguage.push(r);else throw new Error("Invalid service config choice: invalid clientLanguage")}else throw new Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in e)if(Array.isArray(e.clientHostname)){t.clientHostname=[];for(let r of e.clientHostname)if(typeof r=="string")t.clientHostname.push(r);else throw new Error("Invalid service config choice: invalid clientHostname")}else throw new Error("Invalid service config choice: invalid clientHostname");if("percentage"in e)if(typeof e.percentage=="number"&&0<=e.percentage&&e.percentage<=100)t.percentage=e.percentage;else throw new Error("Invalid service config choice: invalid percentage");let n=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let r in e)if(!n.includes(r))throw new Error(`Invalid service config choice: unexpected field ${r}`);return t}function m2t(e,t){if(!Array.isArray(e))throw new Error("Invalid service config list");for(let n of e){let r=h2t(n);if(!(typeof r.percentage=="number"&&t>r.percentage)){if(Array.isArray(r.clientHostname)){let a=!1;for(let i of r.clientHostname)i===o2t.hostname()&&(a=!0);if(!a)continue}if(Array.isArray(r.clientLanguage)){let a=!1;for(let i of r.clientLanguage)i===c2t&&(a=!0);if(!a)continue}return r.serviceConfig}}throw new Error("No matching service config found")}function g2t(e,t){for(let n of e)if(n.length>0&&n[0].startsWith("grpc_config=")){let r=n.join("").substring(12),a=JSON.parse(r);return m2t(a,t)}return null}});var to=S(CM=>{"use strict";Object.defineProperty(CM,"__esModule",{value:!0});CM.ConnectivityState=void 0;var IPe;(function(e){e[e.IDLE=0]="IDLE",e[e.CONNECTING=1]="CONNECTING",e[e.READY=2]="READY",e[e.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",e[e.SHUTDOWN=4]="SHUTDOWN"})(IPe||(CM.ConnectivityState=IPe={}))});var ap=S(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});Ah.QueuePicker=Ah.UnavailablePicker=Ah.PickResultType=void 0;var y2t=ma(),v2t=Kt(),NM;(function(e){e[e.COMPLETE=0]="COMPLETE",e[e.QUEUE=1]="QUEUE",e[e.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",e[e.DROP=3]="DROP"})(NM||(Ah.PickResultType=NM={}));var TW=class{constructor(t){this.status=Object.assign({code:v2t.Status.UNAVAILABLE,details:"No connection established",metadata:new y2t.Metadata},t)}pick(t){return{pickResultType:NM.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}};Ah.UnavailablePicker=TW;var kW=class{constructor(t,n){this.loadBalancer=t,this.childPicker=n,this.calledExitIdle=!1}pick(t){return this.calledExitIdle||(process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0),this.childPicker?this.childPicker.pick(t):{pickResultType:NM.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}};Ah.QueuePicker=kW});var Wb=S(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0});DM.BackoffTimeout=void 0;var b2t=Kt(),S2t=hr(),_2t="backoff",w2t=1e3,I2t=1.6,x2t=12e4,E2t=.2;function T2t(e,t){return Math.random()*(t-e)+e}var MM=class e{constructor(t,n){this.callback=t,this.initialDelay=w2t,this.multiplier=I2t,this.maxDelay=x2t,this.jitter=E2t,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=e.getNextId(),n&&(n.initialDelay&&(this.initialDelay=n.initialDelay),n.multiplier&&(this.multiplier=n.multiplier),n.jitter&&(this.jitter=n.jitter),n.maxDelay&&(this.maxDelay=n.maxDelay)),this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace(t){S2t.trace(b2t.LogVerbosity.DEBUG,_2t,"{"+this.id+"} "+t)}runTimer(t){var n,r;this.trace("runTimer(delay="+t+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+t),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},t),this.hasRef||(r=(n=this.timerId).unref)===null||r===void 0||r.call(n)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let t=Math.min(this.nextDelay*this.multiplier,this.maxDelay),n=t*this.jitter;this.nextDelay=t+T2t(-n,n)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let t=new Date,n=this.startTime;n.setMilliseconds(n.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),t<n?this.runTimer(n.getTime()-t.getTime()):this.running=!1}}isRunning(){return this.running}ref(){var t,n;this.hasRef=!0,(n=(t=this.timerId).ref)===null||n===void 0||n.call(t)}unref(){var t,n;this.hasRef=!1,(n=(t=this.timerId).unref)===null||n===void 0||n.call(t)}getEndTime(){return this.endTime}};DM.BackoffTimeout=MM;MM.nextId=0});var BM=S(UM=>{"use strict";Object.defineProperty(UM,"__esModule",{value:!0});UM.ChildLoadBalancerHandler=void 0;var k2t=Oh(),O2t=to(),A2t="child_load_balancer_helper",OW=class{constructor(t){this.channelControlHelper=t,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(n){this.parent=n,this.child=null}createSubchannel(n,r){return this.parent.channelControlHelper.createSubchannel(n,r)}updateState(n,r,a){var i;if(this.calledByPendingChild()){if(n===O2t.ConnectivityState.CONNECTING)return;(i=this.parent.currentChild)===null||i===void 0||i.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(n,r,a)}requestReresolution(){var n;let r=(n=this.parent.pendingChild)!==null&&n!==void 0?n:this.parent.currentChild;this.child===r&&this.parent.channelControlHelper.requestReresolution()}setChild(n){this.child=n}addChannelzChild(n){this.parent.channelControlHelper.addChannelzChild(n)}removeChannelzChild(n){this.parent.channelControlHelper.removeChannelzChild(n)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance(t,n){return t.getLoadBalancerName()!==n.getLoadBalancerName()}updateAddressList(t,n,r,a){let i;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,n)){let s=new this.ChildPolicyHelper(this),o=(0,k2t.createLoadBalancer)(n,s);s.setChild(o),this.currentChild===null?(this.currentChild=o,i=this.currentChild):(this.pendingChild&&this.pendingChild.destroy(),this.pendingChild=o,i=this.pendingChild)}else this.pendingChild===null?i=this.currentChild:i=this.pendingChild;return this.latestConfig=n,i.updateAddressList(t,n,r,a)}exitIdle(){this.currentChild&&(this.currentChild.exitIdle(),this.pendingChild&&this.pendingChild.exitIdle())}resetBackoff(){this.currentChild&&(this.currentChild.resetBackoff(),this.pendingChild&&this.pendingChild.resetBackoff())}destroy(){this.currentChild&&(this.currentChild.destroy(),this.currentChild=null),this.pendingChild&&(this.pendingChild.destroy(),this.pendingChild=null)}getTypeName(){return A2t}};UM.ChildLoadBalancerHandler=OW});var TPe=S(FM=>{"use strict";Object.defineProperty(FM,"__esModule",{value:!0});FM.ResolvingLoadBalancer=void 0;var P2t=Oh(),R2t=EW(),Oo=to(),xPe=Hl(),AT=ap(),C2t=Wb(),AW=Kt(),N2t=ma(),M2t=hr(),D2t=Kt(),U2t=eo(),B2t=BM(),F2t="resolving_load_balancer";function EPe(e){M2t.trace(D2t.LogVerbosity.DEBUG,F2t,e)}var L2t=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function V2t(e,t,n,r){for(let a of n.name)switch(r){case"EMPTY":if(!a.service&&!a.method)return!0;break;case"SERVICE":if(a.service===e&&!a.method)return!0;break;case"SERVICE_AND_METHOD":if(a.service===e&&a.method===t)return!0}return!1}function q2t(e,t,n,r){for(let a of n)if(V2t(e,t,a,r))return a;return null}function $2t(e){return{invoke(t,n){var r,a;let i=t.split("/").filter(c=>c.length>0),s=(r=i[0])!==null&&r!==void 0?r:"",o=(a=i[1])!==null&&a!==void 0?a:"";if(e&&e.methodConfig)for(let c of L2t){let l=q2t(s,o,e.methodConfig,c);if(l)return{methodConfig:l,pickInformation:{},status:AW.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:AW.Status.OK,dynamicFilterFactories:[]}},unref(){}}}var PW=class{constructor(t,n,r,a,i){this.target=t,this.channelControlHelper=n,this.channelOptions=r,this.onSuccessfulResolution=a,this.onFailedResolution=i,this.latestChildState=Oo.ConnectivityState.IDLE,this.latestChildPicker=new AT.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=Oo.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,r["grpc.service_config"]?this.defaultServiceConfig=(0,R2t.validateServiceConfig)(JSON.parse(r["grpc.service_config"])):this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]},this.updateState(Oo.ConnectivityState.IDLE,new AT.QueuePicker(this),null),this.childLoadBalancer=new B2t.ChildLoadBalancerHandler({createSubchannel:n.createSubchannel.bind(n),requestReresolution:()=>{this.backoffTimeout.isRunning()?(EPe("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0):this.updateResolution()},updateState:(o,c,l)=>{this.latestChildState=o,this.latestChildPicker=c,this.latestChildErrorMessage=l,this.updateState(o,c,l)},addChannelzChild:n.addChannelzChild.bind(n),removeChannelzChild:n.removeChannelzChild.bind(n)}),this.innerResolver=(0,xPe.createResolver)(t,this.handleResolverResult.bind(this),r);let s={initialDelay:r["grpc.initial_reconnect_backoff_ms"],maxDelay:r["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new C2t.BackoffTimeout(()=>{this.continueResolving?(this.updateResolution(),this.continueResolving=!1):this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},s),this.backoffTimeout.unref()}handleResolverResult(t,n,r,a){var i,s;this.backoffTimeout.stop(),this.backoffTimeout.reset();let o=!0,c=null;if(r===null?c=this.defaultServiceConfig:r.ok?c=r.value:this.previousServiceConfig!==null?c=this.previousServiceConfig:(o=!1,this.handleResolutionFailure(r.error)),c!==null){let l=(i=c?.loadBalancingConfig)!==null&&i!==void 0?i:[],u=(0,P2t.selectLbConfigFromList)(l,!0);u===null?(o=!1,this.handleResolutionFailure({code:AW.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new N2t.Metadata})):o=this.childLoadBalancer.updateAddressList(t,u,Object.assign(Object.assign({},this.channelOptions),n),a)}return o&&this.onSuccessfulResolution(c,(s=n[xPe.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&s!==void 0?s:$2t(c)),o}updateResolution(){this.innerResolver.updateResolution(),this.currentState===Oo.ConnectivityState.IDLE&&this.updateState(Oo.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage),this.backoffTimeout.runOnce()}updateState(t,n,r){EPe((0,U2t.uriToString)(this.target)+" "+Oo.ConnectivityState[this.currentState]+" -> "+Oo.ConnectivityState[t]),t===Oo.ConnectivityState.IDLE&&(n=new AT.QueuePicker(this,n)),this.currentState=t,this.channelControlHelper.updateState(t,n,r)}handleResolutionFailure(t){this.latestChildState===Oo.ConnectivityState.IDLE&&(this.updateState(Oo.ConnectivityState.TRANSIENT_FAILURE,new AT.UnavailablePicker(t),t.details),this.onFailedResolution(t))}exitIdle(){(this.currentState===Oo.ConnectivityState.IDLE||this.currentState===Oo.ConnectivityState.TRANSIENT_FAILURE)&&(this.backoffTimeout.isRunning()?this.continueResolving=!0:this.updateResolution()),this.childLoadBalancer.exitIdle()}updateAddressList(t,n){throw new Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=Oo.ConnectivityState.IDLE,this.latestChildPicker=new AT.QueuePicker(this),this.currentState=Oo.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}};FM.ResolvingLoadBalancer=PW});var kPe=S(PT=>{"use strict";Object.defineProperty(PT,"__esModule",{value:!0});PT.recognizedOptions=void 0;PT.channelOptionsEqual=z2t;PT.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function z2t(e,t){let n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let a=0;a<n.length;a+=1)if(n[a]!==r[a]||e[n[a]]!==t[r[a]])return!1;return!0}});var Ao=S(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});Wl.EndpointMap=void 0;Wl.isTcpSubchannelAddress=CT;Wl.subchannelAddressEqual=LM;Wl.subchannelAddressToString=APe;Wl.stringToSubchannelAddress=J2t;Wl.endpointEqual=H2t;Wl.endpointToString=W2t;Wl.endpointHasAddress=PPe;var OPe=require("net");function CT(e){return"port"in e}function LM(e,t){return!e&&!t?!0:!e||!t?!1:CT(e)?CT(t)&&e.host===t.host&&e.port===t.port:!CT(t)&&e.path===t.path}function APe(e){return CT(e)?(0,OPe.isIPv6)(e.host)?"["+e.host+"]:"+e.port:e.host+":"+e.port:e.path}var G2t=443;function J2t(e,t){return(0,OPe.isIP)(e)?{host:e,port:t??G2t}:{path:e}}function H2t(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n=0;n<e.addresses.length;n++)if(!LM(e.addresses[n],t.addresses[n]))return!1;return!0}function W2t(e){return"["+e.addresses.map(APe).join(", ")+"]"}function PPe(e,t){for(let n of e.addresses)if(LM(n,t))return!0;return!1}function RT(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n of e.addresses){let r=!1;for(let a of t.addresses)if(LM(n,a)){r=!0;break}if(!r)return!1}return!0}var RW=class{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress(t){for(let n of this.map)if(PPe(n.key,t))return n.value}deleteMissing(t){let n=[];for(let r of this.map){let a=!1;for(let i of t)RT(i,r.key)&&(a=!0);a||(n.push(r.value),this.map.delete(r))}return n}get(t){for(let n of this.map)if(RT(t,n.key))return n.value}set(t,n){for(let r of this.map)if(RT(t,r.key)){r.value=n;return}this.map.add({key:t,value:n})}delete(t){for(let n of this.map)if(RT(t,n.key)){this.map.delete(n);return}}has(t){for(let n of this.map)if(RT(t,n.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let t of this.map)yield t.key}*values(){for(let t of this.map)yield t.value}*entries(){for(let t of this.map)yield[t.key,t.value]}};Wl.EndpointMap=RW});var RPe=S(LW=>{"use strict";Object.defineProperty(LW,"t",{value:!0});var VM=class{constructor(t,n,r=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=t,this.l=n,this.p=r}I(){let t=this,n=t.o.o===t;if(n&&t.p===1)t=t.h;else if(t.i)for(t=t.i;t.h;)t=t.h;else{if(n)return t.o;let r=t.o;for(;r.i===t;)t=r,r=t.o;t=r}return t}B(){let t=this;if(t.h){for(t=t.h;t.i;)t=t.i;return t}else{let n=t.o;for(;n.h===t;)t=n,n=t.o;return t.h!==n?n:t}}_(){let t=this.o,n=this.h,r=n.i;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.i=this,this.o=n,this.h=r,r&&(r.o=this),n}g(){let t=this.o,n=this.i,r=n.h;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.h=this,this.o=n,this.i=r,r&&(r.o=this),n}},CW=class extends VM{constructor(){super(...arguments),this.M=1}_(){let t=super._();return this.O(),t.O(),t}g(){let t=super.g();return this.O(),t.O(),t}O(){this.M=1,this.i&&(this.M+=this.i.M),this.h&&(this.M+=this.h.M)}},NW=class{constructor(t=0){this.iteratorType=t}equals(t){return this.T===t.T}},MW=class{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}},DW=class extends MW{};function yy(){throw new RangeError("Iterator access denied!")}var UW=class extends DW{constructor(t=function(r,a){return r<a?-1:r>a?1:0},n=!1){super(),this.v=void 0,this.A=t,this.enableIndex=n,this.N=n?CW:VM,this.C=new this.N}R(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)t=t.h;else if(a>0)r=t,t=t.i;else return t}return r}K(t,n){let r=this.C;for(;t;)this.A(t.u,n)<=0?t=t.h:(r=t,t=t.i);return r}L(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)r=t,t=t.h;else if(a>0)t=t.i;else return t}return r}k(t,n){let r=this.C;for(;t;)this.A(t.u,n)<0?(r=t,t=t.h):t=t.i;return r}P(t){for(;;){let n=t.o;if(n===this.C)return;if(t.p===1){t.p=0;return}if(t===n.i){let r=n.h;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n._():n._();else if(r.h&&r.h.p===1){r.p=n.p,n.p=0,r.h.p=0,n===this.v?this.v=n._():n._();return}else r.i&&r.i.p===1?(r.p=1,r.i.p=0,r.g()):(r.p=1,t=n)}else{let r=n.i;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n.g():n.g();else if(r.i&&r.i.p===1){r.p=n.p,n.p=0,r.i.p=0,n===this.v?this.v=n.g():n.g();return}else r.h&&r.h.p===1?(r.p=1,r.h.p=0,r._()):(r.p=1,t=n)}}}S(t){if(this.m===1){this.clear();return}let n=t;for(;n.i||n.h;){if(n.h)for(n=n.h;n.i;)n=n.i;else n=n.i;let a=t.u;t.u=n.u,n.u=a;let i=t.l;t.l=n.l,n.l=i,t=n}this.C.i===n?this.C.i=n.o:this.C.h===n&&(this.C.h=n.o),this.P(n);let r=n.o;if(n===r.i?r.i=void 0:r.h=void 0,this.m-=1,this.v.p=0,this.enableIndex)for(;r!==this.C;)r.M-=1,r=r.o}U(t){let n=typeof t=="number"?t:void 0,r=typeof t=="function"?t:void 0,a=typeof t>"u"?[]:void 0,i=0,s=this.v,o=[];for(;o.length||s;)if(s)o.push(s),s=s.i;else{if(s=o.pop(),i===n)return s;a&&a.push(s),r&&r(s,i,this),i+=1,s=s.h}return a}j(t){for(;;){let n=t.o;if(n.p===0)return;let r=n.o;if(n===r.i){let a=r.h;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.h){if(t.p=0,t.i&&(t.i.o=n),t.h&&(t.h.o=r),n.h=t.i,r.i=t.h,t.i=n,t.h=r,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r.g():r.g(),r.p=1;return}}else{let a=r.i;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.i){if(t.p=0,t.i&&(t.i.o=r),t.h&&(t.h.o=n),r.h=t.i,n.i=t.h,t.i=r,t.h=n,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r._():r._(),r.p=1;return}}this.enableIndex&&(n.O(),r.O(),t.O());return}}q(t,n,r){if(this.v===void 0)return this.m+=1,this.v=new this.N(t,n,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let a,i=this.C.i,s=this.A(i.u,t);if(s===0)return i.l=n,this.m;if(s>0)i.i=new this.N(t,n),i.i.o=i,a=i.i,this.C.i=a;else{let o=this.C.h,c=this.A(o.u,t);if(c===0)return o.l=n,this.m;if(c<0)o.h=new this.N(t,n),o.h.o=o,a=o.h,this.C.h=a;else{if(r!==void 0){let l=r.T;if(l!==this.C){let u=this.A(l.u,t);if(u===0)return l.l=n,this.m;if(u>0){let d=l.I(),f=this.A(d.u,t);if(f===0)return d.l=n,this.m;f<0&&(a=new this.N(t,n),d.h===void 0?(d.h=a,a.o=d):(l.i=a,a.o=l))}}}if(a===void 0)for(a=this.v;;){let l=this.A(a.u,t);if(l>0){if(a.i===void 0){a.i=new this.N(t,n),a.i.o=a,a=a.i;break}a=a.i}else if(l<0){if(a.h===void 0){a.h=new this.N(t,n),a.h.o=a,a=a.h;break}a=a.h}else return a.l=n,this.m}}}if(this.enableIndex){let o=a.o;for(;o!==this.C;)o.M+=1,o=o.o}return this.j(a),this.m+=1,this.m}H(t,n){for(;t;){let r=this.A(t.u,n);if(r<0)t=t.h;else if(r>0)t=t.i;else return t}return t||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator(t,n){let r=t.T;if(r===this.C&&yy(),this.m===1)return r.u=n,!0;let a=r.B().u;if(r===this.C.i)return this.A(a,n)>0?(r.u=n,!0):!1;let i=r.I().u;return r===this.C.h?this.A(i,n)<0?(r.u=n,!0):!1:this.A(i,n)>=0||this.A(a,n)<=0?!1:(r.u=n,!0)}eraseElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return this.S(n),this.m}eraseElementByKey(t){if(this.m===0)return!1;let n=this.H(this.v,t);return n===this.C?!1:(this.S(n),!0)}eraseElementByIterator(t){let n=t.T;n===this.C&&yy();let r=n.h===void 0;return t.iteratorType===0?r&&t.next():(!r||n.i===void 0)&&t.next(),this.S(n),t}getHeight(){if(this.m===0)return 0;function t(n){return n?Math.max(t(n.i),t(n.h))+1:0}return t(this.v)}},BW=class extends NW{constructor(t,n,r){super(r),this.T=t,this.C=n,this.iteratorType===0?(this.pre=function(){return this.T===this.C.i&&yy(),this.T=this.T.I(),this},this.next=function(){return this.T===this.C&&yy(),this.T=this.T.B(),this}):(this.pre=function(){return this.T===this.C.h&&yy(),this.T=this.T.B(),this},this.next=function(){return this.T===this.C&&yy(),this.T=this.T.I(),this})}get index(){let t=this.T,n=this.C.o;if(t===this.C)return n?n.M-1:0;let r=0;for(t.i&&(r+=t.i.M);t!==n;){let a=t.o;t===a.h&&(r+=1,a.i&&(r+=a.i.M)),t=a}return r}isAccessible(){return this.T!==this.C}},Yl=class e extends BW{constructor(t,n,r,a){super(t,n,a),this.container=r}get pointer(){this.T===this.C&&yy();let t=this;return new Proxy([],{get(n,r){return r==="0"?t.T.u:r==="1"?t.T.l:(n[0]=t.T.u,n[1]=t.T.l,n[r])},set(n,r,a){if(r!=="1")throw new TypeError("prop must be 1");return t.T.l=a,!0}})}copy(){return new e(this.T,this.C,this.container,this.iteratorType)}},FW=class extends UW{constructor(t=[],n,r){super(n,r);let a=this;t.forEach(function(i){a.setElement(i[0],i[1])})}begin(){return new Yl(this.C.i||this.C,this.C,this)}end(){return new Yl(this.C,this.C,this)}rBegin(){return new Yl(this.C.h||this.C,this.C,this,1)}rEnd(){return new Yl(this.C,this.C,this,1)}front(){if(this.m===0)return;let t=this.C.i;return[t.u,t.l]}back(){if(this.m===0)return;let t=this.C.h;return[t.u,t.l]}lowerBound(t){let n=this.R(this.v,t);return new Yl(n,this.C,this)}upperBound(t){let n=this.K(this.v,t);return new Yl(n,this.C,this)}reverseLowerBound(t){let n=this.L(this.v,t);return new Yl(n,this.C,this)}reverseUpperBound(t){let n=this.k(this.v,t);return new Yl(n,this.C,this)}forEach(t){this.U(function(n,r,a){t([n.u,n.l],r,a)})}setElement(t,n,r){return this.q(t,n,r)}getElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return[n.u,n.l]}find(t){let n=this.H(this.v,t);return new Yl(n,this.C,this)}getElementByKey(t){return this.H(this.v,t).l}union(t){let n=this;return t.forEach(function(r){n.setElement(r[0],r[1])}),this.m}*[Symbol.iterator](){let t=this.m,n=this.U();for(let r=0;r<t;++r){let a=n[r];yield[a.u,a.l]}}};LW.OrderedMap=FW});var $M=S(qM=>{"use strict";Object.defineProperty(qM,"__esModule",{value:!0});qM.registerAdminService=Y2t;qM.addAdminServicesToServer=K2t;var CPe=[];function Y2t(e,t){CPe.push({getServiceDefinition:e,getHandlers:t})}function K2t(e){for(let{getServiceDefinition:t,getHandlers:n}of CPe)e.addService(t(),n())}});var NPe=S(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});Kl.ClientDuplexStreamImpl=Kl.ClientWritableStreamImpl=Kl.ClientReadableStreamImpl=Kl.ClientUnaryCallImpl=void 0;Kl.callErrorFromStatus=X2t;var j2t=require("events"),GW=require("stream"),NT=Kt();function X2t(e,t){let n=`${e.code} ${NT.Status[e.code]}: ${e.details}`,a=`${new Error(n).stack}
|
|
214
214
|
for call at
|
|
215
215
|
${t}`;return Object.assign(new Error(n),e,{stack:a})}var VW=class extends j2t.EventEmitter{constructor(){super()}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(NT.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}};Kl.ClientUnaryCallImpl=VW;var qW=class extends GW.Readable{constructor(t){super({objectMode:!0}),this.deserialize=t}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(NT.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_read(t){var n;(n=this.call)===null||n===void 0||n.startRead()}};Kl.ClientReadableStreamImpl=qW;var $W=class extends GW.Writable{constructor(t){super({objectMode:!0}),this.serialize=t}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(NT.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_write(t,n,r){var a;let i={callback:r},s=Number(n);Number.isNaN(s)||(i.flags=s),(a=this.call)===null||a===void 0||a.sendMessageWithContext(i,t)}_final(t){var n;(n=this.call)===null||n===void 0||n.halfClose(),t()}};Kl.ClientWritableStreamImpl=$W;var zW=class extends GW.Duplex{constructor(t,n){super({objectMode:!0}),this.serialize=t,this.deserialize=n}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(NT.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_read(t){var n;(n=this.call)===null||n===void 0||n.startRead()}_write(t,n,r){var a;let i={callback:r},s=Number(n);Number.isNaN(s)||(i.flags=s),(a=this.call)===null||a===void 0||a.sendMessageWithContext(i,t)}_final(t){var n;(n=this.call)===null||n===void 0||n.halfClose(),t()}};Kl.ClientDuplexStreamImpl=zW});var by=S(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});vy.InterceptingListenerImpl=void 0;vy.statusOrFromValue=Q2t;vy.statusOrFromError=eMt;vy.isInterceptingListener=tMt;var Z2t=ma();function Q2t(e){return{ok:!0,value:e}}function eMt(e){var t;return{ok:!1,error:Object.assign(Object.assign({},e),{metadata:(t=e.metadata)!==null&&t!==void 0?t:new Z2t.Metadata})}}function tMt(e){return e.onReceiveMetadata!==void 0&&e.onReceiveMetadata.length===1}var JW=class{constructor(t,n){this.listener=t,this.nextListener=n,this.processingMetadata=!1,this.hasPendingMessage=!1,this.processingMessage=!1,this.pendingStatus=null}processPendingMessage(){this.hasPendingMessage&&(this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1)}processPendingStatus(){this.pendingStatus&&this.nextListener.onReceiveStatus(this.pendingStatus)}onReceiveMetadata(t){this.processingMetadata=!0,this.listener.onReceiveMetadata(t,n=>{this.processingMetadata=!1,this.nextListener.onReceiveMetadata(n),this.processPendingMessage(),this.processPendingStatus()})}onReceiveMessage(t){this.processingMessage=!0,this.listener.onReceiveMessage(t,n=>{this.processingMessage=!1,this.processingMetadata?(this.pendingMessage=n,this.hasPendingMessage=!0):(this.nextListener.onReceiveMessage(n),this.processPendingStatus())})}onReceiveStatus(t){this.listener.onReceiveStatus(t,n=>{this.processingMetadata||this.processingMessage?this.pendingStatus=n:this.nextListener.onReceiveStatus(n)})}};vy.InterceptingListenerImpl=JW});var ZW=S(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});jl.InterceptingCall=jl.RequesterBuilder=jl.ListenerBuilder=jl.InterceptorConfigurationError=void 0;jl.getInterceptingCall=aMt;var nMt=ma(),MPe=by(),DPe=Kt(),UPe=wM(),DT=class e extends Error{constructor(t){super(t),this.name="InterceptorConfigurationError",Error.captureStackTrace(this,e)}};jl.InterceptorConfigurationError=DT;var WW=class{constructor(){this.metadata=void 0,this.message=void 0,this.status=void 0}withOnReceiveMetadata(t){return this.metadata=t,this}withOnReceiveMessage(t){return this.message=t,this}withOnReceiveStatus(t){return this.status=t,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveStatus:this.status}}};jl.ListenerBuilder=WW;var YW=class{constructor(){this.start=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withStart(t){return this.start=t,this}withSendMessage(t){return this.message=t,this}withHalfClose(t){return this.halfClose=t,this}withCancel(t){return this.cancel=t,this}build(){return{start:this.start,sendMessage:this.message,halfClose:this.halfClose,cancel:this.cancel}}};jl.RequesterBuilder=YW;var HW={onReceiveMetadata:(e,t)=>{t(e)},onReceiveMessage:(e,t)=>{t(e)},onReceiveStatus:(e,t)=>{t(e)}},MT={start:(e,t,n)=>{n(e,t)},sendMessage:(e,t)=>{t(e)},halfClose:e=>{e()},cancel:e=>{e()}},KW=class{constructor(t,n){var r,a,i,s;this.nextCall=t,this.processingMetadata=!1,this.pendingMessageContext=null,this.processingMessage=!1,this.pendingHalfClose=!1,n?this.requester={start:(r=n.start)!==null&&r!==void 0?r:MT.start,sendMessage:(a=n.sendMessage)!==null&&a!==void 0?a:MT.sendMessage,halfClose:(i=n.halfClose)!==null&&i!==void 0?i:MT.halfClose,cancel:(s=n.cancel)!==null&&s!==void 0?s:MT.cancel}:this.requester=MT}cancelWithStatus(t,n){this.requester.cancel(()=>{this.nextCall.cancelWithStatus(t,n)})}getPeer(){return this.nextCall.getPeer()}processPendingMessage(){this.pendingMessageContext&&(this.nextCall.sendMessageWithContext(this.pendingMessageContext,this.pendingMessage),this.pendingMessageContext=null,this.pendingMessage=null)}processPendingHalfClose(){this.pendingHalfClose&&this.nextCall.halfClose()}start(t,n){var r,a,i,s,o,c;let l={onReceiveMetadata:(a=(r=n?.onReceiveMetadata)===null||r===void 0?void 0:r.bind(n))!==null&&a!==void 0?a:u=>{},onReceiveMessage:(s=(i=n?.onReceiveMessage)===null||i===void 0?void 0:i.bind(n))!==null&&s!==void 0?s:u=>{},onReceiveStatus:(c=(o=n?.onReceiveStatus)===null||o===void 0?void 0:o.bind(n))!==null&&c!==void 0?c:u=>{}};this.processingMetadata=!0,this.requester.start(t,l,(u,d)=>{var f,h,g;this.processingMetadata=!1;let v;if((0,MPe.isInterceptingListener)(d))v=d;else{let b={onReceiveMetadata:(f=d.onReceiveMetadata)!==null&&f!==void 0?f:HW.onReceiveMetadata,onReceiveMessage:(h=d.onReceiveMessage)!==null&&h!==void 0?h:HW.onReceiveMessage,onReceiveStatus:(g=d.onReceiveStatus)!==null&&g!==void 0?g:HW.onReceiveStatus};v=new MPe.InterceptingListenerImpl(b,l)}this.nextCall.start(u,v),this.processPendingMessage(),this.processPendingHalfClose()})}sendMessageWithContext(t,n){this.processingMessage=!0,this.requester.sendMessage(n,r=>{this.processingMessage=!1,this.processingMetadata?(this.pendingMessageContext=t,this.pendingMessage=n):(this.nextCall.sendMessageWithContext(t,r),this.processPendingHalfClose())})}sendMessage(t){this.sendMessageWithContext({},t)}startRead(){this.nextCall.startRead()}halfClose(){this.requester.halfClose(()=>{this.processingMetadata||this.processingMessage?this.pendingHalfClose=!0:this.nextCall.halfClose()})}getAuthContext(){return this.nextCall.getAuthContext()}};jl.InterceptingCall=KW;function rMt(e,t,n){var r,a;let i=(r=n.deadline)!==null&&r!==void 0?r:1/0,s=n.host,o=(a=n.parent)!==null&&a!==void 0?a:null,c=n.propagate_flags,l=n.credentials,u=e.createCall(t,i,s,o,c);return l&&u.setCredentials(l),u}var zM=class{constructor(t,n){this.call=t,this.methodDefinition=n}cancelWithStatus(t,n){this.call.cancelWithStatus(t,n)}getPeer(){return this.call.getPeer()}sendMessageWithContext(t,n){let r;try{r=this.methodDefinition.requestSerialize(n)}catch(a){this.call.cancelWithStatus(DPe.Status.INTERNAL,`Request message serialization failure: ${(0,UPe.getErrorMessage)(a)}`);return}this.call.sendMessageWithContext(t,r)}sendMessage(t){this.sendMessageWithContext({},t)}start(t,n){let r=null;this.call.start(t,{onReceiveMetadata:a=>{var i;(i=n?.onReceiveMetadata)===null||i===void 0||i.call(n,a)},onReceiveMessage:a=>{var i;let s;try{s=this.methodDefinition.responseDeserialize(a)}catch(o){r={code:DPe.Status.INTERNAL,details:`Response message parsing error: ${(0,UPe.getErrorMessage)(o)}`,metadata:new nMt.Metadata},this.call.cancelWithStatus(r.code,r.details);return}(i=n?.onReceiveMessage)===null||i===void 0||i.call(n,s)},onReceiveStatus:a=>{var i,s;r?(i=n?.onReceiveStatus)===null||i===void 0||i.call(n,r):(s=n?.onReceiveStatus)===null||s===void 0||s.call(n,a)}})}startRead(){this.call.startRead()}halfClose(){this.call.halfClose()}getAuthContext(){return this.call.getAuthContext()}},jW=class extends zM{constructor(t,n){super(t,n)}start(t,n){var r,a;let i=!1,s={onReceiveMetadata:(a=(r=n?.onReceiveMetadata)===null||r===void 0?void 0:r.bind(n))!==null&&a!==void 0?a:o=>{},onReceiveMessage:o=>{var c;i=!0,(c=n?.onReceiveMessage)===null||c===void 0||c.call(n,o)},onReceiveStatus:o=>{var c,l;i||(c=n?.onReceiveMessage)===null||c===void 0||c.call(n,null),(l=n?.onReceiveStatus)===null||l===void 0||l.call(n,o)}};super.start(t,s),this.call.startRead()}},XW=class extends zM{};function iMt(e,t,n){let r=rMt(e,n.path,t);return n.responseStream?new XW(r,n):new jW(r,n)}function aMt(e,t,n,r){if(e.clientInterceptors.length>0&&e.clientInterceptorProviders.length>0)throw new DT("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if(e.callInterceptors.length>0&&e.callInterceptorProviders.length>0)throw new DT("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");let a=[];e.callInterceptors.length>0||e.callInterceptorProviders.length>0?a=[].concat(e.callInterceptors,e.callInterceptorProviders.map(o=>o(t))).filter(o=>o):a=[].concat(e.clientInterceptors,e.clientInterceptorProviders.map(o=>o(t))).filter(o=>o);let i=Object.assign({},n,{method_definition:t});return a.reduceRight((o,c)=>l=>c(l,o),o=>iMt(r,o,t))(i)}});var t7=S(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.Client=void 0;var Sd=NPe(),sMt=n7(),oMt=to(),Ph=Kt(),Yb=ma(),GM=ZW(),Xl=Symbol(),Kb=Symbol(),jb=Symbol(),sp=Symbol();function QW(e){return typeof e=="function"}function Xb(e){var t;return((t=e.stack)===null||t===void 0?void 0:t.split(`
|
|
216
216
|
`).slice(1).join(`
|
|
@@ -246,7 +246,7 @@ const app = await modal.apps.fromName("my-app");
|
|
|
246
246
|
modal.sandboxes.experimentalList({ appId: app.appId });`);let t=e.tags?Object.entries(e.tags).map(([r,a])=>({tagName:r,tagValue:a})):[],n;for(;;){let r=await this.#e.cpClient.sandboxListV2({appId:e.appId,beforeTimestamp:n,includeFinished:!1,tags:t});if(!r.sandboxes||r.sandboxes.length===0)return;for(let a of r.sandboxes)yield new Yy(this.#e,a.id,{isV2:!0});n=r.sandboxes[r.sandboxes.length-1].createdAt}}},KYe=class{constructor(e,t,n,r){this.host=e,this.port=t,this.unencryptedHost=n,this.unencryptedPort=r}get url(){let e=`https://${this.host}`;return this.port!==443&&(e+=`:${this.port}`),e}get tlsSocket(){return[this.host,this.port]}get tcpSocket(){if(!this.unencryptedHost||this.unencryptedPort===void 0)throw new wt("This tunnel is not configured for unencrypted TCP.");return[this.unencryptedHost,this.unencryptedPort]}};Yy=class QYe{#e;sandboxId;#t;#n;#r;#a;#s;#l;#u;#c;#p;#d;#h=!0;#m;#g;constructor(t,n,r={}){this.#e=t,this.sandboxId=n,this.#c=r.isV2??!1,this.#l=r.taskId||void 0,this.#u=r.tunnels}get stdin(){return this.#f("stdin"),this.#t||(this.#t=HYe(CHt(this.#e.cpClient,this.sandboxId))),this.#t}get stdout(){if(this.#f("stdout"),!this.#n){this.#a=new AbortController;let t=yU(nJe(this.#e.cpClient,this.sandboxId,1,this.#a.signal),()=>this.#a?.abort());this.#n=gw(t.pipeThrough(new TextDecoderStream))}return this.#n}get stderr(){if(this.#f("stderr"),!this.#r){this.#s=new AbortController;let t=yU(nJe(this.#e.cpClient,this.sandboxId,2,this.#s.signal),()=>this.#s?.abort());this.#r=gw(t.pipeThrough(new TextDecoderStream))}return this.#r}get filesystem(){return this.#i(),this.#m||(this.#m=new GYe((t,n)=>this.#y(t,n))),this.#m}get experimentalSidecars(){return this.#i(),this.#g||(this.#g=new gHt({client:this.#e,exec:(t,n,r)=>this.#y(t,n,r),commandRouter:()=>this.#o()})),this.#g}async setTags(t){this.#i(),this.#f("setTags");let n=Object.entries(t).map(([r,a])=>({tagName:r,tagValue:a}));try{await this.#e.cpClient.sandboxTagsSet({environmentName:this.#e.environmentName(),sandboxId:this.sandboxId,tags:n})}catch(r){throw r instanceof Us.ClientError&&r.code===Us.Status.INVALID_ARGUMENT?new wt(r.details||r.message):r}}async getTags(){this.#i(),this.#f("getTags");let t;try{t=await this.#e.cpClient.sandboxTagsGet({sandboxId:this.sandboxId})}catch(r){throw r instanceof Us.ClientError&&r.code===Us.Status.INVALID_ARGUMENT?new wt(r.details||r.message):r}let n={};for(let r of t.tags)n[r.tagName]=r.tagValue;return n}async exec(t,n){return this.#y(t,n)}async#y(t,n,r){this.#i(),XYe(t),xU(n?.env??{});let[a,i]=Fj(n?.secrets??[]);Object.assign(a,n?.env??{}),await ww(this.#e,i);let s={...n,env:a,secrets:i},[o,c]=await this.#o(),l=Hy(),u=OHt(o,l,t,s,r);await c.execStart(u),this.#e.logger.debug("Created ContainerProcess","exec_id",l,"sandbox_id",this.sandboxId,"container_id",r??"","command",t);let d=n?.timeoutMs?Date.now()+n.timeoutMs:null;return new RHt(o,l,c,n,d)}async#o(){this.#i();let t=await this.#I(),n=await this.#x(t);return[t,n]}#i(){if(!this.#h)throw new mU}#f(t){if(this.#c)throw new wt(`Sandbox.${t} is not supported for V2 sandboxes`)}#v(t){let n={sandboxId:this.sandboxId,timeout:t};return this.#c?this.#e.cpClient.sandboxWaitV2(n):this.#e.cpClient.sandboxWait(n)}#b(){let t={sandboxId:this.sandboxId};return this.#c?this.#e.cpClient.sandboxGetTaskIdV2(t):this.#e.cpClient.sandboxGetTaskId(t)}#S(t){let n={sandboxId:this.sandboxId,timeout:t/1e3};return this.#c?this.#e.cpClient.sandboxGetTunnelsV2(n):this.#e.cpClient.sandboxGetTunnels(n)}async#_(){let t={sandboxId:this.sandboxId};if(this.#c){await this.#e.cpClient.sandboxTerminateV2(t);return}await this.#e.cpClient.sandboxTerminate(t)}static#w=600;async#I(){if(this.#l!==void 0)return this.#l;for(let t=0;t<QYe.#w;t++){let n=await this.#b();if(n.taskResult)throw n.taskResult.status===1||!n.taskResult.exception?new Error(`Sandbox ${this.sandboxId} has already completed`):new Error(`Sandbox ${this.sandboxId} has already completed with result: exception:"${n.taskResult.exception}"`);if(n.taskId)return this.#l=n.taskId,this.#l;await(0,Lj.setTimeout)(500)}throw new Error(`Timed out waiting for task ID for Sandbox ${this.sandboxId}`)}async#x(t){if(this.#p!==void 0)return this.#p;if(this.#d!==void 0)return this.#d;let n=(async()=>{let r=await KJt.tryInit(this.#e.cpClient,t,this.sandboxId,this.#c,this.#e.logger,this.#e.profile);if(!r)throw new Error("Command router access is not available for this sandbox");if(!this.#h)throw r.close(),new mU;return this.#p=r,r})();this.#d=n;try{return await n}catch(r){throw this.#d===n&&(this.#d=void 0),r}}async createConnectToken(t){this.#i(),this.#f("createConnectToken");let n=t?.port??8080;if(!Number.isInteger(n)||n<1||n>65535)throw new wt(`createConnectToken() expects \`port\` in [1, 65535], got ${n}`);let r=await this.#e.cpClient.sandboxCreateConnectToken({sandboxId:this.sandboxId,userMetadata:t?.userMetadata,port:n});return{url:r.url,token:r.token}}async terminate(t){this.#i(),await this.#_();let n;return t?.wait&&(n=await this.wait()),this.#l=void 0,this.detach(),n}detach(){this.#p?.close(),this.#h=!1,this.#p=void 0,this.#d=void 0}async wait(){for(;;){let t=await this.#v(10);if(t.result){let n=yw(t.result);return this.#e.logger.debug("Sandbox wait completed","sandbox_id",this.sandboxId,"status",t.result.status,"return_code",n),n}}}async waitUntilReady(t=3e5){if(this.#i(),t<=0)throw new wt(`timeoutMs must be positive, got ${t}`);let[n,r]=await this.#o();await r.sandboxWaitUntilReady(n,t)}async tunnels(t=5e4){if(this.#i(),this.#u)return this.#u;let n=await this.#S(t);if(n.result?.status===4)throw new kGt;this.#u={};for(let r of n.tunnels)this.#u[r.containerPort]=new KYe(r.host,r.port,r.unencryptedHost,r.unencryptedPort);return this.#u}async snapshotFilesystem(t){this.#i();let n=eJe(t?.ttlMs),r=t?.timeoutMs||55e3,[a,i]=await this.#o(),s=eX.create({taskId:a,snapshotId:Hy(),ttlSeconds:n}),o=await i.snapshotFilesystem(s,{timeoutMs:r});if(!o.imageId)throw new Error("Sandbox snapshot filesystem response missing `imageId`");return new ev(this.#e,o.imageId,"")}async mountImage(t,n,r){this.#i();let[a,i]=await this.#o();if(n&&!n.imageId)throw new Error("Image must be built before mounting. Call `image.build(app)` first.");let s=n?.imageId??"",o=AHt(a,t,s,r);await i.mountDirectory(o)}async unmountImage(t){this.#i();let[n,r]=await this.#o(),a=new TextEncoder().encode(t),i=tX.create({taskId:n,path:a});await r.unmountDirectory(i)}async updateNetworkPolicy(t){if(this.#i(),t.outboundCidrAllowlist===void 0||t.outboundDomainAllowlist===void 0)throw new wt("updateNetworkPolicy currently requires both outboundCidrAllowlist and outboundDomainAllowlist to be set");let[n,r]=await this.#o(),a=Zj.create({taskId:n,networkAccess:ro.create({networkAccessType:3,allowedCidrs:t.outboundCidrAllowlist,allowedDomains:t.outboundDomainAllowlist})});await r.setNetworkAccess(a)}async reloadVolumes(t){if(this.#i(),t?.timeoutMs!==void 0&&t.timeoutMs<0)throw new wt("`timeoutMs` must not be negative");let n=t?.timeoutMs||55e3,[r,a]=await this.#o();await a.reloadVolumes(Xj.create({taskId:r}),{timeoutMs:n})}async snapshotDirectory(t,n){this.#i();let r=eJe(n?.ttlMs),a=n?.timeoutMs||55e3,[i,s]=await this.#o(),o=PHt(i,t,Hy(),r,n),c=await s.snapshotDirectory(o,{timeoutMs:a});if(!c.imageId)throw new Error("Sandbox snapshot directory response missing `imageId`");return new ev(this.#e,c.imageId,"")}async poll(){this.#i();let t=await this.#v(0);return yw(t.result)}},RHt=class{stdin;stdout;stderr;#e;#t;#n;#r;constructor(e,t,n,r,a){this.#e=e,this.#t=t,this.#n=n,this.#r=a??null;let i=r?.mode??"text",s=r?.stdout??"pipe",o=r?.stderr??"pipe";this.stdin=HYe(NHt(n,e,t));let c=s==="ignore"?ReadableStream.from([]):yU(rJe(n,e,t,1,this.#r)),l=o==="ignore"?ReadableStream.from([]):yU(rJe(n,e,t,2,this.#r));i==="text"?(this.stdout=gw(c.pipeThrough(new TextDecoderStream)),this.stderr=gw(l.pipeThrough(new TextDecoderStream))):(this.stdout=gw(c),this.stderr=gw(l))}async closeStdin(){await this.#n.execStdinWrite(this.#e,this.#t,0,new Uint8Array(0),!0).catch(()=>{})}async wait(){let e=await this.#n.execWait(this.#e,this.#t,this.#r);if(e.code!==void 0)return e.code;if(e.signal!==void 0)return 128+e.signal;throw new wt("Unexpected exit status")}}});var r9e=S((zxn,n9e)=>{n9e.exports=require("events")});var a9e=S((Jxn,i9e)=>{i9e.exports=class{constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var rX=S((Wxn,o9e)=>{var s9e=a9e();o9e.exports=class{constructor(t){this.hwm=t||16,this.head=new s9e(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(t){if(this.length++,!this.head.push(t)){let n=this.head;this.head=n.next=new s9e(2*this.head.buffer.length),this.head.push(t)}}shift(){this.length!==0&&this.length--;let t=this.tail.shift();if(t===void 0&&this.tail.next){let n=this.tail.next;return this.tail.next=null,this.tail=n,this.tail.shift()}return t}peek(){let t=this.tail.peek();return t===void 0&&this.tail.next?this.tail.next.peek():t}isEmpty(){return this.length===0}}});var Iw=S((Yxn,c9e)=>{function MHt(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function DHt(e){return Buffer.isEncoding(e)}function UHt(e,t,n){return Buffer.alloc(e,t,n)}function BHt(e){return Buffer.allocUnsafe(e)}function FHt(e){return Buffer.allocUnsafeSlow(e)}function LHt(e,t){return Buffer.byteLength(e,t)}function VHt(e,t){return Buffer.compare(e,t)}function qHt(e,t){return Buffer.concat(e,t)}function $Ht(e,t,n,r,a){return cr(e).copy(t,n,r,a)}function zHt(e,t){return cr(e).equals(t)}function GHt(e,t,n,r,a){return cr(e).fill(t,n,r,a)}function JHt(e,t,n){return Buffer.from(e,t,n)}function HHt(e,t,n,r){return cr(e).includes(t,n,r)}function WHt(e,t,n,r){return cr(e).indexOf(t,n,r)}function YHt(e,t,n,r){return cr(e).lastIndexOf(t,n,r)}function KHt(e){return cr(e).swap16()}function jHt(e){return cr(e).swap32()}function XHt(e){return cr(e).swap64()}function cr(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function ZHt(e,t,n,r){return cr(e).toString(t,n,r)}function QHt(e,t,n,r,a){return cr(e).write(t,n,r,a)}function e6t(e,t){return cr(e).readDoubleBE(t)}function t6t(e,t){return cr(e).readDoubleLE(t)}function n6t(e,t){return cr(e).readFloatBE(t)}function r6t(e,t){return cr(e).readFloatLE(t)}function i6t(e,t){return cr(e).readInt32BE(t)}function a6t(e,t){return cr(e).readInt32LE(t)}function s6t(e,t){return cr(e).readUInt32BE(t)}function o6t(e,t){return cr(e).readUInt32LE(t)}function c6t(e,t,n){return cr(e).writeDoubleBE(t,n)}function l6t(e,t,n){return cr(e).writeDoubleLE(t,n)}function u6t(e,t,n){return cr(e).writeFloatBE(t,n)}function d6t(e,t,n){return cr(e).writeFloatLE(t,n)}function f6t(e,t,n){return cr(e).writeInt32BE(t,n)}function p6t(e,t,n){return cr(e).writeInt32LE(t,n)}function h6t(e,t,n){return cr(e).writeUInt32BE(t,n)}function m6t(e,t,n){return cr(e).writeUInt32LE(t,n)}c9e.exports={isBuffer:MHt,isEncoding:DHt,alloc:UHt,allocUnsafe:BHt,allocUnsafeSlow:FHt,byteLength:LHt,compare:VHt,concat:qHt,copy:$Ht,equals:zHt,fill:GHt,from:JHt,includes:HHt,indexOf:WHt,lastIndexOf:YHt,swap16:KHt,swap32:jHt,swap64:XHt,toBuffer:cr,toString:ZHt,write:QHt,readDoubleBE:e6t,readDoubleLE:t6t,readFloatBE:n6t,readFloatLE:r6t,readInt32BE:i6t,readInt32LE:a6t,readUInt32BE:s6t,readUInt32LE:o6t,writeDoubleBE:c6t,writeDoubleLE:l6t,writeFloatBE:u6t,writeFloatLE:d6t,writeInt32BE:f6t,writeInt32LE:p6t,writeUInt32BE:h6t,writeUInt32LE:m6t}});var u9e=S((jxn,l9e)=>{var g6t=Iw();l9e.exports=class{constructor(t){this.encoding=t}get remaining(){return 0}decode(t){return g6t.toString(t,this.encoding)}flush(){return""}}});var f9e=S((Zxn,d9e)=>{var y6t=Iw();d9e.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(t){if(this.bytesNeeded===0){let r=!0;for(let a=Math.max(0,t.byteLength-4),i=t.byteLength;a<i&&r;a++)r=t[a]<=127;if(r)return y6t.toString(t,"utf8")}let n="";for(let r=0,a=t.byteLength;r<a;r++){let i=t[r];if(this.bytesNeeded===0){i<=127?n+=String.fromCharCode(i):(this.bytesSeen=1,i>=194&&i<=223?(this.bytesNeeded=2,this.codePoint=i&31):i>=224&&i<=239?(i===224?this.lowerBoundary=160:i===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=i&15):i>=240&&i<=244?(i===240&&(this.lowerBoundary=144),i===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=i&7):n+="\uFFFD");continue}if(i<this.lowerBoundary||i>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,n+="\uFFFD";continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|i&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(n+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return n}flush(){let t=this.bytesNeeded>0?"\uFFFD":"";return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t}}});var h9e=S((eEn,p9e)=>{var v6t=u9e(),b6t=f9e();p9e.exports=class{constructor(t="utf8"){switch(this.encoding=S6t(t),this.encoding){case"utf8":this.decoder=new b6t;break;case"utf16le":case"base64":throw new Error("Unsupported encoding: "+this.encoding);default:this.decoder=new v6t(this.encoding)}}get remaining(){return this.decoder.remaining}push(t){return typeof t=="string"?t:this.decoder.decode(t)}write(t){return this.push(t)}end(t){let n="";return t&&(n=this.push(t)),n+=this.decoder.flush(),n}};function S6t(e){switch(e=e.toLowerCase(),e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:throw new Error("Unknown encoding: "+e)}}});var bX=S((tEn,B9e)=>{var{EventEmitter:_6t}=r9e(),CU=new Error("Stream was destroyed"),iX=new Error("Premature close"),S9e=rX(),w6t=h9e(),aX=typeof queueMicrotask>"u"?e=>global.process.nextTick(e):queueMicrotask,ii=(1<<29)-1,Yd=1,fX=2,ov=4,Jk=8,_9e=ii^Yd,I6t=ii^fX,jk=16,xw=32,kw=64,om=128,Xk=256,pX=512,cv=1024,sX=2048,hX=4096,mX=8192,Uu=16384,sm=32768,NU=65536,lv=131072,w9e=Xk|pX,x6t=jk|NU,E6t=kw|jk,T6t=hX|om,gX=Xk|lv,k6t=ii^jk,O6t=ii^kw,A6t=ii^(kw|NU),m9e=ii^NU,P6t=ii^Xk,R6t=ii^(om|mX),C6t=ii^cv,g9e=ii^w9e,I9e=ii^sm,N6t=ii^xw,x9e=ii^lv,M6t=ii^gX,Tp=1<<18,Tw=2<<18,Zk=4<<18,uv=8<<18,Qk=16<<18,cm=32<<18,oX=64<<18,Ew=128<<18,yX=256<<18,dv=512<<18,MU=1024<<18,D6t=ii^(Tp|yX),E9e=ii^Zk,U6t=ii^(Tp|dv),B6t=ii^Qk,F6t=ii^uv,T9e=ii^Ew,L6t=ii^Tw,k9e=ii^MU,Hk=jk|Tp,O9e=ii^Hk,vX=Uu|cm,Kd=ov|Jk|fX,gc=Kd|Yd,A9e=Kd|vX,V6t=E9e&O6t,DU=Ew|sm,q6t=DU&O9e,P9e=gc|q6t,$6t=gc|cv|Uu,y9e=gc|Uu|om,z6t=gc|cv|om,G6t=gc|hX|om|mX,J6t=gc|jk|cv|Uu|NU|lv,H6t=Kd|cv|Uu,W6t=xw|gc|sm|kw,Y6t=sm|Yd,K6t=gc|dv|cm,j6t=uv|Qk,R9e=uv|Tp,X6t=uv|Qk|gc|Tp,v9e=gc|Tp|uv|MU,Z6t=Zk|Tp,Q6t=Tp|yX,e8t=gc|dv|R9e|cm,t8t=Qk|Kd|dv|cm,n8t=Tw|gc|Ew|Zk,r8t=dv|cm|Kd,kU=Symbol.asyncIterator||Symbol("asyncIterator"),OU=class{constructor(t,{highWaterMark:n=16384,map:r=null,mapWritable:a,byteLength:i,byteLengthWritable:s}={}){this.stream=t,this.queue=new S9e,this.highWaterMark=n,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=s||i||U9e,this.map=a||r,this.afterWrite=s8t.bind(this),this.afterUpdateNextTick=l8t.bind(this)}get ended(){return(this.stream._duplexState&cm)!==0}push(t){return this.stream._duplexState&r8t?!1:(this.map!==null&&(t=this.map(t)),this.buffered+=this.byteLength(t),this.queue.push(t),this.buffered<this.highWaterMark?(this.stream._duplexState|=uv,!0):(this.stream._duplexState|=j6t,!1))}shift(){let t=this.queue.shift();return this.buffered-=this.byteLength(t),this.buffered===0&&(this.stream._duplexState&=F6t),t}end(t){typeof t=="function"?this.stream.once("finish",t):t!=null&&this.push(t),this.stream._duplexState=(this.stream._duplexState|dv)&E9e}autoBatch(t,n){let r=[],a=this.stream;for(r.push(t);(a._duplexState&v9e)===R9e;)r.push(a._writableState.shift());if(a._duplexState&gc)return n(null);a._writev(r,n)}update(){let t=this.stream;t._duplexState|=Tw;do{for(;(t._duplexState&v9e)===uv;){let n=this.shift();t._duplexState|=Q6t,t._write(n,this.afterWrite)}t._duplexState&Z6t||this.updateNonPrimary()}while(this.continueUpdate()===!0);t._duplexState&=L6t}updateNonPrimary(){let t=this.stream;if((t._duplexState&e8t)===dv){t._duplexState=t._duplexState|Tp,t._final(a8t.bind(this));return}if((t._duplexState&Kd)===ov){t._duplexState&DU||(t._duplexState|=Hk,t._destroy(C9e.bind(this)));return}(t._duplexState&P9e)===Yd&&(t._duplexState=(t._duplexState|Hk)&_9e,t._open(N9e.bind(this)))}continueUpdate(){return this.stream._duplexState&Ew?(this.stream._duplexState&=T9e,!0):!1}updateCallback(){(this.stream._duplexState&n8t)===Zk?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&Ew||(this.stream._duplexState|=Ew,this.stream._duplexState&Tw||aX(this.afterUpdateNextTick))}},cX=class{constructor(t,{highWaterMark:n=16384,map:r=null,mapReadable:a,byteLength:i,byteLengthReadable:s}={}){this.stream=t,this.queue=new S9e,this.highWaterMark=n===0?1:n,this.buffered=0,this.readAhead=n>0,this.error=null,this.pipeline=null,this.byteLength=s||i||U9e,this.map=a||r,this.pipeTo=null,this.afterRead=o8t.bind(this),this.afterUpdateNextTick=c8t.bind(this)}get ended(){return(this.stream._duplexState&Uu)!==0}pipe(t,n){if(this.pipeTo!==null)throw new Error("Can only pipe to one destination");if(typeof n!="function"&&(n=null),this.stream._duplexState|=pX,this.pipeTo=t,this.pipeline=new uX(this.stream,t,n),n&&this.stream.on("error",b9e),Kk(t))t._writableState.pipeline=this.pipeline,n&&t.on("error",b9e),t.on("finish",this.pipeline.finished.bind(this.pipeline));else{let r=this.pipeline.done.bind(this.pipeline,t),a=this.pipeline.done.bind(this.pipeline,t,null);t.on("error",r),t.on("close",a),t.on("finish",this.pipeline.finished.bind(this.pipeline))}t.on("drain",i8t.bind(this)),this.stream.emit("piping",t),t.emit("pipe",this.stream)}push(t){let n=this.stream;return t===null?(this.highWaterMark=0,n._duplexState=(n._duplexState|cv)&A6t,!1):this.map!==null&&(t=this.map(t),t===null)?(n._duplexState&=m9e,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(t),this.queue.push(t),n._duplexState=(n._duplexState|om)&m9e,this.buffered<this.highWaterMark)}shift(){let t=this.queue.shift();return this.buffered-=this.byteLength(t),this.buffered===0&&(this.stream._duplexState&=R6t),t}unshift(t){let n=[this.map!==null?this.map(t):t];for(;this.buffered>0;)n.push(this.shift());for(let r=0;r<n.length-1;r++){let a=n[r];this.buffered+=this.byteLength(a),this.queue.push(a)}this.push(n[n.length-1])}read(){let t=this.stream;if((t._duplexState&y9e)===om){let n=this.shift();return this.pipeTo!==null&&this.pipeTo.write(n)===!1&&(t._duplexState&=g9e),t._duplexState&sX&&t.emit("data",n),n}return this.readAhead===!1&&(t._duplexState|=lv,this.updateNextTick()),null}drain(){let t=this.stream;for(;(t._duplexState&y9e)===om&&t._duplexState&w9e;){let n=this.shift();this.pipeTo!==null&&this.pipeTo.write(n)===!1&&(t._duplexState&=g9e),t._duplexState&sX&&t.emit("data",n)}}update(){let t=this.stream;t._duplexState|=xw;do{for(this.drain();this.buffered<this.highWaterMark&&(t._duplexState&J6t)===lv;)t._duplexState|=x6t,t._read(this.afterRead),this.drain();(t._duplexState&G6t)===T6t&&(t._duplexState|=mX,t.emit("readable")),t._duplexState&E6t||this.updateNonPrimary()}while(this.continueUpdate()===!0);t._duplexState&=N6t}updateNonPrimary(){let t=this.stream;if((t._duplexState&z6t)===cv&&(t._duplexState=(t._duplexState|Uu)&C6t,t.emit("end"),(t._duplexState&A9e)===vX&&(t._duplexState|=ov),this.pipeTo!==null&&this.pipeTo.end()),(t._duplexState&Kd)===ov){t._duplexState&DU||(t._duplexState|=Hk,t._destroy(C9e.bind(this)));return}(t._duplexState&P9e)===Yd&&(t._duplexState=(t._duplexState|Hk)&_9e,t._open(N9e.bind(this)))}continueUpdate(){return this.stream._duplexState&sm?(this.stream._duplexState&=I9e,!0):!1}updateCallback(){(this.stream._duplexState&W6t)===kw?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&Y6t||(this.stream._duplexState|=sm,this.stream._duplexState&xw||aX(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&sm||(this.stream._duplexState|=sm,this.stream._duplexState&xw||aX(this.afterUpdateNextTick))}},lX=class{constructor(t){this.data=null,this.afterTransform=d8t.bind(t),this.afterFinal=null}},uX=class{constructor(t,n,r){this.from=t,this.to=n,this.afterPipe=r,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(t,n){if(n&&(this.error=n),t===this.to&&(this.to=null,this.from!==null)){(!(this.from._duplexState&Uu)||!this.pipeToFinished)&&this.from.destroy(this.error||new Error("Writable stream closed prematurely"));return}if(t===this.from&&(this.from=null,this.to!==null)){t._duplexState&Uu||this.to.destroy(this.error||new Error("Readable stream closed before ending"));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function i8t(){this.stream._duplexState|=pX,this.updateCallback()}function a8t(e){let t=this.stream;e&&t.destroy(e),t._duplexState&Kd||(t._duplexState|=cm,t.emit("finish")),(t._duplexState&A9e)===vX&&(t._duplexState|=ov),t._duplexState&=U6t,t._duplexState&Tw?this.updateNextTick():this.update()}function C9e(e){let t=this.stream;!e&&this.error!==CU&&(e=this.error),e&&t.emit("error",e),t._duplexState|=Jk,t.emit("close");let n=t._readableState,r=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),r!==null){for(;r.drains!==null&&r.drains.length>0;)r.drains.shift().resolve(!1);r.pipeline!==null&&r.pipeline.done(t,e)}}function s8t(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=D6t,this.drains!==null&&u8t(this.drains),(t._duplexState&X6t)===Qk&&(t._duplexState&=B6t,(t._duplexState&oX)===oX&&t.emit("drain")),this.updateCallback()}function o8t(e){e&&this.stream.destroy(e),this.stream._duplexState&=k6t,this.readAhead===!1&&!(this.stream._duplexState&Xk)&&(this.stream._duplexState&=x9e),this.updateCallback()}function c8t(){this.stream._duplexState&xw||(this.stream._duplexState&=I9e,this.update())}function l8t(){this.stream._duplexState&Tw||(this.stream._duplexState&=T9e,this.update())}function u8t(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function N9e(e){let t=this.stream;e&&t.destroy(e),t._duplexState&ov||(t._duplexState&$6t||(t._duplexState|=kw),t._duplexState&K6t||(t._duplexState|=Zk),t.emit("open")),t._duplexState&=O9e,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function d8t(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function f8t(e){this._readableState!==null&&(e==="data"&&(this._duplexState|=sX|gX,this._readableState.updateNextTick()),e==="readable"&&(this._duplexState|=hX,this._readableState.updateNextTick())),this._writableState!==null&&e==="drain"&&(this._duplexState|=oX,this._writableState.updateNextTick())}var Wk=class extends _6t{constructor(t){super(),this._duplexState=0,this._readableState=null,this._writableState=null,t&&(t.open&&(this._open=t.open),t.destroy&&(this._destroy=t.destroy),t.predestroy&&(this._predestroy=t.predestroy),t.signal&&t.signal.addEventListener("abort",w8t.bind(this))),this.on("newListener",f8t)}_open(t){t(null)}_destroy(t){t(null)}_predestroy(){}get readable(){return this._readableState!==null?!0:void 0}get writable(){return this._writableState!==null?!0:void 0}get destroyed(){return(this._duplexState&Jk)!==0}get destroying(){return(this._duplexState&Kd)!==0}destroy(t){this._duplexState&Kd||(t||(t=CU),this._duplexState=(this._duplexState|ov)&V6t,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=t),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=t),this._duplexState|=fX,this._predestroy(),this._duplexState&=I6t,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},AU=class e extends Wk{constructor(t){super(t),this._duplexState|=Yd|cm|lv,this._readableState=new cX(this,t),t&&(this._readableState.readAhead===!1&&(this._duplexState&=x9e),t.read&&(this._read=t.read),t.eagerOpen&&this._readableState.updateNextTick(),t.encoding&&this.setEncoding(t.encoding))}setEncoding(t){let n=new w6t(t),r=this._readableState.map||m8t;return this._readableState.map=a,this;function a(i){let s=n.push(i);return s===""&&(i.byteLength!==0||n.remaining>0)?null:r(s)}}_read(t){t(null)}pipe(t,n){return this._readableState.updateNextTick(),this._readableState.pipe(t,n),t}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(t){return this._readableState.updateNextTickIfOpen(),this._readableState.push(t)}unshift(t){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(t)}resume(){return this._duplexState|=gX,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?M6t:P6t,this}static _fromAsyncIterator(t,n){let r,a=new e({...n,read(s){t.next().then(i).then(s.bind(null,null)).catch(s)},predestroy(){r=t.return()},destroy(s){if(!r)return s(null);r.then(s.bind(null,null)).catch(s)}});return a;function i(s){s.done?a.push(null):a.push(s.value)}}static from(t,n){if(b8t(t))return t;if(t[kU])return this._fromAsyncIterator(t[kU](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(a){this.push(r===t.length?null:t[r++]),a(null)}})}static isBackpressured(t){return(t._duplexState&H6t)!==0||t._readableState.buffered>=t._readableState.highWaterMark}static isPaused(t){return(t._duplexState&Xk)===0}[kU](){let t=this,n=null,r=null,a=null;return this.on("error",l=>{n=l}),this.on("readable",i),this.on("close",s),{[kU](){return this},next(){return new Promise(function(l,u){r=l,a=u;let d=t.read();d!==null?o(d):t._duplexState&Jk&&o(null)})},return(){return c(null)},throw(l){return c(l)}};function i(){r!==null&&o(t.read())}function s(){r!==null&&o(null)}function o(l){a!==null&&(n?a(n):l===null&&!(t._duplexState&Uu)?a(CU):r({value:l,done:l===null}),a=r=null)}function c(l){return t.destroy(l),new Promise((u,d)=>{if(t._duplexState&Jk)return u({value:void 0,done:!0});t.once("close",function(){l?d(l):u({value:void 0,done:!0})})})}}},PU=class extends Wk{constructor(t){super(t),this._duplexState|=Yd|Uu,this._writableState=new OU(this,t),t&&(t.writev&&(this._writev=t.writev),t.write&&(this._write=t.write),t.final&&(this._final=t.final),t.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=MU}uncork(){this._duplexState&=k9e,this._writableState.updateNextTick()}_writev(t,n){n(null)}_write(t,n){this._writableState.autoBatch(t,n)}_final(t){t(null)}static isBackpressured(t){return(t._duplexState&t8t)!==0}static drained(t){if(t.destroyed)return Promise.resolve(!1);let n=t._writableState,a=(I8t(t)?Math.min(1,n.queue.length):n.queue.length)+(t._duplexState&yX?1:0);return a===0?Promise.resolve(!0):(n.drains===null&&(n.drains=[]),new Promise(i=>{n.drains.push({writes:a,resolve:i})}))}write(t){return this._writableState.updateNextTick(),this._writableState.push(t)}end(t){return this._writableState.updateNextTick(),this._writableState.end(t),this}},Yk=class extends AU{constructor(t){super(t),this._duplexState=Yd|this._duplexState&lv,this._writableState=new OU(this,t),t&&(t.writev&&(this._writev=t.writev),t.write&&(this._write=t.write),t.final&&(this._final=t.final))}cork(){this._duplexState|=MU}uncork(){this._duplexState&=k9e,this._writableState.updateNextTick()}_writev(t,n){n(null)}_write(t,n){this._writableState.autoBatch(t,n)}_final(t){t(null)}write(t){return this._writableState.updateNextTick(),this._writableState.push(t)}end(t){return this._writableState.updateNextTick(),this._writableState.end(t),this}},RU=class extends Yk{constructor(t){super(t),this._transformState=new lX(this),t&&(t.transform&&(this._transform=t.transform),t.flush&&(this._flush=t.flush))}_write(t,n){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=t:this._transform(t,this._transformState.afterTransform)}_read(t){if(this._transformState.data!==null){let n=this._transformState.data;this._transformState.data=null,t(null),this._transform(n,this._transformState.afterTransform)}else t(null)}destroy(t){super.destroy(t),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(t,n){n(null,t)}_flush(t){t(null)}_final(t){this._transformState.afterFinal=t,this._flush(p8t.bind(this))}},dX=class extends RU{};function p8t(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function h8t(...e){return new Promise((t,n)=>M9e(...e,r=>{if(r)return n(r);t()}))}function M9e(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]=="function"?n.pop():null;if(n.length<2)throw new Error("Pipeline requires at least 2 streams");let a=n[0],i=null,s=null;for(let l=1;l<n.length;l++)i=n[l],Kk(a)?a.pipe(i,c):(o(a,!0,l>1,c),a.pipe(i)),a=i;if(r){let l=!1,u=Kk(i)||!!(i._writableState&&i._writableState.autoDestroy);i.on("error",d=>{s===null&&(s=d)}),i.on("finish",()=>{l=!0,u||r(s)}),u&&i.on("close",()=>r(s||(l?null:iX)))}return i;function o(l,u,d,f){l.on("error",f),l.on("close",h);function h(){if(u&&l._readableState&&!l._readableState.ended||d&&l._writableState&&!l._writableState.ended)return f(iX)}}function c(l){if(!(!l||s)){s=l;for(let u of n)u.destroy(l)}}}function m8t(e){return e}function D9e(e){return!!e._readableState||!!e._writableState}function Kk(e){return typeof e._duplexState=="number"&&D9e(e)}function g8t(e){return!!e._readableState&&e._readableState.ended}function y8t(e){return!!e._writableState&&e._writableState.ended}function v8t(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===CU?null:n}function b8t(e){return Kk(e)&&e.readable}function S8t(e){return(e._duplexState&Yd)!==Yd||(e._duplexState&DU)!==0}function _8t(e){return typeof e=="object"&&e!==null&&typeof e.byteLength=="number"}function U9e(e){return _8t(e)?e.byteLength:1024}function b9e(){}function w8t(){this.destroy(new Error("Stream aborted."))}function I8t(e){return e._writev!==PU.prototype._writev&&e._writev!==Yk.prototype._writev}B9e.exports={pipeline:M9e,pipelinePromise:h8t,isStream:D9e,isStreamx:Kk,isEnded:g8t,isFinished:y8t,isDisturbed:S8t,getStreamError:v8t,Stream:Wk,Writable:PU,Readable:AU,Duplex:Yk,Transform:RU,PassThrough:dX}});var wX=S(Aw=>{var An=Iw(),x8t="0000000000000000000",E8t="7777777777777777777",UU=48,F9e=An.from([117,115,116,97,114,0]),T8t=An.from([UU,UU]),k8t=An.from([117,115,116,97,114,32]),O8t=An.from([32,0]),A8t=4095,eO=257,_X=263;Aw.decodeLongPath=function(t,n){return Ow(t,0,t.length,n)};Aw.encodePax=function(t){let n="";t.name&&(n+=SX(" path="+t.name+`
|
|
247
247
|
`)),t.linkname&&(n+=SX(" linkpath="+t.linkname+`
|
|
248
248
|
`));let r=t.pax;if(r)for(let a in r)n+=SX(" "+a+"="+r[a]+`
|
|
249
|
-
`);return An.from(n)};Aw.decodePax=function(t){let n={};for(;t.length;){let r=0;for(;r<t.length&&t[r]!==32;)r++;let a=parseInt(An.toString(t.subarray(0,r)),10);if(!a)return n;let i=An.toString(t.subarray(r+1,a-1)),s=i.indexOf("=");if(s===-1)return n;n[i.slice(0,s)]=i.slice(s+1),t=t.subarray(a)}return n};Aw.encode=function(t){let n=An.alloc(512),r=t.name,a="";if(t.typeflag===5&&r[r.length-1]!=="/"&&(r+="/"),An.byteLength(r)!==r.length)return null;for(;An.byteLength(r)>100;){let i=r.indexOf("/");if(i===-1)return null;a+=a?"/"+r.slice(0,i):r.slice(0,i),r=r.slice(i+1)}return An.byteLength(r)>100||An.byteLength(a)>155||t.linkname&&An.byteLength(t.linkname)>100?null:(An.write(n,r),An.write(n,um(t.mode&A8t,6),100),An.write(n,um(t.uid,6),108),An.write(n,um(t.gid,6),116),U8t(t.size,n,124),An.write(n,um(t.mtime.getTime()/1e3|0,11),136),n[156]=UU+M8t(t.type),t.linkname&&An.write(n,t.linkname,157),An.copy(F9e,n,eO),An.copy(T8t,n,_X),t.uname&&An.write(n,t.uname,265),t.gname&&An.write(n,t.gname,297),An.write(n,um(t.devmajor||0,6),329),An.write(n,um(t.devminor||0,6),337),a&&An.write(n,a,345),An.write(n,um(V9e(n),6),148),n)};Aw.decode=function(t,n,r){let a=t[156]===0?0:t[156]-UU,i=Ow(t,0,100,n),s=lm(t,100,8),o=lm(t,108,8),c=lm(t,116,8),l=lm(t,124,12),u=lm(t,136,12),d=N8t(a),f=t[157]===0?null:Ow(t,157,100,n),h=Ow(t,265,32),g=Ow(t,297,32),v=lm(t,329,8),b=lm(t,337,8),y=V9e(t);if(y===8*32)return null;if(y!==lm(t,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(P8t(t))t[345]&&(i=Ow(t,345,155,n)+"/"+i);else if(!R8t(t)){if(!r)throw new Error("Invalid tar header: unknown format.")}return a===0&&i&&i[i.length-1]==="/"&&(a=5),{name:i,mode:s,uid:o,gid:c,size:l,mtime:new Date(1e3*u),type:d,linkname:f,uname:h,gname:g,devmajor:v,devminor:b,pax:null}};function P8t(e){return An.equals(F9e,e.subarray(eO,eO+6))}function R8t(e){return An.equals(k8t,e.subarray(eO,eO+6))&&An.equals(O8t,e.subarray(_X,_X+2))}function C8t(e,t,n){return typeof e!="number"?n:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)}function N8t(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function M8t(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function L9e(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function V9e(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function um(e,t){return e=e.toString(8),e.length>t?E8t.slice(0,t)+" ":x8t.slice(0,t-e.length)+e+" "}function D8t(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function U8t(e,t,n){e.toString(8).length>11?D8t(e,t,n):An.write(t,um(e,11),n)}function B8t(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let s=e[r];t?n.push(s):n.push(255-s)}let a=0,i=n.length;for(r=0;r<i;r++)a+=n[r]*Math.pow(256,r);return t?a:-1*a}function lm(e,t,n){if(e=e.subarray(t,t+n),t=0,e[t]&128)return B8t(e);{for(;t<e.length&&e[t]===32;)t++;let r=C8t(L9e(e,32,t,e.length),e.length,e.length);for(;t<r&&e[t]===0;)t++;return r===t?0:parseInt(An.toString(e.subarray(t,r)),8)}}function Ow(e,t,n,r){return An.toString(e.subarray(t,L9e(e,0,t,t+n)),r)}function SX(e){let t=An.byteLength(e),n=Math.floor(Math.log(t)/Math.log(10))+1;return t+n>=Math.pow(10,n)&&n++,t+n+e}});var J9e=S((rEn,G9e)=>{var{Writable:F8t,Readable:L8t,getStreamError:q9e}=bX(),V8t=rX(),$9e=Iw(),Pw=wX(),q8t=$9e.alloc(0),xX=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new V8t,this._offset=0}push(t){this.buffered+=t.byteLength,this.queue.push(t)}shiftFirst(t){return this._buffered===0?null:this._next(t)}shift(t){if(t>this.buffered)return null;if(t===0)return q8t;let n=this._next(t);if(t===n.byteLength)return n;let r=[n];for(;(t-=n.byteLength)>0;)n=this._next(t),r.push(n);return $9e.concat(r)}_next(t){let n=this.queue.peek(),r=n.byteLength-this._offset;if(t>=r){let a=this._offset?n.subarray(this._offset,n.byteLength):n;return this.queue.shift(),this._offset=0,this.buffered-=r,this.shifted+=r,a}return this.buffered-=t,this.shifted+=t,n.subarray(this._offset,this._offset+=t)}},EX=class extends L8t{constructor(t,n,r){super(),this.header=n,this.offset=r,this._parent=t}_read(t){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),t(null)}_predestroy(){this._parent.destroy(q9e(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=z9e(this.header.size),this._parent._update())}_destroy(t){this._detach(),t(null)}},TX=class extends F8t{constructor(t){super(t),t||(t={}),this._buffer=new xX,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=IX,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=t.filenameEncoding||"utf-8",this._allowUnknownFormat=!!t.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(t){if(this._locked=!1,t){this.destroy(t),this._continueWrite(t);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=Pw.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(t){return this._continueWrite(t),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory"?(this.emit("entry",this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&(this._header.name=this._gnuLongPath,this._gnuLongPath=null),this._gnuLongLinkPath&&(this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null),this._pax&&(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,this._pax=null)}_decodeLongHeader(t){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=Pw.decodeLongPath(t,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=Pw.decodeLongPath(t,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=Pw.decodePax(t);break;case"pax-header":this._pax=this._paxGlobal===null?Pw.decodePax(t):Object.assign({},this._paxGlobal,Pw.decodePax(t));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=z9e(this._header.size);let t=this._buffer.shift(this._header.size);try{this._decodeLongHeader(t)}catch(n){return this._continueWrite(n),!1}return!0}_consumeStream(){let t=this._buffer.shiftFirst(this._missing);if(t===null)return!1;this._missing-=t.byteLength;let n=this._stream.push(t);return this._missing===0?(this._stream.push(null),n&&this._stream._detach(),n&&this._locked===!1):n}_createStream(){return new EX(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let t=this._buffer.shiftFirst(this._missing);t!==null&&(this._missing-=t.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(t){let n=this._callback;this._callback=IX,n(t)}_write(t,n){this._callback=n,this._buffer.push(t),this._update()}_final(t){this._finished=this._missing===0&&this._buffer.buffered===0,t(this._finished?null:new Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy(t){this._stream&&this._stream.destroy(q9e(this)),t(null)}[Symbol.asyncIterator](){let t=null,n=null,r=null,a=null,i=null,s=this;return this.on("entry",l),this.on("error",f=>{t=f}),this.on("close",u),{[Symbol.asyncIterator](){return this},next(){return new Promise(c)},return(){return d(null)},throw(f){return d(f)}};function o(f){if(!i)return;let h=i;i=null,h(f)}function c(f,h){if(t)return h(t);if(a){f({value:a,done:!1}),a=null;return}n=f,r=h,o(null),s._finished&&n&&(n({value:void 0,done:!0}),n=r=null)}function l(f,h,g){i=g,h.on("error",IX),n?(n({value:h,done:!1}),n=r=null):a=h}function u(){o(t),n&&(t?r(t):n({value:void 0,done:!0}),n=r=null)}function d(f){return s.destroy(f),o(f),new Promise((h,g)=>{if(s.destroyed)return h({value:void 0,done:!0});s.once("close",function(){f?g(f):h({value:void 0,done:!0})})})}}};G9e.exports=function(t){return new TX(t)};function IX(){}function z9e(e){return e&=511,e&&512-e}});var W9e=S((iEn,kX)=>{var H9e={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{kX.exports=require("fs").constants||H9e}catch{kX.exports=H9e}});var Z9e=S((aEn,X9e)=>{var{Readable:$8t,Writable:z8t,getStreamError:Y9e}=bX(),fv=Iw(),Rw=W9e(),BU=wX(),G8t=493,J8t=420,K9e=fv.alloc(1024),AX=class extends z8t{constructor(t,n,r){super({mapWritable:W8t,eagerOpen:!0}),this.written=0,this.header=n,this._callback=r,this._linkname=null,this._isLinkname=n.type==="symlink"&&!n.linkname,this._isVoid=n.type!=="file"&&n.type!=="contiguous-file",this._finished=!1,this._pack=t,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(t){this._openCallback=t,this._pack._stream===this&&this._continueOpen()}_continuePack(t){if(this._callback===null)return;let n=this._callback;this._callback=null,n(t)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let t=this._openCallback;if(this._openCallback=null,t!==null){if(this._pack.destroying)return t(new Error("pack stream destroyed"));if(this._pack._finalized)return t(new Error("pack stream is already finalized"));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),t(null)}}_write(t,n){if(this._isLinkname)return this._linkname=this._linkname?fv.concat([this._linkname,t]):t,n(null);if(this._isVoid)return t.byteLength>0?n(new Error("No body allowed for this entry")):n();if(this.written+=t.byteLength,this._pack.push(t))return n();this._pack._drain=n}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?fv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),j9e(this._pack,this.header.size),this._pack._done(this))}_final(t){if(this.written!==this.header.size)return t(new Error("Size mismatch"));this._finish(),t(null)}_getError(){return Y9e(this)||new Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(t){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),t()}},PX=class extends $8t{constructor(t){super(t),this._drain=OX,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(t,n,r){if(this._finalized||this.destroying)throw new Error("already finalized or destroyed");typeof n=="function"&&(r=n,n=null),r||(r=OX),(!t.size||t.type==="symlink")&&(t.size=0),t.type||(t.type=H8t(t.mode)),t.mode||(t.mode=t.type==="directory"?G8t:J8t),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof n=="string"&&(n=fv.from(n));let a=new AX(this,t,r);return fv.isBuffer(n)?(t.size=n.byteLength,a.write(n),a.end(),a):(a._isVoid,a)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(K9e),this.push(null))}_done(t){t===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(t){if(!t.pax){let n=BU.encode(t);if(n){this.push(n);return}}this._encodePax(t)}_encodePax(t){let n=BU.encodePax({name:t.name,linkname:t.linkname,pax:t.pax}),r={name:"PaxHeader",mode:t.mode,uid:t.uid,gid:t.gid,size:n.byteLength,mtime:t.mtime,type:"pax-header",linkname:t.linkname&&"PaxHeader",uname:t.uname,gname:t.gname,devmajor:t.devmajor,devminor:t.devminor};this.push(BU.encode(r)),this.push(n),j9e(this,n.byteLength),r.size=t.size,r.type=t.type,this.push(BU.encode(r))}_doDrain(){let t=this._drain;this._drain=OX,t()}_predestroy(){let t=Y9e(this);for(this._stream&&this._stream.destroy(t);this._pending.length;){let n=this._pending.shift();n.destroy(t),n._continueOpen()}this._doDrain()}_read(t){this._doDrain(),t()}};X9e.exports=function(t){return new PX(t)};function H8t(e){switch(e&Rw.S_IFMT){case Rw.S_IFBLK:return"block-device";case Rw.S_IFCHR:return"character-device";case Rw.S_IFDIR:return"directory";case Rw.S_IFIFO:return"fifo";case Rw.S_IFLNK:return"symlink"}return"file"}function OX(){}function j9e(e,t){t&=511,t&&e.push(K9e.subarray(0,512-t))}function W8t(e){return fv.isBuffer(e)?e:fv.from(e)}});var CX=S(RX=>{RX.extract=J9e();RX.pack=Z9e()});var mKe={};Bu(mKe,{EVOLVE_IMAGE_VERSION:()=>FU,MODAL_MAX_LIFETIME_MS:()=>FX,MODAL_MAX_LIST_SANDBOXES:()=>BX,MODAL_STDIN_CHUNK_BYTES:()=>tO,ModalCommands:()=>fKe,ModalFiles:()=>pKe,ModalIdleTimeoutError:()=>NX,ModalNetworkPolicyError:()=>UX,ModalProvider:()=>qX,ModalResourcesError:()=>DX,ModalSandboxLifetimeError:()=>aKe,_testBuildSandboxInfo:()=>lWt,_testCollectSandboxes:()=>uWt,_testDynamicNetworkPolicyParams:()=>aWt,_testImageMap:()=>rWt,_testMapIdleTimeout:()=>fWt,_testMapNetworkPolicy:()=>iWt,_testMapResources:()=>oWt,_testRequiresDynamicNetwork:()=>sWt,_testResolveImageRegistry:()=>cWt,_testValidateTimeout:()=>dWt,_testWrapCommand:()=>nWt,createModalProvider:()=>VU});async function*Y8t(e){let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;r&&(yield r)}}finally{t.releaseLock()}}function sKe(e){if(e>FX)throw new aKe(e)}function oKe(e){if(e===void 0)return{};if(!Number.isFinite(e)||e<=0)throw new NX(e,"it must be a positive number of milliseconds");if(e>FX)throw new NX(e,"it exceeds Modal's 24h lifetime cap, so the sandbox would always die of the lifetime first");return{idleTimeoutMs:e}}function MX(e,t,n,r){let a="";r&&Object.keys(r).length>0&&(a=Object.entries(r).filter(([,o])=>o!=null).map(([o,c])=>`export ${o}='${String(c).replace(/'/g,"'\\''")}'`).join("; ")+"; ");let i=n?`cd '${n.replace(/'/g,"'\\''")}' && ${a}${e}`:`${a}${e}`;if(t==="root")return["bash","-c",i];let s=Buffer.from(i).toString("base64");return["su",t,"-c",`echo ${s} | base64 -d | bash`]}function cKe(e){if(e?.disk!==void 0)throw new DX(`Modal's JS SDK has no create-time disk-size parameter, so a ${e.disk} GiB disk request cannot be enforced. Drop \`resources.disk\` (containers get Modal's default disk quota) or run on a provider that sizes disk.`);if((e?.gpu===void 0||e.gpu<=0)&&e?.gpuTypes?.length)throw new DX("resources.gpuTypes was set without a positive resources.gpu count \u2014 declare how many GPUs to reserve, or drop gpuTypes.");let t=e?.gpu!==void 0&&e.gpu>0?`${e.gpuTypes?.length?e.gpuTypes[0]:"any"}:${e.gpu}`:void 0;return{cpu:e?.cpu??K8t,memoryMiB:e?.memory!==void 0?Math.ceil(e.memory*1024):j8t,...t!==void 0?{gpu:t}:{}}}function lKe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function X8t(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!lKe(e)}function Z8t(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function Q8t(e){return/^[^:]+:\d+$/.test(e)}function LX(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{}}let t=e.allowedDestinations??[];if(t.length===0)return{blockNetwork:!0};let n=[],r=[];for(let a of t)if(lKe(a))n.push(a.includes("/")?a:`${a}/32`);else{if(X8t(a))throw new UX("invalid-ipv4",`"${a}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,a);if(Z8t(a))n.push(a.includes("/")?a:`${a}/128`);else{if(Q8t(a))throw new UX("port-unsupported",`Modal's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${a}" and list just the host or IP.`,a);r.push(a)}}return{outboundCidrAllowlist:n,outboundDomainAllowlist:r}}function LU(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{outboundCidrAllowlist:["0.0.0.0/0"],outboundDomainAllowlist:["*"]}}let t=LX(e);return{outboundCidrAllowlist:t.outboundCidrAllowlist??[],outboundDomainAllowlist:tWt(t.outboundDomainAllowlist??[])}}function tWt(e){return e.length>0?e:[eWt]}function uKe(e,t){if(!t||t.length===0)return!1;let n=a=>a===void 0?"open|":`${a.outbound}|${[...new Set(a.allowedDestinations??[])].sort().join(",")}`,r=n(e);return t.some(a=>n(a)!==r)}function dKe(e){let t=e.split("/")[0];return/^\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com$/.test(t)?"aws-ecr":t==="gcr.io"||t.endsWith(".gcr.io")||t.endsWith("-docker.pkg.dev")?"gcp-artifact-registry":"registry"}function VX(e,t,n){let{[rKe]:r,[iKe]:a,...i}=t;return{sandboxId:e,image:r??n??"",metadata:i,startedAt:a??""}}async function hKe(e,t){let n=[];try{for await(let r of e()){if(t!==void 0&&n.length>=t)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!0,error:`stopped at the requested limit of ${t} with more sandboxes available`};if(n.length>=BX)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list exceeded ${BX} sandboxes`};let a=await r.getTags();n.push(VX(r.sandboxId,a))}}catch(r){return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list failed: ${r instanceof Error?r.message:String(r)}`}}return{sandboxes:n,complete:!0,pagesFetched:n.length,stoppedAtLimit:!1}}function VU(e={}){let t=e.tokenId??process.env.MODAL_TOKEN_ID,n=e.tokenSecret??process.env.MODAL_TOKEN_SECRET;if(!t||!n)throw new Error("Modal credentials required. Set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables, or pass tokenId/tokenSecret in config. Get your token at https://modal.com/settings/tokens");return new qX({...e,tokenId:t,tokenSecret:n})}var tKe,FU,nKe,FX,tO,Q9e,rKe,iKe,aKe,NX,DX,K8t,j8t,UX,eWt,BX,fKe,pKe,eKe,qX,nWt,rWt,iWt,aWt,sWt,oWt,cWt,lWt,uWt,dWt,fWt,qU=Q(()=>{"use strict";t9e();tKe=Ve(CX(),1),FU="c-7bcda3467a79",nKe={[`evolve-all-${FU}`]:`evolvingmachines/evolve-all:${FU}`,"evolve-all":"evolvingmachines/evolve-all"},FX=1440*60*1e3,tO=8*1024*1024;Q9e="user",rKe="evolve.image",iKe="evolve.startedAt",aKe=class extends Error{requestedTimeoutMs;constructor(e){let t=(e/36e5).toFixed(1);super(`Modal sandboxes have a hard 24h lifetime cap; requested timeout was ${t}h. For sessions longer than 24h, persist progress with Evolve checkpoints and resume in a fresh sandbox instead of extending the timeout.`),this.name="ModalSandboxLifetimeError",this.requestedTimeoutMs=e}};NX=class extends Error{requestedIdleTimeoutMs;constructor(e,t){super(`Modal idleTimeoutMs of ${e}ms is invalid: ${t}`),this.name="ModalIdleTimeoutError",this.requestedIdleTimeoutMs=e}};DX=class extends Error{constructor(e){super(e),this.name="ModalResourcesError"}},K8t=4,j8t=4096;UX=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="ModalNetworkPolicyError",this.reason=e,this.destination=n}};eWt="sealed.invalid";BX=1e4,fKe=class{constructor(e,t){this.sandbox=e,this.user=t}async run(e,t){let n=MX(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),{stdout:a,stderr:i}=await this.accumulateStreams(r,t?.onStdout,t?.onStderr);return{exitCode:await r.wait(),stdout:a,stderr:i}}async spawn(e,t){let n=MX(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),a="",i="",s=this.accumulateStreams(r,t?.onStdout?o=>{t.onStdout(o)}:void 0,t?.onStderr?o=>{t.onStderr(o)}:void 0).then(({stdout:o,stderr:c})=>{a=o,i=c}).catch(()=>{});return{processId:`modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:async()=>(await s,{exitCode:await r.wait(),stdout:a,stderr:i}),kill:async()=>!1}}async list(){let e=await this.sandbox.exec(["ps","-eo","pid,comm,args"],{timeoutMs:1e4});return await e.wait(),(await e.stdout.readText()).trim().split(`
|
|
249
|
+
`);return An.from(n)};Aw.decodePax=function(t){let n={};for(;t.length;){let r=0;for(;r<t.length&&t[r]!==32;)r++;let a=parseInt(An.toString(t.subarray(0,r)),10);if(!a)return n;let i=An.toString(t.subarray(r+1,a-1)),s=i.indexOf("=");if(s===-1)return n;n[i.slice(0,s)]=i.slice(s+1),t=t.subarray(a)}return n};Aw.encode=function(t){let n=An.alloc(512),r=t.name,a="";if(t.typeflag===5&&r[r.length-1]!=="/"&&(r+="/"),An.byteLength(r)!==r.length)return null;for(;An.byteLength(r)>100;){let i=r.indexOf("/");if(i===-1)return null;a+=a?"/"+r.slice(0,i):r.slice(0,i),r=r.slice(i+1)}return An.byteLength(r)>100||An.byteLength(a)>155||t.linkname&&An.byteLength(t.linkname)>100?null:(An.write(n,r),An.write(n,um(t.mode&A8t,6),100),An.write(n,um(t.uid,6),108),An.write(n,um(t.gid,6),116),U8t(t.size,n,124),An.write(n,um(t.mtime.getTime()/1e3|0,11),136),n[156]=UU+M8t(t.type),t.linkname&&An.write(n,t.linkname,157),An.copy(F9e,n,eO),An.copy(T8t,n,_X),t.uname&&An.write(n,t.uname,265),t.gname&&An.write(n,t.gname,297),An.write(n,um(t.devmajor||0,6),329),An.write(n,um(t.devminor||0,6),337),a&&An.write(n,a,345),An.write(n,um(V9e(n),6),148),n)};Aw.decode=function(t,n,r){let a=t[156]===0?0:t[156]-UU,i=Ow(t,0,100,n),s=lm(t,100,8),o=lm(t,108,8),c=lm(t,116,8),l=lm(t,124,12),u=lm(t,136,12),d=N8t(a),f=t[157]===0?null:Ow(t,157,100,n),h=Ow(t,265,32),g=Ow(t,297,32),v=lm(t,329,8),b=lm(t,337,8),y=V9e(t);if(y===8*32)return null;if(y!==lm(t,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(P8t(t))t[345]&&(i=Ow(t,345,155,n)+"/"+i);else if(!R8t(t)){if(!r)throw new Error("Invalid tar header: unknown format.")}return a===0&&i&&i[i.length-1]==="/"&&(a=5),{name:i,mode:s,uid:o,gid:c,size:l,mtime:new Date(1e3*u),type:d,linkname:f,uname:h,gname:g,devmajor:v,devminor:b,pax:null}};function P8t(e){return An.equals(F9e,e.subarray(eO,eO+6))}function R8t(e){return An.equals(k8t,e.subarray(eO,eO+6))&&An.equals(O8t,e.subarray(_X,_X+2))}function C8t(e,t,n){return typeof e!="number"?n:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)}function N8t(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function M8t(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function L9e(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function V9e(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function um(e,t){return e=e.toString(8),e.length>t?E8t.slice(0,t)+" ":x8t.slice(0,t-e.length)+e+" "}function D8t(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function U8t(e,t,n){e.toString(8).length>11?D8t(e,t,n):An.write(t,um(e,11),n)}function B8t(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let s=e[r];t?n.push(s):n.push(255-s)}let a=0,i=n.length;for(r=0;r<i;r++)a+=n[r]*Math.pow(256,r);return t?a:-1*a}function lm(e,t,n){if(e=e.subarray(t,t+n),t=0,e[t]&128)return B8t(e);{for(;t<e.length&&e[t]===32;)t++;let r=C8t(L9e(e,32,t,e.length),e.length,e.length);for(;t<r&&e[t]===0;)t++;return r===t?0:parseInt(An.toString(e.subarray(t,r)),8)}}function Ow(e,t,n,r){return An.toString(e.subarray(t,L9e(e,0,t,t+n)),r)}function SX(e){let t=An.byteLength(e),n=Math.floor(Math.log(t)/Math.log(10))+1;return t+n>=Math.pow(10,n)&&n++,t+n+e}});var J9e=S((rEn,G9e)=>{var{Writable:F8t,Readable:L8t,getStreamError:q9e}=bX(),V8t=rX(),$9e=Iw(),Pw=wX(),q8t=$9e.alloc(0),xX=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new V8t,this._offset=0}push(t){this.buffered+=t.byteLength,this.queue.push(t)}shiftFirst(t){return this._buffered===0?null:this._next(t)}shift(t){if(t>this.buffered)return null;if(t===0)return q8t;let n=this._next(t);if(t===n.byteLength)return n;let r=[n];for(;(t-=n.byteLength)>0;)n=this._next(t),r.push(n);return $9e.concat(r)}_next(t){let n=this.queue.peek(),r=n.byteLength-this._offset;if(t>=r){let a=this._offset?n.subarray(this._offset,n.byteLength):n;return this.queue.shift(),this._offset=0,this.buffered-=r,this.shifted+=r,a}return this.buffered-=t,this.shifted+=t,n.subarray(this._offset,this._offset+=t)}},EX=class extends L8t{constructor(t,n,r){super(),this.header=n,this.offset=r,this._parent=t}_read(t){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),t(null)}_predestroy(){this._parent.destroy(q9e(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=z9e(this.header.size),this._parent._update())}_destroy(t){this._detach(),t(null)}},TX=class extends F8t{constructor(t){super(t),t||(t={}),this._buffer=new xX,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=IX,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=t.filenameEncoding||"utf-8",this._allowUnknownFormat=!!t.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(t){if(this._locked=!1,t){this.destroy(t),this._continueWrite(t);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=Pw.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(t){return this._continueWrite(t),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory"?(this.emit("entry",this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&(this._header.name=this._gnuLongPath,this._gnuLongPath=null),this._gnuLongLinkPath&&(this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null),this._pax&&(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,this._pax=null)}_decodeLongHeader(t){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=Pw.decodeLongPath(t,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=Pw.decodeLongPath(t,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=Pw.decodePax(t);break;case"pax-header":this._pax=this._paxGlobal===null?Pw.decodePax(t):Object.assign({},this._paxGlobal,Pw.decodePax(t));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=z9e(this._header.size);let t=this._buffer.shift(this._header.size);try{this._decodeLongHeader(t)}catch(n){return this._continueWrite(n),!1}return!0}_consumeStream(){let t=this._buffer.shiftFirst(this._missing);if(t===null)return!1;this._missing-=t.byteLength;let n=this._stream.push(t);return this._missing===0?(this._stream.push(null),n&&this._stream._detach(),n&&this._locked===!1):n}_createStream(){return new EX(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let t=this._buffer.shiftFirst(this._missing);t!==null&&(this._missing-=t.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(t){let n=this._callback;this._callback=IX,n(t)}_write(t,n){this._callback=n,this._buffer.push(t),this._update()}_final(t){this._finished=this._missing===0&&this._buffer.buffered===0,t(this._finished?null:new Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy(t){this._stream&&this._stream.destroy(q9e(this)),t(null)}[Symbol.asyncIterator](){let t=null,n=null,r=null,a=null,i=null,s=this;return this.on("entry",l),this.on("error",f=>{t=f}),this.on("close",u),{[Symbol.asyncIterator](){return this},next(){return new Promise(c)},return(){return d(null)},throw(f){return d(f)}};function o(f){if(!i)return;let h=i;i=null,h(f)}function c(f,h){if(t)return h(t);if(a){f({value:a,done:!1}),a=null;return}n=f,r=h,o(null),s._finished&&n&&(n({value:void 0,done:!0}),n=r=null)}function l(f,h,g){i=g,h.on("error",IX),n?(n({value:h,done:!1}),n=r=null):a=h}function u(){o(t),n&&(t?r(t):n({value:void 0,done:!0}),n=r=null)}function d(f){return s.destroy(f),o(f),new Promise((h,g)=>{if(s.destroyed)return h({value:void 0,done:!0});s.once("close",function(){f?g(f):h({value:void 0,done:!0})})})}}};G9e.exports=function(t){return new TX(t)};function IX(){}function z9e(e){return e&=511,e&&512-e}});var W9e=S((iEn,kX)=>{var H9e={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{kX.exports=require("fs").constants||H9e}catch{kX.exports=H9e}});var Z9e=S((aEn,X9e)=>{var{Readable:$8t,Writable:z8t,getStreamError:Y9e}=bX(),fv=Iw(),Rw=W9e(),BU=wX(),G8t=493,J8t=420,K9e=fv.alloc(1024),AX=class extends z8t{constructor(t,n,r){super({mapWritable:W8t,eagerOpen:!0}),this.written=0,this.header=n,this._callback=r,this._linkname=null,this._isLinkname=n.type==="symlink"&&!n.linkname,this._isVoid=n.type!=="file"&&n.type!=="contiguous-file",this._finished=!1,this._pack=t,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(t){this._openCallback=t,this._pack._stream===this&&this._continueOpen()}_continuePack(t){if(this._callback===null)return;let n=this._callback;this._callback=null,n(t)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let t=this._openCallback;if(this._openCallback=null,t!==null){if(this._pack.destroying)return t(new Error("pack stream destroyed"));if(this._pack._finalized)return t(new Error("pack stream is already finalized"));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),t(null)}}_write(t,n){if(this._isLinkname)return this._linkname=this._linkname?fv.concat([this._linkname,t]):t,n(null);if(this._isVoid)return t.byteLength>0?n(new Error("No body allowed for this entry")):n();if(this.written+=t.byteLength,this._pack.push(t))return n();this._pack._drain=n}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?fv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),j9e(this._pack,this.header.size),this._pack._done(this))}_final(t){if(this.written!==this.header.size)return t(new Error("Size mismatch"));this._finish(),t(null)}_getError(){return Y9e(this)||new Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(t){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),t()}},PX=class extends $8t{constructor(t){super(t),this._drain=OX,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(t,n,r){if(this._finalized||this.destroying)throw new Error("already finalized or destroyed");typeof n=="function"&&(r=n,n=null),r||(r=OX),(!t.size||t.type==="symlink")&&(t.size=0),t.type||(t.type=H8t(t.mode)),t.mode||(t.mode=t.type==="directory"?G8t:J8t),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof n=="string"&&(n=fv.from(n));let a=new AX(this,t,r);return fv.isBuffer(n)?(t.size=n.byteLength,a.write(n),a.end(),a):(a._isVoid,a)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(K9e),this.push(null))}_done(t){t===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(t){if(!t.pax){let n=BU.encode(t);if(n){this.push(n);return}}this._encodePax(t)}_encodePax(t){let n=BU.encodePax({name:t.name,linkname:t.linkname,pax:t.pax}),r={name:"PaxHeader",mode:t.mode,uid:t.uid,gid:t.gid,size:n.byteLength,mtime:t.mtime,type:"pax-header",linkname:t.linkname&&"PaxHeader",uname:t.uname,gname:t.gname,devmajor:t.devmajor,devminor:t.devminor};this.push(BU.encode(r)),this.push(n),j9e(this,n.byteLength),r.size=t.size,r.type=t.type,this.push(BU.encode(r))}_doDrain(){let t=this._drain;this._drain=OX,t()}_predestroy(){let t=Y9e(this);for(this._stream&&this._stream.destroy(t);this._pending.length;){let n=this._pending.shift();n.destroy(t),n._continueOpen()}this._doDrain()}_read(t){this._doDrain(),t()}};X9e.exports=function(t){return new PX(t)};function H8t(e){switch(e&Rw.S_IFMT){case Rw.S_IFBLK:return"block-device";case Rw.S_IFCHR:return"character-device";case Rw.S_IFDIR:return"directory";case Rw.S_IFIFO:return"fifo";case Rw.S_IFLNK:return"symlink"}return"file"}function OX(){}function j9e(e,t){t&=511,t&&e.push(K9e.subarray(0,512-t))}function W8t(e){return fv.isBuffer(e)?e:fv.from(e)}});var CX=S(RX=>{RX.extract=J9e();RX.pack=Z9e()});var mKe={};Bu(mKe,{EVOLVE_IMAGE_VERSION:()=>FU,MODAL_MAX_LIFETIME_MS:()=>FX,MODAL_MAX_LIST_SANDBOXES:()=>BX,MODAL_STDIN_CHUNK_BYTES:()=>tO,ModalCommands:()=>fKe,ModalFiles:()=>pKe,ModalIdleTimeoutError:()=>NX,ModalNetworkPolicyError:()=>UX,ModalProvider:()=>qX,ModalResourcesError:()=>DX,ModalSandboxLifetimeError:()=>aKe,_testBuildSandboxInfo:()=>lWt,_testCollectSandboxes:()=>uWt,_testDynamicNetworkPolicyParams:()=>aWt,_testImageMap:()=>rWt,_testMapIdleTimeout:()=>fWt,_testMapNetworkPolicy:()=>iWt,_testMapResources:()=>oWt,_testRequiresDynamicNetwork:()=>sWt,_testResolveImageRegistry:()=>cWt,_testValidateTimeout:()=>dWt,_testWrapCommand:()=>nWt,createModalProvider:()=>VU});async function*Y8t(e){let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;r&&(yield r)}}finally{t.releaseLock()}}function sKe(e){if(e>FX)throw new aKe(e)}function oKe(e){if(e===void 0)return{};if(!Number.isFinite(e)||e<=0)throw new NX(e,"it must be a positive number of milliseconds");if(e>FX)throw new NX(e,"it exceeds Modal's 24h lifetime cap, so the sandbox would always die of the lifetime first");return{idleTimeoutMs:e}}function MX(e,t,n,r){let a="";r&&Object.keys(r).length>0&&(a=Object.entries(r).filter(([,o])=>o!=null).map(([o,c])=>`export ${o}='${String(c).replace(/'/g,"'\\''")}'`).join("; ")+"; ");let i=n?`cd '${n.replace(/'/g,"'\\''")}' && ${a}${e}`:`${a}${e}`;if(t==="root")return["bash","-c",i];let s=Buffer.from(i).toString("base64");return["su",t,"-c",`echo ${s} | base64 -d | bash`]}function cKe(e){if(e?.disk!==void 0)throw new DX(`Modal's JS SDK has no create-time disk-size parameter, so a ${e.disk} GiB disk request cannot be enforced. Drop \`resources.disk\` (containers get Modal's default disk quota) or run on a provider that sizes disk.`);if((e?.gpu===void 0||e.gpu<=0)&&e?.gpuTypes?.length)throw new DX("resources.gpuTypes was set without a positive resources.gpu count \u2014 declare how many GPUs to reserve, or drop gpuTypes.");let t=e?.gpu!==void 0&&e.gpu>0?`${e.gpuTypes?.length?e.gpuTypes[0]:"any"}:${e.gpu}`:void 0;return{cpu:e?.cpu??K8t,memoryMiB:e?.memory!==void 0?Math.ceil(e.memory*1024):j8t,...t!==void 0?{gpu:t}:{}}}function lKe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function X8t(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!lKe(e)}function Z8t(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function Q8t(e){return/^[^:]+:\d+$/.test(e)}function LX(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{}}let t=e.allowedDestinations??[];if(t.length===0)return{blockNetwork:!0};let n=[],r=[];for(let a of t)if(lKe(a))n.push(a.includes("/")?a:`${a}/32`);else{if(X8t(a))throw new UX("invalid-ipv4",`"${a}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,a);if(Z8t(a))n.push(a.includes("/")?a:`${a}/128`);else{if(Q8t(a))throw new UX("port-unsupported",`Modal's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${a}" and list just the host or IP.`,a);r.push(a)}}return{outboundCidrAllowlist:n,outboundDomainAllowlist:r}}function LU(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{outboundCidrAllowlist:["0.0.0.0/0"],outboundDomainAllowlist:["*"]}}let t=LX(e);return{outboundCidrAllowlist:t.outboundCidrAllowlist??[],outboundDomainAllowlist:tWt(t.outboundDomainAllowlist??[])}}function tWt(e){return e.length>0?e:[eWt]}function uKe(e,t){if(!t||t.length===0)return!1;let n=a=>a===void 0?"open|":`${a.outbound}|${[...new Set(a.allowedDestinations??[])].sort().join(",")}`,r=n(e);return t.some(a=>n(a)!==r)}function dKe(e){let t=e.split("/")[0];return/^\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com$/.test(t)?"aws-ecr":t==="gcr.io"||t.endsWith(".gcr.io")||t.endsWith("-docker.pkg.dev")?"gcp-artifact-registry":"registry"}function VX(e,t,n){let{[rKe]:r,[iKe]:a,...i}=t;return{sandboxId:e,image:r??n??"",metadata:i,startedAt:a??""}}async function hKe(e,t){let n=[];try{for await(let r of e()){if(t!==void 0&&n.length>=t)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!0,error:`stopped at the requested limit of ${t} with more sandboxes available`};if(n.length>=BX)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list exceeded ${BX} sandboxes`};let a=await r.getTags();n.push(VX(r.sandboxId,a))}}catch(r){return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list failed: ${r instanceof Error?r.message:String(r)}`}}return{sandboxes:n,complete:!0,pagesFetched:n.length,stoppedAtLimit:!1}}function VU(e={}){let t=e.tokenId??process.env.MODAL_TOKEN_ID,n=e.tokenSecret??process.env.MODAL_TOKEN_SECRET;if(!t||!n)throw new Error("Modal credentials required. Set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables, or pass tokenId/tokenSecret in config. Get your token at https://modal.com/settings/tokens");return new qX({...e,tokenId:t,tokenSecret:n})}var tKe,FU,nKe,FX,tO,Q9e,rKe,iKe,aKe,NX,DX,K8t,j8t,UX,eWt,BX,fKe,pKe,eKe,qX,nWt,rWt,iWt,aWt,sWt,oWt,cWt,lWt,uWt,dWt,fWt,qU=Q(()=>{"use strict";t9e();tKe=Ve(CX(),1),FU="c-fae503a880ec",nKe={[`evolve-all-${FU}`]:`evolvingmachines/evolve-all:${FU}`,"evolve-all":"evolvingmachines/evolve-all"},FX=1440*60*1e3,tO=8*1024*1024;Q9e="user",rKe="evolve.image",iKe="evolve.startedAt",aKe=class extends Error{requestedTimeoutMs;constructor(e){let t=(e/36e5).toFixed(1);super(`Modal sandboxes have a hard 24h lifetime cap; requested timeout was ${t}h. For sessions longer than 24h, persist progress with Evolve checkpoints and resume in a fresh sandbox instead of extending the timeout.`),this.name="ModalSandboxLifetimeError",this.requestedTimeoutMs=e}};NX=class extends Error{requestedIdleTimeoutMs;constructor(e,t){super(`Modal idleTimeoutMs of ${e}ms is invalid: ${t}`),this.name="ModalIdleTimeoutError",this.requestedIdleTimeoutMs=e}};DX=class extends Error{constructor(e){super(e),this.name="ModalResourcesError"}},K8t=4,j8t=4096;UX=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="ModalNetworkPolicyError",this.reason=e,this.destination=n}};eWt="sealed.invalid";BX=1e4,fKe=class{constructor(e,t){this.sandbox=e,this.user=t}async run(e,t){let n=MX(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),{stdout:a,stderr:i}=await this.accumulateStreams(r,t?.onStdout,t?.onStderr);return{exitCode:await r.wait(),stdout:a,stderr:i}}async spawn(e,t){let n=MX(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),a="",i="",s=this.accumulateStreams(r,t?.onStdout?o=>{t.onStdout(o)}:void 0,t?.onStderr?o=>{t.onStderr(o)}:void 0).then(({stdout:o,stderr:c})=>{a=o,i=c}).catch(()=>{});return{processId:`modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:async()=>(await s,{exitCode:await r.wait(),stdout:a,stderr:i}),kill:async()=>!1}}async list(){let e=await this.sandbox.exec(["ps","-eo","pid,comm,args"],{timeoutMs:1e4});return await e.wait(),(await e.stdout.readText()).trim().split(`
|
|
250
250
|
`).slice(1).map(t=>{let n=t.trim().split(/\s+/);return{processId:n[0],cmd:n[1]||"",args:n.slice(2),envs:{}}})}async connect(e,t){throw new Error("Modal does not support connecting to existing processes")}async sendStdin(e,t){throw new Error("Modal does not support sendStdin by process ID")}async kill(e){return await(await this.sandbox.exec(["kill","-9",e],{timeoutMs:1e4})).wait()===0}async accumulateStreams(e,t,n){let r="",a="",i=[];return i.push((async()=>{try{for await(let s of e.stdout){let o=typeof s=="string"?s:new TextDecoder().decode(s);r+=o,t?.(o)}}catch{}})()),i.push((async()=>{try{for await(let s of e.stderr){let o=typeof s=="string"?s:new TextDecoder().decode(s);a+=o,n?.(o)}}catch{}})()),await Promise.all(i),{stdout:r,stderr:a}}},pKe=class{constructor(e,t){this.sandbox=e,this.user=t}async chownToUser(e,t=!1){if(this.user==="root")return;let n=t?["chown","-R",`${this.user}:${this.user}`,e]:["chown",`${this.user}:${this.user}`,e];await(await this.sandbox.exec(n,{timeoutMs:t?3e4:1e4})).wait()}async writeStdinChunked(e,t){for(let n=0;n<t.length;n+=tO)await e.writeBytes(t.subarray(n,n+tO))}async writeStdinCoalesced(e,t){let n=[],r=0,a=async()=>{if(r===0)return;let i=n.length===1?n[0]:Buffer.concat(n,r);n=[],r=0,await this.writeStdinChunked(e,i)};for await(let i of t)n.push(i),r+=i.length,r>=tO&&await a();await a()}async read(e){let t=await this.sandbox.exec(["cat",e],{timeoutMs:3e5,mode:"binary"}),n=await t.wait();if(n!==0){let a=await t.stderr.readText();throw new Error(`Failed to read file ${e}: ${a||`exit code ${n}`}`)}let r=await t.stdout.readBytes();if(!r.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(r)}catch{}return r}async write(e,t){let n=this.toBuffer(t),r=e.substring(0,e.lastIndexOf("/"));r&&await this.makeDir(r);let a=e.replace(/'/g,"'\\''"),i=await this.sandbox.exec(["bash","-c",`cat > '${a}'`],{mode:"binary"});await this.writeStdinChunked(i.stdin,new Uint8Array(n)),await i.stdin.getWriter().close(),await i.wait(),await this.chownToUser(e)}async writeBatch(e){let t=(0,tKe.pack)(),n=new Set;for(let a of e){let i=this.toBuffer(a.data),s=a.path.startsWith("/")?a.path.slice(1):a.path;t.entry({name:s},i);let o=a.path.substring(0,a.path.lastIndexOf("/"));o&&n.add(o)}t.finalize();let r=await this.sandbox.exec(["tar","-xf","-","-C","/"],{mode:"binary"});if(await this.writeStdinCoalesced(r.stdin,t),await r.stdin.getWriter().close(),await r.wait(),n.size>0){let a=Array.from(n),i=new Set(a.map(s=>s.split("/").slice(0,4).join("/")));for(let s of i)await this.chownToUser(s,!0)}}async makeDir(e){await(await this.sandbox.exec(["mkdir","-p",e],{timeoutMs:1e4})).wait(),await this.chownToUser(e,!0)}async exists(e){return await(await this.sandbox.exec(["test","-e",e],{timeoutMs:1e4})).wait()===0}async list(e){let t=e.replace(/'/g,"'\\''"),n=await this.sandbox.exec(["bash","-c",`ls -la '${t}' | tail -n +2`],{timeoutMs:3e4});await n.wait();let r=await n.stdout.readText(),a=[];for(let i of r.trim().split(`
|
|
251
251
|
`)){if(!i)continue;let s=i.split(/\s+/);if(s.length<9)continue;let o=s[0],c=s.slice(8).join(" ");c==="."||c===".."||a.push({name:c,path:e.endsWith("/")?`${e}${c}`:`${e}/${c}`,type:o.startsWith("d")?"dir":"file"})}return a}async remove(e){await(await this.sandbox.exec(["rm","-rf",e],{timeoutMs:3e4})).wait()}async rename(e,t){await(await this.sandbox.exec(["mv",e,t],{timeoutMs:3e4})).wait()}async readStream(e){return(await this.sandbox.exec(["cat",e],{timeoutMs:3e5,mode:"binary"})).stdout}async writeStream(e,t){let n=e.substring(0,e.lastIndexOf("/"));n&&await this.makeDir(n);let r=e.replace(/'/g,"'\\''"),a=await this.sandbox.exec(["bash","-c",`cat > '${r}'`],{mode:"binary"});await this.writeStdinCoalesced(a.stdin,Y8t(t)),await a.stdin.getWriter().close(),await a.wait(),await this.chownToUser(e)}async writeFromPath(e,t){let{createReadStream:n}=await import("fs"),{Readable:r}=await import("stream"),a=r.toWeb(n(t,{highWaterMark:tO}));await this.writeStream(e,a)}async uploadUrl(e,t){throw new Error("Modal does not support pre-signed upload URLs")}async downloadUrl(e,t){throw new Error("Modal does not support pre-signed download URLs")}async watchDir(e,t,n){throw new Error("Modal does not support watchDir")}toBuffer(e){if(typeof e=="string")return Buffer.from(e,"utf-8");if(e instanceof Buffer)return e;if(e instanceof ArrayBuffer||e instanceof Uint8Array)return Buffer.from(e);throw new Error(`Unsupported data type: ${typeof e}`)}},eKe=class{constructor(e,t,n){this.sandbox=e,this.commands=new fKe(e,n),this.files=new pKe(e,n),this.image=t}commands;files;image;get sandboxId(){return this.sandbox.sandboxId}async getHost(e){let t=(await this.sandbox.tunnels())[e];if(!t)throw new Error(`No tunnel found for port ${e}`);return t.url}async isRunning(){try{return await this.sandbox.poll()===null}catch{return!1}}async getInfo(){let e=await this.sandbox.getTags();return VX(this.sandbox.sandboxId,e,this.image)}async updateNetwork(e){await this.sandbox.updateNetworkPolicy(LU(e))}async kill(){try{await this.sandbox.terminate()}catch{await new Promise(e=>setTimeout(e,500)),await this.sandbox.terminate()}}async pause(){throw new Error("Modal does not support pause/resume. Persist progress with Evolve checkpoints and resume in a fresh sandbox, or use kill() to terminate.")}},qX=class{providerType="modal";name="Modal";client;appName;defaultTimeoutMs;imageName;imageSecretName;_app;sandboxUsers=new Map;constructor(e){!e.endpoint&&process.env.MODAL_SERVER_URL?.startsWith("unix:")?process.env.MODAL_SERVER_URL="https://api.modal.com:443":e.endpoint&&(process.env.MODAL_SERVER_URL=e.endpoint),this.client=new NYe({tokenId:e.tokenId,tokenSecret:e.tokenSecret}),this.appName=e.appName??"evolve-sandbox",this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.imageName=e.imageName??`evolve-all-${FU}`,this.imageSecretName=e.imageSecretName}async getApp(){return this._app||(this._app=await this.client.apps.fromName(this.appName,{createIfMissing:!0})),this._app}async resolveImage(e){let t=dKe(e);if(t==="registry"){let r=this.imageSecretName?await this.client.secrets.fromName(this.imageSecretName):void 0;return this.client.images.fromRegistry(e,r)}if(!this.imageSecretName)throw new Error(`Private registry image "${e}" requires config.imageSecretName \u2014 the name of a Modal Secret holding registry credentials (AWS ECR: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION with read-only ECR IAM). Create one at https://modal.com/secrets`);let n=await this.client.secrets.fromName(this.imageSecretName);return t==="aws-ecr"?this.client.images.fromAwsEcr(e,n):this.client.images.fromGcpArtifactRegistry(e,n)}async resolveAndBuildImage(e){let t=await this.getApp(),n=nKe[e]??e,r=await this.resolveImage(n);return{tag:n,image:await r.build(t)}}async prepareImage(e){await this.resolveAndBuildImage(e||this.imageName)}async create(e){let t=e.timeoutMs??this.defaultTimeoutMs;sKe(t);let n=oKe(e.idleTimeoutMs);for(let h of e.phaseNetworkPolicies??[])LU(h);let r=uKe(e.network,e.phaseNetworkPolicies)?LU(e.network):LX(e.network),a=cKe(e.resources),i=e.user??Q9e,s=await this.getApp(),{tag:o,image:c}=await this.resolveAndBuildImage(e.image||this.imageName),l=e.envs?Object.fromEntries(Object.entries(e.envs).filter(([,h])=>h!=null)):void 0,u=l&&Object.keys(l).length>0?l:void 0,d={...e.metadata,[rKe]:o,[iKe]:new Date().toISOString()},f=await this.client.sandboxes.create(s,c,{cpu:a.cpu,memoryMiB:a.memoryMiB,...a.gpu!==void 0?{gpu:a.gpu}:{},timeoutMs:t,...n,workdir:e.workingDirectory,env:u,tags:d,...r});return e.workingDirectory&&i!=="root"&&await(await f.exec(["chown","-R",`${i}:${i}`,e.workingDirectory],{timeoutMs:3e4})).wait(),this.sandboxUsers.set(f.sandboxId,i),new eKe(f,o,i)}async connect(e,t){let n=await this.client.sandboxes.fromId(e),r=this.sandboxUsers.get(e)??Q9e;return new eKe(n,void 0,r)}async list(e){let t=await this.walk(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.walk(e);return n}async walk(e){if(e?.state&&!e.state.includes("running"))return{sandboxes:[],complete:!0,pagesFetched:0,stoppedAtLimit:!1};let t;try{t=await this.getApp()}catch(n){return{sandboxes:[],complete:!1,pagesFetched:0,stoppedAtLimit:!1,error:`sandbox list failed: ${n instanceof Error?n.message:String(n)}`}}return hKe(()=>this.client.sandboxes.list({appId:t.appId,tags:e?.metadata}),e?.limit)}async listSandboxIds(){let e=new Set;try{let t=await this.getApp();for await(let n of this.client.sandboxes.list({appId:t.appId}))e.add(n.sandboxId);return{ids:e,complete:!0}}catch{return{ids:new Set,complete:!1}}}};nWt=MX,rWt=nKe,iWt=LX,aWt=LU,sWt=uKe,oWt=cKe,cWt=dKe,lWt=VX,uWt=hKe,dWt=sKe,fWt=oKe});var gKe={};Bu(gKe,{extractTarGz:()=>gWt,tarGzipDirectory:()=>mWt});async function hWt(e){let t=[],n=async r=>{let a=r===""?e:(0,hv.join)(e,r),i=await(0,pv.readdir)(a,{withFileTypes:!0});i.sort((s,o)=>s.name<o.name?-1:s.name>o.name?1:0);for(let s of i){if(pWt.has(s.name))continue;let o=r===""?s.name:`${r}/${s.name}`,c=(0,hv.join)(a,s.name),l=await(0,pv.lstat)(c);l.isSymbolicLink()||(l.isDirectory()?await n(o):l.isFile()&&t.push({rel:o,abs:c,mode:l.mode&73?493:420,size:l.size}))}};return await n(""),t.sort((r,a)=>r.rel<a.rel?-1:r.rel>a.rel?1:0)}async function mWt(e){let t=await hWt(e),n=(0,zU.pack)(),r=(0,$U.createGzip)({level:9}),a=[],i=(async()=>{for await(let o of r)a.push(Buffer.from(o))})(),s=(async()=>{for(let{rel:o,abs:c,mode:l,size:u}of t){let d=n.entry({name:o,size:u,mode:l,mtime:new Date(0),uid:0,gid:0,uname:"",gname:"",type:"file"});await(0,nO.pipeline)((0,rO.createReadStream)(c),d)}n.finalize()})();return await Promise.all([(0,nO.pipeline)(n,r),s,i]),Buffer.concat(a)}async function gWt(e,t,n){let r=(0,zU.extract)(),a=[],i=(async()=>{for await(let s of r){let o=s.header.name,c=o.split("/").filter(u=>u!==""&&u!==".");if(o.startsWith("/")||o.includes("\\")||c.length===0||c.some(u=>u===".."))throw new Error(`refusing to extract "${o}": the path escapes the target directory`);if(c[0]!==n)throw new Error(`refusing to extract "${o}": entry outside ${n}/`);if(s.header.type==="directory"){await(0,pv.mkdir)((0,hv.join)(t,...c),{recursive:!0}),s.resume();continue}if(s.header.type!=="file")throw new Error(`refusing to extract "${o}": unsupported entry type "${s.header.type}"`);let l=(0,hv.join)(t,...c);await(0,pv.mkdir)((0,hv.dirname)(l),{recursive:!0}),await(0,nO.pipeline)(s,(0,rO.createWriteStream)(l)),a.push(c.join("/"))}})();try{await Promise.all([(0,nO.pipeline)((0,rO.createReadStream)(e),(0,$U.createGunzip)(),r),i])}catch(s){throw r.destroy(),s}return a}var $U,rO,pv,hv,nO,zU,pWt,yKe=Q(()=>{"use strict";$U=require("zlib"),rO=require("fs"),pv=require("fs/promises"),hv=require("path"),nO=require("stream/promises"),zU=Ve(CX(),1),pWt=new Set([".git",".DS_Store",".venv"])});var _Ke={};Bu(_Ke,{ManagedModalProvider:()=>SWt,ManagedModalWriteLimitError:()=>vKe,_testManagedModalSandbox:()=>_Wt});function yWt(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error(`Unsupported data type: ${typeof e}`)}function SKe(e){return{sandboxId:e.sandboxId,image:e.image??"",metadata:e.metadata??{},startedAt:e.startedAt??""}}var vKe,bKe,vWt,bWt,$X,SWt,_Wt,wKe=Q(()=>{"use strict";vKe=class extends Error{bytes;constructor(e,t){super(`Managed Modal ${e} body is ${t} bytes; the managed door caps every request at 1048576 bytes (1 MiB) of wire bytes, base64 inflation included. Split the payload into smaller writes.`),this.name="ManagedModalWriteLimitError",this.bytes=t}};bKe=class{constructor(e){this.config=e}async request(e,t,n){let r=await fetch(`${this.config.baseUrl}${t}`,{...n,headers:{authorization:`Bearer ${this.config.apiKey}`,...n.headers??{}}});if(!r.ok){let a="";try{a=(await r.json())?.error??""}catch{}throw new Error(`Managed Modal ${e} failed (${r.status})${a?`: ${a}`:""}`)}return r}json(e){return{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}}},vWt=class{constructor(e,t){this.door=e,this.sandboxId=t}async run(e,t){let n=await this.door.request("exec",`/sandboxes/${encodeURIComponent(this.sandboxId)}/exec`,this.door.json({command:e,...t?.cwd?{cwd:t.cwd}:{},...t?.envs?{envs:t.envs}:{},...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}})),r="",a="",i,s=o=>{if(!o.trim())return;let c;try{c=JSON.parse(o)}catch{throw new Error(`Managed Modal exec stream carried a garbled record: ${o}`)}c.stream==="stdout"&&typeof c.data=="string"?(r+=c.data,t?.onStdout?.(c.data)):c.stream==="stderr"&&typeof c.data=="string"?(a+=c.data,t?.onStderr?.(c.data)):i=c};if(n.body){let o=n.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:u,value:d}=await o.read();if(u)break;l+=c.decode(d,{stream:!0});let f;for(;(f=l.indexOf(`
|
|
252
252
|
`))!==-1;)s(l.slice(0,f)),l=l.slice(f+1)}l+=c.decode(),s(l)}else for(let o of(await n.text()).split(`
|
|
@@ -1023,6 +1023,21 @@ class JobStats(TypedDict, total=False):
|
|
|
1023
1023
|
#: verifier-phase judge keys spent. 0 for a job with no judge-enabled
|
|
1024
1024
|
#: tasks; None before anything settled, like ``cost_usd``.
|
|
1025
1025
|
judge_cost_usd: Optional[float]
|
|
1026
|
+
#: HOW MANY SETTLED TRIALS ``cost_usd`` CANNOT ACCOUNT FOR — trials whose
|
|
1027
|
+
#: ``spend_source`` lane is ``'assumed_cap'``, meaning nobody ever
|
|
1028
|
+
#: measured their gateway spend. Such a trial stores 0, and the job total
|
|
1029
|
+
#: is the sum of its trials, so each one folds a zero in and ``cost_usd``
|
|
1030
|
+
#: comes out LOWER than what was really spent. A plain count, never None:
|
|
1031
|
+
#: before anything settles it is honestly 0, where ``cost_usd`` is None.
|
|
1032
|
+
#: It is a FLOOR — a retried-away attempt's lineage snapshot keeps no
|
|
1033
|
+
#: spend-source column, so an earlier attempt nobody measured cannot be
|
|
1034
|
+
#: counted here.
|
|
1035
|
+
n_unmeasured_trials: int
|
|
1036
|
+
#: The judge half of the same fact, itemized the way ``judge_cost_usd``
|
|
1037
|
+
#: itemizes ``cost_usd``: trials that ran a judge whose spend was never
|
|
1038
|
+
#: measured (``judge_spend_source`` ``'assumed_cap'``). 0 on jobs with no
|
|
1039
|
+
#: judge-enabled tasks.
|
|
1040
|
+
n_unmeasured_judge_trials: int
|
|
1026
1041
|
|
|
1027
1042
|
|
|
1028
1043
|
class JobRetryConfigInput(TypedDict, total=False):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{evolve_sdk-0.0.52.dev880 → evolve_sdk-0.0.52.dev892}/evolve_sdk.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|