@mastra/deployer-sandbox 0.0.0 → 0.1.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 (60) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/LICENSE.md +30 -0
  3. package/dist/alias.d.ts +10 -0
  4. package/dist/alias.d.ts.map +1 -0
  5. package/dist/chunk-CSXC6CZL.cjs +115 -0
  6. package/dist/chunk-CSXC6CZL.cjs.map +1 -0
  7. package/dist/chunk-Z636GNUQ.js +101 -0
  8. package/dist/chunk-Z636GNUQ.js.map +1 -0
  9. package/dist/client/index.cjs +159 -0
  10. package/dist/client/index.cjs.map +1 -0
  11. package/dist/client/index.d.ts +98 -0
  12. package/dist/client/index.d.ts.map +1 -0
  13. package/dist/client/index.js +155 -0
  14. package/dist/client/index.js.map +1 -0
  15. package/dist/deployer.d.ts +57 -0
  16. package/dist/deployer.d.ts.map +1 -0
  17. package/dist/engine.d.ts +19 -0
  18. package/dist/engine.d.ts.map +1 -0
  19. package/dist/index.cjs +381 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +6 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +372 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/manifest.d.ts +7 -0
  26. package/dist/manifest.d.ts.map +1 -0
  27. package/dist/shared.d.ts +63 -0
  28. package/dist/shared.d.ts.map +1 -0
  29. package/dist/studio/assets/CommitMono-400-Regular-DzkyLZ26.woff2 +0 -0
  30. package/dist/studio/assets/CommitMono-700-Regular-DmOSN4kd.woff2 +0 -0
  31. package/dist/studio/assets/MonaSans-VariableFont_wdth-wght-CX-7s9jm.ttf +0 -0
  32. package/dist/studio/assets/babel-lWBcy2sH.js +16 -0
  33. package/dist/studio/assets/bash-atvbtKCR.js +1 -0
  34. package/dist/studio/assets/core-CBT9ED6Q.js +12 -0
  35. package/dist/studio/assets/engine-compile-BkERmzkH.js +137 -0
  36. package/dist/studio/assets/engine-javascript-CSIo_1eZ.js +1 -0
  37. package/dist/studio/assets/estree-Dd9JfUIE.js +44 -0
  38. package/dist/studio/assets/github-dark-DHJKELXO.js +1 -0
  39. package/dist/studio/assets/github-light-DAi9KRSo.js +1 -0
  40. package/dist/studio/assets/index-CORJOrgI.js +2 -0
  41. package/dist/studio/assets/index-yUiD89B4.js +1 -0
  42. package/dist/studio/assets/javascript-ySlJ1b_l.js +1 -0
  43. package/dist/studio/assets/json-BQoSv7ci.js +1 -0
  44. package/dist/studio/assets/jsx-BAng5TT0.js +1 -0
  45. package/dist/studio/assets/livekit-client.esm-CKIgC2IJ.js +39 -0
  46. package/dist/studio/assets/main-BYaOwSFl.js +784 -0
  47. package/dist/studio/assets/markdown-UIAJJxZW.js +1 -0
  48. package/dist/studio/assets/preload-helper-PPVm8Dsz.js +1 -0
  49. package/dist/studio/assets/python-DhUJRlN_.js +1 -0
  50. package/dist/studio/assets/shell-CjFT_Tl9.js +1 -0
  51. package/dist/studio/assets/standalone-Dfz2oS5J.js +29 -0
  52. package/dist/studio/assets/style-DMLmyAwy.css +1 -0
  53. package/dist/studio/assets/tsx-B6W0miNI.js +1 -0
  54. package/dist/studio/assets/typescript-Dj6nwHGl.js +1 -0
  55. package/dist/studio/index.html +100 -0
  56. package/dist/studio/mastra.svg +17 -0
  57. package/dist/studio/routes-manifest.json +27 -0
  58. package/dist/types.d.ts +90 -0
  59. package/dist/types.d.ts.map +1 -0
  60. package/package.json +18 -18
