eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
15 lines • 151 kB
JavaScript
import{i as e,o as t,t as n}from"../../_chunks/node/rolldown-runtime-tZXQYakl.js";import{n as r,t as i}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as a,t as o}from"../../_chunks/node/retry-hTJQ4iNT.js";import{a as s,f as c,g as l,l as u,o as d,p as f,s as p,t as m,u as h,v as g,y as _}from"../../_chunks/node/schemas-g-rLPCNX.js";import{t as v}from"../../_chunks/node/undici-h5GH4RBM.js";import{t as y}from"../../_chunks/node/version-C__MqbLM.js";import{n as b,r as x,t as S}from"../../_chunks/node/token-util-DpJNusVS.js";import{Readable as C}from"stream";import ee from"zlib";import w,{dirname as te,resolve as T}from"path";import{createWriteStream as ne}from"fs";import re from"os";import{pipeline as E}from"stream/promises";import{mkdir as ie}from"fs/promises";import*as ae from"node:constants";import{setTimeout as oe}from"node:timers/promises";var D=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},O=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};const se=`iad1`;function ce(e){return e==null?[]:Array.isArray(e)?e:[e]}var le=t(n(((e,t)=>{var n=o();function r(e,t){function r(r,i){var a=t||{},o;`randomize`in a||(a.randomize=!0),o=n.operation(a);function s(e){i(e||Error(`Aborted`))}function c(e,t){if(e.bail){s(e);return}o.retry(e)?a.onRetry&&a.onRetry(e,t):i(o.mainError())}function l(t){var n;try{n=e(s,t)}catch(e){c(e,t);return}Promise.resolve(n).then(r).catch(function(e){c(e,t)})}o.attempt(l)}return new Promise(r)}t.exports=r}))(),1);function ue(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,le.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new D(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await de(e*1e3,n.signal),new D(o)}if(o.status>=500&&o.status<600)throw new D(o);return o}catch(e){if(fe(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof D)return e.response;throw e}}}async function de(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function fe(e){return e!=null&&e.name===`AbortError`}const pe=new(v()).Agent({bodyTimeout:0});var me=class{constructor(e){this.fetch=ue(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=pe}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))ce(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function he(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function ge(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}const _e=f({error:f({message:g()})});function ve(e){let t=_e.safeParse(e);return t.success?t.data.error.message:void 0}async function ye(e,t){let n=he(t.url),r;n||(r=ge(t.url));let i=await t.text().catch(e=>new D(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new D(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok){let e=ve(a);return new D(t,{message:e?`Status code ${t.status} is not ok: ${e}`:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r})}let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new D(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function k(e,t){let n=await ye(e,t);if(n instanceof D)throw n;return n}const be=f({exact:g().optional(),startsWith:g().optional(),regex:g().optional()}),xe=f({key:be.optional(),value:be.optional()}),Se=f({path:be.optional(),method:d(g()).optional(),queryString:d(xe).optional(),headers:d(xe).optional()}),Ce=f({domain:g(),headers:l(g(),g()).optional(),headerNames:d(g()).optional(),match:Se.optional()}),we=f({domain:g(),forwardURL:g(),match:Se.optional()}),Te=f({headers:l(g(),g()).optional()}),Ee=f({match:Se.optional(),transform:d(Te).optional(),forwardURL:g().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),De=f({allow:_([d(g()),l(g(),d(Ee))]).optional(),subnets:f({allow:d(g()).optional(),deny:d(g()).optional()}).optional()}),Oe=_([f({mode:h(`allow-all`)}).passthrough(),f({mode:h(`deny-all`)}).passthrough()]),ke=f({mode:h(`custom`),allowedDomains:d(g()).optional(),allowedCIDRs:d(g()).optional(),deniedCIDRs:d(g()).optional(),injectionRules:d(Ce).optional(),forwardRules:d(we).optional()}).passthrough(),Ae=_([Oe,De.passthrough()]),A=_([Oe,ke]),j=f({id:g(),memory:c(),vcpus:c(),region:g(),runtime:g().optional(),timeout:c(),status:m([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:c(),startedAt:c().optional(),requestedStopAt:c().optional(),stoppedAt:c().optional(),abortedAt:c().optional(),duration:c().optional(),sourceSnapshotId:g().optional(),snapshottedAt:c().optional(),createdAt:c(),cwd:g(),updatedAt:c(),interactivePort:c().optional(),networkPolicy:A.optional(),activeCpuDurationMs:c().optional(),networkTransfer:f({ingress:c(),egress:c()}).optional()}),je=f({url:g(),subdomain:g(),port:c()}),M=f({id:g(),sourceSessionId:g(),region:g(),regions:d(g()).optional(),status:m([`created`,`deleted`,`failed`]),sizeBytes:c(),expiresAt:c().optional(),createdAt:c(),updatedAt:c(),lastUsedAt:c().optional(),creationMethod:g().optional(),parentId:g().optional()}),N=f({count:c(),next:g().nullable()}),Me=f({id:g(),name:g(),args:d(g()),cwd:g(),sessionId:g(),exitCode:c().nullable(),durationMs:c().optional(),startedAt:c()}),Ne=Me.extend({exitCode:c()}),Pe=f({session:j.passthrough()}),Fe=Pe.extend({routes:d(je)}),Ie=f({url:g(),token:g()}),Le=f({sessions:d(j.passthrough()),pagination:N}),Re=f({command:Me}),ze=f({command:Ne}),Be=f({}),Ve=f({data:g()}),He=Ve.extend({stream:h(`stdout`)}),Ue=Ve.extend({stream:h(`stderr`)}),We=f({stream:h(`error`),data:f({code:g(),message:g()})}),Ge=u(`stream`,[He,Ue,We]),Ke=f({snapshots:d(M),pagination:N}),qe=f({snapshot:M,siblings:d(M),count:g()}),Je=f({snapshots:d(qe),anchor:qe.optional(),pagination:N}),Ye=f({snapshot:M,session:j.passthrough()}),Xe=f({snapshot:M}),Ze=f({id:g(),name:g(),projectId:g(),region:g(),maxSizeBytes:c(),currentSessionId:g().optional(),currentSandboxName:g().optional(),createdAt:c(),updatedAt:c()}),Qe=f({drives:d(Ze),pagination:N}),$e=f({drive:Ze}),et=f({name:g(),persistent:p(),region:g().optional(),failoverRegions:d(g()).optional(),vcpus:c().optional(),memory:c().optional(),runtime:g().optional(),image:g().optional(),timeout:c().optional(),networkPolicy:A.optional(),totalEgressBytes:c().optional(),totalIngressBytes:c().optional(),totalActiveCpuDurationMs:c().optional(),totalDurationMs:c().optional(),createdAt:c(),updatedAt:c(),expiresAt:c().optional(),currentSessionId:g(),currentSnapshotId:g().optional(),status:j.shape.status,statusUpdatedAt:c().optional(),cwd:g().optional(),tags:l(g(),g()).optional(),mounts:l(g(),f({drive:g(),mode:m([`snapshot`,`read-write`,`read-only`]).optional()}).transform(e=>({drive:e.drive,mode:e.mode===`read-only`?`snapshot`:e.mode??`read-write`}))).optional(),snapshotExpiration:c().optional(),keepLastSnapshots:f({count:c(),expiration:c().optional(),deleteEvicted:p().optional()}).optional()}),tt=f({session:j.passthrough(),sandbox:et.optional(),snapshot:M.optional()}),nt=f({sandbox:et,session:j.passthrough(),routes:d(je),resumed:p().optional()}),rt=f({sandboxes:d(et),pagination:N}),it=f({sandbox:et,routes:d(je).optional()});var at=n(((t,n)=>{n.exports=e(`events`)})),ot=n(((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-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(e){return this.buffer[this.top]===void 0&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})),st=n(((e,t)=>{let n=ot();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})),ct=n(((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n){return b(e).toString(`hex`,t,n)}function C(e,t,n,r,i){return b(e).write(t,n,r,i)}function ee(e,t){return b(e).readDoubleBE(t)}function w(e,t){return b(e).readDoubleLE(t)}function te(e,t){return b(e).readFloatBE(t)}function T(e,t){return b(e).readFloatLE(t)}function ne(e,t){return b(e).readInt32BE(t)}function re(e,t){return b(e).readInt32LE(t)}function E(e,t){return b(e).readUInt32BE(t)}function ie(e,t){return b(e).readUInt32LE(t)}function ae(e,t,n){return b(e).writeDoubleBE(t,n)}function oe(e,t,n){return b(e).writeDoubleLE(t,n)}function D(e,t,n){return b(e).writeFloatBE(t,n)}function O(e,t,n){return b(e).writeFloatLE(t,n)}function se(e,t,n){return b(e).writeInt32BE(t,n)}function ce(e,t,n){return b(e).writeInt32LE(t,n)}function le(e,t,n){return b(e).writeUInt32BE(t,n)}function ue(e,t,n){return b(e).writeUInt32LE(t,n)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,toHex:S,write:C,readDoubleBE:ee,readDoubleLE:w,readFloatBE:te,readFloatLE:T,readInt32BE:ne,readInt32LE:re,readUInt32BE:E,readUInt32LE:ie,writeDoubleBE:ae,writeDoubleLE:oe,writeFloatBE:D,writeFloatLE:O,writeInt32BE:se,writeInt32LE:ce,writeUInt32BE:le,writeUInt32LE:ue}})),lt=n(((e,t)=>{let n=ct();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})),ut=n(((e,t)=>{let n=ct();t.exports=class{constructor(){this._reset()}get remaining(){return this.bytesSeen}decode(e){if(e.byteLength===0)return``;if(this.bytesNeeded===0&&r(e,0)===0)return this.bytesSeen=i(e),n.toString(e,`utf8`);let t=``,a=0;if(this.bytesNeeded>0){for(;a<e.byteLength;){let n=e[a];if(n<this.lowerBoundary||n>this.upperBoundary){t+=`�`,this._reset();break}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|n&63,this.bytesSeen++,a++,this.bytesSeen===this.bytesNeeded){t+=String.fromCodePoint(this.codePoint),this._reset();break}}if(this.bytesNeeded>0)return t}let o=r(e,a),s=e.byteLength-o;s>a&&(t+=n.toString(e,`utf8`,a,s));for(let n=s;n<e.byteLength;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?(this.bytesSeen=0,t+=String.fromCharCode(r)):r>=194&&r<=223?(this.bytesNeeded=2,this.bytesSeen=1,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.bytesSeen=1,this.codePoint=r&15):r>=240&&r<=244?(r===240?this.lowerBoundary=144:r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.bytesSeen=1,this.codePoint=r&7):(this.bytesSeen=1,t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){t+=`�`,n--,this._reset();continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this._reset())}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this._reset(),e}_reset(){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191}};function r(e,t){let n=e.byteLength;if(n<=t)return 0;let r=Math.max(t,n-4),i=n-1;for(;i>r&&(e[i]&192)==128;)i--;if(i<t)return 0;let a=e[i],o;if(a<=127)return 0;if(a>=194&&a<=223)o=2;else if(a>=224&&a<=239)o=3;else if(a>=240&&a<=244)o=4;else return 0;let s=n-i;return s<o?s:0}function i(e){let t=e.byteLength;if(t===0)return 0;let n=e[t-1];if(n<=127)return 0;if((n&192)!=128)return 1;let r=Math.max(0,t-4),i=t-2;for(;i>=r&&(e[i]&192)==128;)i--;if(i<0)return 1;let a=e[i],o;if(a>=194&&a<=223)o=2;else if(a>=224&&a<=239)o=3;else if(a>=240&&a<=244)o=4;else return 1;if(t-i!==o)return 1;if(o>=3){let t=e[i+1];if(a===224&&t<160||a===237&&t>159||a===240&&t<144||a===244&&t>143)return 1}return 0}})),dt=n(((e,t)=>{let n=lt(),r=ut();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(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 Error(`Unknown encoding: `+e)}}})),ft=n(((e,t)=>{t.exports=class e extends Error{constructor(t,n,r=e){super(t),this.code=n,Error.captureStackTrace&&Error.captureStackTrace(this,r)}static isStreamDestroyed(e){return e&&e.code===`STREAM_DESTROYED`}static isPrematureClose(e){return e&&e.code===`PREMATURE_CLOSE`}static isAborted(e){return e&&e.code===`ABORTED`}static isBadArgument(e){return e&&e.code===`BAD_ARGUMENT`}get name(){return`StreamError`}static STREAM_DESTROYED(){return new e(`Stream was destroyed`,`STREAM_DESTROYED`,e.STREAM_DESTROYED)}static PREMATURE_CLOSE(t=`Premature close`){return new e(t,`PREMATURE_CLOSE`,e.PREMATURE_CLOSE)}static ABORTED(){return new e(`Stream aborted`,`ABORTED`,e.ABORTED)}static BAD_ARGUMENT(t=`Bad argument`){return new e(t,`BAD_ARGUMENT`,e.BAD_ARGUMENT)}}})),pt=n(((e,t)=>{let{EventEmitter:n}=at(),r=st(),i=dt(),a=ft(),o=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,s=536870910,c=1024,l=2048,u=16384,d=32768,f=131072,p=536805375,m=536870143,h=536838143,g=536739839,_=2<<18,v=4<<18,y=8<<18,b=32<<18,x=64<<18,S=128<<18,C=512<<18,ee=1024<<18,w=503316479,te=268435455,T=262160,ne=8404992,re=8405006,E=33587200,ie=33587215,ae=16527,oe=270794767,D=Symbol.asyncIterator||Symbol(`asyncIterator`);var O=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:i,byteLength:a,byteLengthWritable:o}={}){this.stream=e,this.queue=new r,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||a||Ie,this.map=i||n,this.afterWrite=pe.bind(this),this.afterUpdateNextTick=ge.bind(this)}get ending(){return!!(this.stream._duplexState&C)}get ended(){return!!(this.stream._duplexState&b)}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=y,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|C)&535822335}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&oe)==2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=_;do{for(;(e._duplexState&oe)==y;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)==C){e._duplexState|=262144,e._final(de.bind(this));return}if((e._duplexState&14)==4){e._duplexState&E||(e._duplexState|=T,e._destroy(fe.bind(this)));return}(e._duplexState&ie)==1&&(e._duplexState=(e._duplexState|T)&s,e._open(ve.bind(this)))}continueUpdate(){return this.stream._duplexState&S?(this.stream._duplexState&=w,!0):!1}updateCallback(){(this.stream._duplexState&35127311)==v?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&S||(this.stream._duplexState|=S,this.stream._duplexState&_||o(this.afterUpdateNextTick))}},se=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:i,byteLength:a,byteLengthReadable:o}={}){this.stream=e,this.queue=new r,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||a||Ie,this.map=i||n,this.pipeTo=null,this.afterRead=me.bind(this),this.afterUpdateNextTick=he.bind(this)}get ending(){return!!(this.stream._duplexState&c)}get ended(){return!!(this.stream._duplexState&u)}pipe(e,t){if(this.pipeTo!==null)throw a.BAD_ARGUMENT(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new le(this.stream,e,t),t&&this.stream.on(`error`,Le),A(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Le),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,ue.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|c)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=p,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&p,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&ae)==128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=m),e._duplexState&l&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=f,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&ae)==128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=m),e._duplexState&l&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)==f;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=8192,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)==c&&(e._duplexState=(e._duplexState|u)&536869887,e.emit(`end`),(e._duplexState&re)==ne&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){e._duplexState&E||(e._duplexState|=T,e._destroy(fe.bind(this)));return}(e._duplexState&ie)==1&&(e._duplexState=(e._duplexState|T)&s,e._open(ve.bind(this)))}continueUpdate(){return this.stream._duplexState&d?(this.stream._duplexState&=h,!0):!1}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=d,this.stream._duplexState&32||o(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&d||(this.stream._duplexState|=d,this.stream._duplexState&32||o(this.afterUpdateNextTick))}},ce=class{constructor(e){this.data=null,this.afterTransform=ye.bind(e),this.afterFinal=null}},le=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){(!(this.from._duplexState&u)||!this.pipeToFinished)&&this.from.destroy(this.error||a.PREMATURE_CLOSE(`Writable stream closed`));return}if(e===this.from&&(this.from=null,this.to!==null)){e._duplexState&u||this.to.destroy(this.error||a.PREMATURE_CLOSE(`Readable stream closed`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function ue(){this.stream._duplexState|=512,this.updateCallback()}function de(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=b,t.emit(`finish`)),(t._duplexState&re)==ne&&(t._duplexState|=4),t._duplexState&=402391039,t._duplexState&_?this.updateNextTick():this.update()}function fe(e){let t=this.stream;!e&&!a.isStreamDestroyed(this.error)&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,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 pe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&_e(this.drains),(t._duplexState&6553615)==4194304&&(t._duplexState&=532676607,(t._duplexState&x)==x&&t.emit(`drain`)),this.updateCallback()}function me(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=g),this.updateCallback()}function he(){this.stream._duplexState&32||(this.stream._duplexState&=h,this.update())}function ge(){this.stream._duplexState&_||(this.stream._duplexState&=w,this.update())}function _e(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function ve(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=v),t.emit(`open`)),t._duplexState&=536608751,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function ye(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function k(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=133376,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=4096,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=x,this._writableState.updateNextTick())}var be=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Re.bind(this))),this.on(`newListener`,k)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState!==null||void 0}get writable(){return this._writableState!==null||void 0}get destroyed(){return!!(this._duplexState&8)}get destroying(){return!!(this._duplexState&14)}destroy(e){this._duplexState&14||(e||=a.STREAM_DESTROYED(),this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},xe=class e extends be{constructor(e){super(e),this._duplexState|=8519681,this._readableState=new se(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=g),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}static deferred(e,t){let n=new Te(t);return e().then(e=>{if(e===null)return n.end();n.destroying||Oe(e,n,Le)}).catch(e=>n.destroy(e)),n}setEncoding(e){let t=new i(e),n=this._readableState.map||ke;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=131328,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(Ne(t))return t;if(t[D])return this._fromAsyncIterator(t[D](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return!!(e._duplexState&17422)||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return!(e._duplexState&256)}[D](){let e=this,t=null,n=null,r=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,i),this.on(`close`,o),{[D](){return this},next(){return new Promise(function(t,i){n=t,r=i;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function i(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(i){r!==null&&(t?r(t):i===null&&!(e._duplexState&u)?r(a.STREAM_DESTROYED()):n({value:i,done:i===null}),r=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},Se=class extends be{constructor(e){super(e),this._duplexState|=16385,this._writableState=new O(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=ee}uncork(){this._duplexState&=te,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return!!(e._duplexState&146800654)}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(ze(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&67108864?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Ce=class extends xe{constructor(e){super(e),this._duplexState=1|this._duplexState&f,this._writableState=new O(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=ee}uncork(){this._duplexState&=te,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},we=class extends Ce{constructor(e){super(e),this._transformState=new ce(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(Ee.bind(this))}},Te=class extends we{};function Ee(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function De(...e){return new Promise((t,n)=>Oe(...e,e=>{if(e)return n(e);t()}))}function Oe(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 a.BAD_ARGUMENT(`Pipeline requires at least 2 streams`);let i=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],A(i)?i.pipe(o,l):(c(i,!0,e>1,l),i.pipe(o)),i=o;if(r){let e=!1,t=A(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:a.PREMATURE_CLOSE())))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,i);function i(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(a.PREMATURE_CLOSE())}}function l(e){if(e&&!s){s=e;for(let t of n)t.destroy(e)}}}function ke(e){return e}function Ae(e){return!!e._readableState||!!e._writableState}function A(e){return typeof e._duplexState==`number`&&Ae(e)}function j(e){return!!e._readableState&&e._readableState.ending}function je(e){return!!e._readableState&&e._readableState.ended}function M(e){return!!e._writableState&&e._writableState.ending}function N(e){return!!e._writableState&&e._writableState.ended}function Me(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&a.isStreamDestroyed(n)?null:n}function Ne(e){return A(e)&&e.readable}function Pe(e){return(e._duplexState&1)!=1||(e._duplexState&4)==4||!!(e._duplexState&E)}function Fe(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Ie(e){return Fe(e)?e.byteLength:1024}function Le(){}function Re(){this.destroy(a.ABORTED())}function ze(e){return e._writev!==Se.prototype._writev&&e._writev!==Ce.prototype._writev}t.exports={pipeline:Oe,pipelinePromise:De,isStream:Ae,isStreamx:A,isEnding:j,isEnded:je,isFinishing:M,isFinished:N,isDisturbed:Pe,getStreamError:Me,Stream:be,Writable:Se,Readable:xe,Duplex:Ce,Transform:we,PassThrough:Te}})),mt=n((e=>{let t=ct(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
`)),e.linkname&&(n+=y(` linkpath=`+e.linkname+`
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
`);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(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 u(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 d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(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 p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(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 i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})),ht=n(((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=pt(),a=st(),o=ct(),s=mt(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!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,null),this._gnuLongLinkPath&&=(this._header.linkname=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,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e))}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(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 e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})),gt=n(((t,n)=>{let r={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{n.exports=e(`fs`).constants||r}catch{n.exports=r}})),_t=n(((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=pt(),a=ct(),o=gt(),s=mt(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})),vt=t(n((e=>{e.extract=ht(),e.pack=_t()}))(),1),yt=class{constructor(){let e=ee.createGzip();this.pack=vt.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof C?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function bt(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function xt(e){if(!w.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!w.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=w.posix.isAbsolute(e.filePath)?w.posix.normalize(e.filePath):w.posix.join(e.cwd,e.filePath);return w.posix.relative(e.extractDir,t)}function St(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Ae.parse(t),t}function Ct(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const P=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var wt=n(((t,n)=>{var r=e(`stream`).Transform;function i(e){if(!(this instanceof i))throw TypeError(`Cannot call a class as a function`);e||={},r.call(this,{objectMode:!0}),this._memory=``,this._emitInvalidLines=e.emitInvalidLines||!1}i.prototype=Object.create(r.prototype),i.prototype._handleLines=function(e,t){for(var n=0;n<e.length;n++)if(e[n]!==``){var r=null,i=null;try{i=JSON.parse(e[n])}catch(t){t.source=e[n],r=t}if(r){if(this._emitInvalidLines)this.emit(`invalid-line`,r);else return t(r)}else this.push(i)}t(null)},i.prototype._transform=function(e,t,n){var r=(this._memory+e.toString()).split(`
`);this._memory=r.pop(),this._handleLines(r,n)},i.prototype._flush=function(e){if(!this._memory)return e(null);var t=this._memory;this._memory=``,this._handleLines([t],e)},n.exports=i})),Tt=n(((t,n)=>{var r=e(`stream`).Transform;function i(){if(!(this instanceof i))throw TypeError(`Cannot call a class as a function`);r.call(this,{objectMode:!0})}i.prototype=Object.create(r.prototype),i.prototype._transform=function(e,t,n){var r;try{r=JSON.stringify(e)}catch(t){return t.source=e,n(t)}n(null,r+`
`)},n.exports=i})),Et=n((e=>{var t=wt();Tt(),e.parse=function(e){return new t(e)}})),Dt=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}0&&(t.exports={SYMBOL_FOR_REQ_CONTEXT:u,getContext:d})})),Ot=n(((e,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{getVercelOidcToken:()=>p,getVercelOidcTokenSync:()=>m}),n.exports=l(u);var d=Dt(),f=x();async function p(e){let n=``,r;try{n=m()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await import(`../../_chunks/node/token-util-DwHQ2a3c.js`).then(e=>t(e.default)),await import(`../../_chunks/node/token-Bedbhv5z.js`).then(e=>t(e.default))]);(!n||i(r(n),e?.expirationBufferMs))&&(await a(e),n=m())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
${e.message}`),t?new f.VercelOidcTokenError(t):e}return n}function m(){let e=(0,d.getContext)().headers?.[`x-vercel-oidc-token`]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error(`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`);return e}0&&(n.exports={getVercelOidcToken:p,getVercelOidcTokenSync:m})})),kt=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>f.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>f.RefreshAccessTokenFailedError,getContext:()=>d.getContext,getVercelOidcToken:()=>u.getVercelOidcToken,getVercelOidcTokenSync:()=>u.getVercelOidcTokenSync,getVercelToken:()=>p.getVercelToken}),t.exports=c(l);var u=Ot(),d=Dt(),f=b(),p=S();0&&(t.exports={AccessTokenMissingError,RefreshAccessTokenFailedError,getContext,getVercelOidcToken,getVercelOidcTokenSync,getVercelToken})})),At=t(Et(),1),jt=kt();function Mt(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var F=class extends me{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=Mt(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,jt.getVercelOidcToken)({expirationBufferMs:3e5,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=Mt(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${y} (Node.js/${process.version}; ${re.platform()}/${re.arch()})`,...t?.headers}})}async getSession(e){let t=P(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,k(Fe,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=P(e),n=e.runtime===void 0?`/v3/sandboxes`:`/v2/sandboxes`;return k(nt,await this.request(n,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?St(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,mounts:e.mounts,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async forkSandbox(e){let t=P(e);return k(nt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?St(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await k(s(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new D(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new D(t,{message:`No response body`,sessionId:e.sessionId});let n=At.parse();Nt(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new O(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:a}=Re.parse(i.value);return{command:a,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new O(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=ze.parse(t.value);return e}let n=Ge.parse(t.value);if(n.stream===`error`)throw new O(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return k(Re,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?k(ze,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):k(Re,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return k(Ie,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return k(Be,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new yt;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await bt(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return k(Le,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return k(Ke,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return k(Je,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listDrives(e){return k(Qe,await this.request(`/v2/sandboxes/drives`,{query:{projectId:e.projectId,limit:e.limit,cursor:e.cursor,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix},method:`GET`,signal:e.signal}))}async getOrCreateDrive(e){return k($e,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,region:e.region,maxSizeBytes:e.maxSizeBytes}),signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:xt({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await k(Be,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new D(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:C.fromWeb(t.body)}async killCommand(e){return k(Re,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?Pt(e.signal,n.signal):n.signal,i=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,i=await t.request(n,{method:`GET`,signal:r});if(i.ok||await k(s(),i),i.headers.get(`content-type`)!==`application/x-ndjson`)throw new D(i,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(i.body===null)throw new D(i,{message:`No response body`,sessionId:e.sessionId});let a=At.parse();Nt(i.body,a,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of a){let n=Ge.parse(t);if(n.stream===`error`)throw new O(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(i,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return k(tt,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return k(Pe,await this.request(t,{method:`POST`,body:JSON.stringify(St(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return k(Pe,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return k(Ye,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return k(Xe,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return k(Xe,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=P(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),k(nt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return k(rt,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:Ft(e.tags)},method:`GET`,signal:e.signal}))}async deleteDrive(e){let t=`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`;return k($e,await this.request(t,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}async updateSandbox(e){return k(it,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,timeout:e.timeout,networkPolicy:e.networkPolicy?St(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions,mounts:e.mounts}),signal:e.signal}))}async deleteSandbox(e){return k(it,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId,deleteOrphanSnapshots:e.deleteOrphanSnapshots?`true`:void 0},signal:e.signal}))}};async function Nt(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function Pt(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function Ft(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0){if(t.length>1)throw Error("Filtering by multiple tags is not supported. Pass a single `{ key: value }` tag.");return t.map(([e,t])=>`${e}:${t}`)}}function It(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var I=t(n(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c}))(),1);const Lt={warn:I.default.yellow,error:I.default.red,success:I.default.green,info:I.default.blue},Rt=I.default.dim(`[vercel/sandbox]`);function L(e,t){t=Array.isArray(t)?t.join(`
`):t;let n=t.replace(/^/gm,`${Rt} `);console.error(Lt[e](n))}function zt(e){return I.default.italic(I.default.dim("`")+e+I.default.dim("`"))}var Bt=t(a(),1);async function Vt(){return await import(`../../_chunks/node/auth-DDrvYko5.js`)}function Ht(){return process.env.NODE_ENV!==`production`&&![`1`,`true`].includes(process.env.CI||``)&&process.stdout.isTTY&&process.stdin.isTTY}const Ut=(()=>{let e=null;return async t=>{(!e||e[0].teamId!==t.teamId||e[0].projectId!==t.projectId)&&(e=[t,Wt(t).catch(t=>{throw e=null,t})]);let n=await e[1];return L(`warn`,`using inferred credentials team=${n.teamId} project=${n.projectId}`),n}})();async function Wt(e){let{OAuth:t,pollForToken:n,getAuth:r,updateAuthConfig:i,inferScope:a}=await Vt(),o=r();if(!o?.token){let e=process.env.VERCEL_URL?`1 minute`:`5 minutes`;o=await Gt({OAuth:t,pollForToken:n,getAuth:r},e)}if(o?.refreshToken&&o.expiresAt&&o.expiresAt.getTime()<=Date.now()){let e=await(await t()).refreshToken(o.refreshToken);o={expiresAt:new Date(Date.now()+e.expires_in*1e3),token:e.access_token,refreshToken:e.refresh_token||o.refreshToken},i(o)}if(!o?.token)throw Error([`Failed to retrieve authentication token.`,`${I.default.bold(`hint:`)} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,`├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox`,`╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token`].join(`
`));if(e.teamId&&e.projectId)return{token:o.token,teamId:e.teamId,projectId:e.projectId};let s=await a({teamId:e.teamId,token:o.token});return s.created&&L(`info`,`Created default project "${s.projectId}" in team "${s.teamId}".`),{token:o.token,teamId:e.teamId||s.teamId,projectId:e.projectId||s.projectId}}async function Gt(e,t){L(`warn`,[`No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,`│ ${I.default.bold(`help:`)} this flow only happens on development environment.`,`│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`]);let n=await e.OAuth(),r=await n.deviceAuthorizationRequest();L(`info`,[`╰▶ To authenticate, visit: ${r.verification_uri_complete}`,` or visit ${I.default.italic(r.verification_uri)} and type ${I.default.bold(r.user_code)}`,` Press ${I.default.bold(`<return>`)} to open in your browser`]);let i,a=e.pollForToken({request:r,oauth:n}),o=!1,s=setTimeout(()=>{if(o)return;let e=[`Authentication flow timed out after ${t}.`,`│ Make sure to provide a token to avoid prompting an interactive flow.`,`╰▶ ${I.default.bold(`help:`)} Link your project with ${zt(`npx vercel link`)} to refresh OIDC token automatically.`].join(`
`);i=Error(e),a.return()},(0,Bt.default)(t));try{for await(let e of a)switch(e._tag){case`SlowDown`:case`Timeout`:case`Response`:break;case`Error`:i=e.error;break;default:throw Error(`Unknown event type: ${JSON.stringify(e)}`)}}finally{o=!0,clearTimeout(s)}if(i)throw L(`error`,`${I.default.bold(`error:`)} Authentication failed: ${i.message}`),i;return L(`success`,`${I.default.bold(`done!`)} Authenticated successfully!`),e.getAuth()}var Kt=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,"Please link your Vercel project using `npx vercel link`.","Then, pull an initial OIDC token with `npx vercel env pull`",`and retry.`,"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."].join(`
`);super(t,{cause:e}),this.name=`LocalOidcContextError`}},qt=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
`);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function Jt(e){try{return Zt(await(0,jt.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!Ht())throw process.env.VERCEL_URL?new qt(t):new Kt(t);return await Ut(e)}}async function R(e){return Yt(e??{})||await Jt({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Yt(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const Xt=f({exp:c().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:c().optional().describe(`Issued at timestamp`),owner_id:g(),project_id:g()});function Zt(e){try{let t=Xt.parse(It(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const Qt={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function $t(e){if(typeof e==`number`)return e;if(e in Qt)return Qt[e];throw Error(`Unknown signal name: ${String(e)}`)}var en=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[r](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new tn({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:$t(e??`SIGTERM`),abortSignal:t?.abortSignal})}},tn=class e extends en{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[r](e){return{...en[r](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function z(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){nn(i);let t=e;for(yield t;t.pagination.next!==null;)nn(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)nn(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function nn(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var rn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get regions(){return this.snapshot.regions??[this.snapshot.region]}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[r](e){return{snapshot:e.snapshot}}static[i](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return z(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function an(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?Ct(t):void 0}}var on=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[r](e){return{session:e.session,routes:e.routes}}static[i](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=an(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new en({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new tn({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new en({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:bt(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=T(t.cwd??``,t.path);return n?.mkdirRecursive&&await ie(te(e),{recursive:!0}),await E(i,ne(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=an(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=an((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=an((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=an(n.json.session),new rn({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:B,S_IFREG:sn,S_IFDIR:cn,S_IFLNK:ln,S_IFBLK:un,S_IFCHR:dn,S_IFIFO:fn,S_IFSOCK:pn}=ae;function V(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function mn(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var hn=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&B)===sn}isDirectory(){return(this.mode&B)===cn}isBlockDevice(){return(this.mode&B)===un}isCharacterDevice(){return(this.mode&B)===dn}isSymbolicLink(){return(this.mode&B)===ln}isFIFO(){return(this.mode&B)===fn}isSocket(){return(this.mode&B)===pn}},gn=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function _n(e){let t=e.trim().split(`|`);return new hn(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function vn(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw V(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new gn(r,bn[i]??1,t)}const yn=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,bn={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var xn=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=mn(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw V(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw V(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`scandir`,e):V(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
`).filter(Boolean).map(t=>vn(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`scandir`,e):V(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
`).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,yn,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`stat`,e):V(`EACCES`,t.trim(),`stat`,e)}return _n(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,yn,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`lstat`,e):V(`EACCES`,t.trim(),`lstat`,e)}return _n(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`unlink`,e):V(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`rm`,e):V(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?V(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):V(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`rename`,e):V(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`copyfile`,e):V(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw V(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`chmod`,e):V(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`chown`,e):V(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?V(`EEXIST`,`file already exists`,`symlink`,t):V(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`readlink`,e):V(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`realpath`,e):V(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?V(`ENOENT`,`no such file or directory`,`truncate`,e):V(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw V(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};const Sn=/^[a-z_][a-z0-9_-]*$/;function H(e,t){if(!e)throw Error(`Invalid ${t}: must not be empty`);if(e.length>32)throw Error(`Invalid ${t} "${e}": must be at most 32 characters`);if(!Sn.test(e))throw Error(`Invalid ${t} "${e}": must match ${Sn} (lowercase letters, digits, hyphens, underscores)`)}var Cn=class extends Error{constructor(e){super(`Failed to create user "${e}": user already exists`),this.name=`SandboxUserAlreadyExistsError`,this.username=e}},wn=class{constructor({sandbox:e,username:t}){this.sandbox=e,this.username=t,this.homeDir=t===`root`?`/root`:`/home/${t}`}buildUserCommand(e){let t=Object.entries(e.env??{}),n=t.length>0?[`env`,...t.map(([e,t])=>`${e}=${t}`)]:[],r=e.cwd??this.homeDir;return{cmd:`sudo`,args:[`-u`,this.username,`--`,`bash`,`-c`,`cd "$1" || exit 1; shift; exec "$@"`,`bash`,r,...n,e.cmd,...e.args??[]]}}resolvePath(e){return e.startsWith(`/`)?e:`${this.homeDir}/${e}`}async runCommand(e,t,n){if(typeof e==`string`){let r=this.buildUserCommand({cmd:e,args:t});return this.sandbox.runCommand({...r,signal:n?.signal,timeoutMs:n?.timeoutMs})}let r=e;if(r.sudo)return this.sandbox.runCommand({...r});let i=this.buildUserCommand({cmd:r.cmd,args:r.args,env:r.env,cwd:r.cwd});return this.sandbox.runCommand({cmd:i.cmd,args:i.args,detached:r.detached,stdout:r.stdout,stderr:r.stderr,signal:r.signal,timeoutMs:r.timeoutMs})}async writeFiles(e,t){let n=e.map(e=>({...e,path:this.resolvePath(e.path)}));await this.sandbox.writeFiles(n,t);let r=n.map(e=>e.path);if(r.length===0)return;await this.chownOrThrow(r,`${this.username}:${await this.primaryGroup(t?.signal)}`,t?.signal);let i=this.ancestorDirsUnderHome(r);if(i.length>0){let{group:e}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(i,`${this.username}:${e}`,t?.signal),await this.chmodOrThrow(i,`770`,t?.signal)}}async readFile(e,t){"use step";let n=await this.catAsUser(e,t);return n===null?null:C.from([n])}async readFileToBuffer(e,t){return this.catAsUser(e,t)}async downloadFile(e,t,n){"use step";let r=await this.readFile(e,n);if(r===null)return null;let i=T(t.cwd??``,t.path);return n?.mkdirRecursive&&await ie(te(i),{recursive:!0}),await E(r,ne(i),{signal:n?.signal}),i}async catAsUser(e,t){let n=e.path.startsWith(`/`)?e.path:`${e.cwd??this.homeDir}/${e.path}`,r=await this.runCommand({cmd:`base64`,args:[n],signal:t?.signal});if(r.exitCode!==0){let e=await r.stderr();if(/No such file or directory/i.test(e))return null;throw Error(`Failed to read ${n}: ${e}`)}return Buffer.from(await r.stdout(),`base64`)}async mkDir(e,t){let n=this.resolvePath(e);await this.sandbox.mkDir(n,t);let r=[n,...this.ancestorDirsUnderHome([n])],{group:i}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(r,`${this.username}:${i}`,t?.signal),await this.chmodOrThrow(r,`770`,t?.signal)}primaryGroup(e){return this.primaryGroupPromise||=this.resolvePrimaryGroup(e).catch(e=>{throw this.primaryGroupPromise=void 0,e}),this.primaryGroupPromise}async resolvePrimaryGroup(e){let t=await this.sandbox.runCommand({cmd:`id`,args:[`-gn`,this.username],signal:e});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the primary group of "${this.username}": ${e}`)}let n=(await t.stdout()).trim();if(!n)throw Error(`Failed to resolve the primary group of "${this.username}"`);return n}async chownOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chown`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set ownership on ${e.join(`, `)}: ${t}`)}}async chmodOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chmod`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set permissions on ${e.join(`, `)}: ${t}`)}}ancestorDirsUnderHome(e){let t=new Set,n=`${this.homeDir}/`;for(let r of e){let e=r.slice(0,r.lastIndexOf(`/`));for(;e.length>this.homeDir.length&&e.startsWith(n);)t.add(e),e=e.slice(0,e.lastIndexOf(`/`))}return[...t]}async addToGroup(e,t){H(e,`group name`),await this.sandbox.addUserToGroup(this.username,e,t)}async removeFromGroup(e,t){H(e,`group name`),await this.sandbox.removeUserFromGroup(this.username,e,t)}};function Tn(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{drive:`mode`in t?t.drive:t.name,mode:`mode`in t?t.mode:`read-write`}]))}function En(e){return e instanceof D&&e.response.status===410}function Dn(e){return e instanceof D&&e.response.status===404}function On(e){return e instanceof D&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function kn(e){return e instanceof D&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function An(e){return e instanceof D&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var jn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region??`iad1`}get failoverRegions(){return this.sandbox.failoverRegions??[]}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get image(){return this.sandbox.image}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get cwd(){return this.currentSession().cwd}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get expiresAt(){if(this.session?.status===`running`){let e=this.session.startedAt??this.session.createdAt;return new Date(e.getTime()+this.session.timeout)}return this.sandbox.expiresAt===void 0?void 0:new Date(this.sandbox.expiresAt)}get tags(){return this.sandbox.tags}get mounts(){return this.sandbox.mounts}get networkPolicy(){return this.sandbox.networkPolicy?Ct(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[r](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[i](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new on({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";if(e?.runtime!==void 0&&e.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=P(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e?.runtime,image:e?.image,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,mounts:Tn(e?.mounts),snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,region:e?.region,failoverRegions:e?.failoverRegions,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new Mn({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(e){"use step";let t=await R(e),n=new F({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=P(e),i=await n.forkSandbox({sourceSandbox:e.sourceSandbox,projectId:t.projectId,name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,networkPolicy:e.networkPolicy,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,persistent:e.persistent,signal:e.signal,...r});return new Mn({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e.onResume})}static async get(t){"use step";let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=P(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(t?.runtime!==void 0&&t.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(Dn(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if(On(n)){let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=P(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!Dn(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new on({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new xn(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new on({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await oe(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new on({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(En(n))return await this.resume(t),e();if(kn(n)||An(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async openInteractive(e){"use step";return this.withResume(()=>this.session.openInteractive(e),e?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}getDefaultUser(e){return this.defaultUserPromise||=this.resolveDefaultUser(e).catch(e=>{throw this.defaultUserPromise=void 0,e}),this.defaultUserPromise}async resolveDefaultUser(e){let t=await this.runCommand({cmd:`sh`,args:[`-c`,`id -un; id -gn`],signal:e?.signal});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the default sandbox user: ${e}`)}let[n,r]=(await t.stdout()).trim().split(`
`);if(!n||!r)throw Error(`Failed to resolve the default sandbox user (got "${n}:${r}")`);return{username:n,group:r}}async createUser(e,t){H(e,`username`);let{group:n}=await this.getDefaultUser(t),r=await this.runCommand({cmd:`useradd`,args:[`-m`,`-s`,`/bin/bash`,e],sudo:!0,signal:t?.signal});if(r.exitCode!==0){if(r.exitCode===9)throw new Cn(e);let t=await r.stderr();throw Error(`Failed to create user "${e}": ${t}`)}let i=await this.runCommand({cmd:`chown`,args:[`${e}:${n}`,`/home/${e}`],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to set ownership on /home/${e}: ${t}`)}let a=await this.runCommand({cmd:`chmod`,args:[`770`,`/home/${e}`],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let t=await a.stderr();throw Error(`Failed to set permissions on /home/${e}: ${t}`)}return new wn({sandbox:this,username:e})}asUser(e){return H(e,`username`),new wn({sandbox:this,username:e})}async createGroup(e,t){H(e,`group name`);let{username:n}=await this.getDefaultUser(t),r=`/shared/${e}`,i=await this.runCommand({cmd:`groupadd`,args:[e],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to create group "${e}": ${t}`)}let a=await this.runCommand({cmd:`mkdir`,args:[`-p`,r],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let e=await a.stderr();throw Error(`Failed to create shared directory ${r}: ${e}`)}let o=await this.runCommand({cmd:`chown`,args:[`${n}:${e}`,r],sudo:!0,signal:t?.signal});if(o.exitCode!==0){let e=await o.stderr();throw Error(`Failed to set ownership on ${r}: ${e}`)}let s=await this.runCommand({cmd:`chmod`,args:[`2770`,r],sudo:!0,signal:t?.signal});if(s.exitCode!==0){let e=await s.stderr();throw Error(`Failed to set permissions on ${r}: ${e}`)}return{groupname:e,sharedDir:r}}async addUserToGroup(e,t,n){H(e,`username`),H(t,`group name`);let r=await this.runCommand({cmd:`usermod`,args:[`-aG`,t,e],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to add "${e}" to group "${t}": ${n}`)}}async removeUserFromGroup(e,t,n){H(e,`username`),H(t,`group name`);let r=await this.runCommand({cmd:`gpasswd`,args:[`-d`,e,t],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to remove "${e}" from group "${t}": ${n}`)}}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions,mounts:Tn(e.mounts),signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.timeout!==void 0&&this.session?.status===`running`){let n=e.timeout-this.session.timeout;if(n>0)try{await this.session.extendTimeout(n,t)}catch(e){if(!En(e)&&!kn(e))throw e}}if(e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(En(e)||kn(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,deleteOrphanSnapshots:e?.deleteOrphanSnapshots,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return z(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return z(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},Mn=class extends jn{async[Symbol.asyncDispose](){await this.stop()}},Nn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await R();return this._client=new F({teamId:e.teamId,token:e.token}),this._client}get driveId(){return this.drive.id}get name(){return this.drive.name}get projectId(){return this._projectId}get region(){return this.drive.region??`iad1`}get maxSize(){return this.drive.maxSizeBytes}get currentSessionId(){return this.drive.currentSessionId}get currentSandboxName(){return this.drive.currentSandboxName}get createdAt(){return new Date(this.drive.createdAt)}get updatedAt(){return new Date(this.drive.updatedAt)}snapshot(){return{drive:this.name,mode:`snapshot`}}static[r](e){return{drive:e.drive,projectId:e._projectId}}static[i](t){return new e({drive:t.drive,projectId:t.projectId})}constructor({client:e,drive:t,projectId:n}){this._client=null,this._client=e??null,this.drive=t,this._projectId=n??t.projectId}static async list(t){"use step";let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t?.fetch}),i=async i=>{let a=await r.listDrives({...n,...t,...i!==void 0&&{cursor:i}});return{...a.json,drives:a.json.drives.map(t=>new e({client:r,drive:t,projectId:n.projectId}))}};return z(await i(t?.cursor),{itemsKey:`drives`,fetchNext:i,signal:t?.signal})}static async getOrCreate(t){"use step";let n=await R(t),r=new F({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,drive:(await r.getOrCreateDrive({projectId:n.projectId,name:t.name,region:t.region,maxSizeBytes:t.maxSize,signal:t.signal})).json.drive,projectId:n.projectId})}async delete(e){"use step";this.drive=(await(await this.ensureClient()).deleteDrive({projectId:this._projectId,name:this.drive.name,signal:e?.signal})).json.drive}};const Pn=new TextEncoder,U=new TextDecoder;function Fn(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function In(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Ln(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Rn(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:U.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=U.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return Ln(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}const W=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),zn=(e,t)=>e.name===t;function Bn(e){return parseInt(e.name.slice(4),10)}function Vn(e,t){if(Bn(e.hash)!==t)throw W(`SHA-${t}`,`algorithm.hash`)}function Hn(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function Un(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Wn(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!zn(e.algorithm,`HMAC`))throw W(`HMAC`);Vn(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!zn(e.algorithm,`RSASSA-PKCS1-v1_5`))throw W(`RSASSA-PKCS1-v1_5`);Vn(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!zn(e.algorithm,`RSA-PSS`))throw W(`RSA-PSS`);Vn(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!zn(e.algorithm,`Ed25519`))throw W(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!zn(e.algorithm,t))throw W(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!zn(e.algorithm,`ECDSA`))throw W(`ECDSA`);let n=Hn(t);if(e.algorithm.namedCurve!==n)throw W(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}Un(e,n)}function Gn(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const Kn=(e,...t)=>Gn(`Key must be `,e,...t),qn=(e,t,...n)=>Gn(`Key for the ${e} algorithm must be `,t,...n);var G=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},K=class extends G{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Jn=class extends G{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Yn=class extends G{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},q=class extends G{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},J=class extends G{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},Y=class extends G{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},Xn=class extends G{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},Zn=class extends G{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},Qn=class extends G{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},$n=class extends G{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},er=class extends G{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};const tr=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},nr=e=>e?.[Symbol.toStringTag]===`KeyObject`,rr=e=>tr(e)||nr(e);function ir(e,t,n){try{return Rn(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}const ar=e=>typeof e==`object`&&!!e;function X(e){if(!ar(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function or(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const sr=e=>X(e)&&typeof e.kty==`string`,cr=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),lr=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,ur=e=>e.kty===`oct`&&typeof e.k==`string`;function dr(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function fr(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new q(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function pr(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(Kn(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return Wn(t,e,n),t}async function mr(e,t,n,r){let i=await pr(e,t,`verify`);dr(e,i);let a=fr(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const hr=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function gr(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new q(hr)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new q(hr)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new q(hr)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new q(hr)}break;default:throw new q(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function _r(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=gr(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const vr=`given KeyObject instance cannot be used for this algorithm`;let Z;const yr=async(e,t,n,r=!1)=>{Z||=new WeakMap;let i=Z.get(e);if(i?.[n])return i[n];let a=await _r({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:Z.set(e,{[n]:a}),a},br=(e,t)=>{Z||=new WeakMap;let n=Z.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(vr)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(vr);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(vr);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(vr)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(vr);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(vr);return n?n[t]=a:Z.set(e,{[t]:a}),a};async function xr(e,t){if(e instanceof Uint8Array||tr(e))return e;if(nr(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return br(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:`jwk`});return yr(e,n,t)}if(sr(e))return e.k?Rn(e.k):yr(e,e,t,!0);throw Error(`unreachable`)}async function Sr(e,t,n){if(!X(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return Rn(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new q(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return _r({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return _r({...e,ext:r});case`EC`:case`OKP`:return _r({...e,alg:t,ext:r});default:throw new q(`Unsupported "kty" (Key Type) Parameter value`)}}function Cr(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new q(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function wr(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const Tr=e=>e?.[Symbol.toStringTag],Er=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},Dr=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(sr(t)){if(ur(t)&&Er(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!rr(t))throw TypeError(qn(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${Tr(t)} instances for symmetric algorithms must be of type "secret"`)}},Or=(e,t,n)=>{if(sr(t))switch(n){case`decrypt`:case`sign`:if(cr(t)&&Er(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(lr(t)&&Er(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!rr(t))throw TypeError(qn(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${Tr(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${Tr(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${Tr(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${Tr(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${Tr(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function kr(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:Dr(e,t,n);break;default:Or(e,t,n)}}async function Ar(e,t,n){if(!X(e))throw new J(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new J(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new J(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new J(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new J(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!X(e.header))throw new J(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=Rn(e.protected);r=JSON.parse(U.decode(t))}catch{throw new J(`JWS Protected Header is invalid`)}if(!or(r,e.header))throw new J(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...r,...e.header},a=Cr(J,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new J(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new J(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&wr(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new Yn(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new J(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new J(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`&&(t=await t(r,e),l=!0),kr(s,t,`verify`);let u=Fn(e.protected===void 0?new Uint8Array:In(e.protected),In(`.`),typeof e.payload==`string`?o?In(e.payload):Pn.encode(e.payload):e.payload),d=ir(e.signature,`signature`,J),f=await xr(t,s);if(!await mr(s,f,d,u))throw new er;let p;p=o?ir(e.payload,`payload`,J):typeof e.payload==`string`?Pn.encode(e.payload):e.payload;let m={payload:p};return e.protected!==void 0&&(m.protectedHeader=r),e.header!==void 0&&(m.unprotectedHeader=e.header),l?{...m,key:f}:m}async function jr(e,t,n){if(e instanceof Uint8Array&&(e=U.decode(e)),typeof e!=`string`)throw new J(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new J(`Invalid Compact JWS`);let s=await Ar({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?{...c,key:s.key}:c}const Mr=e=>Math.floor(e.getTime()/1e3),Nr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Pr(e){let t=Nr.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600)}return t[1]===`-`||t[4]===`ago`?-i:i}const Fr=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,Ir=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function Lr(e,t,n={}){let r;try{r=JSON.parse(U.decode(t))}catch{}if(!X(r))throw new Y(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||Fr(e.typ)!==Fr(i)))throw new K(`unexpected "typ" JWT header value`,r,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in r))throw new K(`missing required "${e}" claim`,r,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new K(`unexpected "iss" claim value`,r,`iss`,`check_failed`);if(s&&r.sub!==s)throw new K(`unexpected "sub" claim value`,r,`sub`,`check_failed`);if(c&&!Ir(r.aud,typeof c==`string`?[c]:c))throw new K(`unexpected "aud" claim value`,r,`aud`,`check_failed`);let d;switch(typeof n.clockTolerance){case`string`:d=Pr(n.clockTolerance);break;case`number`:d=n.clockTolerance;break;case`undefined`:d=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:f}=n,p=Mr(f||new Date);if((r.iat!==void 0||l)&&typeof r.iat!=`number`)throw new K(`"iat" claim must be a number`,r,`iat`,`invalid`);if(r.nbf!==void 0){if(typeof r.nbf!=`number`)throw new K(`"nbf" claim must be a number`,r,`nbf`,`invalid`);if(r.nbf>p+d)throw new K(`"nbf" claim timestamp check failed`,r,`nbf`,`check_failed`)}if(r.exp!==void 0){if(typeof r.exp!=`number`)throw new K(`"exp" claim must be a number`,r,`exp`,`invalid`);if(r.exp<=p-d)throw new Jn(`"exp" claim timestamp check failed`,r,`exp`,`check_failed`)}if(l){let e=p-r.iat,t=typeof l==`number`?l:Pr(l);if(e-d>t)throw new Jn(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,`check_failed`);if(e<0-d)throw new K(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,`check_failed`)}return r}async function Rr(e,t,n){let r=await jr(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new Y(`JWTs MUST NOT use unencoded payload`);let i={payload:Lr(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}function zr(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new q(`Unsupported "alg" value for a JSON Web Key Set`)}}function Br(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(Vr)}function Vr(e){return X(e)}var Hr=class{#e;#t=new WeakMap;constructor(e){if(!Br(e))throw new Xn(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=zr(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`}return t}),{0:o,length:s}=a;if(s===0)throw new Zn;if(s!==1){let e=new Qn,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await Ur(t,e,n)}catch{}},e}return Ur(this.#t,o,n)}};async function Ur(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await Sr({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new Xn(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Wr(e){let t=new Hr(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function Gr(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Kr;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Kr=`jose/v6.2.3`);const qr=Symbol();async function Jr(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new $n:e});if(i.status!==200)throw new G(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new G(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Yr=Symbol();function Xr(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!X(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,X))}var Zr=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),Kr&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,Kr),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[qr],t?.[Yr]!==void 0&&(this.#l=t?.[Yr],Xr(t?.[Yr],this.#r)&&(this.#i=this.#l.uat,this.#c=Wr(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`&&Date.now()<this.#i+this.#n}fresh(){return typeof this.#i==`number`&&Date.now()<this.#i+this.#r}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof Zn&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&Gr()&&(this.#a=void 0),this.#a||=Jr(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=Wr(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function Qr(e,t){let n=new Zr(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}function $r(e){if(typeof e!=`string`)throw new Y(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Y(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Y(`Invalid JWT`);if(!t)throw new Y(`JWTs must contain a payload`);let r;try{r=Rn(t)}catch{throw new Y(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(U.decode(r))}catch{throw new Y(`Failed to parse the decoded payload as JSON`)}if(!X(i))throw new Y(`Invalid JWT Claims Set`);return i}const Q=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,ei=new Set,ti=typeof process==`object`&&process?process:{},ni=(e,t,n,r)=>{typeof ti.emitWarning==`function`?ti.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let ri=globalThis.AbortController,ii=globalThis.AbortSignal;if(ri===void 0){ii=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},ri=class{constructor(){t()}signal=new ii;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=ti.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,ni("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.",`NO_ABORT_CONTROLLER`,`ENOTSUP`,t))}}const ai=e=>!ei.has(e),$=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),oi=e=>$(e)?e<=256?Uint8Array:e<=2**16?Uint16Array:e<=2**32?Uint32Array:e<=2**53-1?si:null:null;var si=class extends Array{constructor(e){super(e),this.fill(0)}},ci=class e{heap;length;static#e=!1;static create(t){let n=oi(t);if(!n)return[];e.#e=!0;let r=new e(t,n);return e.#e=!1,r}constructor(t,n){if(!e.#e)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},li=class e{#e;#t;#n;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;static unsafeExposeInternals(e){return{starts:e.#v,ttls:e.#y,sizes:e.#_,keyMap:e.#c,keyList:e.#l,valList:e.#u,next:e.#d,prev:e.#f,get head(){return e.#p},get tail(){return e.#m},free:e.#h,isBackgroundFetch:t=>e.#L(t),backgroundFetch:(t,n,r,i)=>e.#I(t,n,r,i),moveToTail:t=>e.#z(t),indexes:t=>e.#M(t),rindexes:t=>e.#N(t),isStale:t=>e.#D(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#s}get size(){return this.#o}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:f,maxSize:p=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:_,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:b,allowStaleOnFetchAbort:x,ignoreFetchAbort:S}=t;if(n!==0&&!$(n))throw TypeError(`max option must be a nonnegative integer`);let C=n?oi(n):Array;if(!C)throw Error(`invalid max value: `+n);if(this.#e=n,this.#t=p,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(_!==void 0&&typeof _!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#a=_,g!==void 0&&typeof g!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#i=g,this.#x=!!g,this.#c=new Map,this.#l=Array(n).fill(void 0),this.#u=Array(n).fill(void 0),this.#d=new C(n),this.#f=new C(n),this.#p=0,this.#m=0,this.#h=ci.create(n),this.#o=0,this.#s=0,typeof l==`function`&&(this.#n=l),typeof u==`function`?(this.#r=u,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#b=!!this.#n,this.#S=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!b,this.allowStaleOnFetchAbort=!!x,this.ignoreFetchAbort=!!S,this.maxEntrySize!==0){if(this.#t!==0&&!$(this.#t))throw TypeError(`maxSize must be a positive integer if specified`);if(!$(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#O()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=$(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!$(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#C()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#e&&!this.#t){let t=`LRU_CACHE_UNBOUNDED`;ai(t)&&(ei.add(t),ni(`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`,`UnboundedCacheWarning`,t,e))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#C(){let e=new si(this.#e),t=new si(this.#e);this.#y=e,this.#v=t,this.#E=(n,r,i=Q.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#D(n)&&this.#B(this.#l[n],`expire`)},r+1);e.unref&&e.unref()}},this.#w=n=>{t[n]=e[n]===0?0:Q.now()},this.#T=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r(),i.remainingTTL=o-(i.now-s)}};let n=0,r=()=>{let e=Q.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#c.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];return!o||!s?1/0:o-((n||r())-s)},this.#D=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#w=()=>{};#T=()=>{};#E=()=>{};#D=()=>!1;#O(){let e=new si(this.#e);this.#s=0,this.#_=e,this.#k=t=>{this.#s-=e[t],e[t]=0},this.#j=(e,t,n,r)=>{if(this.#L(t))return 0;if(!$(n)){if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!$(n))throw TypeError(`sizeCalculation return invalid (expect positive integer)`)}else throw TypeError(`invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.`)}return n},this.#A=(t,n,r)=>{if(e[t]=n,this.#t){let n=this.#t-e[t];for(;this.#s>n;)this.#F(!0)}this.#s+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#s)}}#k=e=>{};#A=(e,t,n)=>{};#j=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#M({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#m;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#p));)t=this.#f[t]}*#N({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#p;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#m));)t=this.#d[t]}#P(e){return e!==void 0&&this.#c.get(this.#l[e])===e}*entries(){for(let e of this.#M())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*rentries(){for(let e of this.#N())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*keys(){for(let e of this.#M()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*rkeys(){for(let e of this.#N()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*values(){for(let e of this.#M())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}*rvalues(){for(let e of this.#N())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#N()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#N({allowStale:!0}))this.#D(t)&&(this.#B(this.#l[t],`expire`),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#u[t],r=this.#L(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#y&&this.#v){let e=this.#y[t],n=this.#v[t];e&&n&&(i.ttl=e-(Q.now()-n),i.start=Date.now())}return this.#_&&(i.size=this.#_[t]),i}dump(){let e=[];for(let t of this.#M({allowStale:!0})){let n=this.#l[t],r=this.#u[t],i=this.#L(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#y&&this.#v){a.ttl=this.#y[t];let e=Q.now()-this.#v[t];a.start=Math.floor(Date.now()-e)}this.#_&&(a.size=this.#_[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=Q.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#j(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#B(e,`set`),this;let u=this.#o===0?void 0:this.#c.get(e);if(u===void 0)u=this.#o===0?this.#m:this.#h.length===0?this.#o===this.#e?this.#F(!1):this.#o:this.#h.pop(),this.#l[u]=e,this.#u[u]=t,this.#c.set(e,u),this.#d[this.#m]=u,this.#f[u]=this.#m,this.#m=u,this.#o++,this.#A(u,l,s),s&&(s.set=`add`),c=!1;else{this.#z(u);let n=this.#u[u];if(t!==n){if(this.#x&&this.#L(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#b&&this.#n?.(t,e,`set`),this.#S&&this.#g?.push([t,e,`set`]))}else a||(this.#b&&this.#n?.(n,e,`set`),this.#S&&this.#g?.push([n,e,`set`]));if(this.#k(u),this.#A(u,l,s),this.#u[u]=t,s){s.set=`replace`;let e=n&&this.#L(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`)}if(r!==0&&!this.#y&&this.#C(),this.#y&&(c||this.#E(u,r,i),s&&this.#T(s,u)),!a&&this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return this}pop(){try{for(;this.#o;){let e=this.#u[this.#p];if(this.#F(!0),this.#L(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],r=this.#u[t];return this.#x&&this.#L(r)?r.__abortController.abort(Error(`evicted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(r,n,`evict`),this.#S&&this.#g?.push([r,n,`evict`])),this.#k(t),e&&(this.#l[t]=void 0,this.#u[t]=void 0,this.#h.push(t)),this.#o===1?(this.#p=this.#m=0,this.#h.length=0):this.#p=this.#d[t],this.#c.delete(n),this.#o--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#c.get(e);if(i!==void 0){let e=this.#u[i];if(this.#L(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#D(i))r&&(r.has=`stale`,this.#T(r,i));else return n&&this.#w(i),r&&(r.has=`hit`,this.#T(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#c.get(e);if(r===void 0||!n&&this.#D(r))return;let i=this.#u[r];return this.#L(i)?i.__staleWhileFetching:i}#I(e,t,n,r){let i=t===void 0?void 0:this.#u[t];if(this.#L(i))return i;let a=new ri,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#u[t]===f&&(r===void 0?l.__staleWhileFetching?this.#u[t]=l.__staleWhileFetching:this.#B(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#u[t]===f&&(!c||l.__staleWhileFetching===void 0?this.#B(e,`fetch`):o||(this.#u[t]=l.__staleWhileFetching)),s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#i?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#c.get(e)):this.#u[t]=p,p}#L(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof ri}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:_}=t;if(!this.#x)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:_},y=this.#c.get(e);if(y===void 0){g&&(g.fetch=`miss`);let t=this.#I(e,y,v,m);return t.__returned=t}{let t=this.#u[y];if(this.#L(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#D(y);if(!h&&!i)return g&&(g.fetch=`hit`),this.#z(y),r&&this.#w(y),g&&this.#T(g,y),t;let a=this.#I(e,y,v,m),o=a.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=i?`stale`:`refresh`,o&&i&&(g.returnedStale=!0)),o?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#a;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#c.get(e);if(o!==void 0){let t=this.#u[o],s=this.#L(t);return a&&this.#T(a,o),this.#D(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#B(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#z(o),r&&this.#w(o),t))}a&&(a.get=`miss`)}#R(e,t){this.#f[t]=e,this.#d[e]=t}#z(e){e!==this.#m&&(e===this.#p?this.#p=this.#d[e]:this.#R(this.#f[e],this.#d[e]),this.#R(this.#m,e),this.#m=e)}delete(e){return this.#B(e,`delete`)}#B(e,t){let n=!1;if(this.#o!==0){let r=this.#c.get(e);if(r!==void 0){if(n=!0,this.#o===1)this.#V(t);else{this.#k(r);let n=this.#u[r];if(this.#L(n)?n.__abortController.abort(Error(`deleted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(n,e,t),this.#S&&this.#g?.push([n,e,t])),this.#c.delete(e),this.#l[r]=void 0,this.#u[r]=void 0,r===this.#m)this.#m=this.#f[r];else if(r===this.#p)this.#p=this.#d[r];else{let e=this.#f[r];this.#d[e]=this.#d[r];let t=this.#d[r];this.#f[t]=this.#f[r]}this.#o--,this.#h.push(r)}}}if(this.#S&&this.#g?.length){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return n}clear(){return this.#V(`delete`)}#V(e){for(let t of this.#N({allowStale:!0})){let n=this.#u[t];if(this.#L(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#l[t];this.#b&&this.#n?.(n,r,e),this.#S&&this.#g?.push([n,r,e])}}if(this.#c.clear(),this.#u.fill(void 0),this.#l.fill(void 0),this.#y&&this.#v&&(this.#y.fill(0),this.#v.fill(0)),this.#_&&this.#_.fill(0),this.#p=0,this.#m=0,this.#h.length=0,this.#s=0,this.#o=0,this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}};const ui=`vercel-forwarded-host`,di=`vercel-forwarded-scheme`,fi=`vercel-forwarded-port`,pi=`vercel-forwarded-path`,mi=`vercel-sandbox-oidc-token`,hi=new li({max:100});function gi(e,t=_i){return async function(n){let r=new Headers(n.headers),i=r.get(ui),a=r.get(di),o=r.get(fi),s=r.get(pi),c=r.get(mi);if(r.delete(ui),r.delete(di),r.delete(fi),r.delete(pi),r.delete(mi),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(vi(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=yi(new URL(n.url),s),r=await Si(c,t),i=xi(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function _i(){return new Response(`Forbidden`,{status:403})}function vi(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function yi(e,t){let n=bi(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=bi(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=bi(r.pathname.slice(0,-n.length))),r}function bi(e){return e.replace(/\/+$/,``)||`/`}function xi(e,t){let n=Ti(t,`team_id`),r=Ti(t,`project_id`),i=Ti(t,`sandbox_id`),a=Ti(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function Si(e,t){let n=Ti($r(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await Rr(e,wi(n),{audience:Ci(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function Ci(e){let t=bi(e.pathname);return t===`/`?e.origin:e.origin+t}function wi(e){let t=hi.get(e);if(t)return t;let n=Qr(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return hi.set(e,n),n}function Ti(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{D as APIError,en as Command,tn as CommandFinished,se as DEFAULT_SANDBOX_REGION,Nn as Drive,xn as FileSystem,jn as Sandbox,wn as SandboxUser,Cn as SandboxUserAlreadyExistsError,on as Session,rn as Snapshot,O as StreamError,gi as defineSandboxProxy};