@mastra/deployer 1.13.3-alpha.0 → 1.13.3-alpha.1

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 (53) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/build/analyze.cjs +2 -2
  3. package/dist/build/analyze.js +1 -1
  4. package/dist/build/bundler.cjs +3 -3
  5. package/dist/build/bundler.js +1 -1
  6. package/dist/build/index.cjs +15 -15
  7. package/dist/build/index.js +5 -5
  8. package/dist/build/utils.d.ts +1 -0
  9. package/dist/build/utils.d.ts.map +1 -1
  10. package/dist/bundler/index.cjs +3 -3
  11. package/dist/bundler/index.js +1 -1
  12. package/dist/{chunk-YKTV7TY3.cjs → chunk-5GQ4KYVA.cjs} +41 -41
  13. package/dist/{chunk-YKTV7TY3.cjs.map → chunk-5GQ4KYVA.cjs.map} +1 -1
  14. package/dist/{chunk-G7R456H2.cjs → chunk-A3JIVJHX.cjs} +3 -2
  15. package/dist/chunk-A3JIVJHX.cjs.map +1 -0
  16. package/dist/{chunk-XN3FKMO6.js → chunk-CVFIGXXI.js} +3 -2
  17. package/dist/chunk-CVFIGXXI.js.map +1 -0
  18. package/dist/{chunk-JNJDIOG2.js → chunk-EIHBOFJ2.js} +7 -7
  19. package/dist/{chunk-JNJDIOG2.js.map → chunk-EIHBOFJ2.js.map} +1 -1
  20. package/dist/{chunk-37PC7CXR.cjs → chunk-I4JVB6BK.cjs} +16 -16
  21. package/dist/{chunk-37PC7CXR.cjs.map → chunk-I4JVB6BK.cjs.map} +1 -1
  22. package/dist/{chunk-GSO2J4MT.js → chunk-IGXPFW6N.js} +4 -4
  23. package/dist/{chunk-GSO2J4MT.js.map → chunk-IGXPFW6N.js.map} +1 -1
  24. package/dist/{chunk-GRC4HK7K.js → chunk-KFHJXZBM.js} +7 -7
  25. package/dist/{chunk-GRC4HK7K.js.map → chunk-KFHJXZBM.js.map} +1 -1
  26. package/dist/{chunk-4O7AWOLQ.cjs → chunk-LYJKUXY5.cjs} +17 -17
  27. package/dist/{chunk-4O7AWOLQ.cjs.map → chunk-LYJKUXY5.cjs.map} +1 -1
  28. package/dist/{chunk-V245ALKI.cjs → chunk-NNVFGNAO.cjs} +4 -4
  29. package/dist/{chunk-V245ALKI.cjs.map → chunk-NNVFGNAO.cjs.map} +1 -1
  30. package/dist/{chunk-IY4RBV63.js → chunk-OOGT37UD.js} +4 -4
  31. package/dist/{chunk-IY4RBV63.js.map → chunk-OOGT37UD.js.map} +1 -1
  32. package/dist/{chunk-3Y3N6DCM.cjs → chunk-QT5YQ63Q.cjs} +7 -7
  33. package/dist/{chunk-3Y3N6DCM.cjs.map → chunk-QT5YQ63Q.cjs.map} +1 -1
  34. package/dist/{chunk-PM35TGRT.cjs → chunk-QTMOHGMX.cjs} +16 -16
  35. package/dist/{chunk-PM35TGRT.cjs.map → chunk-QTMOHGMX.cjs.map} +1 -1
  36. package/dist/{chunk-HXQ27JQX.js → chunk-WQFD37DQ.js} +3 -3
  37. package/dist/{chunk-HXQ27JQX.js.map → chunk-WQFD37DQ.js.map} +1 -1
  38. package/dist/{chunk-MPZSAF6V.js → chunk-X3T5NPCG.js} +3 -3
  39. package/dist/{chunk-MPZSAF6V.js.map → chunk-X3T5NPCG.js.map} +1 -1
  40. package/dist/docs/SKILL.md +1 -1
  41. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  42. package/dist/index.cjs +4 -4
  43. package/dist/index.js +2 -2
  44. package/dist/server/index.cjs +15 -10
  45. package/dist/server/index.cjs.map +1 -1
  46. package/dist/server/index.d.ts.map +1 -1
  47. package/dist/server/index.js +12 -7
  48. package/dist/server/index.js.map +1 -1
  49. package/dist/validator/custom-resolver.cjs +3 -3
  50. package/dist/validator/custom-resolver.js +1 -1
  51. package/package.json +8 -8
  52. package/dist/chunk-G7R456H2.cjs.map +0 -1
  53. package/dist/chunk-XN3FKMO6.js.map +0 -1
