@mastra/deployer 1.42.0-alpha.3 → 1.42.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 (33) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/build/bundler.cjs +3 -3
  3. package/dist/build/bundler.js +1 -1
  4. package/dist/build/index.cjs +7 -7
  5. package/dist/build/index.js +2 -2
  6. package/dist/build/plugins/local-storage-detector.d.ts +6 -4
  7. package/dist/build/plugins/local-storage-detector.d.ts.map +1 -1
  8. package/dist/bundler/index.cjs +3 -3
  9. package/dist/bundler/index.js +1 -1
  10. package/dist/{chunk-UVEN22VX.cjs → chunk-4I6VIARR.cjs} +5 -5
  11. package/dist/{chunk-UVEN22VX.cjs.map → chunk-4I6VIARR.cjs.map} +1 -1
  12. package/dist/{chunk-GBDZZHB2.js → chunk-G2ZY3BL6.js} +3 -3
  13. package/dist/{chunk-GBDZZHB2.js.map → chunk-G2ZY3BL6.js.map} +1 -1
  14. package/dist/{chunk-4KPYOOLH.cjs → chunk-GPRMW5ZF.cjs} +4 -2
  15. package/dist/chunk-GPRMW5ZF.cjs.map +1 -0
  16. package/dist/{chunk-MZ3WIURS.js → chunk-H7Q36A6X.js} +3 -3
  17. package/dist/{chunk-MZ3WIURS.js.map → chunk-H7Q36A6X.js.map} +1 -1
  18. package/dist/{chunk-FQ5JFVJK.js → chunk-TG7R2YUM.js} +4 -2
  19. package/dist/chunk-TG7R2YUM.js.map +1 -0
  20. package/dist/{chunk-LITSHR6E.cjs → chunk-WE66TECO.cjs} +5 -5
  21. package/dist/{chunk-LITSHR6E.cjs.map → chunk-WE66TECO.cjs.map} +1 -1
  22. package/dist/docs/SKILL.md +1 -1
  23. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  24. package/dist/index.cjs +2 -2
  25. package/dist/index.js +1 -1
  26. package/dist/server/index.cjs +17 -8
  27. package/dist/server/index.cjs.map +1 -1
  28. package/dist/server/index.d.ts.map +1 -1
  29. package/dist/server/index.js +17 -8
  30. package/dist/server/index.js.map +1 -1
  31. package/package.json +10 -10
  32. package/dist/chunk-4KPYOOLH.cjs.map +0 -1
  33. package/dist/chunk-FQ5JFVJK.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/build/plugins/local-storage-detector.ts","../src/build/plugins/node-modules-extension-resolver.ts","../src/build/bundler.ts"],"names":["nodeResolve","join"],"mappings":";;;;;;;;;;;;;AAMA,IAAM,mBAAA,GAAgE;AAAA,EACpE;AAAA,IACE,OAAA,EAAS,8CAAA;AAAA,IACT,IAAA,EAAM;AAAA,GACR;AAAA,EACA;AAAA,IACE,OAAA,EAAS,8EAAA;AAAA,IACT,IAAA,EAAM;AAAA,GACR;AAAA,EACA;AAAA,IACE,OAAA,EAAS,gFAAA;AAAA,IACT,IAAA,EAAM;AAAA;AAEV,CAAA;AAeA,IAAM,gBAAA,GAAmB,yCAAA;AAgBlB,SAAS,oBAAA,GAA+B;AAC7C,EAAA,MAAM,iBAAA,uBAAwB,GAAA,EAAoD;AAElF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,+BAAA;AAAA,IAEN,SAAA,CAAU,OAAO,EAAA,EAAI;AACnB,MAAA,IAAI,EAAA,CAAG,QAAA,CAAS,cAAc,CAAA,EAAG,OAAO,IAAA;AACxC,MAAA,IAAI,gBAAA,CAAiB,IAAA,CAAK,EAAE,CAAA,EAAG,OAAO,IAAA;AAEtC,MAAA,MAAM,UAAkD,EAAC;AACzD,MAAA,KAAA,MAAW,EAAE,OAAA,EAAS,IAAA,EAAK,IAAK,mBAAA,EAAqB;AACnD,QAAA,MAAM,EAAA,GAAK,IAAI,MAAA,CAAO,OAAA,CAAQ,QAAQ,OAAA,CAAQ,KAAA,CAAM,QAAA,CAAS,GAAG,CAAA,GAAI,OAAA,CAAQ,KAAA,GAAQ,OAAA,CAAQ,QAAQ,GAAG,CAAA;AACvG,QAAA,KAAA,MAAW,CAAA,IAAK,KAAA,CAAM,QAAA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QACzB,aAAa,EAAA,EAAI;AACf,UAAA,OAAO,SAAA,CAAU,SAAS,EAAE,CAAA;AAAA,QAC9B;AAAA,OACD,CAAA;AAAA,MACL,aAAA,GAAgB,SAAQ,GAAI,MAAA;AAAA,MAC5B,eAAA,GAAkB,8BAA6B,GAAI,iBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAenD,IAAA,EAAK;AAAA,MACL,oBAAA,EAAqB;AAAA,MACrB,cAAA,CAAe,SAAA,EAAW,EAAE,SAAA,EAAW,CAAA;AAAA;AAAA,MAEvC,OAAA,CAAQ;AAAA,QACN,OAAA,EAAS,SAAA;AAAA,QACT;AAAA,OACD;AAAA,KACH,CAAE,OAAO,OAAO;AAAA,GAClB;AACF;AAEA,eAAsB,aAAA,CACpB,cACA,aAAA,EACA;AACA,EAAA,MAAM,OAAA,GAAU,MAAM,MAAA,CAAO,YAAY,CAAA;AAEzC,EAAA,OAAO;AAAA,IACL,OAAO,MAAM;AACX,MAAA,OAAO,QAAQ,KAAA,CAAM;AAAA,QACnB,GAAG,aAAA;AAAA,QACH,MAAA,EAAQ,KAAA;AAAA,QACR,cAAA,EAAgB,YAAA;AAAA,QAChB,cAAA,EAAgB;AAAA,OACjB,CAAA;AAAA,IACH,CAAA;AAAA,IACA,OAAO,MAAM;AACX,MAAA,OAAO,QAAQ,KAAA,EAAM;AAAA,IACvB;AAAA,GACF;AACF","file":"chunk-TG7R2YUM.js","sourcesContent":["import type { Plugin } from 'rollup';\n\n/**\n * Connection-string-shaped patterns that resolve to the build host and will\n * never work inside the deploy container.\n */\nconst LOCAL_HOST_PATTERNS: Array<{ pattern: RegExp; hint: string }> = [\n {\n pattern: /\\bfile:\\.{1,2}\\/[^\\s'\"`]+\\.(?:db|sqlite)\\b/gi,\n hint: 'LibSQL/SQLite file path relative to the build host',\n },\n {\n pattern: /\\b(?:postgres(?:ql)?|mysql|mongodb|redis|libsql):\\/\\/[^/\\s'\"`]*localhost\\b/gi,\n hint: 'localhost in a connection string',\n },\n {\n pattern: /\\b(?:postgres(?:ql)?|mysql|mongodb|redis|libsql):\\/\\/[^/\\s'\"`]*127\\.0\\.0\\.1\\b/g,\n hint: '127.0.0.1 in a connection string',\n },\n];\n\nexport interface LocalStorageDetection {\n value: string;\n hint: string;\n module: string;\n}\n\n/**\n * Matches the deployer's own intermediate dependency shims emitted under\n * `.mastra/.build/` (e.g. `@mastra__core.mjs`, `@mastra__core__mastra.mjs`).\n * These pre-bundled chunks preserve JSDoc examples from the original library\n * source (e.g. `LibSQLStore({ url: 'file:./data.db' })`) which would otherwise\n * trip the host-local detector even though they're not user code.\n */\nconst MASTRA_SHIM_PATH = /[\\\\/]\\.mastra[\\\\/]\\.build[\\\\/]@mastra__/;\n\n/**\n * Rollup plugin that detects host-local storage URLs (e.g. `file:./mastra.db`,\n * `postgres://localhost`) in **user source modules** during bundling.\n *\n * Only modules outside `node_modules` (and the deployer's own\n * `.mastra/.build/@mastra__*` shim files) are inspected, so library code\n * (like Agent Builder prompt templates or JSDoc examples in `@mastra/core`)\n * is naturally excluded. Tree-shaken modules are excluded via\n * `generateBundle` — only modules that actually contribute rendered code to\n * the output are reported.\n *\n * Detected paths are emitted as `preflight-local-paths.json` in the output\n * directory for the CLI preflight check to consume.\n */\nexport function localStorageDetector(): Plugin {\n const userModuleMatches = new Map<string, Array<{ value: string; hint: string }>>();\n\n return {\n name: 'mastra-local-storage-detector',\n\n transform(_code, id) {\n if (id.includes('node_modules')) return null;\n if (MASTRA_SHIM_PATH.test(id)) return null;\n\n const matches: Array<{ value: string; hint: string }> = [];\n for (const { pattern, hint } of LOCAL_HOST_PATTERNS) {\n const re = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');\n for (const m of _code.matchAll(re)) {\n matches.push({ value: m[0], hint });\n }\n }\n\n if (matches.length > 0) {\n userModuleMatches.set(id, matches);\n }\n\n return null;\n },\n\n generateBundle(_, bundle) {\n const detections: LocalStorageDetection[] = [];\n const seen = new Set<string>();\n\n for (const chunk of Object.values(bundle)) {\n if (chunk.type !== 'chunk') continue;\n\n for (const [moduleId, moduleInfo] of Object.entries(chunk.modules)) {\n if (moduleInfo.renderedLength === 0) continue;\n\n const matches = userModuleMatches.get(moduleId);\n if (!matches) continue;\n\n for (const { value, hint } of matches) {\n const key = `${hint}::${value}`;\n if (seen.has(key)) continue;\n seen.add(key);\n\n detections.push({ value, hint, module: moduleId });\n }\n }\n }\n\n this.emitFile({\n type: 'asset',\n fileName: 'preflight-local-paths.json',\n source: JSON.stringify(detections),\n });\n },\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport { join, isAbsolute } from 'node:path';\nimport nodeResolve from '@rollup/plugin-node-resolve';\nimport type { Plugin } from 'rollup';\nimport type { PackageJson } from 'type-fest';\nimport { getPackageRootPath } from '../package-info';\nimport { getPackageName, isExternalProtocolImport, isBareModuleSpecifier } from '../utils';\n\n/**\n * Check if a package has an exports field in its package.json.\n * Results are cached to avoid repeated filesystem reads.\n */\nasync function getPackageJSON(pkgName: string, importer: string): Promise<PackageJson> {\n const pkgRoot = await getPackageRootPath(pkgName, importer);\n if (!pkgRoot) {\n throw new Error(`Package ${pkgName} not found`);\n }\n\n const pkgJSON = JSON.parse(await readFile(join(pkgRoot, 'package.json'), 'utf-8')) as PackageJson;\n return pkgJSON;\n}\n\n/**\n * Rollup plugin that resolves module extensions for external dependencies.\n *\n * This plugin handles ESM compatibility for external imports when node-resolve is not used:\n * - Packages WITH exports field (e.g., hono, date-fns): Keep imports as-is or strip redundant extensions\n * - Packages WITHOUT exports field (e.g., lodash): Add .js extension for direct file imports\n */\nexport function nodeModulesExtensionResolver(): Plugin {\n // Create a single instance of node-resolve to reuse\n const nodeResolvePlugin = nodeResolve();\n\n return {\n name: 'node-modules-extension-resolver',\n async resolveId(id, importer, options) {\n // Only bare package imports are relevant here.\n if (!importer || !isBareModuleSpecifier(id) || isExternalProtocolImport(id) || isAbsolute(id)) {\n return null;\n }\n\n // Skip direct package imports (e.g., 'lodash', '@mastra/core')\n const parts = id.split('/');\n const isScoped = id.startsWith('@');\n if ((isScoped && parts.length === 2) || (!isScoped && parts.length === 1)) {\n return null;\n }\n\n const pkgName = getPackageName(id);\n if (!pkgName) {\n return null;\n }\n\n try {\n const packageJSON = await getPackageJSON(pkgName, importer);\n // if it has exports, node should be able to rsolve it, if not the exports map is wrong.\n if (!!packageJSON.exports) {\n return null;\n }\n\n const packageRoot = await getPackageRootPath(pkgName, importer);\n // @ts-expect-error - handle is part of resolveId signature\n const nodeResolved = await nodeResolvePlugin.resolveId?.handler?.call(this, id, importer, options);\n // if we cannot resolve it, it's not a valid import so we let node handle it\n if (!nodeResolved?.id) {\n return null;\n }\n\n let filePath = nodeResolved.id;\n if (nodeResolved.resolvedBy === 'commonjs--resolver') {\n filePath = filePath.substring(1).split('?')[0];\n }\n\n const resolvedImportPath = filePath.replace(packageRoot, pkgName);\n\n return {\n id: resolvedImportPath,\n external: true,\n };\n } catch (err) {\n console.error(err);\n return null;\n }\n },\n };\n}\n","import { join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';\nimport alias from '@rollup/plugin-alias';\nimport commonjs from '@rollup/plugin-commonjs';\nimport json from '@rollup/plugin-json';\nimport nodeResolve from '@rollup/plugin-node-resolve';\nimport { rollup } from 'rollup';\nimport type { InputOptions, OutputOptions, Plugin } from 'rollup';\nimport type { analyzeBundle } from './analyze';\nimport { esbuild } from './plugins/esbuild';\nimport { esmShim } from './plugins/esm-shim';\nimport { localStorageDetector } from './plugins/local-storage-detector';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { protocolExternalResolver } from './plugins/protocol-external-resolver';\nimport { removeDeployer } from './plugins/remove-deployer';\nimport { subpathExternalsResolver } from './plugins/subpath-externals-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport { getNodeResolveOptions, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport async function getInputOptions(\n entryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n platform: BundlerPlatform,\n env: Record<string, string> = { 'process.env.NODE_ENV': JSON.stringify('production') },\n {\n sourcemap = false,\n isDev = false,\n projectRoot,\n workspaceRoot = undefined,\n enableEsmShim = true,\n externalsPreset = false,\n }: {\n sourcemap?: boolean;\n isDev?: boolean;\n workspaceRoot?: string;\n projectRoot: string;\n enableEsmShim?: boolean;\n externalsPreset?: boolean;\n },\n): Promise<InputOptions> {\n const nodeResolvePlugin = nodeResolve(getNodeResolveOptions(platform));\n\n const externalsCopy = new Set<string>(analyzedBundleInfo.externalDependencies.keys());\n const externals = externalsPreset ? [] : Array.from(externalsCopy);\n\n const normalizedEntryFile = slash(entryFile);\n return {\n logLevel: process.env.MASTRA_BUNDLER_DEBUG === 'true' ? 'debug' : 'silent',\n treeshake: 'smallest',\n preserveSymlinks: true,\n external: externals,\n plugins: [\n protocolExternalResolver(),\n subpathExternalsResolver(externals),\n {\n name: 'alias-optimized-deps',\n resolveId(id: string) {\n if (!analyzedBundleInfo.dependencies.has(id)) {\n return null;\n }\n\n const filename = analyzedBundleInfo.dependencies.get(id)!;\n const absolutePath = join(workspaceRoot || projectRoot, filename);\n\n // During `mastra dev` we want to keep deps as external\n if (isDev) {\n return {\n id: process.platform === 'win32' ? pathToFileURL(absolutePath).href : absolutePath,\n external: true,\n };\n }\n\n // For production builds return the absolute path as-is so Rollup can handle itself\n return {\n id: absolutePath,\n external: false,\n };\n },\n } satisfies Plugin,\n alias({\n entries: [\n {\n find: /^\\#server$/,\n replacement: slash(fileURLToPath(import.meta.resolve('@mastra/deployer/server'))),\n },\n {\n find: /^\\@mastra\\/server\\/(.*)/,\n replacement: `@mastra/server/$1`,\n customResolver: id => {\n if (id.startsWith('@mastra/server')) {\n return {\n id: fileURLToPath(import.meta.resolve(id)),\n };\n }\n },\n },\n { find: /^\\#mastra$/, replacement: normalizedEntryFile },\n ],\n }),\n tsConfigPaths(),\n {\n name: 'tools-rewriter',\n resolveId(id: string) {\n if (id === '#tools') {\n return {\n id: './tools.mjs',\n external: true,\n };\n }\n },\n } satisfies Plugin,\n esbuild({\n platform,\n define: env,\n }),\n optimizeLodashImports({\n include: '**/*.{js,ts,mjs,cjs}',\n }),\n externalsPreset\n ? null\n : commonjs({\n extensions: ['.js', '.ts'],\n transformMixedEsModules: true,\n esmExternals(id) {\n return externals.includes(id);\n },\n }),\n enableEsmShim ? esmShim() : undefined,\n externalsPreset ? nodeModulesExtensionResolver() : nodeResolvePlugin,\n // for debugging\n // {\n // name: 'logger',\n // //@ts-expect-error\n // resolveId(id, ...args) {\n // console.log({ id, args });\n // },\n // // @ts-expect-error\n // transform(code, id) {\n // if (code.includes('class Duplexify ')) {\n // console.log({ duplex: id });\n // }\n // },\n // },\n json(),\n localStorageDetector(),\n removeDeployer(entryFile, { sourcemap }),\n // treeshake unused imports\n esbuild({\n include: entryFile,\n platform,\n }),\n ].filter(Boolean),\n } satisfies InputOptions;\n}\n\nexport async function createBundler(\n inputOptions: InputOptions,\n outputOptions: Partial<OutputOptions> & { dir: string },\n) {\n const bundler = await rollup(inputOptions);\n\n return {\n write: () => {\n return bundler.write({\n ...outputOptions,\n format: 'esm',\n entryFileNames: '[name].mjs',\n chunkFileNames: '[name].mjs',\n });\n },\n close: () => {\n return bundler.close();\n },\n };\n}\n"]}
@@ -2,7 +2,7 @@
2
2
 
3
3
  var chunkKBVOYAAL_cjs = require('./chunk-KBVOYAAL.cjs');
4
4
  var chunkU5HOHRPU_cjs = require('./chunk-U5HOHRPU.cjs');
5
- var chunk4KPYOOLH_cjs = require('./chunk-4KPYOOLH.cjs');
5
+ var chunkGPRMW5ZF_cjs = require('./chunk-GPRMW5ZF.cjs');
6
6
  var chunkYW7AIVNG_cjs = require('./chunk-YW7AIVNG.cjs');
7
7
  var chunkUEH6D24P_cjs = require('./chunk-UEH6D24P.cjs');
8
8
  var chunk3T7FP546_cjs = require('./chunk-3T7FP546.cjs');
@@ -93,7 +93,7 @@ var Bundler = class extends bundler.MastraBundler {
93
93
  );
94
94
  }