package/dist/index.js ADDED
@@ -0,0 +1,372 @@
1
+ import { DEFAULT_PORT, resolveRemoteDir, runInSandbox, shellQuote, killPreviousServer, INSTALL_MARKER, SERVER_SCRIPT, launchServer, waitForHealthy, tailServerLog, getInfoSafe, SERVER_PIDFILE, SERVER_LOGFILE } from './chunk-Z636GNUQ.js';
2
+ import { mkdtemp, readFile, rm, writeFile, access } from 'fs/promises';
3
+ import { join, dirname } from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import { Deployer } from '@mastra/deployer';
6
+ import { copy } from 'fs-extra/esm';
7
+ import { execFile } from 'child_process';
8
+ import { createHash } from 'crypto';
9
+ import { existsSync } from 'fs';
10
+ import { tmpdir } from 'os';
11
+ import { promisify } from 'util';
12
+ import { supportsNetworking } from '@mastra/core/workspace';
13
+
14
+ // src/alias.ts
15
+ async function updateEdgeConfigAlias(options) {
16
+ const { token, teamId } = options;
17
+ if (!token) {
18
+ throw new Error("Updating the Edge Config alias requires a Vercel API token. Pass `alias.token`.");
19
+ }
20
+ const endpoint = new URL(`https://api.vercel.com/v1/edge-config/${options.edgeConfigId}/items`);
21
+ if (teamId) {
22
+ endpoint.searchParams.set("teamId", teamId);
23
+ }
24
+ const res = await fetch(endpoint, {
25
+ method: "PATCH",
26
+ headers: {
27
+ Authorization: `Bearer ${token}`,
28
+ "Content-Type": "application/json"
29
+ },
30
+ body: JSON.stringify({
31
+ items: [{ operation: "upsert", key: options.key, value: options.url }]
32
+ }),
33
+ // Bounded so a hung Vercel API request can't keep `mastra build` open
34
+ // after the sandbox itself is already deployed.
35
+ signal: AbortSignal.timeout(3e4)
36
+ });
37
+ if (!res.ok) {
38
+ const body = await res.text().catch(() => "");
39
+ throw new Error(`Failed to update Edge Config alias "${options.key}" (${res.status}): ${body}`);
40
+ }
41
+ }
42
+ var execFileAsync = promisify(execFile);
43
+ var noopLogger = {
44
+ debug: () => {
45
+ },
46
+ info: () => {
47
+ },
48
+ warn: () => {
49
+ },
50
+ error: () => {
51
+ }
52
+ };
53
+ var UPLOAD_CHUNK_SIZE = 96e3;
54
+ async function deployToSandbox(options) {
55
+ const {
56
+ sandbox,
57
+ dir,
58
+ port = DEFAULT_PORT,
59
+ env = {},
60
+ studio = false,
61
+ healthCheckPath = "/api",
62
+ healthCheckTimeoutMs = 6e4,
63
+ healthCheckIntervalMs = 1e3,
64
+ installCommand = "npm install --omit=dev",
65
+ logger = noopLogger
66
+ } = options;
67
+ if (!existsSync(join(dir, "index.mjs"))) {
68
+ throw new Error(`No index.mjs found in "${dir}" \u2014 did the build succeed?`);
69
+ }
70
+ logger.info(`Starting ${sandbox.provider} sandbox...`);
71
+ await sandbox.start?.();
72
+ if (!supportsNetworking(sandbox)) {
73
+ throw new Error(
74
+ `Sandbox provider "${sandbox.provider}" does not support networking (public port URLs), which is required for sandbox deploys.`
75
+ );
76
+ }
77
+ if (!sandbox.executeCommand) {
78
+ throw new Error(
79
+ `Sandbox provider "${sandbox.provider}" does not support executeCommand, which is required for sandbox deploys.`
80
+ );
81
+ }
82
+ const url = await sandbox.networking.getPortUrl(port);
83
+ if (!url) {
84
+ throw new Error(
85
+ `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}]\`).`
86
+ );
87
+ }
88
+ const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);
89
+ const mergedEnv = { ...env };
90
+ if (studio && mergedEnv.MASTRA_STUDIO_PATH === void 0) {
91
+ mergedEnv.MASTRA_STUDIO_PATH = `${remoteDir}/studio`;
92
+ }
93
+ logger.info(`Uploading build output from ${dir}...`);
94
+ const tarball = await createTarball(dir);
95
+ logger.debug(`Tarball size: ${(tarball.length / 1024 / 1024).toFixed(2)} MB`);
96
+ const remoteTarball = `${remoteDir}/.deploy.tgz`;
97
+ await runInSandbox(sandbox, `mkdir -p ${shellQuote(remoteDir)}`);
98
+ await uploadFile(sandbox, remoteTarball, tarball);
99
+ await killPreviousServer(sandbox, remoteDir);
100
+ await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && tar -xzf .deploy.tgz && rm -f .deploy.tgz`, {
101
+ timeout: 12e4
102
+ });
103
+ const installHash = await hashInstallInputs(dir, installCommand);
104
+ const marker = `${remoteDir}/${INSTALL_MARKER}`;
105
+ const markerCheck = await runInSandbox(sandbox, `cat ${shellQuote(marker)} 2>/dev/null || true`, {
106
+ allowFailure: true
107
+ });
108
+ if (installHash && markerCheck.stdout.trim() === installHash) {
109
+ logger.info("Dependencies unchanged \u2014 skipping install.");
110
+ } else {
111
+ logger.info(`Installing dependencies (${installCommand})...`);
112
+ await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && ${installCommand}`, {
113
+ timeout: 6e5,
114
+ label: `install dependencies (${installCommand})`
115
+ });
116
+ if (installHash) {
117
+ await runInSandbox(sandbox, `printf '%s' ${shellQuote(installHash)} > ${shellQuote(marker)}`);
118
+ }
119
+ }
120
+ const launchScript = buildLaunchScript({ remoteDir, port, env: mergedEnv });
121
+ await uploadFile(sandbox, `${remoteDir}/${SERVER_SCRIPT}`, Buffer.from(launchScript));
122
+ await runInSandbox(sandbox, `chmod 700 ${shellQuote(`${remoteDir}/${SERVER_SCRIPT}`)}`);
123
+ logger.info("Starting Mastra server...");
124
+ await launchServer(sandbox, remoteDir);
125
+ const healthy = await waitForHealthy(url, {
126
+ path: healthCheckPath,
127
+ timeoutMs: healthCheckTimeoutMs,
128
+ intervalMs: healthCheckIntervalMs
129
+ });
130
+ if (!healthy) {
131
+ const log = await tailServerLog(sandbox, remoteDir).catch(() => "");
132
+ throw new Error(
133
+ `Mastra server did not become healthy at ${url}${healthCheckPath} within ${healthCheckTimeoutMs}ms.` + (log ? `
134
+
135
+ Server log:
136
+ ${log}` : "\n\n(no server log output captured)")
137
+ );
138
+ }
139
+ const info = await getInfoSafe(sandbox);
140
+ return {
141
+ url,
142
+ sandboxId: info?.id ?? sandbox.id,
143
+ expiresAt: info?.timeoutAt,
144
+ stop: async () => {
145
+ await sandbox.stop?.();
146
+ },
147
+ destroy: async () => {
148
+ await sandbox.destroy?.();
149
+ },
150
+ logs: (lines) => tailServerLog(sandbox, remoteDir, lines)
151
+ };
152
+ }
153
+ function buildLaunchScript(opts) {
154
+ const lines = ["#!/bin/sh", `cd ${shellQuote(opts.remoteDir)}`];
155
+ const env = {
156
+ MASTRA_AUTO_DETECT_URL: "true",
157
+ ...opts.env,
158
+ PORT: String(opts.port),
159
+ MASTRA_HOST: "0.0.0.0"
160
+ };
161
+ for (const [key, value] of Object.entries(env)) {
162
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
163
+ throw new Error(`Invalid environment variable name: "${key}"`);
164
+ }
165
+ lines.push(`export ${key}=${shellQuote(value)}`);
166
+ }
167
+ lines.push(`echo $$ > ${shellQuote(SERVER_PIDFILE)}`);
168
+ lines.push(`exec node index.mjs >> ${shellQuote(SERVER_LOGFILE)} 2>&1`);
169
+ return lines.join("\n") + "\n";
170
+ }
171
+ async function createTarball(dir) {
172
+ const tmp = await mkdtemp(join(tmpdir(), "mastra-sandbox-"));
173
+ const tarPath = join(tmp, "deploy.tgz");
174
+ try {
175
+ await execFileAsync("tar", ["-czf", tarPath, "--exclude=node_modules", "-C", dir, "."]);
176
+ return await readFile(tarPath);
177
+ } finally {
178
+ await rm(tmp, { recursive: true, force: true });
179
+ }
180
+ }
181
+ async function uploadFile(sandbox, remotePath, content) {
182
+ if (sandbox.writeFiles) {
183
+ await sandbox.writeFiles([{ path: remotePath, content }]);
184
+ return;
185
+ }
186
+ const b64 = content.toString("base64");
187
+ const tmpPath = `${remotePath}.b64`;
188
+ await runInSandbox(sandbox, `rm -f ${shellQuote(tmpPath)}`);
189
+ for (let i = 0; i < b64.length; i += UPLOAD_CHUNK_SIZE) {
190
+ const chunk = b64.slice(i, i + UPLOAD_CHUNK_SIZE);
191
+ await runInSandbox(sandbox, `printf '%s' ${shellQuote(chunk)} >> ${shellQuote(tmpPath)}`, {
192
+ label: `upload chunk to ${remotePath}`
193
+ });
194
+ }
195
+ await runInSandbox(
196
+ sandbox,
197
+ `base64 -d ${shellQuote(tmpPath)} > ${shellQuote(remotePath)} && rm -f ${shellQuote(tmpPath)}`,
198
+ { label: `decode upload at ${remotePath}` }
199
+ );
200
+ }
201
+ var LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock"];
202
+ async function hashInstallInputs(dir, installCommand) {
203
+ const hash = createHash("sha256");
204
+ try {
205
+ hash.update(await readFile(join(dir, "package.json")));
206
+ } catch {
207
+ return null;
208
+ }
209
+ for (const lockfile of LOCKFILES) {
210
+ let content;
211
+ try {
212
+ content = await readFile(join(dir, lockfile));
213
+ } catch {
214
+ continue;
215
+ }
216
+ hash.update(lockfile).update(content);
217
+ }
218
+ hash.update(installCommand);
219
+ return hash.digest("hex");
220
+ }
221
+ var MANIFEST_FILENAME = "sandbox-deployment.json";
222
+ async function writeDeploymentManifest(outputDir, manifest) {
223
+ await writeFile(join(outputDir, MANIFEST_FILENAME), JSON.stringify(manifest, null, 2));
224
+ }
225
+ async function readDeploymentManifest(outputDir) {
226
+ let raw;
227
+ try {
228
+ raw = await readFile(join(outputDir, MANIFEST_FILENAME), "utf-8");
229
+ } catch (error) {
230
+ if (error.code === "ENOENT") {
231
+ return null;
232
+ }
233
+ throw error;
234
+ }
235
+ return JSON.parse(raw);
236
+ }
237
+
238
+ // src/deployer.ts
239
+ var SandboxDeployer = class extends Deployer {
240
+ /** Sandbox deploys are push-style: `mastra build` runs `deploy()` after bundling. */
241
+ deployOnBuild = true;
242
+ sandbox;
243
+ port;
244
+ studio;
245
+ /** Explicit remote dir, when configured. The engine defaults to `$HOME/mastra-app` inside the sandbox. */
246
+ remoteDir;
247
+ env;
248
+ alias;
249
+ healthCheckTimeoutMs;
250
+ constructor(options) {
251
+ super({ name: "SANDBOX" });
252
+ this.sandbox = options.sandbox;
253
+ this.port = options.port ?? DEFAULT_PORT;
254
+ this.studio = options.studio ?? true;
255
+ this.remoteDir = options.remoteDir;
256
+ this.env = options.env ?? {};
257
+ this.alias = options.alias;
258
+ this.healthCheckTimeoutMs = options.healthCheckTimeoutMs;
259
+ }
260
+ /**
261
+ * Merge all existing env files instead of only the first one (base behavior).
262
+ * Later files win in `loadEnvVars()`, so order least → most specific: a
263
+ * `.env.local` written by `vercel env pull` shouldn't shadow the `.env` that
264
+ * holds the app's own keys.
265
+ */
266
+ async getEnvFiles() {
267
+ const candidates = [".env", ".env.production", ".env.local"];
268
+ const existing = [];
269
+ for (const file of candidates) {
270
+ try {
271
+ await access(file);
272
+ existing.push(file);
273
+ } catch {
274
+ }
275
+ }
276
+ return existing;
277
+ }
278
+ async getUserBundlerOptions(mastraEntryFile, outputDirectory) {
279
+ const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);
280
+ return {
281
+ ...bundlerOptions,
282
+ externals: true
283
+ };
284
+ }
285
+ getEntry() {
286
+ return `
287
+ // @ts-expect-error
288
+ import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';
289
+ import { mastra } from '#mastra';
290
+ import { createNodeServer, getToolExports } from '#server';
291
+ import { tools } from '#tools';
292
+
293
+ // @ts-expect-error
294
+ await createNodeServer(mastra, { tools: getToolExports(tools), studio: ${this.studio} });
295
+
296
+ const storage = mastra.getStorage();
297
+ if (storage) {
298
+ if (!storage.disableInit) {
299
+ storage.init();
300
+ }
301
+ mastra.__registerInternalWorkflow(scoreTracesWorkflow);
302
+ }
303
+ `;
304
+ }
305
+ async prepare(outputDirectory) {
306
+ await super.prepare(outputDirectory);
307
+ if (this.studio) {
308
+ const __filename = fileURLToPath(import.meta.url);
309
+ const __dirname = dirname(__filename);
310
+ const studioSource = join(dirname(__dirname), "dist", "studio");
311
+ const studioServePath = join(outputDirectory, this.outputDir, "studio");
312
+ try {
313
+ await copy(studioSource, studioServePath, { overwrite: true });
314
+ } catch (err) {
315
+ throw new Error(
316
+ `Failed to copy studio assets from "${studioSource}" to "${studioServePath}": ${err instanceof Error ? err.message : err}`
317
+ );
318
+ }
319
+ }
320
+ }
321
+ async bundle(entryFile, outputDirectory, { toolsPaths, projectRoot }) {
322
+ return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot }, toolsPaths);
323
+ }
324
+ /**
325
+ * Deploy the built output into the sandbox and wait for the server to come
326
+ * up on its public URL. Writes `sandbox-deployment.json` into the output
327
+ * directory and updates the Edge Config alias when configured.
328
+ */
329
+ async deploy(outputDirectory) {
330
+ const dir = join(outputDirectory, this.outputDir);
331
+ const envVars = await this.loadEnvVars();
332
+ const env = { ...Object.fromEntries(envVars), ...this.env };
333
+ if (envVars.size > 0) {
334
+ this.logger.warn(
335
+ "Environment variables from your .env file are injected into the remote sandbox. Anyone with access to the sandbox can read them."
336
+ );
337
+ }
338
+ const deployment = await deployToSandbox({
339
+ sandbox: this.sandbox,
340
+ dir,
341
+ port: this.port,
342
+ env,
343
+ studio: this.studio,
344
+ remoteDir: this.remoteDir,
345
+ healthCheckTimeoutMs: this.healthCheckTimeoutMs,
346
+ logger: this.logger
347
+ });
348
+ await writeDeploymentManifest(dir, {
349
+ provider: this.sandbox.provider,
350
+ sandboxId: deployment.sandboxId,
351
+ url: deployment.url,
352
+ port: this.port,
353
+ deployedAt: (/* @__PURE__ */ new Date()).toISOString(),
354
+ expiresAt: deployment.expiresAt?.toISOString()
355
+ });
356
+ if (this.alias) {
357
+ await updateEdgeConfigAlias({ ...this.alias, url: deployment.url });
358
+ this.logger.info(`Edge Config alias "${this.alias.key}" now points at ${deployment.url}`);
359
+ }
360
+ this.logger.info(`Mastra server deployed: ${deployment.url}/api`);
361
+ if (this.studio) {
362
+ this.logger.info(`Studio: ${deployment.url}`);
363
+ }
364
+ if (deployment.expiresAt) {
365
+ this.logger.warn(`Sandbox expires at ${deployment.expiresAt.toISOString()} (provider runtime cap).`);
366
+ }
367
+ }
368
+ };
369
+
370
+ export { MANIFEST_FILENAME, SandboxDeployer, buildLaunchScript, deployToSandbox, readDeploymentManifest, updateEdgeConfigAlias, writeDeploymentManifest };
371
+ //# sourceMappingURL=index.js.map
372
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/alias.ts","../src/engine.ts","../src/manifest.ts","../src/deployer.ts"],"names":["join","readFile"],"mappings":";;;;;;;;;;;;;;AAOA,eAAsB,sBAAsB,OAAA,EAA+D;AACzG,EAAA,MAAM,EAAE,KAAA,EAAO,MAAA,EAAO,GAAI,OAAA;AAC1B,EAAA,IAAI,CAAC,K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C9C,CAAA;AAED,IAAA,IAAI,KAAK,KAAA,EAAO;AACd,MAAA,MAAM,qBAAA,CAAsB,EAAE,GAAG,IAAA,CAAK,OAAO,GAAA,EAAK,UAAA,CAAW,KAAK,CAAA;AAClE,MAAA,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA,mBAAA,EAAsB,IAAA,CAAK,MAAM,GAAG,CAAA,gBAAA,EAAmB,UAAA,CAAW,GAAG,CAAA,CAAE,CAAA;AAAA,IAC1F;AAEA,IAAA,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,CAAA,wBAAA,EAA2B,UAAA,CAAW,GAAG,CAAA,IAAA,CAAM,CAAA;AAChE,IAAA,IAAI,KAAK,MAAA,EAAQ;AACf,MAAA,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,CAAA,QAAA,EAAW,UAAA,CAAW,GAAG,CAAA,CAAE,CAAA;AAAA,IAC9C;AACA,IAAA,IAAI,WAAW,SAAA,EAAW;AACxB,MAAA,IAAA,CAAK,OAAO,IAAA,CAAK,CAAA,mBAAA,EAAsB,WAAW,SAAA,CAAU,WAAA,EAAa,CAAA,wBAAA,CAA0B,CAAA;AAAA,IACrG;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { SandboxAliasOptions } from './types';\n\n/**\n * Upsert a Vercel Edge Config item so a stable key always points at the\n * current sandbox URL. Used for Tier 3 routing: apps read the key from Edge\n * Config (e.g. in middleware) instead of hardcoding the rotating sandbox URL.\n */\nexport async function updateEdgeConfigAlias(options: SandboxAliasOptions & { url: string }): Promise<void> {\n const { token, teamId } = options;\n if (!token) {\n throw new Error('Updating the Edge Config alias requires a Vercel API token. Pass `alias.token`.');\n }\n\n const endpoint = new URL(`https://api.vercel.com/v1/edge-config/${options.edgeConfigId}/items`);\n if (teamId) {\n endpoint.searchParams.set('teamId', teamId);\n }\n\n const res = await fetch(endpoint, {\n method: 'PATCH',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n items: [{ operation: 'upsert', key: options.key, value: options.url }],\n }),\n // Bounded so a hung Vercel API request can't keep `mastra build` open\n // after the sandbox itself is already deployed.\n signal: AbortSignal.timeout(30_000),\n });\n\n if (!res.ok) {\n const body = await res.text().catch(() => '');\n throw new Error(`Failed to update Edge Config alias \"${options.key}\" (${res.status}): ${body}`);\n }\n}\n","import { execFile } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, readFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { supportsNetworking } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport {\n DEFAULT_PORT,\n INSTALL_MARKER,\n SERVER_LOGFILE,\n SERVER_PIDFILE,\n SERVER_SCRIPT,\n getInfoSafe,\n killPreviousServer,\n launchServer,\n resolveRemoteDir,\n runInSandbox,\n shellQuote,\n tailServerLog,\n waitForHealthy,\n} from './shared';\nimport type { DeployToSandboxOptions, SandboxDeployLogger, SandboxDeployment } from './types';\n\nconst execFileAsync = promisify(execFile);\n\nconst noopLogger: SandboxDeployLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/** Max shell-command payload per chunk for the base64 upload fallback. */\nconst UPLOAD_CHUNK_SIZE = 96_000;\n\n/**\n * Deploy a prebuilt Mastra server directory into any workspace sandbox that\n * supports networking. Provider-agnostic: only uses the core WorkspaceSandbox\n * contract (`executeCommand` + `networking`, with `writeFiles` / `processes`\n * as fast paths).\n */\nexport async function deployToSandbox(options: DeployToSandboxOptions): Promise<SandboxDeployment> {\n const {\n sandbox,\n dir,\n port = DEFAULT_PORT,\n env = {},\n studio = false,\n healthCheckPath = '/api',\n healthCheckTimeoutMs = 60_000,\n healthCheckIntervalMs = 1_000,\n installCommand = 'npm install --omit=dev',\n logger = noopLogger,\n } = options;\n\n if (!existsSync(join(dir, 'index.mjs'))) {\n throw new Error(`No index.mjs found in \"${dir}\" — did the build succeed?`);\n }\n\n // 1. Start (providers handle create-or-resume by identity, e.g. sandbox name).\n logger.info(`Starting ${sandbox.provider} sandbox...`);\n await sandbox.start?.();\n\n if (!supportsNetworking(sandbox)) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support networking (public port URLs), ` +\n `which is required for sandbox deploys.`,\n );\n }\n if (!sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support executeCommand, which is required for sandbox deploys.`,\n );\n }\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 // Default the remote dir to $HOME/mastra-app — home directories persist\n // across snapshot stop/resume (unlike /tmp), so wakes find the app intact.\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n\n const mergedEnv = { ...env };\n if (studio && mergedEnv.MASTRA_STUDIO_PATH === undefined) {\n mergedEnv.MASTRA_STUDIO_PATH = `${remoteDir}/studio`;\n }\n\n // 2. Upload the build output as a tarball and extract it in the sandbox.\n logger.info(`Uploading build output from ${dir}...`);\n const tarball = await createTarball(dir);\n logger.debug(`Tarball size: ${(tarball.length / 1024 / 1024).toFixed(2)} MB`);\n\n const remoteTarball = `${remoteDir}/.deploy.tgz`;\n await runInSandbox(sandbox, `mkdir -p ${shellQuote(remoteDir)}`);\n await uploadFile(sandbox, remoteTarball, tarball);\n\n // Stop the previous server BEFORE extracting over the live directory so it\n // can never serve a mix of old and new files while the release lands.\n await killPreviousServer(sandbox, remoteDir);\n\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && tar -xzf .deploy.tgz && rm -f .deploy.tgz`, {\n timeout: 120_000,\n });\n\n // 3. Install dependencies, skipped when the install inputs (package.json,\n // bundled lockfiles, and the install command itself) are unchanged since\n // the last completed install.\n const installHash = await hashInstallInputs(dir, installCommand);\n const marker = `${remoteDir}/${INSTALL_MARKER}`;\n const markerCheck = await runInSandbox(sandbox, `cat ${shellQuote(marker)} 2>/dev/null || true`, {\n allowFailure: true,\n });\n\n if (installHash && markerCheck.stdout.trim() === installHash) {\n logger.info('Dependencies unchanged — skipping install.');\n } else {\n logger.info(`Installing dependencies (${installCommand})...`);\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && ${installCommand}`, {\n timeout: 600_000,\n label: `install dependencies (${installCommand})`,\n });\n if (installHash) {\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(installHash)} > ${shellQuote(marker)}`);\n }\n }\n\n // 4. Write the launch script and start the new server (the previous one was\n // stopped before extraction).\n const launchScript = buildLaunchScript({ remoteDir, port, env: mergedEnv });\n await uploadFile(sandbox, `${remoteDir}/${SERVER_SCRIPT}`, Buffer.from(launchScript));\n await runInSandbox(sandbox, `chmod 700 ${shellQuote(`${remoteDir}/${SERVER_SCRIPT}`)}`);\n\n logger.info('Starting Mastra server...');\n await launchServer(sandbox, remoteDir);\n\n // 5. Wait for the server to answer on its public URL.\n const healthy = await waitForHealthy(url, {\n path: healthCheckPath,\n timeoutMs: healthCheckTimeoutMs,\n intervalMs: healthCheckIntervalMs,\n });\n if (!healthy) {\n const log = await tailServerLog(sandbox, remoteDir).catch(() => '');\n throw new Error(\n `Mastra server did not become healthy at ${url}${healthCheckPath} within ${healthCheckTimeoutMs}ms.` +\n (log ? `\\n\\nServer log:\\n${log}` : '\\n\\n(no server log output captured)'),\n );\n }\n\n const info = await getInfoSafe(sandbox);\n\n return {\n url,\n sandboxId: info?.id ?? sandbox.id,\n expiresAt: info?.timeoutAt,\n stop: async () => {\n await sandbox.stop?.();\n },\n destroy: async () => {\n await sandbox.destroy?.();\n },\n logs: (lines?: number) => tailServerLog(sandbox, remoteDir, lines),\n };\n}\n\n/**\n * Build the POSIX launch script. Re-running the script restarts the server —\n * the wake path uses this after a snapshot resume (which restores the\n * filesystem but not processes).\n */\nexport function buildLaunchScript(opts: { remoteDir: string; port: number; env: Record<string, string> }): string {\n const lines = ['#!/bin/sh', `cd ${shellQuote(opts.remoteDir)}`];\n\n // MASTRA_AUTO_DETECT_URL so Studio connects to the sandbox's public URL\n // (same origin) instead of localhost:4111 — overridable. PORT and\n // MASTRA_HOST are applied AFTER custom env: networking (`getPortUrl`) and\n // health checks target the configured port, and the server must bind\n // 0.0.0.0 to be reachable through the public port proxy. Change the port\n // via the deploy `port` option, not env.\n const env: Record<string, string> = {\n MASTRA_AUTO_DETECT_URL: 'true',\n ...opts.env,\n PORT: String(opts.port),\n MASTRA_HOST: '0.0.0.0',\n };\n for (const [key, value] of Object.entries(env)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n throw new Error(`Invalid environment variable name: \"${key}\"`);\n }\n lines.push(`export ${key}=${shellQuote(value)}`);\n }\n\n lines.push(`echo $$ > ${shellQuote(SERVER_PIDFILE)}`);\n lines.push(`exec node index.mjs >> ${shellQuote(SERVER_LOGFILE)} 2>&1`);\n return lines.join('\\n') + '\\n';\n}\n\n/** Create a gzipped tarball of the directory contents (excluding node_modules). */\nasync function createTarball(dir: string): Promise<Buffer> {\n const tmp = await mkdtemp(join(tmpdir(), 'mastra-sandbox-'));\n const tarPath = join(tmp, 'deploy.tgz');\n try {\n await execFileAsync('tar', ['-czf', tarPath, '--exclude=node_modules', '-C', dir, '.']);\n return await readFile(tarPath);\n } finally {\n await rm(tmp, { recursive: true, force: true });\n }\n}\n\n/**\n * Upload a file into the sandbox. Uses the provider's native `writeFiles` fast\n * path when available, otherwise falls back to base64 chunks over\n * `executeCommand` — so `executeCommand` + `networking` is the minimum contract.\n */\nasync function uploadFile(sandbox: WorkspaceSandbox, remotePath: string, content: Buffer): Promise<void> {\n if (sandbox.writeFiles) {\n await sandbox.writeFiles([{ path: remotePath, content }]);\n return;\n }\n\n const b64 = content.toString('base64');\n const tmpPath = `${remotePath}.b64`;\n await runInSandbox(sandbox, `rm -f ${shellQuote(tmpPath)}`);\n for (let i = 0; i < b64.length; i += UPLOAD_CHUNK_SIZE) {\n const chunk = b64.slice(i, i + UPLOAD_CHUNK_SIZE);\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(chunk)} >> ${shellQuote(tmpPath)}`, {\n label: `upload chunk to ${remotePath}`,\n });\n }\n await runInSandbox(\n sandbox,\n `base64 -d ${shellQuote(tmpPath)} > ${shellQuote(remotePath)} && rm -f ${shellQuote(tmpPath)}`,\n { label: `decode upload at ${remotePath}` },\n );\n}\n\n/** Lockfiles that, when present in the build output, participate in the install-skip hash. */\nconst LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock'];\n\n/**\n * Hash everything that determines the outcome of a dependency install:\n * package.json, any bundled lockfile, and the install command itself. A\n * matching hash means the previous `node_modules` can be reused.\n */\nasync function hashInstallInputs(dir: string, installCommand: string): Promise<string | null> {\n const hash = createHash('sha256');\n try {\n hash.update(await readFile(join(dir, 'package.json')));\n } catch {\n return null;\n }\n for (const lockfile of LOCKFILES) {\n let content: Buffer;\n try {\n content = await readFile(join(dir, lockfile));\n } catch {\n // Lockfile not part of the build output.\n continue;\n }\n hash.update(lockfile).update(content);\n }\n hash.update(installCommand);\n return hash.digest('hex');\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { SandboxDeploymentManifest } from './types';\n\nexport const MANIFEST_FILENAME = 'sandbox-deployment.json';\n\n/** Write `sandbox-deployment.json` into the build output directory. */\nexport async function writeDeploymentManifest(outputDir: string, manifest: SandboxDeploymentManifest): Promise<void> {\n await writeFile(join(outputDir, MANIFEST_FILENAME), JSON.stringify(manifest, null, 2));\n}\n\n/** Read `sandbox-deployment.json` from the build output directory, or null when absent. */\nexport async function readDeploymentManifest(outputDir: string): Promise<SandboxDeploymentManifest | null> {\n let raw: string;\n try {\n raw = await readFile(join(outputDir, MANIFEST_FILENAME), 'utf-8');\n } catch (error) {\n // Only \"no manifest\" maps to null — anything else (permissions, a\n // corrupted file, malformed JSON below) should surface, not be hidden.\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n return JSON.parse(raw) as SandboxDeploymentManifest;\n}\n","import { access } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { Deployer } from '@mastra/deployer';\nimport { copy } from 'fs-extra/esm';\nimport { updateEdgeConfigAlias } from './alias';\nimport { deployToSandbox } from './engine';\nimport { writeDeploymentManifest } from './manifest';\nimport { DEFAULT_PORT } from './shared';\nimport type { SandboxDeployerOptions } from './types';\n\n/**\n * Deploy a full Mastra server into any workspace sandbox that supports\n * networking (Vercel Sandbox, E2B, ...) and get a live public URL.\n *\n * Positioning: ephemeral environments — instant previews, PR/CI smoke deploys,\n * agent-built-app verification. Not production hosting.\n *\n * @example\n * ```typescript\n * import { SandboxDeployer } from '@mastra/deployer-sandbox';\n * import { VercelSandbox } from '@mastra/vercel';\n *\n * export const mastra = new Mastra({\n * deployer: new SandboxDeployer({\n * sandbox: new VercelSandbox({ sandboxName: 'my-preview', timeout: 3_600_000, ports: [4111] }),\n * }),\n * });\n * ```\n */\nexport class SandboxDeployer extends Deployer {\n /** Sandbox deploys are push-style: `mastra build` runs `deploy()` after bundling. */\n readonly deployOnBuild = true;\n readonly sandbox: WorkspaceSandbox;\n readonly port: number;\n readonly studio: boolean;\n /** Explicit remote dir, when configured. The engine defaults to `$HOME/mastra-app` inside the sandbox. */\n readonly remoteDir?: string;\n private readonly env: Record<string, string>;\n private readonly alias?: SandboxDeployerOptions['alias'];\n private readonly healthCheckTimeoutMs?: number;\n\n constructor(options: SandboxDeployerOptions) {\n super({ name: 'SANDBOX' });\n\n this.sandbox = options.sandbox;\n this.port = options.port ?? DEFAULT_PORT;\n this.studio = options.studio ?? true;\n this.remoteDir = options.remoteDir;\n this.env = options.env ?? {};\n this.alias = options.alias;\n this.healthCheckTimeoutMs = options.healthCheckTimeoutMs;\n }\n\n /**\n * Merge all existing env files instead of only the first one (base behavior).\n * Later files win in `loadEnvVars()`, so order least → most specific: a\n * `.env.local` written by `vercel env pull` shouldn't shadow the `.env` that\n * holds the app's own keys.\n */\n override async getEnvFiles(): Promise<string[]> {\n const candidates = ['.env', '.env.production', '.env.local'];\n const existing: string[] = [];\n for (const file of candidates) {\n try {\n await access(file);\n existing.push(file);\n } catch {\n // skip missing files\n }\n }\n return existing;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Dependencies are installed inside the sandbox, so keep them external.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n protected getEntry(): string {\n return `\n // @ts-expect-error\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n import { mastra } from '#mastra';\n import { createNodeServer, getToolExports } from '#server';\n import { tools } from '#tools';\n\n // @ts-expect-error\n await createNodeServer(mastra, { tools: getToolExports(tools), studio: ${this.studio} });\n\n const storage = mastra.getStorage();\n if (storage) {\n if (!storage.disableInit) {\n storage.init();\n }\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n `;\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioSource = join(dirname(__dirname), 'dist', 'studio');\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n\n try {\n await copy(studioSource, studioServePath, { overwrite: true });\n } catch (err) {\n throw new Error(\n `Failed to copy studio assets from \"${studioSource}\" to \"${studioServePath}\": ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot }, toolsPaths);\n }\n\n /**\n * Deploy the built output into the sandbox and wait for the server to come\n * up on its public URL. Writes `sandbox-deployment.json` into the output\n * directory and updates the Edge Config alias when configured.\n */\n async deploy(outputDirectory: string): Promise<void> {\n const dir = join(outputDirectory, this.outputDir);\n\n // Merge .env file vars under explicitly configured env.\n const envVars = await this.loadEnvVars();\n const env: Record<string, string> = { ...Object.fromEntries(envVars), ...this.env };\n if (envVars.size > 0) {\n this.logger.warn(\n 'Environment variables from your .env file are injected into the remote sandbox. ' +\n 'Anyone with access to the sandbox can read them.',\n );\n }\n\n const deployment = await deployToSandbox({\n sandbox: this.sandbox,\n dir,\n port: this.port,\n env,\n studio: this.studio,\n remoteDir: this.remoteDir,\n healthCheckTimeoutMs: this.healthCheckTimeoutMs,\n logger: this.logger,\n });\n\n await writeDeploymentManifest(dir, {\n provider: this.sandbox.provider,\n sandboxId: deployment.sandboxId,\n url: deployment.url,\n port: this.port,\n deployedAt: new Date().toISOString(),\n expiresAt: deployment.expiresAt?.toISOString(),\n });\n\n if (this.alias) {\n await updateEdgeConfigAlias({ ...this.alias, url: deployment.url });\n this.logger.info(`Edge Config alias \"${this.alias.key}\" now points at ${deployment.url}`);\n }\n\n this.logger.info(`Mastra server deployed: ${deployment.url}/api`);\n if (this.studio) {\n this.logger.info(`Studio: ${deployment.url}`);\n }\n if (deployment.expiresAt) {\n this.logger.warn(`Sandbox expires at ${deployment.expiresAt.toISOString()} (provider runtime cap).`);\n }\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { SandboxDeploymentManifest } from './types.js';
2
+ export declare const MANIFEST_FILENAME = "sandbox-deployment.json";
3
+ /** Write `sandbox-deployment.json` into the build output directory. */
4
+ export declare function writeDeploymentManifest(outputDir: string, manifest: SandboxDeploymentManifest): Promise<void>;
5
+ /** Read `sandbox-deployment.json` from the build output directory, or null when absent. */
6
+ export declare function readDeploymentManifest(outputDir: string): Promise<SandboxDeploymentManifest | null>;
7
+ //# sourceMappingURL=manifest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AAEzD,eAAO,MAAM,iBAAiB,4BAA4B,CAAC;AAE3D,uEAAuE;AACvE,wBAAsB,uBAAuB,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEnH;AAED,2FAA2F;AAC3F,wBAAsB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAazG"}
@@ -0,0 +1,63 @@
1
+ import type { SandboxInfo, WorkspaceSandbox } from '@mastra/core/workspace';
2
+ /** Directory name (under the sandbox user's home) that the app is deployed into by default. */
3
+ export declare const REMOTE_DIR_NAME = "mastra-app";
4
+ /** Default port the Mastra server listens on. */
5
+ export declare const DEFAULT_PORT = 4111;
6
+ /** Launch script written into the remote dir. Re-running it restarts the server (e.g. after a wake). */
7
+ export declare const SERVER_SCRIPT = ".mastra-server.sh";
8
+ /** Pidfile written by the launch script. */
9
+ export declare const SERVER_PIDFILE = ".mastra-server.pid";
10
+ /** Server log file inside the remote dir. */
11
+ export declare const SERVER_LOGFILE = ".mastra-server.log";
12
+ /** Marker recording the package.json hash of the last completed dependency install. */
13
+ export declare const INSTALL_MARKER = ".mastra-install-hash";
14
+ /** getInfo may be sync or async, and may throw — normalize to `undefined` on failure. */
15
+ export declare function getInfoSafe(sandbox: WorkspaceSandbox): Promise<SandboxInfo | undefined>;
16
+ /**
17
+ * Resolve the directory the app is (or will be) deployed into. Defaults to
18
+ * `$HOME/mastra-app` resolved inside the sandbox — home directories persist
19
+ * across snapshot stop/resume on providers that support it, unlike `/tmp`.
20
+ * The sandbox must be running.
21
+ */
22
+ export declare function resolveRemoteDir(sandbox: WorkspaceSandbox, remoteDir?: string): Promise<string>;
23
+ /** Single-quote a value for POSIX shells. */
24
+ export declare function shellQuote(value: string): string;
25
+ /** Run a shell script string inside the sandbox and throw on failure. */
26
+ export declare function runInSandbox(sandbox: WorkspaceSandbox, script: string, opts?: {
27
+ allowFailure?: boolean;
28
+ timeout?: number;
29
+ /** Safe description used in error messages instead of the script itself. */
30
+ label?: string;
31
+ }): Promise<{
32
+ stdout: string;
33
+ stderr: string;
34
+ exitCode: number;
35
+ }>;
36
+ /**
37
+ * Kill the previously launched server (if any) using its pidfile, waiting for
38
+ * the process to exit (bounded, then SIGKILL) so the replacement never races
39
+ * the old server for the port. Safe when nothing is running.
40
+ */
41
+ export declare function killPreviousServer(sandbox: WorkspaceSandbox, remoteDir: string): Promise<void>;
42
+ /**
43
+ * Launch (or relaunch) the server by running the recorded launch script,
44
+ * detached via nohup. Deliberately NOT `processes.spawn()`: provider process
45
+ * handles follow the command's log stream, which would keep the calling
46
+ * process's event loop alive for as long as the server runs. The server's
47
+ * lifecycle is managed through its pidfile instead.
48
+ */
49
+ export declare function launchServer(sandbox: WorkspaceSandbox, remoteDir: string): Promise<void>;
50
+ /** Tail the server log from inside the sandbox. */
51
+ export declare function tailServerLog(sandbox: WorkspaceSandbox, remoteDir: string, lines?: number): Promise<string>;
52
+ /**
53
+ * Poll `${url}${path}` until the server responds. Any HTTP status below 500
54
+ * counts as "the server is up" — gateway errors (502/503) mean nothing is
55
+ * listening on the port, and 410 is what some providers (e.g. Vercel) return
56
+ * from their edge when the sandbox itself is stopped.
57
+ */
58
+ export declare function waitForHealthy(url: string, opts?: {
59
+ path?: string;
60
+ timeoutMs?: number;
61
+ intervalMs?: number;
62
+ }): Promise<boolean>;
63
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"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