@@ -82,6 +82,7 @@ function injectStudioHtmlConfig(html, config) {
82
82
  html = html.replace(`'%%MASTRA_HIDE_CLOUD_CTA%%'`, config.hideCloudCta);
83
83
  html = html.replace(`'%%MASTRA_CLOUD_API_ENDPOINT%%'`, config.cloudApiEndpoint);
84
84
  html = html.replace(`'%%MASTRA_EXPERIMENTAL_FEATURES%%'`, config.experimentalFeatures);
85
+ html = html.replace(`'%%MASTRA_TEMPLATES%%'`, config.templates);
85
86
  html = html.replace(`'%%MASTRA_TELEMETRY_DISABLED%%'`, config.telemetryDisabled);
86
87
  html = html.replace(`'%%MASTRA_REQUEST_CONTEXT_PRESETS%%'`, config.requestContextPresets);
87
88
  if (config.autoDetectUrl) {
@@ -104,5 +105,5 @@ exports.isDependencyPartOfPackage = isDependencyPartOfPackage;
104
105
  exports.normalizeStudioBase = normalizeStudioBase;
105
106
  exports.rollupSafeName = rollupSafeName;
106
107
  exports.slash = slash;
107
- //# sourceMappingURL=chunk-G7R456H2.cjs.map
108
- //# sourceMappingURL=chunk-G7R456H2.cjs.map
108
+ //# sourceMappingURL=chunk-A3JIVJHX.cjs.map
109
+ //# sourceMappingURL=chunk-A3JIVJHX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/build/utils.ts"],"names":["join","relative","basename","builtinModules"],"mappings":";;;;;;AA0BO,SAAS,sBAAsB,QAAA,EAAqD;AACzF,EAAA,IAAI,aAAa,SAAA,EAAW;AAC1B,IAAA,OAAO;AAAA,MACL,cAAA,EAAgB,KAAA;AAAA,MAChB,OAAA,EAAS,IAAA;AAAA,MACT,gBAAA,EAAkB,CAAC,SAAA,EAAW,QAAA,EAAU,SAAS;AAAA,KACnD;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB,IAAA;AAAA,IAChB,gBAAA,EAAkB,CAAC,MAAM;AAAA,GAC3B;AACF;AASO,SAAS,aAAA,GAAiC;AAC/C,EAAA,IAAI,OAAA,CAAQ,UAAU,GAAA,EAAK;AACzB,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OA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AAA,IAC5BA,uBAAA,CAAe,QAAA,CAAS,SAAA,CAAU,OAAA,CAAQ,QAAA,EAAU,EAAE,CAAC,CAAA;AAE3D","file":"chunk-A3JIVJHX.cjs","sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync } from 'node:fs';\nimport { builtinModules } from 'node:module';\nimport { basename, join, relative } from 'node:path';\nimport type { RollupNodeResolveOptions } from '@rollup/plugin-node-resolve';\n\n/** The detected JavaScript runtime environment */\nexport type RuntimePlatform = 'node' | 'bun';\n\n/**\n * The esbuild/bundler platform setting.\n * - 'node': Assumes Node.js environment, externalizes built-in modules\n * - 'browser': Assumes browser environment, polyfills Node APIs\n * - 'neutral': Runtime-agnostic, preserves all globals as-is (used for Bun)\n */\nexport type BundlerPlatform = 'node' | 'browser' | 'neutral';\n\n/**\n * Get nodeResolve plugin options based on the target platform.\n *\n * For 'browser' platform (e.g., Cloudflare Workers), uses browser-compatible\n * export conditions so packages like the Cloudflare SDK resolve to their\n * web runtime instead of Node.js-specific code.\n *\n * For 'node' and 'neutral' (Bun) platforms, uses Node.js module resolution.\n */\nexport function getNodeResolveOptions(platform: BundlerPlatform): RollupNodeResolveOptions {\n if (platform === 'browser') {\n return {\n preferBuiltins: false,\n browser: true,\n exportConditions: ['browser', 'worker', 'default'],\n };\n }\n return {\n preferBuiltins: true,\n exportConditions: ['node'],\n };\n}\n\n/**\n * Detect the current JavaScript runtime environment.\n *\n * This is used by the bundler to determine the appropriate esbuild platform\n * setting. When running under Bun, we need to use 'neutral' platform to\n * preserve Bun-specific globals (like Bun.s3).\n */\nexport function detectRuntime(): RuntimePlatform {\n if (process.versions?.bun) {\n return 'bun';\n }\n return 'node';\n}\n\nexport function upsertMastraDir({ dir = process.cwd() }: { dir?: string }) {\n const dirPath = join(dir, '.mastra');\n\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n execSync(`echo \".mastra\" >> .gitignore`);\n }\n}\n\nexport function isDependencyPartOfPackage(dep: string, packageName: string) {\n if (dep === packageName) {\n return true;\n }\n\n return dep.startsWith(`${packageName}/`);\n}\n\n/**\n * Get the package name from a module ID\n */\nexport function getPackageName(id: string) {\n const parts = id.split('/');\n\n if (id.startsWith('@')) {\n return parts.slice(0, 2).join('/');\n }\n\n return parts[0];\n}\n\n/**\n * During `mastra dev` we are compiling TS files to JS (inside workspaces) so that users can just their workspace packages.\n * We store these compiled files inside `node_modules/.cache` for each workspace package.\n */\nexport function getCompiledDepCachePath(rootPath: string, packageName: string) {\n return slash(join(rootPath, 'node_modules', '.cache', packageName));\n}\n\n/**\n * Convert windows backslashes to posix slashes\n *\n * @example\n * ```ts\n * slash('C:\\\\Users\\\\user\\\\code\\\\mastra') // 'C:/Users/user/code/mastra'\n * ```\n */\nexport function slash(path: string) {\n const isExtendedLengthPath = path.startsWith('\\\\\\\\?\\\\');\n\n if (isExtendedLengthPath) {\n return path;\n }\n\n return path.replaceAll('\\\\', '/');\n}\n\n/**\n * Make a Rollup-safe name: pathless, POSIX, and without parent/absolute segments\n */\nexport function rollupSafeName(name: string, rootDir: string) {\n const rel = relative(rootDir, name);\n let entry = slash(rel);\n entry = entry.replace(/^(\\.\\.\\/)+/, '');\n entry = entry.replace(/^\\/+/, '');\n entry = entry.replace(/^[A-Za-z]:\\//, '');\n if (!entry) {\n entry = slash(basename(name));\n }\n return entry;\n}\n\n/**\n * Native binding loaders and infrastructure packages that should be ignored when identifying the actual package that requires native bindings\n */\nconst NATIVE_BINDING_LOADERS = [\n 'node-gyp-build',\n 'prebuild-install',\n 'bindings',\n 'node-addon-api',\n 'node-pre-gyp',\n 'nan', // Native Abstractions for Node.js\n] as const;\n\n/**\n * Finds the first real package from node_modules that likely contains native bindings, filtering out virtual modules and native binding loader infrastructure.\n *\n * @param moduleIds - Array of module IDs from a Rollup chunk\n * @returns The module ID of the actual native package, or undefined if not found\n *\n * @example\n * const moduleIds = [\n * '\\x00/path/node_modules/bcrypt/bcrypt.js?commonjs-module',\n * '/path/node_modules/node-gyp-build/index.js',\n * '/path/node_modules/bcrypt/bcrypt.js',\n * ];\n * findNativePackageModule(moduleIds); // Returns '/path/node_modules/bcrypt/bcrypt.js'\n */\nexport function findNativePackageModule(moduleIds: string[]): string | undefined {\n return moduleIds.find(id => {\n // Skip virtual modules (Rollup plugin-generated)\n if (id.startsWith('\\x00')) {\n return false;\n }\n\n // Must be from node_modules\n if (!id.includes('/node_modules/')) {\n return false;\n }\n\n // Skip native binding loader infrastructure\n for (const loader of NATIVE_BINDING_LOADERS) {\n if (id.includes(`/${loader}/`) || id.includes(`/${loader}@`)) {\n return false;\n }\n }\n\n return true;\n });\n}\n\n/**\n * Ensures that server.studioBase is normalized:\n * - Adds leading slash if missing (e.g., 'admin' → '/admin')\n * - Removes trailing slashes (e.g., '/admin/' → '/admin')\n * - Normalizes multiple slashes to single slash (e.g., '//api' → '/api')\n * - Returns empty string for root paths ('/' or '')\n *\n * @param studioBase - The studioBase path to normalize\n * @returns Normalized studioBase path string\n * @throws Error if path contains invalid characters ('..', '?', '#')\n */\nexport function normalizeStudioBase(studioBase: string): string {\n studioBase = studioBase.trim();\n\n // Validate: no path traversal, no query params, no special chars\n if (studioBase.includes('..') || studioBase.includes('?') || studioBase.includes('#')) {\n throw new Error(`Invalid base path: \"${studioBase}\". Base path cannot contain '..', '?', or '#'`);\n }\n\n // Normalize multiple slashes to single slash\n studioBase = studioBase.replace(/\\/+/g, '/');\n\n // Handle default value cases\n if (studioBase === '/' || studioBase === '') {\n return '';\n }\n\n // Remove trailing slash\n if (studioBase.endsWith('/')) {\n studioBase = studioBase.slice(0, -1);\n }\n\n // Add leading slash if missing\n if (!studioBase.startsWith('/')) {\n studioBase = `/${studioBase}`;\n }\n\n return studioBase;\n}\n\n/**\n * Configuration values for Studio's index.html placeholder injection.\n *\n * Each value is the **exact JavaScript expression** that replaces the\n * corresponding `'%%PLACEHOLDER%%'` token (including surrounding quotes).\n *\n * For literal strings pass `\"'value'\"` (quoted).\n * For runtime expressions pass the raw JS, e.g. `\"window.location.hostname\"`.\n */\nexport interface StudioInjectionConfig {\n host: string;\n port: string;\n protocol: string;\n apiPrefix: string;\n basePath: string;\n hideCloudCta: string;\n cloudApiEndpoint: string;\n experimentalFeatures: string;\n templates: string;\n telemetryDisabled: string;\n requestContextPresets: string;\n autoDetectUrl?: string;\n}\n\n/**\n * Replace all `%%MASTRA_*%%` placeholders in the Studio `index.html` with the\n * supplied configuration values.\n *\n * The `<base href>` tag and the `window.MASTRA_STUDIO_BASE_PATH` assignment\n * use `basePath` as a plain string (no surrounding quotes), while all other\n * placeholders replace `'%%TOKEN%%'` (with surrounding single-quotes in the\n * source HTML) with the provided expression verbatim.\n */\nexport function injectStudioHtmlConfig(html: string, config: StudioInjectionConfig): string {\n html = html.replace(`'%%MASTRA_SERVER_HOST%%'`, config.host);\n html = html.replace(`'%%MASTRA_SERVER_PORT%%'`, config.port);\n html = html.replace(`'%%MASTRA_SERVER_PROTOCOL%%'`, config.protocol);\n html = html.replace(`'%%MASTRA_API_PREFIX%%'`, config.apiPrefix);\n html = html.replace(`'%%MASTRA_HIDE_CLOUD_CTA%%'`, config.hideCloudCta);\n html = html.replace(`'%%MASTRA_CLOUD_API_ENDPOINT%%'`, config.cloudApiEndpoint);\n html = html.replace(`'%%MASTRA_EXPERIMENTAL_FEATURES%%'`, config.experimentalFeatures);\n html = html.replace(`'%%MASTRA_TEMPLATES%%'`, config.templates);\n html = html.replace(`'%%MASTRA_TELEMETRY_DISABLED%%'`, config.telemetryDisabled);\n html = html.replace(`'%%MASTRA_REQUEST_CONTEXT_PRESETS%%'`, config.requestContextPresets);\n if (config.autoDetectUrl) {\n html = html.replace(`'%%MASTRA_AUTO_DETECT_URL%%'`, config.autoDetectUrl);\n }\n html = html.replaceAll('%%MASTRA_STUDIO_BASE_PATH%%', config.basePath);\n\n return html;\n}\n\n/**\n * Check if a module is a Node.js builtin module\n * @param specifier - Module specifier\n * @returns True if it's a builtin module\n */\nexport function isBuiltinModule(specifier: string): boolean {\n return (\n builtinModules.includes(specifier) ||\n specifier.startsWith('node:') ||\n builtinModules.includes(specifier.replace(/^node:/, ''))\n );\n}\n"]}
@@ -80,6 +80,7 @@ function injectStudioHtmlConfig(html, config) {
80
80
  html = html.replace(`'%%MASTRA_HIDE_CLOUD_CTA%%'`, config.hideCloudCta);
81
81
  html = html.replace(`'%%MASTRA_CLOUD_API_ENDPOINT%%'`, config.cloudApiEndpoint);
82
82
  html = html.replace(`'%%MASTRA_EXPERIMENTAL_FEATURES%%'`, config.experimentalFeatures);
83
+ html = html.replace(`'%%MASTRA_TEMPLATES%%'`, config.templates);
83
84
  html = html.replace(`'%%MASTRA_TELEMETRY_DISABLED%%'`, config.telemetryDisabled);
84
85
  html = html.replace(`'%%MASTRA_REQUEST_CONTEXT_PRESETS%%'`, config.requestContextPresets);
85
86
  if (config.autoDetectUrl) {
@@ -93,5 +94,5 @@ function isBuiltinModule(specifier) {
93
94
  }
94
95
 
95
96
  export { detectRuntime, getCompiledDepCachePath, getNodeResolveOptions, getPackageName, injectStudioHtmlConfig, isBuiltinModule, isDependencyPartOfPackage, normalizeStudioBase, rollupSafeName, slash };
96
- //# sourceMappingURL=chunk-XN3FKMO6.js.map
97
- //# sourceMappingURL=chunk-XN3FKMO6.js.map
97
+ //# sourceMappingURL=chunk-CVFIGXXI.js.map
98
+ //# sourceMappingURL=chunk-CVFIGXXI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/build/utils.ts"],"names":[],"mappings":";;;;AA0BO,SAAS,sBAAsB,QAAA,EAAqD;AACzF,EAAA,IAAI,aAAa,SAAA,EAAW;AAC1B,IAAA,OAAO;AAAA,MACL,cAAA,EAAgB,KAAA;AAAA,MAChB,OAAA,EAAS,IAAA;AAAA,MACT,gBAAA,EAAkB,CAAC,SAAA,EAAW,QAAA,EAAU,SAAS;AAAA,KACnD;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB,IAAA;AAAA,IAChB,gBAAA,EAAkB,C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ErE,EAAA,OAAO,IAAA;AACT;AAOO,SAAS,gBAAgB,SAAA,EAA4B;AAC1D,EAAA,OACE,cAAA,CAAe,QAAA,CAAS,SAAS,CAAA,IACjC,UAAU,UAAA,CAAW,OAAO,CAAA,IAC5B,cAAA,CAAe,QAAA,CAAS,SAAA,CAAU,OAAA,CAAQ,QAAA,EAAU,EAAE,CAAC,CAAA;AAE3D","file":"chunk-CVFIGXXI.js","sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync } from 'node:fs';\nimport { builtinModules } from 'node:module';\nimport { basename, join, relative } from 'node:path';\nimport type { RollupNodeResolveOptions } from '@rollup/plugin-node-resolve';\n\n/** The detected JavaScript runtime environment */\nexport type RuntimePlatform = 'node' | 'bun';\n\n/**\n * The esbuild/bundler platform setting.\n * - 'node': Assumes Node.js environment, externalizes built-in modules\n * - 'browser': Assumes browser environment, polyfills Node APIs\n * - 'neutral': Runtime-agnostic, preserves all globals as-is (used for Bun)\n */\nexport type BundlerPlatform = 'node' | 'browser' | 'neutral';\n\n/**\n * Get nodeResolve plugin options based on the target platform.\n *\n * For 'browser' platform (e.g., Cloudflare Workers), uses browser-compatible\n * export conditions so packages like the Cloudflare SDK resolve to their\n * web runtime instead of Node.js-specific code.\n *\n * For 'node' and 'neutral' (Bun) platforms, uses Node.js module resolution.\n */\nexport function getNodeResolveOptions(platform: BundlerPlatform): RollupNodeResolveOptions {\n if (platform === 'browser') {\n return {\n preferBuiltins: false,\n browser: true,\n exportConditions: ['browser', 'worker', 'default'],\n };\n }\n return {\n preferBuiltins: true,\n exportConditions: ['node'],\n };\n}\n\n/**\n * Detect the current JavaScript runtime environment.\n *\n * This is used by the bundler to determine the appropriate esbuild platform\n * setting. When running under Bun, we need to use 'neutral' platform to\n * preserve Bun-specific globals (like Bun.s3).\n */\nexport function detectRuntime(): RuntimePlatform {\n if (process.versions?.bun) {\n return 'bun';\n }\n return 'node';\n}\n\nexport function upsertMastraDir({ dir = process.cwd() }: { dir?: string }) {\n const dirPath = join(dir, '.mastra');\n\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n execSync(`echo \".mastra\" >> .gitignore`);\n }\n}\n\nexport function isDependencyPartOfPackage(dep: string, packageName: string) {\n if (dep === packageName) {\n return true;\n }\n\n return dep.startsWith(`${packageName}/`);\n}\n\n/**\n * Get the package name from a module ID\n */\nexport function getPackageName(id: string) {\n const parts = id.split('/');\n\n if (id.startsWith('@')) {\n return parts.slice(0, 2).join('/');\n }\n\n return parts[0];\n}\n\n/**\n * During `mastra dev` we are compiling TS files to JS (inside workspaces) so that users can just their workspace packages.\n * We store these compiled files inside `node_modules/.cache` for each workspace package.\n */\nexport function getCompiledDepCachePath(rootPath: string, packageName: string) {\n return slash(join(rootPath, 'node_modules', '.cache', packageName));\n}\n\n/**\n * Convert windows backslashes to posix slashes\n *\n * @example\n * ```ts\n * slash('C:\\\\Users\\\\user\\\\code\\\\mastra') // 'C:/Users/user/code/mastra'\n * ```\n */\nexport function slash(path: string) {\n const isExtendedLengthPath = path.startsWith('\\\\\\\\?\\\\');\n\n if (isExtendedLengthPath) {\n return path;\n }\n\n return path.replaceAll('\\\\', '/');\n}\n\n/**\n * Make a Rollup-safe name: pathless, POSIX, and without parent/absolute segments\n */\nexport function rollupSafeName(name: string, rootDir: string) {\n const rel = relative(rootDir, name);\n let entry = slash(rel);\n entry = entry.replace(/^(\\.\\.\\/)+/, '');\n entry = entry.replace(/^\\/+/, '');\n entry = entry.replace(/^[A-Za-z]:\\//, '');\n if (!entry) {\n entry = slash(basename(name));\n }\n return entry;\n}\n\n/**\n * Native binding loaders and infrastructure packages that should be ignored when identifying the actual package that requires native bindings\n */\nconst NATIVE_BINDING_LOADERS = [\n 'node-gyp-build',\n 'prebuild-install',\n 'bindings',\n 'node-addon-api',\n 'node-pre-gyp',\n 'nan', // Native Abstractions for Node.js\n] as const;\n\n/**\n * Finds the first real package from node_modules that likely contains native bindings, filtering out virtual modules and native binding loader infrastructure.\n *\n * @param moduleIds - Array of module IDs from a Rollup chunk\n * @returns The module ID of the actual native package, or undefined if not found\n *\n * @example\n * const moduleIds = [\n * '\\x00/path/node_modules/bcrypt/bcrypt.js?commonjs-module',\n * '/path/node_modules/node-gyp-build/index.js',\n * '/path/node_modules/bcrypt/bcrypt.js',\n * ];\n * findNativePackageModule(moduleIds); // Returns '/path/node_modules/bcrypt/bcrypt.js'\n */\nexport function findNativePackageModule(moduleIds: string[]): string | undefined {\n return moduleIds.find(id => {\n // Skip virtual modules (Rollup plugin-generated)\n if (id.startsWith('\\x00')) {\n return false;\n }\n\n // Must be from node_modules\n if (!id.includes('/node_modules/')) {\n return false;\n }\n\n // Skip native binding loader infrastructure\n for (const loader of NATIVE_BINDING_LOADERS) {\n if (id.includes(`/${loader}/`) || id.includes(`/${loader}@`)) {\n return false;\n }\n }\n\n return true;\n });\n}\n\n/**\n * Ensures that server.studioBase is normalized:\n * - Adds leading slash if missing (e.g., 'admin' → '/admin')\n * - Removes trailing slashes (e.g., '/admin/' → '/admin')\n * - Normalizes multiple slashes to single slash (e.g., '//api' → '/api')\n * - Returns empty string for root paths ('/' or '')\n *\n * @param studioBase - The studioBase path to normalize\n * @returns Normalized studioBase path string\n * @throws Error if path contains invalid characters ('..', '?', '#')\n */\nexport function normalizeStudioBase(studioBase: string): string {\n studioBase = studioBase.trim();\n\n // Validate: no path traversal, no query params, no special chars\n if (studioBase.includes('..') || studioBase.includes('?') || studioBase.includes('#')) {\n throw new Error(`Invalid base path: \"${studioBase}\". Base path cannot contain '..', '?', or '#'`);\n }\n\n // Normalize multiple slashes to single slash\n studioBase = studioBase.replace(/\\/+/g, '/');\n\n // Handle default value cases\n if (studioBase === '/' || studioBase === '') {\n return '';\n }\n\n // Remove trailing slash\n if (studioBase.endsWith('/')) {\n studioBase = studioBase.slice(0, -1);\n }\n\n // Add leading slash if missing\n if (!studioBase.startsWith('/')) {\n studioBase = `/${studioBase}`;\n }\n\n return studioBase;\n}\n\n/**\n * Configuration values for Studio's index.html placeholder injection.\n *\n * Each value is the **exact JavaScript expression** that replaces the\n * corresponding `'%%PLACEHOLDER%%'` token (including surrounding quotes).\n *\n * For literal strings pass `\"'value'\"` (quoted).\n * For runtime expressions pass the raw JS, e.g. `\"window.location.hostname\"`.\n */\nexport interface StudioInjectionConfig {\n host: string;\n port: string;\n protocol: string;\n apiPrefix: string;\n basePath: string;\n hideCloudCta: string;\n cloudApiEndpoint: string;\n experimentalFeatures: string;\n templates: string;\n telemetryDisabled: string;\n requestContextPresets: string;\n autoDetectUrl?: string;\n}\n\n/**\n * Replace all `%%MASTRA_*%%` placeholders in the Studio `index.html` with the\n * supplied configuration values.\n *\n * The `<base href>` tag and the `window.MASTRA_STUDIO_BASE_PATH` assignment\n * use `basePath` as a plain string (no surrounding quotes), while all other\n * placeholders replace `'%%TOKEN%%'` (with surrounding single-quotes in the\n * source HTML) with the provided expression verbatim.\n */\nexport function injectStudioHtmlConfig(html: string, config: StudioInjectionConfig): string {\n html = html.replace(`'%%MASTRA_SERVER_HOST%%'`, config.host);\n html = html.replace(`'%%MASTRA_SERVER_PORT%%'`, config.port);\n html = html.replace(`'%%MASTRA_SERVER_PROTOCOL%%'`, config.protocol);\n html = html.replace(`'%%MASTRA_API_PREFIX%%'`, config.apiPrefix);\n html = html.replace(`'%%MASTRA_HIDE_CLOUD_CTA%%'`, config.hideCloudCta);\n html = html.replace(`'%%MASTRA_CLOUD_API_ENDPOINT%%'`, config.cloudApiEndpoint);\n html = html.replace(`'%%MASTRA_EXPERIMENTAL_FEATURES%%'`, config.experimentalFeatures);\n html = html.replace(`'%%MASTRA_TEMPLATES%%'`, config.templates);\n html = html.replace(`'%%MASTRA_TELEMETRY_DISABLED%%'`, config.telemetryDisabled);\n html = html.replace(`'%%MASTRA_REQUEST_CONTEXT_PRESETS%%'`, config.requestContextPresets);\n if (config.autoDetectUrl) {\n html = html.replace(`'%%MASTRA_AUTO_DETECT_URL%%'`, config.autoDetectUrl);\n }\n html = html.replaceAll('%%MASTRA_STUDIO_BASE_PATH%%', config.basePath);\n\n return html;\n}\n\n/**\n * Check if a module is a Node.js builtin module\n * @param specifier - Module specifier\n * @returns True if it's a builtin module\n */\nexport function isBuiltinModule(specifier: string): boolean {\n return (\n builtinModules.includes(specifier) ||\n specifier.startsWith('node:') ||\n builtinModules.includes(specifier.replace(/^node:/, ''))\n );\n}\n"]}
@@ -1,8 +1,8 @@
1
- import { extractMastraOption } from './chunk-HXQ27JQX.js';
2
- import { getWorkspaceInformation, analyzeBundle, aliasHono } from './chunk-IY4RBV63.js';
3
- import { getInputOptions, nodeModulesExtensionResolver } from './chunk-GSO2J4MT.js';
4
- import { tsConfigPaths } from './chunk-MPZSAF6V.js';
5
- import { slash, getPackageName } from './chunk-XN3FKMO6.js';
1
+ import { extractMastraOption } from './chunk-WQFD37DQ.js';
2
+ import { getWorkspaceInformation, analyzeBundle, aliasHono } from './chunk-OOGT37UD.js';
3
+ import { getInputOptions, nodeModulesExtensionResolver } from './chunk-IGXPFW6N.js';
4
+ import { tsConfigPaths } from './chunk-X3T5NPCG.js';
5
+ import { slash, getPackageName } from './chunk-CVFIGXXI.js';
6
6
  import { dirname, posix } from 'path';
7
7
  import { noopLogger } from '@mastra/core/logger';
8
8
  import * as pkg from 'empathic/package';
@@ -94,5 +94,5 @@ async function getServerOptions(entryFile, outputDir, logger) {
94
94
  }
95
95
 
96
96
  export { createWatcher, getInputOptions2 as getInputOptions, getServerOptions };
97
- //# sourceMappingURL=chunk-JNJDIOG2.js.map
98
- //# sourceMappingURL=chunk-JNJDIOG2.js.map
97
+ //# sourceMappingURL=chunk-EIHBOFJ2.js.map
98
+ //# sourceMappingURL=chunk-EIHBOFJ2.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/build/watcher.ts","../src/build/serverOptions.ts"],"names":["getInputOptions"],"mappings":";;;;;;;;;;AAeA,eAAsBA,gBAAAA,CACpB,SAAA,EACA,QAAA,EACA,GAAA,EACA;AAAA,EACE,SAAA,GAAY,KAAA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OAAO,OAAA;AACT;;;AC9FA,eAAsB,gBAAA,CACpB,SAAA,EACA,SAAA,EACA,MAAA,EACkC;AAClC,EAAA,MAAM,SAAS,MAAM,mBAAA,CAAoB,QAAA,EAAU,SAAA,EAAW,WAAW,MAAM,CAAA;AAC/E,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,OAAO,SAAA,EAAU;AAC1B","file":"chunk-JNJDIOG2.js","sourcesContent":["import { dirname, posix } from 'node:path';\nimport { noopLogger } from '@mastra/core/logger';\nimport * as pkg from 'empathic/package';\nimport type { InputOptions, OutputOptions, Plugin } from 'rollup';\nimport { watch } from 'rollup';\nimport { getWorkspaceInformation } from '../bundler/workspaceDependencies';\nimport { analyzeBundle } from './analyze';\nimport { getInputOptions as getBundlerInputOptions } from './bundler';\nimport { aliasHono } from './plugins/hono-alias';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport type { BundlerOptions } from './types';\nimport { getPackageName, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport async function getInputOptions(\n entryFile: string,\n platform: BundlerPlatform,\n env?: Record<string, string>,\n {\n sourcemap = false,\n bundlerOptions = {\n enableSourcemap: false,\n enableEsmShim: true,\n externals: true,\n },\n }: { sourcemap?: boolean; bundlerOptions?: BundlerOptions } = {},\n) {\n const closestPkgJson = pkg.up({ cwd: dirname(entryFile) });\n const projectRoot = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());\n const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: entryFile });\n\n const analyzeEntryResult = await analyzeBundle(\n [entryFile],\n entryFile,\n {\n outputDir: posix.join(process.cwd(), '.mastra', '.build'),\n projectRoot: workspaceRoot || process.cwd(),\n platform,\n isDev: true,\n bundlerOptions,\n },\n noopLogger,\n );\n\n const deps = /* @__PURE__ */ new Map();\n for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {\n const pkgName = getPackageName(dep);\n if (pkgName && workspaceMap.has(pkgName)) {\n deps.set(dep, metadata);\n }\n }\n\n const inputOptions = await getBundlerInputOptions(\n entryFile,\n {\n dependencies: deps,\n externalDependencies: new Map(),\n workspaceMap,\n },\n platform,\n env,\n { sourcemap, isDev: true, workspaceRoot, projectRoot, externalsPreset: bundlerOptions?.externals === true },\n );\n\n if (Array.isArray(inputOptions.plugins)) {\n // filter out node-resolve plugin so all node_modules are external\n // and tsconfig-paths plugin as we are injection a custom one\n const plugins = [] as Plugin[];\n inputOptions.plugins.forEach(plugin => {\n if ((plugin as Plugin | undefined)?.name === 'node-resolve') {\n return;\n }\n\n if ((plugin as Plugin | undefined)?.name === 'tsconfig-paths') {\n plugins.push(\n tsConfigPaths({\n localResolve: true,\n }),\n );\n return;\n }\n\n plugins.push(plugin as Plugin);\n });\n\n inputOptions.plugins = plugins;\n inputOptions.plugins.push(aliasHono());\n // fixes imports like lodash/fp/get\n inputOptions.plugins.push(nodeModulesExtensionResolver());\n }\n\n return inputOptions;\n}\n\nexport async function createWatcher(inputOptions: InputOptions, outputOptions: OutputOptions) {\n const watcher = await watch({\n ...inputOptions,\n output: {\n ...outputOptions,\n format: 'esm',\n entryFileNames: '[name].mjs',\n chunkFileNames: '[name].mjs',\n },\n });\n\n return watcher;\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport type { Config } from '@mastra/core/mastra';\nimport { extractMastraOption, extractMastraOptionBundler } from './shared/extract-mastra-option';\n\nexport function getServerOptionsBundler(\n entryFile: string,\n result: {\n hasCustomConfig: false;\n },\n) {\n return extractMastraOptionBundler('server', entryFile, result);\n}\n\nexport async function getServerOptions(\n entryFile: string,\n outputDir: string,\n logger?: IMastraLogger,\n): Promise<Config['server'] | null> {\n const result = await extractMastraOption('server', entryFile, outputDir, logger);\n if (!result) {\n return null;\n }\n\n return result.getConfig();\n}\n"]}
1
+ {"version":3,"sources":["../src/build/watcher.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;AAAA,MACN,GAAG,aAAA;AAAA,MACH,MAAA,EAAQ,KAAA;AAAA,MACR,cAAA,EAAgB,YAAA;AAAA,MAChB,cAAA,EAAgB;AAAA;AAClB,GACD,CAAA;AAED,EAAA,OAAO,OAAA;AACT;;;AC9FA,eAAsB,gBAAA,CACpB,SAAA,EACA,SAAA,EACA,MAAA,EACkC;AAClC,EAAA,MAAM,SAAS,MAAM,mBAAA,CAAoB,QAAA,EAAU,SAAA,EAAW,WAAW,MAAM,CAAA;AAC/E,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,OAAO,SAAA,EAAU;AAC1B","file":"chunk-EIHBOFJ2.js","sourcesContent":["import { dirname, posix } from 'node:path';\nimport { noopLogger } from '@mastra/core/logger';\nimport * as pkg from 'empathic/package';\nimport type { InputOptions, OutputOptions, Plugin } from 'rollup';\nimport { watch } from 'rollup';\nimport { getWorkspaceInformation } from '../bundler/workspaceDependencies';\nimport { analyzeBundle } from './analyze';\nimport { getInputOptions as getBundlerInputOptions } from './bundler';\nimport { aliasHono } from './plugins/hono-alias';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport type { BundlerOptions } from './types';\nimport { getPackageName, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport async function getInputOptions(\n entryFile: string,\n platform: BundlerPlatform,\n env?: Record<string, string>,\n {\n sourcemap = false,\n bundlerOptions = {\n enableSourcemap: false,\n enableEsmShim: true,\n externals: true,\n },\n }: { sourcemap?: boolean; bundlerOptions?: BundlerOptions } = {},\n) {\n const closestPkgJson = pkg.up({ cwd: dirname(entryFile) });\n const projectRoot = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());\n const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: entryFile });\n\n const analyzeEntryResult = await analyzeBundle(\n [entryFile],\n entryFile,\n {\n outputDir: posix.join(process.cwd(), '.mastra', '.build'),\n projectRoot: workspaceRoot || process.cwd(),\n platform,\n isDev: true,\n bundlerOptions,\n },\n noopLogger,\n );\n\n const deps = /* @__PURE__ */ new Map();\n for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {\n const pkgName = getPackageName(dep);\n if (pkgName && workspaceMap.has(pkgName)) {\n deps.set(dep, metadata);\n }\n }\n\n const inputOptions = await getBundlerInputOptions(\n entryFile,\n {\n dependencies: deps,\n externalDependencies: new Map(),\n workspaceMap,\n },\n platform,\n env,\n { sourcemap, isDev: true, workspaceRoot, projectRoot, externalsPreset: bundlerOptions?.externals === true },\n );\n\n if (Array.isArray(inputOptions.plugins)) {\n // filter out node-resolve plugin so all node_modules are external\n // and tsconfig-paths plugin as we are injection a custom one\n const plugins = [] as Plugin[];\n inputOptions.plugins.forEach(plugin => {\n if ((plugin as Plugin | undefined)?.name === 'node-resolve') {\n return;\n }\n\n if ((plugin as Plugin | undefined)?.name === 'tsconfig-paths') {\n plugins.push(\n tsConfigPaths({\n localResolve: true,\n }),\n );\n return;\n }\n\n plugins.push(plugin as Plugin);\n });\n\n inputOptions.plugins = plugins;\n inputOptions.plugins.push(aliasHono());\n // fixes imports like lodash/fp/get\n inputOptions.plugins.push(nodeModulesExtensionResolver());\n }\n\n return inputOptions;\n}\n\nexport async function createWatcher(inputOptions: InputOptions, outputOptions: OutputOptions) {\n const watcher = await watch({\n ...inputOptions,\n output: {\n ...outputOptions,\n format: 'esm',\n entryFileNames: '[name].mjs',\n chunkFileNames: '[name].mjs',\n },\n });\n\n return watcher;\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport type { Config } from '@mastra/core/mastra';\nimport { extractMastraOption, extractMastraOptionBundler } from './shared/extract-mastra-option';\n\nexport function getServerOptionsBundler(\n entryFile: string,\n result: {\n hasCustomConfig: false;\n },\n) {\n return extractMastraOptionBundler('server', entryFile, result);\n}\n\nexport async function getServerOptions(\n entryFile: string,\n outputDir: string,\n logger?: IMastraLogger,\n): Promise<Config['server'] | null> {\n const result = await extractMastraOption('server', entryFile, outputDir, logger);\n if (!result) {\n return null;\n }\n\n return result.getConfig();\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunk3Y3N6DCM_cjs = require('./chunk-3Y3N6DCM.cjs');
4
- var chunkYKTV7TY3_cjs = require('./chunk-YKTV7TY3.cjs');
5
- var chunk4O7AWOLQ_cjs = require('./chunk-4O7AWOLQ.cjs');
6
- var chunkV245ALKI_cjs = require('./chunk-V245ALKI.cjs');
7
- var chunkG7R456H2_cjs = require('./chunk-G7R456H2.cjs');
3
+ var chunkQT5YQ63Q_cjs = require('./chunk-QT5YQ63Q.cjs');
4
+ var chunk5GQ4KYVA_cjs = require('./chunk-5GQ4KYVA.cjs');
5
+ var chunkLYJKUXY5_cjs = require('./chunk-LYJKUXY5.cjs');
6
+ var chunkNNVFGNAO_cjs = require('./chunk-NNVFGNAO.cjs');
7
+ var chunkA3JIVJHX_cjs = require('./chunk-A3JIVJHX.cjs');
8
8
  var path = require('path');
9
9
  var logger = require('@mastra/core/logger');
10
10
  var pkg = require('empathic/package');
@@ -39,9 +39,9 @@ async function getInputOptions2(entryFile, platform, env, {
39
39
  }
40
40
  } = {}) {
41
41
  const closestPkgJson = pkg__namespace.up({ cwd: path.dirname(entryFile) });
42
- const projectRoot = closestPkgJson ? path.dirname(chunkG7R456H2_cjs.slash(closestPkgJson)) : chunkG7R456H2_cjs.slash(process.cwd());
43
- const { workspaceMap, workspaceRoot } = await chunkYKTV7TY3_cjs.getWorkspaceInformation({ mastraEntryFile: entryFile });
44
- const analyzeEntryResult = await chunkYKTV7TY3_cjs.analyzeBundle(
42
+ const projectRoot = closestPkgJson ? path.dirname(chunkA3JIVJHX_cjs.slash(closestPkgJson)) : chunkA3JIVJHX_cjs.slash(process.cwd());
43
+ const { workspaceMap, workspaceRoot } = await chunk5GQ4KYVA_cjs.getWorkspaceInformation({ mastraEntryFile: entryFile });
44
+ const analyzeEntryResult = await chunk5GQ4KYVA_cjs.analyzeBundle(
45
45
  [entryFile],
46
46
  entryFile,
47
47
  {
@@ -55,12 +55,12 @@ async function getInputOptions2(entryFile, platform, env, {
55
55
  );
56
56
  const deps = /* @__PURE__ */ new Map();
57
57
  for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {
58
- const pkgName = chunkG7R456H2_cjs.getPackageName(dep);
58
+ const pkgName = chunkA3JIVJHX_cjs.getPackageName(dep);
59
59
  if (pkgName && workspaceMap.has(pkgName)) {
60
60
  deps.set(dep, metadata);
61
61
  }
62
62
  }
63
- const inputOptions = await chunk4O7AWOLQ_cjs.getInputOptions(
63
+ const inputOptions = await chunkLYJKUXY5_cjs.getInputOptions(
64
64
  entryFile,
65
65
  {
66
66
  dependencies: deps,
@@ -79,7 +79,7 @@ async function getInputOptions2(entryFile, platform, env, {
79
79
  }
80
80
  if (plugin?.name === "tsconfig-paths") {
81
81
  plugins.push(
82
- chunkV245ALKI_cjs.tsConfigPaths({
82
+ chunkNNVFGNAO_cjs.tsConfigPaths({
83
83
  localResolve: true
84
84
  })
85
85
  );
@@ -88,8 +88,8 @@ async function getInputOptions2(entryFile, platform, env, {
88
88
  plugins.push(plugin);
89
89
  });
90
90
  inputOptions.plugins = plugins;
91
- inputOptions.plugins.push(chunkYKTV7TY3_cjs.aliasHono());
92
- inputOptions.plugins.push(chunk4O7AWOLQ_cjs.nodeModulesExtensionResolver());
91
+ inputOptions.plugins.push(chunk5GQ4KYVA_cjs.aliasHono());
92
+ inputOptions.plugins.push(chunkLYJKUXY5_cjs.nodeModulesExtensionResolver());
93
93
  }
94
94
  return inputOptions;
95
95
  }
@@ -108,7 +108,7 @@ async function createWatcher(inputOptions, outputOptions) {
108
108
 
109
109
  // src/build/serverOptions.ts
110
110
  async function getServerOptions(entryFile, outputDir, logger) {
111
- const result = await chunk3Y3N6DCM_cjs.extractMastraOption("server", entryFile, outputDir, logger);
111
+ const result = await chunkQT5YQ63Q_cjs.extractMastraOption("server", entryFile, outputDir, logger);
112
112
  if (!result) {
113
113
  return null;
114
114
  }
@@ -118,5 +118,5 @@ async function getServerOptions(entryFile, outputDir, logger) {
118
118
  exports.createWatcher = createWatcher;
119
119
  exports.getInputOptions = getInputOptions2;
120
120
  exports.getServerOptions = getServerOptions;
121
- //# sourceMappingURL=chunk-37PC7CXR.cjs.map
122
- //# sourceMappingURL=chunk-37PC7CXR.cjs.map
121
+ //# sourceMappingURL=chunk-I4JVB6BK.cjs.map
122
+ //# sourceMappingURL=chunk-I4JVB6BK.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/build/watcher.ts","../src/build/serverOptions.ts"],"names":["getInputOptions","pkg","dirname","slash","getWorkspaceInformation","analyzeBundle","posix","noopLogger","getPackageName","tsConfigPaths","aliasHono","nodeModulesExtensionResolver","watch","extractMastraOption"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,eAAsBA,gBAAAA,CACpB,SAAA,EACA,QAAA,EACA,GAAA,EACA;AAAA,EACE,SAAA,GAAY,KAAA;AAAA,EACZ,cAAA,GAAiB;AAAA,IACf,eAAA,EAAiB,KAAA;AAAA,IACjB,aAAA,EAAe,IAAA;AAAA,IACf,SAAA,EAAW;AAAA;AAEf,CAAA,GAA8D,EAAC,EAC/D;AACA,EAAA,MAAM,iBAAqBC,cAAA,CAAA,EAAA,CAAG,EAAE,KAAKC,YAAA,CAAQ,SAAS,GAAG,CAAA;AACzD,EAAA,MAAM,WAAA,GAAc,cAAA,GAAiBA,YAAA,CAAQC,uBAAA,CAAM,cAAc,CAAC,CAAA,GAAIA,uBAAA,CAAM,OAAA,CAAQ,GAAA,EAAK,CAAA;AACzF,EAAA,MAAM,EAAE,cAAc,aAAA,EAAc,GAAI,MAAMC,yCAAA,CAAwB,EAAE,eAAA,EAAiB,SAAA,EAAW,CAAA;AAEpG,EAAA,MAAM,qBAAqB,MAAMC,+BAAA;AAAA,IAC/B,CAAC,SAAS,CAAA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,OAAA,CAAQ,IAAA;AAAA,UACNS,+BAAA,CAAc;AAAA,YACZ,YAAA,EAAc;AAAA,WACf;AAAA,SACH;AACA,QAAA;AAAA,MACF;AAEA,MAAA,OAAA,CAAQ,KAAK,MAAgB,CAAA;AAAA,IAC/B,CAAC,CAAA;AAED,IAAA,YAAA,CAAa,OAAA,GAAU,OAAA;AACvB,IAAA,YAAA,CAAa,OAAA,CAAQ,IAAA,CAAKC,2BAAA,EAAW,CAAA;AAErC,IAAA,YAAA,CAAa,OAAA,CAAQ,IAAA,CAAKC,8CAAA,EAA8B,CAAA;AAAA,EAC1D;AAEA,EAAA,OAAO,YAAA;AACT;AAEA,eAAsB,aAAA,CAAc,cAA4B,aAAA,EAA8B;AAC5F,EAAA,MAAM,OAAA,GAAU,MAAMC,YAAA,CAAM;AAAA,IAC1B,GAAG,YAAA;AAAA,IACH,MAAA,EAAQ;AAAA,MACN,GAAG,aAAA;AAAA,MACH,MAAA,EAAQ,KAAA;AAAA,MACR,cAAA,EAAgB,YAAA;AAAA,MAChB,cAAA,EAAgB;AAAA;AAClB,GACD,CAAA;AAED,EAAA,OAAO,OAAA;AACT;;;AC9FA,eAAsB,gBAAA,CACpB,SAAA,EACA,SAAA,EACA,MAAA,EACkC;AAClC,EAAA,MAAM,SAAS,MAAMC,qCAAA,CAAoB,QAAA,EAAU,SAAA,EAAW,WAAW,MAAM,CAAA;AAC/E,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,OAAO,SAAA,EAAU;AAC1B","file":"chunk-37PC7CXR.cjs","sourcesContent":["import { dirname, posix } from 'node:path';\nimport { noopLogger } from '@mastra/core/logger';\nimport * as pkg from 'empathic/package';\nimport type { InputOptions, OutputOptions, Plugin } from 'rollup';\nimport { watch } from 'rollup';\nimport { getWorkspaceInformation } from '../bundler/workspaceDependencies';\nimport { analyzeBundle } from './analyze';\nimport { getInputOptions as getBundlerInputOptions } from './bundler';\nimport { aliasHono } from './plugins/hono-alias';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport type { BundlerOptions } from './types';\nimport { getPackageName, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport async function getInputOptions(\n entryFile: string,\n platform: BundlerPlatform,\n env?: Record<string, string>,\n {\n sourcemap = false,\n bundlerOptions = {\n enableSourcemap: false,\n enableEsmShim: true,\n externals: true,\n },\n }: { sourcemap?: boolean; bundlerOptions?: BundlerOptions } = {},\n) {\n const closestPkgJson = pkg.up({ cwd: dirname(entryFile) });\n const projectRoot = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());\n const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: entryFile });\n\n const analyzeEntryResult = await analyzeBundle(\n [entryFile],\n entryFile,\n {\n outputDir: posix.join(process.cwd(), '.mastra', '.build'),\n projectRoot: workspaceRoot || process.cwd(),\n platform,\n isDev: true,\n bundlerOptions,\n },\n noopLogger,\n );\n\n const deps = /* @__PURE__ */ new Map();\n for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {\n const pkgName = getPackageName(dep);\n if (pkgName && workspaceMap.has(pkgName)) {\n deps.set(dep, metadata);\n }\n }\n\n const inputOptions = await getBundlerInputOptions(\n entryFile,\n {\n dependencies: deps,\n externalDependencies: new Map(),\n workspaceMap,\n },\n platform,\n env,\n { sourcemap, isDev: true, workspaceRoot, projectRoot, externalsPreset: bundlerOptions?.externals === true },\n );\n\n if (Array.isArray(inputOptions.plugins)) {\n // filter out node-resolve plugin so all node_modules are external\n // and tsconfig-paths plugin as we are injection a custom one\n const plugins = [] as Plugin[];\n inputOptions.plugins.forEach(plugin => {\n if ((plugin as Plugin | undefined)?.name === 'node-resolve') {\n return;\n }\n\n if ((plugin as Plugin | undefined)?.name === 'tsconfig-paths') {\n plugins.push(\n tsConfigPaths({\n localResolve: true,\n }),\n );\n return;\n }\n\n plugins.push(plugin as Plugin);\n });\n\n inputOptions.plugins = plugins;\n inputOptions.plugins.push(aliasHono());\n // fixes imports like lodash/fp/get\n inputOptions.plugins.push(nodeModulesExtensionResolver());\n }\n\n return inputOptions;\n}\n\nexport async function createWatcher(inputOptions: InputOptions, outputOptions: OutputOptions) {\n const watcher = await watch({\n ...inputOptions,\n output: {\n ...outputOptions,\n format: 'esm',\n entryFileNames: '[name].mjs',\n chunkFileNames: '[name].mjs',\n },\n });\n\n return watcher;\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport type { Config } from '@mastra/core/mastra';\nimport { extractMastraOption, extractMastraOptionBundler } from './shared/extract-mastra-option';\n\nexport function getServerOptionsBundler(\n entryFile: string,\n result: {\n hasCustomConfig: false;\n },\n) {\n return extractMastraOptionBundler('server', entryFile, result);\n}\n\nexport async function getServerOptions(\n entryFile: string,\n outputDir: string,\n logger?: IMastraLogger,\n): Promise<Config['server'] | null> {\n const result = await extractMastraOption('server', entryFile, outputDir, logger);\n if (!result) {\n return null;\n }\n\n return result.getConfig();\n}\n"]}
1
+ {"version":3,"sources":["../src/build/watcher.ts","../src/build/serverOptions.ts"],"names":["getInputOptions","pkg","dirname","slash","getWorkspaceInformation","analyzeBundle","posix","noopLogger","getPackageName","tsConfigPaths","aliasHono","nodeModulesExtensionResolver","watch","extractMastraOption"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,eAAsBA,gBAAAA,CACpB,SAAA,EACA,QAAA,EACA,GAAA,EACA;AAAA,EACE,SAAA,GAAY,KAAA;AAAA,EACZ,cAAA,GAAiB;AAAA,IACf,eAAA,EAAiB,KAAA;AAAA,IACjB,aAAA,EAAe,IAAA;AAAA,IACf,SAAA,EAAW;AAAA;AAEf,CAAA,GAA8D,EAAC,EAC/D;AACA,EAAA,MAAM,iBAAqBC,cAAA,CAAA,EAAA,CAAG,EAAE,KAAKC,YAAA,CAAQ,SAAS,GAAG,CAAA;AACzD,EAAA,MAAM,WA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T;AAEA,EAAA,OAAO,OAAO,SAAA,EAAU;AAC1B","file":"chunk-I4JVB6BK.cjs","sourcesContent":["import { dirname, posix } from 'node:path';\nimport { noopLogger } from '@mastra/core/logger';\nimport * as pkg from 'empathic/package';\nimport type { InputOptions, OutputOptions, Plugin } from 'rollup';\nimport { watch } from 'rollup';\nimport { getWorkspaceInformation } from '../bundler/workspaceDependencies';\nimport { analyzeBundle } from './analyze';\nimport { getInputOptions as getBundlerInputOptions } from './bundler';\nimport { aliasHono } from './plugins/hono-alias';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport type { BundlerOptions } from './types';\nimport { getPackageName, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport async function getInputOptions(\n entryFile: string,\n platform: BundlerPlatform,\n env?: Record<string, string>,\n {\n sourcemap = false,\n bundlerOptions = {\n enableSourcemap: false,\n enableEsmShim: true,\n externals: true,\n },\n }: { sourcemap?: boolean; bundlerOptions?: BundlerOptions } = {},\n) {\n const closestPkgJson = pkg.up({ cwd: dirname(entryFile) });\n const projectRoot = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());\n const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: entryFile });\n\n const analyzeEntryResult = await analyzeBundle(\n [entryFile],\n entryFile,\n {\n outputDir: posix.join(process.cwd(), '.mastra', '.build'),\n projectRoot: workspaceRoot || process.cwd(),\n platform,\n isDev: true,\n bundlerOptions,\n },\n noopLogger,\n );\n\n const deps = /* @__PURE__ */ new Map();\n for (const [dep, metadata] of analyzeEntryResult.dependencies.entries()) {\n const pkgName = getPackageName(dep);\n if (pkgName && workspaceMap.has(pkgName)) {\n deps.set(dep, metadata);\n }\n }\n\n const inputOptions = await getBundlerInputOptions(\n entryFile,\n {\n dependencies: deps,\n externalDependencies: new Map(),\n workspaceMap,\n },\n platform,\n env,\n { sourcemap, isDev: true, workspaceRoot, projectRoot, externalsPreset: bundlerOptions?.externals === true },\n );\n\n if (Array.isArray(inputOptions.plugins)) {\n // filter out node-resolve plugin so all node_modules are external\n // and tsconfig-paths plugin as we are injection a custom one\n const plugins = [] as Plugin[];\n inputOptions.plugins.forEach(plugin => {\n if ((plugin as Plugin | undefined)?.name === 'node-resolve') {\n return;\n }\n\n if ((plugin as Plugin | undefined)?.name === 'tsconfig-paths') {\n plugins.push(\n tsConfigPaths({\n localResolve: true,\n }),\n );\n return;\n }\n\n plugins.push(plugin as Plugin);\n });\n\n inputOptions.plugins = plugins;\n inputOptions.plugins.push(aliasHono());\n // fixes imports like lodash/fp/get\n inputOptions.plugins.push(nodeModulesExtensionResolver());\n }\n\n return inputOptions;\n}\n\nexport async function createWatcher(inputOptions: InputOptions, outputOptions: OutputOptions) {\n const watcher = await watch({\n ...inputOptions,\n output: {\n ...outputOptions,\n format: 'esm',\n entryFileNames: '[name].mjs',\n chunkFileNames: '[name].mjs',\n },\n });\n\n return watcher;\n}\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport type { Config } from '@mastra/core/mastra';\nimport { extractMastraOption, extractMastraOptionBundler } from './shared/extract-mastra-option';\n\nexport function getServerOptionsBundler(\n entryFile: string,\n result: {\n hasCustomConfig: false;\n },\n) {\n return extractMastraOptionBundler('server', entryFile, result);\n}\n\nexport async function getServerOptions(\n entryFile: string,\n outputDir: string,\n logger?: IMastraLogger,\n): Promise<Config['server'] | null> {\n const result = await extractMastraOption('server', entryFile, outputDir, logger);\n if (!result) {\n return null;\n }\n\n return result.getConfig();\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { getPackageRootPath, subpathExternalsResolver, tsConfigPaths, esbuild, esmShim, removeDeployer } from './chunk-MPZSAF6V.js';
2
- import { isBuiltinModule, getPackageName, getNodeResolveOptions, slash } from './chunk-XN3FKMO6.js';
1
+ import { getPackageRootPath, subpathExternalsResolver, tsConfigPaths, esbuild, esmShim, removeDeployer } from './chunk-X3T5NPCG.js';
2
+ import { isBuiltinModule, getPackageName, getNodeResolveOptions, slash } from './chunk-CVFIGXXI.js';
3
3
  import { isAbsolute, join } from 'path';
4
4
  import { pathToFileURL, fileURLToPath } from 'url';
5
5
  import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
@@ -192,5 +192,5 @@ async function createBundler(inputOptions, outputOptions) {
192
192
  }
193
193
 
194
194
  export { createBundler, getInputOptions, nodeModulesExtensionResolver };
195
- //# sourceMappingURL=chunk-GSO2J4MT.js.map
196
- //# sourceMappingURL=chunk-GSO2J4MT.js.map
195
+ //# sourceMappingURL=chunk-IGXPFW6N.js.map
196
+ //# sourceMappingURL=chunk-IGXPFW6N.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/build/plugins/node-modules-extension-resolver.ts","../src/build/bundler.ts"],"names":["nodeResolve","join"],"mappings":";;;;;;;;;;;;AAYA,eAAe,cAAA,CAAe,SAAiB,QAAA,EAAwC;AACrF,EAAA,MAAM,OAAA,GAAU,MAAM,kBAAA,CAAmB,OAAA,EAAS,QAAQ,CAAA;AAC1D,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,QAAA,EAAW,OAAO,CAAA,UAAA,CAAY,CAAA;AAAA,EAChD;AAEA,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,MAAM,QAAA,CAAS,KAAK,OAAA,EAAS,cAAc,CAAA,EAAG,OAAO,CAAC,CAAA;AACjF,EAAA,OAAO,OAAA;AACT;AASO,SAAS,4BAAA,GAAuC;AAErD,EAAA,MAAM,oBAAoB,WAAA,EAAY;AAEtC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,iCAAA;AAAA,IACN,MAAM,SAAA,CAAU,EAAA,EAAI,QAAA,EAAU,OAAA,EAAS;AAErC,MAAA,IAAI,CAAC,QAAA,IAAY,EAAA,CAAG,UAAA,CAAW,GAAG,CAAA,IAAK,EAAA,CAAG,UAAA,CAAW,GAAG,KAAK,eAAA,CAA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AAO,QAAQ,KAAA,EAAM;AAAA,IACvB;AAAA,GACF;AACF","file":"chunk-GSO2J4MT.js","sourcesContent":["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, isBuiltinModule } 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 // Skip relative imports, absolute paths, no importer, or builtin modules\n if (!importer || id.startsWith('.') || id.startsWith('/') || isBuiltinModule(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 { nodeModulesExtensionResolver } from './plugins/node-modules-extension-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 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 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"]}
1
+ {"version":3,"sources":["../src/build/plugins/node-modules-extension-resolver.ts","../src/build/bundler.ts"],"names":["nodeResolve","join"],"mappings":";;;;;;;;;;;;AAYA,eAAe,cAAA,CAAe,SAAiB,QAAA,EAAwC;AACrF,EAAA,MAAM,OAAA,GAAU,MAAM,kBAAA,CAAmB,OAAA,EAAS,QAAQ,CAAA;AAC1D,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,QAAA,EAAW,OAAO,CAAA,UAAA,CAAY,CAAA;AAAA,EAChD;AAEA,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,MAAM,QAAA,CAAS,KAAK,OAAA,EAAS,cAAc,CAAA,EAAG,OAAO,CAAC,CAAA;AACjF,EAAA,OAAO,OAAA;AACT;AASO,SAAS,4BAAA,GAAuC;AAErD,EAAA,MAAM,oBAAoB,WAAA,EAAY;AAEtC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,iCAAA;AAAA,IACN,MAAM,SAAA,CAAU,EAAA,EAAI,QAAA,EAAU,OAAA,EAAS;AAErC,MAAA,IAAI,CAAC,QAAA,IAAY,EAAA,CAAG,UAAA,C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AAA,OACjB,CAAA;AAAA,IACH,CAAA;AAAA,IACA,OAAO,MAAM;AACX,MAAA,OAAO,QAAQ,KAAA,EAAM;AAAA,IACvB;AAAA,GACF;AACF","file":"chunk-IGXPFW6N.js","sourcesContent":["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, isBuiltinModule } 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 // Skip relative imports, absolute paths, no importer, or builtin modules\n if (!importer || id.startsWith('.') || id.startsWith('/') || isBuiltinModule(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 { nodeModulesExtensionResolver } from './plugins/node-modules-extension-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 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 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"]}
@@ -1,9 +1,9 @@
1
- import { getBundlerOptions } from './chunk-HXQ27JQX.js';
2
- import { analyzeBundle, getWorkspaceInformation } from './chunk-IY4RBV63.js';
3
- import { createBundler, getInputOptions } from './chunk-GSO2J4MT.js';
4
- import { getPackageRootPath } from './chunk-MPZSAF6V.js';
1
+ import { getBundlerOptions } from './chunk-WQFD37DQ.js';
2
+ import { analyzeBundle, getWorkspaceInformation } from './chunk-OOGT37UD.js';
3
+ import { createBundler, getInputOptions } from './chunk-IGXPFW6N.js';
4
+ import { getPackageRootPath } from './chunk-X3T5NPCG.js';
5
5
  import { DepsService, FileService } from './chunk-DPDWM7HQ.js';
6
- import { slash } from './chunk-XN3FKMO6.js';
6
+ import { slash } from './chunk-CVFIGXXI.js';
7
7
  import { existsSync } from 'fs';
8
8
  import { writeFile, stat } from 'fs/promises';
9
9
  import { join, dirname, posix } from 'path';
@@ -343,5 +343,5 @@ export const tools = [${toolsExports.join(", ")}]`
343
343
  };
344
344
 
345
345
  export { Bundler, IS_DEFAULT };
346
- //# sourceMappingURL=chunk-GRC4HK7K.js.map
347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AAE,eAAA,EAAiB,OAAA,EAAS,aAAa,CAAA;AAEjE,MAAA,IAAA,CAAK,MAAA,CAAO,KAAK,0BAA0B,CAAA;AAE3C,MAAA,IAAA,CAAK,MAAA,CAAO,KAAK,yBAAyB,CAAA;AAC1C,MAAA,MAAM,IAAA,CAAK,mBAAA,CAAoB,eAAA,EAAiB,WAAW,CAAA;AAE3D,MAAA,IAAA,CAAK,MAAA,CAAO,KAAK,8BAA8B,CAAA;AAAA,IACjD,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,MAAA,MAAM,IAAI,WAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,sCAAA;AAAA,UACJ,IAAA,EAAM,uCAAuC,OAAO,CAAA,CAAA;AAAA,UACpD,QAAQ,WAAA,CAAY,QAAA;AAAA,UACpB,UAAU,aAAA,CAAc;AAAA,SAC1B;AAAA,QACA;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,MAAA,CAAO,KAAK,CAAA,MAAA,EAAS,WAAW,IAAI,WAAA,KAAgB,CAAA,GAAI,MAAA,GAAS,OAAO,CAAA,CAAE,CAAA;AAAA,IACjF;AAAA,EACF;AACF","file":"chunk-GRC4HK7K.js","sourcesContent":["import { existsSync } from 'node:fs';\nimport { 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 { 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 description: '',\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n author: 'Mastra',\n license: 'ISC',\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n pnpm: {\n neverBuiltDependencies: [],\n },\n },\n null,\n 2,\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 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\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 in ${path}, skipping...`);\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 ${path} does not exist, skipping...`);\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)) {\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\\t${warning.message.replace('Circular dependency: ', '')}`);\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\n this.logger.info('Done installing dependencies');\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 ${toolsLength} ${toolsLength === 1 ? 'tool' : 'tools'}`);\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/bundler/index.ts"],"names":["pkg"],"mappings":";;;;;;;;;;;;;;;;AAyBO,IAAM,UAAA,0BAAoB,YAAY;AAEtC,IAAe,OAAA,GAAf,cAA+B,aAAA,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,MAAM,SAAS,eAAe,CAAA;AAE9B,IAAA,MAAM,SAAA,CAAU,IAAA,CAAK,eAAA,EAAiB,IAAA,CAAK,gBAAgB,CAAC,CAAA;AAC5D,IAAA,MAAM,SAAA,CAAU,IAAA,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,CAAA,8BAAA,CAAgC,CAAA;AAElD,IAAA,MAAM,UAAU,eAAe,CAAA;AAC/B,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,eAAA,EAAiB,cAAc,CAAA;AAEpD,IAAA,MAAM,eAAA,uBAAsB,GAAA,EAAI;AAChC,IAAA,K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;AAAA,EACF;AACF","file":"chunk-KFHJXZBM.js","sourcesContent":["import { existsSync } from 'node:fs';\nimport { 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 { 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 description: '',\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n author: 'Mastra',\n license: 'ISC',\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n pnpm: {\n neverBuiltDependencies: [],\n },\n },\n null,\n 2,\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 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\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 in ${path}, skipping...`);\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 ${path} does not exist, skipping...`);\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)) {\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\\t${warning.message.replace('Circular dependency: ', '')}`);\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\n this.logger.info('Done installing dependencies');\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 ${toolsLength} ${toolsLength === 1 ? 'tool' : 'tools'}`);\n }\n }\n}\n"]}