95
95
  createBundler(inputOptions, outputOptions) {
96
- return chunk4KPYOOLH_cjs.createBundler(inputOptions, outputOptions);
96
+ return chunkGPRMW5ZF_cjs.createBundler(inputOptions, outputOptions);
97
97
  }
98
98
  async getUserBundlerOptions(mastraEntryFile, outputDirectory) {
99
99
  const defaultBundlerOptions = {
@@ -185,7 +185,7 @@ var Bundler = class extends bundler.MastraBundler {
185
185
  const { workspaceRoot } = await chunkU5HOHRPU_cjs.getWorkspaceInformation({ mastraEntryFile });
186
186
  const closestPkgJson = pkg__namespace.up({ cwd: path.dirname(mastraEntryFile) });
187
187
  const projectRoot = closestPkgJson ? path.dirname(closestPkgJson) : process.cwd();
188
- const inputOptions = await chunk4KPYOOLH_cjs.getInputOptions(
188
+ const inputOptions = await chunkGPRMW5ZF_cjs.getInputOptions(
189
189
  mastraEntryFile,
190
190
  analyzedBundleInfo,
191
191
  this.platform,
@@ -406,5 +406,5 @@ export const tools = [${toolsExports.join(", ")}]`
406
406
 
407
407
  exports.Bundler = Bundler;
408
408
  exports.IS_DEFAULT = IS_DEFAULT;
409
- //# sourceMappingURL=chunk-LITSHR6E.cjs.map
410
- //# sourceMappingURL=chunk-LITSHR6E.cjs.map
409
+ //# sourceMappingURL=chunk-WE66TECO.cjs.map
410
+ //# sourceMappingURL=chunk-WE66TECO.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bundler/index.ts"],"names":["MastraBundler","emptyDir","ensureDir","join","writeFile","createBundler","getBundlerOptions","analyzeBundle","DepsService","fsExtra","execSync","rm","stat","copy","getWorkspaceInformation","pkg","dirname","getInputOptions","existsSync","virtual","slash","posix","glob","path","FileService","error","MastraError","ErrorDomain","ErrorCategory","isBareModuleSpecifier","getPackageRootPath","readJSON"],"mappings":";;;;;;;;;;;;;;;;;;;;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,MAAM,KAAK,mBAAA,CAAoBb,SAAA,CAAK,eAAA,EAAiB,IAAA,CAAK,SAAS,CAAC,CAAA;AACpE,MAAA,IAAA,CAAK,MAAA,CAAO,KAAK,mCAAmC,CAAA;AAAA,IACtD,SAASsB,OAAA,EAAO;AACd,MAAA,MAAM,UAAUA,OAAA,YAAiB,KAAA,GAAQA,OAAA,CAAM,OAAA,GAAU,OAAOA,OAAK,CAAA;AACrE,MAAA,MAAM,IAAIC,iBAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,sCAAA;AAAA,UACJ,IAAA,EAAM,uCAAuC,OAAO,CAAA,CAAA;AAAA,UACpD,QAAQC,iBAAA,CAAY,QAAA;AAAA,UACpB,UAAUC,mBAAA,CAAc;AAAA,SAC1B;AAAA,QACAH;AAAA,OACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,IAAA,CAAK,UAAA,EAAoB,gBAAA,EAA0B,UAAA,EAAkD;AACzG,IAAA,MAAM,iBAAA,GAAoB,MAAM,IAAA,CAAK,qBAAA,CAAsB,UAAU,CAAA;AACrE,IAAA,MAAM,WAAA,GAAc,MAAA,CAAO,IAAA,CAAK,iBAAiB,CAAA,CAAE,MAAA;AACnD,IAAA,IAAI,cAAc,CAAA,EAAG;AACnB,MAAA,IAAA,CAAK,OAAO,IAAA,CAAK,aAAA,EAAe,EAAE,KAAA,EAAO,aAAa,CAAA;AAAA,IACxD;AAAA,EACF;AACF","file":"chunk-LITSHR6E.cjs","sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix } from 'node:path';\nimport { MastraBundler } from '@mastra/core/bundler';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport type { Config } from '@mastra/core/mastra';\nimport virtual from '@rollup/plugin-virtual';\nimport * as pkg from 'empathic/package';\nimport fsExtra, { copy, ensureDir, readJSON, emptyDir } from 'fs-extra/esm';\nimport type { InputOptions, OutputOptions } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport { analyzeBundle } from '../build/analyze';\nimport { createBundler as createBundlerUtil, getInputOptions } from '../build/bundler';\nimport { getBundlerOptions } from '../build/bundlerOptions';\nimport { getPackageRootPath } from '../build/package-info';\nimport type { BundlerOptions } from '../build/types';\nimport type { BundlerPlatform } from '../build/utils';\nimport { isBareModuleSpecifier, slash } from '../build/utils';\nimport { DepsService } from '../services/deps';\nimport { FileService } from '../services/fs';\nimport { getWorkspaceInformation } from './workspaceDependencies';\n\nexport type { BundlerOptions } from '../build/types';\nexport type { BundlerPlatform } from '../build/utils';\n\nexport const IS_DEFAULT = Symbol('IS_DEFAULT');\n\nexport abstract class Bundler extends MastraBundler {\n protected analyzeOutputDir = '.build';\n protected outputDir = 'output';\n protected platform: BundlerPlatform = 'node';\n\n constructor(name: string, component: 'BUNDLER' | 'DEPLOYER' = 'BUNDLER') {\n super({ name, component });\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n // Clean up the output directory first\n await emptyDir(outputDirectory);\n\n await ensureDir(join(outputDirectory, this.analyzeOutputDir));\n await ensureDir(join(outputDirectory, this.outputDir));\n }\n\n async writePackageJson(\n outputDirectory: string,\n dependencies: Map<string, string>,\n resolutions?: Record<string, string>,\n ) {\n this.logger.debug(\"Writing project's package.json\");\n\n await ensureDir(outputDirectory);\n const pkgPath = join(outputDirectory, 'package.json');\n\n const dependenciesMap = new Map();\n for (const [key, value] of dependencies.entries()) {\n if (key.startsWith('@')) {\n // Handle scoped packages (e.g. @org/package)\n const pkgChunks = key.split('/');\n dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, value);\n } else {\n // For non-scoped packages, take only the first part before any slash\n const pkgName = key.split('/')[0] || key;\n dependenciesMap.set(pkgName, value);\n }\n }\n\n await writeFile(\n pkgPath,\n JSON.stringify(\n {\n name: 'server',\n version: '1.0.0',\n private: true,\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n },\n null,\n 2,\n ),\n );\n\n // pnpm v11 requires build policy via pnpm-workspace.yaml in the output directory\n await writeFile(\n join(outputDirectory, 'pnpm-workspace.yaml'),\n \"packages:\\n - '.'\\nallowBuilds:\\n bcrypt: true\\n esbuild: true\\n sharp: true\\n protobufjs: true\\n workerd: true\\n bufferutil: true\\n utf-8-validate: true\\n\",\n );\n }\n\n protected createBundler(inputOptions: InputOptions, outputOptions: Partial<OutputOptions> & { dir: string }) {\n return createBundlerUtil(inputOptions, outputOptions);\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const defaultBundlerOptions: Config['bundler'] = {\n externals: [],\n sourcemap: false,\n transpilePackages: [],\n [IS_DEFAULT]: true,\n } as const;\n\n try {\n const bundlerOptions = await getBundlerOptions(mastraEntryFile, outputDirectory);\n\n return bundlerOptions ?? defaultBundlerOptions;\n } catch (error) {\n this.logger.debug('Failed to get bundler options, sourcemap will be disabled', { error });\n }\n\n return defaultBundlerOptions;\n }\n\n protected async analyze(entry: string | string[], mastraFile: string, outputDirectory: string) {\n return await analyzeBundle(\n ([] as string[]).concat(entry),\n mastraFile,\n {\n outputDir: join(outputDirectory, this.analyzeOutputDir),\n projectRoot: outputDirectory,\n platform: this.platform,\n },\n this.logger,\n );\n }\n\n protected async installDependencies(outputDirectory: string, rootDir = process.cwd()) {\n const deps = new DepsService(rootDir);\n deps.__setLogger(this.logger);\n\n await deps.install({ dir: join(outputDirectory, this.outputDir) });\n }\n\n /**\n * Generate a package-lock.json for the output directory so that deploy targets\n * can use `npm ci` instead of `npm install`, skipping version resolution entirely.\n * This is a lockfile-only operation — no packages are downloaded.\n *\n * Temporarily moves node_modules out of the way because pnpm's symlink-based\n * layout confuses npm's arborist, then restores it afterwards so that\n * `mastra start` (or wrangler) can still resolve dependencies at runtime.\n */\n private async generateNpmLockfile(outputDir: string): Promise<void> {\n const nodeModules = join(outputDir, 'node_modules');\n const nodeModulesTmp = join(outputDir, 'node_modules.__tmp');\n let movedNodeModules = false;\n try {\n // Move node_modules aside — pnpm's symlink layout confuses npm's arborist\n if (await fsExtra.pathExists(nodeModules)) {\n await fsExtra.move(nodeModules, nodeModulesTmp, { overwrite: true });\n movedNodeModules = true;\n }\n execSync('npm install --package-lock-only --force', {\n cwd: outputDir,\n stdio: 'pipe',\n timeout: 60_000,\n });\n } catch {\n this.logger.warn('Failed to generate package-lock.json — deploy will fall back to npm install');\n } finally {\n // Restore node_modules so runtime resolution works\n if (movedNodeModules) {\n await rm(nodeModules, { recursive: true, force: true });\n await fsExtra.move(nodeModulesTmp, nodeModules, { overwrite: true });\n }\n }\n }\n\n protected async copyPublic(mastraDir: string, outputDirectory: string) {\n const publicDir = join(mastraDir, 'public');\n\n try {\n await stat(publicDir);\n } catch {\n return;\n }\n\n await copy(publicDir, join(outputDirectory, this.outputDir));\n }\n\n protected async copyDOTNPMRC({\n rootDir = process.cwd(),\n outputDirectory,\n }: {\n rootDir?: string;\n outputDirectory: string;\n }) {\n const sourceDotNpmRcPath = join(rootDir, '.npmrc');\n const targetDotNpmRcPath = join(outputDirectory, this.outputDir, '.npmrc');\n\n try {\n await stat(sourceDotNpmRcPath);\n await copy(sourceDotNpmRcPath, targetDotNpmRcPath);\n } catch {\n return;\n }\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap, enableEsmShim, externals }: BundlerOptions,\n ) {\n const { workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile });\n const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });\n const projectRoot = closestPkgJson ? dirname(closestPkgJson) : process.cwd();\n\n const inputOptions: InputOptions = await getInputOptions(\n mastraEntryFile,\n analyzedBundleInfo,\n this.platform,\n {\n 'process.env.NODE_ENV': JSON.stringify('production'),\n },\n { sourcemap: enableSourcemap, workspaceRoot, projectRoot, enableEsmShim, externalsPreset: externals === true },\n );\n const isVirtual = serverFile.includes('\\n') || !existsSync(serverFile);\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);\n\n if (isVirtual) {\n inputOptions.input = { index: '#entry', ...toolsInputOptions };\n\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins.unshift(virtual({ '#entry': serverFile }));\n } else {\n inputOptions.plugins = [virtual({ '#entry': serverFile })];\n }\n } else {\n inputOptions.input = { index: serverFile, ...toolsInputOptions };\n }\n\n return inputOptions;\n }\n\n getAllToolPaths(mastraDir: string, toolsPaths: (string | string[])[] = []): (string | string[])[] {\n // Normalize Windows paths to forward slashes for consistent handling\n const normalizedMastraDir = slash(mastraDir);\n\n // Prepare default tools paths with glob patterns\n const defaultToolsPath = posix.join(normalizedMastraDir, 'tools/**/*.{js,ts}');\n const defaultToolsIgnorePaths = [\n `!${posix.join(normalizedMastraDir, 'tools/**/*.{test,spec}.{js,ts}')}`,\n `!${posix.join(normalizedMastraDir, 'tools/**/__tests__/**')}`,\n ];\n\n // Combine default path with ignore patterns\n const defaultPaths = [defaultToolsPath, ...defaultToolsIgnorePaths];\n\n // If no tools paths provided, use only the default paths\n if (toolsPaths.length === 0) {\n return [defaultPaths];\n }\n\n // If tools paths are provided, add the default paths to ensure standard tools are always included\n return [...toolsPaths, defaultPaths];\n }\n\n async listToolsInputOptions(toolsPaths: (string | string[])[]) {\n const inputs: Record<string, string> = {};\n\n for (const toolPath of toolsPaths) {\n const expandedPaths = await glob(toolPath, {\n absolute: true,\n expandDirectories: false,\n });\n\n for (const path of expandedPaths) {\n if (await fsExtra.pathExists(path)) {\n const fileService = new FileService();\n const entryFile = fileService.getFirstExistingFile([\n join(path, 'index.ts'),\n join(path, 'index.js'),\n path, // if path itself is a file\n ]);\n\n // if it doesn't exist or is a dir skip it. using a dir as a tool will crash the process\n if (!entryFile || (await stat(entryFile)).isDirectory()) {\n this.logger.warn('No entry file found, skipping', { path });\n continue;\n }\n\n const uniqueToolID = crypto.randomUUID();\n // Normalize Windows paths to forward slashes for consistent handling\n const normalizedEntryFile = entryFile.replaceAll('\\\\', '/');\n inputs[`tools/${uniqueToolID}`] = normalizedEntryFile;\n } else {\n this.logger.warn('Tool path does not exist, skipping', { path });\n }\n }\n }\n\n return inputs;\n }\n\n protected async _bundle(\n serverFile: string,\n mastraEntryFile: string,\n {\n projectRoot,\n outputDirectory,\n enableEsmShim = true,\n }: {\n projectRoot: string;\n outputDirectory: string;\n enableEsmShim?: boolean;\n },\n toolsPaths: (string | string[])[] = [],\n bundleLocation: string = join(outputDirectory, this.outputDir),\n ): Promise<void> {\n const analyzeDir = join(outputDirectory, this.analyzeOutputDir);\n\n const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n const internalBundlerOptions: BundlerOptions = {\n enableSourcemap: !!bundlerOptions.sourcemap,\n externals: bundlerOptions.externals ?? [],\n enableEsmShim,\n dynamicPackages: bundlerOptions.dynamicPackages,\n };\n\n let analyzedBundleInfo;\n try {\n const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths);\n analyzedBundleInfo = await analyzeBundle(\n [serverFile, ...Object.values(resolvedToolsPaths)],\n mastraEntryFile,\n {\n outputDir: analyzeDir,\n projectRoot,\n platform: this.platform,\n bundlerOptions: internalBundlerOptions,\n },\n this.logger,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n if (error instanceof MastraError) {\n throw error;\n }\n\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_ANALYZE_FAILED',\n text: `Failed to analyze Mastra application: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n\n const dependenciesToInstall = new Map<string, string>();\n for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {\n if (analyzedBundleInfo.workspaceMap.has(dep) || !isBareModuleSpecifier(dep)) {\n continue;\n }\n\n let version = depInfo.version;\n let actualPackageName: string | undefined;\n\n // Read package.json to get actual package name (for alias detection) and version if not pre-resolved\n try {\n // First try to resolve from the project root (provides correct context for monorepos)\n let rootPath = await getPackageRootPath(dep, projectRoot);\n\n // If not found in user's project, try resolving from deployer's location\n // This handles packages like hono that are provided by @mastra/deployer\n if (!rootPath) {\n rootPath = await getPackageRootPath(dep, import.meta.dirname);\n }\n\n if (rootPath) {\n const pkg = await readJSON(`${rootPath}/package.json`);\n actualPackageName = pkg.name;\n // Use pre-resolved version if available, otherwise use from package.json\n if (!version) {\n version = pkg.version;\n }\n }\n } catch {\n // Resolution failed, will use 'latest' for version\n }\n\n // Default to 'latest' if still no version\n version = version || 'latest';\n\n // Check if this is an npm alias (import name differs from actual package name)\n // e.g., importing \"ai-v5\" which resolves to package \"ai\"\n // or importing \"@ai-sdk/openai-v5\" which resolves to \"@ai-sdk/openai\"\n // In this case, write npm alias syntax: \"ai-v5\": \"npm:ai@5.0.93\"\n const isAlias = actualPackageName && dep !== actualPackageName;\n\n if (isAlias) {\n dependenciesToInstall.set(dep, `npm:${actualPackageName}@${version}`);\n } else {\n dependenciesToInstall.set(dep, version);\n }\n }\n\n try {\n await this.writePackageJson(join(outputDirectory, this.outputDir), dependenciesToInstall);\n\n this.logger.info('Bundling Mastra application');\n\n const inputOptions: InputOptions = await this.getBundlerOptions(\n serverFile,\n mastraEntryFile,\n analyzedBundleInfo,\n toolsPaths,\n internalBundlerOptions,\n );\n\n const bundler = await this.createBundler(\n {\n ...inputOptions,\n logLevel: inputOptions.logLevel === 'silent' ? 'warn' : inputOptions.logLevel,\n onwarn: warning => {\n if (warning.code === 'CIRCULAR_DEPENDENCY') {\n if (warning.ids?.[0]?.includes('node_modules')) {\n return;\n }\n\n this.logger.warn('Circular dependency found', {\n dependency: warning.message.replace('Circular dependency: ', ''),\n });\n }\n },\n },\n {\n dir: bundleLocation,\n manualChunks: {\n mastra: ['#mastra'],\n },\n sourcemap: internalBundlerOptions.enableSourcemap,\n },\n );\n\n await bundler.write();\n const toolImports: string[] = [];\n const toolsExports: string[] = [];\n Array.from(Object.keys(inputOptions.input || {}))\n .filter(key => key.startsWith('tools/'))\n .forEach((key, index) => {\n const toolExport = `tool${index}`;\n toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);\n toolsExports.push(toolExport);\n });\n\n await writeFile(\n join(bundleLocation, 'tools.mjs'),\n `${toolImports.join('\\n')}\n\nexport const tools = [${toolsExports.join(', ')}]`,\n );\n this.logger.info('Bundling Mastra done');\n\n this.logger.info('Copying public files');\n await this.copyPublic(dirname(mastraEntryFile), outputDirectory);\n this.logger.info('Done copying public files');\n\n this.logger.info('Copying .npmrc file');\n await this.copyDOTNPMRC({ outputDirectory, rootDir: projectRoot });\n\n this.logger.info('Done copying .npmrc file');\n\n this.logger.info('Installing dependencies');\n await this.installDependencies(outputDirectory, projectRoot);\n this.logger.info('Done installing dependencies');\n\n this.logger.info('Generating package-lock.json for deploy');\n await this.generateNpmLockfile(join(outputDirectory, this.outputDir));\n this.logger.info('Done generating package-lock.json');\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED',\n text: `Failed during bundler bundle stage: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n }\n\n async lint(_entryFile: string, _outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);\n const toolsLength = Object.keys(toolsInputOptions).length;\n if (toolsLength > 0) {\n this.logger.info('Found tools', { count: toolsLength });\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/bundler/index.ts"],"names":["MastraBundler","emptyDir","ensureDir","join","writeFile","createBundler","getBundlerOptions","analyzeBundle","DepsService","fsExtra","execSync","rm","stat","copy","getWorkspaceInformation","pkg","dirname","getInputOptions","existsSync","virtual","slash","posix","glob","path","FileService","error","MastraError","ErrorDomain","ErrorCategory","isBareModuleSpecifier","getPackageRootPath","readJSON"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BO,IAAM,UAAA,0BAAoB,YAAY;AAEtC,IAAe,OAAA,GAAf,cAA+BA,qBAAA,CAAc;AAAA,EACxC,gBAAA,GAAmB,QAAA;AAAA,EACnB,SAAA,GAAY,QAAA;AAAA,EACZ,QAAA,GAA4B,MAAA;AAAA,EAEtC,WAAA,CAAY,IAAA,EAAc,SAAA,GAAoC,SAAA,EAAW;AACvE,IAAA,KAAA,CAAM,EAAE,IAAA,EAAM,SAAA,EAAW,CAAA;AAAA,EAC3B;AAAA,EAEA,MAAM,QAAQ,eAAA,EAAwC;AAEpD,IAAA,MAAMC,iBAAS,eAAe,CAAA;AAE9B,IAAA,MAAMC,iBAAA,CAAUC,SAAA,CAAK,eAAA,EAAiB,IAAA,CAAK,gBAAgB,CAAC,CAAA;AAC5D,IAAA,MAAMD,iBAAA,CAAUC,SAAA,CAAK,eAAA,EAAiB,IAAA,CAAK,SAAS,CAAC,CAAA;AAAA,EACvD;AAAA,EAEA,MAAM,gBAAA,CACJ,eAAA,EACA,YAAA,EACA,WAAA,EACA;AACA,IAAA,IAAA,CAAK,MAAA,CAAO,MAAM,gCAAgC,CAAA;AAElD,IAAA,MAAMD,kBAAU,eAAe,CAAA;AAC/B,IAAA,MAAM,OAAA,GAAUC,SAAA,CAAK,eAAA,EAAiB,cAAc,CAAA;AAEpD,IAAA,MAAM,eAAA,uBAAsB,GAAA,EAAI;AAChC,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,CAAA,IAAK,YAAA,CAAa,SAAQ,EAAG;AACjD,MAAA,IAAI,GAAA,CAAI,UAAA,CAAW,GAAG,CAAA,EAAG;AAEvB,QAAA,MAAM,SAAA,GAAY,GAAA,CAAI,KAAA,CAAM,GAAG,CAAA;AAC/B,QAAA,eAAA,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,IAAA,CAAK,MAAA,CAAO,KAAK,8BAA8B,CAAA;AAE/C,MAAA,IAAA,CAAK,MAAA,CAAO,KAAK,yCAAyC,CAAA;AAC1D,MAAA,MAAM,KAAK,mBAAA,CAAoBb,SAAA,CAAK,eAAA,EAAiB,IAAA,CAAK,SAAS,CAAC,CAAA;AACpE,MAAA,IAAA,CAAK,MAAA,CAAO,KAAK,mCAAmC,CAAA;AAAA,IACtD,SAASsB,OAAA,EAAO;AACd,MAAA,MAAM,UAAUA,OAAA,YAAiB,KAAA,GAAQA,OAAA,CAAM,OAAA,GAAU,OAAOA,OAAK,CAAA;AACrE,MAAA,MAAM,IAAIC,iBAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,sCAAA;AAAA,UACJ,IAAA,EAAM,uCAAuC,OAAO,CAAA,CAAA;AAAA,UACpD,QAAQC,iBAAA,CAAY,QAAA;AAAA,UACpB,UAAUC,mBAAA,CAAc;AAAA,SAC1B;AAAA,QACAH;AAAA,OACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,IAAA,CAAK,UAAA,EAAoB,gBAAA,EAA0B,UAAA,EAAkD;AACzG,IAAA,MAAM,iBAAA,GAAoB,MAAM,IAAA,CAAK,qBAAA,CAAsB,UAAU,CAAA;AACrE,IAAA,MAAM,WAAA,GAAc,MAAA,CAAO,IAAA,CAAK,iBAAiB,CAAA,CAAE,MAAA;AACnD,IAAA,IAAI,cAAc,CAAA,EAAG;AACnB,MAAA,IAAA,CAAK,OAAO,IAAA,CAAK,aAAA,EAAe,EAAE,KAAA,EAAO,aAAa,CAAA;AAAA,IACxD;AAAA,EACF;AACF","file":"chunk-WE66TECO.cjs","sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix } from 'node:path';\nimport { MastraBundler } from '@mastra/core/bundler';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport type { Config } from '@mastra/core/mastra';\nimport virtual from '@rollup/plugin-virtual';\nimport * as pkg from 'empathic/package';\nimport fsExtra, { copy, ensureDir, readJSON, emptyDir } from 'fs-extra/esm';\nimport type { InputOptions, OutputOptions } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport { analyzeBundle } from '../build/analyze';\nimport { createBundler as createBundlerUtil, getInputOptions } from '../build/bundler';\nimport { getBundlerOptions } from '../build/bundlerOptions';\nimport { getPackageRootPath } from '../build/package-info';\nimport type { BundlerOptions } from '../build/types';\nimport type { BundlerPlatform } from '../build/utils';\nimport { isBareModuleSpecifier, slash } from '../build/utils';\nimport { DepsService } from '../services/deps';\nimport { FileService } from '../services/fs';\nimport { getWorkspaceInformation } from './workspaceDependencies';\n\nexport type { BundlerOptions } from '../build/types';\nexport type { BundlerPlatform } from '../build/utils';\n\nexport const IS_DEFAULT = Symbol('IS_DEFAULT');\n\nexport abstract class Bundler extends MastraBundler {\n protected analyzeOutputDir = '.build';\n protected outputDir = 'output';\n protected platform: BundlerPlatform = 'node';\n\n constructor(name: string, component: 'BUNDLER' | 'DEPLOYER' = 'BUNDLER') {\n super({ name, component });\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n // Clean up the output directory first\n await emptyDir(outputDirectory);\n\n await ensureDir(join(outputDirectory, this.analyzeOutputDir));\n await ensureDir(join(outputDirectory, this.outputDir));\n }\n\n async writePackageJson(\n outputDirectory: string,\n dependencies: Map<string, string>,\n resolutions?: Record<string, string>,\n ) {\n this.logger.debug(\"Writing project's package.json\");\n\n await ensureDir(outputDirectory);\n const pkgPath = join(outputDirectory, 'package.json');\n\n const dependenciesMap = new Map();\n for (const [key, value] of dependencies.entries()) {\n if (key.startsWith('@')) {\n // Handle scoped packages (e.g. @org/package)\n const pkgChunks = key.split('/');\n dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, value);\n } else {\n // For non-scoped packages, take only the first part before any slash\n const pkgName = key.split('/')[0] || key;\n dependenciesMap.set(pkgName, value);\n }\n }\n\n await writeFile(\n pkgPath,\n JSON.stringify(\n {\n name: 'server',\n version: '1.0.0',\n private: true,\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n },\n null,\n 2,\n ),\n );\n\n // pnpm v11 requires build policy via pnpm-workspace.yaml in the output directory\n await writeFile(\n join(outputDirectory, 'pnpm-workspace.yaml'),\n \"packages:\\n - '.'\\nallowBuilds:\\n bcrypt: true\\n esbuild: true\\n sharp: true\\n protobufjs: true\\n workerd: true\\n bufferutil: true\\n utf-8-validate: true\\n\",\n );\n }\n\n protected createBundler(inputOptions: InputOptions, outputOptions: Partial<OutputOptions> & { dir: string }) {\n return createBundlerUtil(inputOptions, outputOptions);\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const defaultBundlerOptions: Config['bundler'] = {\n externals: [],\n sourcemap: false,\n transpilePackages: [],\n [IS_DEFAULT]: true,\n } as const;\n\n try {\n const bundlerOptions = await getBundlerOptions(mastraEntryFile, outputDirectory);\n\n return bundlerOptions ?? defaultBundlerOptions;\n } catch (error) {\n this.logger.debug('Failed to get bundler options, sourcemap will be disabled', { error });\n }\n\n return defaultBundlerOptions;\n }\n\n protected async analyze(entry: string | string[], mastraFile: string, outputDirectory: string) {\n return await analyzeBundle(\n ([] as string[]).concat(entry),\n mastraFile,\n {\n outputDir: join(outputDirectory, this.analyzeOutputDir),\n projectRoot: outputDirectory,\n platform: this.platform,\n },\n this.logger,\n );\n }\n\n protected async installDependencies(outputDirectory: string, rootDir = process.cwd()) {\n const deps = new DepsService(rootDir);\n deps.__setLogger(this.logger);\n\n await deps.install({ dir: join(outputDirectory, this.outputDir) });\n }\n\n /**\n * Generate a package-lock.json for the output directory so that deploy targets\n * can use `npm ci` instead of `npm install`, skipping version resolution entirely.\n * This is a lockfile-only operation — no packages are downloaded.\n *\n * Temporarily moves node_modules out of the way because pnpm's symlink-based\n * layout confuses npm's arborist, then restores it afterwards so that\n * `mastra start` (or wrangler) can still resolve dependencies at runtime.\n */\n private async generateNpmLockfile(outputDir: string): Promise<void> {\n const nodeModules = join(outputDir, 'node_modules');\n const nodeModulesTmp = join(outputDir, 'node_modules.__tmp');\n let movedNodeModules = false;\n try {\n // Move node_modules aside — pnpm's symlink layout confuses npm's arborist\n if (await fsExtra.pathExists(nodeModules)) {\n await fsExtra.move(nodeModules, nodeModulesTmp, { overwrite: true });\n movedNodeModules = true;\n }\n execSync('npm install --package-lock-only --force', {\n cwd: outputDir,\n stdio: 'pipe',\n timeout: 60_000,\n });\n } catch {\n this.logger.warn('Failed to generate package-lock.json — deploy will fall back to npm install');\n } finally {\n // Restore node_modules so runtime resolution works\n if (movedNodeModules) {\n await rm(nodeModules, { recursive: true, force: true });\n await fsExtra.move(nodeModulesTmp, nodeModules, { overwrite: true });\n }\n }\n }\n\n protected async copyPublic(mastraDir: string, outputDirectory: string) {\n const publicDir = join(mastraDir, 'public');\n\n try {\n await stat(publicDir);\n } catch {\n return;\n }\n\n await copy(publicDir, join(outputDirectory, this.outputDir));\n }\n\n protected async copyDOTNPMRC({\n rootDir = process.cwd(),\n outputDirectory,\n }: {\n rootDir?: string;\n outputDirectory: string;\n }) {\n const sourceDotNpmRcPath = join(rootDir, '.npmrc');\n const targetDotNpmRcPath = join(outputDirectory, this.outputDir, '.npmrc');\n\n try {\n await stat(sourceDotNpmRcPath);\n await copy(sourceDotNpmRcPath, targetDotNpmRcPath);\n } catch {\n return;\n }\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap, enableEsmShim, externals }: BundlerOptions,\n ) {\n const { workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile });\n const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });\n const projectRoot = closestPkgJson ? dirname(closestPkgJson) : process.cwd();\n\n const inputOptions: InputOptions = await getInputOptions(\n mastraEntryFile,\n analyzedBundleInfo,\n this.platform,\n {\n 'process.env.NODE_ENV': JSON.stringify('production'),\n },\n { sourcemap: enableSourcemap, workspaceRoot, projectRoot, enableEsmShim, externalsPreset: externals === true },\n );\n const isVirtual = serverFile.includes('\\n') || !existsSync(serverFile);\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);\n\n if (isVirtual) {\n inputOptions.input = { index: '#entry', ...toolsInputOptions };\n\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins.unshift(virtual({ '#entry': serverFile }));\n } else {\n inputOptions.plugins = [virtual({ '#entry': serverFile })];\n }\n } else {\n inputOptions.input = { index: serverFile, ...toolsInputOptions };\n }\n\n return inputOptions;\n }\n\n getAllToolPaths(mastraDir: string, toolsPaths: (string | string[])[] = []): (string | string[])[] {\n // Normalize Windows paths to forward slashes for consistent handling\n const normalizedMastraDir = slash(mastraDir);\n\n // Prepare default tools paths with glob patterns\n const defaultToolsPath = posix.join(normalizedMastraDir, 'tools/**/*.{js,ts}');\n const defaultToolsIgnorePaths = [\n `!${posix.join(normalizedMastraDir, 'tools/**/*.{test,spec}.{js,ts}')}`,\n `!${posix.join(normalizedMastraDir, 'tools/**/__tests__/**')}`,\n ];\n\n // Combine default path with ignore patterns\n const defaultPaths = [defaultToolsPath, ...defaultToolsIgnorePaths];\n\n // If no tools paths provided, use only the default paths\n if (toolsPaths.length === 0) {\n return [defaultPaths];\n }\n\n // If tools paths are provided, add the default paths to ensure standard tools are always included\n return [...toolsPaths, defaultPaths];\n }\n\n async listToolsInputOptions(toolsPaths: (string | string[])[]) {\n const inputs: Record<string, string> = {};\n\n for (const toolPath of toolsPaths) {\n const expandedPaths = await glob(toolPath, {\n absolute: true,\n expandDirectories: false,\n });\n\n for (const path of expandedPaths) {\n if (await fsExtra.pathExists(path)) {\n const fileService = new FileService();\n const entryFile = fileService.getFirstExistingFile([\n join(path, 'index.ts'),\n join(path, 'index.js'),\n path, // if path itself is a file\n ]);\n\n // if it doesn't exist or is a dir skip it. using a dir as a tool will crash the process\n if (!entryFile || (await stat(entryFile)).isDirectory()) {\n this.logger.warn('No entry file found, skipping', { path });\n continue;\n }\n\n const uniqueToolID = crypto.randomUUID();\n // Normalize Windows paths to forward slashes for consistent handling\n const normalizedEntryFile = entryFile.replaceAll('\\\\', '/');\n inputs[`tools/${uniqueToolID}`] = normalizedEntryFile;\n } else {\n this.logger.warn('Tool path does not exist, skipping', { path });\n }\n }\n }\n\n return inputs;\n }\n\n protected async _bundle(\n serverFile: string,\n mastraEntryFile: string,\n {\n projectRoot,\n outputDirectory,\n enableEsmShim = true,\n }: {\n projectRoot: string;\n outputDirectory: string;\n enableEsmShim?: boolean;\n },\n toolsPaths: (string | string[])[] = [],\n bundleLocation: string = join(outputDirectory, this.outputDir),\n ): Promise<void> {\n const analyzeDir = join(outputDirectory, this.analyzeOutputDir);\n\n const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n const internalBundlerOptions: BundlerOptions = {\n enableSourcemap: !!bundlerOptions.sourcemap,\n externals: bundlerOptions.externals ?? [],\n enableEsmShim,\n dynamicPackages: bundlerOptions.dynamicPackages,\n };\n\n let analyzedBundleInfo;\n try {\n const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths);\n analyzedBundleInfo = await analyzeBundle(\n [serverFile, ...Object.values(resolvedToolsPaths)],\n mastraEntryFile,\n {\n outputDir: analyzeDir,\n projectRoot,\n platform: this.platform,\n bundlerOptions: internalBundlerOptions,\n },\n this.logger,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n if (error instanceof MastraError) {\n throw error;\n }\n\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_ANALYZE_FAILED',\n text: `Failed to analyze Mastra application: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n\n const dependenciesToInstall = new Map<string, string>();\n for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {\n if (analyzedBundleInfo.workspaceMap.has(dep) || !isBareModuleSpecifier(dep)) {\n continue;\n }\n\n let version = depInfo.version;\n let actualPackageName: string | undefined;\n\n // Read package.json to get actual package name (for alias detection) and version if not pre-resolved\n try {\n // First try to resolve from the project root (provides correct context for monorepos)\n let rootPath = await getPackageRootPath(dep, projectRoot);\n\n // If not found in user's project, try resolving from deployer's location\n // This handles packages like hono that are provided by @mastra/deployer\n if (!rootPath) {\n rootPath = await getPackageRootPath(dep, import.meta.dirname);\n }\n\n if (rootPath) {\n const pkg = await readJSON(`${rootPath}/package.json`);\n actualPackageName = pkg.name;\n // Use pre-resolved version if available, otherwise use from package.json\n if (!version) {\n version = pkg.version;\n }\n }\n } catch {\n // Resolution failed, will use 'latest' for version\n }\n\n // Default to 'latest' if still no version\n version = version || 'latest';\n\n // Check if this is an npm alias (import name differs from actual package name)\n // e.g., importing \"ai-v5\" which resolves to package \"ai\"\n // or importing \"@ai-sdk/openai-v5\" which resolves to \"@ai-sdk/openai\"\n // In this case, write npm alias syntax: \"ai-v5\": \"npm:ai@5.0.93\"\n const isAlias = actualPackageName && dep !== actualPackageName;\n\n if (isAlias) {\n dependenciesToInstall.set(dep, `npm:${actualPackageName}@${version}`);\n } else {\n dependenciesToInstall.set(dep, version);\n }\n }\n\n try {\n await this.writePackageJson(join(outputDirectory, this.outputDir), dependenciesToInstall);\n\n this.logger.info('Bundling Mastra application');\n\n const inputOptions: InputOptions = await this.getBundlerOptions(\n serverFile,\n mastraEntryFile,\n analyzedBundleInfo,\n toolsPaths,\n internalBundlerOptions,\n );\n\n const bundler = await this.createBundler(\n {\n ...inputOptions,\n logLevel: inputOptions.logLevel === 'silent' ? 'warn' : inputOptions.logLevel,\n onwarn: warning => {\n if (warning.code === 'CIRCULAR_DEPENDENCY') {\n if (warning.ids?.[0]?.includes('node_modules')) {\n return;\n }\n\n this.logger.warn('Circular dependency found', {\n dependency: warning.message.replace('Circular dependency: ', ''),\n });\n }\n },\n },\n {\n dir: bundleLocation,\n manualChunks: {\n mastra: ['#mastra'],\n },\n sourcemap: internalBundlerOptions.enableSourcemap,\n },\n );\n\n await bundler.write();\n const toolImports: string[] = [];\n const toolsExports: string[] = [];\n Array.from(Object.keys(inputOptions.input || {}))\n .filter(key => key.startsWith('tools/'))\n .forEach((key, index) => {\n const toolExport = `tool${index}`;\n toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);\n toolsExports.push(toolExport);\n });\n\n await writeFile(\n join(bundleLocation, 'tools.mjs'),\n `${toolImports.join('\\n')}\n\nexport const tools = [${toolsExports.join(', ')}]`,\n );\n this.logger.info('Bundling Mastra done');\n\n this.logger.info('Copying public files');\n await this.copyPublic(dirname(mastraEntryFile), outputDirectory);\n this.logger.info('Done copying public files');\n\n this.logger.info('Copying .npmrc file');\n await this.copyDOTNPMRC({ outputDirectory, rootDir: projectRoot });\n\n this.logger.info('Done copying .npmrc file');\n\n this.logger.info('Installing dependencies');\n await this.installDependencies(outputDirectory, projectRoot);\n this.logger.info('Done installing dependencies');\n\n this.logger.info('Generating package-lock.json for deploy');\n await this.generateNpmLockfile(join(outputDirectory, this.outputDir));\n this.logger.info('Done generating package-lock.json');\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED',\n text: `Failed during bundler bundle stage: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n }\n\n async lint(_entryFile: string, _outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);\n const toolsLength = Object.keys(toolsInputOptions).length;\n if (toolsLength > 0) {\n this.logger.info('Found tools', { count: toolsLength });\n }\n }\n}\n"]}
@@ -3,7 +3,7 @@ name: mastra-deployer
3
3
  description: Documentation for @mastra/deployer. Use when working with @mastra/deployer APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/deployer"
6
- version: "1.42.0-alpha.3"
6
+ version: "1.42.0"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.42.0-alpha.3",
2
+ "version": "1.42.0",
3
3
  "package": "@mastra/deployer",
4
4
  "exports": {
5
5
  "Deps": {
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var chunkLITSHR6E_cjs = require('./chunk-LITSHR6E.cjs');
3
+ var chunkWE66TECO_cjs = require('./chunk-WE66TECO.cjs');
4
4
  var chunkKBVOYAAL_cjs = require('./chunk-KBVOYAAL.cjs');
5
5
  var chunkUEH6D24P_cjs = require('./chunk-UEH6D24P.cjs');
6
6
 
7
7
  // src/deploy/base.ts
8
- var Deployer = class extends chunkLITSHR6E_cjs.Bundler {
8
+ var Deployer = class extends chunkWE66TECO_cjs.Bundler {
9
9
  deps = new chunkUEH6D24P_cjs.DepsService();
10
10
  constructor(args) {
11
11
  super(args.name, "DEPLOYER");
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Bundler } from './chunk-GBDZZHB2.js';
1
+ import { Bundler } from './chunk-G2ZY3BL6.js';
2
2
  import { extractMastraOption } from './chunk-FXJXKXAV.js';
3
3
  import { DepsService, FileService } from './chunk-ZIES2RI2.js';
4
4
  export { Deps, FileService, createChildProcessLogger, createPinoStream } from './chunk-ZIES2RI2.js';
@@ -3253,12 +3253,13 @@ var MastraServer = class extends serverAdapter.MastraServer {
3253
3253
  request: c.req.raw
3254
3254
  // Standard Request object with headers/cookies
3255
3255
  };
3256
- const authConfig = this.mastra.getServer()?.auth;
3257
- if (authConfig) {
3256
+ const requestContext = c.get("requestContext");
3257
+ const hasAuth = this.mastra.getStudio()?.auth || this.mastra.getServer()?.auth;
3258
+ if (hasAuth) {
3258
3259
  const hasPermission = await loadHasPermission();
3259
3260
  if (hasPermission) {
3260
- const userPermissions = c.get("requestContext").get("mastra__userPermissions");
3261
- const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);
3261
+ const userPermissions = requestContext.get("mastra__userPermissions");
3262
+ const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);
3262
3263
  if (permissionError) {
3263
3264
  return c.json(
3264
3265
  {
@@ -3350,12 +3351,18 @@ var MastraServer = class extends serverAdapter.MastraServer {
3350
3351
  return c.json({ error: authError.error }, authError.status);
3351
3352
  }
3352
3353
  }
3353
- const authConfig = this.mastra.getServer()?.auth;
3354
- if (authConfig) {
3354
+ const requestContext = c.get("requestContext");
3355
+ const hasAuth = this.mastra.getStudio()?.auth || this.mastra.getServer()?.auth;
3356
+ if (hasAuth) {
3355
3357
  const hasPermission = await loadHasPermission();
3356
3358
  if (hasPermission) {
3357
- const userPermissions = c.get("requestContext").get("mastra__userPermissions");
3358
- const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);
3359
+ const userPermissions = requestContext.get("mastra__userPermissions");
3360
+ const permissionError = this.checkRoutePermission(
3361
+ serverRoute,
3362
+ userPermissions,
3363
+ hasPermission,
3364
+ requestContext
3365
+ );
3359
3366
  if (permissionError) {
3360
3367
  return c.json(
3361
3368
  { error: permissionError.error, message: permissionError.message },
@@ -4479,6 +4486,8 @@ async function createNodeServer(mastra, options = { tools: {} }) {
4479
4486
  } else {
4480
4487
  await workerLifecycle.startEventEngine();
4481
4488
  }
4489
+ void import('@mastra/core/telemetry').then(({ syncUsageTelemetry }) => syncUsageTelemetry(mastra)).catch(() => {
4490
+ });
4482
4491
  const SHUTDOWN_TIMEOUT_MS = 5e3;
4483
4492
  let shuttingDown = false;
4484
4493
  const shutdown = async (signal) => {