@opencoredev/sandbox-sdk 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/ai.js +1 -1
- package/dist/{chunk-ek44atpe.js → chunk-08jjwqh4.js} +2 -2
- package/dist/{chunk-kdecey83.js → chunk-16kht6jp.js} +13 -13
- package/dist/{chunk-7s9pxk1v.js → chunk-4m1br1sq.js} +4 -4
- package/dist/{chunk-x4rrgmxf.js → chunk-9a843q9b.js} +10 -10
- package/dist/chunk-9v2dntaq.js +84 -0
- package/dist/chunk-adrd5ka7.js +2 -0
- package/dist/{chunk-pdgnaxp9.js → chunk-bfvk7mnq.js} +2 -2
- package/dist/chunk-bvwsd99g.js +17 -0
- package/dist/chunk-h6xh0pr0.js +2 -0
- package/dist/{chunk-aq6fmgdx.js → chunk-k26rjbb9.js} +2 -2
- package/dist/chunk-kq1xms6a.js +2 -0
- package/dist/chunk-m7hbefp1.js +2 -0
- package/dist/{chunk-qfhee1t8.js → chunk-n0f7xz7g.js} +2 -2
- package/dist/chunk-qdc1zgmf.js +5 -0
- package/dist/{chunk-x05t86n3.js → chunk-szwxave3.js} +2 -2
- package/dist/chunk-xw0znbmg.js +78 -0
- package/dist/chunk-xx9znywe.js +4 -0
- package/dist/chunk-y86x0kmz.js +1 -0
- package/dist/chunk-z1pmcdka.js +2 -0
- package/dist/chunk-zygv9qfq.js +26 -0
- package/dist/handle.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/mastra.js +1 -1
- package/dist/memory.js +1 -1
- package/dist/openai.js +1 -1
- package/dist/provider.d.ts +19 -0
- package/dist/provider.js +1 -1
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/archil/errors.d.ts +16 -0
- package/dist/providers/archil/execute.d.ts +89 -0
- package/dist/providers/archil/index.d.ts +3 -0
- package/dist/providers/archil/index.js +25 -0
- package/dist/providers/archil/provider.d.ts +25 -0
- package/dist/providers/baseten/index.js +5 -5
- package/dist/providers/beam/api.d.ts +54 -0
- package/dist/providers/beam/errors.d.ts +25 -0
- package/dist/providers/beam/execute.d.ts +11 -0
- package/dist/providers/beam/index.d.ts +9 -0
- package/dist/providers/beam/index.js +1 -0
- package/dist/providers/beam/provider.d.ts +75 -0
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boxd/index.js +5 -5
- package/dist/providers/daytona/index.js +14 -14
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/freestyle/index.js +6 -6
- package/dist/providers/instabox/index.js +5 -5
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/modal/index.js +2 -2
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/index.js +2 -84
- package/dist/providers/tenki/index.js +10 -10
- package/dist/providers/upstash/index.js +10 -10
- package/dist/providers/vercel/index.js +1 -1
- package/dist/testing.js +3 -3
- package/dist/tools.js +1 -1
- package/dist/version.d.ts +2 -2
- package/package.json +19 -1
- package/dist/chunk-0eeyc0aq.js +0 -4
- package/dist/chunk-0wp6x4wb.js +0 -2
- package/dist/chunk-2999xbh7.js +0 -2
- package/dist/chunk-3h6c1ack.js +0 -2
- package/dist/chunk-7rkcx5cx.js +0 -2
- package/dist/chunk-aek8n3a4.js +0 -78
- package/dist/chunk-drhcb2hx.js +0 -2
- package/dist/chunk-rx9318sh.js +0 -5
- package/dist/chunk-sjnk17y5.js +0 -26
- package/dist/chunk-w8nk1xf2.js +0 -17
- package/dist/chunk-xqtzts2q.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{H}from"../../chunk-7s9pxk1v.js";import{A}from"../../chunk-aq6fmgdx.js";import{m,J,g,C,_}from"../../chunk-kdecey83.js";import{N,b,S,P}from"../../chunk-ek44atpe.js";import{f,w,v}from"../../chunk-2999xbh7.js";import{t,o,r,e,i,d,a}from"../../chunk-0eeyc0aq.js";import{createHash as Je}from"node:crypto";import{AsyncLocalStorage as _e}from"node:async_hooks";import{createHash as Oe}from"node:crypto";import{AsyncLocalStorage as Me}from"node:async_hooks";import{AsyncLocalStorage as Ie}from"node:async_hooks";var ne=new Ie,Re=new Set(["v5","vms","fs","read","write","uploads","commit","dir","mkdir","remove","exists","stat","exec-await","firewall","rules","tls","pause","start","snapshot","snapshots","background-requests"]);function ye(s){return(s.split("?")[0]??"").split("/").map((c)=>Re.has(c)?c:c?":id":"").join("/")}function he(s,c="GET",y){let x=ne.getStore();if(!x)return;if(y&&!x.deniedValues?.includes(y))x.deniedValues=[...x.deniedValues??[],y];let F=new URL(s instanceof Request?s.url:s).pathname;if(!F.startsWith("/v5/background-requests/")||!x.operation)x.operation=`${/^(GET|POST|PUT|DELETE|PATCH|HEAD)$/.test(c)?c:"REQUEST"} ${ye(F)}`,delete x.backgroundRequestId;delete x.status,delete x.requestId}function ge(s,c){let y=ne.getStore();if(!y)return;y.status=s.status;let x=s.headers.get("x-freestyle-background-request-id"),F=(T)=>T&&/^[A-Za-z0-9_-]{1,128}$/.test(T)&&!T.includes(c)&&!y.deniedValues?.some((q)=>T.includes(q))?T:void 0;if(F(x))y.backgroundRequestId=F(x);y.requestId=F(s.headers.get("x-request-id"))??F(s.headers.get("x-freestyle-request-id"))??y.backgroundRequestId}function E(s,c="provider",y,x){return new e(c==="auth"?s:`${s}. Check Freestyle configuration and retry.`,{code:c,provider:"freestyle",sandboxId:y,cause:x})}class se extends Error{status;code;path;backgroundRequestId;name="FreestyleApiError";constructor(s,c,y,x,F){super(y||`Freestyle API error: ${c??s}`);this.status=s;this.code=c;this.path=x;this.backgroundRequestId=F}}var Te=new Map([[400,"invalid_argument"],[401,"auth"],[403,"auth"],[404,"not_found"],[402,"quota"],[408,"timeout"],[429,"quota"],[500,"unavailable"],[502,"unavailable"],[503,"unavailable"],[504,"timeout"]]),Ae=(s,c)=>s===404&&/no such file or directory|\bos error 2\b/i.test(c??""),le=(s,c)=>Ae(s,c)?"file_not_found":Te.get(s)??"provider";function re(s,c){if(s instanceof e)return s;let y=r(s)&&"status"in s?s.status:void 0,x=ne.getStore(),F={};if(o(y)&&Number.isInteger(y)&&y>=100&&y<=599)F.status=y;if(r(s)){if("code"in s&&t(s.code)&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.code)){let G=s.code;if(!x?.deniedValues?.some((I)=>G.includes(I)))F.providerCode=G}if("path"in s&&t(s.path))F.operation=ye(s.path)}if(x?.operation)F.operation=x.operation;if(x?.status===y&&x?.requestId)F.requestId=x.requestId;let T=o(y)?le(y,s instanceof Error?s.message:void 0):s instanceof Error&&(s.name==="TimeoutError"||s.name==="AbortError")?s.name==="TimeoutError"?"timeout":"aborted":s instanceof Error&&s.name==="FreestyleTransportError"?"unavailable":"provider",{detail:q}=i(s,{code:T,status:y===void 0?void 0:String(y),redact:d([process.env.FREESTYLE_API_KEY,...x?.deniedValues??[]])});if(q!==void 0)F.native=q;let L=Object.keys(F).length?Object.assign(Error(JSON.stringify(F)),F):void 0;return E(`Freestyle request failed: ${a(T,F.native)}`,T,c,L)}var Q=new Me;async function we(s,c,y){if(y?.aborted)throw E("Operation aborted","aborted");let x=f(c,y),F=()=>x.parent?.aborted&&!x.timeout.aborted?E("Operation aborted","aborted"):E("Native operation timed out","timeout"),T=()=>{},q=new Promise((L,G)=>{if(T=()=>G(F()),x.signal.addEventListener("abort",T,{once:!0}),x.signal.aborted)T()});try{if(x.signal.aborted)throw F();return await Promise.race([Q.run(x,s),q])}finally{x.signal.removeEventListener("abort",T)}}var xe="https://api.freestyle.sh",Ce="x-freestyle-background-after-secs",be="x-freestyle-background-request-id",ie={afterSecs:5,pollMs:2000,unavailableMs:300000,hopMs:30000},Ve=new Set([408,429,502,503,504]),qe=8388608,De=16777216,je=5,ve={"content-type":"application/octet-stream"},Ne=4294967296,Z=(s)=>typeof s==="object"&&s!==null&&!Array.isArray(s);function ee(s,c){throw E(`Freestyle returned an unexpected ${s}`,"provider",c)}function de(s){return s===void 0||s===null||typeof s==="number"}function ce(s,c){if(!Z(s)||!t(s.id)||!t(s.state))ee("VM record",c);let y={};if(s.metadata!==void 0&&s.metadata!==null){if(!Z(s.metadata))ee("VM record",c);for(let[G,I]of Object.entries(s.metadata))if(t(I))Object.defineProperty(y,G,{value:I,enumerable:!0})}let{idleTimeoutSeconds:x,ttlSeconds:F,autoDeleteSeconds:T,vpcs:q,createdAt:L}=s;if(!de(x)||!de(F)||!de(T)||q!==void 0&&!Array.isArray(q)||L!==void 0&&!t(L))ee("VM record",c);return{id:s.id,state:s.state,metadata:y,createdAt:L??"",idleTimeoutSeconds:x,ttlSeconds:F,autoDeleteSeconds:T,vpcs:q}}function Ue(s){if(s===void 0||s===null)return[];if(!Array.isArray(s))ee("firewall rule list");return s.map((c)=>{if(!Z(c)||!t(c.action)||!Z(c.source)||!Z(c.destination))ee("firewall rule");return{action:c.action,source:c.source,destination:c.destination}})}function He(s,c){if(!Z(s)||!de(s.statusCode)||s.stdout!==void 0&&s.stdout!==null&&!t(s.stdout)||s.stderr!==void 0&&s.stderr!==null&&!t(s.stderr))ee("command result",c);return{statusCode:s.statusCode??null,stdout:s.stdout,stderr:s.stderr}}function fe(s,c){if(!Z(s)||!t(s.uploadId)||!Number.isSafeInteger(s.receivedBytes))ee("upload session",c);return{uploadId:s.uploadId,receivedBytes:Number(s.receivedBytes)}}var ae=(s,c)=>{let y=Z(s)?s[c]:void 0;return t(y)&&y?y:void 0};function ke(s){let c=new _e,y,x=()=>(y=s.apiKey(),{authorization:`Bearer ${y}`}),F=v({provider:"freestyle",label:"Freestyle",defaultPlane:"api",planes:{api:{baseUrl:s.baseUrl,auth:x}},timeoutMs:s.requestTimeoutMs,secrets:()=>[process.env.FREESTYLE_API_KEY,y],authHint:"Set FREESTYLE_API_KEY to a valid Freestyle API key, or pass apiKey.",async fetch(u,k){he(u,k.method,y);let R=await globalThis.fetch(u,k);if(y!==void 0)ge(R,y);return R},mapError(u){let k=c.getStore();if(k)k.failure=u;return u.kind==="status"?le(u.status,u.body.message):void 0}});async function T(u){let k={};try{return await c.run(k,()=>F.request(u))}catch(R){let M=k.failure;if(M?.kind!=="status")throw R;throw new se(M.status,M.body.code,M.body.message,u.path,M.headers.get(be)??void 0)}}let q=()=>Q.getStore()??f(s.requestTimeoutMs),L=(u)=>u instanceof se?Ve.has(u.status)&&u.backgroundRequestId===void 0:u instanceof e&&(u.code==="unavailable"||u.code==="timeout");async function G(u,k,R){let M;try{M=u.json()}catch{M=void 0}let U=u.headers.get(be)??ae(M,"requestId"),j=ae(M,"resultUrl")??(U===void 0?void 0:`/v5/background-requests/${encodeURIComponent(U)}`);if(j===void 0||/[{}]/.test(j))throw new se(u.status,"BACKGROUND_PROTOCOL_ERROR","202 Accepted carried no background request id",k);let n;for(;;){await w(ie.pollMs,R,"freestyle");try{let p=f(Math.min(ie.hopMs,R.remaining()),R.signal),l=await T({method:"GET",path:j,deadline:p});if(l.status!==202)return l;n=void 0}catch(p){if(R.signal.aborted||!L(p))throw p;if(n??=Date.now(),Date.now()-n>=ie.unavailableMs)throw p}}}async function I(u){let k=q(),R={...u,deadline:k},M=await T({...R,headers:{...u.headers,[Ce]:String(ie.afterSecs)}});if(M.status!==202)return M;try{return await G(M,u.path,k)}catch(U){if(u.method==="GET"&&U instanceof se&&U.code==="BACKGROUND_RESULT_UNSTORABLE")return await T(R);throw U}}let Y=(u)=>({params:{id:u},sandboxId:u});async function ue(u,k,R,M){let U={path:"/v5/vms/{id}/fs/uploads/{upload}",params:{id:u,upload:k},sandboxId:u};for(let j=1;;j++)try{return fe((await I({...U,method:"PUT",query:{offset:M},body:R,headers:ve})).json(),u)}catch(n){let p=n instanceof se?n.status>=500||n.status===408||n.status===409||n.status===429:L(n),l=q();if(!p||l.signal.aborted||j>=je)throw n;await w(Math.min(500*2**(j-1),8000),l,"freestyle");let h=await I({...U,method:"GET"}).then((O)=>fe(O.json(),u),()=>{return});if(h&&h.receivedBytes>M)return h}}return{http:F,async createVm(u){let k=(await I({method:"POST",path:"/v5/vms",body:u})).json();return{data:ce(k),firewallRules:Ue(Z(k)?k.firewallRules:void 0),tlsRules:Z(k)&&Array.isArray(k.tlsRules)?k.tlsRules:[]}},async listVms(u,k){let R=(await I({method:"GET",path:"/v5/vms",query:{limit:u,offset:k}})).json();if(!Z(R)||!Array.isArray(R.vms)||!Number.isSafeInteger(R.totalCount))ee("VM list");return{vms:R.vms.map((M)=>ce(M)),totalCount:Number(R.totalCount)}},async getVm(u){return ce((await I({method:"GET",path:"/v5/vms/{id}",...Y(u)})).json(),u)},async deleteVm(u){await I({method:"DELETE",path:"/v5/vms/{id}",...Y(u)})},async exec(u,k){return He((await I({method:"POST",path:"/v5/vms/{id}/exec-await",...Y(u),body:{...k,linuxUser:"root"}})).json(),u)},async lifecycle(u,k){await I({method:"POST",path:`/v5/vms/{id}/${k}`,...Y(u),body:{}})},async snapshot(u,k){let R=(await I({method:"POST",path:"/v5/vms/{id}/snapshot",...Y(u),body:k})).json(),M=ae(R,"snapshotId");if(M===void 0)ee("snapshot result",u);return M},async createTlsRule(u){let k=ae((await I({method:"POST",path:"/v5/tls",body:u})).json(),"domain");if(k===void 0)ee("TLS rule");return{domain:k}},async readFile(u,k,R){let M=R?{range:`bytes=${R.offset}-${R.offset+R.length-1}`}:void 0;return(await T({method:"GET",path:"/v5/vms/{id}/fs/read",...Y(u),query:{path:k},deadline:q(),maxBytes:Ne,headers:M})).body},async writeFile(u,k,R,M){let U=Oe("sha256").update(R).digest("hex");if(R.byteLength<=qe){await I({method:"PUT",path:"/v5/vms/{id}/fs/write",...Y(u),query:{path:k,mode:M,sha256:U},body:R,headers:ve});return}let j=R.byteLength,n=fe((await I({method:"POST",path:"/v5/vms/{id}/fs/uploads",...Y(u),body:{path:k,size:j,sha256:U,mode:M}})).json(),u),p={id:u,upload:n.uploadId};try{let l=n.receivedBytes;while(l<j){let h=(await ue(u,n.uploadId,R.subarray(l,Math.min(l+De,j)),l)).receivedBytes;if(h<=l)throw E("Freestyle upload made no progress","provider",u);l=h}await I({method:"POST",path:"/v5/vms/{id}/fs/uploads/{upload}/commit",params:p,sandboxId:u,body:{}})}catch(l){throw await F.cleanup({method:"DELETE",path:"/v5/vms/{id}/fs/uploads/{upload}",params:p,sandboxId:u}).catch(()=>{}),l}}}}var pe=`import os,sys,marshal,_signal as signal,select,time,fcntl
|
|
2
|
-
${
|
|
3
|
-
${
|
|
1
|
+
import{q}from"../../chunk-4m1br1sq.js";import{C}from"../../chunk-k26rjbb9.js";import{c,X,x,M,k}from"../../chunk-16kht6jp.js";import{B,b,E,T}from"../../chunk-08jjwqh4.js";import{h,y,v}from"../../chunk-kq1xms6a.js";import{t,o,r,e,i,u,a}from"../../chunk-xx9znywe.js";import{createHash as Je}from"node:crypto";import{AsyncLocalStorage as _e}from"node:async_hooks";import{createHash as Oe}from"node:crypto";import{AsyncLocalStorage as Me}from"node:async_hooks";import{AsyncLocalStorage as Ie}from"node:async_hooks";var ne=new Ie,Re=new Set(["v5","vms","fs","read","write","uploads","commit","dir","mkdir","remove","exists","stat","exec-await","firewall","rules","tls","pause","start","snapshot","snapshots","background-requests"]);function ye(s){return(s.split("?")[0]??"").split("/").map((f)=>Re.has(f)?f:f?":id":"").join("/")}function he(s,f="GET",m){let w=ne.getStore();if(!w)return;if(m&&!w.deniedValues?.includes(m))w.deniedValues=[...w.deniedValues??[],m];let F=new URL(s instanceof Request?s.url:s).pathname;if(!F.startsWith("/v5/background-requests/")||!w.operation)w.operation=`${/^(GET|POST|PUT|DELETE|PATCH|HEAD)$/.test(f)?f:"REQUEST"} ${ye(F)}`,delete w.backgroundRequestId;delete w.status,delete w.requestId}function ge(s,f){let m=ne.getStore();if(!m)return;m.status=s.status;let w=s.headers.get("x-freestyle-background-request-id"),F=(A)=>A&&/^[A-Za-z0-9_-]{1,128}$/.test(A)&&!A.includes(f)&&!m.deniedValues?.some((D)=>A.includes(D))?A:void 0;if(F(w))m.backgroundRequestId=F(w);m.requestId=F(s.headers.get("x-request-id"))??F(s.headers.get("x-freestyle-request-id"))??m.backgroundRequestId}function P(s,f="provider",m,w){return new e(f==="auth"?s:`${s}. Check Freestyle configuration and retry.`,{code:f,provider:"freestyle",sandboxId:m,cause:w})}class se extends Error{status;code;path;backgroundRequestId;name="FreestyleApiError";constructor(s,f,m,w,F){super(m||`Freestyle API error: ${f??s}`);this.status=s;this.code=f;this.path=w;this.backgroundRequestId=F}}var Te=new Map([[400,"invalid_argument"],[401,"auth"],[403,"auth"],[404,"not_found"],[402,"quota"],[408,"timeout"],[429,"quota"],[500,"unavailable"],[502,"unavailable"],[503,"unavailable"],[504,"timeout"]]),Ae=(s,f)=>s===404&&/no such file or directory|\bos error 2\b/i.test(f??""),le=(s,f)=>Ae(s,f)?"file_not_found":Te.get(s)??"provider";function re(s,f){if(s instanceof e)return s;let m=r(s)&&"status"in s?s.status:void 0,w=ne.getStore(),F={};if(o(m)&&Number.isInteger(m)&&m>=100&&m<=599)F.status=m;if(r(s)){if("code"in s&&t(s.code)&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.code)){let L=s.code;if(!w?.deniedValues?.some((I)=>L.includes(I)))F.providerCode=L}if("path"in s&&t(s.path))F.operation=ye(s.path)}if(w?.operation)F.operation=w.operation;if(w?.status===m&&w?.requestId)F.requestId=w.requestId;let A=o(m)?le(m,s instanceof Error?s.message:void 0):s instanceof Error&&(s.name==="TimeoutError"||s.name==="AbortError")?s.name==="TimeoutError"?"timeout":"aborted":s instanceof Error&&s.name==="FreestyleTransportError"?"unavailable":"provider",{detail:D}=i(s,{code:A,status:m===void 0?void 0:String(m),redact:u([process.env.FREESTYLE_API_KEY,...w?.deniedValues??[]])});if(D!==void 0)F.native=D;let K=Object.keys(F).length?Object.assign(Error(JSON.stringify(F)),F):void 0;return P(`Freestyle request failed: ${a(A,F.native)}`,A,f,K)}var Q=new Me;async function we(s,f,m){if(m?.aborted)throw P("Operation aborted","aborted");let w=h(f,m),F=()=>w.parent?.aborted&&!w.timeout.aborted?P("Operation aborted","aborted"):P("Native operation timed out","timeout"),A=()=>{},D=new Promise((K,L)=>{if(A=()=>L(F()),w.signal.addEventListener("abort",A,{once:!0}),w.signal.aborted)A()});try{if(w.signal.aborted)throw F();return await Promise.race([Q.run(w,s),D])}finally{w.signal.removeEventListener("abort",A)}}var xe="https://api.freestyle.sh",Ce="x-freestyle-background-after-secs",be="x-freestyle-background-request-id",ie={afterSecs:5,pollMs:2000,unavailableMs:300000,hopMs:30000},Ve=new Set([408,429,502,503,504]),qe=8388608,De=16777216,je=5,ve={"content-type":"application/octet-stream"},Ne=4294967296,Y=(s)=>typeof s==="object"&&s!==null&&!Array.isArray(s);function ee(s,f){throw P(`Freestyle returned an unexpected ${s}`,"provider",f)}function de(s){return s===void 0||s===null||typeof s==="number"}function ce(s,f){if(!Y(s)||!t(s.id)||!t(s.state))ee("VM record",f);let m={};if(s.metadata!==void 0&&s.metadata!==null){if(!Y(s.metadata))ee("VM record",f);for(let[L,I]of Object.entries(s.metadata))if(t(I))Object.defineProperty(m,L,{value:I,enumerable:!0})}let{idleTimeoutSeconds:w,ttlSeconds:F,autoDeleteSeconds:A,vpcs:D,createdAt:K}=s;if(!de(w)||!de(F)||!de(A)||D!==void 0&&!Array.isArray(D)||K!==void 0&&!t(K))ee("VM record",f);return{id:s.id,state:s.state,metadata:m,createdAt:K??"",idleTimeoutSeconds:w,ttlSeconds:F,autoDeleteSeconds:A,vpcs:D}}function Ue(s){if(s===void 0||s===null)return[];if(!Array.isArray(s))ee("firewall rule list");return s.map((f)=>{if(!Y(f)||!t(f.action)||!Y(f.source)||!Y(f.destination))ee("firewall rule");return{action:f.action,source:f.source,destination:f.destination}})}function He(s,f){if(!Y(s)||!de(s.statusCode)||s.stdout!==void 0&&s.stdout!==null&&!t(s.stdout)||s.stderr!==void 0&&s.stderr!==null&&!t(s.stderr))ee("command result",f);return{statusCode:s.statusCode??null,stdout:s.stdout,stderr:s.stderr}}function fe(s,f){if(!Y(s)||!t(s.uploadId)||!Number.isSafeInteger(s.receivedBytes))ee("upload session",f);return{uploadId:s.uploadId,receivedBytes:Number(s.receivedBytes)}}var ae=(s,f)=>{let m=Y(s)?s[f]:void 0;return t(m)&&m?m:void 0};function ke(s){let f=new _e,m,w=()=>(m=s.apiKey(),{authorization:`Bearer ${m}`}),F=v({provider:"freestyle",label:"Freestyle",defaultPlane:"api",planes:{api:{baseUrl:s.baseUrl,auth:w}},timeoutMs:s.requestTimeoutMs,secrets:()=>[process.env.FREESTYLE_API_KEY,m],authHint:"Set FREESTYLE_API_KEY to a valid Freestyle API key, or pass apiKey.",async fetch(d,S){he(d,S.method,m);let R=await globalThis.fetch(d,S);if(m!==void 0)ge(R,m);return R},mapError(d){let S=f.getStore();if(S)S.failure=d;return d.kind==="status"?le(d.status,d.body.message):void 0}});async function A(d){let S={};try{return await f.run(S,()=>F.request(d))}catch(R){let _=S.failure;if(_?.kind!=="status")throw R;throw new se(_.status,_.body.code,_.body.message,d.path,_.headers.get(be)??void 0)}}let D=()=>Q.getStore()??h(s.requestTimeoutMs),K=(d)=>d instanceof se?Ve.has(d.status)&&d.backgroundRequestId===void 0:d instanceof e&&(d.code==="unavailable"||d.code==="timeout");async function L(d,S,R){let _;try{_=d.json()}catch{_=void 0}let U=d.headers.get(be)??ae(_,"requestId"),N=ae(_,"resultUrl")??(U===void 0?void 0:`/v5/background-requests/${encodeURIComponent(U)}`);if(N===void 0||/[{}]/.test(N))throw new se(d.status,"BACKGROUND_PROTOCOL_ERROR","202 Accepted carried no background request id",S);let n;for(;;){await y(ie.pollMs,R,"freestyle");try{let p=h(Math.min(ie.hopMs,R.remaining()),R.signal),l=await A({method:"GET",path:N,deadline:p});if(l.status!==202)return l;n=void 0}catch(p){if(R.signal.aborted||!K(p))throw p;if(n??=Date.now(),Date.now()-n>=ie.unavailableMs)throw p}}}async function I(d){let S=D(),R={...d,deadline:S},_=await A({...R,headers:{...d.headers,[Ce]:String(ie.afterSecs)}});if(_.status!==202)return _;try{return await L(_,d.path,S)}catch(U){if(d.method==="GET"&&U instanceof se&&U.code==="BACKGROUND_RESULT_UNSTORABLE")return await A(R);throw U}}let z=(d)=>({params:{id:d},sandboxId:d});async function ue(d,S,R,_){let U={path:"/v5/vms/{id}/fs/uploads/{upload}",params:{id:d,upload:S},sandboxId:d};for(let N=1;;N++)try{return fe((await I({...U,method:"PUT",query:{offset:_},body:R,headers:ve})).json(),d)}catch(n){let p=n instanceof se?n.status>=500||n.status===408||n.status===409||n.status===429:K(n),l=D();if(!p||l.signal.aborted||N>=je)throw n;await y(Math.min(500*2**(N-1),8000),l,"freestyle");let g=await I({...U,method:"GET"}).then((O)=>fe(O.json(),d),()=>{return});if(g&&g.receivedBytes>_)return g}}return{http:F,async createVm(d){let S=(await I({method:"POST",path:"/v5/vms",body:d})).json();return{data:ce(S),firewallRules:Ue(Y(S)?S.firewallRules:void 0),tlsRules:Y(S)&&Array.isArray(S.tlsRules)?S.tlsRules:[]}},async listVms(d,S){let R=(await I({method:"GET",path:"/v5/vms",query:{limit:d,offset:S}})).json();if(!Y(R)||!Array.isArray(R.vms)||!Number.isSafeInteger(R.totalCount))ee("VM list");return{vms:R.vms.map((_)=>ce(_)),totalCount:Number(R.totalCount)}},async getVm(d){return ce((await I({method:"GET",path:"/v5/vms/{id}",...z(d)})).json(),d)},async deleteVm(d){await I({method:"DELETE",path:"/v5/vms/{id}",...z(d)})},async exec(d,S){return He((await I({method:"POST",path:"/v5/vms/{id}/exec-await",...z(d),body:{...S,linuxUser:"root"}})).json(),d)},async lifecycle(d,S){await I({method:"POST",path:`/v5/vms/{id}/${S}`,...z(d),body:{}})},async snapshot(d,S){let R=(await I({method:"POST",path:"/v5/vms/{id}/snapshot",...z(d),body:S})).json(),_=ae(R,"snapshotId");if(_===void 0)ee("snapshot result",d);return _},async createTlsRule(d){let S=ae((await I({method:"POST",path:"/v5/tls",body:d})).json(),"domain");if(S===void 0)ee("TLS rule");return{domain:S}},async readFile(d,S,R){let _=R?{range:`bytes=${R.offset}-${R.offset+R.length-1}`}:void 0;return(await A({method:"GET",path:"/v5/vms/{id}/fs/read",...z(d),query:{path:S},deadline:D(),maxBytes:Ne,headers:_})).body},async writeFile(d,S,R,_){let U=Oe("sha256").update(R).digest("hex");if(R.byteLength<=qe){await I({method:"PUT",path:"/v5/vms/{id}/fs/write",...z(d),query:{path:S,mode:_,sha256:U},body:R,headers:ve});return}let N=R.byteLength,n=fe((await I({method:"POST",path:"/v5/vms/{id}/fs/uploads",...z(d),body:{path:S,size:N,sha256:U,mode:_}})).json(),d),p={id:d,upload:n.uploadId};try{let l=n.receivedBytes;while(l<N){let g=(await ue(d,n.uploadId,R.subarray(l,Math.min(l+De,N)),l)).receivedBytes;if(g<=l)throw P("Freestyle upload made no progress","provider",d);l=g}await I({method:"POST",path:"/v5/vms/{id}/fs/uploads/{upload}/commit",params:p,sandboxId:d,body:{}})}catch(l){throw await F.cleanup({method:"DELETE",path:"/v5/vms/{id}/fs/uploads/{upload}",params:p,sandboxId:d}).catch(()=>{}),l}}}}var pe=`import os,sys,marshal,_signal as signal,select,time,fcntl
|
|
2
|
+
${x}
|
|
3
|
+
${M}
|
|
4
4
|
root=sys.argv[1]
|
|
5
5
|
v=marshal.loads(bytes.fromhex(sys.stdin.read()))
|
|
6
6
|
if v.get('files') is not None:
|
|
@@ -77,7 +77,7 @@ finally:
|
|
|
77
77
|
if a:
|
|
78
78
|
try: os.unlink(a)
|
|
79
79
|
except FileNotFoundError: pass
|
|
80
|
-
`,Be=
|
|
80
|
+
`,Be=X(pe);async function Se(s,f,m){return q({guest:s,input:f,fail:(w,F)=>P(w,F),launch:(w,F)=>s.exec(Be.command(s.id,w),C({files:m,command:f.command,env:f.env,cwd:f.cwd,stdin:f.stdin??"",timeoutMs:f.timeoutMs,activityPath:f.activityPath}).toString("hex"),f.timeoutMs+5000,F)})}var me="/var/lib/sandbox-sdk.json",Ee=Je("sha256").update(pe).digest("hex"),oe="sandbox-sdk-info";function Ke(s){let m=Buffer.from(JSON.stringify({key:s.key??null,labels:s.labels})).toString("base64url").match(/.{1,63}/g)??[];if(m.length>62)throw P("Key and labels exceed Freestyle's native metadata budget","unsupported");return{"sandbox-sdk":"1",[oe]:String(m.length),...Object.fromEntries(m.map((w,F)=>[`${oe}-${F}`,w]))}}var Le="/var/lib/sandbox-sdk-env.json";function Pe(s,f){if(s===void 0)return;if(!Number.isSafeInteger(s)||s<=0)throw P("Timeout must be a positive integer","invalid_argument");if(f&&s<1000)throw P("Hard lifetime requires at least one second","unsupported");return f?Math.floor(s/1000):Math.ceil(s/1000)}function $e(s){if(s.network==="none"||r(s.network)&&s.network.allow.length===0)return[];if(r(s.network))throw P("Host allow lists are not implemented; use all or none","unsupported");return[{action:"allow",source:{},destination:{public:!0}}]}function kt(s={}){let f=new Set,m=new Map,w=new Map,F=new Map,A=s.requestTimeoutMs??30000;if(s.autoDeleteMs!==void 0&&(!Number.isSafeInteger(s.autoDeleteMs)||s.autoDeleteMs<0))throw P("autoDeleteMs must be a non-negative integer of milliseconds","invalid_argument");let D=s.autoDeleteMs===void 0?void 0:Math.ceil(s.autoDeleteMs/1000),K=s.baseUrl??xe;function L(){if(!Number.isSafeInteger(A)||A<=0)throw P("requestTimeoutMs must be a positive integer","invalid_argument");let n=s.apiKey??process.env.FREESTYLE_API_KEY;if(!n?.trim())throw P("Freestyle API key is missing. Authentication is required. Set FREESTYLE_API_KEY or pass apiKey.","auth");return n}let I=ke({baseUrl:K,apiKey:L,requestTimeoutMs:Number.isSafeInteger(A)&&A>0?A:30000}),z={package:"freestyle",async connect(n,p){let l=E(n,"Freestyle",[{apiKey:L(),baseUrl:K}],"freestyle");if(p===void 0)return l;return B(await T(l.vms,"ref",[p],"freestyle"),"vms.ref","freestyle")}},ue=b({http:I.http,placeholder:["vmId","vmIdOrSlug"],sdk:z});async function d(n,p,l,g=A){return ne.run({deniedValues:ne.getStore()?.deniedValues},async()=>{try{return await we(p,g,l??Q.getStore()?.signal)}catch(O){throw re(O,n)}})}async function S(n,p,l,g){let O=m.get(n);if(!O)return I.exec(n,{command:p,stdin:l,timeoutMs:g});let V=await I.exec(n,{command:c(`import os,sys,json,tempfile,base64
|
|
81
81
|
v=json.load(sys.stdin)
|
|
82
82
|
for path in ['/workspace','/tmp/.sandbox-sdk']:
|
|
83
83
|
os.makedirs(path,exist_ok=True)
|
|
@@ -92,5 +92,5 @@ for path,content in v['files']:
|
|
|
92
92
|
with tempfile.TemporaryFile() as f:
|
|
93
93
|
f.write(base64.b64decode(v.get('stdin') or '')); f.seek(0); os.dup2(f.fileno(),0)
|
|
94
94
|
print('SDK_PREPARED:',end='',flush=True)
|
|
95
|
-
os.execvp('sh',['sh','-c',v['command']])`),stdin:Buffer.from(JSON.stringify({files:O,command:p,stdin:l})).toString("base64"),timeoutMs:
|
|
96
|
-
if m is not None: os.chmod(p,m)`,p,
|
|
95
|
+
os.execvp('sh',['sh','-c',v['command']])`),stdin:Buffer.from(JSON.stringify({files:O,command:p,stdin:l})).toString("base64"),timeoutMs:g});if(V.stdout?.startsWith("SDK_PREPARED:"))return m.delete(n),{...V,stdout:V.stdout.slice(13)};return V}async function R(n){return{name:"freestyle",raw:async(p)=>{let l=await d(n,()=>S(n,p,void 0,A));if(l.statusCode!==0)throw P("Guest operation failed",l.statusCode===null?"timeout":"provider",n);return l.stdout??""},upload:(p,l,g)=>d(n,async()=>{if(m.has(n)){if((await S(n,c(`import os,sys; p=sys.argv[1]; os.makedirs(os.path.dirname(p),exist_ok=True); m=int(sys.argv[2],8) if sys.argv[2] else None; f=open(p,'wb'); f.write(sys.stdin.buffer.read()); f.close()
|
|
96
|
+
if m is not None: os.chmod(p,m)`,p,g===void 0?"":g.toString(8)),Buffer.from(l).toString("base64"),A)).statusCode!==0)throw P("File upload failed","provider",n)}else await I.writeFile(n,p,l,g)}),read:(p,l)=>d(n,()=>I.readFile(n,p,l))}}async function _(n,p=!1){if(n.metadata["sandbox-sdk"]!=="1")throw P("Not an SDK VM","not_found",n.id);let l;if(p&&n.metadata[oe]!==void 0){let j=Number(n.metadata[oe]);if(!Number.isInteger(j)||j<1||j>62)throw P("Invalid SDK metadata","not_found",n.id);let H="";for(let J=0;J<j;J++){let Z=n.metadata[`${oe}-${J}`];if(!Z||!/^[A-Za-z0-9_-]{1,63}$/.test(Z))throw P("Invalid SDK metadata","not_found",n.id);H+=Z}l=Buffer.from(H,"base64url").toString()}else l=new TextDecoder().decode(await I.readFile(n.id,me));let g;try{g=JSON.parse(l)}catch{throw P("Invalid SDK metadata","not_found",n.id)}if(!g||!r(g)||!("key"in g)||g.key!==null&&!t(g.key)||!("labels"in g)||!g.labels||!r(g.labels)||Array.isArray(g.labels))throw P("Invalid SDK metadata","not_found",n.id);let O={};for(let[j,H]of Object.entries(g.labels)){if(!t(H))throw P("Invalid SDK label","not_found",n.id);Object.defineProperty(O,j,{value:H,enumerable:!0})}let V=Date.parse(n.createdAt);if(!Number.isFinite(V))throw P("Invalid VM creation time","provider",n.id);return{supervisorHash:"supervisorHash"in g&&t(g.supervisorHash)?g.supervisorHash:void 0,info:{id:n.id,key:g.key??void 0,labels:O,createdAt:V,state:n.state==="running"?"running":n.state==="paused"||n.state==="pausing"?"paused":"stopped"}}}async function U(n,p=!1){return(await _(n,p)).info}let N={name:"freestyle",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","snapshot","network-policy"]),create:(n)=>d(void 0,async()=>{let p=ne.getStore();if(p)p.deniedValues=Object.values(n.env??{}).filter(Boolean);if(n.size!==void 0)throw P("Explicit sizes are not implemented; select a base snapshot instead","unsupported");let l=$e(n),g=Pe(n.idleTimeoutMs,!1),O=Pe(n.timeoutMs,!0);if(n.signal?.aborted||Q.getStore()?.signal.aborted)throw P("Creation aborted","aborted");let V={snapshotId:n.from??s.snapshotId??"freestyle/ubuntu",metadata:Ke(n),firewall:{rules:l},tls:{rules:[]},vpcs:[],idleTimeoutSeconds:g??-1,ttlSeconds:O,autoDeleteSeconds:D},j,H=Date.now();L();try{let G=Q.getStore();j=G?await Q.run({signal:G.timeout,timeout:G.timeout,remaining:G.remaining},()=>I.createVm(V)):await I.createVm(V)}catch(G){let W=re(G);if(W.code==="unavailable"||W.code==="timeout")throw P("VM creation outcome is unknown; inspect the account before retrying","outcome_unknown",void 0,W.cause);throw G}let{data:J,firewallRules:Z,tlsRules:Fe}=j,te=J.id;f.add(te);try{if(n.signal?.aborted||Q.getStore()?.signal.aborted)throw P("Creation aborted","aborted");if(g!==void 0&&J.idleTimeoutSeconds!==g||O!==void 0&&J.ttlSeconds!==O||D!==void 0&&J.autoDeleteSeconds!==D)throw P("Freestyle did not confirm requested limits","unsupported",te);if(!Array.isArray(J.vpcs)||J.vpcs.length||Z.length!==l.length||Z.some((W)=>W.action!=="allow"||Object.keys(W.source).length!==1||W.source.vmId!==te||Object.keys(W.destination).length!==1||W.destination.public!==!0))throw P("Freestyle did not confirm the requested firewall","unsupported",te);if(Fe.length)throw P("Unexpected TLS egress grants","unsupported",te);let G=[[me,JSON.stringify({key:n.key??null,labels:n.labels,supervisorHash:Ee})]];if(Object.keys(n.env??{}).length||n.from!==void 0||s.snapshotId!==void 0)G.push([Le,JSON.stringify(n.env??{})]);if(m.set(te,G),Object.keys(n.env??{}).length||n.from!==void 0||s.snapshotId!==void 0){if((await S(te,"true",void 0,A)).statusCode!==0)throw P("Guest setup failed","provider",te)}return await U({...J,createdAt:J.createdAt||new Date(H).toISOString(),state:"running"},!0)}catch(G){throw await Q.exit(()=>N.destroy(te)),G}},n.signal).catch((p)=>{let l=re(p);if(l.code==="timeout")throw P("VM creation outcome is unknown; inspect the account before retrying","outcome_unknown",void 0,l.cause);throw l}),list:(n)=>d(void 0,async()=>{let p=[],l=0;while(!0){let g=await I.listVms(100,l);for(let O of g.vms){if(O.metadata["sandbox-sdk"]!=="1")continue;try{let V=await U(O,!0);if(Object.entries(n).every(([j,H])=>V.labels[j]===H))p.push(V)}catch(V){if(re(V,O.id).code!=="not_found")throw V}}if(l+=g.vms.length,l>=g.totalCount)break;if(!g.vms.length)throw P("VM list ended before all pages were returned")}return p}),async find(n){let p=(await N.list({})).find((l)=>l.key===n);if(!p)return;try{return await N.connect(p.id)}catch(l){if(re(l,p.id).code!=="not_found")throw l;return}},connect:(n)=>d(n,async()=>{let p=await I.getVm(n);f.add(n);let l;try{l=await _(p)}catch(g){if(!["file_not_found","not_found"].includes(re(g,n).code))throw g;l=await _(p,!0),m.set(n,[[me,JSON.stringify({key:l.info.key??null,labels:l.info.labels,supervisorHash:Ee})]])}return l.info}),destroy:(n)=>d(n,async()=>{try{await I.deleteVm(n)}catch(p){if(re(p).code!=="not_found")throw p}f.delete(n),F.delete(n),m.delete(n);for(let p of w.keys())if(p.startsWith(n+":"))w.delete(p)}),async close(n){f.delete(n),F.delete(n)},exec:async(n,p)=>{try{if(!f.has(n))await N.connect(n);let l=await R(n),g=m.get(n),O=await Se({id:n,raw:l.raw,read:(V,j,H)=>d(n,()=>I.readFile(n,V,j),H),exec:(V,j,H,J)=>d(n,async()=>{let Z=await I.exec(n,{command:V,stdin:Buffer.from(j).toString("base64"),timeoutMs:H});if(Z.statusCode!==0||!Z.stdout)throw P("Guest execution failed","provider",n);return Z.stdout},J,H)},p,g);if(!O.timedOut&&m.get(n)===g)m.delete(n);return O}catch(l){throw re(l,n)}},files:{...k(R,d),writeSupportsMode:!0},previewUrl:(n,p)=>d(n,async()=>{let l=`${n}:${p}`,g=w.get(l);if(g)return{url:g};let O=`sdk-${crypto.randomUUID()}.style.dev`,V=await I.createTlsRule({action:"allow",domain:O,source:{public:!0},destination:{vmId:n,port:p}});if(V.domain!==O)throw P("Freestyle returned a different preview domain","provider",n);let j=`https://${V.domain}`;return w.set(l,j),{url:j}}),pause:(n)=>d(n,async()=>{await I.lifecycle(n,"pause")}),resume:(n)=>d(n,async()=>{await I.lifecycle(n,"start")}),snapshot:(n,p)=>d(n,async()=>{let l=p?.expiresInMs;if(l!==void 0&&(!Number.isSafeInteger(l)||l<0))throw P("expiresInMs must be a non-negative integer","invalid_argument",n);return{id:await I.snapshot(n,l?{ttlSeconds:Math.ceil(l/1000)}:{})}}),native(n){if(!f.has(n))throw P("Connect the VM first","not_found",n);let p=F.get(n);if(!p)p=b({http:I.http,placeholder:["vmId","vmIdOrSlug"],sandboxId:n,sdk:z}),F.set(n,p);return p},api:ue};return N}export{kt as freestyle};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{x}from"../../chunk-drhcb2hx.js";import{c}from"../../chunk-0wp6x4wb.js";import{t,o,e,i,T,a,F}from"../../chunk-0eeyc0aq.js";import{randomUUID as Q}from"node:crypto";import{posix as fe}from"node:path";var V="instabox";function p(r,u="provider",f={}){return new e(`Instabox: ${r}`,{code:u,provider:V,...f})}var ne=/^[a-z][a-z0-9_]{0,47}$/,ue=/^[A-Za-z0-9_-]{1,64}$/;function q(r){let u=c(r)?r.error:void 0;if(!c(u))return;let{code:f,retryAfterSeconds:h,requestId:y}=u;return{code:t(f)&&ne.test(f)?f:"unknown",retryable:u.retryable===!0,retryAfterSeconds:o(h)?h:void 0,requestId:t(y)&&ue.test(y)?y:void 0}}function K(r,u){switch(u){case"missing_key":case"malformed_key":case"invalid_key":case"expired_key":case"revoked_key":case"missing_scope":case"permission_denied":return"auth";case"quota_exceeded":case"rate_limited":case"no_capacity":return"quota";case"spec_not_allowed":case"template_not_allowed":return"unsupported";case"host_unavailable":return"unavailable";case"not_found":return"not_found";default:return r===0?"provider":F(r)}}class N extends Error{status;body;constructor(r,u){super(`Instabox HTTP ${r} ${u.code}`);this.status=r;this.body=u;this.name="InstaboxApiFailure"}}function Ee(r,u){let f={operation:r,status:u.status};if(u.body.code!=="unknown")f.providerCode=u.body.code;if(u.body.requestId)f.requestId=u.body.requestId;return f}function B(r,u,f){if(r instanceof e)return r;if(r instanceof N){let y=K(r.status,r.body.code);return new e(`Instabox ${u} failed: ${a(y)}`,{code:y,provider:V,sandboxId:f,retryable:r.body.retryable||r.status===429,cause:T(Ee(u,r))})}let h=i(r,{code:"provider",known:!0});return new e(`Instabox ${u} failed: ${a("provider")}`,{code:"provider",provider:V,sandboxId:f,cause:h.cause})}function me(r){let u=r.errorCode&&ne.test(r.errorCode)?r.errorCode:void 0,f=K(0,u??""),h={operation:"operation"};if(u)h.providerCode=u;return new e(`Instabox operation ${r.operationId} failed: ${a(f)}`,{code:f,provider:V,sandboxId:r.sandboxId,cause:T(h)})}function ke(r){if(!(r instanceof Error))return{};let u={};if("status"in r&&o(r.status))u.status=r.status;if("providerCode"in r&&t(r.providerCode)&&ne.test(r.providerCode))u.providerCode=r.providerCode;if("requestId"in r&&t(r.requestId)&&ue.test(r.requestId))u.requestId=r.requestId;return u}function le(r,u){let f=B(r,"create",u.sandboxId),h={operation:"create",admittedByThisCall:!0,stage:u.stage,...ke(f.cause)};if(/^m_[a-z0-9]{1,64}$/.test(u.sandboxId))h.sandboxId=u.sandboxId;if(u.cleanupCode!==void 0)h.cleanupCode=u.cleanupCode;return new e(f.message,{code:f.code,provider:V,sandboxId:u.sandboxId,retryable:f.retryable,cause:T(h)})}var W="sandbox-sdk-key",Se=new Set(["suspended","suspending"]),_e=new Set(["running","creating","starting","resuming"]),w=(r,u)=>c(r)?r[u]:void 0;function Me(r){let u={};if(c(r)){for(let[f,h]of Object.entries(r))if(t(h))u[f]=h}return u}function re(r){let u=w(r,"id"),f=w(r,"name"),h=w(r,"state"),y=w(r,"createdAt");if(!t(u)||!t(f)||!t(h)||!t(y))throw p("unexpected machine object from the API");let A=Date.parse(y);if(!Number.isFinite(A))throw p("machine has no valid creation time","provider",{sandboxId:u});return{id:u,name:f,state:h,metadata:Me(w(r,"metadata")),createdAt:A}}function H(r){let u=w(r,"id"),f=w(r,"machineId"),h=w(r,"state");if(!t(u)||!t(f)||!t(h))throw p("unexpected operation object from the API");let y=w(r,"error");return{id:u,machineId:f,state:h,errorCode:y===void 0?void 0:q({error:y})?.code}}function X(r){return r.state==="succeeded"||r.state==="failed"}function pe(r){let u=w(r,"machines");if(!Array.isArray(u))throw p("unexpected machine list from the API");let f=w(r,"nextCursor");return{machines:u.map(re),nextCursor:t(f)?f:null}}function oe(r){let u=w(r,"id"),f=w(r,"status");if(!t(u)||!t(f))throw p("unexpected snapshot object from the API");return{id:u,status:f}}function he(r,u){let f;try{f=JSON.parse(u)}catch{throw p(`exec stream sent invalid JSON in a ${r} event`)}if(!c(f))throw p(`exec stream sent a non-object ${r} event`);switch(r){case"stdout":case"stderr":{let h=w(f,"data");return{kind:r,text:t(h)?h:""}}case"exit":{let h=w(f,"exitCode"),y=w(f,"timedOut")===!0;return{kind:"exit",exitCode:!y&&o(h)?h:null,timedOut:y}}case"error":return{kind:"error",code:(q(f)??q({error:f}))?.code??"unknown"};default:return}}function Ae(r){if(r==="dir"||r==="directory")return"directory";if(r==="symlink")return"symlink";return"file"}function be(r,u){let f=w(u,"name"),h=w(u,"type");if(!t(f)||!t(h))throw p("unexpected directory entry from the API");let y=w(u,"size"),A=w(u,"modTime"),P=t(A)?Date.parse(A):Number.NaN;return{path:fe.join(r,f),type:Ae(h),size:o(y)?y:0,modifiedAt:Number.isFinite(P)?P:0}}function z(r){let{[W]:u,...f}=r.metadata,h=Se.has(r.state)?"paused":_e.has(r.state)?"running":"stopped";return u===void 0?{id:r.id,labels:f,state:h,createdAt:r.createdAt}:{id:r.id,key:u,labels:f,state:h,createdAt:r.createdAt}}function ye(r,u){let[f="",h="0",y="0"]=u.split("|");return{path:r,type:f==="directory"?"directory":f==="symbolic link"?"symlink":"file",size:Number(h),modifiedAt:Math.round(Number(y)*1000)}}function xe(r,u){let f=u.split("\x00"),h=[];for(let y=0;y+3<f.length;y+=4){let[A="",P="f",U="0",E="0"]=f.slice(y,y+4);h.push({path:fe.join(r,A),type:P==="d"?"directory":P==="l"?"symlink":"file",size:Number(U),modifiedAt:Math.round(Number(E)*1000)})}return h}var $e="instabox",we="/data/workspace",Te={small:{vcpus:2,memMiB:4096},medium:{vcpus:4,memMiB:8192},large:{vcpus:8,memMiB:16384}},Pe=["set -e",`if [ ! -e /workspace ]; then mkdir -p ${we}; sudo -n ln -s ${we} /workspace; fi`,"test -w /workspace/","mkdir -p /tmp/.sandbox-sdk","command -v python3 git tar nohup setsid >/dev/null"].join("; "),Oe=new Set(["BASH_ENV","ENV","HOME","HOSTNAME","IFS","LOGNAME","OLDPWD","PATH","PWD","SHELL","SHLVL","USER","BASHOPTS","BASH_VERSINFO","EUID","PPID","SHELLOPTS","UID","TERM","XDG_RUNTIME_DIR","DBUS_SESSION_BUS_ADDRESS","SSL_CERT_FILE","SSL_CERT_DIR","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","NODE_EXTRA_CA_CERTS"]);function Re(r){return Oe.has(r)||r.startsWith("INSTABOX_")||r.startsWith("SSH_")}function Ie(r){return`'${r.replaceAll("'",`'"'"'`)}'`}function D(r){if(!r.startsWith("/"))throw p(`path must be absolute: ${r}`,"invalid_argument");return r}function Ne(r){if(r===void 0)return{};if(t(r))return Te[r];if(r.diskGb!==void 0)throw p("the disk size comes with the machine size (20 GiB); omit diskGb and resize it later","unsupported");return{vcpus:r.cpu,memMiB:r.memoryMb}}function De(r){let u=Math.ceil(r/60000)*60;if(u<300||u>1800)throw p("idleTimeoutMs must be between 5 and 30 minutes","unsupported");return u}function Ue(r){let u=Math.ceil(r/1000);if(u<60||u>86400)throw p("timeoutMs must be between 1 minute and 24 hours","unsupported");return u}function se(r,u){return new Promise((f)=>{let h=setTimeout(f,r);u?.addEventListener("abort",()=>{clearTimeout(h),f()},{once:!0})})}function ge(r={}){let u=(r.baseUrl??process.env.INSTABOX_API_URL??"https://api.instabox.sh").replace(/\/+$/,""),f=r.requestTimeoutMs??60000,h=r.operationTimeoutMs??300000,y=new Map;function A(){let n=r.apiKey??process.env.INSTABOX_API_KEY;if(!n?.trim())throw p("no API key; set INSTABOX_API_KEY or pass apiKey","auth",{retryable:!1});return n.trim()}function P(n,s){let d=new URL(u+n);for(let[m,l]of Object.entries(s??{}))if(l!==void 0)d.searchParams.set(m,l);return d}async function U(n){let s=n.idempotent?Q():void 0,d=Date.now()+(n.timeoutMs??f),m=n.method==="POST"||n.method==="PATCH",l=!m||!!s;for(let b=0;;b++){let I=new Headers({"X-API-Key":A(),"User-Agent":x});if(s)I.set("Idempotency-Key",s);if(n.confirmDelete)I.set("X-Confirm-Delete",n.confirmDelete);if(n.accept)I.set("Accept",n.accept);let S;if(n.raw!==void 0)I.set("Content-Type","application/octet-stream"),S=new Uint8Array(n.raw);else if(n.body!==void 0)I.set("Content-Type","application/json"),S=JSON.stringify(n.body);let k=AbortSignal.timeout(Math.max(1,d-Date.now())),v=n.signal?AbortSignal.any([n.signal,k]):k,g;try{g=await fetch(P(n.path,n.query),{method:n.method,headers:I,body:S,signal:v,redirect:"error"})}catch(ee){let te=i(ee,{code:"outcome_unknown",known:!0});if(n.signal?.aborted)throw p(`${n.operation} aborted`,"aborted",{sandboxId:n.sandboxId,cause:te.cause});if(k.aborted)throw p(`${n.operation} timed out`,m?"outcome_unknown":"timeout",{sandboxId:n.sandboxId,retryable:!m,cause:te.cause});if(l&&b<4){await se(250*2**b,n.signal);continue}throw p(`${n.operation}: the connection failed`,m?"outcome_unknown":"unavailable",{sandboxId:n.sandboxId,retryable:!m,cause:te.cause})}if(g.ok)return g;let C="";try{C=await g.text()}catch(ee){if(m&&g.status>=500)throw p(`${n.operation}: the error answer broke off`,"outcome_unknown",{sandboxId:n.sandboxId,cause:i(ee,{code:"outcome_unknown",known:!0}).cause})}let _;try{_=JSON.parse(C)}catch{_=void 0}let R=q(_)??{code:"unknown",retryable:g.status>=500,retryAfterSeconds:void 0,requestId:void 0},G=g.status===429||l&&(R.retryable||[502,503,504].includes(g.status)),L=Number(g.headers.get("retry-after")),M=1000*(R.retryAfterSeconds??(Number.isFinite(L)?L:0)),O=Math.max(M,500*2**Math.min(b,5));if(G&&b<8&&Date.now()+O<d){if(await se(O,n.signal),n.signal?.aborted)throw p(`${n.operation} aborted`,"aborted");continue}if(m&&g.status===504)throw p(`${n.operation} timed out at the gateway`,"outcome_unknown",{sandboxId:n.sandboxId});throw new N(g.status,R)}}async function E(n){try{let s=await U(n),d;try{d=await s.text()}catch(l){let b=n.method==="POST"||n.method==="PATCH";throw p(`${n.operation}: the answer broke off`,b?"outcome_unknown":"unavailable",{sandboxId:n.sandboxId,retryable:!b,cause:i(l,{code:"unavailable",known:!0}).cause})}let m;try{m=d?JSON.parse(d):void 0}catch{throw p(`${n.operation} returned invalid JSON`,"provider",{sandboxId:n.sandboxId})}return m}catch(s){throw B(s,n.operation,n.sandboxId)}}async function Y(n,s){let d=n,m=Date.now()+h;while(!X(d)){if(Date.now()>m)throw p(`operation ${d.id} did not finish in time`,"timeout",{sandboxId:s,retryable:!0});let l=m-Date.now();if(d=H(await E({method:"GET",path:`/v1/operations/${encodeURIComponent(d.id)}`,operation:"operation status",query:{wait:`${Math.max(1,Math.min(25,Math.floor(l/1000)))}s`},sandboxId:s,timeoutMs:Math.max(1,Math.min(40000,l))})),!X(d)&&Date.now()>m)break}if(!X(d))throw p(`operation ${d.id} did not finish in time`,"timeout",{sandboxId:s,retryable:!0});if(d.state==="failed")throw me({operationId:d.id,errorCode:d.errorCode,sandboxId:s});return d}async function Z(n){return re(await E({method:"GET",path:`/v1/machines/${encodeURIComponent(n)}`,operation:"connect",sandboxId:n}))}async function ae(n){let s=[],d=null;do{let m=P("/v1/machines");for(let[b,I]of Object.entries(n))m.searchParams.append("metadata",`${b}:${I}`);if(m.searchParams.set("limit","200"),d)m.searchParams.set("cursor",d);let l=pe(await E({method:"GET",path:m.pathname+m.search,operation:"list"}));s.push(...l.machines),d=l.nextCursor}while(d);return s.filter((m)=>m.state!=="deleting"&&Object.entries(n).every(([l,b])=>m.metadata[l]===b))}async function ie(n,s){let d=await E({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/${s}`,operation:s==="suspend"?"pause":s,idempotent:!0,sandboxId:n});await Y(H(d),n)}async function de(n,s,d,m){let l={path:D(s),parents:"true",mode:m.mode===void 0?void 0:`0${(m.mode&4095).toString(8)}`};try{await U({method:"PUT",path:`/v1/machines/${encodeURIComponent(n)}/files`,operation:"write file",query:l,raw:d,sandboxId:n,signal:m.signal,timeoutMs:m.timeoutMs})}catch(b){if(b instanceof N&&b.body.code==="not_a_file")throw p(`${s} is a directory`,"invalid_argument",{sandboxId:n});throw B(b,"write file",n)}}async function J(n,s,d){let m=new AbortController,l=setTimeout(()=>m.abort(),d.timeoutMs),b=d.signal?AbortSignal.any([d.signal,m.signal]):m.signal,I;try{I=await U({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/exec`,operation:"exec",body:{...s,timeoutSeconds:Math.min(600,Math.max(1,Math.ceil(d.timeoutMs/1000)+1))},accept:"text/event-stream",sandboxId:n,signal:b,timeoutMs:d.timeoutMs+30000})}catch(C){if(clearTimeout(l),b.aborted)return{exitCode:null,timedOut:!0};throw B(C,"exec",n)}let S=I.body?.getReader();if(!S)throw clearTimeout(l),p("exec returned no stream","provider",{sandboxId:n});let k=new TextDecoder,v="",g=!1;try{for(;;){let C;try{C=await S.read()}catch(R){if(b.aborted)return{exitCode:null,timedOut:!0};throw p("exec stream broke","outcome_unknown",{sandboxId:n,cause:i(R,{code:"outcome_unknown",known:!0}).cause})}if(C.done){g=!0;break}v+=k.decode(C.value,{stream:!0});let _=v.indexOf(`
|
|
1
|
+
import{S}from"../../chunk-h6xh0pr0.js";import{l}from"../../chunk-m7hbefp1.js";import{t,o,e,i,R,a,I}from"../../chunk-xx9znywe.js";import{randomUUID as Q}from"node:crypto";import{posix as fe}from"node:path";var F="instabox";function p(r,c="provider",f={}){return new e(`Instabox: ${r}`,{code:c,provider:F,...f})}var ne=/^[a-z][a-z0-9_]{0,47}$/,ue=/^[A-Za-z0-9_-]{1,64}$/;function B(r){let c=l(r)?r.error:void 0;if(!l(c))return;let{code:f,retryAfterSeconds:h,requestId:y}=c;return{code:t(f)&&ne.test(f)?f:"unknown",retryable:c.retryable===!0,retryAfterSeconds:o(h)?h:void 0,requestId:t(y)&&ue.test(y)?y:void 0}}function K(r,c){switch(c){case"missing_key":case"malformed_key":case"invalid_key":case"expired_key":case"revoked_key":case"missing_scope":case"permission_denied":return"auth";case"quota_exceeded":case"rate_limited":case"no_capacity":return"quota";case"spec_not_allowed":case"template_not_allowed":return"unsupported";case"host_unavailable":return"unavailable";case"not_found":return"not_found";default:return r===0?"provider":I(r)}}class D extends Error{status;body;constructor(r,c){super(`Instabox HTTP ${r} ${c.code}`);this.status=r;this.body=c;this.name="InstaboxApiFailure"}}function Ee(r,c){let f={operation:r,status:c.status};if(c.body.code!=="unknown")f.providerCode=c.body.code;if(c.body.requestId)f.requestId=c.body.requestId;return f}function J(r,c,f){if(r instanceof e)return r;if(r instanceof D){let y=K(r.status,r.body.code);return new e(`Instabox ${c} failed: ${a(y)}`,{code:y,provider:F,sandboxId:f,retryable:r.body.retryable||r.status===429,cause:R(Ee(c,r))})}let h=i(r,{code:"provider",known:!0});return new e(`Instabox ${c} failed: ${a("provider")}`,{code:"provider",provider:F,sandboxId:f,cause:h.cause})}function me(r){let c=r.errorCode&&ne.test(r.errorCode)?r.errorCode:void 0,f=K(0,c??""),h={operation:"operation"};if(c)h.providerCode=c;return new e(`Instabox operation ${r.operationId} failed: ${a(f)}`,{code:f,provider:F,sandboxId:r.sandboxId,cause:R(h)})}function ke(r){if(!(r instanceof Error))return{};let c={};if("status"in r&&o(r.status))c.status=r.status;if("providerCode"in r&&t(r.providerCode)&&ne.test(r.providerCode))c.providerCode=r.providerCode;if("requestId"in r&&t(r.requestId)&&ue.test(r.requestId))c.requestId=r.requestId;return c}function le(r,c){let f=J(r,"create",c.sandboxId),h={operation:"create",admittedByThisCall:!0,stage:c.stage,...ke(f.cause)};if(/^m_[a-z0-9]{1,64}$/.test(c.sandboxId))h.sandboxId=c.sandboxId;if(c.cleanupCode!==void 0)h.cleanupCode=c.cleanupCode;return new e(f.message,{code:f.code,provider:F,sandboxId:c.sandboxId,retryable:f.retryable,cause:R(h)})}var W="sandbox-sdk-key",Se=new Set(["suspended","suspending"]),_e=new Set(["running","creating","starting","resuming"]),x=(r,c)=>l(r)?r[c]:void 0;function Me(r){let c={};if(l(r)){for(let[f,h]of Object.entries(r))if(t(h))c[f]=h}return c}function re(r){let c=x(r,"id"),f=x(r,"name"),h=x(r,"state"),y=x(r,"createdAt");if(!t(c)||!t(f)||!t(h)||!t(y))throw p("unexpected machine object from the API");let T=Date.parse(y);if(!Number.isFinite(T))throw p("machine has no valid creation time","provider",{sandboxId:c});return{id:c,name:f,state:h,metadata:Me(x(r,"metadata")),createdAt:T}}function H(r){let c=x(r,"id"),f=x(r,"machineId"),h=x(r,"state");if(!t(c)||!t(f)||!t(h))throw p("unexpected operation object from the API");let y=x(r,"error");return{id:c,machineId:f,state:h,errorCode:y===void 0?void 0:B({error:y})?.code}}function X(r){return r.state==="succeeded"||r.state==="failed"}function pe(r){let c=x(r,"machines");if(!Array.isArray(c))throw p("unexpected machine list from the API");let f=x(r,"nextCursor");return{machines:c.map(re),nextCursor:t(f)?f:null}}function oe(r){let c=x(r,"id"),f=x(r,"status");if(!t(c)||!t(f))throw p("unexpected snapshot object from the API");return{id:c,status:f}}function he(r,c){let f;try{f=JSON.parse(c)}catch{throw p(`exec stream sent invalid JSON in a ${r} event`)}if(!l(f))throw p(`exec stream sent a non-object ${r} event`);switch(r){case"stdout":case"stderr":{let h=x(f,"data");return{kind:r,text:t(h)?h:""}}case"exit":{let h=x(f,"exitCode"),y=x(f,"timedOut")===!0;return{kind:"exit",exitCode:!y&&o(h)?h:null,timedOut:y}}case"error":return{kind:"error",code:(B(f)??B({error:f}))?.code??"unknown"};default:return}}function Ae(r){if(r==="dir"||r==="directory")return"directory";if(r==="symlink")return"symlink";return"file"}function be(r,c){let f=x(c,"name"),h=x(c,"type");if(!t(f)||!t(h))throw p("unexpected directory entry from the API");let y=x(c,"size"),T=x(c,"modTime"),P=t(T)?Date.parse(T):Number.NaN;return{path:fe.join(r,f),type:Ae(h),size:o(y)?y:0,modifiedAt:Number.isFinite(P)?P:0}}function z(r){let{[W]:c,...f}=r.metadata,h=Se.has(r.state)?"paused":_e.has(r.state)?"running":"stopped";return c===void 0?{id:r.id,labels:f,state:h,createdAt:r.createdAt}:{id:r.id,key:c,labels:f,state:h,createdAt:r.createdAt}}function ye(r,c){let[f="",h="0",y="0"]=c.split("|");return{path:r,type:f==="directory"?"directory":f==="symbolic link"?"symlink":"file",size:Number(h),modifiedAt:Math.round(Number(y)*1000)}}function xe(r,c){let f=c.split("\x00"),h=[];for(let y=0;y+3<f.length;y+=4){let[T="",P="f",L="0",E="0"]=f.slice(y,y+4);h.push({path:fe.join(r,T),type:P==="d"?"directory":P==="l"?"symlink":"file",size:Number(L),modifiedAt:Math.round(Number(E)*1000)})}return h}var $e="instabox",we="/data/workspace",Te={small:{vcpus:2,memMiB:4096},medium:{vcpus:4,memMiB:8192},large:{vcpus:8,memMiB:16384}},Pe=["set -e",`if [ ! -e /workspace ]; then mkdir -p ${we}; sudo -n ln -s ${we} /workspace; fi`,"test -w /workspace/","mkdir -p /tmp/.sandbox-sdk","command -v python3 git tar nohup setsid >/dev/null"].join("; "),Oe=new Set(["BASH_ENV","ENV","HOME","HOSTNAME","IFS","LOGNAME","OLDPWD","PATH","PWD","SHELL","SHLVL","USER","BASHOPTS","BASH_VERSINFO","EUID","PPID","SHELLOPTS","UID","TERM","XDG_RUNTIME_DIR","DBUS_SESSION_BUS_ADDRESS","SSL_CERT_FILE","SSL_CERT_DIR","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","NODE_EXTRA_CA_CERTS"]);function Re(r){return Oe.has(r)||r.startsWith("INSTABOX_")||r.startsWith("SSH_")}function Ie(r){return`'${r.replaceAll("'",`'"'"'`)}'`}function U(r){if(!r.startsWith("/"))throw p(`path must be absolute: ${r}`,"invalid_argument");return r}function Ne(r){if(r===void 0)return{};if(t(r))return Te[r];if(r.diskGb!==void 0)throw p("the disk size comes with the machine size (20 GiB); omit diskGb and resize it later","unsupported");return{vcpus:r.cpu,memMiB:r.memoryMb}}function De(r){let c=Math.ceil(r/60000)*60;if(c<300||c>1800)throw p("idleTimeoutMs must be between 5 and 30 minutes","unsupported");return c}function Ue(r){let c=Math.ceil(r/1000);if(c<60||c>86400)throw p("timeoutMs must be between 1 minute and 24 hours","unsupported");return c}function se(r,c){return new Promise((f)=>{let h=setTimeout(f,r);c?.addEventListener("abort",()=>{clearTimeout(h),f()},{once:!0})})}function ge(r={}){let c=(r.baseUrl??process.env.INSTABOX_API_URL??"https://api.instabox.sh").replace(/\/+$/,""),f=r.requestTimeoutMs??60000,h=r.operationTimeoutMs??300000,y=new Map;function T(){let n=r.apiKey??process.env.INSTABOX_API_KEY;if(!n?.trim())throw p("no API key; set INSTABOX_API_KEY or pass apiKey","auth",{retryable:!1});return n.trim()}function P(n,s){let d=new URL(c+n);for(let[u,m]of Object.entries(s??{}))if(m!==void 0)d.searchParams.set(u,m);return d}async function L(n){let s=n.idempotent?Q():void 0,d=Date.now()+(n.timeoutMs??f),u=n.method==="POST"||n.method==="PATCH",m=!u||!!s;for(let b=0;;b++){let w=new Headers({"X-API-Key":T(),"User-Agent":S});if(s)w.set("Idempotency-Key",s);if(n.confirmDelete)w.set("X-Confirm-Delete",n.confirmDelete);if(n.accept)w.set("Accept",n.accept);let _;if(n.raw!==void 0)w.set("Content-Type","application/octet-stream"),_=new Uint8Array(n.raw);else if(n.body!==void 0)w.set("Content-Type","application/json"),_=JSON.stringify(n.body);let k=AbortSignal.timeout(Math.max(1,d-Date.now())),v=n.signal?AbortSignal.any([n.signal,k]):k,g;try{g=await fetch(P(n.path,n.query),{method:n.method,headers:w,body:_,signal:v,redirect:"error"})}catch(ee){let te=i(ee,{code:"outcome_unknown",known:!0});if(n.signal?.aborted)throw p(`${n.operation} aborted`,"aborted",{sandboxId:n.sandboxId,cause:te.cause});if(k.aborted)throw p(`${n.operation} timed out`,u?"outcome_unknown":"timeout",{sandboxId:n.sandboxId,retryable:!u,cause:te.cause});if(m&&b<4){await se(250*2**b,n.signal);continue}throw p(`${n.operation}: the connection failed`,u?"outcome_unknown":"unavailable",{sandboxId:n.sandboxId,retryable:!u,cause:te.cause})}if(g.ok)return g;let C="";try{C=await g.text()}catch(ee){if(u&&g.status>=500)throw p(`${n.operation}: the error answer broke off`,"outcome_unknown",{sandboxId:n.sandboxId,cause:i(ee,{code:"outcome_unknown",known:!0}).cause})}let M;try{M=JSON.parse(C)}catch{M=void 0}let N=B(M)??{code:"unknown",retryable:g.status>=500,retryAfterSeconds:void 0,requestId:void 0},G=g.status===429||m&&(N.retryable||[502,503,504].includes(g.status)),q=Number(g.headers.get("retry-after")),A=1000*(N.retryAfterSeconds??(Number.isFinite(q)?q:0)),O=Math.max(A,500*2**Math.min(b,5));if(G&&b<8&&Date.now()+O<d){if(await se(O,n.signal),n.signal?.aborted)throw p(`${n.operation} aborted`,"aborted");continue}if(u&&g.status===504)throw p(`${n.operation} timed out at the gateway`,"outcome_unknown",{sandboxId:n.sandboxId});throw new D(g.status,N)}}async function E(n){try{let s=await L(n),d;try{d=await s.text()}catch(m){let b=n.method==="POST"||n.method==="PATCH";throw p(`${n.operation}: the answer broke off`,b?"outcome_unknown":"unavailable",{sandboxId:n.sandboxId,retryable:!b,cause:i(m,{code:"unavailable",known:!0}).cause})}let u;try{u=d?JSON.parse(d):void 0}catch{throw p(`${n.operation} returned invalid JSON`,"provider",{sandboxId:n.sandboxId})}return u}catch(s){throw J(s,n.operation,n.sandboxId)}}async function Y(n,s){let d=n,u=Date.now()+h;while(!X(d)){if(Date.now()>u)throw p(`operation ${d.id} did not finish in time`,"timeout",{sandboxId:s,retryable:!0});let m=u-Date.now();if(d=H(await E({method:"GET",path:`/v1/operations/${encodeURIComponent(d.id)}`,operation:"operation status",query:{wait:`${Math.max(1,Math.min(25,Math.floor(m/1000)))}s`},sandboxId:s,timeoutMs:Math.max(1,Math.min(40000,m))})),!X(d)&&Date.now()>u)break}if(!X(d))throw p(`operation ${d.id} did not finish in time`,"timeout",{sandboxId:s,retryable:!0});if(d.state==="failed")throw me({operationId:d.id,errorCode:d.errorCode,sandboxId:s});return d}async function Z(n){return re(await E({method:"GET",path:`/v1/machines/${encodeURIComponent(n)}`,operation:"connect",sandboxId:n}))}async function ae(n){let s=[],d=null;do{let u=P("/v1/machines");for(let[b,w]of Object.entries(n))u.searchParams.append("metadata",`${b}:${w}`);if(u.searchParams.set("limit","200"),d)u.searchParams.set("cursor",d);let m=pe(await E({method:"GET",path:u.pathname+u.search,operation:"list"}));s.push(...m.machines),d=m.nextCursor}while(d);return s.filter((u)=>u.state!=="deleting"&&Object.entries(n).every(([m,b])=>u.metadata[m]===b))}async function ie(n,s){let d=await E({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/${s}`,operation:s==="suspend"?"pause":s,idempotent:!0,sandboxId:n});await Y(H(d),n)}async function de(n,s,d,u){let m={path:U(s),parents:"true",mode:u.mode===void 0?void 0:`0${(u.mode&4095).toString(8)}`};try{await L({method:"PUT",path:`/v1/machines/${encodeURIComponent(n)}/files`,operation:"write file",query:m,raw:d,sandboxId:n,signal:u.signal,timeoutMs:u.timeoutMs})}catch(b){if(b instanceof D&&b.body.code==="not_a_file")throw p(`${s} is a directory`,"invalid_argument",{sandboxId:n});throw J(b,"write file",n)}}async function j(n,s,d){let u=new AbortController,m=setTimeout(()=>u.abort(),d.timeoutMs),b=d.signal?AbortSignal.any([d.signal,u.signal]):u.signal,w;try{w=await L({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/exec`,operation:"exec",body:{...s,timeoutSeconds:Math.min(600,Math.max(1,Math.ceil(d.timeoutMs/1000)+1))},accept:"text/event-stream",sandboxId:n,signal:b,timeoutMs:d.timeoutMs+30000})}catch(C){if(clearTimeout(m),b.aborted)return{exitCode:null,timedOut:!0};throw J(C,"exec",n)}let _=w.body?.getReader();if(!_)throw clearTimeout(m),p("exec returned no stream","provider",{sandboxId:n});let k=new TextDecoder,v="",g=!1;try{for(;;){let C;try{C=await _.read()}catch(N){if(b.aborted)return{exitCode:null,timedOut:!0};throw p("exec stream broke","outcome_unknown",{sandboxId:n,cause:i(N,{code:"outcome_unknown",known:!0}).cause})}if(C.done){g=!0;break}v+=k.decode(C.value,{stream:!0});let M=v.indexOf(`
|
|
2
2
|
|
|
3
|
-
`);while(
|
|
3
|
+
`);while(M>=0){let N=v.slice(0,M);v=v.slice(M+2),M=v.indexOf(`
|
|
4
4
|
|
|
5
|
-
`);let G="message",
|
|
6
|
-
`))if(O.startsWith("event:"))G=O.slice(6).trim();else if(O.startsWith("data:"))
|
|
7
|
-
`));if(!
|
|
5
|
+
`);let G="message",q=[];for(let O of N.split(`
|
|
6
|
+
`))if(O.startsWith("event:"))G=O.slice(6).trim();else if(O.startsWith("data:"))q.push(O.slice(5).replace(/^ /,""));if(!q.length)continue;let A=he(G,q.join(`
|
|
7
|
+
`));if(!A)continue;switch(A.kind){case"stdout":case"stderr":if(A.text)d.onChunk({stream:A.kind,text:A.text});break;case"exit":return g=await ve(_),{exitCode:A.exitCode,timedOut:A.timedOut};case"error":throw p(`exec failed (${A.code})`,K(0,A.code),{sandboxId:n});default:throw p(`unknown exec event ${String(A)}`)}}}if(b.aborted)return{exitCode:null,timedOut:!0};throw p("exec stream ended without an exit event","outcome_unknown",{sandboxId:n})}finally{if(clearTimeout(m),!g)await _.cancel().catch(()=>{return})}}async function ve(n){let s=Date.now()+1000;try{while(Date.now()<s){let d=new Promise((m)=>setTimeout(()=>m("timeout"),Math.max(1,s-Date.now()))),u=await Promise.race([n.read(),d]);if(u==="timeout")return!1;if(u.done)return!0}}catch{return!1}return!1}async function V(n,s,d=[0]){let u="",m="",b=await j(n,{argv:s},{timeoutMs:60000,onChunk(w){if(w.stream==="stdout")u+=w.text;else m+=w.text}});if(b.timedOut)throw p(`${s[0]} timed out`,"timeout",{sandboxId:n});if(b.exitCode===null||!d.includes(b.exitCode))throw p(`${s[0]} failed (exit ${b.exitCode}): ${m.trim().slice(0,300)}`,"provider",{sandboxId:n});return{exitCode:b.exitCode,stdout:u}}async function ce(n){try{let s=await E({method:"DELETE",path:`/v1/machines/${encodeURIComponent(n)}`,operation:"destroy",idempotent:!0,confirmDelete:n,sandboxId:n});await Y(H(s),n)}catch(s){if(s instanceof e&&s.code==="not_found")return;throw s}finally{for(let s of y.keys())if(s.startsWith(`${n}:`))y.delete(s)}}async function Ce(n,s,d){let u;try{await ce(n)}catch(m){u=m instanceof e?m.code:"provider"}throw le(d,{sandboxId:n,stage:s,cleanupCode:u})}return{name:$e,keyMode:"best-effort",commandShell:"bash",capabilities:new Set(["pause","snapshot","snapshot-delete","size"]),async create(n){if(n.network!==void 0&&n.network!=="all")throw p("network policies are not supported","unsupported");let s={...n.labels};if(n.key!==void 0)s[W]=n.key;if(Object.keys(s).length>32)throw p("at most 32 labels (one is used for the key)","unsupported");let d=n.from?.startsWith("sn_")?n.from:void 0,u=d?void 0:n.from??r.template,m=Ne(n.size),b={name:`sbx-${Q().slice(0,13).replace("-","")}`,metadata:s,...m};if(d)b.snapshotId=d;else if(u)b.templateId=u;if(n.idleTimeoutMs!==void 0)b.autoSuspendAfterSeconds=De(n.idleTimeoutMs);if(n.timeoutMs!==void 0)b.deleteAfterSeconds=Ue(n.timeoutMs);let w=Object.fromEntries(Object.entries(n.env??{}).filter(([C])=>!Re(C)));if(Object.keys(w).length>0)b.env=w;let _=H(await E({method:"POST",path:"/v1/machines",operation:"create",body:b,idempotent:!0})),k=_.machineId,v="operation",g=()=>p("create aborted","aborted",{sandboxId:k});try{if(await Y(_,k),n.signal?.aborted)throw g();if(v="prepare",await V(k,["bash","-c",Pe]),n.signal?.aborted)throw g();return v="read",z(await Z(k))}catch(C){return Ce(k,v,C)}},async find(n){let[s]=await ae({[W]:n});return s?z(s):void 0},async connect(n){return z(await Z(n))},async list(n){return(await ae(n)).map(z)},destroy:ce,async exec(n,s){let d={cmd:s.command,cwd:s.cwd,envs:s.env};if(s.stdin!==void 0){let u=new TextEncoder().encode(s.stdin);if(u.byteLength<=1048576)return j(n,{...d,stdin:s.stdin},s);let m=`/tmp/.sandbox-sdk/stdin-${Q()}`,b=Date.now(),w=new AbortController,_=setTimeout(()=>w.abort(),s.timeoutMs),k=s.signal?AbortSignal.any([s.signal,w.signal]):w.signal,v=()=>j(n,{argv:["rm","-f","--",m]},{timeoutMs:1e4,onChunk:()=>{return}}).catch(()=>{return});try{await de(n,m,u,{signal:k,timeoutMs:s.timeoutMs})}catch(M){if(await v(),k.aborted)return{exitCode:null,timedOut:!0};throw M}finally{clearTimeout(_)}let g=`exec < ${Ie(m)}; rm -f ${Ie(m)}; ${s.command}`,C;try{C=await j(n,{...d,cmd:g},{...s,timeoutMs:Math.max(1,s.timeoutMs-(Date.now()-b))})}catch(M){throw await v(),M}if(C.exitCode===null)await v();return C}return j(n,d,s)},files:{writeCreatesParents:!0,writeSupportsMode:!0,async read(n,s){try{let d=await L({method:"GET",path:`/v1/machines/${encodeURIComponent(n)}/files/content`,operation:"read file",query:{path:U(s)},sandboxId:n,timeoutMs:300000});return new Uint8Array(await d.arrayBuffer())}catch(d){if(d instanceof D&&d.status===404)throw p(`no such file: ${s}`,"file_not_found",{sandboxId:n});if(d instanceof D&&d.body.code==="not_a_file")throw p(`${s} is a directory`,"invalid_argument",{sandboxId:n});throw J(d,"read file",n)}},async write(n,s,d,u){await de(n,s,d,{mode:u?.mode,timeoutMs:300000})},async list(n,s){let d;try{d=await E({method:"GET",path:`/v1/machines/${encodeURIComponent(n)}/files`,operation:"list files",query:{path:U(s)},sandboxId:n})}catch(m){if(m instanceof e&&m.code==="not_found")throw p(`no such directory: ${s}`,"file_not_found",{sandboxId:n});throw m}if(x(d,"type")!=="dir")throw p(`${s} is not a directory`,"invalid_argument",{sandboxId:n});let u=x(d,"entries");if(!Array.isArray(u))throw p("directory listing has no entries","provider",{sandboxId:n});if(u.length>=5000){let{stdout:m}=await V(n,["find","-H",U(s),"-mindepth","1","-maxdepth","1","-printf","%P\\0%y\\0%s\\0%T@\\0"]);return xe(s,m)}return u.map((m)=>be(s,m))},async stat(n,s){let d=U(s),u=d==="/workspace"||d==="/workspace/"?["-L"]:[],{exitCode:m,stdout:b}=await V(n,["stat",...u,"-c","%F|%s|%.3Y","--",d],[0,1]);if(m!==0)throw p(`no such file: ${s}`,"file_not_found",{sandboxId:n});return ye(s,b.trim())},async remove(n,s,d){let u=U(s),{exitCode:m}=await V(n,["bash","-c",'test -e "$1" || test -L "$1" || exit 3; rm -f $2 -- "$1"',"remove",u,d.recursive?"-r":"-d"],[0,3]);if(m===3)throw p(`no such file: ${s}`,"file_not_found",{sandboxId:n})},async mkdir(n,s){await V(n,["mkdir","-p","--",U(s)])}},async previewUrl(n,s){let d=y.get(`${n}:${s}`);if(d)return{url:d};let u=await E({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/ports`,operation:"publish port",body:{port:s},sandboxId:n}),m=x(u,"url");if(!t(m))throw p("publishing the port returned no URL","provider",{sandboxId:n});return y.set(`${n}:${s}`,m),{url:m}},native(n){return{machineId:n,request:({method:s,path:d,body:u})=>{let m=s.toUpperCase();if(m!=="GET"&&m!=="POST"&&m!=="PUT"&&m!=="PATCH"&&m!=="DELETE")throw p(`unsupported method ${s}`,"invalid_argument");return E({method:m,path:d,operation:"native request",body:u,idempotent:m!=="GET",sandboxId:n})}}},async pause(n){await ie(n,"suspend")},async resume(n){let s=await Z(n);await ie(n,s.state==="stopped"?"start":"resume")},async snapshot(n,s){if(s?.expiresInMs)throw p("snapshots are kept until deleted; omit expiresInMs","unsupported",{sandboxId:n});let d=oe(await E({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/snapshots`,operation:"snapshot",body:{name:`sbx-${Q()}`},idempotent:!0,sandboxId:n,timeoutMs:h})),u=Date.now()+h;while(d.status==="pending"){if(Date.now()>u)throw p(`snapshot ${d.id} is still pending`,"timeout",{sandboxId:n});await se(500),d=oe(await E({method:"GET",path:`/v1/snapshots/${encodeURIComponent(d.id)}`,operation:"snapshot status",sandboxId:n}))}if(d.status!=="ready")throw p(`snapshot ${d.id} ended ${d.status}`,"provider",{sandboxId:n});return{id:d.id}},async deleteSnapshot(n){try{return await E({method:"DELETE",path:`/v1/snapshots/${encodeURIComponent(n)}`,operation:"delete snapshot",idempotent:!0,confirmDelete:n}),!0}catch(s){if(s instanceof e&&s.code==="not_found")return!1;throw s}}}}function nt(r={}){return ge(r)}export{nt as instabox};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n}from"../../chunk-2ts3evzh.js";import{
|
|
2
|
-
`)){let w=g(R(T));if(w.error)throw d(`Image pull: ${L(w.error)}`)}return}return R(C.toString())}async exec(s,a,l){let E=g(await this.call("POST",`/containers/${k(s)}/exec`,{Cmd:a,WorkingDir:l.cwd??"/",User:l.user,Env:Object.entries(l.env??{}).map(([w,b])=>`${w}=${b}`),AttachStdout:!0,AttachStderr:!0,AttachStdin:l.stdin!==void 0,Tty:!1})),C=L(E.Id);await new Promise((w,b)=>{let h=new K(l.onChunk),M=W({agent:this.pool(),socketPath:this.socketPath,path:`/v1.44/exec/${k(C)}/start`,method:"POST",headers:{"Content-Type":"application/json","User-Agent":x,Connection:"Upgrade",Upgrade:"tcp"}}),S=(v)=>{v.on("data",(P)=>{try{h.push(P)}catch(I){v.destroy(),b(I)}}),v.on("error",(P)=>b(d(P.message,"unavailable"))),v.on("end",()=>{try{h.end(),w()}catch(P){b(P)}})};M.on("upgrade",(v,P,I)=>{if(P.setTimeout(0),S(P),I.length)try{h.push(I)}catch(r){P.destroy(),b(r);return}P.end(l.stdin??"")}),M.on("response",(v)=>{if((v.statusCode??500)>=400){v.resume(),b(d(`Exec attach HTTP ${v.statusCode}`));return}S(v)}),M.on("error",(v)=>b(d(v.message,"unavailable"))),M.setTimeout(30000,()=>M.destroy(d("Exec attach timed out","timeout"))),M.end(JSON.stringify({Detach:!1,Tty:!1}))});let T=g(await this.call("GET",`/exec/${k(C)}/json`));if(T.Running)throw d("Exec attachment ended before the process exited","outcome_unknown");return q(T.ExitCode)}}var F="sandbox-sdk.local.deadline",H="sandbox-sdk.local.idle-ms",_="/tmp/.sandbox-sdk-activity",z="sandbox-sdk.local.key",Z="sandbox-sdk.local.snapshot",se=["for d in /tmp/.sandbox-sdk/procs/*/",'do [ -d "$d" ] || continue','rm -rf "$d"lock','[ ! -f "$d"spec.json ] || [ -f "$d"exit ] || printf 137 > "$d"exit || exit 1',"done","rm -rf /tmp/.sandbox-sdk/runs/*"].join("; "),ie=new Set([F,H,z,Z]),ee=(s)=>Object.fromEntries(Object.entries(s).filter(([a])=>!ie.has(a))),X=(s)=>`sandbox-sdk-${oe("sha256").update(s).digest("hex")}`,ae={small:{cpu:1,memoryMb:1024},medium:{cpu:2,memoryMb:4096},large:{cpu:4,memoryMb:8192}};function ce(s){if(!s)return{};if(!t(s)&&s.diskGb!==void 0)throw d("Docker cannot enforce diskGb portably; pass only cpu and memoryMb, or use small, medium, or large","unsupported");let a=t(s)?ae[s]:s;if(!a)throw d("Unknown size preset","unsupported");if(!(a.cpu>0)||!Number.isFinite(a.cpu)||!Number.isSafeInteger(a.memoryMb)||a.memoryMb<6)throw d("Custom sizes need cpu above 0 and memoryMb of at least 6","invalid_argument");return{NanoCpus:Math.round(a.cpu*1e9),Memory:a.memoryMb*1024*1024,MemorySwap:a.memoryMb*1024*1024}}function de(s,a){let l=g(s);return a.startsWith(`${String(l.Os)}/${String(l.Architecture)}`)}var Q=(s,a)=>{if(s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw d(`${a} must be a positive integer`,"invalid_argument")};function ue(s){Q(s.pidsLimit,"pidsLimit"),Q(s.shmSizeMb,"shmSizeMb");let a=s.networkMode;if(a!==void 0&&(!a||a==="host"||a==="none"||a.startsWith("container:")))throw d("networkMode must name a bridge-style network; host and container modes break localhost previews and network: none","unsupported");for(let l of s.mounts??[]){if(!["bind","volume","tmpfs"].includes(l.type)||!l.target.startsWith("/"))throw d("Mounts need type bind, volume or tmpfs and an absolute target","invalid_argument");if(l.type==="bind"?!l.source?.startsWith("/"):l.type==="tmpfs"&&l.source!==void 0)throw d("Bind mounts need an absolute host source; tmpfs mounts take none","invalid_argument")}return{Runtime:s.runtime,Mounts:s.mounts?.length?s.mounts.map((l)=>({Type:l.type,Target:l.target,Source:l.source,ReadOnly:l.readOnly??!1})):void 0,PidsLimit:s.pidsLimit,ShmSize:s.shmSizeMb===void 0?void 0:s.shmSizeMb*1024*1024,CapAdd:s.capAdd?.length?s.capAdd:void 0,CapDrop:s.capDrop?.length?s.capDrop:void 0,SecurityOpt:s.securityOpt?.length?s.securityOpt:void 0}}function te(s){let a=g(s),l=g(a.Config),E=g(a.State),C=Object.fromEntries(Object.entries(g(l.Labels??{})).map(([T,w])=>[T,L(w)]));if(C["sandbox-sdk"]!=="1")throw d("Container was not created by Sandbox SDK","not_found");return{info:{id:L(a.Id),key:C[z]||void 0,labels:ee(C),state:E.Paused?"paused":E.Running?"running":"stopped",createdAt:Date.parse(L(a.Created))},labels:C}}var Y=(s)=>te(s).info;function ve(s={}){let a=new U(s.dockerHost),l=s.image??"node:22-bookworm",E=ue(s),C=s.platform?`&platform=${k(s.platform)}`:"",T=new Map,w=new Set,b=new Map,h=(r)=>a.call("GET",`/containers/${k(r)}/json`);async function M(r,i,u){let f="",p="",m=w.has(r)?["sh","-c",`touch ${_}; "$@"; code=$?; touch ${_}; exit "$code"`,"sh",...i]:i,O=await a.exec(r,m,{stdin:u,onChunk(D){if(D.stream==="stdout")f+=D.text;else p+=D.text}});if(O!==0)throw d(`Container operation exited ${O}: ${p}`,p.includes("ENOENT")||p.includes("No such file")?"file_not_found":"provider");return f}let S=(r,i,u=[],f)=>M(r,["node","-e",i,...u],f),v="const fs=require('fs'); const p=require('path'); const stat=x=>{const s=fs.lstatSync(x);return {path:x,type:s.isSymbolicLink()?'symlink':s.isDirectory()?'directory':'file',size:s.size,modifiedAt:s.mtimeMs}};";function P(r){let i=g(r),u=i.type;if(u!=="file"&&u!=="directory"&&u!=="symlink")throw d("Invalid file type");return{path:L(i.path),type:u,size:q(i.size),modifiedAt:q(i.modifiedAt)}}let I={name:"local",keyMode:"exact",capabilities:new Set(["pause","snapshot","size","network-policy"]),async create(r){if(r.network!==void 0&&r.network!=="all"&&r.network!=="none")throw d("Network allow-lists cannot be enforced by this Docker adapter","unsupported");for(let y of[r.idleTimeoutMs,r.timeoutMs])if(y!==void 0&&(!Number.isFinite(y)||y<=0))throw d("Timeouts must be positive milliseconds","invalid_argument");let i=ce(r.size);if(r.signal?.aborted)throw d("Creation aborted","aborted");let u={},f=performance.now(),p=r.from??l,m;try{let y=await a.call("GET",`/images/${k(p)}/json`);m=!s.platform||r.from!==void 0||de(y,s.platform)}catch(y){if(!(y instanceof e)||y.code!=="not_found")throw y;if(r.from)throw d("Snapshot image not found","not_found");m=!1}if(!m)await a.call("POST",`/images/create?fromImage=${k(p)}${C}`);if(u.createInspectMs=performance.now()-f,r.signal?.aborted)throw d("Creation aborted after image pull","aborted");let O=[...new Set(r.ports??[3000])],D=Object.fromEntries(O.map((y)=>[`${y}/tcp`,[{HostIp:"127.0.0.1",HostPort:""}]]));f=performance.now();let j=Date.now(),J={...r.labels,"sandbox-sdk":"1",[z]:r.key??"",[F]:r.timeoutMs===void 0?"":String(j+r.timeoutMs),[H]:r.idleTimeoutMs===void 0?"":String(r.idleTimeoutMs)},N=g(await a.call("POST",`/containers/create?name=${k(r.key?X(r.key):`sandbox-sdk-${V()}`)}${r.from===void 0?C:""}`,{Image:p,WorkingDir:"/workspace",Cmd:["sh","-c","exec sleep infinity"],User:s.user,Env:Object.entries(r.env??{}).map(([y,ne])=>`${y}=${ne}`),Labels:J,ExposedPorts:Object.fromEntries(O.map((y)=>[`${y}/tcp`,{}])),HostConfig:{...E,...i,NetworkMode:r.network==="none"?"none":s.networkMode??"bridge",PortBindings:r.network==="none"?{}:D,Init:!0}}));u.createContainerMs=performance.now()-f;let A=L(N.Id);if(b.set(A,u),r.timeoutMs!==void 0||r.idleTimeoutMs!==void 0)w.add(A);try{if(f=performance.now(),await a.call("POST",`/containers/${k(A)}/start`),u.createStartMs=performance.now()-f,f=performance.now(),s.user!==void 0){if(await a.exec(A,["chown","--",s.user,"/workspace"],{user:"0",onChunk(){}})!==0)throw d(`Could not give /workspace to user ${s.user}`,"invalid_argument")}if(r.from!==void 0)await M(A,["sh","-c",se]);if(u.createPrerequisiteMs=performance.now()-f,r.signal?.aborted)throw d("Creation aborted","aborted");if(r.timeoutMs!==void 0||r.idleTimeoutMs!==void 0)return await I.connect(A);return{id:A,key:r.key,labels:ee(J),state:"running",createdAt:j}}catch(y){throw await I.destroy(A),y}},async find(r){try{let i=await I.connect(X(r));return i.key===r?i:void 0}catch(i){if(i instanceof e&&i.code==="not_found")return;throw i}},async connect(r){let{info:i,labels:u}=te(await h(r)),f=(D)=>D?Number(D):1/0,p=f(u[F]),m=f(u[H]);if(Number.isFinite(p)||Number.isFinite(m))w.add(i.id);let O=Date.now()>=p;if(!O&&Number.isFinite(m)&&i.state==="running"){let D="";if(await a.exec(i.id,["node","-e",`const f=require('fs'), p='/tmp/.sandbox-sdk';const busy=(f.existsSync(p+'/runs')&&f.readdirSync(p+'/runs').length)||(f.existsSync(p+'/procs')&&f.readdirSync(p+'/procs').some(n=>!f.existsSync(p+'/procs/'+n+'/exit')));process.stdout.write(String(busy?Date.now():Math.max(${i.createdAt},f.existsSync('${_}')?f.statSync('${_}').mtimeMs:0)))`],{onChunk(J){if(J.stream==="stdout")D+=J.text}})!==0||!Number.isFinite(Number(D)))throw d("Could not check local idle deadline","provider");O=Date.now()-Number(D)>=m}if(O)throw await I.destroy(i.id),d("Local sandbox deadline expired; create another sandbox","not_found");return i},async list(r){let i=k(JSON.stringify({label:Object.entries({...r,"sandbox-sdk":"1"}).map(([p,m])=>`${p}=${m}`)})),u=B(await a.call("GET",`/containers/json?all=1&filters=${i}`)),f=[];for(let p of u)try{f.push(Y(await h(L(g(p).Id))))}catch(m){if(!(m instanceof e)||m.code!=="not_found")throw m}return f},async destroy(r){let i=T.get(r);if(i)return i;let u=(async()=>{try{let f=Y(await h(r));if(f.state==="paused")await a.call("POST",`/containers/${k(r)}/unpause`);if(f.state!=="stopped")await a.call("POST",`/containers/${k(r)}/stop?t=1`);await a.call("DELETE",`/containers/${k(r)}?force=1&v=1`)}catch(f){if(!(f instanceof e)||f.code!=="not_found")throw f}})();T.set(r,u);try{await u}finally{T.delete(r),w.delete(r),b.delete(r)}},async exec(r,i){let u=performance.now();if(i.signal?.aborted)return{exitCode:null,timedOut:!0};let f=`/tmp/.sandbox-sdk-exec-${V()}`,p=!1,m=()=>{},O=new Promise((N)=>{m=()=>{p=!0,N("cancelled")}});i.signal?.addEventListener("abort",m,{once:!0});let D=setTimeout(m,i.timeoutMs),j=["setsid","--wait","sh","-c",`echo $$ > ${n(f)}; ${w.has(r)?`touch ${_}; trap 'touch ${_}' EXIT;`:""} cd ${n(i.cwd)} || exit; sh -c ${n(i.command)}`],J=a.exec(r,j,{env:i.env,stdin:i.stdin,onChunk:i.onChunk});try{if(await Promise.race([J,O]),p)await M(r,["sh","-c",`i=0; while [ ! -s ${n(f)} ]; do i=$((i+1)); [ "$i" -lt 3000 ] || exit 1; sleep .01; done; p=$(cat ${n(f)}); node -e 'try {process.kill(-Number(process.argv[1]), "SIGKILL")} catch(e) {if(e.code!=="ESRCH") throw e}' "$p"`]);let N=await J;return{exitCode:p?null:N,timedOut:p}}finally{clearTimeout(D),i.signal?.removeEventListener("abort",m),await M(r,["rm","-f",f]).catch(()=>{});let N=b.get(r);if(N&&N.firstCommandMs===void 0)N.firstCommandMs=performance.now()-u}},files:{writeCreatesParents:!0,writeSupportsMode:!0,listOrder:"name",async read(r,i){return new Uint8Array(Buffer.from(await S(r,"process.stdout.write(require('fs').readFileSync(process.argv[1]).toString('base64'))",[i]),"base64"))},async write(r,i,u,f){await S(r,"const f=require('fs'),p=process.argv[1];f.mkdirSync(require('path').dirname(p),{recursive:true});f.writeFileSync(p,Buffer.from(f.readFileSync(0,'utf8'),'base64'));if(process.argv[2])f.chmodSync(p,parseInt(process.argv[2],8))",[i,f?.mode===void 0?"":f.mode.toString(8)],Buffer.from(u).toString("base64"))},async stat(r,i){return P(R(await S(r,v+"process.stdout.write(JSON.stringify(stat(process.argv[1])))",[i])))},async list(r,i){return B(R(await S(r,v+"process.stdout.write(JSON.stringify(fs.readdirSync(process.argv[1]).map(x=>stat(p.join(process.argv[1],x)))))",[i]))).map(P)},async mkdir(r,i){await S(r,"require('fs').mkdirSync(process.argv[1],{recursive:true})",[i])},async remove(r,i,u){await S(r,"require('fs').rmSync(process.argv[1],{recursive:process.argv[2]==='true'})",[i,String(u.recursive)])}},async previewUrl(r,i){let u=g(await h(r)),f=g(u.NetworkSettings),p=g(f.Ports??{}),m=B(p[`${i}/tcp`]??[])[0];if(!m)throw d(`Port ${i} has no localhost mapping; declare it in ports when creating the sandbox`,"unsupported");let O=g(m);if(O.HostIp!=="127.0.0.1")throw d("Preview binding is not loopback","unsupported");return{url:`http://127.0.0.1:${L(O.HostPort)}/`}},native(r){return{id:r,client:a}},async usage(r){let i=g(await h(r)),u=g(i.State);return{...b.get(r),runningMs:u.Running&&!u.Paused?Math.max(0,Date.now()-Date.parse(L(u.StartedAt))):0}},async pause(r){await I.connect(r),await a.call("POST",`/containers/${k(r)}/pause`)},async resume(r){await I.connect(r),await a.call("POST",`/containers/${k(r)}/unpause`)},async snapshot(r,i){if(i?.expiresInMs)throw d("Docker images do not expire; omit expiresInMs and delete the snapshot image when you are done","unsupported");await I.connect(r);let u=g(await a.call("POST",`/commit?container=${k(r)}&pause=true`,{Labels:{"sandbox-sdk":"1",[Z]:"1"}}));return{id:L(u.Id)}}};return I}export{ve as local};
|
|
1
|
+
import{n}from"../../chunk-2ts3evzh.js";import{S}from"../../chunk-h6xh0pr0.js";import{l}from"../../chunk-m7hbefp1.js";import{t,o,e}from"../../chunk-xx9znywe.js";import{createHash as oe,randomUUID as V}from"node:crypto";import{Agent as re,request as W}from"node:http";import{StringDecoder as G}from"node:string_decoder";var c=(s,a="provider")=>new e(`${s}. Docker request failed. Check Docker access and the supplied options.`,{code:a,provider:"local"});function g(s){if(!l(s))throw c("Invalid Docker response");return Object.fromEntries(Object.entries(s))}function L(s){if(!t(s))throw c("Expected a Docker string");return s}function q(s){if(!o(s)||!Number.isFinite(s))throw c("Expected a Docker number");return s}function B(s){if(!Array.isArray(s))throw c("Expected a Docker array");return s}var k=encodeURIComponent;function R(s){try{return JSON.parse(s)}catch{throw c("Malformed Docker JSON response")}}class K{emit;pending=Buffer.alloc(0);stdout=new G("utf8");stderr=new G("utf8");constructor(s){this.emit=s}push(s){this.pending=Buffer.concat([this.pending,s]);while(this.pending.length>=8){let a=this.pending.readUInt32BE(4);if(a>67108864||![1,2].includes(this.pending[0]??0))throw c("Invalid Docker exec frame");if(this.pending.length<a+8)return;let f=this.pending[0]===1?"stdout":"stderr",E=this[f].write(this.pending.subarray(8,a+8));if(E)this.emit({stream:f,text:E});this.pending=this.pending.subarray(a+8)}}end(){if(this.pending.length)throw c("Truncated Docker exec frame");for(let s of["stdout","stderr"]){let a=this[s].end();if(a)this.emit({stream:s,text:a})}}}class U{socketPath;connectionPool;pool(){return this.connectionPool??=new re({keepAlive:!0,timeout:5000})}constructor(s=process.env.DOCKER_HOST??"unix:///var/run/docker.sock"){if(!s.startsWith("unix://")||!s.slice(7).startsWith("/"))throw c("DOCKER_HOST must be an absolute unix:// socket URL; remote Docker hosts cannot provide localhost previews","unsupported");this.socketPath=s.slice(7)}async call(s,a,f){let E=f===void 0?void 0:JSON.stringify(f),C=await new Promise((T,w)=>{let b=W({agent:this.pool(),socketPath:this.socketPath,path:`/v1.44${a}`,method:s,headers:{"Content-Type":"application/json","User-Agent":S}},(h)=>{let M=[];h.on("data",(x)=>M.push(x)),h.on("error",(x)=>w(c(x.message,"unavailable"))),h.on("end",()=>{let x=Buffer.concat(M);if((h.statusCode??500)>=400){w(c(x.toString(),h.statusCode===404?"not_found":h.statusCode===401||h.statusCode===403?"auth":"provider"));return}T(x)})});b.setTimeout(600000,()=>b.destroy(c("Docker API timed out","timeout"))),b.on("error",(h)=>w(h instanceof e?h:c(h.message,"unavailable"))),b.end(E)});if(!C.length)return;if(a.startsWith("/images/create")){for(let T of C.toString().trim().split(`
|
|
2
|
+
`)){let w=g(R(T));if(w.error)throw c(`Image pull: ${L(w.error)}`)}return}return R(C.toString())}async exec(s,a,f){let E=g(await this.call("POST",`/containers/${k(s)}/exec`,{Cmd:a,WorkingDir:f.cwd??"/",User:f.user,Env:Object.entries(f.env??{}).map(([w,b])=>`${w}=${b}`),AttachStdout:!0,AttachStderr:!0,AttachStdin:f.stdin!==void 0,Tty:!1})),C=L(E.Id);await new Promise((w,b)=>{let h=new K(f.onChunk),M=W({agent:this.pool(),socketPath:this.socketPath,path:`/v1.44/exec/${k(C)}/start`,method:"POST",headers:{"Content-Type":"application/json","User-Agent":S,Connection:"Upgrade",Upgrade:"tcp"}}),x=(v)=>{v.on("data",(P)=>{try{h.push(P)}catch(I){v.destroy(),b(I)}}),v.on("error",(P)=>b(c(P.message,"unavailable"))),v.on("end",()=>{try{h.end(),w()}catch(P){b(P)}})};M.on("upgrade",(v,P,I)=>{if(P.setTimeout(0),x(P),I.length)try{h.push(I)}catch(r){P.destroy(),b(r);return}P.end(f.stdin??"")}),M.on("response",(v)=>{if((v.statusCode??500)>=400){v.resume(),b(c(`Exec attach HTTP ${v.statusCode}`));return}x(v)}),M.on("error",(v)=>b(c(v.message,"unavailable"))),M.setTimeout(30000,()=>M.destroy(c("Exec attach timed out","timeout"))),M.end(JSON.stringify({Detach:!1,Tty:!1}))});let T=g(await this.call("GET",`/exec/${k(C)}/json`));if(T.Running)throw c("Exec attachment ended before the process exited","outcome_unknown");return q(T.ExitCode)}}var F="sandbox-sdk.local.deadline",H="sandbox-sdk.local.idle-ms",_="/tmp/.sandbox-sdk-activity",z="sandbox-sdk.local.key",Z="sandbox-sdk.local.snapshot",se=["for d in /tmp/.sandbox-sdk/procs/*/",'do [ -d "$d" ] || continue','rm -rf "$d"lock','[ ! -f "$d"spec.json ] || [ -f "$d"exit ] || printf 137 > "$d"exit || exit 1',"done","rm -rf /tmp/.sandbox-sdk/runs/*"].join("; "),ie=new Set([F,H,z,Z]),ee=(s)=>Object.fromEntries(Object.entries(s).filter(([a])=>!ie.has(a))),X=(s)=>`sandbox-sdk-${oe("sha256").update(s).digest("hex")}`,ae={small:{cpu:1,memoryMb:1024},medium:{cpu:2,memoryMb:4096},large:{cpu:4,memoryMb:8192}};function ce(s){if(!s)return{};if(!t(s)&&s.diskGb!==void 0)throw c("Docker cannot enforce diskGb portably; pass only cpu and memoryMb, or use small, medium, or large","unsupported");let a=t(s)?ae[s]:s;if(!a)throw c("Unknown size preset","unsupported");if(!(a.cpu>0)||!Number.isFinite(a.cpu)||!Number.isSafeInteger(a.memoryMb)||a.memoryMb<6)throw c("Custom sizes need cpu above 0 and memoryMb of at least 6","invalid_argument");return{NanoCpus:Math.round(a.cpu*1e9),Memory:a.memoryMb*1024*1024,MemorySwap:a.memoryMb*1024*1024}}function de(s,a){let f=g(s);return a.startsWith(`${String(f.Os)}/${String(f.Architecture)}`)}var Q=(s,a)=>{if(s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw c(`${a} must be a positive integer`,"invalid_argument")};function ue(s){Q(s.pidsLimit,"pidsLimit"),Q(s.shmSizeMb,"shmSizeMb");let a=s.networkMode;if(a!==void 0&&(!a||a==="host"||a==="none"||a.startsWith("container:")))throw c("networkMode must name a bridge-style network; host and container modes break localhost previews and network: none","unsupported");for(let f of s.mounts??[]){if(!["bind","volume","tmpfs"].includes(f.type)||!f.target.startsWith("/"))throw c("Mounts need type bind, volume or tmpfs and an absolute target","invalid_argument");if(f.type==="bind"?!f.source?.startsWith("/"):f.type==="tmpfs"&&f.source!==void 0)throw c("Bind mounts need an absolute host source; tmpfs mounts take none","invalid_argument")}return{Runtime:s.runtime,Mounts:s.mounts?.length?s.mounts.map((f)=>({Type:f.type,Target:f.target,Source:f.source,ReadOnly:f.readOnly??!1})):void 0,PidsLimit:s.pidsLimit,ShmSize:s.shmSizeMb===void 0?void 0:s.shmSizeMb*1024*1024,CapAdd:s.capAdd?.length?s.capAdd:void 0,CapDrop:s.capDrop?.length?s.capDrop:void 0,SecurityOpt:s.securityOpt?.length?s.securityOpt:void 0}}function te(s){let a=g(s),f=g(a.Config),E=g(a.State),C=Object.fromEntries(Object.entries(g(f.Labels??{})).map(([T,w])=>[T,L(w)]));if(C["sandbox-sdk"]!=="1")throw c("Container was not created by Sandbox SDK","not_found");return{info:{id:L(a.Id),key:C[z]||void 0,labels:ee(C),state:E.Paused?"paused":E.Running?"running":"stopped",createdAt:Date.parse(L(a.Created))},labels:C}}var Y=(s)=>te(s).info;function ve(s={}){let a=new U(s.dockerHost),f=s.image??"node:22-bookworm",E=ue(s),C=s.platform?`&platform=${k(s.platform)}`:"",T=new Map,w=new Set,b=new Map,h=(r)=>a.call("GET",`/containers/${k(r)}/json`);async function M(r,i,d){let u="",p="",m=w.has(r)?["sh","-c",`touch ${_}; "$@"; code=$?; touch ${_}; exit "$code"`,"sh",...i]:i,O=await a.exec(r,m,{stdin:d,onChunk(D){if(D.stream==="stdout")u+=D.text;else p+=D.text}});if(O!==0)throw c(`Container operation exited ${O}: ${p}`,p.includes("ENOENT")||p.includes("No such file")?"file_not_found":"provider");return u}let x=(r,i,d=[],u)=>M(r,["node","-e",i,...d],u),v="const fs=require('fs'); const p=require('path'); const stat=x=>{const s=fs.lstatSync(x);return {path:x,type:s.isSymbolicLink()?'symlink':s.isDirectory()?'directory':'file',size:s.size,modifiedAt:s.mtimeMs}};";function P(r){let i=g(r),d=i.type;if(d!=="file"&&d!=="directory"&&d!=="symlink")throw c("Invalid file type");return{path:L(i.path),type:d,size:q(i.size),modifiedAt:q(i.modifiedAt)}}let I={name:"local",keyMode:"exact",capabilities:new Set(["pause","snapshot","size","network-policy"]),async create(r){if(r.network!==void 0&&r.network!=="all"&&r.network!=="none")throw c("Network allow-lists cannot be enforced by this Docker adapter","unsupported");for(let y of[r.idleTimeoutMs,r.timeoutMs])if(y!==void 0&&(!Number.isFinite(y)||y<=0))throw c("Timeouts must be positive milliseconds","invalid_argument");let i=ce(r.size);if(r.signal?.aborted)throw c("Creation aborted","aborted");let d={},u=performance.now(),p=r.from??f,m;try{let y=await a.call("GET",`/images/${k(p)}/json`);m=!s.platform||r.from!==void 0||de(y,s.platform)}catch(y){if(!(y instanceof e)||y.code!=="not_found")throw y;if(r.from)throw c("Snapshot image not found","not_found");m=!1}if(!m)await a.call("POST",`/images/create?fromImage=${k(p)}${C}`);if(d.createInspectMs=performance.now()-u,r.signal?.aborted)throw c("Creation aborted after image pull","aborted");let O=[...new Set(r.ports??[3000])],D=Object.fromEntries(O.map((y)=>[`${y}/tcp`,[{HostIp:"127.0.0.1",HostPort:""}]]));u=performance.now();let j=Date.now(),J={...r.labels,"sandbox-sdk":"1",[z]:r.key??"",[F]:r.timeoutMs===void 0?"":String(j+r.timeoutMs),[H]:r.idleTimeoutMs===void 0?"":String(r.idleTimeoutMs)},N=g(await a.call("POST",`/containers/create?name=${k(r.key?X(r.key):`sandbox-sdk-${V()}`)}${r.from===void 0?C:""}`,{Image:p,WorkingDir:"/workspace",Cmd:["sh","-c","exec sleep infinity"],User:s.user,Env:Object.entries(r.env??{}).map(([y,ne])=>`${y}=${ne}`),Labels:J,ExposedPorts:Object.fromEntries(O.map((y)=>[`${y}/tcp`,{}])),HostConfig:{...E,...i,NetworkMode:r.network==="none"?"none":s.networkMode??"bridge",PortBindings:r.network==="none"?{}:D,Init:!0}}));d.createContainerMs=performance.now()-u;let A=L(N.Id);if(b.set(A,d),r.timeoutMs!==void 0||r.idleTimeoutMs!==void 0)w.add(A);try{if(u=performance.now(),await a.call("POST",`/containers/${k(A)}/start`),d.createStartMs=performance.now()-u,u=performance.now(),s.user!==void 0){if(await a.exec(A,["chown","--",s.user,"/workspace"],{user:"0",onChunk(){}})!==0)throw c(`Could not give /workspace to user ${s.user}`,"invalid_argument")}if(r.from!==void 0)await M(A,["sh","-c",se]);if(d.createPrerequisiteMs=performance.now()-u,r.signal?.aborted)throw c("Creation aborted","aborted");if(r.timeoutMs!==void 0||r.idleTimeoutMs!==void 0)return await I.connect(A);return{id:A,key:r.key,labels:ee(J),state:"running",createdAt:j}}catch(y){throw await I.destroy(A),y}},async find(r){try{let i=await I.connect(X(r));return i.key===r?i:void 0}catch(i){if(i instanceof e&&i.code==="not_found")return;throw i}},async connect(r){let{info:i,labels:d}=te(await h(r)),u=(D)=>D?Number(D):1/0,p=u(d[F]),m=u(d[H]);if(Number.isFinite(p)||Number.isFinite(m))w.add(i.id);let O=Date.now()>=p;if(!O&&Number.isFinite(m)&&i.state==="running"){let D="";if(await a.exec(i.id,["node","-e",`const f=require('fs'), p='/tmp/.sandbox-sdk';const busy=(f.existsSync(p+'/runs')&&f.readdirSync(p+'/runs').length)||(f.existsSync(p+'/procs')&&f.readdirSync(p+'/procs').some(n=>!f.existsSync(p+'/procs/'+n+'/exit')));process.stdout.write(String(busy?Date.now():Math.max(${i.createdAt},f.existsSync('${_}')?f.statSync('${_}').mtimeMs:0)))`],{onChunk(J){if(J.stream==="stdout")D+=J.text}})!==0||!Number.isFinite(Number(D)))throw c("Could not check local idle deadline","provider");O=Date.now()-Number(D)>=m}if(O)throw await I.destroy(i.id),c("Local sandbox deadline expired; create another sandbox","not_found");return i},async list(r){let i=k(JSON.stringify({label:Object.entries({...r,"sandbox-sdk":"1"}).map(([p,m])=>`${p}=${m}`)})),d=B(await a.call("GET",`/containers/json?all=1&filters=${i}`)),u=[];for(let p of d)try{u.push(Y(await h(L(g(p).Id))))}catch(m){if(!(m instanceof e)||m.code!=="not_found")throw m}return u},async destroy(r){let i=T.get(r);if(i)return i;let d=(async()=>{try{let u=Y(await h(r));if(u.state==="paused")await a.call("POST",`/containers/${k(r)}/unpause`);if(u.state!=="stopped")await a.call("POST",`/containers/${k(r)}/stop?t=1`);await a.call("DELETE",`/containers/${k(r)}?force=1&v=1`)}catch(u){if(!(u instanceof e)||u.code!=="not_found")throw u}})();T.set(r,d);try{await d}finally{T.delete(r),w.delete(r),b.delete(r)}},async exec(r,i){let d=performance.now();if(i.signal?.aborted)return{exitCode:null,timedOut:!0};let u=`/tmp/.sandbox-sdk-exec-${V()}`,p=!1,m=()=>{},O=new Promise((N)=>{m=()=>{p=!0,N("cancelled")}});i.signal?.addEventListener("abort",m,{once:!0});let D=setTimeout(m,i.timeoutMs),j=["setsid","--wait","sh","-c",`echo $$ > ${n(u)}; ${w.has(r)?`touch ${_}; trap 'touch ${_}' EXIT;`:""} cd ${n(i.cwd)} || exit; sh -c ${n(i.command)}`],J=a.exec(r,j,{env:i.env,stdin:i.stdin,onChunk:i.onChunk});try{if(await Promise.race([J,O]),p)await M(r,["sh","-c",`i=0; while [ ! -s ${n(u)} ]; do i=$((i+1)); [ "$i" -lt 3000 ] || exit 1; sleep .01; done; p=$(cat ${n(u)}); node -e 'try {process.kill(-Number(process.argv[1]), "SIGKILL")} catch(e) {if(e.code!=="ESRCH") throw e}' "$p"`]);let N=await J;return{exitCode:p?null:N,timedOut:p}}finally{clearTimeout(D),i.signal?.removeEventListener("abort",m),await M(r,["rm","-f",u]).catch(()=>{});let N=b.get(r);if(N&&N.firstCommandMs===void 0)N.firstCommandMs=performance.now()-d}},files:{writeCreatesParents:!0,writeSupportsMode:!0,listOrder:"name",async read(r,i){return new Uint8Array(Buffer.from(await x(r,"process.stdout.write(require('fs').readFileSync(process.argv[1]).toString('base64'))",[i]),"base64"))},async write(r,i,d,u){await x(r,"const f=require('fs'),p=process.argv[1];f.mkdirSync(require('path').dirname(p),{recursive:true});f.writeFileSync(p,Buffer.from(f.readFileSync(0,'utf8'),'base64'));if(process.argv[2])f.chmodSync(p,parseInt(process.argv[2],8))",[i,u?.mode===void 0?"":u.mode.toString(8)],Buffer.from(d).toString("base64"))},async stat(r,i){return P(R(await x(r,v+"process.stdout.write(JSON.stringify(stat(process.argv[1])))",[i])))},async list(r,i){return B(R(await x(r,v+"process.stdout.write(JSON.stringify(fs.readdirSync(process.argv[1]).map(x=>stat(p.join(process.argv[1],x)))))",[i]))).map(P)},async mkdir(r,i){await x(r,"require('fs').mkdirSync(process.argv[1],{recursive:true})",[i])},async remove(r,i,d){await x(r,"require('fs').rmSync(process.argv[1],{recursive:process.argv[2]==='true'})",[i,String(d.recursive)])}},async previewUrl(r,i){let d=g(await h(r)),u=g(d.NetworkSettings),p=g(u.Ports??{}),m=B(p[`${i}/tcp`]??[])[0];if(!m)throw c(`Port ${i} has no localhost mapping; declare it in ports when creating the sandbox`,"unsupported");let O=g(m);if(O.HostIp!=="127.0.0.1")throw c("Preview binding is not loopback","unsupported");return{url:`http://127.0.0.1:${L(O.HostPort)}/`}},native(r){return{id:r,client:a}},async usage(r){let i=g(await h(r)),d=g(i.State);return{...b.get(r),runningMs:d.Running&&!d.Paused?Math.max(0,Date.now()-Date.parse(L(d.StartedAt))):0}},async pause(r){await I.connect(r),await a.call("POST",`/containers/${k(r)}/pause`)},async resume(r){await I.connect(r),await a.call("POST",`/containers/${k(r)}/unpause`)},async snapshot(r,i){if(i?.expiresInMs)throw c("Docker images do not expire; omit expiresInMs and delete the snapshot image when you are done","unsupported");await I.connect(r);let d=g(await a.call("POST",`/commit?container=${k(r)}&pause=true`,{Labels:{"sandbox-sdk":"1",[Z]:"1"}}));return{id:L(d.Id)}}};return I}export{ve as local};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`);if(!M&&I<0&&S.length<256)return;F=!0;let _=I<0?S:S.slice(0,I),ue=I<0?"":S.slice(I+1);if(_.startsWith(ee)){let Q=Number(_.slice(ee.length));if(Number.isSafeInteger(Q)&&Q>0)
|
|
1
|
+
import{f}from"../../chunk-bfvk7mnq.js";import{m}from"../../chunk-n0f7xz7g.js";import{o,e,i,u,a}from"../../chunk-xx9znywe.js";import{createHash as Re}from"node:crypto";var Ce=new Map([["NotFoundError","not_found"],["SandboxFilesystemNotFoundError","file_not_found"],["SandboxFilesystemNotADirectoryError","invalid_argument"],["SandboxFilesystemIsADirectoryError","invalid_argument"],["SandboxFilesystemDirectoryNotEmptyError","invalid_argument"],["SandboxFilesystemPathAlreadyExistsError","invalid_argument"],["SandboxFilesystemFileTooLargeError","invalid_argument"],["SandboxFilesystemPermissionError","invalid_argument"],["AlreadyExistsError","invalid_argument"],["ConflictError","invalid_argument"],["InvalidError","invalid_argument"],["ResourceExhaustedError","quota"],["InternalFailure","unavailable"],["TimeoutError","timeout"],["SandboxTimeoutError","timeout"],["AbortError","aborted"]]),De=new Map([[1,"aborted"],[3,"invalid_argument"],[4,"timeout"],[5,"not_found"],[7,"auth"],[8,"quota"],[14,"unavailable"],[16,"auth"]]);function Ae(s){if(/is not a valid sandbox ID/.test(s.message))return"not_found";let l=Ce.get(s.name);if(l)return l;let p=o(s.code)?De.get(s.code):void 0;if(p)return p;if(/token|credential|unauthenticated/i.test(s.message))return"auth";return"provider"}function P(s,l){if(s instanceof e)return s;let p=f(s),w=Ae(p),h=i(s,{code:w,status:o(p.code)?`gRPC ${p.code}`:void 0,redact:u([process.env.MODAL_TOKEN_ID,process.env.MODAL_TOKEN_SECRET])});return new e(`Modal request failed: ${a(w,h.detail)}. Check credentials, resource limits, and the sandbox state before retrying.`,{code:w,provider:"modal",sandboxId:l,retryable:w==="quota"||w==="unavailable",cause:h.cause})}function R(s){throw new e(`${s}. Modal cannot enforce this request. Use the supported Modal settings or another provider.`,{code:"unsupported",provider:"modal"})}function W(s){throw new e(s,{code:"invalid_argument",provider:"modal"})}var B="sandbox-sdk",V="sandbox-sdk-key",Y="sandbox-sdk-created",q="sandbox-sdk-destroying",Oe="destroyed",Le=60000,me="node:22-bookworm",$e=3600000,Fe=24*$e,Be=10,qe=1024,fe=/^[\w.-]{1,63}$/,pe=(s)=>`sdk-${Re("sha256").update(s).digest("hex").slice(0,56)}`,je={small:{cpu:1,memoryMb:2048},medium:{cpu:2,memoryMb:4096},large:{cpu:4,memoryMb:8192}},We='for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/runs; true',ee="__sandbox_sdk_pgid__=",he="__sandbox_sdk_cwd_error__",Ke=`cd -- "$1" 2>/dev/null || { echo ${he} >&2; exit 125; }; echo "${ee}$$" >&2; exec timeout --signal=KILL "$2" sh -c "$3"`;function te(s){return Math.ceil(s/1000)*1000}function Ge(s){let l=new TextEncoder;return Object.entries(s).reduce((p,[w,h])=>p+l.encode(w).length+l.encode(h).length,0)}function Ue(s,l){if(s===void 0)return l??{};if(l!==void 0)W("Pass size to createSandbox or resources to modal(), not both.");if(s==="small"||s==="medium"||s==="large")return we(je[s]);if(s.diskGb!==void 0)R("Modal sets no disk size for a sandbox; leave diskGb unset");if(!Number.isFinite(s.cpu)||s.cpu<0.125)R("Modal needs a cpu of at least 0.125");if(!Number.isSafeInteger(s.memoryMb)||s.memoryMb<128)R("Modal needs memoryMb as a whole number of at least 128");return we(s)}function we({cpu:s,memoryMb:l}){return{cpu:s,cpuLimit:s,memoryMiB:l,memoryLimitMiB:l}}var ze=/^\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?$/;function He(s){if(s===void 0||s==="all")return{};if(s==="none")return{outboundCidrAllowlist:[],outboundDomainAllowlist:[]};let l=s.allow.filter((w)=>ze.test(w)||w.includes(":")),p=s.allow.filter((w)=>!l.includes(w));return{outboundCidrAllowlist:l.map((w)=>w.includes("/")?w:`${w}/${w.includes(":")?128:32}`),outboundDomainAllowlist:p}}function Je(s){let l=s??process.env.MODAL_SANDBOX_REGION;if(l===void 0)return;let p=[l].flat().flatMap((w)=>w.split(",")).map((w)=>w.trim()).filter(Boolean);return p.length?p:void 0}function be(s){if(s===void 0)return;if(s>Fe)R("Modal caps a sandbox's lifetime at 24 hours");return te(s)}async function K(s,l){let p=s.getReader();try{for(;;){let{done:w,value:h}=await p.read();if(w)return;if(h)l(h)}}finally{p.releaseLock()}}var Xe=9;function Qe(s){return s.code===Xe&&/Exec has already completed/.test(s.message)}var Ve=new Set([3,7,8,12,16]);function Ye(s,l){let p=P(s,l);if(p.sandboxId===l)return p;return new e(p.message,{code:p.code,retryable:p.retryable,hint:p.hint,provider:"modal",sandboxId:l,cause:s})}function Ze(s){return o(s.code)&&Ve.has(s.code)||s.name==="InvalidError"}var Z=(s)=>new Promise((l)=>setTimeout(l,s));async function G(s,l){let p;s.catch(()=>{});try{return await Promise.race([s.then((w)=>({settled:!0,value:w})),new Promise((w)=>{p=setTimeout(()=>w({settled:!1}),Math.max(0,l))})])}finally{clearTimeout(p)}}function ye(s){return s[q]!==void 0||s[B]===Oe}function ge(s){return{path:s.path,type:s.type,size:s.size,modifiedAt:s.modifiedTime*1000}}function xe(s,l={}){let p=new Map,w=new Map,h=new Map,C=new Set,k=l.app??"sandbox-sdk",ve=be(l.timeoutMs),ne=l.destroyWaitMs??Le,re,O=new Map,Me,N=()=>re??=(async()=>{try{return await s()}catch(t){throw re=void 0,t}})(),U=(t=k)=>{if(!fe.test(t))W("Modal App names use letters, digits, dashes, periods and underscores, under 64 characters.");let n=O.get(t);if(n)return n;let r=(async()=>{try{return await(await N()).apps.fromName(t,{createIfMissing:!0,environment:l.environment})}catch(d){throw O.delete(t),d}})();return O.set(t,r),r},ae=async(t)=>{let n=O.get(t);if(n)return n;try{let r=await(await N()).apps.fromName(t,{createIfMissing:!1,environment:l.environment});return O.set(t,Promise.resolve(r)),r}catch(r){if(P(r).code==="not_found")return null;throw r}};async function oe(t){let n=await N();await ae(k);let r=(await Promise.allSettled(O.values())).flatMap((c)=>c.status==="fulfilled"?[c.value]:[]),d=new Map;for(let c of r)for await(let b of n.sandboxes.list({appId:c.appId,tags:t,environment:l.environment}))d.set(b.sandboxId,b);return[...d.values()]}let g=async(t,n)=>{try{return await n()}catch(r){throw P(r,t)}},Pe=(t)=>new e("Sandbox has finished. Modal sandboxes cannot run again once they stop. Create a new sandbox.",{code:"not_found",provider:"modal",sandboxId:t}),Ie=(t)=>{let n=p.get(t);if(!n)throw new e("Sandbox is not attached. No local native object exists. Connect the sandbox first.",{code:"not_found",provider:"modal",sandboxId:t});return n},T=async(t)=>{let n=p.get(t);if(n)return n;let r=await(await N()).sandboxes.fromId(t);return p.set(t,r),r};function z(t,n){let{[V]:r,[Y]:d,[q]:c,...b}=n,v=ye(n)||C.has(t)?"stopped":"running";return{id:t,key:r,labels:b,state:v,createdAt:Number(d)||0}}async function H(t){let[n,r]=await Promise.all([t.poll(),t.getTags()]);if(n!==null)throw Pe(t.sandboxId);let d=r,c=Date.now()+60000;while(d[B]==="pending"){if(Date.now()>=c)throw new e("Sandbox initialization is incomplete. The creator has not finished setup. Retry connection later.",{code:"unavailable",provider:"modal",sandboxId:t.sandboxId,retryable:!0});await Z(250),d=await t.getTags()}return p.set(t.sandboxId,t),h.set(t.sandboxId,d),z(t.sandboxId,d)}async function ke(t){let n=await N(),r;try{r=await n.sandboxes.fromName(k,t,{environment:l.environment})}catch(d){if(P(d).code==="not_found")return!0;throw d}if(!C.has(r.sandboxId)&&!ye(await r.getTags()))return!1;return J(r,Date.now()+60000)}async function se(t,n){let r=await t.exec(["sh","-c",n]);await r.stdin.close();let[d]=await Promise.all([r.wait(),K(r.stdout,()=>{}),K(r.stderr,()=>{})]);return d}async function ie(t,n,r=1,d=()=>!0){for(let c=0;c<r&&d();c++){if(c)await Z(250*c);try{let{[q]:b,...v}=h.get(t.sandboxId)??await t.getTags(),y=n?{...v,[q]:String(Date.now())}:v;return await t.setTags(y),h.set(t.sandboxId,y),!0}catch{}}return!1}async function J(t,n){for(;;){try{let d=await G(t.poll(),n-Date.now());if(d.settled&&d.value!==null)return!0}catch(d){if(P(d).code==="not_found")return!0;throw d}let r=n-Date.now();if(r<=0)return!1;await Z(Math.min(250,r))}}function j(t){p.get(t)?.detach(),p.delete(t),w.delete(t),h.delete(t),C.delete(t)}async function Se(t,n){await se(t,`kill -KILL -${n} 2>/dev/null || true`)}async function Ne(t,n){let r=Date.now(),d=await t.exec(["setsid","--wait","sh","-c",Ke,"sh",n.cwd,`${Math.max(1,Math.ceil(n.timeoutMs))/1000}s`,n.command],{env:n.env}),c,b=()=>{},v=new Promise((M)=>b=M),y=!1,x=!1,L,D=()=>L??=(async()=>{if(await Promise.race([v,new Promise((M)=>setTimeout(M,1e4))]),c!==void 0)await Se(t,c)})(),A=()=>{x=!0,D().catch(()=>{})};n.signal?.addEventListener("abort",A,{once:!0});let E=setTimeout(A,Math.max(0,n.timeoutMs-(Date.now()-r)));if(n.signal?.aborted)A();let S="",F=!1,le=(M)=>{let I=S.indexOf(`
|
|
2
|
+
`);if(!M&&I<0&&S.length<256)return;F=!0;let _=I<0?S:S.slice(0,I),ue=I<0?"":S.slice(I+1);if(_.startsWith(ee)){let Q=Number(_.slice(ee.length));if(Number.isSafeInteger(Q)&&Q>0)c=Q}else if(_===he)y=!0;else{b(),n.onChunk({stream:"stderr",text:S});return}if(b(),ue)n.onChunk({stream:"stderr",text:ue})},X=d.wait(),ce=!1;X.then(()=>ce=!0,()=>{});let _e=async(M)=>{let I;try{return await Promise.race([X.then(()=>!0,()=>!1),new Promise((_)=>I=setTimeout(()=>_(!1),M))])}finally{clearTimeout(I)}},Ee=async()=>{try{if(n.stdin!==void 0)await d.stdin.writeText(n.stdin);await d.stdin.close()}catch(M){if(!Qe(f(M))||!(ce||await _e(1000)))throw P(M,t.sandboxId);d.stdin.close().catch(()=>{})}};try{let M=Ee(),[I]=await Promise.all([X,K(d.stdout,(_)=>n.onChunk({stream:"stdout",text:_})),K(d.stderr,(_)=>{if(F)n.onChunk({stream:"stderr",text:_});else S+=_,le(!1)}),M]);if(!F&&S)le(!0);if(I===137&&Date.now()-r>=n.timeoutMs)x=!0;if(await L,!x&&I===125&&y)throw new e("Command could not start. The working directory does not exist or is not a directory. Check cwd.",{code:"invalid_argument",provider:"modal",sandboxId:t.sandboxId});return{exitCode:x?null:I,timedOut:x}}catch(M){throw await D().catch(()=>{}),M}finally{b(),clearTimeout(E),n.signal?.removeEventListener("abort",A)}}async function Te(t,n){let{timeoutMs:r,signal:d}=n;if(r===void 0&&d===void 0)return t;let c,b=()=>{},v=new Promise((y,x)=>{if(r!==void 0)c=setTimeout(()=>x(new e("Template build timed out. Modal may still finish the image. Retry with a longer timeoutMs.",{code:"timeout",provider:"modal"})),r);if(b=()=>x(new e("Template build aborted. Modal may still finish the image.",{code:"aborted",provider:"modal"})),d?.addEventListener("abort",b,{once:!0}),d?.aborted)b()});try{return await Promise.race([t,v])}finally{clearTimeout(c),d?.removeEventListener("abort",b)}}let de={name:"modal",keyMode:"exact",capabilities:new Set(["snapshot","snapshot-delete","templates","network-policy","size"]),native:Ie,create:(t)=>g(void 0,async()=>{let n={...t.labels,[Y]:String(Date.now())};if(t.key!==void 0)n[V]=t.key;if(Object.keys(n).length+1>Be)R("Modal allows ten tags per sandbox, and the SDK uses up to four of them (sandbox-sdk, sandbox-sdk-created, sandbox-sdk-key, sandbox-sdk-destroying)");if(Ge({...n,[q]:String(Date.now())})>qe)R("Modal allows 1024 bytes of tag names and values per sandbox, key included");let r=[...new Set(t.ports)],d={...Ue(t.size,l.resources),...He(t.network),timeoutMs:be(t.timeoutMs)??ve,idleTimeoutMs:t.idleTimeoutMs===void 0?void 0:te(t.idleTimeoutMs),workdir:"/workspace",env:t.env,encryptedPorts:r.length?r:void 0,regions:Je(l.region),runtime:l.runtime,name:t.key===void 0?void 0:pe(t.key),tags:t.from===void 0?n:{...n,[B]:"pending"}},c=await N(),b=t.from===void 0?Me??=c.images.fromRegistry(l.image??me):await c.images.fromId(t.from),v=await U(t.key===void 0?l.createApp?.({labels:t.labels})??k:k),y;try{y=await c.sandboxes.create(v,b,d)}catch(x){if(d.name===void 0||!await ke(d.name))throw x;y=await c.sandboxes.create(v,b,d)}if(p.set(y.sandboxId,y),w.set(y.sandboxId,new Set(r)),h.set(y.sandboxId,n),t.from===void 0)return z(y.sandboxId,n);try{if(await se(y,We)!==0)throw Error("Could not invalidate restored processes");return await y.setTags(n),z(y.sandboxId,n)}catch(x){throw await de.destroy(y.sandboxId).catch(()=>{}),Ye(x,y.sandboxId)}}),find:(t)=>g(void 0,async()=>{let n;try{n=await(await N()).sandboxes.fromName(k,pe(t),{environment:l.environment})}catch(d){if(P(d).code==="not_found")return;throw d}let r;try{r=await H(n)}catch(d){if(P(d).code==="not_found")return;throw d}if(r.labels[B]!=="1"||r.key!==t||r.state==="stopped")return;return r}),connect:(t)=>g(t,async()=>H(p.get(t)??await(await N()).sandboxes.fromId(t))),list:(t)=>g(void 0,async()=>{let n={...t,[B]:"1"};return(await Promise.all((await oe(n)).map(async(d)=>{try{return await H(d)}catch(c){if(P(c,d.sandboxId).code==="not_found")return;throw c}}))).filter((d)=>d!==void 0&&Object.entries(n).every(([c,b])=>d.labels[c]===b))}),destroy:(t)=>g(t,async()=>{let n=await T(t),r=Date.now(),d=r+ne,c=!1,b=(E)=>new e(`Sandbox termination was requested, but ${E} within ${ne} ms. It stays listed with state "stopped". Call destroy again to keep waiting.`,{code:"timeout",provider:"modal",sandboxId:t,retryable:!0}),v=C.has(t);C.add(t);let y=ie(n,!0,3,()=>!c),x;try{x=await G(n.terminate(),d-Date.now())}catch(E){if(P(E).code==="not_found"){c=!0;try{l.onDestroy?.({sandboxId:t,requestMs:null,stoppedMs:Date.now()-r})}catch{}return j(t)}if(Ze(f(E))){if(c=!0,v)throw E;C.delete(t);let F=await G(y,d-Date.now());if(F.settled&&F.value)await G(ie(n,!1),d-Date.now());throw E}let S=!1;try{S=await J(n,d)}catch{}finally{c=!0}if(!S)throw E;try{l.onDestroy?.({sandboxId:t,requestMs:null,stoppedMs:Date.now()-r})}catch{}return j(t)}if(!x.settled)throw c=!0,b("Modal did not accept the request");let L=Date.now()-r,D;try{D=await J(n,d)}finally{c=!0}let A=D?Date.now()-r:null;try{l.onDestroy?.({sandboxId:t,requestMs:L,stoppedMs:A})}catch{}if(!D)throw b("Modal still reports it running");j(t)}),exec:(t,n)=>g(t,async()=>{if(n.signal?.aborted)return{exitCode:null,timedOut:!0};return Ne(await T(t),n)}),files:{writeCreatesParents:!0,read:(t,n)=>g(t,async()=>new Uint8Array(await(await T(t)).filesystem.readBytes(n))),write:(t,n,r)=>g(t,async()=>{await(await T(t)).filesystem.writeBytes(r,n)}),list:(t,n)=>g(t,async()=>(await(await T(t)).filesystem.listFiles(n)).map(ge)),stat:(t,n)=>g(t,async()=>ge(await(await T(t)).filesystem.stat(n))),remove:(t,n,r)=>g(t,async()=>{await(await T(t)).filesystem.remove(n,{recursive:r.recursive})}),mkdir:(t,n)=>g(t,async()=>{await(await T(t)).filesystem.makeDirectory(n,{createParents:!0})})},previewUrl:(t,n)=>g(t,async()=>{let r=w.get(t),d=()=>new e(`Port ${n} was not declared at creation. Modal tunnels only ports given in CreateInput. Recreate with ports: [${n}].`,{code:"invalid_argument",provider:"modal",sandboxId:t});if(r&&!r.has(n))throw d();let c=(await(await T(t)).tunnels())[n];if(!c)throw d();return{url:c.url}}),close:async(t)=>j(t),snapshot:(t,n={})=>g(t,async()=>{let{expiresInMs:r}=n,d=r===void 0?void 0:r===0?null:te(r);return{id:(await(await T(t)).snapshotFilesystem({ttlMs:d})).imageId}}),deleteSnapshot:(t)=>g(void 0,async()=>{let n=await N();try{await n.images.fromId(t)}catch(r){if(P(r).code==="not_found")return!1;throw r}return await n.images.delete(t),!0}),buildTemplate:(t,n)=>g(void 0,async()=>{if(t.size!==void 0)R("Modal images carry no CPU or memory size. Pass size to createSandbox instead");if(t.workdir!==void 0&&(!t.workdir.startsWith("/")||/[\r\n]/.test(t.workdir)))W("Template workdir must be an absolute path on one line.");let r=[...t.workdir===void 0?[]:[`WORKDIR ${t.workdir}`],...(t.run??[]).map((y)=>`RUN ${JSON.stringify(["sh","-c",y])}`)],c=(await N()).images.fromRegistry(t.image??l.image??me),b=r.length?c.dockerfileCommands(r,{env:t.env}):c;return{id:(await Te(U().then((y)=>b.build(y)),n)).imageId,name:t.name}})};return Object.assign(de,{prepareApp:(t,n={})=>g(void 0,async()=>{if(n.createIfMissing??!0)return{name:t,appId:(await U(t)).appId};if(!fe.test(t))return null;let r=await ae(t);return r&&{name:t,appId:r.appId}}),listPending:(t)=>g(void 0,async()=>{let n={...t,[B]:"pending"};return(await Promise.all((await oe(n)).map(async(d)=>{try{let[c,b]=await Promise.all([d.poll(),d.getTags()]);if(c!==null||!Object.entries(n).every(([D,A])=>b[D]===A))return;let{[V]:v,[Y]:y,[q]:x,...L}=b;return{id:d.sandboxId,labels:L,createdAt:Number(y)||0}}catch(c){if(P(c,d.sandboxId).code==="not_found")return;throw c}}))).filter((d)=>d!==void 0)})})}function pt(s={}){let{tokenId:l,tokenSecret:p,client:w,...h}=s;return xe(async()=>{let{ModalClient:C}=await m("modal","modal",()=>import("modal")),k={...w};if(l!==void 0)k.tokenId=l;if(p!==void 0)k.tokenSecret=p;if(h.environment!==void 0)k.environment=h.environment;return new C(k)},h)}export{pt as modal};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j}from"../../chunk-7rkcx5cx.js";import{u}from"../../chunk-pdgnaxp9.js";import{h}from"../../chunk-qfhee1t8.js";import{n}from"../../chunk-2ts3evzh.js";import{x}from"../../chunk-drhcb2hx.js";import{e,i,d,a}from"../../chunk-0eeyc0aq.js";import{posix as W}from"node:path";var B=new Set;function U(o){B.add(o)}function N(o,I){if(o instanceof e)return o;let E=u(o),{name:R,status:y}=E,b=(A)=>[...B].some((O)=>o instanceof O[A])||R===A,w="provider";if(b("RailwayAuthError")||y===401||y===403)w="auth";else if(b("SandboxFileNotFoundError"))w="file_not_found";else if(b("SandboxNotFoundError")||y===404)w="not_found";else if(b("ExecControlUnsupportedError"))w="unsupported";else if(b("ExecNotStartedError"))w="unavailable";else if(b("ExecInterruptedError")||b("RailwayConnectionError"))w="outcome_unknown";else if(y===429||y===507)w="quota";else if(y!==void 0&&y>=500)w="unavailable";else if(b("SandboxTimeoutError"))w="timeout";else if(R==="AbortError")w="aborted";else if(o instanceof TypeError&&o.message==="fetch failed")w="unavailable";else if(o instanceof TypeError||y===400)w="invalid_argument";let v=w==="auth"?"Check RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID.":"Check the sandbox and Railway service before retrying.",k=i(o,{code:w,known:o instanceof TypeError?!1:void 0,status:y===void 0?void 0:`HTTP ${y}`,redact:d([process.env.RAILWAY_API_TOKEN])});return new e(`Railway request failed: ${a(w,k.detail)}. ${v}`,{code:w,provider:"railway",sandboxId:I,hint:v,retryable:["quota","unavailable"].includes(w),cause:k.cause})}function P(o){throw new e(`${o}. Railway cannot enforce this request. Omit the option or use another provider.`,{code:"unsupported",provider:"railway"})}var M="/tmp/.sandbox-sdk/railway.json",q="SANDBOX_SDK_EXEC_ID",G=(o)=>`for f in $(grep -lzx ${n(`${q}=${o}`)} /proc/[0-9]*/environ 2>/dev/null); do p=\${f#/proc/}; kill -KILL "\${p%/environ}" 2>/dev/null; done; true`;function Y(o){let I=(b)=>{throw new e(`Invalid Railway SDK ${b}`,{code:"not_found",provider:"railway"})},{key:E,labels:R,version:y}=j(o,I);if(y!==1||E===null)I("metadata");return{version:1,key:E,labels:R}}function K(o){return typeof o==="object"&&o!==null&&!(("errors"in o)&&o.errors)&&"data"in o&&typeof o.data==="object"&&o.data!==null&&"sandboxes"in o.data}function H(o){return typeof o==="object"&&o!==null&&"edges"in o&&Array.isArray(o.edges)&&"pageInfo"in o}function V(o){return typeof o==="object"&&o!==null&&"node"in o&&typeof o.node==="object"&&o.node!==null&&"id"in o.node&&typeof o.node.id==="string"}function J(o){return typeof o==="object"&&o!==null&&"hasNextPage"in o&&typeof o.hasNextPage==="boolean"}function Q(o){return"endCursor"in o&&typeof o.endCursor==="string"}function D(o,I){let E=Date.parse(o.createdAt);if(!Number.isFinite(E))throw Error("Invalid Railway creation time");return{id:o.id,key:I.key,labels:I.labels,state:o.status==="RUNNING"?"running":"stopped",createdAt:E}}function z(o,I){let E,R=()=>E??=h("railway","railway",I).then((t)=>(U(t),t)),y=()=>({token:o.token??process.env.RAILWAY_API_TOKEN,environmentId:o.environmentId??process.env.RAILWAY_ENVIRONMENT_ID,authType:o.authType}),b=new Map,w=new Map;async function v(t,r){try{return await r()}catch(s){throw N(s,t)}}async function k(t){let r=b.get(t);if(r)return r;let{Sandbox:s}=await R(),l=await s.connect(t,y());return b.set(t,l),l}async function A(){let t=y();if(!t.token||!t.environmentId)throw new e("Railway credentials are missing. Authentication requires a token and environment ID. Set RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID or pass token and environmentId.",{code:"auth",provider:"railway"});let r=[],s=null;do{let l=await fetch((await R()).DEFAULT_RAILWAY_GRAPHQL_ENDPOINT,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":x,...t.authType==="project-token"?{"Project-Access-Token":t.token}:{Authorization:`Bearer ${t.token}`}},signal:AbortSignal.timeout(30000),body:JSON.stringify({query:"query SandboxSdkRailwayList($environmentId: String!, $after: String) { sandboxes(environmentId: $environmentId, first: 100, after: $after) { edges { node { id } } pageInfo { hasNextPage endCursor } } }",variables:{environmentId:t.environmentId,after:s}})});if(!l.ok)throw Object.assign(Error("Railway list failed"),{status:l.status});let f=await l.json();if(!K(f))throw Error("Invalid Railway list response");let c=f.data.sandboxes;if(!H(c))throw Error("Invalid Railway connection");for(let g of c.edges){if(!V(g))throw Error("Invalid Railway sandbox ID");r.push(g.node.id)}let m=c.pageInfo;if(!J(m))throw Error("Invalid Railway pagination");if(!m.hasNextPage)break;if(!Q(m)||!m.endCursor||m.endCursor===s)throw Error("Missing Railway cursor");s=m.endCursor}while(s!==null);return r}async function O(t,r){try{return(await T(t,{command:G(r),cwd:"/",env:{},timeoutMs:15000,onChunk(){}},!1)).exitCode===0}catch{return!1}}let L=(t)=>new e("Command outcome unknown. Railway did not confirm that the command stopped, and the cleanup command failed. Check the sandbox, or destroy it if the command must not keep running.",{code:"outcome_unknown",provider:"railway",sandboxId:t});async function T(t,r,s=!0){if(r.signal?.aborted)return{exitCode:null,timedOut:!0};let l=await k(t),f=new AbortController,c=()=>f.abort(),m=setTimeout(c,r.timeoutMs);if(r.signal?.addEventListener("abort",c,{once:!0}),r.signal?.aborted)c();let g=crypto.randomUUID();try{let C=l.exec(r.command,{cwd:r.cwd,env:{...r.env,[q]:g},stdin:r.stdin!==void 0,ephemeral:!0,captureOutput:!1,signal:f.signal,onStdout:(p)=>r.onChunk({stream:"stdout",text:p}),onStderr:(p)=>r.onChunk({stream:"stderr",text:p})}),S=Promise.resolve(C);S.catch(()=>{});try{if(r.stdin!==void 0)try{await C.stdin.write(r.stdin),await C.stdin.end()}catch{await S}let p=await S;if(p.timedOut&&p.exitCode===null&&s&&!await O(t,g))throw L(t);return{exitCode:p.timedOut?null:p.exitCode,timedOut:p.timedOut}}catch(p){if(p instanceof e&&p.code==="outcome_unknown")throw p;if(f.signal.aborted){if(await S.catch(()=>{}),p!==f.signal.reason&&s&&!await O(t,g))throw L(t);return{exitCode:null,timedOut:!0}}if(s&&N(p,t).code==="outcome_unknown")await O(t,g);throw p}}finally{clearTimeout(m),r.signal?.removeEventListener("abort",c)}}async function F(t,r){let s="";if((await T(t,{command:`stat -c '%f %s %Y' -- ${n(r)}`,cwd:"/",env:{},timeoutMs:30000,onChunk:(p)=>{if(p.stream==="stdout")s+=p.text}})).exitCode!==0)throw await(await k(t)).files.stat(r),Error("Railway stat command failed");let[f,c,m]=s.trim().split(/\s+/),g=Number.parseInt(f??"",16),C=Number(c),S=Number(m)*1000;if(![g,C,S].every(Number.isFinite))throw Error("Invalid Railway stat output");return{path:r,type:(g&61440)===40960?"symlink":(g&61440)===16384?"directory":"file",size:C,modifiedAt:S}}let _={name:"railway",commandShell:"bash",keyMode:"best-effort",capabilities:new Set(["snapshot"]),create:(t)=>v(void 0,async()=>{if(t.size!==void 0)P("Railway resources set CPU and memory but cannot set diskGb; size presets and exact sizes are unavailable");if(t.network!==void 0&&t.network!=="all")P("Railway isolation modes retain outbound internet access");if(t.timeoutMs!==void 0)P("Railway has no hard sandbox lifetime; idle destruction is not a lifetime limit");if(t.signal?.aborted)throw new e("Creation aborted. The signal was cancelled. Retry with a fresh signal.",{code:"aborted",provider:"railway"});if(t.ports&&(t.ports.length>10||new Set(t.ports).size!==t.ports.length))P("Railway accepts at most 10 unique preview ports");if(t.ports?.length&&o.networkIsolation==="ISOLATED")P("Public domains require PRIVATE networking");if(t.idleTimeoutMs!==void 0&&(!Number.isFinite(t.idleTimeoutMs)||t.idleTimeoutMs<=0))throw new e("Invalid idle timeout. A positive duration is required. Set idleTimeoutMs above zero.",{code:"invalid_argument",provider:"railway"});let{Sandbox:r}=await R(),s={...y(),region:o.region,env:t.env,idleTimeoutMinutes:t.idleTimeoutMs===void 0?void 0:Math.ceil(t.idleTimeoutMs/60000),networkIsolation:t.ports?.length?"PRIVATE":o.networkIsolation,domains:t.ports?.map((m)=>({port:m}))};if(o.resources!==void 0)s.resources=o.resources;let l=t.from??o.checkpoint,f=l??o.template,c;if(l!==void 0)c=await r.create(l,s);else if(o.template!==void 0)c=await r.create(o.template,s);else c=await r.create(s);b.set(c.id,c);try{if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived while provisioning. Retry with a fresh signal.",{code:"aborted",provider:"railway"});let m={version:1,key:t.key,labels:{...t.labels,"sandbox-sdk":"1"}},g=f===void 0?"":'for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/runs; ',C=await T(c.id,{command:`mkdir -p /workspace /tmp/.sandbox-sdk && { ${g}printf %s ${n(JSON.stringify(m))} > ${n(M)}; }`,cwd:"/",env:{},timeoutMs:30000,onChunk(){}});if(C.timedOut||C.exitCode!==0)throw Error("Railway workspace and ownership initialization failed");if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived during initialization. Retry with a fresh signal.",{code:"aborted",provider:"railway"});return w.set(c.id,m),D(c,m)}catch(m){throw await _.destroy(c.id),m}}),connect:(t)=>v(t,async()=>{let{Sandbox:r}=await R(),s=await r.connect(t,y());if(s.status==="DESTROYED"||s.status==="DESTROYING")throw new e(`Railway sandbox ${t} was not found. It has been destroyed.`,{code:"not_found",provider:"railway",sandboxId:t});b.set(t,s);let l=Y(await s.files.read(M));return w.set(t,l),D(s,l)}),find:(t)=>v(void 0,async()=>(await _.list({})).find((r)=>r.key===t)),list:(t)=>v(void 0,async()=>{let r=[];for(let s of await A())try{let{Sandbox:l}=await R(),f=await l.connect(s,y());if(f.status==="DESTROYED"||f.status==="DESTROYING")continue;let c;try{c=Y(await f.files.read(M))}catch(m){if(c=w.get(s),f.status==="RUNNING"&&!c)throw m}if(c&&c.labels["sandbox-sdk"]==="1"&&Object.entries(t).every(([m,g])=>c.labels[m]===g))r.push(D(f,c))}catch(l){if(!["not_found","file_not_found"].includes(N(l,s).code))throw l}return r}),destroy:(t)=>v(t,async()=>{try{await(await k(t)).destroy()}catch(r){if(N(r,t).code!=="not_found")throw r}b.delete(t),w.delete(t)}),close:async(t)=>{b.delete(t)},native(t){let r=b.get(t);if(!r)throw new e("Sandbox client is detached. No cached Railway object exists. Connect first.",{code:"not_found",provider:"railway",sandboxId:t});return r},exec:(t,r)=>v(t,()=>T(t,r)),files:{writeCreatesParents:!0,writeSupportsMode:!0,read:(t,r)=>v(t,async()=>(await k(t)).files.read(r,{format:"bytes"})),readRange:(t,r,s)=>v(t,async()=>s.length===0?new Uint8Array:(await k(t)).files.read(r,{format:"bytes",...s})),write:(t,r,s,l)=>v(t,async()=>{await(await k(t)).files.write(r,s,l?.mode===void 0?void 0:{mode:l.mode})}),mkdir:(t,r)=>v(t,async()=>{await(await k(t)).files.mkdir(r)}),stat:(t,r)=>v(t,()=>F(t,r)),list:(t,r)=>v(t,async()=>{let s=await(await k(t)).files.list(r),l=[];for(let f of s)l.push(await F(t,W.join(r,f.name)));return l}),remove:(t,r,s)=>v(t,async()=>{let l=await k(t);if(!s.recursive){await l.files.remove(r);return}if((await T(t,{command:`rm -rf -- ${n(r)}`,cwd:"/",env:{},timeoutMs:30000,onChunk(){}})).exitCode!==0)throw Error("Railway recursive removal failed")})},previewUrl:(t,r)=>v(t,async()=>{let l=(await k(t)).domains.find((f)=>f.port===r);if(!l)P("The preview port was not declared at creation; pass ports to createSandbox");return{url:`https://${l.domain}`}}),snapshot:(t,r)=>v(t,async()=>{if(r?.expiresInMs)P("Checkpoint expiry is unavailable; Railway keeps checkpoints until you delete them. Omit expiresInMs, or pass 0");return{id:(await(await k(t)).checkpoint(`sandbox-sdk-${crypto.randomUUID()}`)).key}})};return _}function ce(o={}){return z(o,()=>import("railway"))}export{ce as railway};
|
|
1
|
+
import{z}from"../../chunk-adrd5ka7.js";import{f}from"../../chunk-bfvk7mnq.js";import{m}from"../../chunk-n0f7xz7g.js";import{n}from"../../chunk-2ts3evzh.js";import{S}from"../../chunk-h6xh0pr0.js";import{e,i,u,a}from"../../chunk-xx9znywe.js";import{posix as W}from"node:path";var j=new Set;function B(o){j.add(o)}function N(o,R){if(o instanceof e)return o;let k=f(o),{name:E,status:b}=k,h=(A)=>[...j].some((O)=>o instanceof O[A])||E===A,c="provider";if(h("RailwayAuthError")||b===401||b===403)c="auth";else if(h("SandboxFileNotFoundError"))c="file_not_found";else if(h("SandboxNotFoundError")||b===404)c="not_found";else if(h("ExecControlUnsupportedError"))c="unsupported";else if(h("ExecNotStartedError"))c="unavailable";else if(h("ExecInterruptedError")||h("RailwayConnectionError"))c="outcome_unknown";else if(b===429||b===507)c="quota";else if(b!==void 0&&b>=500)c="unavailable";else if(h("SandboxTimeoutError"))c="timeout";else if(E==="AbortError")c="aborted";else if(o instanceof TypeError&&o.message==="fetch failed")c="unavailable";else if(o instanceof TypeError||b===400)c="invalid_argument";let x=c==="auth"?"Check RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID.":"Check the sandbox and Railway service before retrying.",g=i(o,{code:c,known:o instanceof TypeError?!1:void 0,status:b===void 0?void 0:`HTTP ${b}`,redact:u([process.env.RAILWAY_API_TOKEN])});return new e(`Railway request failed: ${a(c,g.detail)}. ${x}`,{code:c,provider:"railway",sandboxId:R,hint:x,retryable:["quota","unavailable"].includes(c),cause:g.cause})}function C(o){throw new e(`${o}. Railway cannot enforce this request. Omit the option or use another provider.`,{code:"unsupported",provider:"railway"})}var M="/tmp/.sandbox-sdk/railway.json",Y="SANDBOX_SDK_EXEC_ID",G=(o)=>`for f in $(grep -lzx ${n(`${Y}=${o}`)} /proc/[0-9]*/environ 2>/dev/null); do p=\${f#/proc/}; kill -KILL "\${p%/environ}" 2>/dev/null; done; true`;function U(o){let R=(h)=>{throw new e(`Invalid Railway SDK ${h}`,{code:"not_found",provider:"railway"})},{key:k,labels:E,version:b}=z(o,R);if(b!==1||k===null)R("metadata");return{version:1,key:k,labels:E}}function K(o){return typeof o==="object"&&o!==null&&!(("errors"in o)&&o.errors)&&"data"in o&&typeof o.data==="object"&&o.data!==null&&"sandboxes"in o.data}function H(o){return typeof o==="object"&&o!==null&&"edges"in o&&Array.isArray(o.edges)&&"pageInfo"in o}function V(o){return typeof o==="object"&&o!==null&&"node"in o&&typeof o.node==="object"&&o.node!==null&&"id"in o.node&&typeof o.node.id==="string"}function J(o){return typeof o==="object"&&o!==null&&"hasNextPage"in o&&typeof o.hasNextPage==="boolean"}function Q(o){return"endCursor"in o&&typeof o.endCursor==="string"}function D(o,R){let k=Date.parse(o.createdAt);if(!Number.isFinite(k))throw Error("Invalid Railway creation time");return{id:o.id,key:R.key,labels:R.labels,state:o.status==="RUNNING"?"running":"stopped",createdAt:k}}function q(o,R){let k,E=()=>k??=m("railway","railway",R).then((t)=>(B(t),t)),b=()=>({token:o.token??process.env.RAILWAY_API_TOKEN,environmentId:o.environmentId??process.env.RAILWAY_ENVIRONMENT_ID,authType:o.authType}),h=new Map,c=new Map;async function x(t,r){try{return await r()}catch(s){throw N(s,t)}}async function g(t){let r=h.get(t);if(r)return r;let{Sandbox:s}=await E(),d=await s.connect(t,b());return h.set(t,d),d}async function A(){let t=b();if(!t.token||!t.environmentId)throw new e("Railway credentials are missing. Authentication requires a token and environment ID. Set RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID or pass token and environmentId.",{code:"auth",provider:"railway"});let r=[],s=null;do{let d=await fetch((await E()).DEFAULT_RAILWAY_GRAPHQL_ENDPOINT,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":S,...t.authType==="project-token"?{"Project-Access-Token":t.token}:{Authorization:`Bearer ${t.token}`}},signal:AbortSignal.timeout(30000),body:JSON.stringify({query:"query SandboxSdkRailwayList($environmentId: String!, $after: String) { sandboxes(environmentId: $environmentId, first: 100, after: $after) { edges { node { id } } pageInfo { hasNextPage endCursor } } }",variables:{environmentId:t.environmentId,after:s}})});if(!d.ok)throw Object.assign(Error("Railway list failed"),{status:d.status});let w=await d.json();if(!K(w))throw Error("Invalid Railway list response");let l=w.data.sandboxes;if(!H(l))throw Error("Invalid Railway connection");for(let v of l.edges){if(!V(v))throw Error("Invalid Railway sandbox ID");r.push(v.node.id)}let p=l.pageInfo;if(!J(p))throw Error("Invalid Railway pagination");if(!p.hasNextPage)break;if(!Q(p)||!p.endCursor||p.endCursor===s)throw Error("Missing Railway cursor");s=p.endCursor}while(s!==null);return r}async function O(t,r){try{return(await T(t,{command:G(r),cwd:"/",env:{},timeoutMs:15000,onChunk(){}},!1)).exitCode===0}catch{return!1}}let L=(t)=>new e("Command outcome unknown. Railway did not confirm that the command stopped, and the cleanup command failed. Check the sandbox, or destroy it if the command must not keep running.",{code:"outcome_unknown",provider:"railway",sandboxId:t});async function T(t,r,s=!0){if(r.signal?.aborted)return{exitCode:null,timedOut:!0};let d=await g(t),w=new AbortController,l=()=>w.abort(),p=setTimeout(l,r.timeoutMs);if(r.signal?.addEventListener("abort",l,{once:!0}),r.signal?.aborted)l();let v=crypto.randomUUID();try{let I=d.exec(r.command,{cwd:r.cwd,env:{...r.env,[Y]:v},stdin:r.stdin!==void 0,ephemeral:!0,captureOutput:!1,signal:w.signal,onStdout:(y)=>r.onChunk({stream:"stdout",text:y}),onStderr:(y)=>r.onChunk({stream:"stderr",text:y})}),P=Promise.resolve(I);P.catch(()=>{});try{if(r.stdin!==void 0)try{await I.stdin.write(r.stdin),await I.stdin.end()}catch{await P}let y=await P;if(y.timedOut&&y.exitCode===null&&s&&!await O(t,v))throw L(t);return{exitCode:y.timedOut?null:y.exitCode,timedOut:y.timedOut}}catch(y){if(y instanceof e&&y.code==="outcome_unknown")throw y;if(w.signal.aborted){if(await P.catch(()=>{}),y!==w.signal.reason&&s&&!await O(t,v))throw L(t);return{exitCode:null,timedOut:!0}}if(s&&N(y,t).code==="outcome_unknown")await O(t,v);throw y}}finally{clearTimeout(p),r.signal?.removeEventListener("abort",l)}}async function F(t,r){let s="";if((await T(t,{command:`stat -c '%f %s %Y' -- ${n(r)}`,cwd:"/",env:{},timeoutMs:30000,onChunk:(y)=>{if(y.stream==="stdout")s+=y.text}})).exitCode!==0)throw await(await g(t)).files.stat(r),Error("Railway stat command failed");let[w,l,p]=s.trim().split(/\s+/),v=Number.parseInt(w??"",16),I=Number(l),P=Number(p)*1000;if(![v,I,P].every(Number.isFinite))throw Error("Invalid Railway stat output");return{path:r,type:(v&61440)===40960?"symlink":(v&61440)===16384?"directory":"file",size:I,modifiedAt:P}}let _={name:"railway",commandShell:"bash",keyMode:"best-effort",capabilities:new Set(["snapshot"]),create:(t)=>x(void 0,async()=>{if(t.size!==void 0)C("Railway resources set CPU and memory but cannot set diskGb; size presets and exact sizes are unavailable");if(t.network!==void 0&&t.network!=="all")C("Railway isolation modes retain outbound internet access");if(t.timeoutMs!==void 0)C("Railway has no hard sandbox lifetime; idle destruction is not a lifetime limit");if(t.signal?.aborted)throw new e("Creation aborted. The signal was cancelled. Retry with a fresh signal.",{code:"aborted",provider:"railway"});if(t.ports&&(t.ports.length>10||new Set(t.ports).size!==t.ports.length))C("Railway accepts at most 10 unique preview ports");if(t.ports?.length&&o.networkIsolation==="ISOLATED")C("Public domains require PRIVATE networking");if(t.idleTimeoutMs!==void 0&&(!Number.isFinite(t.idleTimeoutMs)||t.idleTimeoutMs<=0))throw new e("Invalid idle timeout. A positive duration is required. Set idleTimeoutMs above zero.",{code:"invalid_argument",provider:"railway"});let{Sandbox:r}=await E(),s={...b(),region:o.region,env:t.env,idleTimeoutMinutes:t.idleTimeoutMs===void 0?void 0:Math.ceil(t.idleTimeoutMs/60000),networkIsolation:t.ports?.length?"PRIVATE":o.networkIsolation,domains:t.ports?.map((p)=>({port:p}))};if(o.resources!==void 0)s.resources=o.resources;let d=t.from??o.checkpoint,w=d??o.template,l;if(d!==void 0)l=await r.create(d,s);else if(o.template!==void 0)l=await r.create(o.template,s);else l=await r.create(s);h.set(l.id,l);try{if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived while provisioning. Retry with a fresh signal.",{code:"aborted",provider:"railway"});let p={version:1,key:t.key,labels:{...t.labels,"sandbox-sdk":"1"}},v=w===void 0?"":'for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/runs; ',I=await T(l.id,{command:`mkdir -p /workspace /tmp/.sandbox-sdk && { ${v}printf %s ${n(JSON.stringify(p))} > ${n(M)}; }`,cwd:"/",env:{},timeoutMs:30000,onChunk(){}});if(I.timedOut||I.exitCode!==0)throw Error("Railway workspace and ownership initialization failed");if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived during initialization. Retry with a fresh signal.",{code:"aborted",provider:"railway"});return c.set(l.id,p),D(l,p)}catch(p){throw await _.destroy(l.id),p}}),connect:(t)=>x(t,async()=>{let{Sandbox:r}=await E(),s=await r.connect(t,b());if(s.status==="DESTROYED"||s.status==="DESTROYING")throw new e(`Railway sandbox ${t} was not found. It has been destroyed.`,{code:"not_found",provider:"railway",sandboxId:t});h.set(t,s);let d=U(await s.files.read(M));return c.set(t,d),D(s,d)}),find:(t)=>x(void 0,async()=>(await _.list({})).find((r)=>r.key===t)),list:(t)=>x(void 0,async()=>{let r=[];for(let s of await A())try{let{Sandbox:d}=await E(),w=await d.connect(s,b());if(w.status==="DESTROYED"||w.status==="DESTROYING")continue;let l;try{l=U(await w.files.read(M))}catch(p){if(l=c.get(s),w.status==="RUNNING"&&!l)throw p}if(l&&l.labels["sandbox-sdk"]==="1"&&Object.entries(t).every(([p,v])=>l.labels[p]===v))r.push(D(w,l))}catch(d){if(!["not_found","file_not_found"].includes(N(d,s).code))throw d}return r}),destroy:(t)=>x(t,async()=>{try{await(await g(t)).destroy()}catch(r){if(N(r,t).code!=="not_found")throw r}h.delete(t),c.delete(t)}),close:async(t)=>{h.delete(t)},native(t){let r=h.get(t);if(!r)throw new e("Sandbox client is detached. No cached Railway object exists. Connect first.",{code:"not_found",provider:"railway",sandboxId:t});return r},exec:(t,r)=>x(t,()=>T(t,r)),files:{writeCreatesParents:!0,writeSupportsMode:!0,read:(t,r)=>x(t,async()=>(await g(t)).files.read(r,{format:"bytes"})),readRange:(t,r,s)=>x(t,async()=>s.length===0?new Uint8Array:(await g(t)).files.read(r,{format:"bytes",...s})),write:(t,r,s,d)=>x(t,async()=>{await(await g(t)).files.write(r,s,d?.mode===void 0?void 0:{mode:d.mode})}),mkdir:(t,r)=>x(t,async()=>{await(await g(t)).files.mkdir(r)}),stat:(t,r)=>x(t,()=>F(t,r)),list:(t,r)=>x(t,async()=>{let s=await(await g(t)).files.list(r),d=[];for(let w of s)d.push(await F(t,W.join(r,w.name)));return d}),remove:(t,r,s)=>x(t,async()=>{let d=await g(t);if(!s.recursive){await d.files.remove(r);return}if((await T(t,{command:`rm -rf -- ${n(r)}`,cwd:"/",env:{},timeoutMs:30000,onChunk(){}})).exitCode!==0)throw Error("Railway recursive removal failed")})},previewUrl:(t,r)=>x(t,async()=>{let d=(await g(t)).domains.find((w)=>w.port===r);if(!d)C("The preview port was not declared at creation; pass ports to createSandbox");return{url:`https://${d.domain}`}}),snapshot:(t,r)=>x(t,async()=>{if(r?.expiresInMs)C("Checkpoint expiry is unavailable; Railway keeps checkpoints until you delete them. Omit expiresInMs, or pass 0");return{id:(await(await g(t)).checkpoint(`sandbox-sdk-${crypto.randomUUID()}`)).key}})};return _}function ce(o={}){return q(o,()=>import("railway"))}export{ce as railway};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-
|
|
1
|
+
import"../../chunk-zygv9qfq.js";import{K,Q}from"../../chunk-qdc1zgmf.js";import{h,y}from"../../chunk-kq1xms6a.js";import{t,r}from"../../chunk-xx9znywe.js";var w=["requested","nearest","default","source"],{failure:i,boatError:v}=K("sandboxer","Sandboxer","SANDBOXER_API_KEY",!0),k="https://sandboxer.com/api/v1",g="X-Sandboxer-Confirm-Delete";function R(u={}){let S=u.requestTimeoutMs??90000,l=new Map,d=u.region??process.env.SANDBOXER_REGION;if(d!==void 0&&!/^[a-z][a-z0-9-]{0,31}$/.test(d))throw i("Invalid Sandboxer region","invalid_argument");let x=new Map;function I(n){if(!("id"in n)||!t(n.id)||!("region"in n))return;let e=t(n.region)?n.region:null,o="regionSource"in n?w.find((a)=>a===n.regionSource)??null:null;x.set(n.id,{region:e,regionSource:o})}async function p(n,e,o){let a=h(S);for(;;){if(o(await c.json({method:"GET",path:n,params:e,deadline:a})))return;if(a.remaining()<=0)break;try{await y(Math.min(250,a.remaining()),a,"sandboxer")}catch{break}}throw i("Sandboxer operation did not finish before its deadline","timeout")}async function m(n,e){if(!/^[a-z0-9][a-z0-9-]{0,62}$/.test(e))throw i("Invalid snapshot name","invalid_argument",n);try{return await c.json({method:"POST",path:"/named-snapshots",body:{sandboxId:n,name:e},sandboxId:n}),await p("/named-snapshots/{name}",{name:e},(o)=>{if(!r(o)||o===null||!("snapshot"in o))throw i("Invalid snapshot response");let a=o.snapshot;if(!r(a)||a===null||!("status"in a)||!("name"in a)||a.name!==e||!("sourceSandboxId"in a)||a.sourceSandboxId!==n)throw i("Invalid snapshot metadata");if(a.status==="failed")throw i("Sandboxer snapshot failed","provider",n);return a.status==="ready"}),{id:e}}catch(o){throw i(`Sandboxer snapshot ${e} did not complete; inspect this name before retrying`,v(o,n).code,n)}}let{provider:b,http:c}=Q(u,{name:"sandboxer",label:"Sandboxer",keyEnv:"SANDBOXER_API_KEY",baseUrl:k,createFrom:!0,idleStop:!0,pausedStates:["archived","stopped"],createFields:d===void 0?void 0:{region:d},observe:(n)=>I(n.raw),downloadMaxBytes:52428800,destroy:async(n,e)=>{let o=l.get(e);if(!o){let a=await n.json({method:"DELETE",path:"/sandboxes/{sandboxId}",params:{sandboxId:e},sandboxId:e,headers:{[g]:e,"X-Ascii-Confirm-Delete":e}}),s=r(a)&&"operation"in a?a.operation:void 0;if(!r(s)||s===null||!("targetId"in s)||s.targetId!==e||!("kind"in s)||s.kind!=="sandbox"||!("status"in s))throw i("Invalid deletion operation","outcome_unknown",e);if(s.status==="completed")return;if(!("id"in s)||!t(s.id)||!s.id)throw i("Invalid deletion operation","outcome_unknown",e);o=s.id,l.set(e,o)}await p("/deletion-operations/{operationId}",{operationId:o},(a)=>{if(!r(a)||a===null||!("operation"in a))throw i("Invalid deletion response");let s=a.operation;if(!r(s)||s===null||!("targetId"in s)||s.targetId!==e||!("status"in s))throw i("Invalid deletion metadata");return s.status==="completed"}),l.delete(e)},download:async(n,e,o)=>(await n.request({method:"GET",path:"/sandboxes/{sandboxId}/artifacts",params:{sandboxId:e},query:{path:o},sandboxId:e,maxBytes:52428801})).body,preview:async(n)=>{let e=new URL(n),o=e.searchParams.get("_token");if(o===null)return{url:n};if(!/^[A-Za-z0-9._~-]+$/.test(o))throw i("Invalid preview token");return e.searchParams.delete("_token"),{url:e.toString(),headers:{Cookie:`__sbx_auth=${o}`}}},sdkConfiguration:{middleware:[{async pre({url:n,init:e}){let o=new URL(n).pathname;if(e.method!=="DELETE"||!/\/sandboxes\/[^/]+$/.test(o))return;let a=new Headers(e.headers);return a.set(g,decodeURIComponent(o.slice(o.lastIndexOf("/")+1))),{url:n,init:{...e,headers:a}}}}]}}),f=(n,e)=>({method:"POST",path:`/sandboxes/{sandboxId}/${e}`,params:{sandboxId:n},sandboxId:n});return{...b,capabilities:new Set(["size","pause","snapshot"]),async pause(n){await c.json(f(n,"stop")),await p("/sandboxes/{sandboxId}",{sandboxId:n},(e)=>{if(!r(e)||e===null||!("sandbox"in e))throw i("Invalid stop response");let o=e.sandbox;if(!r(o)||o===null||!("id"in o)||o.id!==n||!("stop"in o))throw i("Invalid stop metadata");let a=o.stop;if(!r(a)||a===null||!("status"in a))return!1;return a.status==="completed"})},async resume(n){await c.json(f(n,"resume")),await p("/sandboxes/{sandboxId}",{sandboxId:n},(e)=>{if(!r(e)||e===null||!("sandbox"in e))throw i("Invalid resume response");let o=e.sandbox;if(!r(o)||o===null||!("id"in o)||o.id!==n||!("state"in o))throw i("Invalid resume metadata");return o.state==="ready"}),await b.connect(n)},async snapshot(n,e={}){if(e.expiresInMs!==void 0&&e.expiresInMs!==0)throw i("Sandboxer named snapshots never expire; expiresInMs is unsupported. Delete the snapshot yourself","unsupported",n);return m(n,`sdk-${crypto.randomUUID()}`)},native:(n)=>Object.assign(b.native(n),{region:null,regionSource:null,...x.get(n),createSnapshot:(e)=>m(n,e)})}}export{R as sandboxer};
|