@mastra/deployer 1.68.0-alpha.0 → 1.68.0-alpha.5

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 (115) hide show
  1. package/dist/_types/@hono_node-server/package.json +1 -0
  2. package/dist/_types/@mastra_hono/package.json +1 -0
  3. package/dist/{analyze-hp4aHpms.cjs → analyze-BC22OIkc.cjs} +109 -94
  4. package/dist/analyze-BC22OIkc.cjs.map +1 -0
  5. package/dist/{analyze-B5HY26Tt.js → analyze-D3eRdXC9.js} +107 -91
  6. package/dist/analyze-D3eRdXC9.js.map +1 -0
  7. package/dist/{arktype-aI7TBD0R-S0daSmHG.js → arktype-aI7TBD0R-BGjyzmsj.js} +2 -2
  8. package/dist/{arktype-aI7TBD0R-S0daSmHG.js.map → arktype-aI7TBD0R-BGjyzmsj.js.map} +1 -1
  9. package/dist/{arktype-aI7TBD0R-BuTX_Phx.cjs → arktype-aI7TBD0R-DCxjN6oF.cjs} +2 -2
  10. package/dist/{arktype-aI7TBD0R-BuTX_Phx.cjs.map → arktype-aI7TBD0R-DCxjN6oF.cjs.map} +1 -1
  11. package/dist/build/analyze/analyzeEntry.d.ts +3 -1
  12. package/dist/build/analyze/analyzeEntry.d.ts.map +1 -1
  13. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  14. package/dist/build/analyze.cjs +1 -1
  15. package/dist/build/analyze.d.ts.map +1 -1
  16. package/dist/build/analyze.js +1 -1
  17. package/dist/build/bundler.cjs +2 -1
  18. package/dist/build/bundler.d.ts +10 -0
  19. package/dist/build/bundler.d.ts.map +1 -1
  20. package/dist/build/bundler.js +2 -2
  21. package/dist/build/index.cjs +6 -6
  22. package/dist/build/index.js +6 -6
  23. package/dist/build/package-info.d.ts +4 -0
  24. package/dist/build/package-info.d.ts.map +1 -1
  25. package/dist/build/plugins/tsconfig-paths.d.ts +2 -1
  26. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  27. package/dist/{build-Boe3fe3L.js → build-C5eBQq1A.js} +6 -6
  28. package/dist/{build-Boe3fe3L.js.map → build-C5eBQq1A.js.map} +1 -1
  29. package/dist/{build-Dit9VFE2.cjs → build-D-GPvP7A.cjs} +6 -6
  30. package/dist/{build-Dit9VFE2.cjs.map → build-D-GPvP7A.cjs.map} +1 -1
  31. package/dist/bundler/index.cjs +29 -62
  32. package/dist/bundler/index.cjs.map +1 -1
  33. package/dist/bundler/index.d.ts +1 -11
  34. package/dist/bundler/index.d.ts.map +1 -1
  35. package/dist/bundler/index.js +30 -63
  36. package/dist/bundler/index.js.map +1 -1
  37. package/dist/bundler/workspaceDependencies.d.ts +1 -1
  38. package/dist/bundler/workspaceDependencies.d.ts.map +1 -1
  39. package/dist/{bundler-CzQiVHzN.js → bundler-CNFQP4Qm.js} +45 -10
  40. package/dist/bundler-CNFQP4Qm.js.map +1 -0
  41. package/dist/{bundler-BKf2S2r_.cjs → bundler-I4HUeik1.cjs} +55 -8
  42. package/dist/bundler-I4HUeik1.cjs.map +1 -0
  43. package/dist/{bundlerOptions-I2E5y2Wp.cjs → bundlerOptions-CkFbsVoE.cjs} +2 -2
  44. package/dist/{bundlerOptions-I2E5y2Wp.cjs.map → bundlerOptions-CkFbsVoE.cjs.map} +1 -1
  45. package/dist/{bundlerOptions-BSySFLb3.js → bundlerOptions-Dg4pdJsM.js} +2 -2
  46. package/dist/{bundlerOptions-BSySFLb3.js.map → bundlerOptions-Dg4pdJsM.js.map} +1 -1
  47. package/dist/core-D3wM1JKp.js +1159 -0
  48. package/dist/core-D3wM1JKp.js.map +1 -0
  49. package/dist/core-QL_X0T4Y.cjs +1159 -0
  50. package/dist/core-QL_X0T4Y.cjs.map +1 -0
  51. package/dist/docs/SKILL.md +1 -1
  52. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  53. package/dist/docs/references/docs-deployment-monorepo.md +2 -2
  54. package/dist/{effect-QlVUlMFu-tf02PTZR.cjs → effect-QlVUlMFu-B2nZ842E.cjs} +3 -3
  55. package/dist/{effect-QlVUlMFu-tf02PTZR.cjs.map → effect-QlVUlMFu-B2nZ842E.cjs.map} +1 -1
  56. package/dist/{effect-QlVUlMFu-BN-VJnMF.js → effect-QlVUlMFu-DbWuPaWV.js} +3 -3
  57. package/dist/{effect-QlVUlMFu-BN-VJnMF.js.map → effect-QlVUlMFu-DbWuPaWV.js.map} +1 -1
  58. package/dist/{esm-DZ1Siz1C.cjs → esm-Ai6osZ1a.cjs} +61 -50
  59. package/dist/esm-Ai6osZ1a.cjs.map +1 -0
  60. package/dist/{esm-B51vJPGv.js → esm-D-wYOO-S.js} +61 -50
  61. package/dist/esm-D-wYOO-S.js.map +1 -0
  62. package/dist/{index-CLddUTqr-eO-ae7Sx.js → index-CLddUTqr-BXqo9et4.js} +8 -8
  63. package/dist/{index-CLddUTqr-eO-ae7Sx.js.map → index-CLddUTqr-BXqo9et4.js.map} +1 -1
  64. package/dist/{index-CLddUTqr-DS5tJ3WV.cjs → index-CLddUTqr-DsGkVS-W.cjs} +8 -8
  65. package/dist/{index-CLddUTqr-DS5tJ3WV.cjs.map → index-CLddUTqr-DsGkVS-W.cjs.map} +1 -1
  66. package/dist/index.cjs +3 -3
  67. package/dist/index.js +3 -3
  68. package/dist/server/index.cjs +8 -8
  69. package/dist/server/index.cjs.map +1 -1
  70. package/dist/server/index.d.ts +2 -2
  71. package/dist/server/index.js +8 -8
  72. package/dist/server/index.js.map +1 -1
  73. package/dist/services/deps.d.ts +1 -1
  74. package/dist/services/deps.d.ts.map +1 -1
  75. package/dist/services/index.cjs +1 -1
  76. package/dist/services/index.js +1 -1
  77. package/dist/{services-BLvNG7v7.cjs → services-Beob47UW.cjs} +42 -23
  78. package/dist/services-Beob47UW.cjs.map +1 -0
  79. package/dist/{services-B9KRKBT-.js → services-Lm6PRS4D.js} +42 -23
  80. package/dist/services-Lm6PRS4D.js.map +1 -0
  81. package/dist/{sury-CWZTCd75-YUPbTtKO.cjs → sury-CWZTCd75-ChXu4j-p.cjs} +3 -3
  82. package/dist/{sury-CWZTCd75-YUPbTtKO.cjs.map → sury-CWZTCd75-ChXu4j-p.cjs.map} +1 -1
  83. package/dist/{sury-CWZTCd75-ClSNrMWF.js → sury-CWZTCd75-OKz7uWLi.js} +3 -3
  84. package/dist/{sury-CWZTCd75-ClSNrMWF.js.map → sury-CWZTCd75-OKz7uWLi.js.map} +1 -1
  85. package/dist/{typebox-Dei93FPO-CVSJ3SAf.js → typebox-Dei93FPO-C5ACKU09.js} +2 -2
  86. package/dist/{typebox-Dei93FPO-CVSJ3SAf.js.map → typebox-Dei93FPO-C5ACKU09.js.map} +1 -1
  87. package/dist/{typebox-Dei93FPO-BTBshlGz.cjs → typebox-Dei93FPO-KTtPU745.cjs} +2 -2
  88. package/dist/{typebox-Dei93FPO-BTBshlGz.cjs.map → typebox-Dei93FPO-KTtPU745.cjs.map} +1 -1
  89. package/dist/{utils-DYi43Kp4.js → utils-Bl3Lm7SI.js} +1 -2
  90. package/dist/{utils-DYi43Kp4.js.map → utils-Bl3Lm7SI.js.map} +1 -1
  91. package/dist/{utils-7WDNT3Ca.cjs → utils-Bsr_sEcH.cjs} +2 -2
  92. package/dist/{utils-7WDNT3Ca.cjs.map → utils-Bsr_sEcH.cjs.map} +1 -1
  93. package/dist/{valibot--1zFm7rT-Dn5WqdyK.cjs → valibot--1zFm7rT-BeX3W1HK.cjs} +3 -3
  94. package/dist/{valibot--1zFm7rT-Dn5WqdyK.cjs.map → valibot--1zFm7rT-BeX3W1HK.cjs.map} +1 -1
  95. package/dist/{valibot--1zFm7rT-BxcEC3Pu.js → valibot--1zFm7rT-BuVb-6oJ.js} +3 -3
  96. package/dist/{valibot--1zFm7rT-BxcEC3Pu.js.map → valibot--1zFm7rT-BuVb-6oJ.js.map} +1 -1
  97. package/dist/validator/custom-resolver.cjs +1 -1
  98. package/dist/validator/custom-resolver.js +1 -1
  99. package/dist/{zod-Bwrt9trS-Bd40XYOT.js → zod-Bwrt9trS-D5b1oyiT.js} +5 -5
  100. package/dist/{zod-Bwrt9trS-Bd40XYOT.js.map → zod-Bwrt9trS-D5b1oyiT.js.map} +1 -1
  101. package/dist/{zod-Bwrt9trS-Bi11nE9Q.cjs → zod-Bwrt9trS-DGQs9DWc.cjs} +5 -5
  102. package/dist/{zod-Bwrt9trS-Bi11nE9Q.cjs.map → zod-Bwrt9trS-DGQs9DWc.cjs.map} +1 -1
  103. package/package.json +13 -12
  104. package/dist/analyze-B5HY26Tt.js.map +0 -1
  105. package/dist/analyze-hp4aHpms.cjs.map +0 -1
  106. package/dist/bundler-BKf2S2r_.cjs.map +0 -1
  107. package/dist/bundler-CzQiVHzN.js.map +0 -1
  108. package/dist/core-D0wEgdn3.cjs +0 -790
  109. package/dist/core-D0wEgdn3.cjs.map +0 -1
  110. package/dist/core-DF65PJXc.js +0 -790
  111. package/dist/core-DF65PJXc.js.map +0 -1
  112. package/dist/esm-B51vJPGv.js.map +0 -1
  113. package/dist/esm-DZ1Siz1C.cjs.map +0 -1
  114. package/dist/services-B9KRKBT-.js.map +0 -1
  115. package/dist/services-BLvNG7v7.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["createBundlerUtil"],"sources":["../../src/bundler/index.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative } 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, emptyDir, readJSON } 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 type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nimport type { BundlerPlatform } from '../build/utils';\nimport { getPackageName, isBareModuleSpecifier, shouldSkipInstall, slash } from '../build/utils';\nimport { DepsService } from '../services/deps';\nimport { FileService } from '../services/fs';\nimport {\n collectTransitiveWorkspaceDependencies,\n getWorkspaceInformation,\n packWorkspaceDependencies,\n} from './workspaceDependencies';\n\nexport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nexport type { BundlerPlatform } from '../build/utils';\n\nexport const IS_DEFAULT = Symbol('IS_DEFAULT');\n\nconst NPM_ALIAS_PREFIX = 'npm:';\n/** Characters a registry range or dist tag can contain. Protocols need `:`, git shorthand needs `/` or `#`. */\nconst REGISTRY_SPEC_PATTERN = /^[A-Za-z0-9.+_^~><=*|!\\s-]+$/;\nconst PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9._-]+\\/)?[A-Za-z0-9._-]+$/;\nconst TARBALL_SUFFIX_PATTERN = /\\.(?:tgz|tar\\.gz|tar)$/i;\n/** npm reads a value starting like this as a path, whatever follows. A bare `~` is a semver range. */\nconst FILE_SPEC_PREFIX_PATTERN = /^(?:\\.|~[/\\\\]|[/\\\\]|[A-Za-z]:[/\\\\])/;\n/** A range admitting any published version: `*`, `x`, `>=0`, and any union containing one. */\nconst UNBOUNDED_RANGE_PATTERN = /(?:^|\\|\\||\\s)\\s*(?:[*xX]|>=?\\s*0(?:\\.0)*(?:\\.0)*)\\s*(?:$|\\|\\|)/;\n\n/**\n * Constraints declared by the source app, plus the packages some resolution field pins.\n *\n * Only `dependencies` values are read. Override fields contribute names, never values: which of\n * `overrides`, `resolutions`, `pnpm.overrides` or `pnpm-workspace.yaml` a given install honoured\n * depends on the package manager and its version, so reproducing that precedence would mean\n * emulating three package managers. A name appearing in any of them is enough to know the resolved\n * version was chosen deliberately, which is all this needs.\n */\nexport type SourceDependencyConstraints = {\n dependencies: Record<string, string>;\n pinnedByResolutionField: Set<string>;\n};\n\nconst toStringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),\n );\n};\n\n/**\n * True when a specifier is something the isolated install in `.mastra/output` can resolve from the\n * registry: a semver range, a dist tag, a wildcard, or an npm alias whose target is a registry\n * package and range.\n *\n * This is an allowlist rather than a denylist of known protocols, so an unfamiliar protocol is\n * rejected without this code having to know it exists. The output directory is not a workspace, has\n * no catalog definitions and has a different relative-path base, so `catalog:`, `workspace:`,\n * `file:`, `link:` and git specifiers are all either uninstallable there or point somewhere else.\n */\nexport const isRegistryVersionSpec = (spec: string): boolean => {\n if (FILE_SPEC_PREFIX_PATTERN.test(spec) || TARBALL_SUFFIX_PATTERN.test(spec)) {\n return false;\n }\n\n if (spec.startsWith(NPM_ALIAS_PREFIX)) {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n // Skip index 0 so `npm:@scope/pkg` reads as an alias with no range rather than an empty name.\n const rangeSeparator = alias.lastIndexOf('@');\n const name = rangeSeparator > 0 ? alias.slice(0, rangeSeparator) : alias;\n const range = rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '*';\n\n return PACKAGE_NAME_PATTERN.test(name) && isRegistryVersionSpec(range);\n }\n\n return REGISTRY_SPEC_PATTERN.test(spec);\n};\n\n/**\n * True when a specifier names a version the output install can be held to.\n *\n * A range admitting anything (`*`, `latest`, `>=0`, an alias with no range) is looser than the\n * version already resolved, so writing it would let a later install pull something the bundle was\n * never analyzed against.\n */\nconst isBoundedVersionSpec = (spec: string): boolean => {\n const range = spec.startsWith(NPM_ALIAS_PREFIX)\n ? (() => {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n const rangeSeparator = alias.lastIndexOf('@');\n return rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '';\n })()\n : spec;\n\n return /\\d/.test(range) && !UNBOUNDED_RANGE_PATTERN.test(range);\n};\n\nconst readManifest = async (manifestPath: string | undefined): Promise<Record<string, unknown> | undefined> => {\n if (!manifestPath) {\n return undefined;\n }\n\n try {\n const manifest = await readJSON(manifestPath);\n return manifest && typeof manifest === 'object' ? manifest : undefined;\n } catch {\n // A manifest that cannot be read tells us nothing about intent.\n return undefined;\n }\n};\n\n/** Collect the package names a manifest's resolution fields pin, ignoring their values. */\nconst collectManifestPinnedNames = (manifest: Record<string, unknown> | undefined, pinned: Set<string>) => {\n const pnpmSection = manifest?.pnpm;\n const records = [\n manifest?.overrides,\n manifest?.resolutions,\n pnpmSection && typeof pnpmSection === 'object' ? (pnpmSection as { overrides?: unknown }).overrides : undefined,\n ];\n\n for (const record of records) {\n if (record && typeof record === 'object' && !Array.isArray(record)) {\n for (const key of Object.keys(record)) {\n pinned.add(key);\n }\n }\n }\n};\n\n/**\n * Collect the names under a top-level `overrides:` block in `pnpm-workspace.yaml`.\n *\n * pnpm moved overrides out of `package.json` into this file, so a workspace on a current pnpm keeps\n * them only here. Reading names off the indented block avoids a YAML dependency, the same tradeoff\n * `copyPnpmWorkspaceSettings` already makes for the top-level keys it copies.\n */\nconst collectPnpmWorkspacePinnedNames = (source: string, pinned: Set<string>) => {\n const lines = source.split(/\\r?\\n/);\n let insideOverrides = false;\n\n for (const line of lines) {\n if (/^\\S/.test(line)) {\n insideOverrides = /^overrides:\\s*$/.test(line);\n continue;\n }\n\n if (!insideOverrides) {\n continue;\n }\n\n const key = /^\\s+(?:'([^']+)'|\"([^\"]+)\"|([^'\"\\s:][^:]*?))\\s*:/.exec(line);\n if (key) {\n pinned.add((key[1] ?? key[2] ?? key[3] ?? '').trim());\n }\n }\n};\n\n/**\n * Read the constraints the source app declared.\n *\n * `dependencies` come from the manifest at `projectRoot`, the package the build was invoked for and\n * whose directory receives the output, falling back to the manifest above the entry file. Anchoring\n * on `projectRoot` rather than the entry file keeps the answer deterministic when the entry handed\n * to the bundler is a generated wrapper rather than the app's own source file.\n *\n * Resolution-field names are collected from both that manifest and the workspace root, including the\n * root `pnpm-workspace.yaml`, because a name pinned anywhere means the resolved version may have been\n * chosen deliberately rather than hoisted by accident.\n */\nexport const getSourceDependencyConstraints = async ({\n projectRoot,\n mastraEntryFile,\n workspaceRoot,\n}: {\n projectRoot: string;\n mastraEntryFile: string;\n workspaceRoot?: string;\n}): Promise<SourceDependencyConstraints> => {\n const manifestPaths = [pkg.up({ cwd: projectRoot }), pkg.up({ cwd: dirname(mastraEntryFile) })].filter(\n (entry, index, entries): entry is string => !!entry && entries.indexOf(entry) === index,\n );\n\n if (workspaceRoot) {\n manifestPaths.push(join(workspaceRoot, 'package.json'));\n }\n\n const pinnedByResolutionField = new Set<string>();\n let dependencies: Record<string, string> | undefined;\n\n for (const manifestPath of manifestPaths) {\n const manifest = await readManifest(manifestPath);\n if (!manifest) {\n continue;\n }\n\n // Nearest manifest wins, and an empty `dependencies` record is still that package's answer.\n dependencies ??= toStringRecord(manifest.dependencies);\n collectManifestPinnedNames(manifest, pinnedByResolutionField);\n }\n\n if (workspaceRoot) {\n try {\n collectPnpmWorkspacePinnedNames(\n await readFile(join(workspaceRoot, 'pnpm-workspace.yaml'), 'utf-8'),\n pinnedByResolutionField,\n );\n } catch {\n // No pnpm workspace config, or unreadable: nothing to learn from it.\n }\n }\n\n return { dependencies: dependencies ?? {}, pinnedByResolutionField };\n};\n\nconst findDeclaredConstraint = (\n constraints: SourceDependencyConstraints,\n dependencyName: string,\n): string | undefined => {\n const names = [dependencyName, getPackageName(dependencyName)].filter(\n (name, index, all): name is string => !!name && all.indexOf(name) === index,\n );\n\n for (const name of names) {\n // A pinned package's resolved version is the deliberate answer, so leave it as `main` wrote it.\n if (constraints.pinnedByResolutionField.has(name)) {\n return undefined;\n }\n }\n\n for (const name of names) {\n const declared = (constraints.dependencies[name] ?? '').trim();\n if (declared && isBoundedVersionSpec(declared) && isRegistryVersionSpec(declared)) {\n return declared;\n }\n }\n\n return undefined;\n};\n\n/**\n * Prefer the constraint the app declared over the version resolved from `node_modules`.\n *\n * The resolved version is whatever the install happened to hoist, so an app declaring `zod: ^4.3.6`\n * next to a hoisted `zod@3.25.76` gets the hoisted version written into the output manifest and the\n * isolated install then locks it in.\n */\nexport const applySourceDependencyRange = (\n dependencyName: string,\n dependencyInfo: ExternalDependencyInfo,\n constraints: SourceDependencyConstraints,\n): ExternalDependencyInfo => {\n const declared = findDeclaredConstraint(constraints, dependencyName);\n if (!declared) {\n return dependencyInfo;\n }\n\n if (declared.startsWith(NPM_ALIAS_PREFIX)) {\n return { ...dependencyInfo, packageSpec: declared };\n }\n\n // `packageSpec` is set only when the resolved package's own name differs from the requested one, so\n // a bare range under this key describes a different package and the resolved alias is the answer.\n if (dependencyInfo.packageSpec) {\n return dependencyInfo;\n }\n\n return { ...dependencyInfo, version: declared };\n};\n\nfunction toolIdForEntry(relativeEntryFile: string): string {\n const digest = createHash('sha256').update(relativeEntryFile).digest('hex');\n return `${digest.slice(0, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}-${digest.slice(16, 20)}-${digest.slice(20, 32)}`;\n}\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 | ExternalDependencyInfo>,\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 const dependencyValue = typeof value === 'string' ? value : (value.packageSpec ?? value.version ?? 'latest');\n if (key.startsWith('@')) {\n // Handle scoped packages (e.g. @org/package)\n const pkgChunks = key.split('/');\n dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);\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, dependencyValue);\n }\n }\n\n await writeFile(\n pkgPath,\n JSON.stringify(\n {\n name: 'server',\n version: '1.0.0',\n private: true,\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n },\n null,\n 2,\n ),\n );\n }\n\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 pnpmNodeLinker?: 'hoisted';\n\n protected getAdditionalEntries(): Record<string, string> {\n return {};\n }\n\n protected async installDependencies(\n outputDirectory: string,\n rootDir = process.cwd(),\n pnpmOverrides?: Record<string, string>,\n ) {\n const deps = new DepsService(rootDir);\n deps.__setLogger(this.logger);\n\n await deps.install({\n dir: join(outputDirectory, this.outputDir),\n pnpmOverrides,\n pnpmNodeLinker: this.pnpmNodeLinker,\n });\n }\n\n /**\n * Generate a package-lock.json for the output directory so that deploy targets\n * can use `npm ci` instead of `npm install`, skipping version resolution entirely.\n * This is a lockfile-only operation — no packages are downloaded.\n *\n * Temporarily moves node_modules out of the way because pnpm's symlink-based\n * layout confuses npm's arborist, then restores it afterwards so that\n * `mastra start` (or wrangler) can still resolve dependencies at runtime.\n */\n private async generateNpmLockfile(outputDir: string): Promise<void> {\n const nodeModules = join(outputDir, 'node_modules');\n const nodeModulesTmp = join(outputDir, 'node_modules.__tmp');\n let movedNodeModules = false;\n try {\n // Move node_modules aside — pnpm's symlink layout confuses npm's arborist\n if (await fsExtra.pathExists(nodeModules)) {\n await fsExtra.move(nodeModules, nodeModulesTmp, { overwrite: true });\n movedNodeModules = true;\n }\n execSync('npm install --package-lock-only --force', {\n cwd: outputDir,\n stdio: 'pipe',\n timeout: 60_000,\n });\n } catch {\n this.logger.warn('Failed to generate package-lock.json — deploy will fall back to npm install');\n } finally {\n // Restore node_modules so runtime resolution works\n if (movedNodeModules) {\n await rm(nodeModules, { recursive: true, force: true });\n await fsExtra.move(nodeModulesTmp, nodeModules, { overwrite: true });\n }\n }\n }\n\n protected async copyPublic(mastraDir: string, outputDirectory: string) {\n const publicDir = join(mastraDir, 'public');\n\n try {\n await stat(publicDir);\n } catch {\n return;\n }\n\n await copy(publicDir, join(outputDirectory, this.outputDir));\n }\n\n protected async copyDOTNPMRC({\n rootDir = process.cwd(),\n outputDirectory,\n }: {\n rootDir?: string;\n outputDirectory: string;\n }) {\n const sourceDotNpmRcPath = join(rootDir, '.npmrc');\n const targetDotNpmRcPath = join(outputDirectory, this.outputDir, '.npmrc');\n\n try {\n await stat(sourceDotNpmRcPath);\n await copy(sourceDotNpmRcPath, targetDotNpmRcPath);\n } catch {\n return;\n }\n }\n\n /**\n * Writes the `mastra-project.json` deployment marker for Software Factory\n * projects after public assets have been copied. Verifies that the Factory\n * SPA (`factory/index.html`) exists in the output before emitting the marker.\n */\n protected async writeFactoryMarker(outputDirectory: string): Promise<void> {\n const outputDir = join(outputDirectory, this.outputDir);\n const factoryIndex = join(outputDir, 'factory', 'index.html');\n if (!existsSync(factoryIndex)) {\n throw new MastraError({\n id: 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING',\n text: 'Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n });\n }\n await writeFile(\n join(outputDir, 'mastra-project.json'),\n JSON.stringify({ schemaVersion: 1, projectType: 'factory', assets: { ui: 'factory' } }, null, 2),\n );\n this.logger.info('Wrote mastra-project.json for Software Factory project');\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap, enableMinify, enableEsmShim, externals }: BundlerOptions,\n additionalEntries: Record<string, string>,\n toolProjectRoot: string,\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 {\n sourcemap: enableSourcemap,\n minify: enableMinify,\n workspaceRoot,\n projectRoot,\n enableEsmShim,\n externalsPreset: externals === true,\n },\n );\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, toolProjectRoot);\n const entryInputs: Record<string, string> = {};\n const virtualEntries: Record<string, string> = {};\n const entries = { index: serverFile, ...additionalEntries };\n\n for (const [name, entry] of Object.entries(entries)) {\n if (entry.includes('\\n') || !existsSync(entry)) {\n const virtualId = name === 'index' ? '#entry' : `#entry-${name}`;\n entryInputs[name] = virtualId;\n virtualEntries[virtualId] = entry;\n } else {\n entryInputs[name] = entry;\n }\n }\n\n inputOptions.input = { ...entryInputs, ...toolsInputOptions };\n\n if (Object.keys(virtualEntries).length > 0) {\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins.unshift(virtual(virtualEntries));\n } else {\n inputOptions.plugins = [virtual(virtualEntries)];\n }\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[])[], projectRoot: string = process.cwd()) {\n const entries = new Map<string, string>();\n\n for (const toolPath of toolsPaths) {\n const expandedPaths = await glob(toolPath, {\n absolute: true,\n expandDirectories: false,\n });\n\n for (const path of expandedPaths) {\n if (await fsExtra.pathExists(path)) {\n const fileService = new FileService();\n const entryFile = fileService.getFirstExistingFile([\n join(path, 'index.ts'),\n join(path, 'index.js'),\n path, // if path itself is a file\n ]);\n\n // if it doesn't exist or is a dir skip it. using a dir as a tool will crash the process\n if (!entryFile || (await stat(entryFile)).isDirectory()) {\n this.logger.warn('No entry file found, skipping', { path });\n continue;\n }\n\n const normalizedEntryFile = entryFile.replaceAll('\\\\', '/');\n const relativeEntryFile = relative(projectRoot, entryFile).replaceAll('\\\\', '/');\n entries.set(relativeEntryFile, normalizedEntryFile);\n } else {\n this.logger.warn('Tool path does not exist, skipping', { path });\n }\n }\n }\n\n return Object.fromEntries(\n [...entries.entries()]\n .sort(([first], [second]) => (first < second ? -1 : first > second ? 1 : 0))\n .map(([relativeEntryFile, entryFile]) => [`tools/${toolIdForEntry(relativeEntryFile)}`, entryFile]),\n );\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 const additionalEntries = this.getAdditionalEntries();\n\n const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n const internalBundlerOptions: BundlerOptions = {\n enableSourcemap: !!bundlerOptions.sourcemap,\n enableMinify: !!bundlerOptions.minify,\n externals: bundlerOptions.externals ?? [],\n enableEsmShim,\n dynamicPackages: bundlerOptions.dynamicPackages,\n };\n\n let analyzedBundleInfo;\n try {\n const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths, projectRoot);\n analyzedBundleInfo = await analyzeBundle(\n [serverFile, ...Object.values(additionalEntries), ...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 { workspaceRoot } = await getWorkspaceInformation({ dir: projectRoot, mastraEntryFile });\n const sourceDependencyConstraints = await getSourceDependencyConstraints({\n projectRoot,\n mastraEntryFile,\n workspaceRoot,\n });\n const dependenciesToInstall = new Map<string, ExternalDependencyInfo>();\n for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {\n if (analyzedBundleInfo.workspaceMap.has(dep) || !isBareModuleSpecifier(dep)) {\n continue;\n }\n\n dependenciesToInstall.set(dep, applySourceDependencyRange(dep, depInfo, sourceDependencyConstraints));\n }\n\n const initialWorkspaceDependencies = new Set<string>();\n for (const dep of analyzedBundleInfo.dependencies.keys()) {\n const pkgName = getPackageName(dep);\n if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) {\n initialWorkspaceDependencies.add(pkgName);\n }\n }\n\n const transitiveWorkspaceDependencies = collectTransitiveWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n initialDependencies: initialWorkspaceDependencies,\n logger: this.logger,\n });\n\n for (const [dep, packageSpec] of Object.entries(transitiveWorkspaceDependencies.resolutions)) {\n dependenciesToInstall.set(dep, {\n version: analyzedBundleInfo.workspaceMap.get(dep)?.version,\n packageSpec,\n });\n }\n\n try {\n await this.writePackageJson(\n join(outputDirectory, this.outputDir),\n dependenciesToInstall,\n transitiveWorkspaceDependencies.resolutions,\n );\n if (transitiveWorkspaceDependencies.usedWorkspacePackages.size > 0) {\n await packWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n usedWorkspacePackages: transitiveWorkspaceDependencies.usedWorkspacePackages,\n bundleOutputDir: join(outputDirectory, this.outputDir),\n logger: this.logger,\n });\n }\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 additionalEntries,\n projectRoot,\n );\n\n const bundler = await this.createBundler(\n {\n ...inputOptions,\n logLevel: inputOptions.logLevel === 'silent' ? 'warn' : inputOptions.logLevel,\n onwarn: warning => {\n if (warning.code === 'CIRCULAR_DEPENDENCY') {\n if (warning.ids?.[0]?.includes('node_modules')) {\n return;\n }\n\n this.logger.warn('Circular dependency found', {\n dependency: warning.message.replace('Circular dependency: ', ''),\n });\n }\n },\n },\n {\n dir: bundleLocation,\n manualChunks: {\n mastra: ['#mastra'],\n },\n sourcemap: internalBundlerOptions.enableSourcemap,\n },\n );\n\n await bundler.write();\n const toolImports: string[] = [];\n const toolsExports: string[] = [];\n Array.from(Object.keys(inputOptions.input || {}))\n .filter(key => key.startsWith('tools/'))\n .forEach((key, index) => {\n const toolExport = `tool${index}`;\n toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);\n toolsExports.push(toolExport);\n });\n\n await writeFile(\n join(bundleLocation, 'tools.mjs'),\n `${toolImports.join('\\n')}\n\nexport const tools = [${toolsExports.join(', ')}]`,\n );\n this.logger.info('Bundling Mastra done');\n\n this.logger.info('Copying public files');\n await this.copyPublic(dirname(mastraEntryFile), outputDirectory);\n this.logger.info('Done copying public files');\n\n // For Software Factory projects, write a deterministic deployment marker\n // after public assets (including the SPA) have been copied.\n if (analyzedBundleInfo.projectType === 'factory') {\n await this.writeFactoryMarker(outputDirectory);\n }\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 if (shouldSkipInstall()) {\n this.logger.info('Skipping dependency installation (MASTRA_BUILD_SKIP_INSTALL set)');\n } else {\n this.logger.info('Installing dependencies');\n await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);\n this.logger.info('Done installing dependencies');\n\n if (Object.keys(transitiveWorkspaceDependencies.resolutions).length === 0) {\n this.logger.info('Generating package-lock.json for deploy');\n await this.generateNpmLockfile(join(outputDirectory, this.outputDir));\n this.logger.info('Done generating package-lock.json');\n } else {\n this.logger.warn(\n 'Skipping package-lock.json generation because the output contains packed workspace dependencies',\n );\n }\n }\n } catch (error) {\n if (\n error instanceof MastraError &&\n (error.id === 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING' || error.id === 'DEPLOYER_PNPM_IGNORED_BUILDS')\n ) {\n throw error;\n }\n\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, dirname(outputDirectory));\n const toolsLength = Object.keys(toolsInputOptions).length;\n if (toolsLength > 0) {\n this.logger.info('Found tools', { count: toolsLength });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8BA,MAAa,aAAa,OAAO,YAAY;AAE7C,MAAM,mBAAmB;;AAEzB,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB;AAC7B,MAAM,yBAAyB;;AAE/B,MAAM,2BAA2B;;AAEjC,MAAM,0BAA0B;AAgBhC,MAAM,kBAAkB,UAA2C;CACjE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO,CAAC;CAGV,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,UAAqC,OAAO,MAAM,OAAO,QAAQ,CACjG;AACF;;;;;;;;;;;AAYA,MAAa,yBAAyB,SAA0B;CAC9D,IAAI,yBAAyB,KAAK,IAAI,KAAK,uBAAuB,KAAK,IAAI,GACzE,OAAO;CAGT,IAAI,KAAK,WAAW,gBAAgB,GAAG;EACrC,MAAM,QAAQ,KAAK,MAAM,CAAuB;EAEhD,MAAM,iBAAiB,MAAM,YAAY,GAAG;EAC5C,MAAM,OAAO,iBAAiB,IAAI,MAAM,MAAM,GAAG,cAAc,IAAI;EACnE,MAAM,QAAQ,iBAAiB,IAAI,MAAM,MAAM,iBAAiB,CAAC,IAAI;EAErE,OAAO,qBAAqB,KAAK,IA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,gBAChB,MAAM,OAAO,yCAAyC,MAAM,OAAO,iCAEpE,MAAM;GAIR,MAAM,IAAI,YACR;IACE,IAAI;IACJ,MAAM,uCAJM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAKjE,QAAQ,YAAY;IACpB,UAAU,cAAc;GAC1B,GACA,KACF;EACF;CACF;CAEA,MAAM,KAAK,YAAoB,iBAAyB,YAAkD;EACxG,MAAM,oBAAoB,MAAM,KAAK,sBAAsB,YAAY,QAAQ,eAAe,CAAC;EAC/F,MAAM,cAAc,OAAO,KAAK,iBAAiB,CAAC,CAAC;EACnD,IAAI,cAAc,GAChB,KAAK,OAAO,KAAK,eAAe,EAAE,OAAO,YAAY,CAAC;CAE1D;AACF"}
