eve 0.46.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/src/channel/schedule.d.ts +1 -0
  3. package/dist/src/channel/schedule.js +1 -1
  4. package/dist/src/compiled/.vendor-stamp.json +2 -1
  5. package/dist/src/compiled/@vercel/sandbox/index.js +9 -15
  6. package/dist/src/compiled/@vercel/sandbox-delete/LICENSE +201 -0
  7. package/dist/src/compiled/@vercel/sandbox-delete/_async-retry.d.ts +8 -0
  8. package/dist/src/compiled/@vercel/sandbox-delete/_workflow-serde.d.ts +5 -0
  9. package/dist/src/compiled/@vercel/sandbox-delete/api-client/api-client.d.ts +1730 -0
  10. package/dist/src/compiled/@vercel/sandbox-delete/api-client/api-error.d.ts +29 -0
  11. package/dist/src/compiled/@vercel/sandbox-delete/api-client/base-client.d.ts +39 -0
  12. package/dist/src/compiled/@vercel/sandbox-delete/api-client/file-writer.d.ts +66 -0
  13. package/dist/src/compiled/@vercel/sandbox-delete/api-client/index.d.ts +2 -0
  14. package/dist/src/compiled/@vercel/sandbox-delete/api-client/validators.d.ts +907 -0
  15. package/dist/src/compiled/@vercel/sandbox-delete/api-client/with-retry.d.ts +10 -0
  16. package/dist/src/compiled/@vercel/sandbox-delete/auth/error.d.ts +15 -0
  17. package/dist/src/compiled/@vercel/sandbox-delete/auth/file.d.ts +18 -0
  18. package/dist/src/compiled/@vercel/sandbox-delete/auth/index.d.ts +6 -0
  19. package/dist/src/compiled/@vercel/sandbox-delete/auth/oauth.d.ts +111 -0
  20. package/dist/src/compiled/@vercel/sandbox-delete/auth/poll-for-token.d.ts +28 -0
  21. package/dist/src/compiled/@vercel/sandbox-delete/auth/project.d.ts +40 -0
  22. package/dist/src/compiled/@vercel/sandbox-delete/command.d.ts +292 -0
  23. package/dist/src/compiled/@vercel/sandbox-delete/constants.d.ts +15 -0
  24. package/dist/src/compiled/@vercel/sandbox-delete/execution-context.d.ts +116 -0
  25. package/dist/src/compiled/@vercel/sandbox-delete/filesystem.d.ts +258 -0
  26. package/dist/src/compiled/@vercel/sandbox-delete/index.d.ts +13 -0
  27. package/dist/src/compiled/@vercel/sandbox-delete/index.js +9 -0
  28. package/dist/src/compiled/@vercel/sandbox-delete/network-policy.d.ts +169 -0
  29. package/dist/src/compiled/@vercel/sandbox-delete/proxy.d.ts +55 -0
  30. package/dist/src/compiled/@vercel/sandbox-delete/sandbox-user.d.ts +211 -0
  31. package/dist/src/compiled/@vercel/sandbox-delete/sandbox.d.ts +1258 -0
  32. package/dist/src/compiled/@vercel/sandbox-delete/session.d.ts +435 -0
  33. package/dist/src/compiled/@vercel/sandbox-delete/snapshot.d.ts +238 -0
  34. package/dist/src/compiled/@vercel/sandbox-delete/utils/get-credentials.d.ts +21 -0
  35. package/dist/src/compiled/@vercel/sandbox-delete/utils/paginator.d.ts +16 -0
  36. package/dist/src/compiled/@vercel/sandbox-delete/utils/resolveSignal.d.ts +15 -0
  37. package/dist/src/compiled/@vercel/sandbox-delete/utils/sandbox-snapshot.d.ts +11 -0
  38. package/dist/src/compiled/@vercel/sandbox-delete/utils/types.d.ts +11 -0
  39. package/dist/src/compiled/_chunks/node/auth-DpzFWvTn.js +2 -0
  40. package/dist/src/compiled/_chunks/node/auth-QgeX8nBM.js +2 -0
  41. package/dist/src/compiled/_chunks/node/decode_jwt-Col8JOnf.js +7 -0
  42. package/dist/src/compiled/_chunks/node/version-DH6yRy-M.js +1 -0
  43. package/dist/src/compiled/_chunks/node/xdg-app-paths-Bys8q02u.js +1 -0
  44. package/dist/src/compiler/extension-compatibility.d.ts +12 -12
  45. package/dist/src/compiler/extension-compatibility.js +1 -1
  46. package/dist/src/compiler/model-catalog.js +1 -1
  47. package/dist/src/context/build-callback-context.js +1 -1
  48. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  49. package/dist/src/context/keys.d.ts +2 -0
  50. package/dist/src/context/keys.js +1 -1
  51. package/dist/src/context/memory-tools.js +1 -1
  52. package/dist/src/context/providers/sandbox.js +1 -1
  53. package/dist/src/evals/context.js +1 -1
  54. package/dist/src/evals/session-content.d.ts +5 -0
  55. package/dist/src/evals/session-content.js +3 -0
  56. package/dist/src/evals/session.d.ts +1 -0
  57. package/dist/src/evals/session.js +1 -1
  58. package/dist/src/evals/types.d.ts +5 -0
  59. package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -1
  60. package/dist/src/execution/eve-workflow-attributes.d.ts +3 -0
  61. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  62. package/dist/src/execution/runtime-context.js +1 -1
  63. package/dist/src/execution/sandbox/bindings/docker-base-setup.d.ts +4 -4
  64. package/dist/src/execution/sandbox/bindings/docker-base-setup.js +1 -1
  65. package/dist/src/execution/sandbox/bindings/docker-session.d.ts +1 -1
  66. package/dist/src/execution/sandbox/bindings/docker-session.js +1 -1
  67. package/dist/src/execution/sandbox/bindings/docker.js +1 -1
  68. package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
  69. package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +1 -1
  70. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
  71. package/dist/src/execution/sandbox/bindings/vercel-base-runtime.d.ts +4 -0
  72. package/dist/src/execution/sandbox/bindings/vercel-base-runtime.js +2 -2
  73. package/dist/src/execution/sandbox/bindings/vercel-lifecycle.d.ts +8 -0
  74. package/dist/src/execution/sandbox/bindings/vercel-lifecycle.js +1 -0
  75. package/dist/src/execution/sandbox/bindings/vercel-sdk-types.d.ts +3 -0
  76. package/dist/src/execution/sandbox/bindings/vercel.d.ts +2 -1
  77. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  78. package/dist/src/execution/sandbox/ensure.d.ts +2 -0
  79. package/dist/src/execution/sandbox/ensure.js +1 -1
  80. package/dist/src/execution/sandbox/require-sandbox.js +1 -1
  81. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  82. package/dist/src/execution/tools/connection-search.js +2 -2
  83. package/dist/src/execution/tools/file-state.js +1 -1
  84. package/dist/src/execution/tools/load-skill.js +1 -1
  85. package/dist/src/execution/tools/subagent/local.js +1 -1
  86. package/dist/src/execution/workflow-steps.js +1 -1
  87. package/dist/src/harness/approval-delivery-coordinator.js +1 -1
  88. package/dist/src/harness/attachment-staging.js +1 -1
  89. package/dist/src/harness/authorization.js +1 -1
  90. package/dist/src/harness/current-messages.d.ts +15 -0
  91. package/dist/src/harness/current-messages.js +1 -0
  92. package/dist/src/harness/instrumentation/runtime-context.js +1 -1
  93. package/dist/src/harness/instrumentation/state.js +1 -1
  94. package/dist/src/harness/step-hooks.js +1 -1
  95. package/dist/src/harness/tool-loop.js +2 -2
  96. package/dist/src/harness/tools.js +1 -1
  97. package/dist/src/internal/application/package.js +1 -1
  98. package/dist/src/internal/model-catalog.js +1 -1
  99. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  100. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
  101. package/dist/src/public/definitions/sandbox-backend.d.ts +1 -1
  102. package/dist/src/public/sandbox/index.d.ts +1 -1
  103. package/dist/src/runtime/agent/resolve-model.js +1 -1
  104. package/dist/src/runtime/connections/principal.js +1 -1
  105. package/dist/src/sandbox/state.d.ts +2 -0
  106. package/dist/src/setup/scaffold/create/project.js +1 -1
  107. package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
  108. package/dist/src/setup/scaffold/create/web-template.js +4 -2
  109. package/dist/src/shared/sandbox-backend.d.ts +9 -0
  110. package/dist/src/shared/sandbox-definition.d.ts +5 -4
  111. package/dist/src/shared/sandbox-session.d.ts +4 -1
  112. package/dist/src/tasks/delivery-policy.d.ts +12 -0
  113. package/dist/src/tasks/delivery-policy.js +1 -0
  114. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  115. package/docs/evals/cases.mdx +11 -2
  116. package/docs/evals/judge.mdx +15 -0
  117. package/docs/evals/overview.mdx +2 -2
  118. package/docs/guides/instrumentation.md +1 -0
  119. package/docs/guides/session-context.md +2 -2
  120. package/docs/sandbox.mdx +25 -2
  121. package/docs/schedules.mdx +2 -0
  122. package/docs/tools/overview.mdx +2 -0
  123. package/package.json +2 -1
  124. package/dist/src/compiled/_chunks/node/auth-BaNbsImr.js +0 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # eve
2
2
 
3
+ ## 0.47.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 52e89ef: Add `delete()` to the runtime sandbox handle for permanently deleting the current session sandbox and reprovisioning it on the next access. Docker handles stay bound to one physical container, and sandbox `onSession` callbacks now receive session metadata through `ctx` while using `use()` for sandbox access.
8
+
9
+ ### Patch Changes
10
+
11
+ - a3b23c0: Eval contexts and sessions now expose a formatted `transcript` of observed user and assistant messages, which can be passed directly to an LLM judge for multi-turn conversation grading.
12
+ - 56514d9: Models with slug ending in `-thinking` are now resolved to the
13
+ correct model instead of failing with `does not have known AI Gateway context window metadata` error or silently using the base model's context window.
14
+ - 41c8286: Restore Bash process substitution in Vercel sandboxes by providing the standard `/dev/fd` path whenever eve creates or resumes a sandbox session.
15
+ - bdb3973: Preserve schedule provenance when a handler starts a session with user credentials. Scheduled background-task launches now stay silent instead of sending a launch acknowledgement, and schedule-created workflow runs expose `$eve.schedule` for attribution.
16
+ - fccbf2b: Fix a TypeScript error in the generated Web Chat `tool.tsx` where `trimEnd` was called on `string | number` values returned by the tool output helper.
17
+
3
18
  ## 0.46.1
4
19
 
5
20
  ### Patch Changes
@@ -52,6 +52,7 @@ export declare class ScheduleDispatcher {
52
52
  readonly channels: readonly ResolvedChannelDefinition[];
53
53
  });
54
54
  trigger(input: ScheduleDispatchInput): Promise<ScheduleDispatchResult>;
55
+ private triggerInScope;
55
56
  private runMarkdown;
56
57
  }
