@mastra/deployer-sandbox 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @mastra/deployer-sandbox
2
2
 
3
+ ## 0.1.3
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`ce93a3c`](https://github.com/mastra-ai/mastra/commit/ce93a3c114ea1cbfbd576f3db41d7c26c9844f5b), [`5718a22`](https://github.com/mastra-ai/mastra/commit/5718a229281dcfd36bcd1f42a242e3717e510a33), [`a211d09`](https://github.com/mastra-ai/mastra/commit/a211d09185dc65a746534914cf38b67f21ee9bac), [`0dca9d0`](https://github.com/mastra-ai/mastra/commit/0dca9d0b1356024a53b72ea6f040db528b126caa), [`6218217`](https://github.com/mastra-ai/mastra/commit/62182171b6cfca0b099f1c6a77a2e65e7639ab86), [`5807d3a`](https://github.com/mastra-ai/mastra/commit/5807d3ae1d259b8b7d6df7e5bf2b485c694af9c8), [`57661af`](https://github.com/mastra-ai/mastra/commit/57661afeca52ff9af4e72675ede2134fa503d5a5), [`05db566`](https://github.com/mastra-ai/mastra/commit/05db566fcbdcbf33d0bffca0c72ec30129e2e3ca), [`57661af`](https://github.com/mastra-ai/mastra/commit/57661afeca52ff9af4e72675ede2134fa503d5a5), [`57661af`](https://github.com/mastra-ai/mastra/commit/57661afeca52ff9af4e72675ede2134fa503d5a5), [`5718a22`](https://github.com/mastra-ai/mastra/commit/5718a229281dcfd36bcd1f42a242e3717e510a33), [`57661af`](https://github.com/mastra-ai/mastra/commit/57661afeca52ff9af4e72675ede2134fa503d5a5), [`d1b7e3a`](https://github.com/mastra-ai/mastra/commit/d1b7e3a978a309a5653eeaa490d2d6c7c53bd093), [`29c584a`](https://github.com/mastra-ai/mastra/commit/29c584a13a88831e5ed1fdeb0ff8e82eae180433), [`c093146`](https://github.com/mastra-ai/mastra/commit/c0931466404d3c521308ea119cb165bb7e695155), [`8124754`](https://github.com/mastra-ai/mastra/commit/8124754ae89fbc69f8136d1df4a91904d0f84c4e), [`d12b2e4`](https://github.com/mastra-ai/mastra/commit/d12b2e4023fd9e3d3e93a9169f5088bcee2a849c)]:
8
+ - @mastra/core@1.54.0
9
+ - @mastra/deployer@1.54.0
10
+
11
+ ## 0.1.3-alpha.0
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies [[`0dca9d0`](https://github.com/mastra-ai/mastra/commit/0dca9d0b1356024a53b72ea6f040db528b126caa)]:
16
+ - @mastra/core@1.54.0-alpha.0
17
+ - @mastra/deployer@1.54.0-alpha.0
18
+
3
19
  ## 0.1.2
4
20
 
5
21
  ### Patch Changes
@@ -1,159 +1,174 @@
1
- 'use strict';
2
-
3
- var chunkCSXC6CZL_cjs = require('../chunk-CSXC6CZL.cjs');
4
- var workspace = require('@mastra/core/workspace');
5
-
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_shared = require("../shared-H9GioaPM.cjs");
3
+ let _mastra_core_workspace = require("@mastra/core/workspace");
4
+ //#region src/client/index.ts
5
+ /**
6
+ * Runtime resolver + routing helpers for sandbox deployments.
7
+ *
8
+ * SERVER-ONLY. This module resolves sandbox URLs using provider credentials
9
+ * (e.g. VERCEL_TOKEN) — importing it in the browser would ship those
10
+ * credentials to the client. Use the proxy/handler patterns instead so the
11
+ * browser only ever talks to your own domain.
12
+ */
6
13
  function assertServerOnly() {
7
- if (typeof globalThis.window !== "undefined") {
8
- throw new Error(
9
- "@mastra/deployer-sandbox/client is server-only: resolving a sandbox requires provider credentials that must never reach the browser. Proxy requests through your own backend instead (see createSandboxHandler / createSandboxProxy)."
10
- );
11
- }
14
+ if (typeof globalThis.window !== "undefined") throw new Error("@mastra/deployer-sandbox/client is server-only: resolving a sandbox requires provider credentials that must never reach the browser. Proxy requests through your own backend instead (see createSandboxHandler / createSandboxProxy).");
12
15
  }
16
+ /**
17
+ * Resolve (and optionally wake) a sandbox deployment.
18
+ *
19
+ * With `wake: false` (default) the sandbox is not started: the URL is resolved
20
+ * only if the sandbox is already running in this process, otherwise
21
+ * `{ url: null, status: 'stopped' | 'unknown' }` is returned and the caller
22
+ * decides whether to wake.
23
+ *
24
+ * With `wake: true` the sandbox is started (providers resume by identity,
25
+ * e.g. name), the server is relaunched if it is not answering, and the
26
+ * deployment is returned once healthy.
27
+ */
13
28
  async function getDeployment(options) {
14
- assertServerOnly();
15
- const {
16
- sandbox,
17
- port = chunkCSXC6CZL_cjs.DEFAULT_PORT,
18
- wake = false,
19
- healthCheckPath = "/api",
20
- healthCheckTimeoutMs = 6e4
21
- } = options;
22
- const handle = (url2, status, expiresAt) => ({
23
- url: url2,
24
- status,
25
- expiresAt,
26
- stop: async () => {
27
- await sandbox.stop?.();
28
- },
29
- destroy: async () => {
30
- await sandbox.destroy?.();
31
- },
32
- // Resolved lazily — reading logs requires a running sandbox anyway.
33
- logs: async (lines) => chunkCSXC6CZL_cjs.tailServerLog(sandbox, await chunkCSXC6CZL_cjs.resolveRemoteDir(sandbox, options.remoteDir), lines)
34
- });
35
- if (!wake) {
36
- const url2 = workspace.supportsNetworking(sandbox) ? await sandbox.networking.getPortUrl(port) : null;
37
- if (!url2) {
38
- return handle(null, "stopped");
39
- }
40
- const healthy2 = await chunkCSXC6CZL_cjs.waitForHealthy(url2, { path: healthCheckPath, timeoutMs: 3e3, intervalMs: 1e3 });
41
- return handle(url2, healthy2 ? "running" : "stopped");
42
- }
43
- await sandbox.start?.();
44
- if (!workspace.supportsNetworking(sandbox)) {
45
- throw new Error(`Sandbox provider "${sandbox.provider}" does not support networking (public port URLs).`);
46
- }
47
- const url = await sandbox.networking.getPortUrl(port);
48
- if (!url) {
49
- throw new Error(
50
- `Sandbox provider "${sandbox.provider}" did not expose a public URL for port ${port}. Make sure the port is declared when constructing the sandbox (e.g. \`ports: [${port}]\`).`
51
- );
52
- }
53
- let healthy = await chunkCSXC6CZL_cjs.waitForHealthy(url, { path: healthCheckPath, timeoutMs: 3e3, intervalMs: 1e3 });
54
- if (!healthy) {
55
- const remoteDir = await chunkCSXC6CZL_cjs.resolveRemoteDir(sandbox, options.remoteDir);
56
- await chunkCSXC6CZL_cjs.killPreviousServer(sandbox, remoteDir);
57
- await chunkCSXC6CZL_cjs.launchServer(sandbox, remoteDir);
58
- healthy = await chunkCSXC6CZL_cjs.waitForHealthy(url, { path: healthCheckPath, timeoutMs: healthCheckTimeoutMs, intervalMs: 1e3 });
59
- }
60
- if (!healthy) {
61
- const log = await chunkCSXC6CZL_cjs.resolveRemoteDir(sandbox, options.remoteDir).then((dir) => chunkCSXC6CZL_cjs.tailServerLog(sandbox, dir)).catch(() => "");
62
- throw new Error(
63
- `Woke sandbox but the Mastra server did not become healthy at ${url}${healthCheckPath}.` + (log ? `
64
-
65
- Server log:
66
- ${log}` : "")
67
- );
68
- }
69
- const info = await chunkCSXC6CZL_cjs.getInfoSafe(sandbox);
70
- return handle(url, "running", info?.timeoutAt);
29
+ assertServerOnly();
30
+ const { sandbox, port = require_shared.DEFAULT_PORT, wake = false, healthCheckPath = "/api", healthCheckTimeoutMs = 6e4 } = options;
31
+ const handle = (url, status, expiresAt) => ({
32
+ url,
33
+ status,
34
+ expiresAt,
35
+ stop: async () => {
36
+ await sandbox.stop?.();
37
+ },
38
+ destroy: async () => {
39
+ await sandbox.destroy?.();
40
+ },
41
+ logs: async (lines) => require_shared.tailServerLog(sandbox, await require_shared.resolveRemoteDir(sandbox, options.remoteDir), lines)
42
+ });
43
+ if (!wake) {
44
+ const url = (0, _mastra_core_workspace.supportsNetworking)(sandbox) ? await sandbox.networking.getPortUrl(port) : null;
45
+ if (!url) return handle(null, "stopped");
46
+ return handle(url, await require_shared.waitForHealthy(url, {
47
+ path: healthCheckPath,
48
+ timeoutMs: 3e3,
49
+ intervalMs: 1e3
50
+ }) ? "running" : "stopped");
51
+ }
52
+ await sandbox.start?.();
53
+ if (!(0, _mastra_core_workspace.supportsNetworking)(sandbox)) throw new Error(`Sandbox provider "${sandbox.provider}" does not support networking (public port URLs).`);
54
+ const url = await sandbox.networking.getPortUrl(port);
55
+ if (!url) throw new Error(`Sandbox provider "${sandbox.provider}" did not expose a public URL for port ${port}. Make sure the port is declared when constructing the sandbox (e.g. \`ports: [${port}]\`).`);
56
+ let healthy = await require_shared.waitForHealthy(url, {
57
+ path: healthCheckPath,
58
+ timeoutMs: 3e3,
59
+ intervalMs: 1e3
60
+ });
61
+ if (!healthy) {
62
+ const remoteDir = await require_shared.resolveRemoteDir(sandbox, options.remoteDir);
63
+ await require_shared.killPreviousServer(sandbox, remoteDir);
64
+ await require_shared.launchServer(sandbox, remoteDir);
65
+ healthy = await require_shared.waitForHealthy(url, {
66
+ path: healthCheckPath,
67
+ timeoutMs: healthCheckTimeoutMs,
68
+ intervalMs: 1e3
69
+ });
70
+ }
71
+ if (!healthy) {
72
+ const log = await require_shared.resolveRemoteDir(sandbox, options.remoteDir).then((dir) => require_shared.tailServerLog(sandbox, dir)).catch(() => "");
73
+ throw new Error(`Woke sandbox but the Mastra server did not become healthy at ${url}${healthCheckPath}.` + (log ? `\n\nServer log:\n${log}` : ""));
74
+ }
75
+ return handle(url, "running", (await require_shared.getInfoSafe(sandbox))?.timeoutAt);
71
76
  }
77
+ /**
78
+ * Framework-free route-handler proxy (fetch `Request` → `Response`). Mount it
79
+ * as a catch-all API route; the browser only ever sees your own domain, and
80
+ * the sandbox URL (which rotates across resumes) stays server-side.
81
+ */
72
82
  function createSandboxHandler(options) {
73
- assertServerOnly();
74
- let cachedUrl = null;
75
- const forward = async (request, baseUrl) => {
76
- const incoming = new URL(request.url);
77
- const target = new URL(incoming.pathname + incoming.search, baseUrl);
78
- const headers = new Headers(request.headers);
79
- headers.delete("host");
80
- if (options.secret) {
81
- headers.set("x-mastra-sandbox-secret", options.secret);
82
- }
83
- const response = await fetch(target, {
84
- method: request.method,
85
- headers,
86
- body: request.body,
87
- // duplex is required by Node's fetch for streamed request bodies
88
- duplex: "half",
89
- redirect: "manual"
90
- });
91
- const location = response.headers.get("location");
92
- if (location) {
93
- const resolved = new URL(location, target);
94
- if (resolved.origin === new URL(baseUrl).origin) {
95
- const rewritten = new URL(resolved.pathname + resolved.search + resolved.hash, incoming.origin);
96
- const responseHeaders = new Headers(response.headers);
97
- responseHeaders.set("location", rewritten.toString());
98
- return new Response(response.body, {
99
- status: response.status,
100
- statusText: response.statusText,
101
- headers: responseHeaders
102
- });
103
- }
104
- }
105
- return response;
106
- };
107
- return async (request) => {
108
- cachedUrl ??= options.resolve();
109
- try {
110
- return await forward(request, await cachedUrl);
111
- } catch (error) {
112
- cachedUrl = null;
113
- if (!["GET", "HEAD", "OPTIONS"].includes(request.method)) {
114
- throw error;
115
- }
116
- cachedUrl = options.resolve();
117
- try {
118
- return await forward(request, await cachedUrl);
119
- } catch (retryError) {
120
- cachedUrl = null;
121
- throw retryError;
122
- }
123
- }
124
- };
83
+ assertServerOnly();
84
+ let cachedUrl = null;
85
+ const forward = async (request, baseUrl) => {
86
+ const incoming = new URL(request.url);
87
+ const target = new URL(incoming.pathname + incoming.search, baseUrl);
88
+ const headers = new Headers(request.headers);
89
+ headers.delete("host");
90
+ if (options.secret) headers.set("x-mastra-sandbox-secret", options.secret);
91
+ const response = await fetch(target, {
92
+ method: request.method,
93
+ headers,
94
+ body: request.body,
95
+ duplex: "half",
96
+ redirect: "manual"
97
+ });
98
+ const location = response.headers.get("location");
99
+ if (location) {
100
+ const resolved = new URL(location, target);
101
+ if (resolved.origin === new URL(baseUrl).origin) {
102
+ const rewritten = new URL(resolved.pathname + resolved.search + resolved.hash, incoming.origin);
103
+ const responseHeaders = new Headers(response.headers);
104
+ responseHeaders.set("location", rewritten.toString());
105
+ return new Response(response.body, {
106
+ status: response.status,
107
+ statusText: response.statusText,
108
+ headers: responseHeaders
109
+ });
110
+ }
111
+ }
112
+ return response;
113
+ };
114
+ return async (request) => {
115
+ cachedUrl ??= options.resolve();
116
+ try {
117
+ return await forward(request, await cachedUrl);
118
+ } catch (error) {
119
+ cachedUrl = null;
120
+ if (![
121
+ "GET",
122
+ "HEAD",
123
+ "OPTIONS"
124
+ ].includes(request.method)) throw error;
125
+ cachedUrl = options.resolve();
126
+ try {
127
+ return await forward(request, await cachedUrl);
128
+ } catch (retryError) {
129
+ cachedUrl = null;
130
+ throw retryError;
131
+ }
132
+ }
133
+ };
125
134
  }
135
+ /**
136
+ * Next.js middleware helper for Tier 3 routing: reads the current sandbox URL
137
+ * from Edge Config (kept fresh by the deployer's `alias` option) and rewrites
138
+ * the request to it. Returns `undefined` when no URL is configured so the
139
+ * request falls through.
140
+ *
141
+ * ```typescript
142
+ * // middleware.ts
143
+ * export const middleware = createSandboxProxy({ key: 'my-preview' });
144
+ * export const config = { matcher: '/api/:path*' };
145
+ * ```
146
+ */
126
147
  function createSandboxProxy(options) {
127
- assertServerOnly();
128
- return async (request) => {
129
- const connection = options.edgeConfig ?? process.env.EDGE_CONFIG;
130
- if (!connection) {
131
- throw new Error("createSandboxProxy requires an Edge Config connection string (EDGE_CONFIG).");
132
- }
133
- const conn = new URL(connection);
134
- const token = conn.searchParams.get("token");
135
- const itemUrl = new URL(`${conn.origin}${conn.pathname}/item/${encodeURIComponent(options.key)}`);
136
- const res = await fetch(itemUrl, { headers: { Authorization: `Bearer ${token}` } });
137
- if (!res.ok) {
138
- return void 0;
139
- }
140
- const sandboxUrl = await res.json();
141
- if (typeof sandboxUrl !== "string" || !sandboxUrl) {
142
- return void 0;
143
- }
144
- const incoming = new URL(request.url);
145
- const target = new URL(incoming.pathname + incoming.search, sandboxUrl);
146
- const headers = new Headers({ "x-middleware-rewrite": target.toString() });
147
- if (options.secret) {
148
- headers.set("x-middleware-request-x-mastra-sandbox-secret", options.secret);
149
- headers.set("x-middleware-override-headers", "x-mastra-sandbox-secret");
150
- }
151
- return new Response(null, { headers });
152
- };
148
+ assertServerOnly();
149
+ return async (request) => {
150
+ const connection = options.edgeConfig ?? process.env.EDGE_CONFIG;
151
+ if (!connection) throw new Error("createSandboxProxy requires an Edge Config connection string (EDGE_CONFIG).");
152
+ const conn = new URL(connection);
153
+ const token = conn.searchParams.get("token");
154
+ const itemUrl = new URL(`${conn.origin}${conn.pathname}/item/${encodeURIComponent(options.key)}`);
155
+ const res = await fetch(itemUrl, { headers: { Authorization: `Bearer ${token}` } });
156
+ if (!res.ok) return;
157
+ const sandboxUrl = await res.json();
158
+ if (typeof sandboxUrl !== "string" || !sandboxUrl) return;
159
+ const incoming = new URL(request.url);
160
+ const target = new URL(incoming.pathname + incoming.search, sandboxUrl);
161
+ const headers = new Headers({ "x-middleware-rewrite": target.toString() });
162
+ if (options.secret) {
163
+ headers.set("x-middleware-request-x-mastra-sandbox-secret", options.secret);
164
+ headers.set("x-middleware-override-headers", "x-mastra-sandbox-secret");
165
+ }
166
+ return new Response(null, { headers });
167
+ };
153
168
  }
154
-
169
+ //#endregion
155
170
  exports.createSandboxHandler = createSandboxHandler;
156
171
  exports.createSandboxProxy = createSandboxProxy;
157
172
  exports.getDeployment = getDeployment;
158
- //# sourceMappingURL=index.cjs.map
173
+
159
174
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/client/index.ts"],"names":["DEFAULT_PORT","url","tailServerLog","resolveRemoteDir","supportsNetworking","healthy","waitForHealthy","killPreviousServer","launchServer","getInfoSafe"],"mappings":";;;;;AAoBA,SAAS,gBAAA,GAAyB;AAChC,EAAA,IAAI,OAAQ,UAAA,CAAoC,MAAA,KAAW,WAAA,EAAa;AACtE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAGF;AAAA,EACF;AACF;AAmDA,eAAsB,cAAc,OAAA,EAA4D;AAC9F,EAAA,gBAAA,EAAiB;AAEjB,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,IAAA,GAAOA,8BAAA;AAAA,IACP,IAAA,GAAO,KAAA;AAAA,IACP,eAAA,GAAkB,MAAA;AAAA,IAClB,oBAAA,GAAuB;AAAA,GACzB,GAAI,OAAA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iCAAiC,yBAAyB,CAAA;AAAA,IACxE;AACA,IAAA,OAAO,IAAI,QAAA,CAAS,IAAA,EAAM,EAAE,SAAS,CAAA;AAAA,EACvC,CAAA;AACF","file":"index.cjs","sourcesContent":["/**\n * Runtime resolver + routing helpers for sandbox deployments.\n *\n * SERVER-ONLY. This module resolves sandbox URLs using provider credentials\n * (e.g. VERCEL_TOKEN) — importing it in the browser would ship those\n * credentials to the client. Use the proxy/handler patterns instead so the\n * browser only ever talks to your own domain.\n */\nimport { supportsNetworking } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport {\n DEFAULT_PORT,\n getInfoSafe,\n killPreviousServer,\n launchServer,\n resolveRemoteDir,\n tailServerLog,\n waitForHealthy,\n} from '../shared';\n\nfunction assertServerOnly(): void {\n if (typeof (globalThis as { window?: unknown }).window !== 'undefined') {\n throw new Error(\n '@mastra/deployer-sandbox/client is server-only: resolving a sandbox requires provider credentials ' +\n 'that must never reach the browser. Proxy requests through your own backend instead ' +\n '(see createSandboxHandler / createSandboxProxy).',\n );\n }\n}\n\nexport type DeploymentStatus = 'running' | 'stopped' | 'unknown';\n\nexport interface GetDeploymentOptions {\n /**\n * The sandbox to resolve. Provider construction is identity — e.g.\n * `new VercelSandbox({ sandboxName: 'my-preview', ports: [4111] })` resolves\n * the same sandbox from any process.\n */\n sandbox: WorkspaceSandbox;\n /** Port the Mastra server listens on. Defaults to 4111. */\n port?: number;\n /**\n * Wake the sandbox when it is not running. Waking starts (resumes) the\n * sandbox and, only if the server is not answering, relaunches it from the\n * recorded launch script — some providers (e.g. E2B) resume processes on\n * wake, others (e.g. Vercel) restore just the filesystem. Defaults to false.\n */\n wake?: boolean;\n /** Directory the app was deployed into. Defaults to `$HOME/mastra-app` resolved inside the sandbox. */\n remoteDir?: string;\n /** Path polled for health. Defaults to `/api`. */\n healthCheckPath?: string;\n /** Max time to wait for health after a wake, in ms. Defaults to 60000. */\n healthCheckTimeoutMs?: number;\n}\n\nexport interface ResolvedDeployment {\n /** Public URL of the Mastra server, or null when it could not be resolved without waking. */\n url: string | null;\n status: DeploymentStatus;\n /** When the sandbox will auto-shutdown (when known). */\n expiresAt?: Date;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n logs(lines?: number): Promise<string>;\n}\n\n/**\n * Resolve (and optionally wake) a sandbox deployment.\n *\n * With `wake: false` (default) the sandbox is not started: the URL is resolved\n * only if the sandbox is already running in this process, otherwise\n * `{ url: null, status: 'stopped' | 'unknown' }` is returned and the caller\n * decides whether to wake.\n *\n * With `wake: true` the sandbox is started (providers resume by identity,\n * e.g. name), the server is relaunched if it is not answering, and the\n * deployment is returned once healthy.\n */\nexport async function getDeployment(options: GetDeploymentOptions): Promise<ResolvedDeployment> {\n assertServerOnly();\n\n const {\n sandbox,\n port = DEFAULT_PORT,\n wake = false,\n healthCheckPath = '/api',\n healthCheckTimeoutMs = 60_000,\n } = options;\n\n const handle = (url: string | null, status: DeploymentStatus, expiresAt?: Date): ResolvedDeployment => ({\n url,\n status,\n expiresAt,\n stop: async () => {\n await sandbox.stop?.();\n },\n destroy: async () => {\n await sandbox.destroy?.();\n },\n // Resolved lazily — reading logs requires a running sandbox anyway.\n logs: async (lines?: number) => tailServerLog(sandbox, await resolveRemoteDir(sandbox, options.remoteDir), lines),\n });\n\n if (!wake) {\n // Resolve without starting the sandbox (starting can resume billing).\n const url = supportsNetworking(sandbox) ? await sandbox.networking.getPortUrl(port) : null;\n if (!url) {\n return handle(null, 'stopped');\n }\n const healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: 3_000, intervalMs: 1_000 });\n return handle(url, healthy ? 'running' : 'stopped');\n }\n\n await sandbox.start?.();\n\n if (!supportsNetworking(sandbox)) {\n throw new Error(`Sandbox provider \"${sandbox.provider}\" does not support networking (public port URLs).`);\n }\n const url = await sandbox.networking.getPortUrl(port);\n if (!url) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" did not expose a public URL for port ${port}. ` +\n `Make sure the port is declared when constructing the sandbox (e.g. \\`ports: [${port}]\\`).`,\n );\n }\n\n // Some providers (e.g. Vercel) restore the filesystem but not processes on\n // resume, while others (e.g. E2B) resume processes too — relaunch the server\n // from the recorded launch script only when it is not answering.\n let healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: 3_000, intervalMs: 1_000 });\n if (!healthy) {\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n await killPreviousServer(sandbox, remoteDir);\n await launchServer(sandbox, remoteDir);\n healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: healthCheckTimeoutMs, intervalMs: 1_000 });\n }\n if (!healthy) {\n const log = await resolveRemoteDir(sandbox, options.remoteDir)\n .then(dir => tailServerLog(sandbox, dir))\n .catch(() => '');\n throw new Error(\n `Woke sandbox but the Mastra server did not become healthy at ${url}${healthCheckPath}.` +\n (log ? `\\n\\nServer log:\\n${log}` : ''),\n );\n }\n\n const info = await getInfoSafe(sandbox);\n return handle(url, 'running', info?.timeoutAt);\n}\n\n// =============================================================================\n// Tier 3 helpers\n// =============================================================================\n\nexport interface CreateSandboxHandlerOptions {\n /**\n * Resolve the current sandbox URL. Called once, cached, and re-invoked when\n * a forwarded request fails at the network level (e.g. the sandbox rotated\n * its URL or went to sleep). Typically wraps `getDeployment`:\n *\n * ```typescript\n * createSandboxHandler({\n * resolve: async () => {\n * const dep = await getDeployment({ sandbox, wake: true });\n * return dep.url!;\n * },\n * });\n * ```\n */\n resolve: () => Promise<string>;\n /** Shared secret attached as the `x-mastra-sandbox-secret` header on forwarded requests. */\n secret?: string;\n}\n\n/**\n * Framework-free route-handler proxy (fetch `Request` → `Response`). Mount it\n * as a catch-all API route; the browser only ever sees your own domain, and\n * the sandbox URL (which rotates across resumes) stays server-side.\n */\nexport function createSandboxHandler(options: CreateSandboxHandlerOptions): (request: Request) => Promise<Response> {\n assertServerOnly();\n\n let cachedUrl: Promise<string> | null = null;\n\n const forward = async (request: Request, baseUrl: string): Promise<Response> => {\n const incoming = new URL(request.url);\n const target = new URL(incoming.pathname + incoming.search, baseUrl);\n\n const headers = new Headers(request.headers);\n headers.delete('host');\n if (options.secret) {\n headers.set('x-mastra-sandbox-secret', options.secret);\n }\n\n const response = await fetch(target, {\n method: request.method,\n headers,\n body: request.body,\n // duplex is required by Node's fetch for streamed request bodies\n duplex: 'half',\n redirect: 'manual',\n } as RequestInit);\n\n // Redirects are passed through manually — rewrite sandbox-host Locations\n // onto the incoming origin so the rotating sandbox URL never reaches the\n // browser (and subsequent requests keep flowing through this handler).\n const location = response.headers.get('location');\n if (location) {\n const resolved = new URL(location, target);\n if (resolved.origin === new URL(baseUrl).origin) {\n const rewritten = new URL(resolved.pathname + resolved.search + resolved.hash, incoming.origin);\n const responseHeaders = new Headers(response.headers);\n responseHeaders.set('location', rewritten.toString());\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n }\n }\n\n return response;\n };\n\n return async (request: Request): Promise<Response> => {\n cachedUrl ??= options.resolve();\n\n try {\n return await forward(request, await cachedUrl);\n } catch (error) {\n // Connection-level failure: the sandbox may have rotated its URL or gone\n // to sleep. Drop the cached URL so the next request re-resolves, and\n // retry once — but only for idempotent, bodyless methods. A failed\n // connection doesn't prove a write never landed, and a streamed body is\n // already consumed.\n cachedUrl = null;\n if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {\n throw error;\n }\n cachedUrl = options.resolve();\n try {\n return await forward(request, await cachedUrl);\n } catch (retryError) {\n cachedUrl = null;\n throw retryError;\n }\n }\n };\n}\n\nexport interface CreateSandboxProxyOptions {\n /** Edge Config item key that holds the current sandbox URL. */\n key: string;\n /**\n * Edge Config connection string (`https://edge-config.vercel.com/ecfg_...?token=...`).\n * Defaults to `process.env.EDGE_CONFIG`.\n */\n edgeConfig?: string;\n /** Shared secret attached as the `x-mastra-sandbox-secret` header on the rewrite. */\n secret?: string;\n}\n\n/**\n * Next.js middleware helper for Tier 3 routing: reads the current sandbox URL\n * from Edge Config (kept fresh by the deployer's `alias` option) and rewrites\n * the request to it. Returns `undefined` when no URL is configured so the\n * request falls through.\n *\n * ```typescript\n * // middleware.ts\n * export const middleware = createSandboxProxy({ key: 'my-preview' });\n * export const config = { matcher: '/api/:path*' };\n * ```\n */\nexport function createSandboxProxy(\n options: CreateSandboxProxyOptions,\n): (request: Request) => Promise<Response | undefined> {\n // Reads (and would transmit) the Edge Config bearer token — same\n // server-only contract as the rest of this module.\n assertServerOnly();\n\n return async (request: Request): Promise<Response | undefined> => {\n const connection = options.edgeConfig ?? process.env.EDGE_CONFIG;\n if (!connection) {\n throw new Error('createSandboxProxy requires an Edge Config connection string (EDGE_CONFIG).');\n }\n\n const conn = new URL(connection);\n const token = conn.searchParams.get('token');\n const itemUrl = new URL(`${conn.origin}${conn.pathname}/item/${encodeURIComponent(options.key)}`);\n\n const res = await fetch(itemUrl, { headers: { Authorization: `Bearer ${token}` } });\n if (!res.ok) {\n return undefined;\n }\n const sandboxUrl: unknown = await res.json();\n if (typeof sandboxUrl !== 'string' || !sandboxUrl) {\n return undefined;\n }\n\n const incoming = new URL(request.url);\n const target = new URL(incoming.pathname + incoming.search, sandboxUrl);\n\n // A Response with the x-middleware-rewrite header is how Next.js\n // middleware expresses a rewrite (NextResponse.rewrite does the same) —\n // this keeps the helper free of a next dependency.\n const headers = new Headers({ 'x-middleware-rewrite': target.toString() });\n if (options.secret) {\n headers.set('x-middleware-request-x-mastra-sandbox-secret', options.secret);\n headers.set('x-middleware-override-headers', 'x-mastra-sandbox-secret');\n }\n return new Response(null, { headers });\n };\n}\n"]}
1
+ {"version":3,"file":"index.cjs","names":["DEFAULT_PORT","tailServerLog","resolveRemoteDir","waitForHealthy","killPreviousServer","launchServer","getInfoSafe"],"sources":["../../src/client/index.ts"],"sourcesContent":["/**\n * Runtime resolver + routing helpers for sandbox deployments.\n *\n * SERVER-ONLY. This module resolves sandbox URLs using provider credentials\n * (e.g. VERCEL_TOKEN) — importing it in the browser would ship those\n * credentials to the client. Use the proxy/handler patterns instead so the\n * browser only ever talks to your own domain.\n */\nimport { supportsNetworking } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport {\n DEFAULT_PORT,\n getInfoSafe,\n killPreviousServer,\n launchServer,\n resolveRemoteDir,\n tailServerLog,\n waitForHealthy,\n} from '../shared';\n\nfunction assertServerOnly(): void {\n if (typeof (globalThis as { window?: unknown }).window !== 'undefined') {\n throw new Error(\n '@mastra/deployer-sandbox/client is server-only: resolving a sandbox requires provider credentials ' +\n 'that must never reach the browser. Proxy requests through your own backend instead ' +\n '(see createSandboxHandler / createSandboxProxy).',\n );\n }\n}\n\nexport type DeploymentStatus = 'running' | 'stopped' | 'unknown';\n\nexport interface GetDeploymentOptions {\n /**\n * The sandbox to resolve. Provider construction is identity — e.g.\n * `new VercelSandbox({ sandboxName: 'my-preview', ports: [4111] })` resolves\n * the same sandbox from any process.\n */\n sandbox: WorkspaceSandbox;\n /** Port the Mastra server listens on. Defaults to 4111. */\n port?: number;\n /**\n * Wake the sandbox when it is not running. Waking starts (resumes) the\n * sandbox and, only if the server is not answering, relaunches it from the\n * recorded launch script — some providers (e.g. E2B) resume processes on\n * wake, others (e.g. Vercel) restore just the filesystem. Defaults to false.\n */\n wake?: boolean;\n /** Directory the app was deployed into. Defaults to `$HOME/mastra-app` resolved inside the sandbox. */\n remoteDir?: string;\n /** Path polled for health. Defaults to `/api`. */\n healthCheckPath?: string;\n /** Max time to wait for health after a wake, in ms. Defaults to 60000. */\n healthCheckTimeoutMs?: number;\n}\n\nexport interface ResolvedDeployment {\n /** Public URL of the Mastra server, or null when it could not be resolved without waking. */\n url: string | null;\n status: DeploymentStatus;\n /** When the sandbox will auto-shutdown (when known). */\n expiresAt?: Date;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n logs(lines?: number): Promise<string>;\n}\n\n/**\n * Resolve (and optionally wake) a sandbox deployment.\n *\n * With `wake: false` (default) the sandbox is not started: the URL is resolved\n * only if the sandbox is already running in this process, otherwise\n * `{ url: null, status: 'stopped' | 'unknown' }` is returned and the caller\n * decides whether to wake.\n *\n * With `wake: true` the sandbox is started (providers resume by identity,\n * e.g. name), the server is relaunched if it is not answering, and the\n * deployment is returned once healthy.\n */\nexport async function getDeployment(options: GetDeploymentOptions): Promise<ResolvedDeployment> {\n assertServerOnly();\n\n const {\n sandbox,\n port = DEFAULT_PORT,\n wake = false,\n healthCheckPath = '/api',\n healthCheckTimeoutMs = 60_000,\n } = options;\n\n const handle = (url: string | null, status: DeploymentStatus, expiresAt?: Date): ResolvedDeployment => ({\n url,\n status,\n expiresAt,\n stop: async () => {\n await sandbox.stop?.();\n },\n destroy: async () => {\n await sandbox.destroy?.();\n },\n // Resolved lazily — reading logs requires a running sandbox anyway.\n logs: async (lines?: number) => tailServerLog(sandbox, await resolveRemoteDir(sandbox, options.remoteDir), lines),\n });\n\n if (!wake) {\n // Resolve without starting the sandbox (starting can resume billing).\n const url = supportsNetworking(sandbox) ? await sandbox.networking.getPortUrl(port) : null;\n if (!url) {\n return handle(null, 'stopped');\n }\n const healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: 3_000, intervalMs: 1_000 });\n return handle(url, healthy ? 'running' : 'stopped');\n }\n\n await sandbox.start?.();\n\n if (!supportsNetworking(sandbox)) {\n throw new Error(`Sandbox provider \"${sandbox.provider}\" does not support networking (public port URLs).`);\n }\n const url = await sandbox.networking.getPortUrl(port);\n if (!url) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" did not expose a public URL for port ${port}. ` +\n `Make sure the port is declared when constructing the sandbox (e.g. \\`ports: [${port}]\\`).`,\n );\n }\n\n // Some providers (e.g. Vercel) restore the filesystem but not processes on\n // resume, while others (e.g. E2B) resume processes too — relaunch the server\n // from the recorded launch script only when it is not answering.\n let healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: 3_000, intervalMs: 1_000 });\n if (!healthy) {\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n await killPreviousServer(sandbox, remoteDir);\n await launchServer(sandbox, remoteDir);\n healthy = await waitForHealthy(url, { path: healthCheckPath, timeoutMs: healthCheckTimeoutMs, intervalMs: 1_000 });\n }\n if (!healthy) {\n const log = await resolveRemoteDir(sandbox, options.remoteDir)\n .then(dir => tailServerLog(sandbox, dir))\n .catch(() => '');\n throw new Error(\n `Woke sandbox but the Mastra server did not become healthy at ${url}${healthCheckPath}.` +\n (log ? `\\n\\nServer log:\\n${log}` : ''),\n );\n }\n\n const info = await getInfoSafe(sandbox);\n return handle(url, 'running', info?.timeoutAt);\n}\n\n// =============================================================================\n// Tier 3 helpers\n// =============================================================================\n\nexport interface CreateSandboxHandlerOptions {\n /**\n * Resolve the current sandbox URL. Called once, cached, and re-invoked when\n * a forwarded request fails at the network level (e.g. the sandbox rotated\n * its URL or went to sleep). Typically wraps `getDeployment`:\n *\n * ```typescript\n * createSandboxHandler({\n * resolve: async () => {\n * const dep = await getDeployment({ sandbox, wake: true });\n * return dep.url!;\n * },\n * });\n * ```\n */\n resolve: () => Promise<string>;\n /** Shared secret attached as the `x-mastra-sandbox-secret` header on forwarded requests. */\n secret?: string;\n}\n\n/**\n * Framework-free route-handler proxy (fetch `Request` → `Response`). Mount it\n * as a catch-all API route; the browser only ever sees your own domain, and\n * the sandbox URL (which rotates across resumes) stays server-side.\n */\nexport function createSandboxHandler(options: CreateSandboxHandlerOptions): (request: Request) => Promise<Response> {\n assertServerOnly();\n\n let cachedUrl: Promise<string> | null = null;\n\n const forward = async (request: Request, baseUrl: string): Promise<Response> => {\n const incoming = new URL(request.url);\n const target = new URL(incoming.pathname + incoming.search, baseUrl);\n\n const headers = new Headers(request.headers);\n headers.delete('host');\n if (options.secret) {\n headers.set('x-mastra-sandbox-secret', options.secret);\n }\n\n const response = await fetch(target, {\n method: request.method,\n headers,\n body: request.body,\n // duplex is required by Node's fetch for streamed request bodies\n duplex: 'half',\n redirect: 'manual',\n } as RequestInit);\n\n // Redirects are passed through manually — rewrite sandbox-host Locations\n // onto the incoming origin so the rotating sandbox URL never reaches the\n // browser (and subsequent requests keep flowing through this handler).\n const location = response.headers.get('location');\n if (location) {\n const resolved = new URL(location, target);\n if (resolved.origin === new URL(baseUrl).origin) {\n const rewritten = new URL(resolved.pathname + resolved.search + resolved.hash, incoming.origin);\n const responseHeaders = new Headers(response.headers);\n responseHeaders.set('location', rewritten.toString());\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n }\n }\n\n return response;\n };\n\n return async (request: Request): Promise<Response> => {\n cachedUrl ??= options.resolve();\n\n try {\n return await forward(request, await cachedUrl);\n } catch (error) {\n // Connection-level failure: the sandbox may have rotated its URL or gone\n // to sleep. Drop the cached URL so the next request re-resolves, and\n // retry once — but only for idempotent, bodyless methods. A failed\n // connection doesn't prove a write never landed, and a streamed body is\n // already consumed.\n cachedUrl = null;\n if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {\n throw error;\n }\n cachedUrl = options.resolve();\n try {\n return await forward(request, await cachedUrl);\n } catch (retryError) {\n cachedUrl = null;\n throw retryError;\n }\n }\n };\n}\n\nexport interface CreateSandboxProxyOptions {\n /** Edge Config item key that holds the current sandbox URL. */\n key: string;\n /**\n * Edge Config connection string (`https://edge-config.vercel.com/ecfg_...?token=...`).\n * Defaults to `process.env.EDGE_CONFIG`.\n */\n edgeConfig?: string;\n /** Shared secret attached as the `x-mastra-sandbox-secret` header on the rewrite. */\n secret?: string;\n}\n\n/**\n * Next.js middleware helper for Tier 3 routing: reads the current sandbox URL\n * from Edge Config (kept fresh by the deployer's `alias` option) and rewrites\n * the request to it. Returns `undefined` when no URL is configured so the\n * request falls through.\n *\n * ```typescript\n * // middleware.ts\n * export const middleware = createSandboxProxy({ key: 'my-preview' });\n * export const config = { matcher: '/api/:path*' };\n * ```\n */\nexport function createSandboxProxy(\n options: CreateSandboxProxyOptions,\n): (request: Request) => Promise<Response | undefined> {\n // Reads (and would transmit) the Edge Config bearer token — same\n // server-only contract as the rest of this module.\n assertServerOnly();\n\n return async (request: Request): Promise<Response | undefined> => {\n const connection = options.edgeConfig ?? process.env.EDGE_CONFIG;\n if (!connection) {\n throw new Error('createSandboxProxy requires an Edge Config connection string (EDGE_CONFIG).');\n }\n\n const conn = new URL(connection);\n const token = conn.searchParams.get('token');\n const itemUrl = new URL(`${conn.origin}${conn.pathname}/item/${encodeURIComponent(options.key)}`);\n\n const res = await fetch(itemUrl, { headers: { Authorization: `Bearer ${token}` } });\n if (!res.ok) {\n return undefined;\n }\n const sandboxUrl: unknown = await res.json();\n if (typeof sandboxUrl !== 'string' || !sandboxUrl) {\n return undefined;\n }\n\n const incoming = new URL(request.url);\n const target = new URL(incoming.pathname + incoming.search, sandboxUrl);\n\n // A Response with the x-middleware-rewrite header is how Next.js\n // middleware expresses a rewrite (NextResponse.rewrite does the same) —\n // this keeps the helper free of a next dependency.\n const headers = new Headers({ 'x-middleware-rewrite': target.toString() });\n if (options.secret) {\n headers.set('x-middleware-request-x-mastra-sandbox-secret', options.secret);\n headers.set('x-middleware-override-headers', 'x-mastra-sandbox-secret');\n }\n return new Response(null, { headers });\n };\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,SAAS,mBAAyB;CAChC,IAAI,OAAQ,WAAoC,WAAW,aACzD,MAAM,IAAI,MACR,uOAGF;AAEJ;;;;;;;;;;;;;AAmDA,eAAsB,cAAc,SAA4D;CAC9F,iBAAiB;CAEjB,MAAM,EACJ,SACA,OAAOA,eAAAA,cACP,OAAO,OACP,kBAAkB,QAClB,uBAAuB,QACrB;CAEJ,MAAM,UAAU,KAAoB,QAA0B,eAA0C;EACtG;EACA;EACA;EACA,MAAM,YAAY;GAChB,MAAM,QAAQ,OAAO;EACvB;EACA,SAAS,YAAY;GACnB,MAAM,QAAQ,UAAU;EAC1B;EAEA,MAAM,OAAO,UAAmBC,eAAAA,cAAc,SAAS,MAAMC,eAAAA,iBAAiB,SAAS,QAAQ,SAAS,GAAG,KAAK;CAClH;CAEA,IAAI,CAAC,MAA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