1
+ {"version":3,"file":"index.js","names":["createBundlerUtil"],"sources":["../../src/bundler/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative } 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, emptyDir, readJSON } from 'fs-extra/esm';\nimport type { InputOptions, OutputOptions } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport { analyzeBundle } from '../build/analyze';\nimport { createBundler as createBundlerUtil, getInputOptions, getUnresolvedWorkspaceImport } from '../build/bundler';\nimport { getBundlerOptions } from '../build/bundlerOptions';\nimport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nimport type { BundlerPlatform } from '../build/utils';\nimport { getPackageName, isBareModuleSpecifier, shouldSkipInstall, slash } from '../build/utils';\nimport { DepsService } from '../services/deps';\nimport { FileService } from '../services/fs';\nimport {\n collectTransitiveWorkspaceDependencies,\n getWorkspaceInformation,\n packWorkspaceDependencies,\n} from './workspaceDependencies';\n\nexport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nexport type { BundlerPlatform } from '../build/utils';\n\nexport const IS_DEFAULT = Symbol('IS_DEFAULT');\n\nconst NPM_ALIAS_PREFIX = 'npm:';\n/** Characters a registry range or dist tag can contain. Protocols need `:`, git shorthand needs `/` or `#`. */\nconst REGISTRY_SPEC_PATTERN = /^[A-Za-z0-9.+_^~><=*|!\\s-]+$/;\nconst PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9._-]+\\/)?[A-Za-z0-9._-]+$/;\nconst TARBALL_SUFFIX_PATTERN = /\\.(?:tgz|tar\\.gz|tar)$/i;\n/** npm reads a value starting like this as a path, whatever follows. A bare `~` is a semver range. */\nconst FILE_SPEC_PREFIX_PATTERN = /^(?:\\.|~[/\\\\]|[/\\\\]|[A-Za-z]:[/\\\\])/;\n/** A range admitting any published version: `*`, `x`, `>=0`, and any union containing one. */\nconst UNBOUNDED_RANGE_PATTERN = /(?:^|\\|\\||\\s)\\s*(?:[*xX]|>=?\\s*0(?:\\.0)*(?:\\.0)*)\\s*(?:$|\\|\\|)/;\n\n/**\n * Constraints declared by the source app, plus the packages some resolution field pins.\n *\n * Only `dependencies` values are read. Override fields contribute names, never values: which of\n * `overrides`, `resolutions`, `pnpm.overrides` or `pnpm-workspace.yaml` a given install honoured\n * depends on the package manager and its version, so reproducing that precedence would mean\n * emulating three package managers. A name appearing in any of them is enough to know the resolved\n * version was chosen deliberately, which is all this needs.\n */\nexport type SourceDependencyConstraints = {\n dependencies: Record<string, string>;\n pinnedByResolutionField: Set<string>;\n};\n\nconst toStringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),\n );\n};\n\n/**\n * True when a specifier is something the isolated install in `.mastra/output` can resolve from the\n * registry: a semver range, a dist tag, a wildcard, or an npm alias whose target is a registry\n * package and range.\n *\n * This is an allowlist rather than a denylist of known protocols, so an unfamiliar protocol is\n * rejected without this code having to know it exists. The output directory is not a workspace, has\n * no catalog definitions and has a different relative-path base, so `catalog:`, `workspace:`,\n * `file:`, `link:` and git specifiers are all either uninstallable there or point somewhere else.\n */\nexport const isRegistryVersionSpec = (spec: string): boolean => {\n if (FILE_SPEC_PREFIX_PATTERN.test(spec) || TARBALL_SUFFIX_PATTERN.test(spec)) {\n return false;\n }\n\n if (spec.startsWith(NPM_ALIAS_PREFIX)) {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n // Skip index 0 so `npm:@scope/pkg` reads as an alias with no range rather than an empty name.\n const rangeSeparator = alias.lastIndexOf('@');\n const name = rangeSeparator > 0 ? alias.slice(0, rangeSeparator) : alias;\n const range = rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '*';\n\n return PACKAGE_NAME_PATTERN.test(name) && isRegistryVersionSpec(range);\n }\n\n return REGISTRY_SPEC_PATTERN.test(spec);\n};\n\n/**\n * True when a specifier names a version the output install can be held to.\n *\n * A range admitting anything (`*`, `latest`, `>=0`, an alias with no range) is looser than the\n * version already resolved, so writing it would let a later install pull something the bundle was\n * never analyzed against.\n */\nconst isBoundedVersionSpec = (spec: string): boolean => {\n const range = spec.startsWith(NPM_ALIAS_PREFIX)\n ? (() => {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n const rangeSeparator = alias.lastIndexOf('@');\n return rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '';\n })()\n : spec;\n\n return /\\d/.test(range) && !UNBOUNDED_RANGE_PATTERN.test(range);\n};\n\nconst readManifest = async (manifestPath: string | undefined): Promise<Record<string, unknown> | undefined> => {\n if (!manifestPath) {\n return undefined;\n }\n\n try {\n const manifest = await readJSON(manifestPath);\n return manifest && typeof manifest === 'object' ? manifest : undefined;\n } catch {\n // A manifest that cannot be read tells us nothing about intent.\n return undefined;\n }\n};\n\n/** Collect the package names a manifest's resolution fields pin, ignoring their values. */\nconst collectManifestPinnedNames = (manifest: Record<string, unknown> | undefined, pinned: Set<string>) => {\n const pnpmSection = manifest?.pnpm;\n const records = [\n manifest?.overrides,\n manifest?.resolutions,\n pnpmSection && typeof pnpmSection === 'object' ? (pnpmSection as { overrides?: unknown }).overrides : undefined,\n ];\n\n for (const record of records) {\n if (record && typeof record === 'object' && !Array.isArray(record)) {\n for (const key of Object.keys(record)) {\n pinned.add(key);\n }\n }\n }\n};\n\n/**\n * Collect the names under a top-level `overrides:` block in `pnpm-workspace.yaml`.\n *\n * pnpm moved overrides out of `package.json` into this file, so a workspace on a current pnpm keeps\n * them only here. Reading names off the indented block avoids a YAML dependency, the same tradeoff\n * `copyPnpmWorkspaceSettings` already makes for the top-level keys it copies.\n */\nconst collectPnpmWorkspacePinnedNames = (source: string, pinned: Set<string>) => {\n const lines = source.split(/\\r?\\n/);\n let insideOverrides = false;\n\n for (const line of lines) {\n if (/^\\S/.test(line)) {\n insideOverrides = /^overrides:\\s*$/.test(line);\n continue;\n }\n\n if (!insideOverrides) {\n continue;\n }\n\n const key = /^\\s+(?:'([^']+)'|\"([^\"]+)\"|([^'\"\\s:][^:]*?))\\s*:/.exec(line);\n if (key) {\n pinned.add((key[1] ?? key[2] ?? key[3] ?? '').trim());\n }\n }\n};\n\n/**\n * Read the constraints the source app declared.\n *\n * `dependencies` come from the manifest at `projectRoot`, the package the build was invoked for and\n * whose directory receives the output, falling back to the manifest above the entry file. Anchoring\n * on `projectRoot` rather than the entry file keeps the answer deterministic when the entry handed\n * to the bundler is a generated wrapper rather than the app's own source file.\n *\n * Resolution-field names are collected from both that manifest and the workspace root, including the\n * root `pnpm-workspace.yaml`, because a name pinned anywhere means the resolved version may have been\n * chosen deliberately rather than hoisted by accident.\n */\nexport const getSourceDependencyConstraints = async ({\n projectRoot,\n mastraEntryFile,\n workspaceRoot,\n}: {\n projectRoot: string;\n mastraEntryFile: string;\n workspaceRoot?: string;\n}): Promise<SourceDependencyConstraints> => {\n const manifestPaths = [pkg.up({ cwd: projectRoot }), pkg.up({ cwd: dirname(mastraEntryFile) })].filter(\n (entry, index, entries): entry is string => !!entry && entries.indexOf(entry) === index,\n );\n\n if (workspaceRoot) {\n manifestPaths.push(join(workspaceRoot, 'package.json'));\n }\n\n const pinnedByResolutionField = new Set<string>();\n let dependencies: Record<string, string> | undefined;\n\n for (const manifestPath of manifestPaths) {\n const manifest = await readManifest(manifestPath);\n if (!manifest) {\n continue;\n }\n\n // Nearest manifest wins, and an empty `dependencies` record is still that package's answer.\n dependencies ??= toStringRecord(manifest.dependencies);\n collectManifestPinnedNames(manifest, pinnedByResolutionField);\n }\n\n if (workspaceRoot) {\n try {\n collectPnpmWorkspacePinnedNames(\n await readFile(join(workspaceRoot, 'pnpm-workspace.yaml'), 'utf-8'),\n pinnedByResolutionField,\n );\n } catch {\n // No pnpm workspace config, or unreadable: nothing to learn from it.\n }\n }\n\n return { dependencies: dependencies ?? {}, pinnedByResolutionField };\n};\n\nconst findDeclaredConstraint = (\n constraints: SourceDependencyConstraints,\n dependencyName: string,\n): string | undefined => {\n const names = [dependencyName, getPackageName(dependencyName)].filter(\n (name, index, all): name is string => !!name && all.indexOf(name) === index,\n );\n\n for (const name of names) {\n // A pinned package's resolved version is the deliberate answer, so leave it as `main` wrote it.\n if (constraints.pinnedByResolutionField.has(name)) {\n return undefined;\n }\n }\n\n for (const name of names) {\n const declared = (constraints.dependencies[name] ?? '').trim();\n if (declared && isBoundedVersionSpec(declared) && isRegistryVersionSpec(declared)) {\n return declared;\n }\n }\n\n return undefined;\n};\n\n/**\n * Prefer the constraint the app declared over the version resolved from `node_modules`.\n *\n * The resolved version is whatever the install happened to hoist, so an app declaring `zod: ^4.3.6`\n * next to a hoisted `zod@3.25.76` gets the hoisted version written into the output manifest and the\n * isolated install then locks it in.\n */\nexport const applySourceDependencyRange = (\n dependencyName: string,\n dependencyInfo: ExternalDependencyInfo,\n constraints: SourceDependencyConstraints,\n): ExternalDependencyInfo => {\n const declared = findDeclaredConstraint(constraints, dependencyName);\n if (!declared) {\n return dependencyInfo;\n }\n\n if (declared.startsWith(NPM_ALIAS_PREFIX)) {\n return { ...dependencyInfo, packageSpec: declared };\n }\n\n // `packageSpec` is set only when the resolved package's own name differs from the requested one, so\n // a bare range under this key describes a different package and the resolved alias is the answer.\n if (dependencyInfo.packageSpec) {\n return dependencyInfo;\n }\n\n return { ...dependencyInfo, version: declared };\n};\n\nfunction toolIdForEntry(relativeEntryFile: string): string {\n const digest = createHash('sha256').update(relativeEntryFile).digest('hex');\n return `${digest.slice(0, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}-${digest.slice(16, 20)}-${digest.slice(20, 32)}`;\n}\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 | ExternalDependencyInfo>,\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 const dependencyValue = typeof value === 'string' ? value : (value.packageSpec ?? value.version ?? 'latest');\n if (key.startsWith('@')) {\n // Handle scoped packages (e.g. @org/package)\n const pkgChunks = key.split('/');\n dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);\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, dependencyValue);\n }\n }\n\n await writeFile(\n pkgPath,\n JSON.stringify(\n {\n name: 'server',\n version: '1.0.0',\n private: true,\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n },\n null,\n 2,\n ),\n );\n }\n\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 pnpmNodeLinker?: 'hoisted';\n\n protected getAdditionalEntries(): Record<string, string> {\n return {};\n }\n\n protected async installDependencies(\n outputDirectory: string,\n rootDir = process.cwd(),\n pnpmOverrides?: Record<string, string>,\n ) {\n const deps = new DepsService(rootDir);\n deps.__setLogger(this.logger);\n const installOptions = {\n dir: join(outputDirectory, this.outputDir),\n pnpmOverrides,\n pnpmNodeLinker: this.pnpmNodeLinker,\n };\n\n this.logger.info('Updating dependency lockfile and installing dependencies');\n await deps.install(installOptions);\n this.logger.info('Done updating dependency lockfile and installing dependencies');\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 /**\n * Writes the `mastra-project.json` deployment marker for Software Factory\n * projects after public assets have been copied. Verifies that the Factory\n * SPA (`factory/index.html`) exists in the output before emitting the marker.\n */\n protected async writeFactoryMarker(outputDirectory: string): Promise<void> {\n const outputDir = join(outputDirectory, this.outputDir);\n const factoryIndex = join(outputDir, 'factory', 'index.html');\n if (!existsSync(factoryIndex)) {\n throw new MastraError({\n id: 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING',\n text: 'Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n });\n }\n await writeFile(\n join(outputDir, 'mastra-project.json'),\n JSON.stringify({ schemaVersion: 1, projectType: 'factory', assets: { ui: 'factory' } }, null, 2),\n );\n this.logger.info('Wrote mastra-project.json for Software Factory project');\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap, enableMinify, enableEsmShim, externals }: BundlerOptions,\n additionalEntries: Record<string, string>,\n projectRoot: string,\n ) {\n const { workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile });\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 {\n sourcemap: enableSourcemap,\n minify: enableMinify,\n workspaceRoot,\n projectRoot,\n enableEsmShim,\n externalsPreset: externals === true,\n },\n );\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, projectRoot);\n const entryInputs: Record<string, string> = {};\n const virtualEntries: Record<string, string> = {};\n const entries = { index: serverFile, ...additionalEntries };\n\n for (const [name, entry] of Object.entries(entries)) {\n if (entry.includes('\\n') || !existsSync(entry)) {\n const virtualId = name === 'index' ? '#entry' : `#entry-${name}`;\n entryInputs[name] = virtualId;\n virtualEntries[virtualId] = entry;\n } else {\n entryInputs[name] = entry;\n }\n }\n\n inputOptions.input = { ...entryInputs, ...toolsInputOptions };\n\n if (Object.keys(virtualEntries).length > 0) {\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins.unshift(virtual(virtualEntries));\n } else {\n inputOptions.plugins = [virtual(virtualEntries)];\n }\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[])[], projectRoot: string = process.cwd()) {\n const entries = new Map<string, string>();\n\n for (const toolPath of toolsPaths) {\n const expandedPaths = await glob(toolPath, {\n absolute: true,\n expandDirectories: false,\n });\n\n for (const path of expandedPaths) {\n if (await fsExtra.pathExists(path)) {\n const fileService = new FileService();\n const entryFile = fileService.getFirstExistingFile([\n join(path, 'index.ts'),\n join(path, 'index.js'),\n path, // if path itself is a file\n ]);\n\n // if it doesn't exist or is a dir skip it. using a dir as a tool will crash the process\n if (!entryFile || (await stat(entryFile)).isDirectory()) {\n this.logger.warn('No entry file found, skipping', { path });\n continue;\n }\n\n const normalizedEntryFile = entryFile.replaceAll('\\\\', '/');\n const relativeEntryFile = relative(projectRoot, entryFile).replaceAll('\\\\', '/');\n entries.set(relativeEntryFile, normalizedEntryFile);\n } else {\n this.logger.warn('Tool path does not exist, skipping', { path });\n }\n }\n }\n\n return Object.fromEntries(\n [...entries.entries()]\n .sort(([first], [second]) => (first < second ? -1 : first > second ? 1 : 0))\n .map(([relativeEntryFile, entryFile]) => [`tools/${toolIdForEntry(relativeEntryFile)}`, entryFile]),\n );\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 const additionalEntries = this.getAdditionalEntries();\n const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });\n const entryProjectRoot = closestPkgJson ? dirname(closestPkgJson) : projectRoot;\n\n const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n const internalBundlerOptions: BundlerOptions = {\n enableSourcemap: !!bundlerOptions.sourcemap,\n enableMinify: !!bundlerOptions.minify,\n externals: bundlerOptions.externals ?? [],\n enableEsmShim,\n dynamicPackages: bundlerOptions.dynamicPackages,\n };\n\n let analyzedBundleInfo;\n try {\n const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths, entryProjectRoot);\n analyzedBundleInfo = await analyzeBundle(\n [serverFile, ...Object.values(additionalEntries), ...Object.values(resolvedToolsPaths)],\n mastraEntryFile,\n {\n outputDir: analyzeDir,\n projectRoot: entryProjectRoot,\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 { workspaceRoot } = await getWorkspaceInformation({ dir: projectRoot, mastraEntryFile });\n const sourceDependencyConstraints = await getSourceDependencyConstraints({\n projectRoot: entryProjectRoot,\n mastraEntryFile,\n workspaceRoot,\n });\n const dependenciesToInstall = new Map<string, ExternalDependencyInfo>();\n for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {\n if (analyzedBundleInfo.workspaceMap.has(dep) || !isBareModuleSpecifier(dep)) {\n continue;\n }\n\n dependenciesToInstall.set(dep, applySourceDependencyRange(dep, depInfo, sourceDependencyConstraints));\n }\n\n const initialWorkspaceDependencies = new Set<string>();\n for (const dep of analyzedBundleInfo.dependencies.keys()) {\n const pkgName = getPackageName(dep);\n if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) {\n initialWorkspaceDependencies.add(pkgName);\n }\n }\n\n const transitiveWorkspaceDependencies = await collectTransitiveWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n initialDependencies: initialWorkspaceDependencies,\n logger: this.logger,\n });\n\n for (const [dep, packageSpec] of Object.entries(transitiveWorkspaceDependencies.resolutions)) {\n dependenciesToInstall.set(dep, {\n version: analyzedBundleInfo.workspaceMap.get(dep)?.version,\n packageSpec,\n });\n }\n\n try {\n await this.writePackageJson(\n join(outputDirectory, this.outputDir),\n dependenciesToInstall,\n transitiveWorkspaceDependencies.resolutions,\n );\n if (transitiveWorkspaceDependencies.usedWorkspacePackages.size > 0) {\n await packWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n usedWorkspacePackages: transitiveWorkspaceDependencies.usedWorkspacePackages,\n bundleOutputDir: join(outputDirectory, this.outputDir),\n logger: this.logger,\n });\n }\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 additionalEntries,\n entryProjectRoot,\n );\n\n const unresolvedWorkspaceImports: Array<{ source: string }> = [];\n\n const bundler = await this.createBundler(\n {\n ...inputOptions,\n logLevel: inputOptions.logLevel === 'silent' ? 'warn' : inputOptions.logLevel,\n onwarn: warning => {\n const unresolvedWorkspaceDep = getUnresolvedWorkspaceImport(\n warning as { code: string; source?: string; id?: string },\n analyzedBundleInfo.workspaceMap,\n );\n if (unresolvedWorkspaceDep) {\n unresolvedWorkspaceImports.push({ source: unresolvedWorkspaceDep });\n }\n\n if (warning.code === 'CIRCULAR_DEPENDENCY') {\n if (warning.ids?.[0]?.includes('node_modules')) {\n return;\n }\n\n this.logger.warn('Circular dependency found', {\n dependency: warning.message.replace('Circular dependency: ', ''),\n });\n }\n },\n },\n {\n dir: bundleLocation,\n manualChunks: {\n mastra: ['#mastra'],\n },\n sourcemap: internalBundlerOptions.enableSourcemap,\n },\n );\n\n await bundler.write();\n\n if (unresolvedWorkspaceImports.length > 0) {\n const importList = unresolvedWorkspaceImports.map(i => ` - ${i.source}`).join('\\n');\n throw new MastraError({\n id: 'DEPLOYER_BUNDLER_UNRESOLVED_WORKSPACE_IMPORT',\n text: `Workspace imports could not be resolved during bundling:\\n${importList}\\n\\nThis means the analyzer did not capture these workspace subpath imports during the analysis phase. Try adding the package as a direct dependency of the app, or check the workspace configuration.`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n });\n }\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 // For Software Factory projects, write a deterministic deployment marker\n // after public assets (including the SPA) have been copied.\n if (analyzedBundleInfo.projectType === 'factory') {\n await this.writeFactoryMarker(outputDirectory);\n }\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 if (shouldSkipInstall()) {\n this.logger.info('Skipping dependency installation (MASTRA_BUILD_SKIP_INSTALL set)');\n } else {\n await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);\n }\n } catch (error) {\n if (\n error instanceof MastraError &&\n (error.id === 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING' || error.id === 'DEPLOYER_PNPM_IGNORED_BUILDS')\n ) {\n throw error;\n }\n\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, dirname(outputDirectory));\n const toolsLength = Object.keys(toolsInputOptions).length;\n if (toolsLength > 0) {\n this.logger.info('Found tools', { count: toolsLength });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6BA,MAAa,aAAa,OAAO,YAAY;AAE7C,MAAM,mBAAmB;;AAEzB,MAAM,wBAAwB;AAC9B,MAAM,uBA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AK,OAAO,KAAK,qBAAqB;GACtC,MAAM,KAAK,aAAa;IAAE;IAAiB,SAAS;GAAY,CAAC;GAEjE,KAAK,OAAO,KAAK,0BAA0B;GAE3C,IAAI,kBAAkB,GACpB,KAAK,OAAO,KAAK,kEAAkE;QAEnF,MAAM,KAAK,oBAAoB,iBAAiB,aAAa,gCAAgC,WAAW;EAE5G,SAAS,OAAO;GACd,IACE,iBAAiB,gBAChB,MAAM,OAAO,yCAAyC,MAAM,OAAO,iCAEpE,MAAM;GAIR,MAAM,IAAI,YACR;IACE,IAAI;IACJ,MAAM,uCAJM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAKjE,QAAQ,YAAY;IACpB,UAAU,cAAc;GAC1B,GACA,KACF;EACF;CACF;CAEA,MAAM,KAAK,YAAoB,iBAAyB,YAAkD;EACxG,MAAM,oBAAoB,MAAM,KAAK,sBAAsB,YAAY,QAAQ,eAAe,CAAC;EAC/F,MAAM,cAAc,OAAO,KAAK,iBAAiB,CAAC,CAAC;EACnD,IAAI,cAAc,GAChB,KAAK,OAAO,KAAK,eAAe,EAAE,OAAO,YAAY,CAAC;CAE1D;AACF"}
@@ -36,7 +36,7 @@ export declare const collectTransitiveWorkspaceDependencies: ({ workspaceMap, in
36
36
  workspaceMap: Map<string, WorkspacePackageInfo>;
37
37
  initialDependencies: Set<string>;
38
38
  logger: IMastraLogger;
39
- }) => TransitiveDependencyResult;
39
+ }) => Promise<TransitiveDependencyResult>;
40
40
  /**
41
41
  * Creates TGZ packages for workspace dependencies in the workspace-module directory
42
42
  */