57
58
  /**
@@ -1 +1 @@
1
- import{createSession}from"#channel/session.js";import{SCHEDULE_APP_AUTH,SCHEDULE_APP_AUTH as SCHEDULE_APP_AUTH$1}from"#channel/schedule-auth.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{expectFunction}from"#internal/authored-module.js";const SCHEDULE_ADAPTER_KIND=`schedule`,SCHEDULE_ADAPTER={kind:SCHEDULE_ADAPTER_KIND};var ScheduleDispatcher=class{runtime;channels;constructor(e){this.runtime=e.runtime,this.channels=e.channels}async trigger(e){let t=[],a=[],o=createCrossChannelToFn(this.runtime,toCrossChannelTargets(this.channels)),s={appAuth:SCHEDULE_APP_AUTH$1,to(e,n){let r=o(e,n);return{async send(e,n){let i=await r.send(e,n);return t.push(i),i}}},waitUntil(e){a.push(e)}};if(e.run)await e.run(s);else if(e.markdown!==void 0){let n=await this.runMarkdown(e.markdown);t.push(n)}else throw Error(`Schedule "${e.scheduleId}" has neither "run" nor "markdown" — at least one must be set.`);return{sessions:t,waitUntilTasks:a}}async runMarkdown(t){return createSession((await this.runtime.createSession({adapter:SCHEDULE_ADAPTER,auth:SCHEDULE_APP_AUTH$1,input:{message:t},mode:`task`})).sessionId,this.runtime)}};function expectScheduleRun(e,t,n){let r=e;if(typeof r!=`object`||!r)throw Error(`Schedule export "${n??`default`}" from "${t}" must be an object.`);return expectFunction(r.run,`Expected the schedule export "${n??`default`}" from "${t}" to export a \`run\` handler function.`)}export{SCHEDULE_ADAPTER,SCHEDULE_ADAPTER_KIND,SCHEDULE_APP_AUTH,ScheduleDispatcher,expectScheduleRun};
1
+ import{createSession}from"#channel/session.js";import{SCHEDULE_APP_AUTH,SCHEDULE_APP_AUTH as SCHEDULE_APP_AUTH$1}from"#channel/schedule-auth.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{ContextContainer,contextStorage}from"#context/container.js";import{ScheduleIdKey}from"#context/keys.js";import{expectFunction}from"#internal/authored-module.js";const SCHEDULE_ADAPTER_KIND=`schedule`,SCHEDULE_ADAPTER={kind:SCHEDULE_ADAPTER_KIND};var ScheduleDispatcher=class{runtime;channels;constructor(e){this.runtime=e.runtime,this.channels=e.channels}async trigger(e){let t=new ContextContainer;return t.set(ScheduleIdKey,e.scheduleId),await contextStorage.run(t,()=>this.triggerInScope(e))}async triggerInScope(e){let t=[],a=[],o=createCrossChannelToFn(this.runtime,toCrossChannelTargets(this.channels)),s={appAuth:SCHEDULE_APP_AUTH$1,to(e,n){let r=o(e,n);return{async send(e,n){let i=await r.send(e,n);return t.push(i),i}}},waitUntil(e){a.push(e)}};if(e.run)await e.run(s);else if(e.markdown!==void 0){let n=await this.runMarkdown(e.markdown);t.push(n)}else throw Error(`Schedule "${e.scheduleId}" has neither "run" nor "markdown" — at least one must be set.`);return{sessions:t,waitUntilTasks:a}}async runMarkdown(t){return createSession((await this.runtime.createSession({adapter:SCHEDULE_ADAPTER,auth:SCHEDULE_APP_AUTH$1,input:{message:t},mode:`task`})).sessionId,this.runtime)}};function expectScheduleRun(e,t,n){let r=e;if(typeof r!=`object`||!r)throw Error(`Schedule export "${n??`default`}" from "${t}" must be an object.`);return expectFunction(r.run,`Expected the schedule export "${n??`default`}" from "${t}" to export a \`run\` handler function.`)}export{SCHEDULE_ADAPTER,SCHEDULE_ADAPTER_KIND,SCHEDULE_APP_AUTH,ScheduleDispatcher,expectScheduleRun};
@@ -37,6 +37,7 @@
37
37
  "@vercel/oidc": "3.8.0",
38
38
  "@vercel/otel": "2.1.3",
39
39
  "@vercel/sandbox-drives": "2.10.0-beta.0",
40
+ "@vercel/sandbox-delete": "3.2.0",
40
41
  "@vercel/sandbox": "2.8.0",
41
42
  "@workflow/core": "5.0.0-beta.43",
42
43
  "@workflow/errors": "5.0.0-beta.17",
@@ -47,7 +48,7 @@
47
48
  "zod": "4.4.3",
48
49
  "zod-validation-error": "5.0.0"
49
50
  },
50
- "scriptHash": "c2549e7c825b1fee74b0de1d2e796161ab02867c3f9c486d9d32c8723c42b605",
51
+ "scriptHash": "f109bdb0f7d441a9dc84e80c154bd0283c21de90d87d251a337773c2020680ca",
51
52
  "toolVersions": {
52
53
  "rolldown": "1.1.5"
53
54
  }
@@ -1,15 +1,9 @@
1
- import{i as e,o as t,t as n}from"../../_chunks/node/rolldown-runtime-DaDcL9Zw.js";import{n as r,t as i}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as a,t as o}from"../../_chunks/node/retry-qwFNGj4P.js";import{At as s,Bt as c,Et as l,Nn as u,Rn as d,Tn as f,Tt as p,Xn as m,dn as h,wn as g,yt as _}from"../../_chunks/node/schemas-DtQwuPdM.js";import{t as v}from"../../_chunks/node/undici-CUIybhQ2.js";import{t as y}from"../../_chunks/node/version-BYHw-SDY.js";import{n as b,r as x,t as S}from"../../_chunks/node/token-util-Ldar52H7.js";import{Readable as C}from"stream";import w,{dirname as ee,resolve as te}from"path";import{createWriteStream as T}from"fs";import ne from"zlib";import re from"os";import{pipeline as E}from"stream/promises";import{mkdir as ie}from"fs/promises";import*as ae from"node:constants";import{setTimeout as oe}from"node:timers/promises";var D=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},O=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function se(e){return e==null?[]:Array.isArray(e)?e:[e]}var ce=t(n(((e,t)=>{var n=o();function r(e,t){function r(r,i){var a=t||{},o;`randomize`in a||(a.randomize=!0),o=n.operation(a);function s(e){i(e||Error(`Aborted`))}function c(e,t){if(e.bail){s(e);return}o.retry(e)?a.onRetry&&a.onRetry(e,t):i(o.mainError())}function l(t){var n;try{n=e(s,t)}catch(e){c(e,t);return}Promise.resolve(n).then(r).catch(function(e){c(e,t)})}o.attempt(l)}return new Promise(r)}t.exports=r}))(),1);function le(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,ce.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new D(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await ue(e*1e3,n.signal),new D(o)}if(o.status>=500&&o.status<600)throw new D(o);return o}catch(e){if(de(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof D)return e.response;throw e}}}async function ue(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function de(e){return e!=null&&e.name===`AbortError`}const fe=new(v()).Agent({bodyTimeout:0});var pe=class{constructor(e){this.fetch=le(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=fe}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))se(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function me(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function he(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}async function ge(e,t){let n=me(t.url),r;n||(r=he(t.url));let i=await t.text().catch(e=>new D(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new D(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok)return new D(t,{message:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r});let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new D(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function k(e,t){let n=await ge(e,t);if(n instanceof D)throw n;return n}const _e=f({exact:d().optional(),startsWith:d().optional(),regex:d().optional()}),ve=f({key:_e.optional(),value:_e.optional()}),ye=f({path:_e.optional(),method:l(d()).optional(),queryString:l(ve).optional(),headers:l(ve).optional()}),be=f({domain:d(),headers:u(d(),d()).optional(),headerNames:l(d()).optional(),match:ye.optional()}),xe=f({domain:d(),forwardURL:d(),match:ye.optional()}),Se=f({headers:u(d(),d()).optional()}),Ce=f({match:ye.optional(),transform:l(Se).optional(),forwardURL:d().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),we=f({allow:m([l(d()),u(d(),l(Ce))]).optional(),subnets:f({allow:l(d()).optional(),deny:l(d()).optional()}).optional()}),Te=m([f({mode:h(`allow-all`)}).passthrough(),f({mode:h(`deny-all`)}).passthrough()]),Ee=f({mode:h(`custom`),allowedDomains:l(d()).optional(),allowedCIDRs:l(d()).optional(),deniedCIDRs:l(d()).optional(),injectionRules:l(be).optional(),forwardRules:l(xe).optional()}).passthrough(),De=m([Te,we.passthrough()]),Oe=m([Te,Ee]),A=f({id:d(),memory:g(),vcpus:g(),region:d(),runtime:d(),timeout:g(),status:_([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:g(),startedAt:g().optional(),requestedStopAt:g().optional(),stoppedAt:g().optional(),abortedAt:g().optional(),duration:g().optional(),sourceSnapshotId:d().optional(),snapshottedAt:g().optional(),createdAt:g(),cwd:d(),updatedAt:g(),interactivePort:g().optional(),networkPolicy:Oe.optional(),activeCpuDurationMs:g().optional(),networkTransfer:f({ingress:g(),egress:g()}).optional()}),ke=f({url:d(),subdomain:d(),port:g()}),j=f({id:d(),sourceSessionId:d(),region:d(),status:_([`created`,`deleted`,`failed`]),sizeBytes:g(),expiresAt:g().optional(),createdAt:g(),updatedAt:g(),lastUsedAt:g().optional(),creationMethod:d().optional(),parentId:d().optional()}),M=f({count:g(),next:d().nullable()}),Ae=f({id:d(),name:d(),args:l(d()),cwd:d(),sessionId:d(),exitCode:g().nullable(),durationMs:g().optional(),startedAt:g()}),je=Ae.extend({exitCode:g()}),Me=f({session:A.passthrough()}),Ne=Me.extend({routes:l(ke)}),Pe=f({url:d(),token:d()}),Fe=f({sessions:l(A.passthrough()),pagination:M}),Ie=f({command:Ae}),Le=f({command:je}),Re=f({}),ze=f({data:d()}),Be=c(`stream`,[ze.extend({stream:h(`stdout`)}),ze.extend({stream:h(`stderr`)}),f({stream:h(`error`),data:f({code:d(),message:d()})})]),Ve=f({snapshots:l(j),pagination:M}),He=f({snapshot:j,siblings:l(j),count:d()}),Ue=f({snapshots:l(He),anchor:He.optional(),pagination:M}),We=f({snapshot:j,session:A.passthrough()}),Ge=f({snapshot:j}),Ke=f({name:d(),projectId:d(),maxSizeBytes:g(),currentSessionId:d().optional(),currentSandboxName:d().optional(),createdAt:g(),updatedAt:g()}),qe=f({drives:l(Ke),pagination:M}),Je=f({drive:Ke}),Ye=f({name:d(),persistent:s(),region:d().optional(),vcpus:g().optional(),memory:g().optional(),runtime:d().optional(),image:d().optional(),timeout:g().optional(),networkPolicy:Oe.optional(),totalEgressBytes:g().optional(),totalIngressBytes:g().optional(),totalActiveCpuDurationMs:g().optional(),totalDurationMs:g().optional(),createdAt:g(),updatedAt:g(),expiresAt:g().optional(),currentSessionId:d(),currentSnapshotId:d().optional(),status:A.shape.status,statusUpdatedAt:g().optional(),cwd:d().optional(),tags:u(d(),d()).optional(),mounts:u(d(),f({drive:d(),mode:_([`read-only`,`read-write`]).optional()})).optional(),snapshotExpiration:g().optional(),keepLastSnapshots:f({count:g(),expiration:g().optional(),deleteEvicted:s().optional()}).optional()}),Xe=f({session:A.passthrough(),sandbox:Ye.optional(),snapshot:j.optional()}),Ze=f({sandbox:Ye,session:A.passthrough(),routes:l(ke),resumed:s().optional()}),Qe=f({sandboxes:l(Ye),pagination:M}),$e=f({sandbox:Ye,routes:l(ke).optional()});var et=n(((t,n)=>{n.exports=e(`events`)})),tt=n(((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return this.buffer[this.top]===void 0?(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0):!1}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})),nt=n(((e,t)=>{let n=tt();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})),rt=n(((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n,r,i){return b(e).write(t,n,r,i)}function C(e,t){return b(e).readDoubleBE(t)}function w(e,t){return b(e).readDoubleLE(t)}function ee(e,t){return b(e).readFloatBE(t)}function te(e,t){return b(e).readFloatLE(t)}function T(e,t){return b(e).readInt32BE(t)}function ne(e,t){return b(e).readInt32LE(t)}function re(e,t){return b(e).readUInt32BE(t)}function E(e,t){return b(e).readUInt32LE(t)}function ie(e,t,n){return b(e).writeDoubleBE(t,n)}function ae(e,t,n){return b(e).writeDoubleLE(t,n)}function oe(e,t,n){return b(e).writeFloatBE(t,n)}function D(e,t,n){return b(e).writeFloatLE(t,n)}function O(e,t,n){return b(e).writeInt32BE(t,n)}function se(e,t,n){return b(e).writeInt32LE(t,n)}function ce(e,t,n){return b(e).writeUInt32BE(t,n)}function le(e,t,n){return b(e).writeUInt32LE(t,n)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,write:S,readDoubleBE:C,readDoubleLE:w,readFloatBE:ee,readFloatLE:te,readInt32BE:T,readInt32LE:ne,readUInt32BE:re,readUInt32LE:E,writeDoubleBE:ie,writeDoubleLE:ae,writeFloatBE:oe,writeFloatLE:D,writeInt32BE:O,writeInt32LE:se,writeUInt32BE:ce,writeUInt32LE:le}})),it=n(((e,t)=>{let n=rt();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})),at=n(((e,t)=>{let n=rt();t.exports=class{constructor(){this._reset()}get remaining(){return this.bytesSeen}decode(e){if(e.byteLength===0)return``;if(this.bytesNeeded===0&&r(e,0)===0)return this.bytesSeen=i(e),n.toString(e,`utf8`);let t=``,a=0;if(this.bytesNeeded>0){for(;a<e.byteLength;){let n=e[a];if(n<this.lowerBoundary||n>this.upperBoundary){t+=`�`,this._reset();break}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|n&63,this.bytesSeen++,a++,this.bytesSeen===this.bytesNeeded){t+=String.fromCodePoint(this.codePoint),this._reset();break}}if(this.bytesNeeded>0)return t}let o=r(e,a),s=e.byteLength-o;s>a&&(t+=n.toString(e,`utf8`,a,s));for(let n=s;n<e.byteLength;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?(this.bytesSeen=0,t+=String.fromCharCode(r)):r>=194&&r<=223?(this.bytesNeeded=2,this.bytesSeen=1,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.bytesSeen=1,this.codePoint=r&15):r>=240&&r<=244?(r===240?this.lowerBoundary=144:r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.bytesSeen=1,this.codePoint=r&7):(this.bytesSeen=1,t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){t+=`�`,n--,this._reset();continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this._reset())}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this._reset(),e}_reset(){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191}};function r(e,t){let n=e.byteLength;if(n<=t)return 0;let r=Math.max(t,n-4),i=n-1;for(;i>r&&(e[i]&192)==128;)i--;if(i<t)return 0;let a=e[i],o;if(a<=127)return 0;if(a>=194&&a<=223)o=2;else if(a>=224&&a<=239)o=3;else if(a>=240&&a<=244)o=4;else return 0;let s=n-i;return s<o?s:0}function i(e){let t=e.byteLength;if(t===0)return 0;let n=e[t-1];if(n<=127)return 0;if((n&192)!=128)return 1;let r=Math.max(0,t-4),i=t-2;for(;i>=r&&(e[i]&192)==128;)i--;if(i<0)return 1;let a=e[i],o;if(a>=194&&a<=223)o=2;else if(a>=224&&a<=239)o=3;else if(a>=240&&a<=244)o=4;else return 1;if(t-i!==o)return 1;if(o>=3){let t=e[i+1];if(a===224&&t<160||a===237&&t>159||a===240&&t<144||a===244&&t>143)return 1}return 0}})),ot=n(((e,t)=>{let n=it(),r=at();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(e){switch(e=e.toLowerCase(),e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:throw Error(`Unknown encoding: `+e)}}})),st=n(((e,t)=>{t.exports=class e extends Error{constructor(t,n,r=e){super(t),this.code=n,Error.captureStackTrace&&Error.captureStackTrace(this,r)}static isStreamDestroyed(e){return e&&e.code===`STREAM_DESTROYED`}static isPrematureClose(e){return e&&e.code===`PREMATURE_CLOSE`}static isAborted(e){return e&&e.code===`ABORTED`}static isBadArgument(e){return e&&e.code===`BAD_ARGUMENT`}get name(){return`StreamError`}static STREAM_DESTROYED(){return new e(`Stream was destroyed`,`STREAM_DESTROYED`,e.STREAM_DESTROYED)}static PREMATURE_CLOSE(t=`Premature close`){return new e(t,`PREMATURE_CLOSE`,e.PREMATURE_CLOSE)}static ABORTED(){return new e(`Stream aborted`,`ABORTED`,e.ABORTED)}static BAD_ARGUMENT(t=`Bad argument`){return new e(t,`BAD_ARGUMENT`,e.BAD_ARGUMENT)}}})),ct=n(((e,t)=>{let{EventEmitter:n}=et(),r=nt(),i=ot(),a=st(),o=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,s=536870910,c=1024,l=2048,u=16384,d=32768,f=131072,p=536805375,m=536870143,h=536838143,g=536739839,_=2<<18,v=4<<18,y=8<<18,b=32<<18,x=64<<18,S=128<<18,C=512<<18,w=1024<<18,ee=503316479,te=268435455,T=262160,ne=8404992,re=8405006,E=33587200,ie=33587215,ae=16527,oe=270794767,D=Symbol.asyncIterator||Symbol(`asyncIterator`);var O=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:i,byteLength:a,byteLengthWritable:o}={}){this.stream=e,this.queue=new r,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||a||Le,this.map=i||n,this.afterWrite=pe.bind(this),this.afterUpdateNextTick=ge.bind(this)}get ending(){return(this.stream._duplexState&C)!=0}get ended(){return(this.stream._duplexState&b)!=0}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=y,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|C)&535822335}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&oe)==2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=_;do{for(;(e._duplexState&oe)==y;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)==C){e._duplexState|=262144,e._final(de.bind(this));return}if((e._duplexState&14)==4){e._duplexState&E||(e._duplexState|=T,e._destroy(fe.bind(this)));return}(e._duplexState&ie)==1&&(e._duplexState=(e._duplexState|T)&s,e._open(_e.bind(this)))}continueUpdate(){return this.stream._duplexState&S?(this.stream._duplexState&=ee,!0):!1}updateCallback(){(this.stream._duplexState&35127311)==v?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&S||(this.stream._duplexState|=S,this.stream._duplexState&_||o(this.afterUpdateNextTick))}},se=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:i,byteLength:a,byteLengthReadable:o}={}){this.stream=e,this.queue=new r,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||a||Le,this.map=i||n,this.pipeTo=null,this.afterRead=me.bind(this),this.afterUpdateNextTick=he.bind(this)}get ending(){return(this.stream._duplexState&c)!=0}get ended(){return(this.stream._duplexState&u)!=0}pipe(e,t){if(this.pipeTo!==null)throw a.BAD_ARGUMENT(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new le(this.stream,e,t),t&&this.stream.on(`error`,Re),j(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Re),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,ue.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|c)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=p,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&p,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&ae)==128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=m),e._duplexState&l&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=f,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&ae)==128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=m),e._duplexState&l&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)==f;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=8192,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)==c&&(e._duplexState=(e._duplexState|u)&536869887,e.emit(`end`),(e._duplexState&re)==ne&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){e._duplexState&E||(e._duplexState|=T,e._destroy(fe.bind(this)));return}(e._duplexState&ie)==1&&(e._duplexState=(e._duplexState|T)&s,e._open(_e.bind(this)))}continueUpdate(){return this.stream._duplexState&d?(this.stream._duplexState&=h,!0):!1}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=d,this.stream._duplexState&32||o(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&d||(this.stream._duplexState|=d,this.stream._duplexState&32||o(this.afterUpdateNextTick))}},ce=class{constructor(e){this.data=null,this.afterTransform=ve.bind(e),this.afterFinal=null}},le=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){(!(this.from._duplexState&u)||!this.pipeToFinished)&&this.from.destroy(this.error||a.PREMATURE_CLOSE(`Writable stream closed`));return}if(e===this.from&&(this.from=null,this.to!==null)){e._duplexState&u||this.to.destroy(this.error||a.PREMATURE_CLOSE(`Readable stream closed`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function ue(){this.stream._duplexState|=512,this.updateCallback()}function de(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=b,t.emit(`finish`)),(t._duplexState&re)==ne&&(t._duplexState|=4),t._duplexState&=402391039,t._duplexState&_?this.updateNextTick():this.update()}function fe(e){let t=this.stream;!e&&!a.isStreamDestroyed(this.error)&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,t.emit(`close`);let n=t._readableState,r=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),r!==null){for(;r.drains!==null&&r.drains.length>0;)r.drains.shift().resolve(!1);r.pipeline!==null&&r.pipeline.done(t,e)}}function pe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&k(this.drains),(t._duplexState&6553615)==4194304&&(t._duplexState&=532676607,(t._duplexState&x)==x&&t.emit(`drain`)),this.updateCallback()}function me(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=g),this.updateCallback()}function he(){this.stream._duplexState&32||(this.stream._duplexState&=h,this.update())}function ge(){this.stream._duplexState&_||(this.stream._duplexState&=ee,this.update())}function k(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function _e(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=v),t.emit(`open`)),t._duplexState&=536608751,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function ve(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function ye(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=133376,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=4096,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=x,this._writableState.updateNextTick())}var be=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,ze.bind(this))),this.on(`newListener`,ye)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState!==null||void 0}get writable(){return this._writableState!==null||void 0}get destroyed(){return(this._duplexState&8)!=0}get destroying(){return(this._duplexState&14)!=0}destroy(e){this._duplexState&14||(e||=a.STREAM_DESTROYED(),this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},xe=class e extends be{constructor(e){super(e),this._duplexState|=8519681,this._readableState=new se(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=g),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}static deferred(e,t){let n=new Te(t);return e().then(e=>{if(e===null)return n.end();n.destroying||Oe(e,n,Re)}).catch(e=>n.destroy(e)),n}setEncoding(e){let t=new i(e),n=this._readableState.map||A;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=131328,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(Pe(t))return t;if(t[D])return this._fromAsyncIterator(t[D](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return(e._duplexState&17422)!=0||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return(e._duplexState&256)==0}[D](){let e=this,t=null,n=null,r=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,i),this.on(`close`,o),{[D](){return this},next(){return new Promise(function(t,i){n=t,r=i;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function i(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(i){r!==null&&(t?r(t):i===null&&!(e._duplexState&u)?r(a.STREAM_DESTROYED()):n({value:i,done:i===null}),r=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},Se=class extends be{constructor(e){super(e),this._duplexState|=16385,this._writableState=new O(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=w}uncork(){this._duplexState&=te,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(Be(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&67108864?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Ce=class extends xe{constructor(e){super(e),this._duplexState=1|this._duplexState&f,this._writableState=new O(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=w}uncork(){this._duplexState&=te,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},we=class extends Ce{constructor(e){super(e),this._transformState=new ce(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(Ee.bind(this))}},Te=class extends we{};function Ee(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function De(...e){return new Promise((t,n)=>Oe(...e,e=>{if(e)return n(e);t()}))}function Oe(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]==`function`?n.pop():null;if(n.length<2)throw a.BAD_ARGUMENT(`Pipeline requires at least 2 streams`);let i=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],j(i)?i.pipe(o,l):(c(i,!0,e>1,l),i.pipe(o)),i=o;if(r){let e=!1,t=j(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:a.PREMATURE_CLOSE())))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,i);function i(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(a.PREMATURE_CLOSE())}}function l(e){if(!(!e||s)){s=e;for(let t of n)t.destroy(e)}}}function A(e){return e}function ke(e){return!!e._readableState||!!e._writableState}function j(e){return typeof e._duplexState==`number`&&ke(e)}function M(e){return!!e._readableState&&e._readableState.ending}function Ae(e){return!!e._readableState&&e._readableState.ended}function je(e){return!!e._writableState&&e._writableState.ending}function Me(e){return!!e._writableState&&e._writableState.ended}function Ne(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&a.isStreamDestroyed(n)?null:n}function Pe(e){return j(e)&&e.readable}function Fe(e){return(e._duplexState&1)!=1||(e._duplexState&4)==4||(e._duplexState&E)!=0}function Ie(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Le(e){return Ie(e)?e.byteLength:1024}function Re(){}function ze(){this.destroy(a.ABORTED())}function Be(e){return e._writev!==Se.prototype._writev&&e._writev!==Ce.prototype._writev}t.exports={pipeline:Oe,pipelinePromise:De,isStream:ke,isStreamx:j,isEnding:M,isEnded:Ae,isFinishing:je,isFinished:Me,isDisturbed:Fe,getStreamError:Ne,Stream:be,Writable:Se,Readable:xe,Duplex:Ce,Transform:we,PassThrough:Te}})),lt=n((e=>{let t=rt(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
2
- `)),e.linkname&&(n+=y(` linkpath=`+e.linkname+`
3
- `));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
4
- `);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})),ut=n(((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=ct(),a=nt(),o=rt(),s=lt(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})),dt=n(((t,n)=>{let r={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{n.exports=e(`fs`).constants||r}catch{n.exports=r}})),ft=n(((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=ct(),a=rt(),o=dt(),s=lt(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})),pt=t(n((e=>{e.extract=ut(),e.pack=ft()}))(),1),mt=class{constructor(){let e=ne.createGzip();this.pack=pt.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof C?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function ht(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function gt(e){if(!w.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!w.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=w.posix.isAbsolute(e.filePath)?w.posix.normalize(e.filePath):w.posix.join(e.cwd,e.filePath);return w.posix.relative(e.extractDir,t)}function _t(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return De.parse(t),t}function vt(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const N=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var yt=n(((t,n)=>{var r=e(`stream`).Transform;function i(e){if(!(this instanceof i))throw TypeError(`Cannot call a class as a function`);e||={},r.call(this,{objectMode:!0}),this._memory=``,this._emitInvalidLines=e.emitInvalidLines||!1}i.prototype=Object.create(r.prototype),i.prototype._handleLines=function(e,t){for(var n=0;n<e.length;n++)if(e[n]!==``){var r=null,i=null;try{i=JSON.parse(e[n])}catch(t){t.source=e[n],r=t}if(r)if(this._emitInvalidLines)this.emit(`invalid-line`,r);else return t(r);else this.push(i)}t(null)},i.prototype._transform=function(e,t,n){var r=(this._memory+e.toString()).split(`
5
- `);this._memory=r.pop(),this._handleLines(r,n)},i.prototype._flush=function(e){if(!this._memory)return e(null);var t=this._memory;this._memory=``,this._handleLines([t],e)},n.exports=i})),bt=n(((t,n)=>{var r=e(`stream`).Transform;function i(){if(!(this instanceof i))throw TypeError(`Cannot call a class as a function`);r.call(this,{objectMode:!0})}i.prototype=Object.create(r.prototype),i.prototype._transform=function(e,t,n){var r;try{r=JSON.stringify(e)}catch(t){return t.source=e,n(t)}n(null,r+`
6
- `)},n.exports=i})),xt=n((e=>{var t=yt();bt(),e.parse=function(e){return new t(e)}})),St=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}0&&(t.exports={SYMBOL_FOR_REQ_CONTEXT:u,getContext:d})})),Ct=n(((e,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{getVercelOidcToken:()=>p,getVercelOidcTokenSync:()=>m}),n.exports=l(u);var d=St(),f=x();async function p(e){let n=``,r;try{n=m()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await import(`../../_chunks/node/token-util-ivUGWb31.js`).then(e=>t(e.default)),await import(`../../_chunks/node/token-DHD-q-fS.js`).then(e=>t(e.default))]);(!n||i(r(n),e?.expirationBufferMs))&&(await a(e),n=m())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
7
- ${e.message}`),t?new f.VercelOidcTokenError(t):e}return n}function m(){let e=(0,d.getContext)().headers?.[`x-vercel-oidc-token`]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error(`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`);return e}0&&(n.exports={getVercelOidcToken:p,getVercelOidcTokenSync:m})})),wt=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>f.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>f.RefreshAccessTokenFailedError,getContext:()=>d.getContext,getVercelOidcToken:()=>u.getVercelOidcToken,getVercelOidcTokenSync:()=>u.getVercelOidcTokenSync,getVercelToken:()=>p.getVercelToken}),t.exports=c(l);var u=Ct(),d=St(),f=b(),p=S();0&&(t.exports={AccessTokenMissingError,RefreshAccessTokenFailedError,getContext,getVercelOidcToken,getVercelOidcTokenSync,getVercelToken})})),Tt=t(xt(),1),Et=wt();function Dt(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var P=class extends pe{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=Dt(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,Et.getVercelOidcToken)({expirationBufferMs:300*1e3,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=Dt(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${y} (Node.js/${process.version}; ${re.platform()}/${re.arch()})`,...t?.headers}})}async getSession(e){let t=N(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,k(Ne,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=N(e);return k(Ze,await this.request(`/v2/sandboxes`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?_t(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,mounts:e.mounts,...t}),signal:e.signal}))}async forkSandbox(e){let t=N(e);return k(Ze,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?_t(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await k(p(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new D(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new D(t,{message:`No response body`,sessionId:e.sessionId});let n=Tt.parse();Ot(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new O(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:a}=Ie.parse(i.value);return{command:a,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new O(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=Le.parse(t.value);return e}let n=Be.parse(t.value);if(n.stream===`error`)throw new O(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return k(Ie,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?k(Le,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):k(Ie,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return k(Pe,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return k(Re,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new mt;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await ht(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return k(Fe,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return k(Ve,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return k(Ue,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listDrives(e){return k(qe,await this.request(`/v2/sandboxes/drives`,{query:{projectId:e.projectId,limit:e.limit,cursor:e.cursor??e.until,since:e.since,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix},method:`GET`,signal:e.signal}))}async getOrCreateDrive(e){return k(Je,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,maxSizeBytes:e.maxSizeBytes}),signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:gt({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await k(Re,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new D(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:C.fromWeb(t.body)}async killCommand(e){return k(Ie,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?kt(e.signal,n.signal):n.signal,i=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,i=await t.request(n,{method:`GET`,signal:r});if(i.ok||await k(p(),i),i.headers.get(`content-type`)!==`application/x-ndjson`)throw new D(i,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(i.body===null)throw new D(i,{message:`No response body`,sessionId:e.sessionId});let a=Tt.parse();Ot(i.body,a,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of a){let n=Be.parse(t);if(n.stream===`error`)throw new O(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(i,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return k(Xe,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return k(Me,await this.request(t,{method:`POST`,body:JSON.stringify(_t(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return k(Me,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return k(We,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return k(Ge,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return k(Ge,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=N(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),k(Ze,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return k(Qe,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:At(e.tags)},method:`GET`,signal:e.signal}))}async deleteDrive(e){let t=`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`;return k(Je,await this.request(t,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}async updateSandbox(e){return k($e,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,runtime:e.runtime,timeout:e.timeout,networkPolicy:e.networkPolicy?_t(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId}),signal:e.signal}))}async deleteSandbox(e){return k($e,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}};async function Ot(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function kt(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function At(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>`${e}:${t}`)}function jt(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var F=t(n(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c}))(),1);const Mt={warn:F.default.yellow,error:F.default.red,success:F.default.green,info:F.default.blue},Nt=F.default.dim(`[vercel/sandbox]`);function I(e,t){t=Array.isArray(t)?t.join(`
8
- `):t;let n=t.replace(/^/gm,`${Nt} `);console.error(Mt[e](n))}function Pt(e){return F.default.italic(F.default.dim("`")+e+F.default.dim("`"))}var Ft=t(a(),1);async function It(){return await import(`../../_chunks/node/auth-BaNbsImr.js`)}function Lt(){return process.env.NODE_ENV!==`production`&&![`1`,`true`].includes(process.env.CI||``)&&process.stdout.isTTY&&process.stdin.isTTY}const Rt=(()=>{let e=null;return async t=>{(!e||e[0].teamId!==t.teamId||e[0].projectId!==t.projectId)&&(e=[t,zt(t).catch(t=>{throw e=null,t})]);let n=await e[1];return I(`warn`,`using inferred credentials team=${n.teamId} project=${n.projectId}`),n}})();async function zt(e){let{OAuth:t,pollForToken:n,getAuth:r,updateAuthConfig:i,inferScope:a}=await It(),o=r();if(!o?.token){let e=process.env.VERCEL_URL?`1 minute`:`5 minutes`;o=await Bt({OAuth:t,pollForToken:n,getAuth:r},e)}if(o?.refreshToken&&o.expiresAt&&o.expiresAt.getTime()<=Date.now()){let e=await(await t()).refreshToken(o.refreshToken);o={expiresAt:new Date(Date.now()+e.expires_in*1e3),token:e.access_token,refreshToken:e.refresh_token||o.refreshToken},i(o)}if(!o?.token)throw Error([`Failed to retrieve authentication token.`,`${F.default.bold(`hint:`)} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,`├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox`,`╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token`].join(`
9
- `));if(e.teamId&&e.projectId)return{token:o.token,teamId:e.teamId,projectId:e.projectId};let s=await a({teamId:e.teamId,token:o.token});return s.created&&I(`info`,`Created default project "${s.projectId}" in team "${s.teamId}".`),{token:o.token,teamId:e.teamId||s.teamId,projectId:e.projectId||s.projectId}}async function Bt(e,t){I(`warn`,[`No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,`│ ${F.default.bold(`help:`)} this flow only happens on development environment.`,`│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`]);let n=await e.OAuth(),r=await n.deviceAuthorizationRequest();I(`info`,[`╰▶ To authenticate, visit: ${r.verification_uri_complete}`,` or visit ${F.default.italic(r.verification_uri)} and type ${F.default.bold(r.user_code)}`,` Press ${F.default.bold(`<return>`)} to open in your browser`]);let i,a=e.pollForToken({request:r,oauth:n}),o=!1,s=setTimeout(()=>{if(o)return;let e=[`Authentication flow timed out after ${t}.`,`│ Make sure to provide a token to avoid prompting an interactive flow.`,`╰▶ ${F.default.bold(`help:`)} Link your project with ${Pt(`npx vercel link`)} to refresh OIDC token automatically.`].join(`
10
- `);i=Error(e),a.return()},(0,Ft.default)(t));try{for await(let e of a)switch(e._tag){case`SlowDown`:case`Timeout`:case`Response`:break;case`Error`:i=e.error;break;default:throw Error(`Unknown event type: ${JSON.stringify(e)}`)}}finally{o=!0,clearTimeout(s)}if(i)throw I(`error`,`${F.default.bold(`error:`)} Authentication failed: ${i.message}`),i;return I(`success`,`${F.default.bold(`done!`)} Authenticated successfully!`),e.getAuth()}var Vt=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,"Please link your Vercel project using `npx vercel link`.","Then, pull an initial OIDC token with `npx vercel env pull`",`and retry.`,"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."].join(`
11
- `);super(t,{cause:e}),this.name=`LocalOidcContextError`}},Ht=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
12
- `);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function Ut(e){try{return Kt(await(0,Et.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!Lt())throw process.env.VERCEL_URL?new Ht(t):new Vt(t);return await Rt(e)}}async function L(e){return Wt(e??{})||await Ut({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Wt(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const Gt=f({exp:g().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:g().optional().describe(`Issued at timestamp`),owner_id:d(),project_id:d()});function Kt(e){try{let t=Gt.parse(jt(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const qt={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function Jt(e){if(typeof e==`number`)return e;if(e in qt)return qt[e];throw Error(`Unknown signal name: ${String(e)}`)}var Yt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await L();return this._client=new P({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[r](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new Xt({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:Jt(e??`SIGTERM`),abortSignal:t?.abortSignal})}},Xt=class e extends Yt{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[r](e){return{...Yt[r](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function R(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){Zt(i);let t=e;for(yield t;t.pagination.next!==null;)Zt(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)Zt(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function Zt(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var Qt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await L();return this._client=new P({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[r](e){return{snapshot:e.snapshot}}static[i](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await L(e),n=new P({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return R(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await L(e),n=new P({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return R(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await L(t),r=new P({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function $t(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?vt(t):void 0}}var en=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await L();return this._client=new P({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[r](e){return{session:e.session,routes:e.routes}}static[i](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=$t(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new Yt({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new Xt({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new Yt({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:ht(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=te(t.cwd??``,t.path);return n?.mkdirRecursive&&await ie(ee(e),{recursive:!0}),await E(i,T(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=$t(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=$t((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=$t((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=$t(n.json.session),new Qt({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:z,S_IFREG:tn,S_IFDIR:nn,S_IFLNK:rn,S_IFBLK:an,S_IFCHR:on,S_IFIFO:sn,S_IFSOCK:cn}=ae;function B(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function ln(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var un=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&z)===tn}isDirectory(){return(this.mode&z)===nn}isBlockDevice(){return(this.mode&z)===an}isCharacterDevice(){return(this.mode&z)===on}isSymbolicLink(){return(this.mode&z)===rn}isFIFO(){return(this.mode&z)===sn}isSocket(){return(this.mode&z)===cn}},dn=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function fn(e){let t=e.trim().split(`|`);return new un(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function pn(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw B(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new dn(r,hn[i]??1,t)}const mn=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,hn={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var gn=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=ln(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw B(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw B(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`scandir`,e):B(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
13
- `).filter(Boolean).map(t=>pn(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`scandir`,e):B(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
14
- `).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,mn,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`stat`,e):B(`EACCES`,t.trim(),`stat`,e)}return fn(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,mn,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`lstat`,e):B(`EACCES`,t.trim(),`lstat`,e)}return fn(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`unlink`,e):B(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`rm`,e):B(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?B(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):B(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`rename`,e):B(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`copyfile`,e):B(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw B(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`chmod`,e):B(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`chown`,e):B(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?B(`EEXIST`,`file already exists`,`symlink`,t):B(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`readlink`,e):B(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`realpath`,e):B(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?B(`ENOENT`,`no such file or directory`,`truncate`,e):B(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw B(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};const _n=/^[a-z_][a-z0-9_-]*$/;function V(e,t){if(!e)throw Error(`Invalid ${t}: must not be empty`);if(e.length>32)throw Error(`Invalid ${t} "${e}": must be at most 32 characters`);if(!_n.test(e))throw Error(`Invalid ${t} "${e}": must match ${_n} (lowercase letters, digits, hyphens, underscores)`)}var vn=class extends Error{constructor(e){super(`Failed to create user "${e}": user already exists`),this.name=`SandboxUserAlreadyExistsError`,this.username=e}},yn=class{constructor({sandbox:e,username:t}){this.sandbox=e,this.username=t,this.homeDir=t===`root`?`/root`:`/home/${t}`}buildUserCommand(e){let t=Object.entries(e.env??{}),n=t.length>0?[`env`,...t.map(([e,t])=>`${e}=${t}`)]:[],r=e.cwd??this.homeDir;return{cmd:`sudo`,args:[`-u`,this.username,`--`,`bash`,`-c`,`cd "$1" || exit 1; shift; exec "$@"`,`bash`,r,...n,e.cmd,...e.args??[]]}}resolvePath(e){return e.startsWith(`/`)?e:`${this.homeDir}/${e}`}async runCommand(e,t,n){if(typeof e==`string`){let r=this.buildUserCommand({cmd:e,args:t});return this.sandbox.runCommand({...r,signal:n?.signal,timeoutMs:n?.timeoutMs})}let r=e;if(r.sudo)return this.sandbox.runCommand({...r});let i=this.buildUserCommand({cmd:r.cmd,args:r.args,env:r.env,cwd:r.cwd});return this.sandbox.runCommand({cmd:i.cmd,args:i.args,detached:r.detached,stdout:r.stdout,stderr:r.stderr,signal:r.signal,timeoutMs:r.timeoutMs})}async writeFiles(e,t){let n=e.map(e=>({...e,path:this.resolvePath(e.path)}));await this.sandbox.writeFiles(n,t);let r=n.map(e=>e.path);if(r.length===0)return;await this.chownOrThrow(r,`${this.username}:${await this.primaryGroup(t?.signal)}`,t?.signal);let i=this.ancestorDirsUnderHome(r);if(i.length>0){let{group:e}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(i,`${this.username}:${e}`,t?.signal),await this.chmodOrThrow(i,`770`,t?.signal)}}async readFile(e,t){"use step";let n=await this.catAsUser(e,t);return n===null?null:C.from([n])}async readFileToBuffer(e,t){return this.catAsUser(e,t)}async downloadFile(e,t,n){"use step";let r=await this.readFile(e,n);if(r===null)return null;let i=te(t.cwd??``,t.path);return n?.mkdirRecursive&&await ie(ee(i),{recursive:!0}),await E(r,T(i),{signal:n?.signal}),i}async catAsUser(e,t){let n=e.path.startsWith(`/`)?e.path:`${e.cwd??this.homeDir}/${e.path}`,r=await this.runCommand({cmd:`base64`,args:[n],signal:t?.signal});if(r.exitCode!==0){let e=await r.stderr();if(/No such file or directory/i.test(e))return null;throw Error(`Failed to read ${n}: ${e}`)}return Buffer.from(await r.stdout(),`base64`)}async mkDir(e,t){let n=this.resolvePath(e);await this.sandbox.mkDir(n,t);let r=[n,...this.ancestorDirsUnderHome([n])],{group:i}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(r,`${this.username}:${i}`,t?.signal),await this.chmodOrThrow(r,`770`,t?.signal)}primaryGroup(e){return this.primaryGroupPromise||=this.resolvePrimaryGroup(e).catch(e=>{throw this.primaryGroupPromise=void 0,e}),this.primaryGroupPromise}async resolvePrimaryGroup(e){let t=await this.sandbox.runCommand({cmd:`id`,args:[`-gn`,this.username],signal:e});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the primary group of "${this.username}": ${e}`)}let n=(await t.stdout()).trim();if(!n)throw Error(`Failed to resolve the primary group of "${this.username}"`);return n}async chownOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chown`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set ownership on ${e.join(`, `)}: ${t}`)}}async chmodOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chmod`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set permissions on ${e.join(`, `)}: ${t}`)}}ancestorDirsUnderHome(e){let t=new Set,n=`${this.homeDir}/`;for(let r of e){let e=r.slice(0,r.lastIndexOf(`/`));for(;e.length>this.homeDir.length&&e.startsWith(n);)t.add(e),e=e.slice(0,e.lastIndexOf(`/`))}return[...t]}async addToGroup(e,t){V(e,`group name`),await this.sandbox.addUserToGroup(this.username,e,t)}async removeFromGroup(e,t){V(e,`group name`),await this.sandbox.removeUserFromGroup(this.username,e,t)}};function bn(e){return e instanceof D&&e.response.status===410}function xn(e){return e instanceof D&&e.response.status===404}function Sn(e){return e instanceof D&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function Cn(e){return e instanceof D&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function wn(e){return e instanceof D&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var Tn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await L();return this._client=new P({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get image(){return this.sandbox.image}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get cwd(){return this.currentSession().cwd}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get expiresAt(){if(this.session?.status===`running`){let e=this.session.startedAt??this.session.createdAt;return new Date(e.getTime()+this.session.timeout)}return this.sandbox.expiresAt===void 0?void 0:new Date(this.sandbox.expiresAt)}get tags(){return this.sandbox.tags}get mounts(){return this.sandbox.mounts}get networkPolicy(){return this.sandbox.networkPolicy?vt(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await L(e),n=new P({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return R(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[r](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[i](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new en({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";let t=await L(e),n=new P({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=N(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e?.runtime,image:e?.image,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,mounts:e?.mounts,snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new En({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(e){"use step";let t=await L(e),n=new P({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=N(e),i=await n.forkSandbox({sourceSandbox:e.sourceSandbox,projectId:t.projectId,name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,networkPolicy:e.networkPolicy,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,persistent:e.persistent,signal:e.signal,...r});return new En({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e.onResume})}static async get(t){"use step";let n=await L(t),r=new P({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=N(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(xn(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if(Sn(n)){let n=await L(t),r=new P({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=N(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!xn(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new en({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new gn(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new en({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await oe(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new en({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(bn(n))return await this.resume(t),e();if(Cn(n)||wn(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async openInteractive(e){"use step";return this.withResume(()=>this.session.openInteractive(e),e?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}getDefaultUser(e){return this.defaultUserPromise||=this.resolveDefaultUser(e).catch(e=>{throw this.defaultUserPromise=void 0,e}),this.defaultUserPromise}async resolveDefaultUser(e){let t=await this.runCommand({cmd:`sh`,args:[`-c`,`id -un; id -gn`],signal:e?.signal});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the default sandbox user: ${e}`)}let[n,r]=(await t.stdout()).trim().split(`
15
- `);if(!n||!r)throw Error(`Failed to resolve the default sandbox user (got "${n}:${r}")`);return{username:n,group:r}}async createUser(e,t){V(e,`username`);let{group:n}=await this.getDefaultUser(t),r=await this.runCommand({cmd:`useradd`,args:[`-m`,`-s`,`/bin/bash`,e],sudo:!0,signal:t?.signal});if(r.exitCode!==0){if(r.exitCode===9)throw new vn(e);let t=await r.stderr();throw Error(`Failed to create user "${e}": ${t}`)}let i=await this.runCommand({cmd:`chown`,args:[`${e}:${n}`,`/home/${e}`],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to set ownership on /home/${e}: ${t}`)}let a=await this.runCommand({cmd:`chmod`,args:[`770`,`/home/${e}`],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let t=await a.stderr();throw Error(`Failed to set permissions on /home/${e}: ${t}`)}return new yn({sandbox:this,username:e})}asUser(e){return V(e,`username`),new yn({sandbox:this,username:e})}async createGroup(e,t){V(e,`group name`);let{username:n}=await this.getDefaultUser(t),r=`/shared/${e}`,i=await this.runCommand({cmd:`groupadd`,args:[e],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to create group "${e}": ${t}`)}let a=await this.runCommand({cmd:`mkdir`,args:[`-p`,r],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let e=await a.stderr();throw Error(`Failed to create shared directory ${r}: ${e}`)}let o=await this.runCommand({cmd:`chown`,args:[`${n}:${e}`,r],sudo:!0,signal:t?.signal});if(o.exitCode!==0){let e=await o.stderr();throw Error(`Failed to set ownership on ${r}: ${e}`)}let s=await this.runCommand({cmd:`chmod`,args:[`2770`,r],sudo:!0,signal:t?.signal});if(s.exitCode!==0){let e=await s.stderr();throw Error(`Failed to set permissions on ${r}: ${e}`)}return{groupname:e,sharedDir:r}}async addUserToGroup(e,t,n){V(e,`username`),V(t,`group name`);let r=await this.runCommand({cmd:`usermod`,args:[`-aG`,t,e],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to add "${e}" to group "${t}": ${n}`)}}async removeUserFromGroup(e,t,n){V(e,`username`),V(t,`group name`);let r=await this.runCommand({cmd:`gpasswd`,args:[`-d`,e,t],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to remove "${e}" from group "${t}": ${n}`)}}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.timeout!==void 0&&this.session?.status===`running`){let n=e.timeout-this.session.timeout;if(n>0)try{await this.session.extendTimeout(n,t)}catch(e){if(!bn(e)&&!Cn(e))throw e}}if(e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(bn(e)||Cn(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return R(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return R(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},En=class extends Tn{async[Symbol.asyncDispose](){await this.stop()}},Dn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await L();return this._client=new P({teamId:e.teamId,token:e.token}),this._client}get name(){return this.drive.name}get projectId(){return this._projectId}get maxSize(){return this.drive.maxSizeBytes}get currentSessionId(){return this.drive.currentSessionId}get currentSandboxName(){return this.drive.currentSandboxName}get createdAt(){return new Date(this.drive.createdAt)}get updatedAt(){return new Date(this.drive.updatedAt)}static[r](e){return{drive:e.drive,projectId:e._projectId}}static[i](t){return new e({drive:t.drive,projectId:t.projectId})}constructor({client:e,drive:t,projectId:n}){this._client=null,this._client=e??null,this.drive=t,this._projectId=n??t.projectId}static async list(t){"use step";let n=await L(t),r=new P({teamId:n.teamId,token:n.token,fetch:t?.fetch}),i=async i=>{let a=await r.listDrives({...n,...t,...i!==void 0&&{cursor:i}});return{...a.json,drives:a.json.drives.map(t=>new e({client:r,drive:t,projectId:n.projectId}))}};return R(await i(t?.cursor??t?.until),{itemsKey:`drives`,fetchNext:i,signal:t?.signal})}static async getOrCreate(t){"use step";let n=await L(t),r=new P({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,drive:(await r.getOrCreateDrive({projectId:n.projectId,name:t.name,maxSizeBytes:t.maxSize,signal:t.signal})).json.drive,projectId:n.projectId})}async delete(e){"use step";this.drive=(await(await this.ensureClient()).deleteDrive({projectId:this._projectId,name:this.drive.name,signal:e?.signal})).json.drive}};const On=new TextEncoder,H=new TextDecoder;function kn(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function An(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function jn(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Mn(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:H.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=H.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return jn(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}const U=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),W=(e,t)=>e.name===t;function Nn(e){return parseInt(e.name.slice(4),10)}function Pn(e,t){if(Nn(e.hash)!==t)throw U(`SHA-${t}`,`algorithm.hash`)}function Fn(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function In(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Ln(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!W(e.algorithm,`HMAC`))throw U(`HMAC`);Pn(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!W(e.algorithm,`RSASSA-PKCS1-v1_5`))throw U(`RSASSA-PKCS1-v1_5`);Pn(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!W(e.algorithm,`RSA-PSS`))throw U(`RSA-PSS`);Pn(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!W(e.algorithm,`Ed25519`))throw U(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!W(e.algorithm,t))throw U(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!W(e.algorithm,`ECDSA`))throw U(`ECDSA`);let n=Fn(t);if(e.algorithm.namedCurve!==n)throw U(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}In(e,n)}function Rn(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const zn=(e,...t)=>Rn(`Key must be `,e,...t),Bn=(e,t,...n)=>Rn(`Key for the ${e} algorithm must be `,t,...n);var G=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},K=class extends G{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Vn=class extends G{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Hn=class extends G{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},q=class extends G{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},J=class extends G{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},Y=class extends G{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},Un=class extends G{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},Wn=class extends G{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},Gn=class extends G{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},Kn=class extends G{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},qn=class extends G{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};const Jn=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Yn=e=>e?.[Symbol.toStringTag]===`KeyObject`,Xn=e=>Jn(e)||Yn(e);function Zn(e,t,n){try{return Mn(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}const Qn=e=>typeof e==`object`&&!!e;function X(e){if(!Qn(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function $n(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const er=e=>X(e)&&typeof e.kty==`string`,tr=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),nr=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,rr=e=>e.kty===`oct`&&typeof e.k==`string`;function ir(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function ar(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new q(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function or(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(zn(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return Ln(t,e,n),t}async function sr(e,t,n,r){let i=await or(e,t,`verify`);ir(e,i);let a=ar(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const cr=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function lr(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new q(cr)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new q(cr)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new q(cr)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new q(cr)}break;default:throw new q(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function ur(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=lr(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const Z=`given KeyObject instance cannot be used for this algorithm`;let Q;const dr=async(e,t,n,r=!1)=>{Q||=new WeakMap;let i=Q.get(e);if(i?.[n])return i[n];let a=await ur({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:Q.set(e,{[n]:a}),a},fr=(e,t)=>{Q||=new WeakMap;let n=Q.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(Z)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(Z);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(Z);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(Z)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(Z);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(Z);return n?n[t]=a:Q.set(e,{[t]:a}),a};async function pr(e,t){if(e instanceof Uint8Array||Jn(e))return e;if(Yn(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return fr(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:`jwk`});return dr(e,n,t)}if(er(e))return e.k?Mn(e.k):dr(e,e,t,!0);throw Error(`unreachable`)}async function mr(e,t,n){if(!X(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return Mn(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new q(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return ur({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return ur({...e,ext:r});case`EC`:case`OKP`:return ur({...e,alg:t,ext:r});default:throw new q(`Unsupported "kty" (Key Type) Parameter value`)}}function hr(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new q(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function gr(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const $=e=>e?.[Symbol.toStringTag],_r=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`;break}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`;break}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},vr=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(er(t)){if(rr(t)&&_r(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!Xn(t))throw TypeError(Bn(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${$(t)} instances for symmetric algorithms must be of type "secret"`)}},yr=(e,t,n)=>{if(er(t))switch(n){case`decrypt`:case`sign`:if(tr(t)&&_r(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(nr(t)&&_r(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!Xn(t))throw TypeError(Bn(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${$(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${$(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${$(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${$(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${$(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function br(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:vr(e,t,n);break;default:yr(e,t,n)}}async function xr(e,t,n){if(!X(e))throw new J(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new J(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new J(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new J(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new J(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!X(e.header))throw new J(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=Mn(e.protected);r=JSON.parse(H.decode(t))}catch{throw new J(`JWS Protected Header is invalid`)}if(!$n(r,e.header))throw new J(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...r,...e.header},a=hr(J,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new J(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new J(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&gr(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new Hn(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new J(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new J(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`&&(t=await t(r,e),l=!0),br(s,t,`verify`);let u=kn(e.protected===void 0?new Uint8Array:An(e.protected),An(`.`),typeof e.payload==`string`?o?An(e.payload):On.encode(e.payload):e.payload),d=Zn(e.signature,`signature`,J),f=await pr(t,s);if(!await sr(s,f,d,u))throw new qn;let p;p=o?Zn(e.payload,`payload`,J):typeof e.payload==`string`?On.encode(e.payload):e.payload;let m={payload:p};return e.protected!==void 0&&(m.protectedHeader=r),e.header!==void 0&&(m.unprotectedHeader=e.header),l?{...m,key:f}:m}async function Sr(e,t,n){if(e instanceof Uint8Array&&(e=H.decode(e)),typeof e!=`string`)throw new J(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new J(`Invalid Compact JWS`);let s=await xr({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?{...c,key:s.key}:c}const Cr=e=>Math.floor(e.getTime()/1e3),wr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Tr(e){let t=wr.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600);break}return t[1]===`-`||t[4]===`ago`?-i:i}const Er=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,Dr=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function Or(e,t,n={}){let r;try{r=JSON.parse(H.decode(t))}catch{}if(!X(r))throw new Y(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||Er(e.typ)!==Er(i)))throw new K(`unexpected "typ" JWT header value`,r,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in r))throw new K(`missing required "${e}" claim`,r,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new K(`unexpected "iss" claim value`,r,`iss`,`check_failed`);if(s&&r.sub!==s)throw new K(`unexpected "sub" claim value`,r,`sub`,`check_failed`);if(c&&!Dr(r.aud,typeof c==`string`?[c]:c))throw new K(`unexpected "aud" claim value`,r,`aud`,`check_failed`);let d;switch(typeof n.clockTolerance){case`string`:d=Tr(n.clockTolerance);break;case`number`:d=n.clockTolerance;break;case`undefined`:d=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:f}=n,p=Cr(f||new Date);if((r.iat!==void 0||l)&&typeof r.iat!=`number`)throw new K(`"iat" claim must be a number`,r,`iat`,`invalid`);if(r.nbf!==void 0){if(typeof r.nbf!=`number`)throw new K(`"nbf" claim must be a number`,r,`nbf`,`invalid`);if(r.nbf>p+d)throw new K(`"nbf" claim timestamp check failed`,r,`nbf`,`check_failed`)}if(r.exp!==void 0){if(typeof r.exp!=`number`)throw new K(`"exp" claim must be a number`,r,`exp`,`invalid`);if(r.exp<=p-d)throw new Vn(`"exp" claim timestamp check failed`,r,`exp`,`check_failed`)}if(l){let e=p-r.iat,t=typeof l==`number`?l:Tr(l);if(e-d>t)throw new Vn(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,`check_failed`);if(e<0-d)throw new K(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,`check_failed`)}return r}async function kr(e,t,n){let r=await Sr(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new Y(`JWTs MUST NOT use unencoded payload`);let i={payload:Or(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}function Ar(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new q(`Unsupported "alg" value for a JSON Web Key Set`)}}function jr(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(Mr)}function Mr(e){return X(e)}var Nr=class{#e;#t=new WeakMap;constructor(e){if(!jr(e))throw new Un(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=Ar(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`;break}return t}),{0:o,length:s}=a;if(s===0)throw new Wn;if(s!==1){let e=new Gn,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await Pr(t,e,n)}catch{}},e}return Pr(this.#t,o,n)}};async function Pr(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await mr({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new Un(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Fr(e){let t=new Nr(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function Ir(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Lr;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Lr=`jose/v6.2.3`);const Rr=Symbol();async function zr(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new Kn:e});if(i.status!==200)throw new G(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new G(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Br=Symbol();function Vr(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!X(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,X))}var Hr=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),Lr&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,Lr),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[Rr],t?.[Br]!==void 0&&(this.#l=t?.[Br],Vr(t?.[Br],this.#r)&&(this.#i=this.#l.uat,this.#c=Fr(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`&&Date.now()<this.#i+this.#n}fresh(){return typeof this.#i==`number`&&Date.now()<this.#i+this.#r}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof Wn&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&Ir()&&(this.#a=void 0),this.#a||=zr(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=Fr(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function Ur(e,t){let n=new Hr(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}function Wr(e){if(typeof e!=`string`)throw new Y(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Y(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Y(`Invalid JWT`);if(!t)throw new Y(`JWTs must contain a payload`);let r;try{r=Mn(t)}catch{throw new Y(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(H.decode(r))}catch{throw new Y(`Failed to parse the decoded payload as JSON`)}if(!X(i))throw new Y(`Invalid JWT Claims Set`);return i}const Gr=`vercel-forwarded-host`,Kr=`vercel-forwarded-scheme`,qr=`vercel-forwarded-port`,Jr=`vercel-forwarded-path`,Yr=`vercel-sandbox-oidc-token`,Xr=new Map;function Zr(e,t=Qr){return async function(n){let r=new Headers(n.headers),i=r.get(Gr),a=r.get(Kr),o=r.get(qr),s=r.get(Jr),c=r.get(Yr);if(r.delete(Gr),r.delete(Kr),r.delete(qr),r.delete(Jr),r.delete(Yr),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request($r(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=ei(new URL(n.url),s),r=await ri(c,t),i=ni(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function Qr(){return new Response(`Forbidden`,{status:403})}function $r(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function ei(e,t){let n=ti(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=ti(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=ti(r.pathname.slice(0,-n.length))),r}function ti(e){return e.replace(/\/+$/,``)||`/`}function ni(e,t){let n=oi(t,`team_id`),r=oi(t,`project_id`),i=oi(t,`sandbox_id`),a=oi(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function ri(e,t){let n=oi(Wr(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await kr(e,ai(n),{audience:ii(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function ii(e){let t=ti(e.pathname);return t===`/`?e.origin:e.origin+t}function ai(e){let t=Xr.get(e);if(t)return t;let n=Ur(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return Xr.set(e,n),n}function oi(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{D as APIError,Yt as Command,Xt as CommandFinished,Dn as Drive,gn as FileSystem,Tn as Sandbox,yn as SandboxUser,vn as SandboxUserAlreadyExistsError,en as Session,Qt as Snapshot,O as StreamError,Zr as defineSandboxProxy};
1
+ import{o as e}from"../../_chunks/node/rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as r}from"../../_chunks/node/retry-qwFNGj4P.js";import{At as i,Bt as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,dn as f,wn as p,yt as m}from"../../_chunks/node/schemas-DtQwuPdM.js";import{t as ee}from"../../_chunks/node/undici-CUIybhQ2.js";import{a as te,c as ne,i as re,n as ie,o as ae,r as oe,s as se,t as ce}from"../../_chunks/node/decode_jwt-Col8JOnf.js";import{t as le}from"../../_chunks/node/version-BYHw-SDY.js";import{Readable as h}from"stream";import g,{dirname as ue,resolve as de}from"path";import{createWriteStream as fe}from"fs";import pe from"zlib";import me from"os";import{pipeline as he}from"stream/promises";import{mkdir as ge}from"fs/promises";import*as _e from"node:constants";import{setTimeout as ve}from"node:timers/promises";var _=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},v=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function ye(e){return e==null?[]:Array.isArray(e)?e:[e]}var be=e(ne(),1);function xe(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,be.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new _(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await Se(e*1e3,n.signal),new _(o)}if(o.status>=500&&o.status<600)throw new _(o);return o}catch(e){if(Ce(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof _)return e.response;throw e}}}async function Se(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function Ce(e){return e!=null&&e.name===`AbortError`}const we=new(ee()).Agent({bodyTimeout:0});var Te=class{constructor(e){this.fetch=xe(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=we}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))ye(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function Ee(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function De(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}async function Oe(e,t){let n=Ee(t.url),r;n||(r=De(t.url));let i=await t.text().catch(e=>new _(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new _(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok)return new _(t,{message:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r});let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new _(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function y(e,t){let n=await Oe(e,t);if(n instanceof _)throw n;return n}const b=l({exact:c().optional(),startsWith:c().optional(),regex:c().optional()}),ke=l({key:b.optional(),value:b.optional()}),x=l({path:b.optional(),method:o(c()).optional(),queryString:o(ke).optional(),headers:o(ke).optional()}),Ae=l({domain:c(),headers:s(c(),c()).optional(),headerNames:o(c()).optional(),match:x.optional()}),je=l({domain:c(),forwardURL:c(),match:x.optional()}),Me=l({headers:s(c(),c()).optional()}),Ne=l({match:x.optional(),transform:o(Me).optional(),forwardURL:c().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),Pe=l({allow:d([o(c()),s(c(),o(Ne))]).optional(),subnets:l({allow:o(c()).optional(),deny:o(c()).optional()}).optional()}),S=d([l({mode:f(`allow-all`)}).passthrough(),l({mode:f(`deny-all`)}).passthrough()]),Fe=l({mode:f(`custom`),allowedDomains:o(c()).optional(),allowedCIDRs:o(c()).optional(),deniedCIDRs:o(c()).optional(),injectionRules:o(Ae).optional(),forwardRules:o(je).optional()}).passthrough(),Ie=d([S,Pe.passthrough()]),C=d([S,Fe]),w=l({id:c(),memory:p(),vcpus:p(),region:c(),runtime:c(),timeout:p(),status:m([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:p(),startedAt:p().optional(),requestedStopAt:p().optional(),stoppedAt:p().optional(),abortedAt:p().optional(),duration:p().optional(),sourceSnapshotId:c().optional(),snapshottedAt:p().optional(),createdAt:p(),cwd:c(),updatedAt:p(),interactivePort:p().optional(),networkPolicy:C.optional(),activeCpuDurationMs:p().optional(),networkTransfer:l({ingress:p(),egress:p()}).optional()}),T=l({url:c(),subdomain:c(),port:p()}),E=l({id:c(),sourceSessionId:c(),region:c(),status:m([`created`,`deleted`,`failed`]),sizeBytes:p(),expiresAt:p().optional(),createdAt:p(),updatedAt:p(),lastUsedAt:p().optional(),creationMethod:c().optional(),parentId:c().optional()}),D=l({count:p(),next:c().nullable()}),O=l({id:c(),name:c(),args:o(c()),cwd:c(),sessionId:c(),exitCode:p().nullable(),durationMs:p().optional(),startedAt:p()}),Le=O.extend({exitCode:p()}),k=l({session:w.passthrough()}),Re=k.extend({routes:o(T)}),ze=l({url:c(),token:c()}),Be=l({sessions:o(w.passthrough()),pagination:D}),A=l({command:O}),Ve=l({command:Le}),He=l({}),Ue=l({data:c()}),We=a(`stream`,[Ue.extend({stream:f(`stdout`)}),Ue.extend({stream:f(`stderr`)}),l({stream:f(`error`),data:l({code:c(),message:c()})})]),Ge=l({snapshots:o(E),pagination:D}),Ke=l({snapshot:E,siblings:o(E),count:c()}),qe=l({snapshots:o(Ke),anchor:Ke.optional(),pagination:D}),Je=l({snapshot:E,session:w.passthrough()}),Ye=l({snapshot:E}),Xe=l({name:c(),projectId:c(),maxSizeBytes:p(),currentSessionId:c().optional(),currentSandboxName:c().optional(),createdAt:p(),updatedAt:p()}),Ze=l({drives:o(Xe),pagination:D}),Qe=l({drive:Xe}),j=l({name:c(),persistent:i(),region:c().optional(),vcpus:p().optional(),memory:p().optional(),runtime:c().optional(),image:c().optional(),timeout:p().optional(),networkPolicy:C.optional(),totalEgressBytes:p().optional(),totalIngressBytes:p().optional(),totalActiveCpuDurationMs:p().optional(),totalDurationMs:p().optional(),createdAt:p(),updatedAt:p(),expiresAt:p().optional(),currentSessionId:c(),currentSnapshotId:c().optional(),status:w.shape.status,statusUpdatedAt:p().optional(),cwd:c().optional(),tags:s(c(),c()).optional(),mounts:s(c(),l({drive:c(),mode:m([`read-only`,`read-write`]).optional()})).optional(),snapshotExpiration:p().optional(),keepLastSnapshots:l({count:p(),expiration:p().optional(),deleteEvicted:i().optional()}).optional()}),$e=l({session:w.passthrough(),sandbox:j.optional(),snapshot:E.optional()}),M=l({sandbox:j,session:w.passthrough(),routes:o(T),resumed:i().optional()}),et=l({sandboxes:o(j),pagination:D}),N=l({sandbox:j,routes:o(T).optional()});var tt=e(se(),1),nt=class{constructor(){let e=pe.createGzip();this.pack=tt.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof h?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function rt(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function it(e){if(!g.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!g.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=g.posix.isAbsolute(e.filePath)?g.posix.normalize(e.filePath):g.posix.join(e.cwd,e.filePath);return g.posix.relative(e.extractDir,t)}function P(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Ie.parse(t),t}function at(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const F=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var ot=e(ae(),1),st=te();function ct(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var I=class extends Te{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=ct(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,st.getVercelOidcToken)({expirationBufferMs:300*1e3,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=ct(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${le} (Node.js/${process.version}; ${me.platform()}/${me.arch()})`,...t?.headers}})}async getSession(e){let t=F(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,y(Re,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=F(e);return y(M,await this.request(`/v2/sandboxes`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,mounts:e.mounts,...t}),signal:e.signal}))}async forkSandbox(e){let t=F(e);return y(M,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await y(u(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new _(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new _(t,{message:`No response body`,sessionId:e.sessionId});let n=ot.parse();lt(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new v(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:a}=A.parse(i.value);return{command:a,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new v(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=Ve.parse(t.value);return e}let n=We.parse(t.value);if(n.stream===`error`)throw new v(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?y(Ve,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return y(ze,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return y(He,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new nt;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await rt(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return y(Be,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return y(Ge,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return y(qe,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listDrives(e){return y(Ze,await this.request(`/v2/sandboxes/drives`,{query:{projectId:e.projectId,limit:e.limit,cursor:e.cursor??e.until,since:e.since,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix},method:`GET`,signal:e.signal}))}async getOrCreateDrive(e){return y(Qe,await this.request(`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`,{method:`POST`,body:JSON.stringify({projectId:e.projectId,maxSizeBytes:e.maxSizeBytes}),signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:it({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await y(He,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new _(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:h.fromWeb(t.body)}async killCommand(e){return y(A,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?ut(e.signal,n.signal):n.signal,i=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,i=await t.request(n,{method:`GET`,signal:r});if(i.ok||await y(u(),i),i.headers.get(`content-type`)!==`application/x-ndjson`)throw new _(i,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(i.body===null)throw new _(i,{message:`No response body`,sessionId:e.sessionId});let a=ot.parse();lt(i.body,a,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of a){let n=We.parse(t);if(n.stream===`error`)throw new v(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(i,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return y($e,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return y(k,await this.request(t,{method:`POST`,body:JSON.stringify(P(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return y(k,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return y(Je,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return y(Ye,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return y(Ye,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=F(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),y(M,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return y(et,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:dt(e.tags)},method:`GET`,signal:e.signal}))}async deleteDrive(e){let t=`/v2/sandboxes/drives/${encodeURIComponent(e.name)}`;return y(Qe,await this.request(t,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}async updateSandbox(e){return y(N,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,runtime:e.runtime,timeout:e.timeout,networkPolicy:e.networkPolicy?P(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId}),signal:e.signal}))}async deleteSandbox(e){return y(N,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId},signal:e.signal}))}};async function lt(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function ut(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function dt(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>`${e}:${t}`)}function ft(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var L=e(re(),1);const pt={warn:L.default.yellow,error:L.default.red,success:L.default.green,info:L.default.blue},mt=L.default.dim(`[vercel/sandbox]`);function R(e,t){t=Array.isArray(t)?t.join(`
2
+ `):t;let n=t.replace(/^/gm,`${mt} `);console.error(pt[e](n))}function ht(e){return L.default.italic(L.default.dim("`")+e+L.default.dim("`"))}var gt=e(r(),1);async function _t(){return await import(`../../_chunks/node/auth-DpzFWvTn.js`)}function vt(){return process.env.NODE_ENV!==`production`&&![`1`,`true`].includes(process.env.CI||``)&&process.stdout.isTTY&&process.stdin.isTTY}const yt=(()=>{let e=null;return async t=>{(!e||e[0].teamId!==t.teamId||e[0].projectId!==t.projectId)&&(e=[t,bt(t).catch(t=>{throw e=null,t})]);let n=await e[1];return R(`warn`,`using inferred credentials team=${n.teamId} project=${n.projectId}`),n}})();async function bt(e){let{OAuth:t,pollForToken:n,getAuth:r,updateAuthConfig:i,inferScope:a}=await _t(),o=r();if(!o?.token){let e=process.env.VERCEL_URL?`1 minute`:`5 minutes`;o=await xt({OAuth:t,pollForToken:n,getAuth:r},e)}if(o?.refreshToken&&o.expiresAt&&o.expiresAt.getTime()<=Date.now()){let e=await(await t()).refreshToken(o.refreshToken);o={expiresAt:new Date(Date.now()+e.expires_in*1e3),token:e.access_token,refreshToken:e.refresh_token||o.refreshToken},i(o)}if(!o?.token)throw Error([`Failed to retrieve authentication token.`,`${L.default.bold(`hint:`)} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,`├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox`,`╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token`].join(`
3
+ `));if(e.teamId&&e.projectId)return{token:o.token,teamId:e.teamId,projectId:e.projectId};let s=await a({teamId:e.teamId,token:o.token});return s.created&&R(`info`,`Created default project "${s.projectId}" in team "${s.teamId}".`),{token:o.token,teamId:e.teamId||s.teamId,projectId:e.projectId||s.projectId}}async function xt(e,t){R(`warn`,[`No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,`│ ${L.default.bold(`help:`)} this flow only happens on development environment.`,`│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`]);let n=await e.OAuth(),r=await n.deviceAuthorizationRequest();R(`info`,[`╰▶ To authenticate, visit: ${r.verification_uri_complete}`,` or visit ${L.default.italic(r.verification_uri)} and type ${L.default.bold(r.user_code)}`,` Press ${L.default.bold(`<return>`)} to open in your browser`]);let i,a=e.pollForToken({request:r,oauth:n}),o=!1,s=setTimeout(()=>{if(o)return;let e=[`Authentication flow timed out after ${t}.`,`│ Make sure to provide a token to avoid prompting an interactive flow.`,`╰▶ ${L.default.bold(`help:`)} Link your project with ${ht(`npx vercel link`)} to refresh OIDC token automatically.`].join(`
4
+ `);i=Error(e),a.return()},(0,gt.default)(t));try{for await(let e of a)switch(e._tag){case`SlowDown`:case`Timeout`:case`Response`:break;case`Error`:i=e.error;break;default:throw Error(`Unknown event type: ${JSON.stringify(e)}`)}}finally{o=!0,clearTimeout(s)}if(i)throw R(`error`,`${L.default.bold(`error:`)} Authentication failed: ${i.message}`),i;return R(`success`,`${L.default.bold(`done!`)} Authenticated successfully!`),e.getAuth()}var St=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,"Please link your Vercel project using `npx vercel link`.","Then, pull an initial OIDC token with `npx vercel env pull`",`and retry.`,"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."].join(`
5
+ `);super(t,{cause:e}),this.name=`LocalOidcContextError`}},Ct=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
6
+ `);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function wt(e){try{return Dt(await(0,st.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!vt())throw process.env.VERCEL_URL?new Ct(t):new St(t);return await yt(e)}}async function z(e){return Tt(e??{})||await wt({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Tt(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const Et=l({exp:p().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:p().optional().describe(`Issued at timestamp`),owner_id:c(),project_id:c()});function Dt(e){try{let t=Et.parse(ft(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const Ot={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function kt(e){if(typeof e==`number`)return e;if(e in Ot)return Ot[e];throw Error(`Unknown signal name: ${String(e)}`)}var B=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[t](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new V({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:kt(e??`SIGTERM`),abortSignal:t?.abortSignal})}},V=class e extends B{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[t](e){return{...B[t](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function H(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){U(i);let t=e;for(yield t;t.pagination.next!==null;)U(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)U(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function U(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var At=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[t](e){return{snapshot:e.snapshot}}static[n](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return H(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return H(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function W(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?at(t):void 0}}var G=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[t](e){return{session:e.session,routes:e.routes}}static[n](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=W(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new B({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new V({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new B({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:rt(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=de(t.cwd??``,t.path);return n?.mkdirRecursive&&await ge(ue(e),{recursive:!0}),await he(i,fe(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=W(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=W((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=W((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=W(n.json.session),new At({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:K,S_IFREG:jt,S_IFDIR:Mt,S_IFLNK:Nt,S_IFBLK:Pt,S_IFCHR:Ft,S_IFIFO:It,S_IFSOCK:Lt}=_e;function q(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function Rt(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var zt=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&K)===jt}isDirectory(){return(this.mode&K)===Mt}isBlockDevice(){return(this.mode&K)===Pt}isCharacterDevice(){return(this.mode&K)===Ft}isSymbolicLink(){return(this.mode&K)===Nt}isFIFO(){return(this.mode&K)===It}isSocket(){return(this.mode&K)===Lt}},Bt=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function Vt(e){let t=e.trim().split(`|`);return new zt(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function Ht(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw q(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new Bt(r,Wt[i]??1,t)}const Ut=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,Wt={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var Gt=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=Rt(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw q(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw q(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`scandir`,e):q(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
7
+ `).filter(Boolean).map(t=>Ht(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`scandir`,e):q(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
8
+ `).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,Ut,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`stat`,e):q(`EACCES`,t.trim(),`stat`,e)}return Vt(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,Ut,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`lstat`,e):q(`EACCES`,t.trim(),`lstat`,e)}return Vt(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`unlink`,e):q(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`rm`,e):q(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?q(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):q(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`rename`,e):q(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`copyfile`,e):q(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw q(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`chmod`,e):q(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`chown`,e):q(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?q(`EEXIST`,`file already exists`,`symlink`,t):q(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`readlink`,e):q(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`realpath`,e):q(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?q(`ENOENT`,`no such file or directory`,`truncate`,e):q(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw q(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};const Kt=/^[a-z_][a-z0-9_-]*$/;function J(e,t){if(!e)throw Error(`Invalid ${t}: must not be empty`);if(e.length>32)throw Error(`Invalid ${t} "${e}": must be at most 32 characters`);if(!Kt.test(e))throw Error(`Invalid ${t} "${e}": must match ${Kt} (lowercase letters, digits, hyphens, underscores)`)}var qt=class extends Error{constructor(e){super(`Failed to create user "${e}": user already exists`),this.name=`SandboxUserAlreadyExistsError`,this.username=e}},Y=class{constructor({sandbox:e,username:t}){this.sandbox=e,this.username=t,this.homeDir=t===`root`?`/root`:`/home/${t}`}buildUserCommand(e){let t=Object.entries(e.env??{}),n=t.length>0?[`env`,...t.map(([e,t])=>`${e}=${t}`)]:[],r=e.cwd??this.homeDir;return{cmd:`sudo`,args:[`-u`,this.username,`--`,`bash`,`-c`,`cd "$1" || exit 1; shift; exec "$@"`,`bash`,r,...n,e.cmd,...e.args??[]]}}resolvePath(e){return e.startsWith(`/`)?e:`${this.homeDir}/${e}`}async runCommand(e,t,n){if(typeof e==`string`){let r=this.buildUserCommand({cmd:e,args:t});return this.sandbox.runCommand({...r,signal:n?.signal,timeoutMs:n?.timeoutMs})}let r=e;if(r.sudo)return this.sandbox.runCommand({...r});let i=this.buildUserCommand({cmd:r.cmd,args:r.args,env:r.env,cwd:r.cwd});return this.sandbox.runCommand({cmd:i.cmd,args:i.args,detached:r.detached,stdout:r.stdout,stderr:r.stderr,signal:r.signal,timeoutMs:r.timeoutMs})}async writeFiles(e,t){let n=e.map(e=>({...e,path:this.resolvePath(e.path)}));await this.sandbox.writeFiles(n,t);let r=n.map(e=>e.path);if(r.length===0)return;await this.chownOrThrow(r,`${this.username}:${await this.primaryGroup(t?.signal)}`,t?.signal);let i=this.ancestorDirsUnderHome(r);if(i.length>0){let{group:e}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(i,`${this.username}:${e}`,t?.signal),await this.chmodOrThrow(i,`770`,t?.signal)}}async readFile(e,t){"use step";let n=await this.catAsUser(e,t);return n===null?null:h.from([n])}async readFileToBuffer(e,t){return this.catAsUser(e,t)}async downloadFile(e,t,n){"use step";let r=await this.readFile(e,n);if(r===null)return null;let i=de(t.cwd??``,t.path);return n?.mkdirRecursive&&await ge(ue(i),{recursive:!0}),await he(r,fe(i),{signal:n?.signal}),i}async catAsUser(e,t){let n=e.path.startsWith(`/`)?e.path:`${e.cwd??this.homeDir}/${e.path}`,r=await this.runCommand({cmd:`base64`,args:[n],signal:t?.signal});if(r.exitCode!==0){let e=await r.stderr();if(/No such file or directory/i.test(e))return null;throw Error(`Failed to read ${n}: ${e}`)}return Buffer.from(await r.stdout(),`base64`)}async mkDir(e,t){let n=this.resolvePath(e);await this.sandbox.mkDir(n,t);let r=[n,...this.ancestorDirsUnderHome([n])],{group:i}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(r,`${this.username}:${i}`,t?.signal),await this.chmodOrThrow(r,`770`,t?.signal)}primaryGroup(e){return this.primaryGroupPromise||=this.resolvePrimaryGroup(e).catch(e=>{throw this.primaryGroupPromise=void 0,e}),this.primaryGroupPromise}async resolvePrimaryGroup(e){let t=await this.sandbox.runCommand({cmd:`id`,args:[`-gn`,this.username],signal:e});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the primary group of "${this.username}": ${e}`)}let n=(await t.stdout()).trim();if(!n)throw Error(`Failed to resolve the primary group of "${this.username}"`);return n}async chownOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chown`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set ownership on ${e.join(`, `)}: ${t}`)}}async chmodOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chmod`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set permissions on ${e.join(`, `)}: ${t}`)}}ancestorDirsUnderHome(e){let t=new Set,n=`${this.homeDir}/`;for(let r of e){let e=r.slice(0,r.lastIndexOf(`/`));for(;e.length>this.homeDir.length&&e.startsWith(n);)t.add(e),e=e.slice(0,e.lastIndexOf(`/`))}return[...t]}async addToGroup(e,t){J(e,`group name`),await this.sandbox.addUserToGroup(this.username,e,t)}async removeFromGroup(e,t){J(e,`group name`),await this.sandbox.removeUserFromGroup(this.username,e,t)}};function X(e){return e instanceof _&&e.response.status===410}function Jt(e){return e instanceof _&&e.response.status===404}function Yt(e){return e instanceof _&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function Z(e){return e instanceof _&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function Xt(e){return e instanceof _&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var Zt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get image(){return this.sandbox.image}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get cwd(){return this.currentSession().cwd}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get expiresAt(){if(this.session?.status===`running`){let e=this.session.startedAt??this.session.createdAt;return new Date(e.getTime()+this.session.timeout)}return this.sandbox.expiresAt===void 0?void 0:new Date(this.sandbox.expiresAt)}get tags(){return this.sandbox.tags}get mounts(){return this.sandbox.mounts}get networkPolicy(){return this.sandbox.networkPolicy?at(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return H(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[t](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[n](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new G({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=F(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e?.runtime,image:e?.image,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,mounts:e?.mounts,snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new Qt({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(e){"use step";let t=await z(e),n=new I({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=F(e),i=await n.forkSandbox({sourceSandbox:e.sourceSandbox,projectId:t.projectId,name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,networkPolicy:e.networkPolicy,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,persistent:e.persistent,signal:e.signal,...r});return new Qt({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e.onResume})}static async get(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=F(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(Jt(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if(Yt(n)){let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=F(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!Jt(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new G({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new Gt(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new G({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await ve(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new G({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(X(n))return await this.resume(t),e();if(Z(n)||Xt(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async openInteractive(e){"use step";return this.withResume(()=>this.session.openInteractive(e),e?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}getDefaultUser(e){return this.defaultUserPromise||=this.resolveDefaultUser(e).catch(e=>{throw this.defaultUserPromise=void 0,e}),this.defaultUserPromise}async resolveDefaultUser(e){let t=await this.runCommand({cmd:`sh`,args:[`-c`,`id -un; id -gn`],signal:e?.signal});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the default sandbox user: ${e}`)}let[n,r]=(await t.stdout()).trim().split(`
9
+ `);if(!n||!r)throw Error(`Failed to resolve the default sandbox user (got "${n}:${r}")`);return{username:n,group:r}}async createUser(e,t){J(e,`username`);let{group:n}=await this.getDefaultUser(t),r=await this.runCommand({cmd:`useradd`,args:[`-m`,`-s`,`/bin/bash`,e],sudo:!0,signal:t?.signal});if(r.exitCode!==0){if(r.exitCode===9)throw new qt(e);let t=await r.stderr();throw Error(`Failed to create user "${e}": ${t}`)}let i=await this.runCommand({cmd:`chown`,args:[`${e}:${n}`,`/home/${e}`],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to set ownership on /home/${e}: ${t}`)}let a=await this.runCommand({cmd:`chmod`,args:[`770`,`/home/${e}`],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let t=await a.stderr();throw Error(`Failed to set permissions on /home/${e}: ${t}`)}return new Y({sandbox:this,username:e})}asUser(e){return J(e,`username`),new Y({sandbox:this,username:e})}async createGroup(e,t){J(e,`group name`);let{username:n}=await this.getDefaultUser(t),r=`/shared/${e}`,i=await this.runCommand({cmd:`groupadd`,args:[e],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to create group "${e}": ${t}`)}let a=await this.runCommand({cmd:`mkdir`,args:[`-p`,r],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let e=await a.stderr();throw Error(`Failed to create shared directory ${r}: ${e}`)}let o=await this.runCommand({cmd:`chown`,args:[`${n}:${e}`,r],sudo:!0,signal:t?.signal});if(o.exitCode!==0){let e=await o.stderr();throw Error(`Failed to set ownership on ${r}: ${e}`)}let s=await this.runCommand({cmd:`chmod`,args:[`2770`,r],sudo:!0,signal:t?.signal});if(s.exitCode!==0){let e=await s.stderr();throw Error(`Failed to set permissions on ${r}: ${e}`)}return{groupname:e,sharedDir:r}}async addUserToGroup(e,t,n){J(e,`username`),J(t,`group name`);let r=await this.runCommand({cmd:`usermod`,args:[`-aG`,t,e],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to add "${e}" to group "${t}": ${n}`)}}async removeUserFromGroup(e,t,n){J(e,`username`),J(t,`group name`);let r=await this.runCommand({cmd:`gpasswd`,args:[`-d`,e,t],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to remove "${e}" from group "${t}": ${n}`)}}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.timeout!==void 0&&this.session?.status===`running`){let n=e.timeout-this.session.timeout;if(n>0)try{await this.session.extendTimeout(n,t)}catch(e){if(!X(e)&&!Z(e))throw e}}if(e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(X(e)||Z(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return H(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return H(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},Qt=class extends Zt{async[Symbol.asyncDispose](){await this.stop()}},$t=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await z();return this._client=new I({teamId:e.teamId,token:e.token}),this._client}get name(){return this.drive.name}get projectId(){return this._projectId}get maxSize(){return this.drive.maxSizeBytes}get currentSessionId(){return this.drive.currentSessionId}get currentSandboxName(){return this.drive.currentSandboxName}get createdAt(){return new Date(this.drive.createdAt)}get updatedAt(){return new Date(this.drive.updatedAt)}static[t](e){return{drive:e.drive,projectId:e._projectId}}static[n](t){return new e({drive:t.drive,projectId:t.projectId})}constructor({client:e,drive:t,projectId:n}){this._client=null,this._client=e??null,this.drive=t,this._projectId=n??t.projectId}static async list(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t?.fetch}),i=async i=>{let a=await r.listDrives({...n,...t,...i!==void 0&&{cursor:i}});return{...a.json,drives:a.json.drives.map(t=>new e({client:r,drive:t,projectId:n.projectId}))}};return H(await i(t?.cursor??t?.until),{itemsKey:`drives`,fetchNext:i,signal:t?.signal})}static async getOrCreate(t){"use step";let n=await z(t),r=new I({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,drive:(await r.getOrCreateDrive({projectId:n.projectId,name:t.name,maxSizeBytes:t.maxSize,signal:t.signal})).json.drive,projectId:n.projectId})}async delete(e){"use step";this.drive=(await(await this.ensureClient()).deleteDrive({projectId:this._projectId,name:this.drive.name,signal:e?.signal})).json.drive}};const en=`vercel-forwarded-host`,tn=`vercel-forwarded-scheme`,nn=`vercel-forwarded-port`,rn=`vercel-forwarded-path`,an=`vercel-sandbox-oidc-token`,on=new Map;function sn(e,t=cn){return async function(n){let r=new Headers(n.headers),i=r.get(en),a=r.get(tn),o=r.get(nn),s=r.get(rn),c=r.get(an);if(r.delete(en),r.delete(tn),r.delete(nn),r.delete(rn),r.delete(an),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(ln(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=un(new URL(n.url),s),r=await fn(c,t),i=dn(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function cn(){return new Response(`Forbidden`,{status:403})}function ln(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function un(e,t){let n=Q(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=Q(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=Q(r.pathname.slice(0,-n.length))),r}function Q(e){return e.replace(/\/+$/,``)||`/`}function dn(e,t){let n=$(t,`team_id`),r=$(t,`project_id`),i=$(t,`sandbox_id`),a=$(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function fn(e,t){let n=$(ce(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await oe(e,mn(n),{audience:pn(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function pn(e){let t=Q(e.pathname);return t===`/`?e.origin:e.origin+t}function mn(e){let t=on.get(e);if(t)return t;let n=ie(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return on.set(e,n),n}function $(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{_ as APIError,B as Command,V as CommandFinished,$t as Drive,Gt as FileSystem,Zt as Sandbox,Y as SandboxUser,qt as SandboxUserAlreadyExistsError,G as Session,At as Snapshot,v as StreamError,sn as defineSandboxProxy};