@@ -1 +1 @@
1
- {"version":3,"file":"workspaceDependencies.d.ts","sourceRoot":"","sources":["../../src/bundler/workspaceDependencies.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAQzD,MAAM,MAAM,oBAAoB,GAAG;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE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MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC;IACjD,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAWF,eAAO,MAAM,aAAa,GAAI,cAAc,OAAO,KAAG,OAYrD,CAAC;AAEF,KAAK,0BAA0B,GAAG;IAChC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,qBAAqB,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACpC,CAAC;AAOF;;;;;;;;;;GAUG;AACH,wBAAsB,uBAAuB,CAAC,EAC5C,GAAmB,EACnB,eAAe,GAChB,EAAE;IACD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,eAAe,EAAE,MAAM,CAAC;CACzB;;;;GA+BA;AAED;;GAEG;AACH,eAAO,MAAM,sCAAsC,GAAU,gDAI1D;IACD,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC;IAChD,mBAAmB,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACjC,MAAM,EAAE,aAAa,CAAC;CACvB,KAAG,OAAO,CAAC,0BAA0B,CA2CrC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,yBAAyB,GAAU,mEAK7C;IACD,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC;IAChD,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,aAAa,CAAC;IACtB,qBAAqB,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACpC,KAAG,OAAO,CAAC,IAAI,CAsCf,CAAC"}
@@ -1,18 +1,19 @@
1
- import { a as getPackageName, i as getNodeResolveOptions, l as isDependencyPartOfPackage, m as slash, s as isBareModuleSpecifier, u as isExternalProtocolImport } from "./utils-DYi43Kp4.js";
1
+ import { a as getPackageName, i as getNodeResolveOptions, l as isDependencyPartOfPackage, m as slash, s as isBareModuleSpecifier, u as isExternalProtocolImport } from "./utils-Bl3Lm7SI.js";
2
2
  import fs, { statSync } from "fs";
3
3
  import { readFile } from "fs/promises";
4
4
  import path, { dirname, isAbsolute, join, normalize, resolve, sep } from "path";
5
- import { readJSON } from "fs-extra/esm";
5
+ import { readJSON, readJson } from "fs-extra/esm";
6
6
  import { transformAsync, types } from "@babel/core";
7
7
  import { fileURLToPath, pathToFileURL } from "url";
8
8
  import commonjs from "@rollup/plugin-commonjs";
9
9
  import json from "@rollup/plugin-json";
10
+ import { getPackageInfo } from "local-pkg";
10
11
  import { rollup } from "rollup";
11
12
  import { optimizeLodashImports } from "@optimize-lodash/rollup-plugin";
12
13
  import nodeResolve from "@rollup/plugin-node-resolve";
13
14
  import originalEsbuild, { minify } from "rollup-plugin-esbuild";
14
15
  import originalEsmShim from "@rollup/plugin-esm-shim";
15
- import { getPackageInfo } from "local-pkg";
16
+ import { findUp } from "find-up-simple";
16
17
  import stripJsonComments from "strip-json-comments";
17
18
  import { createHandler } from "typescript-paths";
18
19
  //#region src/build/plugins/esbuild.ts
@@ -471,6 +472,24 @@ function localStorageDetector(rootDir) {
471
472
  * Note: This function depends on local-pkg and should only be used at build-time.
472
473
  * It is in a separate file to avoid including local-pkg in runtime code.
473
474
  */
475
+ async function getPackageInfo$1(packageName, options) {
476
+ const pkgInfo = await getPackageInfo(packageName, options);
477
+ async function searchUpForPackageJson(rootPath) {
478
+ const path = await findUp("package.json", { cwd: rootPath });
479
+ if (!path) return;
480
+ const pkgJson = await readJson(path);
481
+ if (!pkgJson.version) return searchUpForPackageJson(dirname(rootPath));
482
+ return {
483
+ name: pkgJson.name,
484
+ version: pkgJson.version,
485
+ rootPath: dirname(path),
486
+ packageJsonPath: path,
487
+ packageJson: pkgJson
488
+ };
489
+ }
490
+ if (!pkgInfo?.version && pkgInfo?.rootPath) return searchUpForPackageJson(dirname(pkgInfo.rootPath));
491
+ return pkgInfo;
492
+ }
474
493
  /**
475
494
  * Normalize a resolution base path to a directory path.
476
495
  *
@@ -496,7 +515,7 @@ async function getPackageRootPath(packageName, parentPath) {
496
515
  try {
497
516
  let options = void 0;
498
517
  if (parentPath) options = { paths: [toParentDirectoryUrl(parentPath)] };
499
- rootPath = (await getPackageInfo(packageName, options))?.rootPath ?? null;
518
+ rootPath = (await getPackageInfo$1(packageName, options))?.rootPath ?? null;
500
519
  } catch {
501
520
  rootPath = null;
502
521
  }
@@ -690,7 +709,7 @@ function hasPaths(tsConfigPath) {
690
709
  return false;
691
710
  }
692
711
  }
693
- function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
712
+ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve, cwd } = {}) {
694
713
  const handlerCache = /* @__PURE__ */ new Map();
695
714
  function resolveJsImportToSourceFile(moduleName) {
696
715
  if (fs.existsSync(moduleName)) return moduleName;
@@ -749,7 +768,7 @@ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
749
768
  order: "pre",
750
769
  async handler(request, importer, options) {
751
770
  if (!importer || request.startsWith("\0") || importer.charCodeAt(0) === 0) return null;
752
- if (!path.isAbsolute(importer)) importer = path.resolve(process.cwd(), importer);
771
+ if (!path.isAbsolute(importer)) importer = path.resolve(cwd ?? process.cwd(), importer);
753
772
  const moduleName = resolveAlias(request, importer);
754
773
  if (!moduleName) {
755
774
  const resolved = await this.resolve(request, importer, {
@@ -828,7 +847,11 @@ function mastraToolsAliasPlugin() {
828
847
  };
829
848
  }
830
849
  async function getInputOptions(entryFile, analyzedBundleInfo, platform, env = { "process.env.NODE_ENV": JSON.stringify("production") }, { sourcemap = false, minify: minify$1 = false, isDev = false, projectRoot, workspaceRoot = void 0, enableEsmShim = true, externalsPreset = false }) {
831
- const nodeResolvePlugin = nodeResolve(getNodeResolveOptions(platform));
850
+ const nodeResolvePlugin = nodeResolve({
851
+ ...getNodeResolveOptions(platform),
852
+ rootDir: projectRoot,
853
+ modulePaths: workspaceRoot ? [join(workspaceRoot, "node_modules")] : []
854
+ });
832
855
  const externalsCopy = new Set(analyzedBundleInfo.externalDependencies.keys());
833
856
  const externals = externalsPreset ? [] : Array.from(externalsCopy);
834
857
  return {
@@ -856,7 +879,7 @@ async function getInputOptions(entryFile, analyzedBundleInfo, platform, env = {
856
879
  }
857
880
  },
858
881
  mastraInternalAliasPlugin(entryFile),
859
- tsConfigPaths(),
882
+ tsConfigPaths({ cwd: projectRoot }),
860
883
  mastraToolsAliasPlugin(),
861
884
  esbuild({
862
885
  platform,
@@ -902,7 +925,19 @@ async function createBundler(inputOptions, outputOptions) {
902
925
  }
903
926
  };
904
927
  }
928
+ /**
929
+ * Checks whether a Rollup warning is an UNRESOLVED_IMPORT for a workspace package.
930
+ * Returns the original import specifier if it's a workspace package that leaked
931
+ * through, or undefined if it's not.
932
+ */
933
+ function getUnresolvedWorkspaceImport(warning, workspaceMap) {
934
+ if (warning.code !== "UNRESOLVED_IMPORT") return;
935
+ const src = warning.source ?? warning.id ?? "";
936
+ if (!src) return;
937
+ const pkgName = getPackageName(src);
938
+ if (pkgName && workspaceMap.has(pkgName)) return src;
939
+ }
905
940
  //#endregion
906
- export { tsConfigPaths as a, protocolExternalResolver as c, getPackageRootPath as d, esmShim as f, mastraToolsAliasPlugin as i, nodeModulesExtensionResolver as l, getInputOptions as n, subpathExternalsResolver as o, esbuild as p, mastraInternalAliasPlugin as r, removeDeployer as s, createBundler as t, getPackageMetadata as u };
941
+ export { mastraToolsAliasPlugin as a, removeDeployer as c, getPackageInfo$1 as d, getPackageMetadata as f, esbuild as h, mastraInternalAliasPlugin as i, protocolExternalResolver as l, esmShim as m, getInputOptions as n, tsConfigPaths as o, getPackageRootPath as p, getUnresolvedWorkspaceImport as r, subpathExternalsResolver as s, createBundler as t, nodeModulesExtensionResolver as u };
907
942
 
908
- //# sourceMappingURL=bundler-CzQiVHzN.js.map
943
+ //# sourceMappingURL=bundler-CNFQP4Qm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundler-CNFQP4Qm.js","names":["getPackageInfo","getOriginalPackageInfo","removeDeployer","t","removeDeployerBabelPlugin","minify","esbuildMinify"],"sources":["../src/build/plugins/esbuild.ts","../src/build/plugins/esm-shim.ts","../src/build/plugins/local-storage-detector.ts","../src/build/package-info.ts","../src/build/plugins/node-modules-extension-resolver.ts","../src/build/plugins/protocol-external-resolver.ts","../src/build/babel/remove-deployer.ts","../src/build/plugins/remove-deployer.ts","../src/build/plugins/subpath-externals-resolver.ts","../src/build/plugins/tsconfig-paths.ts","../src/build/bundler.ts"],"sourcesContent":["import originalEsbuild from 'rollup-plugin-esbuild';\n\nexport function esbuild(options: Parameters<typeof originalEsbuild>[0] = {}) {\n return originalEsbuild({\n target: 'node20',\n platform: 'node',\n minify: false,\n ...options,\n });\n}\n","import originalEsmShim from '@rollup/plugin-esm-shim';\nimport type { Plugin } from 'rollup';\n\n// Regex to detect DECLARATIONS of __filename, __dirname\n// Using non-capturing group (?:) for slightly better performance\nconst FilenameDeclarationRegex = /(?:const|let|var)\\s+__filename/;\nconst DirnameDeclarationRegex = /(?:const|let|var)\\s+__dirname/;\n\n/**\n * Custom ESM shim plugin wrapper that respects user-declared __filename/__dirname variables.\n *\n * The original @rollup/plugin-esm-shim would inject shims even when users had already declared\n * their own __filename/__dirname, causing \"Identifier '__filename' has already been declared\" errors.\n *\n * This wrapper checks if the user has already declared these variables and skips the shim injection\n * if so. If either variable is declared, we skip the shim entirely since the original plugin injects\n * both together and we assume users who declare one will also handle the other if needed.\n */\nexport function esmShim(): Plugin {\n const original = originalEsmShim();\n\n return {\n name: 'esm-shim',\n renderChunk(code, chunk, opts, meta) {\n // Fast path: use includes() first to avoid regex if identifiers aren't present\n const hasFilename = code.includes('__filename');\n const hasDirname = code.includes('__dirname');\n\n // If user declared either __filename or __dirname, skip shim injection entirely\n // since the original plugin injects both together\n const userDeclaredFilename = hasFilename && FilenameDeclarationRegex.test(code);\n const userDeclaredDirname = hasDirname && DirnameDeclarationRegex.test(code);\n\n if (userDeclaredFilename || userDeclaredDirname) {\n return null;\n }\n\n // Otherwise, delegate to the original plugin\n if (typeof original.renderChunk === 'function') {\n return original.renderChunk.call(this, code, chunk, opts, meta);\n }\n\n return null;\n },\n };\n}\n\nexport default esmShim;\n","import type { Plugin } from 'rollup';\n\n/**\n * Connection-string-shaped patterns that resolve to the build host and will\n * never work inside the deploy container.\n */\nconst LOCAL_HOST_PATTERNS: Array<{ pattern: RegExp; hint: string }> = [\n {\n pattern: /\\bfile:\\.{1,2}\\/[^\\s'\"`]+\\.(?:db|sqlite)\\b/gi,\n hint: 'LibSQL/SQLite file path relative to the build host',\n },\n {\n pattern: /\\b(?:postgres(?:ql)?|mysql|mongodb|redis|libsql):\\/\\/[^/\\s'\"`]*localhost\\b/gi,\n hint: 'localhost in a connection string',\n },\n {\n pattern: /\\b(?:postgres(?:ql)?|mysql|mongodb|redis|libsql):\\/\\/[^/\\s'\"`]*127\\.0\\.0\\.1\\b/g,\n hint: '127.0.0.1 in a connection string',\n },\n];\n\nexport interface LocalStorageDetection {\n value: string;\n hint: string;\n module: string;\n /**\n * Name of the env var that guards this literal at runtime, when the\n * literal is the fallback arm of a `process.env.X || literal` (or `??`)\n * expression. The CLI preflight uses this to suppress or soften the\n * error when the guarding var is present in the deploy env.\n */\n guardedBy?: string;\n}\n\n/**\n * Unified preflight metadata emitted as `preflight-metadata.json`.\n * Superset of the legacy `preflight-local-paths.json` (which stays emitted\n * for one release so older CLIs keep working with newer deployers).\n */\nexport interface PreflightMetadata {\n version: 1;\n localPaths: LocalStorageDetection[];\n userEnvRefs: string[];\n}\n\n/**\n * Everything under `.mastra/.build/` is deployer-generated pre-bundled\n * dependency code (`@mastra__*.mjs` shims and their shared `chunk-*.mjs`\n * files), never user-authored. These preserve JSDoc examples from the\n * original library source (e.g. `LibSQLStore({ url: 'file:./data.db' })`)\n * which would otherwise trip the host-local detector, and their env var\n * reads are library refs that must not count as user references.\n */\nconst MASTRA_BUILD_DIR = /[\\\\/]\\.mastra[\\\\/]\\.build[\\\\/]/;\n\nconst PROCESS_ENV_DOT = /\\bprocess\\.env\\.([A-Z_][A-Z0-9_]*)\\b/g;\nconst PROCESS_ENV_BRACKET = /\\bprocess\\.env\\[['\"]([A-Z_][A-Z0-9_]*)['\"]\\]/g;\n\n/** Names of the metadata assets emitted into the output dir. */\n// TODO(preflight-metadata): stop emitting the legacy file in the next minor\n// after @mastra/deployer 1.50 — every CLI released alongside 1.50+ reads\n// preflight-metadata.json. Also remove the legacy fallback in the CLI's\n// deploy-preflight.ts at the same time.\nconst LEGACY_LOCAL_PATHS_FILE = 'preflight-local-paths.json';\nconst PREFLIGHT_METADATA_FILE = 'preflight-metadata.json';\nconst WORKERS_CONFIG_FILE = 'workers.json';\n\ninterface ModuleMatch {\n value: string;\n hint: string;\n guardedBy?: string;\n}\n\nfunction collectEnvRefs(code: string): Set<string> {\n const refs = new Set<string>();\n for (const m of code.matchAll(PROCESS_ENV_DOT)) refs.add(m[1]!);\n for (const m of code.matchAll(PROCESS_ENV_BRACKET)) refs.add(m[1]!);\n return refs;\n}\n\n/* ------------------------------------------------------------------ */\n/* AST guard analysis */\n/* ------------------------------------------------------------------ */\n\ninterface AstNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isAstNode(v: unknown): v is AstNode {\n return typeof v === 'object' && v !== null && typeof (v as AstNode).type === 'string';\n}\n\nfunction walkAst(node: AstNode, visit: (node: AstNode) => void): void {\n visit(node);\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isAstNode(item)) walkAst(item, visit);\n }\n } else if (isAstNode(value)) {\n walkAst(value, visit);\n }\n }\n}\n\nfunction propertyName(node: AstNode): string | undefined {\n const key = node.key as AstNode | undefined;\n if (key?.type === 'Identifier' && !node.computed) return key.name as string;\n if (key?.type === 'Literal' && typeof key.value === 'string') return key.value;\n return undefined;\n}\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype WorkerConfig = { enabled: boolean; [key: string]: JsonValue };\n\ntype WorkersConfig = {\n version: 1;\n orchestration: WorkerConfig;\n scheduler: WorkerConfig;\n backgroundTasks: WorkerConfig;\n custom: string[];\n};\n\nfunction staticJsonValue(node: AstNode): JsonValue | undefined {\n if (node.type === 'Literal') {\n const value = node.value;\n if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n return undefined;\n }\n\n if (node.type === 'UnaryExpression' && node.operator === '-') {\n const argument = node.argument as AstNode | undefined;\n const value = argument ? staticJsonValue(argument) : undefined;\n return typeof value === 'number' ? -value : undefined;\n }\n\n if (node.type === 'TemplateLiteral') {\n const expressions = (node.expressions as AstNode[] | undefined) ?? [];\n const quasis = (node.quasis as Array<{ value?: { cooked?: string } }> | undefined) ?? [];\n if (expressions.length === 0) return quasis[0]?.value?.cooked ?? '';\n return undefined;\n }\n\n if (node.type === 'ArrayExpression') {\n const result: JsonValue[] = [];\n for (const element of (node.elements as Array<AstNode | null> | undefined) ?? []) {\n if (!element) return undefined;\n const value = staticJsonValue(element);\n if (value === undefined) return undefined;\n result.push(value);\n }\n return result;\n }\n\n if (node.type === 'ObjectExpression') {\n const result: Record<string, JsonValue> = {};\n for (const property of (node.properties as AstNode[] | undefined) ?? []) {\n if (property.type !== 'Property' || property.kind !== 'init') return undefined;\n const name = propertyName(property);\n const valueNode = property.value as AstNode | undefined;\n if (!name || !valueNode) return undefined;\n const value = staticJsonValue(valueNode);\n if (value === undefined) {\n delete result[name];\n } else {\n result[name] = value;\n }\n }\n return result;\n }\n\n return undefined;\n}\n\nfunction staticObjectValue(node: AstNode | undefined): Record<string, JsonValue> {\n if (!node) return {};\n const value = staticJsonValue(node);\n return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};\n}\n\nfunction isConfigured(node: AstNode | undefined): boolean {\n if (!node) return false;\n if (node.type === 'Literal') return node.value !== null && node.value !== false;\n return node.type !== 'Identifier' || node.name !== 'undefined';\n}\n\nfunction unwrapAwait(node: AstNode | undefined): AstNode | undefined {\n return node?.type === 'AwaitExpression' ? (node.argument as AstNode | undefined) : node;\n}\n\nfunction findPreparedConfigSources(ast: AstNode): Map<string, AstNode> {\n const factoryConfigs = new Map<string, AstNode>();\n const preparedConfigs = new Map<string, AstNode>();\n\n walkAst(ast, node => {\n if (node.type !== 'VariableDeclarator') return;\n const id = node.id as AstNode | undefined;\n const init = node.init as AstNode | undefined;\n const callee = init?.type === 'NewExpression' ? (init.callee as AstNode | undefined) : undefined;\n const config = (init?.arguments as AstNode[] | undefined)?.[0];\n if (\n id?.type === 'Identifier' &&\n callee?.type === 'Identifier' &&\n callee.name === 'MastraFactory' &&\n config?.type === 'ObjectExpression'\n ) {\n factoryConfigs.set(id.name as string, config);\n }\n });\n\n walkAst(ast, node => {\n if (node.type !== 'VariableDeclarator') return;\n const id = node.id as AstNode | undefined;\n const init = unwrapAwait(node.init as AstNode | undefined);\n const callee = init?.type === 'CallExpression' ? (init.callee as AstNode | undefined) : undefined;\n const object = callee?.type === 'MemberExpression' ? (callee.object as AstNode | undefined) : undefined;\n const property = callee?.type === 'MemberExpression' ? (callee.property as AstNode | undefined) : undefined;\n const isPrepareCall =\n (property?.type === 'Identifier' && property.name === 'prepare') ||\n (property?.type === 'Literal' && property.value === 'prepare');\n if (id?.type !== 'Identifier' || object?.type !== 'Identifier' || !isPrepareCall) return;\n\n const factoryConfig = factoryConfigs.get(object.name as string);\n if (factoryConfig) preparedConfigs.set(id.name as string, factoryConfig);\n });\n\n return preparedConfigs;\n}\n\nfunction resolvedObjectProperty(\n config: AstNode,\n name: string,\n preparedConfigs: Map<string, AstNode>,\n seen = new Set<AstNode>(),\n): AstNode | undefined {\n if (config.type !== 'ObjectExpression' || seen.has(config)) return undefined;\n seen.add(config);\n\n let value: AstNode | undefined;\n for (const property of (config.properties as AstNode[] | undefined) ?? []) {\n if (property.type === 'Property' && propertyName(property) === name) {\n value = property.value as AstNode | undefined;\n continue;\n }\n if (property.type !== 'SpreadElement') continue;\n\n const argument = property.argument as AstNode | undefined;\n const spreadConfig = argument?.type === 'Identifier' ? preparedConfigs.get(argument.name as string) : undefined;\n if (!spreadConfig) continue;\n const spreadValue = resolvedObjectProperty(spreadConfig, name, preparedConfigs, seen);\n if (spreadValue) value = spreadValue;\n }\n\n return value;\n}\n\n/**\n * Best-effort static extraction of the worker topology configured on a\n * `new Mastra(...)` instance, including `MastraFactory.prepare()` results spread\n * into its constructor. A worker service is only useful when the instance\n * explicitly provides both storage and pubsub so its processes can coordinate.\n * Dynamic values and callbacks are omitted from the display-only manifest.\n */\nfunction findStaticCustomWorkerNames(ast: AstNode, workers: AstNode | undefined): string[] {\n const variableInitializers = new Map<string, AstNode>();\n const classWorkerNames = new Map<string, string>();\n\n walkAst(ast, node => {\n if (node.type === 'VariableDeclarator') {\n const id = node.id as AstNode | undefined;\n const init = node.init as AstNode | undefined;\n if (id?.type === 'Identifier' && init) variableInitializers.set(id.name as string, init);\n return;\n }\n\n if (node.type !== 'ClassDeclaration' && node.type !== 'ClassExpression') return;\n const id = node.id as AstNode | undefined;\n const body = node.body as AstNode | undefined;\n if (id?.type !== 'Identifier' || body?.type !== 'ClassBody') return;\n\n for (const member of (body.body as AstNode[] | undefined) ?? []) {\n if (member.type !== 'PropertyDefinition' || propertyName(member) !== 'name') continue;\n const value = member.value as AstNode | undefined;\n const name = value ? staticJsonValue(value) : undefined;\n if (typeof name === 'string') classWorkerNames.set(id.name as string, name);\n }\n });\n\n const names = new Set<string>();\n const seen = new Set<AstNode>();\n const visit = (node: AstNode | undefined): void => {\n if (!node || seen.has(node)) return;\n seen.add(node);\n\n if (node.type === 'Identifier') {\n visit(variableInitializers.get(node.name as string));\n return;\n }\n if (node.type === 'ArrayExpression') {\n for (const element of (node.elements as Array<AstNode | null> | undefined) ?? []) {\n if (element?.type === 'SpreadElement') {\n visit(element.argument as AstNode | undefined);\n } else {\n visit(element ?? undefined);\n }\n }\n return;\n }\n if (node.type === 'NewExpression') {\n const callee = node.callee as AstNode | undefined;\n const name = callee?.type === 'Identifier' ? classWorkerNames.get(callee.name as string) : undefined;\n if (name) names.add(name);\n return;\n }\n if (node.type === 'ObjectExpression') {\n const name = staticObjectValue(node).name;\n if (typeof name === 'string') names.add(name);\n }\n };\n\n visit(workers);\n for (const builtIn of ['orchestration', 'scheduler', 'backgroundTasks']) names.delete(builtIn);\n return [...names].sort();\n}\n\nfunction findWorkersConfig(ast: AstNode): WorkersConfig | undefined {\n const preparedConfigs = findPreparedConfigSources(ast);\n let workersConfig: WorkersConfig | undefined;\n walkAst(ast, node => {\n if (workersConfig || node.type !== 'NewExpression') return;\n const callee = node.callee as AstNode | undefined;\n if (callee?.type !== 'Identifier' || callee.name !== 'Mastra') return;\n const config = (node.arguments as AstNode[] | undefined)?.[0];\n if (config?.type !== 'ObjectExpression') return;\n\n const storage = resolvedObjectProperty(config, 'storage', preparedConfigs);\n const pubsub = resolvedObjectProperty(config, 'pubsub', preparedConfigs);\n const workers = resolvedObjectProperty(config, 'workers', preparedConfigs);\n if (!isConfigured(storage) || !isConfigured(pubsub) || (workers?.type === 'Literal' && workers.value === false)) {\n return;\n }\n\n const scheduler = staticObjectValue(resolvedObjectProperty(config, 'scheduler', preparedConfigs));\n const backgroundTasks = staticObjectValue(resolvedObjectProperty(config, 'backgroundTasks', preparedConfigs));\n\n workersConfig = {\n version: 1,\n orchestration: { enabled: true },\n scheduler: { ...scheduler, enabled: scheduler.enabled !== false },\n backgroundTasks: { ...backgroundTasks, enabled: backgroundTasks.enabled === true },\n custom: findStaticCustomWorkerNames(ast, workers),\n };\n });\n return workersConfig;\n}\n\n/** Find the first `process.env.X` / `process.env['X']` read inside an expression. */\nfunction findFirstEnvRef(node: AstNode): string | undefined {\n let found: string | undefined;\n walkAst(node, n => {\n if (found !== undefined) return;\n if (n.type !== 'MemberExpression') return;\n const object = n.object as AstNode | undefined;\n if (\n !object ||\n object.type !== 'MemberExpression' ||\n (object.object as AstNode | undefined)?.type !== 'Identifier' ||\n ((object.object as AstNode).name as string) !== 'process' ||\n (object.property as AstNode | undefined)?.type !== 'Identifier' ||\n ((object.property as AstNode).name as string) !== 'env'\n ) {\n return;\n }\n const property = n.property as AstNode | undefined;\n if (property?.type === 'Identifier' && !n.computed) {\n found = property.name as string;\n } else if (property?.type === 'Literal' && typeof property.value === 'string') {\n found = property.value;\n }\n });\n return found;\n}\n\n/**\n * Parse a module and figure out, for each detected local-path value, whether\n * every string literal containing it is the fallback arm of a\n * `process.env.X || <literal>` / `??` expression. Returns a map from\n * detected value to guarding env var name. Values with any unguarded\n * occurrence (or inconsistent guards) are absent — the CLI then errors as\n * before, which is the safe default.\n */\nfunction findGuardedValues(ast: AstNode, values: Set<string>): Map<string, string> {\n const stringLiterals: AstNode[] = [];\n const guardedLiterals = new Map<AstNode, string>();\n\n walkAst(ast, node => {\n if (node.type === 'Literal' && typeof node.value === 'string') {\n stringLiterals.push(node);\n return;\n }\n if (node.type === 'LogicalExpression' && (node.operator === '||' || node.operator === '??')) {\n const right = node.right as AstNode | undefined;\n if (right?.type === 'Literal' && typeof right.value === 'string') {\n const envName = findFirstEnvRef(node.left as AstNode);\n if (envName) guardedLiterals.set(right, envName);\n }\n }\n });\n\n const result = new Map<string, string>();\n for (const value of values) {\n const containing = stringLiterals.filter(lit => (lit.value as string).includes(value));\n if (containing.length === 0) continue;\n const guards = containing.map(lit => guardedLiterals.get(lit));\n const first = guards[0];\n if (first !== undefined && guards.every(g => g === first)) {\n result.set(value, first);\n }\n }\n return result;\n}\n\n/**\n * Rollup plugin that detects host-local storage URLs (e.g. `file:./mastra.db`,\n * `postgres://localhost`) in **user source modules** during bundling, and\n * collects the env vars user code reads via `process.env.X`.\n *\n * Only modules outside `node_modules` (and the deployer's own\n * `.mastra/.build/` pre-bundled files) are inspected, so library code\n * (like Agent Builder prompt templates or JSDoc examples in `@mastra/core`)\n * is naturally excluded. When `rootDir` is given, modules outside it are\n * also excluded — symlinked dependencies (pnpm `link:`/`file:`) resolve to\n * real paths that never contain `node_modules`. Tree-shaken modules are\n * excluded via\n * `generateBundle` — only modules that actually contribute rendered code to\n * the output are reported.\n *\n * When a detected literal is the fallback arm of a `process.env.X || literal`\n * expression, `guardedBy: \"X\"` is recorded so the CLI preflight can apply\n * deploy-time env context instead of hard-erroring on a dead fallback.\n *\n * Three assets are emitted into the output directory:\n * - `preflight-metadata.json` — unified metadata (local paths + user env refs)\n * - `workers.json` — statically extracted worker topology, or `null`\n * - `preflight-local-paths.json` — legacy shape, kept for one release so an\n * older globally-installed CLI paired with a newer project-local deployer\n * doesn't lose the LOCAL_STORAGE_PATH check.\n */\nexport function localStorageDetector(rootDir?: string): Plugin {\n const userModuleMatches = new Map<string, ModuleMatch[]>();\n const userModuleEnvRefs = new Map<string, Set<string>>();\n const userModuleWorkersConfigs = new Map<string, WorkersConfig>();\n let normalizedRoot: string | undefined;\n if (rootDir) {\n let root = rootDir.replace(/\\\\/g, '/');\n while (root.endsWith('/')) root = root.slice(0, -1);\n normalizedRoot = root + '/';\n }\n\n return {\n name: 'mastra-local-storage-detector',\n\n transform(_code, id) {\n if (id.includes('node_modules')) return null;\n if (MASTRA_BUILD_DIR.test(id)) return null;\n // Modules outside the project/workspace root are dependencies resolved\n // through symlinks (pnpm `link:`, `file:`, monorepo dev setups) whose\n // real path escapes `node_modules` — library code, not user code.\n if (normalizedRoot && !id.replace(/\\\\/g, '/').startsWith(normalizedRoot)) return null;\n\n const refs = collectEnvRefs(_code);\n if (refs.size > 0) {\n userModuleEnvRefs.set(id, refs);\n }\n\n const matches: ModuleMatch[] = [];\n for (const { pattern, hint } of LOCAL_HOST_PATTERNS) {\n const re = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');\n for (const m of _code.matchAll(re)) {\n matches.push({ value: m[0], hint });\n }\n }\n\n // Best-effort structural pass: only parse modules that may contain\n // Mastra worker config or need guard analysis for a detected local path.\n // Existing local-path matches remain unguarded on parse failure.\n if (_code.includes('Mastra') || matches.length > 0) {\n try {\n const ast = this.parse(_code) as unknown as AstNode;\n const workersConfig = findWorkersConfig(ast);\n if (workersConfig) {\n userModuleWorkersConfigs.set(id, workersConfig);\n }\n if (matches.length > 0) {\n const guarded = findGuardedValues(ast, new Set(matches.map(m => m.value)));\n for (const match of matches) {\n const guardedBy = guarded.get(match.value);\n if (guardedBy) match.guardedBy = guardedBy;\n }\n }\n } catch {\n // ignore — optional static metadata is best-effort\n }\n }\n\n if (matches.length > 0) {\n userModuleMatches.set(id, matches);\n }\n\n return null;\n },\n\n generateBundle(_, bundle) {\n const detections: LocalStorageDetection[] = [];\n const seen = new Set<string>();\n const userEnvRefs = new Set<string>();\n let workersConfig: WorkersConfig | undefined;\n\n for (const chunk of Object.values(bundle)) {\n if (chunk.type !== 'chunk') continue;\n\n for (const [moduleId, moduleInfo] of Object.entries(chunk.modules)) {\n if (moduleInfo.renderedLength === 0) continue;\n\n for (const ref of userModuleEnvRefs.get(moduleId) ?? []) {\n userEnvRefs.add(ref);\n }\n workersConfig ??= userModuleWorkersConfigs.get(moduleId);\n\n const matches = userModuleMatches.get(moduleId);\n if (!matches) continue;\n\n for (const { value, hint, guardedBy } of matches) {\n const key = `${hint}::${value}`;\n if (seen.has(key)) continue;\n seen.add(key);\n\n detections.push({ value, hint, module: moduleId, ...(guardedBy ? { guardedBy } : {}) });\n }\n }\n }\n\n const metadata: PreflightMetadata = {\n version: 1,\n localPaths: detections,\n userEnvRefs: [...userEnvRefs].sort(),\n };\n\n this.emitFile({\n type: 'asset',\n fileName: PREFLIGHT_METADATA_FILE,\n source: JSON.stringify(metadata),\n });\n\n this.emitFile({\n type: 'asset',\n fileName: WORKERS_CONFIG_FILE,\n source: JSON.stringify(workersConfig ?? null),\n });\n\n // Legacy asset — shape unchanged (no `guardedBy`) for older CLIs.\n this.emitFile({\n type: 'asset',\n fileName: LEGACY_LOCAL_PATHS_FILE,\n source: JSON.stringify(detections.map(({ value, hint, module }) => ({ value, hint, module }))),\n });\n },\n };\n}\n","/**\n * Note: This function depends on local-pkg and should only be used at build-time.\n * It is in a separate file to avoid including local-pkg in runtime code.\n */\n\nimport { statSync } from 'node:fs';\nimport { dirname, resolve, sep } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { findUp } from 'find-up-simple';\nimport { readJson, readJSON } from 'fs-extra/esm';\nimport { getPackageInfo as getOriginalPackageInfo } from 'local-pkg';\nimport { getPackageName } from './utils';\n\nexport async function getPackageInfo(\n packageName: string,\n options?: { paths?: string[] },\n): Promise<ReturnType<typeof getOriginalPackageInfo>> {\n const pkgInfo = await getOriginalPackageInfo(packageName, options);\n\n async function searchUpForPackageJson(rootPath: string) {\n const path = await findUp('package.json', {\n cwd: rootPath,\n });\n\n if (!path) {\n return undefined;\n }\n\n const pkgJson = await readJson(path);\n\n if (!pkgJson.version) {\n return searchUpForPackageJson(dirname(rootPath));\n }\n\n return {\n name: pkgJson.name,\n version: pkgJson.version,\n rootPath: dirname(path),\n packageJsonPath: path,\n packageJson: pkgJson,\n };\n }\n\n if (!pkgInfo?.version && pkgInfo?.rootPath) {\n return searchUpForPackageJson(dirname(pkgInfo.rootPath));\n }\n\n return pkgInfo;\n}\n\n/**\n * Normalize a resolution base path to a directory path.\n *\n * Callers often pass a module file path (e.g. a rollup module id like\n * `node_modules/@mastra/core/dist/chunk-XYZ.js`) as the parent path. mlly (used by local-pkg)\n * also treats each resolution base as a directory candidate (`<base>/_index.js`), which makes it\n * try to read `<file>/package.json`. That fails with ENOTDIR, which mlly does not tolerate\n * (only ENOENT) and local-pkg then logs the raw error to the console. Using the file's directory\n * as the base avoids this while resolving identically.\n */\nfunction toParentDirectoryUrl(parentPath: string): string {\n let fsPath = resolve(parentPath.startsWith('file://') ? fileURLToPath(parentPath) : parentPath);\n\n try {\n if (statSync(fsPath).isFile()) {\n fsPath = dirname(fsPath);\n }\n } catch {\n // non-existent paths are used as-is\n }\n\n // Keep the trailing separator. Without it, URL resolution treats the directory name as a file\n // and starts package lookup from its parent directory.\n return pathToFileURL(`${fsPath}${sep}`).href;\n}\n\n/**\n * Get package root path\n */\nexport async function getPackageRootPath(packageName: string, parentPath?: string): Promise<string | null> {\n let rootPath: string | null;\n\n try {\n let options: { paths?: string[] } | undefined = undefined;\n if (parentPath) {\n options = {\n paths: [toParentDirectoryUrl(parentPath)],\n };\n }\n\n const pkg = await getPackageInfo(packageName, options);\n rootPath = pkg?.rootPath ?? null;\n } catch {\n rootPath = null;\n }\n\n return rootPath;\n}\n\nasync function readPackageMetadata(\n rootPath: string,\n requestedPackageName: string | null,\n): Promise<{ rootPath: string; version?: string; packageSpec?: string }> {\n try {\n const pkgJson = await readJSON(`${rootPath}/package.json`);\n const version = pkgJson.version;\n const actualPackageName = pkgJson.name;\n const packageSpec =\n version && actualPackageName && requestedPackageName && requestedPackageName !== actualPackageName\n ? `npm:${actualPackageName}@${version}`\n : undefined;\n\n return { rootPath, version, packageSpec };\n } catch {\n return { rootPath };\n }\n}\n\nexport async function getPackageMetadata(\n packageName: string,\n parentPath?: string,\n): Promise<{ rootPath: string | null; version?: string; packageSpec?: string }> {\n const requestedPackageName = getPackageName(packageName);\n const packageNames = [...new Set([packageName, requestedPackageName].filter(Boolean) as string[])];\n let firstRootPath: string | null = null;\n\n for (const name of packageNames) {\n const rootPath = await getPackageRootPath(name, parentPath);\n firstRootPath ??= rootPath;\n if (!rootPath) {\n continue;\n }\n\n const metadata = await readPackageMetadata(rootPath, requestedPackageName ?? null);\n if (metadata.version || metadata.packageSpec) {\n return metadata;\n }\n }\n\n return { rootPath: firstRootPath };\n}\n","import { readFile } from 'node:fs/promises';\nimport { join, isAbsolute } from 'node:path';\nimport nodeResolve from '@rollup/plugin-node-resolve';\nimport type { Plugin } from 'rollup';\nimport type { PackageJson } from 'type-fest';\nimport { getPackageRootPath } from '../package-info';\nimport { getPackageName, isExternalProtocolImport, isBareModuleSpecifier } from '../utils';\n\n/**\n * Check if a package has an exports field in its package.json.\n * Results are cached to avoid repeated filesystem reads.\n */\nasync function getPackageJSON(pkgName: string, importer: string): Promise<PackageJson> {\n const pkgRoot = await getPackageRootPath(pkgName, importer);\n if (!pkgRoot) {\n throw new Error(`Package ${pkgName} not found`);\n }\n\n const pkgJSON = JSON.parse(await readFile(join(pkgRoot, 'package.json'), 'utf-8')) as PackageJson;\n return pkgJSON;\n}\n\n/**\n * Rollup plugin that resolves module extensions for external dependencies.\n *\n * This plugin handles ESM compatibility for external imports when node-resolve is not used:\n * - Packages WITH exports field (e.g., hono, date-fns): Keep imports as-is or strip redundant extensions\n * - Packages WITHOUT exports field (e.g., lodash): Add .js extension for direct file imports\n */\nexport function nodeModulesExtensionResolver(): Plugin {\n // Create a single instance of node-resolve to reuse\n const nodeResolvePlugin = nodeResolve();\n\n return {\n name: 'node-modules-extension-resolver',\n async resolveId(id, importer, options) {\n // Only bare package imports are relevant here.\n // Virtual modules (e.g. `\\0virtual:#entry`) are not real filesystem paths, so they can't be\n // used as a resolution base for package lookups.\n if (\n !importer ||\n importer.startsWith('\\0') ||\n !isBareModuleSpecifier(id) ||\n isExternalProtocolImport(id) ||\n isAbsolute(id)\n ) {\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 {\n return null;\n }\n },\n };\n}\n","import type { Plugin } from 'rollup';\nimport { isExternalProtocolImport } from '../utils';\n\nexport function protocolExternalResolver({ exclude = ['node:'] }: { exclude?: readonly string[] } = {}): Plugin {\n return {\n name: 'protocol-external-resolver',\n resolveId(id) {\n if (!isExternalProtocolImport(id, exclude)) {\n return null;\n }\n\n return {\n id,\n external: true,\n };\n },\n } satisfies Plugin;\n}\n","import { types as t } from '@babel/core';\nimport type { NodePath, PluginObject, PluginPass } from '@babel/core';\n\ninterface RemoveDeployerState extends PluginPass {\n hasReplaced?: boolean;\n}\n\nexport function removeDeployer(): PluginObject<RemoveDeployerState> {\n // Helper to remove deployer property from an object and clean up its binding\n function removeDeployerFromObject(\n objectExpr: t.ObjectExpression,\n scope: { getBinding: (name: string) => { path?: NodePath } | undefined },\n ): t.ObjectProperty | undefined {\n const deployerProp = objectExpr.properties.find(\n prop => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === 'deployer',\n ) as t.ObjectProperty | undefined;\n\n if (deployerProp) {\n objectExpr.properties = objectExpr.properties.filter(prop => prop !== deployerProp);\n\n // Clean up the deployer binding if it's a reference\n if (t.isIdentifier(deployerProp.value)) {\n const deployerBinding = scope.getBinding(deployerProp.value.name);\n if (deployerBinding) {\n deployerBinding.path?.parentPath?.remove();\n }\n }\n }\n\n return deployerProp;\n }\n\n return {\n name: 'remove-deployer',\n visitor: {\n NewExpression(path, state: RemoveDeployerState) {\n // is a variable declaration\n const varDeclaratorPath = path.findParent(path => t.isVariableDeclarator(path.node));\n if (!varDeclaratorPath) {\n return;\n }\n\n const parentNode = path.parentPath.node;\n // check if it's a const of mastra\n if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== 'mastra') {\n return;\n }\n\n if (!state.hasReplaced) {\n state.hasReplaced = true;\n const newMastraObj = t.cloneNode(path.node);\n if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.length) {\n const objectArg = newMastraObj.arguments[0];\n let foundDeployer = false;\n\n // First, check for direct deployer property\n const directDeployer = removeDeployerFromObject(objectArg, state.file.scope);\n if (directDeployer) {\n foundDeployer = true;\n }\n\n // Then, check spread elements for deployer properties\n for (const prop of objectArg.properties) {\n if (t.isSpreadElement(prop) && t.isIdentifier(prop.argument)) {\n const spreadBinding = state.file.scope.getBinding(prop.argument.name);\n if (spreadBinding?.path && t.isVariableDeclarator(spreadBinding.path.node)) {\n const init = spreadBinding.path.node.init;\n if (t.isObjectExpression(init)) {\n const spreadDeployer = removeDeployerFromObject(init, state.file.scope);\n if (spreadDeployer) {\n foundDeployer = true;\n }\n }\n }\n }\n }\n\n if (foundDeployer) {\n path.replaceWith(newMastraObj);\n }\n }\n }\n },\n },\n } as PluginObject<RemoveDeployerState>;\n}\n","import { transformAsync } from '@babel/core';\nimport type { Plugin, SourceMapInput } from 'rollup';\n\nimport { removeDeployer as removeDeployerBabelPlugin } from '../babel/remove-deployer';\n\nexport function removeDeployer(mastraEntry: string, options?: { sourcemap?: boolean }): Plugin {\n return {\n name: 'remove-deployer',\n transform(code, id) {\n if (id !== mastraEntry) {\n return;\n }\n\n return transformAsync(code, {\n babelrc: false,\n configFile: false,\n filename: id,\n plugins: [removeDeployerBabelPlugin],\n sourceMaps: options?.sourcemap,\n }).then(result => ({\n code: result!.code!,\n map: result!.map! as SourceMapInput,\n }));\n },\n } satisfies Plugin;\n}\n","import type { Plugin } from 'rollup';\nimport { isDependencyPartOfPackage } from '../utils';\n\nexport function subpathExternalsResolver(externals: string[]): Plugin {\n return {\n name: 'subpath-externals-resolver',\n resolveId(id) {\n if (id.startsWith('.') || id.startsWith('/')) {\n return null;\n }\n\n const isPartOfExternals = externals.some(external => isDependencyPartOfPackage(id, external));\n if (isPartOfExternals) {\n return {\n id,\n external: true,\n };\n }\n },\n } satisfies Plugin;\n}\n","import fs from 'node:fs';\nimport path, { normalize } from 'node:path';\nimport type { Plugin } from 'rollup';\nimport stripJsonComments from 'strip-json-comments';\nimport type { RegisterOptions } from 'typescript-paths';\nimport { createHandler } from 'typescript-paths';\n\nconst PLUGIN_NAME = 'tsconfig-paths';\nconst JS_IMPORT_SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n\nexport type PluginOptions = Omit<RegisterOptions, 'loggerID'> & { localResolve?: boolean; cwd?: string };\n\n/**\n * Check if a tsconfig file has path mappings configured.\n * Exported for testing purposes.\n *\n * @param tsConfigPath - Path to the tsconfig.json file\n * @returns true if the tsconfig has paths configured or extends another config, false otherwise\n */\nexport function hasPaths(tsConfigPath: string): boolean {\n try {\n const content = fs.readFileSync(tsConfigPath, 'utf8');\n const config = JSON.parse(stripJsonComments(content));\n return !!(\n (config.compilerOptions?.paths && Object.keys(config.compilerOptions.paths).length > 0) ||\n (typeof config.extends === 'string' && config.extends.length > 0) ||\n (Array.isArray(config.extends) && config.extends.length > 0)\n );\n } catch {\n return false;\n }\n}\n\nexport function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve, cwd }: PluginOptions = {}): Plugin {\n const handlerCache = new Map<string, ReturnType<typeof createHandler>>();\n\n function resolveJsImportToSourceFile(moduleName: string): string {\n if (fs.existsSync(moduleName)) {\n return moduleName;\n }\n\n const parsed = path.parse(moduleName);\n if (parsed.ext !== '.js') {\n return moduleName;\n }\n\n for (const extension of JS_IMPORT_SOURCE_EXTENSIONS) {\n const candidate = path.join(parsed.dir, `${parsed.name}${extension}`);\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return moduleName;\n }\n\n // Find tsconfig.json file starting from a directory and walking up\n function findTsConfigForFile(filePath: string): string | null {\n let currentDir = path.dirname(filePath);\n const root = path.parse(currentDir).root;\n\n while (currentDir !== root) {\n const tsConfigPath = path.join(currentDir, 'tsconfig.json');\n\n if (fs.existsSync(tsConfigPath)) {\n // Check if this tsconfig has path mappings\n if (hasPaths(tsConfigPath)) {\n return tsConfigPath;\n }\n }\n\n // Also check for tsconfig.base.json (common in NX)\n const tsConfigBasePath = path.join(currentDir, 'tsconfig.base.json');\n if (fs.existsSync(tsConfigBasePath)) {\n if (hasPaths(tsConfigBasePath)) {\n return tsConfigBasePath;\n }\n }\n\n currentDir = path.dirname(currentDir);\n }\n\n return null;\n }\n\n // Get or create handler for a specific tsconfig file\n function getHandlerForFile(filePath: string): ReturnType<typeof createHandler> | null {\n // If a specific tsConfigPath was provided, use it\n if (tsConfigPath && typeof tsConfigPath === 'string') {\n if (!handlerCache.has(tsConfigPath)) {\n handlerCache.set(\n tsConfigPath,\n createHandler({\n log: () => {},\n tsConfigPath,\n respectCoreModule,\n falllback: moduleName => fs.existsSync(moduleName),\n }),\n );\n }\n return handlerCache.get(tsConfigPath)!;\n }\n\n // Find appropriate tsconfig for this file\n const configPath = findTsConfigForFile(filePath);\n if (!configPath) {\n return null;\n }\n\n // Cache handlers to avoid recreation\n if (!handlerCache.has(configPath)) {\n handlerCache.set(\n configPath,\n createHandler({\n log: () => {},\n tsConfigPath: configPath,\n respectCoreModule,\n falllback: moduleName => fs.existsSync(moduleName),\n }),\n );\n }\n\n return handlerCache.get(configPath)!;\n }\n\n // Simple alias resolution using dynamic handler\n function resolveAlias(request: string, importer: string): string | null | undefined {\n // Get the appropriate handler for this file\n const dynamicHandler = getHandlerForFile(importer);\n if (!dynamicHandler) {\n return null;\n }\n\n const resolved = dynamicHandler(request, normalize(importer));\n return resolved;\n }\n\n return {\n name: PLUGIN_NAME,\n resolveId: {\n order: 'pre',\n async handler(request, importer, options) {\n if (!importer || request.startsWith('\\0') || importer.charCodeAt(0) === 0) {\n return null;\n }\n\n // Convert relative paths to absolute to ensure proper tsconfig path resolution\n // This allows path aliases to work regardless of how the importer path is provided\n if (!path.isAbsolute(importer)) {\n importer = path.resolve(cwd ?? process.cwd(), importer);\n }\n\n const moduleName = resolveAlias(request, importer);\n // No tsconfig alias found, so we need to resolve it normally\n if (!moduleName) {\n const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });\n if (!resolved) {\n return null;\n }\n\n // If localResolve is true, we need to check if the importer has been resolved by the tsconfig-paths plugin\n // if so, we need to resolve the request from the importer instead of the root and mark it as external\n if (localResolve) {\n const importerInfo = this.getModuleInfo(importer);\n const importerPluginMeta = importerInfo?.meta?.[PLUGIN_NAME];\n\n if (\n !path.isAbsolute(request) &&\n !request.startsWith('./') &&\n !request.startsWith('../') &&\n importerPluginMeta?.resolved\n ) {\n return {\n ...resolved,\n external: !request.startsWith('hono/') && request !== 'hono',\n };\n }\n }\n\n return {\n ...resolved,\n meta: {\n ...(resolved.meta || {}),\n },\n };\n }\n\n const resolvedModuleName = resolveJsImportToSourceFile(moduleName);\n\n // When a module does not have an extension, we need to resolve it to a file\n if (!path.extname(resolvedModuleName)) {\n const resolved = await this.resolve(resolvedModuleName, importer, { skipSelf: true, ...options });\n\n if (!resolved) {\n return null;\n }\n\n return {\n ...resolved,\n meta: {\n ...resolved.meta,\n [PLUGIN_NAME]: {\n resolved: true,\n },\n },\n };\n }\n\n // Always pass through bundler's resolution to ensure proper path normalization\n const resolved = await this.resolve(resolvedModuleName, importer, { skipSelf: true, ...options });\n\n if (!resolved) {\n return null;\n }\n\n return {\n ...resolved,\n meta: {\n ...resolved.meta,\n [PLUGIN_NAME]: {\n resolved: true,\n },\n },\n };\n },\n },\n } satisfies Plugin;\n}\n","import { join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';\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 { minify as esbuildMinify } from 'rollup-plugin-esbuild';\nimport type { WorkspacePackageInfo } from '../bundler/workspaceDependencies';\nimport { esbuild } from './plugins/esbuild';\nimport { esmShim } from './plugins/esm-shim';\nimport { localStorageDetector } from './plugins/local-storage-detector';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { protocolExternalResolver } from './plugins/protocol-external-resolver';\nimport { removeDeployer } from './plugins/remove-deployer';\nimport { subpathExternalsResolver } from './plugins/subpath-externals-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport type { ExternalDependencyInfo } from './types';\nimport { getPackageName, getNodeResolveOptions, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport function mastraInternalAliasPlugin(entryFile: string): Plugin {\n const normalizedEntryFile = slash(entryFile);\n\n return {\n name: 'mastra-internal-alias',\n resolveId: {\n order: 'pre',\n handler(id) {\n if (id === '#server') {\n return slash(fileURLToPath(import.meta.resolve('@mastra/deployer/server')));\n }\n\n if (id.startsWith('@mastra/server/')) {\n return fileURLToPath(import.meta.resolve(id));\n }\n\n if (id === '#mastra') {\n return normalizedEntryFile;\n }\n },\n },\n } satisfies Plugin;\n}\n\nexport function mastraToolsAliasPlugin(): Plugin {\n return {\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 };\n}\n\nexport async function getInputOptions(\n entryFile: string,\n analyzedBundleInfo: {\n dependencies: Map<string, string>;\n externalDependencies: Map<string, ExternalDependencyInfo>;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n projectType?: string;\n },\n platform: BundlerPlatform,\n env: Record<string, string> = { 'process.env.NODE_ENV': JSON.stringify('production') },\n {\n sourcemap = false,\n minify = false,\n isDev = false,\n projectRoot,\n workspaceRoot = undefined,\n enableEsmShim = true,\n externalsPreset = false,\n }: {\n sourcemap?: boolean;\n minify?: boolean;\n isDev?: boolean;\n workspaceRoot?: string;\n projectRoot: string;\n enableEsmShim?: boolean;\n externalsPreset?: boolean;\n },\n): Promise<InputOptions> {\n const nodeResolvePlugin = nodeResolve({\n ...getNodeResolveOptions(platform),\n rootDir: projectRoot,\n modulePaths: workspaceRoot ? [join(workspaceRoot, 'node_modules')] : [],\n });\n\n const externalsCopy = new Set<string>(analyzedBundleInfo.externalDependencies.keys());\n const externals = externalsPreset ? [] : Array.from(externalsCopy);\n\n return {\n logLevel: process.env.MASTRA_BUNDLER_DEBUG === 'true' ? 'debug' : 'silent',\n treeshake: 'smallest',\n preserveSymlinks: true,\n external: externals,\n plugins: [\n protocolExternalResolver(),\n subpathExternalsResolver(externals),\n {\n name: 'alias-optimized-deps',\n resolveId(id: string) {\n if (!analyzedBundleInfo.dependencies.has(id)) {\n return null;\n }\n\n const filename = analyzedBundleInfo.dependencies.get(id)!;\n const absolutePath = join(workspaceRoot || projectRoot, filename);\n\n // During `mastra dev` we want to keep deps as external\n if (isDev) {\n return {\n id: process.platform === 'win32' ? pathToFileURL(absolutePath).href : absolutePath,\n external: true,\n };\n }\n\n // For production builds return the absolute path as-is so Rollup can handle itself\n return {\n id: absolutePath,\n external: false,\n };\n },\n } satisfies Plugin,\n mastraInternalAliasPlugin(entryFile),\n tsConfigPaths({ cwd: projectRoot }),\n mastraToolsAliasPlugin(),\n esbuild({\n platform,\n define: env,\n }),\n optimizeLodashImports({\n include: '**/*.{js,ts,mjs,cjs}',\n }),\n externalsPreset\n ? null\n : commonjs({\n extensions: ['.js', '.ts'],\n transformMixedEsModules: true,\n esmExternals(id) {\n return externals.includes(id);\n },\n }),\n enableEsmShim ? esmShim() : undefined,\n externalsPreset ? nodeModulesExtensionResolver() : nodeResolvePlugin,\n // for debugging\n // {\n // name: 'logger',\n // //@ts-expect-error\n // resolveId(id, ...args) {\n // console.log({ id, args });\n // },\n // // @ts-expect-error\n // transform(code, id) {\n // if (code.includes('class Duplexify ')) {\n // console.log({ duplex: id });\n // }\n // },\n // },\n json(),\n localStorageDetector(workspaceRoot || projectRoot),\n removeDeployer(entryFile, { sourcemap }),\n // treeshake unused imports\n esbuild({\n include: entryFile,\n platform,\n }),\n // Runs at renderChunk, so the emitted chunks are minified as a whole rather\n // than module by module. Last in the list so nothing transforms after it.\n // `sourceMap` follows the build's own setting: the plugin defaults it to true,\n // which would build a map Rollup then discards on a non-sourcemap build.\n minify ? esbuildMinify({ target: 'node20', sourceMap: sourcemap }) : null,\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\n/**\n * Checks whether a Rollup warning is an UNRESOLVED_IMPORT for a workspace package.\n * Returns the original import specifier if it's a workspace package that leaked\n * through, or undefined if it's not.\n */\nexport function getUnresolvedWorkspaceImport(\n warning: { code: string; source?: string; id?: string },\n workspaceMap: Map<string, WorkspacePackageInfo>,\n): string | undefined {\n if (warning.code !== 'UNRESOLVED_IMPORT') {\n return undefined;\n }\n\n const src = warning.source ?? warning.id ?? '';\n if (!src) {\n return undefined;\n }\n\n const pkgName = getPackageName(src);\n if (pkgName && workspaceMap.has(pkgName)) {\n return src;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAEA,SAAgB,QAAQ,UAAiD,CAAC,GAAG;CAC3E,OAAO,gBAAgB;EACrB,QAAQ;EACR,UAAU;EACV,QAAQ;EACR,GAAG;CACL,CAAC;AACH;;;ACJA,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;;;;;;;;;;;AAYhC,SAAgB,UAAkB;CAChC,MAAM,WAAW,gBAAgB;CAEjC,OAAO;EACL,MAAM;EACN,YAAY,MAAM,OAAO,MAAM,MAAM;GAEnC,MAAM,cAAc,KAAK,SAAS,YAAY;GAC9C,MAAM,aAAa,KAAK,SAAS,WAAW;GAI5C,MAAM,uBAAuB,eAAe,yBAAyB,KAAK,IAAI;GAC9E,MAAM,sBAAsB,cAAc,wBAAwB,KAAK,IAAI;GAE3E,IAAI,wBAAwB,qBAC1B,OAAO;GAIT,IAA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