@mastra/deployer-cloudflare 1.0.0-beta.0 → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/plugins/__fixtures__/basic.d.ts +1 -1
- package/dist/plugins/__fixtures__/basic.d.ts.map +1 -1
- package/dist/plugins/__fixtures__/empty-mastra.d.ts +1 -1
- package/dist/plugins/__fixtures__/empty-mastra.d.ts.map +1 -1
- package/dist/plugins/__fixtures__/multiple-postgres-stores.d.ts +1 -1
- package/dist/plugins/__fixtures__/multiple-postgres-stores.d.ts.map +1 -1
- package/package.json +7 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @mastra/deployer-cloudflare
|
|
2
2
|
|
|
3
|
+
## 1.0.0-beta.1
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Set `externals: true` as the default for `mastra build` and cloud-deployer to reduce bundle issues with native dependencies. ([`0dbf199`](https://github.com/mastra-ai/mastra/commit/0dbf199110f22192ce5c95b1c8148d4872b4d119))
|
|
8
|
+
|
|
9
|
+
**Note:** If you previously relied on the default bundling behavior (all dependencies bundled), you can explicitly set `externals: false` in your bundler configuration.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- Updated dependencies [[`4f94ed8`](https://github.com/mastra-ai/mastra/commit/4f94ed8177abfde3ec536e3574883e075423350c), [`ac3cc23`](https://github.com/mastra-ai/mastra/commit/ac3cc2397d1966bc0fc2736a223abc449d3c7719), [`a86f4df`](https://github.com/mastra-ai/mastra/commit/a86f4df0407311e0d2ea49b9a541f0938810d6a9), [`029540c`](https://github.com/mastra-ai/mastra/commit/029540ca1e582fc2dd8d288ecd4a9b0f31a954ef), [`66741d1`](https://github.com/mastra-ai/mastra/commit/66741d1a99c4f42cf23a16109939e8348ac6852e), [`01b20fe`](https://github.com/mastra-ai/mastra/commit/01b20fefb7c67c2b7d79417598ef4e60256d1225), [`0dbf199`](https://github.com/mastra-ai/mastra/commit/0dbf199110f22192ce5c95b1c8148d4872b4d119), [`a7ce182`](https://github.com/mastra-ai/mastra/commit/a7ce1822a8785ce45d62dd5c911af465e144f7d7)]:
|
|
14
|
+
- @mastra/core@1.0.0-beta.14
|
|
15
|
+
- @mastra/deployer@1.0.0-beta.14
|
|
16
|
+
|
|
3
17
|
## 1.0.0-beta.0
|
|
4
18
|
|
|
5
19
|
### Major Changes
|
package/dist/index.cjs
CHANGED
|
@@ -207,9 +207,9 @@ var CloudflareDeployer = class extends deployer.Deployer {
|
|
|
207
207
|
await super.prepare(outputDirectory);
|
|
208
208
|
await this.writeFiles(outputDirectory);
|
|
209
209
|
}
|
|
210
|
-
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths,
|
|
210
|
+
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, bundlerOptions) {
|
|
211
211
|
const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {
|
|
212
|
-
|
|
212
|
+
...bundlerOptions,
|
|
213
213
|
enableEsmShim: false
|
|
214
214
|
});
|
|
215
215
|
const hasPostgresStore = await this.deps.checkDependencies(["@mastra/pg"]) === `ok`;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/babel/mastra-instance-wrapper.ts","../src/plugins/mastra-instance-wrapper.ts","../src/babel/postgres-store-instance-checker.ts","../src/plugins/postgres-store-instance-checker.ts","../src/index.ts"],"names":["babel","mastraInstanceWrapper","transformSync","babel2","postgresStoreInstanceChecker","Deployer","writeFile","join","virtual"],"mappings":";;;;;;;;;;;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a,OAAA;AAAA,QAChBP,uBAAsB,eAAe;AAAA,OACvC;AAEA,MAAA,IAAI,gBAAA,EAAkB;AACpB,QAAA,YAAA,CAAa,OAAA,CAAQ,IAAA,CAAKG,6BAAAA,EAA8B,CAAA;AAAA,MAC1D;AAAA,IACF;AAEA,IAAA,OAAO,YAAA;AAAA,EACT;AAAA,EAEA,MAAM,MAAA,CACJ,SAAA,EACA,iBACA,EAAE,UAAA,EAAY,aAAY,EACX;AACf,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,QAAA,EAAS,EAAG,SAAA,EAAW,EAAE,eAAA,EAAiB,WAAA,EAAa,aAAA,EAAe,KAAA,EAAM,EAAG,UAAU,CAAA;AAAA,EACpH;AAAA,EAEA,MAAM,MAAA,GAAwB;AAC5B,IAAA,IAAA,CAAK,MAAA,EAAQ,KAAK,gFAAgF,CAAA;AAAA,EACpG;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,IAAI,MAAM,wFAAwF,CAAA;AAAA,EAC1G;AAAA,EAEA,MAAM,IAAA,CAAK,SAAA,EAAmB,eAAA,EAAyB,UAAA,EAAkD;AACvG,IAAA,MAAM,KAAA,CAAM,IAAA,CAAK,SAAA,EAAW,eAAA,EAAiB,UAAU,CAAA;AAEvD,IAAA,MAAM,SAAA,GAAa,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAkB,CAAC,gBAAgB,CAAC,CAAA,KAAO,CAAA,EAAA,CAAA;AAE9E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV;AAAA,OACF;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["import type { PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\n\n/**\n * Babel plugin that transforms Mastra exports for Cloudflare Workers compatibility.\n *\n * This plugin:\n * 1. Identifies named exports of the 'mastra' variable\n * 2. Checks if the export is a new instance of the 'Mastra' class\n * 3. Wraps the Mastra instantiation in an arrow function to ensure proper initialization\n * in the Cloudflare Workers environment\n *\n * The transformation ensures the Mastra instance is properly scoped and initialized\n * for each request in the Cloudflare Workers environment.\n *\n * @returns {PluginObj} A Babel plugin object with a visitor that performs the transformation\n *\n * @example\n * // Before transformation:\n * export const mastra = new Mastra();\n *\n * // After transformation:\n * export const mastra = () => new Mastra();\n */\nexport function mastraInstanceWrapper(): PluginObj {\n const exportName = 'mastra';\n const className = 'Mastra';\n const t = babel.types;\n\n return {\n name: 'wrap-mastra',\n visitor: {\n ExportNamedDeclaration(path) {\n if (t.isVariableDeclaration(path.node?.declaration)) {\n for (const declaration of path.node.declaration.declarations) {\n if (\n t.isIdentifier(declaration?.id, { name: exportName }) &&\n t.isNewExpression(declaration?.init) &&\n t.isIdentifier(declaration.init.callee, { name: className })\n ) {\n declaration.init = t.arrowFunctionExpression([], declaration.init);\n // there should be only one \"mastra\" export, so we can exit the loop\n break;\n }\n }\n }\n },\n },\n } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { mastraInstanceWrapper as mastraInstanceWrapperBabel } from '../babel/mastra-instance-wrapper';\n\nexport function mastraInstanceWrapper(mastraEntryFile: string): Plugin {\n return {\n name: 'mastra-wrapper',\n transform(code, id) {\n if (id !== mastraEntryFile) {\n return null;\n }\n\n const result = transformSync(code, {\n filename: id,\n babelrc: false,\n configFile: false,\n plugins: [mastraInstanceWrapperBabel],\n });\n\n if (!result?.code) {\n throw new Error('mastra-wrapper plugin did not return code, there is likely a bug in the plugin.');\n }\n\n return {\n code: result.code,\n map: result?.map,\n };\n },\n };\n}\n","import type { NodePath, PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\nimport type { NewExpression } from '@babel/types';\n\n/**\n * Babel plugin that enforces singleton PostgresStore instances in Cloudflare Workers.\n *\n * This plugin:\n * 1. Scans for all `new PostgresStore()` instantiations\n * 2. Records their file locations\n * 3. Throws an error if multiple instances are found\n *\n * Cloudflare Workers should only create one PostgresStore instance to avoid connection\n * pool exhaustion and ensure proper resource management.\n *\n * @returns {PluginObj} A Babel plugin object that validates PostgresStore usage\n *\n * @example\n * // Throws error if multiple instances found:\n * const store1 = new PostgresStore();\n * const store2 = new PostgresStore(); // Error thrown here\n */\nexport function postgresStoreInstanceChecker(): PluginObj {\n const t = babel.types;\n const instances: { path: NodePath<NewExpression>; location: string }[] = [];\n\n return {\n name: 'postgresstore-instance-checker',\n visitor: {\n NewExpression(path, state) {\n if (t.isIdentifier(path.node.callee) && path.node.callee.name === 'PostgresStore') {\n const filename = state.file?.opts?.filename || 'unknown file';\n const location = path.node.loc\n ? `${filename}: line ${path.node.loc.start.line}, column ${path.node.loc.start.column}`\n : 'unknown location';\n\n instances.push({\n path,\n location,\n });\n }\n },\n },\n post() {\n if (instances.length > 1) {\n const errorMessage = [\n `Found ${instances.length} PostgresStore instantiations:`,\n ...instances.map((instance, i) => ` ${i + 1}. At ${instance.location}`),\n 'Only one PostgresStore instance should be created per Cloudflare Worker.',\n ].join('\\n');\n\n const lastInstance = instances[instances.length - 1];\n throw lastInstance?.path.buildCodeFrameError(errorMessage);\n }\n },\n } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { postgresStoreInstanceChecker as postgresStoreInstanceCheckerBabel } from '../babel/postgres-store-instance-checker';\n\nexport function postgresStoreInstanceChecker(): Plugin {\n return {\n name: 'postgres-store-instance-checker',\n transform(code, id) {\n const result = transformSync(code, {\n filename: id,\n babelrc: false,\n configFile: false,\n plugins: [postgresStoreInstanceCheckerBabel],\n });\n\n // If Babel didn't transform anything or returned no code, pass through original source.\n if (!result || typeof result.code !== 'string') {\n return null;\n }\n\n return {\n code: result.code,\n map: result.map ?? null,\n };\n },\n };\n}\n","import { writeFile } from 'fs/promises';\nimport { join } from 'path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport virtual from '@rollup/plugin-virtual';\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\ninterface CFRoute {\n pattern: string;\n zone_name: string;\n custom_domain?: boolean;\n}\n\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n routes?: CFRoute[] = [];\n workerNamespace?: string;\n env?: Record<string, any>;\n projectName?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n\n constructor({\n env,\n projectName = 'mastra',\n routes,\n workerNamespace,\n d1Databases,\n kvNamespaces,\n }: {\n env?: Record<string, any>;\n projectName?: string;\n routes?: CFRoute[];\n workerNamespace?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n }) {\n super({ name: 'CLOUDFLARE' });\n\n this.projectName = projectName;\n this.routes = routes;\n this.workerNamespace = workerNamespace;\n\n if (env) {\n this.env = env;\n }\n\n if (d1Databases) this.d1Databases = d1Databases;\n if (kvNamespaces) this.kvNamespaces = kvNamespaces;\n }\n\n async writeFiles(outputDirectory: string): Promise<void> {\n const env = await this.loadEnvVars();\n const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);\n\n const cfWorkerName = this.projectName;\n\n const wranglerConfig: Record<string, any> = {\n name: cfWorkerName,\n main: './index.mjs',\n compatibility_date: '2025-04-01',\n compatibility_flags: ['nodejs_compat', 'nodejs_compat_populate_process_env'],\n observability: {\n logs: {\n enabled: true,\n },\n },\n vars: envsAsObject,\n };\n\n if (!this.workerNamespace && this.routes) {\n wranglerConfig.routes = this.routes;\n }\n\n if (this.d1Databases?.length) {\n wranglerConfig.d1_databases = this.d1Databases;\n }\n if (this.kvNamespaces?.length) {\n wranglerConfig.kv_namespaces = this.kvNamespaces;\n }\n await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig));\n }\n\n private getEntry(): string {\n return `\n import '#polyfills';\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\n export default {\n fetch: async (request, env, context) => {\n const { mastra } = await import('#mastra');\n const { tools } = await import('#tools');\n const {createHonoServer, getToolExports} = await import('#server');\n const _mastra = mastra();\n\n if (_mastra.getStorage()) {\n _mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n\n const app = await createHonoServer(_mastra, { tools: getToolExports(tools) });\n return app.fetch(request, env, context);\n }\n }\n`;\n }\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n await this.writeFiles(outputDirectory);\n }\n\n async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap = false }: { enableSourcemap?: boolean } = {},\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n enableSourcemap,\n enableEsmShim: false,\n });\n\n const hasPostgresStore = (await this.deps.checkDependencies(['@mastra/pg'])) === `ok`;\n\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins = [\n virtual({\n '#polyfills': `\nprocess.versions = process.versions || {};\nprocess.versions.node = '${process.versions.node}';\n `,\n }),\n ...inputOptions.plugins,\n mastraInstanceWrapper(mastraEntryFile),\n ];\n\n if (hasPostgresStore) {\n inputOptions.plugins.push(postgresStoreInstanceChecker());\n }\n }\n\n return inputOptions;\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot, enableEsmShim: false }, toolsPaths);\n }\n\n async deploy(): Promise<void> {\n this.logger?.info('Deploying to Cloudflare failed. Please use the Cloudflare dashboard to deploy.');\n }\n\n async tagWorker(): Promise<void> {\n throw new Error('tagWorker method is no longer supported. Use the Cloudflare dashboard or API directly.');\n }\n\n async lint(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n await super.lint(entryFile, outputDirectory, toolsPaths);\n\n const hasLibsql = (await this.deps.checkDependencies(['@mastra/libsql'])) === `ok`;\n\n if (hasLibsql) {\n this.logger.error(\n 'Cloudflare Deployer does not support @libsql/client (which may have been installed by @mastra/libsql) as a dependency. Please use Cloudflare D1 instead: @mastra/cloudflare-d1.',\n );\n process.exit(1);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/babel/mastra-instance-wrapper.ts","../src/plugins/mastra-instance-wrapper.ts","../src/babel/postgres-store-instance-checker.ts","../src/plugins/postgres-store-instance-checker.ts","../src/index.ts"],"names":["babel","mastraInstanceWrapper","transformSync","babel2","postgresStoreInstanceChecker","Deployer","writeFile","join","virtual"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBO,SAAS,qBAAA,GAAmC;AACjD,EAAA,MAAM,UAAA,GAAa,QAAA;AACnB,EAAA,MAAM,SAAA,GAAY,QAAA;AAClB,EAAA,MAAM,CAAA,GAAUA,gBAAA,CAAA,KAAA;AAEhB,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,aAAA;AAAA,IACN,OAAA,EAAS;AAAA,MACP,uBAAuB,IAAA,EAAM;AAC3B,QAAA,IAAI,CAAA,CAAE,qBAAA,CAAsB,IAAA,CAAK,IAAA,EAAM,WAAW,CAAA,EAAG;AACnD,UAAA,KAAA,MAAW,WAAA,IAAe,IAAA,CAAK,IAAA,CAAK,WAAA,CAAY,YAAA,EAAc;AAC5D,YAAA,IACE,CAAA,CAAE,aAAa,WAAA,EAAa,EAAA,EAAI,EAAE,IAAA,EAAM,UAAA,EAAY,CAAA,IACpD,CAAA,CAAE,eAAA,CAAgB,aAAa,IAAI,CAAA,IACnC,CAAA,CAAE,YA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AEA,MAAM,IAAA,CAAK,SAAA,EAAmB,eAAA,EAAyB,UAAA,EAAkD;AACvG,IAAA,MAAM,KAAA,CAAM,IAAA,CAAK,SAAA,EAAW,eAAA,EAAiB,UAAU,CAAA;AAEvD,IAAA,MAAM,SAAA,GAAa,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAkB,CAAC,gBAAgB,CAAC,CAAA,KAAO,CAAA,EAAA,CAAA;AAE9E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV;AAAA,OACF;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["import type { PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\n\n/**\n * Babel plugin that transforms Mastra exports for Cloudflare Workers compatibility.\n *\n * This plugin:\n * 1. Identifies named exports of the 'mastra' variable\n * 2. Checks if the export is a new instance of the 'Mastra' class\n * 3. Wraps the Mastra instantiation in an arrow function to ensure proper initialization\n * in the Cloudflare Workers environment\n *\n * The transformation ensures the Mastra instance is properly scoped and initialized\n * for each request in the Cloudflare Workers environment.\n *\n * @returns {PluginObj} A Babel plugin object with a visitor that performs the transformation\n *\n * @example\n * // Before transformation:\n * export const mastra = new Mastra();\n *\n * // After transformation:\n * export const mastra = () => new Mastra();\n */\nexport function mastraInstanceWrapper(): PluginObj {\n const exportName = 'mastra';\n const className = 'Mastra';\n const t = babel.types;\n\n return {\n name: 'wrap-mastra',\n visitor: {\n ExportNamedDeclaration(path) {\n if (t.isVariableDeclaration(path.node?.declaration)) {\n for (const declaration of path.node.declaration.declarations) {\n if (\n t.isIdentifier(declaration?.id, { name: exportName }) &&\n t.isNewExpression(declaration?.init) &&\n t.isIdentifier(declaration.init.callee, { name: className })\n ) {\n declaration.init = t.arrowFunctionExpression([], declaration.init);\n // there should be only one \"mastra\" export, so we can exit the loop\n break;\n }\n }\n }\n },\n },\n } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { mastraInstanceWrapper as mastraInstanceWrapperBabel } from '../babel/mastra-instance-wrapper';\n\nexport function mastraInstanceWrapper(mastraEntryFile: string): Plugin {\n return {\n name: 'mastra-wrapper',\n transform(code, id) {\n if (id !== mastraEntryFile) {\n return null;\n }\n\n const result = transformSync(code, {\n filename: id,\n babelrc: false,\n configFile: false,\n plugins: [mastraInstanceWrapperBabel],\n });\n\n if (!result?.code) {\n throw new Error('mastra-wrapper plugin did not return code, there is likely a bug in the plugin.');\n }\n\n return {\n code: result.code,\n map: result?.map,\n };\n },\n };\n}\n","import type { NodePath, PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\nimport type { NewExpression } from '@babel/types';\n\n/**\n * Babel plugin that enforces singleton PostgresStore instances in Cloudflare Workers.\n *\n * This plugin:\n * 1. Scans for all `new PostgresStore()` instantiations\n * 2. Records their file locations\n * 3. Throws an error if multiple instances are found\n *\n * Cloudflare Workers should only create one PostgresStore instance to avoid connection\n * pool exhaustion and ensure proper resource management.\n *\n * @returns {PluginObj} A Babel plugin object that validates PostgresStore usage\n *\n * @example\n * // Throws error if multiple instances found:\n * const store1 = new PostgresStore();\n * const store2 = new PostgresStore(); // Error thrown here\n */\nexport function postgresStoreInstanceChecker(): PluginObj {\n const t = babel.types;\n const instances: { path: NodePath<NewExpression>; location: string }[] = [];\n\n return {\n name: 'postgresstore-instance-checker',\n visitor: {\n NewExpression(path, state) {\n if (t.isIdentifier(path.node.callee) && path.node.callee.name === 'PostgresStore') {\n const filename = state.file?.opts?.filename || 'unknown file';\n const location = path.node.loc\n ? `${filename}: line ${path.node.loc.start.line}, column ${path.node.loc.start.column}`\n : 'unknown location';\n\n instances.push({\n path,\n location,\n });\n }\n },\n },\n post() {\n if (instances.length > 1) {\n const errorMessage = [\n `Found ${instances.length} PostgresStore instantiations:`,\n ...instances.map((instance, i) => ` ${i + 1}. At ${instance.location}`),\n 'Only one PostgresStore instance should be created per Cloudflare Worker.',\n ].join('\\n');\n\n const lastInstance = instances[instances.length - 1];\n throw lastInstance?.path.buildCodeFrameError(errorMessage);\n }\n },\n } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { postgresStoreInstanceChecker as postgresStoreInstanceCheckerBabel } from '../babel/postgres-store-instance-checker';\n\nexport function postgresStoreInstanceChecker(): Plugin {\n return {\n name: 'postgres-store-instance-checker',\n transform(code, id) {\n const result = transformSync(code, {\n filename: id,\n babelrc: false,\n configFile: false,\n plugins: [postgresStoreInstanceCheckerBabel],\n });\n\n // If Babel didn't transform anything or returned no code, pass through original source.\n if (!result || typeof result.code !== 'string') {\n return null;\n }\n\n return {\n code: result.code,\n map: result.map ?? null,\n };\n },\n };\n}\n","import { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport type { BundlerOptions } from '@mastra/deployer/bundler';\nimport virtual from '@rollup/plugin-virtual';\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\ninterface CFRoute {\n pattern: string;\n zone_name: string;\n custom_domain?: boolean;\n}\n\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n routes?: CFRoute[] = [];\n workerNamespace?: string;\n env?: Record<string, any>;\n projectName?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n\n constructor({\n env,\n projectName = 'mastra',\n routes,\n workerNamespace,\n d1Databases,\n kvNamespaces,\n }: {\n env?: Record<string, any>;\n projectName?: string;\n routes?: CFRoute[];\n workerNamespace?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n }) {\n super({ name: 'CLOUDFLARE' });\n\n this.projectName = projectName;\n this.routes = routes;\n this.workerNamespace = workerNamespace;\n\n if (env) {\n this.env = env;\n }\n\n if (d1Databases) this.d1Databases = d1Databases;\n if (kvNamespaces) this.kvNamespaces = kvNamespaces;\n }\n\n async writeFiles(outputDirectory: string): Promise<void> {\n const env = await this.loadEnvVars();\n const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);\n\n const cfWorkerName = this.projectName;\n\n const wranglerConfig: Record<string, any> = {\n name: cfWorkerName,\n main: './index.mjs',\n compatibility_date: '2025-04-01',\n compatibility_flags: ['nodejs_compat', 'nodejs_compat_populate_process_env'],\n observability: {\n logs: {\n enabled: true,\n },\n },\n vars: envsAsObject,\n };\n\n if (!this.workerNamespace && this.routes) {\n wranglerConfig.routes = this.routes;\n }\n\n if (this.d1Databases?.length) {\n wranglerConfig.d1_databases = this.d1Databases;\n }\n if (this.kvNamespaces?.length) {\n wranglerConfig.kv_namespaces = this.kvNamespaces;\n }\n await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig));\n }\n\n private getEntry(): string {\n return `\n import '#polyfills';\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\n export default {\n fetch: async (request, env, context) => {\n const { mastra } = await import('#mastra');\n const { tools } = await import('#tools');\n const {createHonoServer, getToolExports} = await import('#server');\n const _mastra = mastra();\n\n if (_mastra.getStorage()) {\n _mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n\n const app = await createHonoServer(_mastra, { tools: getToolExports(tools) });\n return app.fetch(request, env, context);\n }\n }\n`;\n }\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n await this.writeFiles(outputDirectory);\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n bundlerOptions: BundlerOptions,\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n ...bundlerOptions,\n enableEsmShim: false,\n });\n\n const hasPostgresStore = (await this.deps.checkDependencies(['@mastra/pg'])) === `ok`;\n\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins = [\n virtual({\n '#polyfills': `\nprocess.versions = process.versions || {};\nprocess.versions.node = '${process.versions.node}';\n `,\n }),\n ...inputOptions.plugins,\n mastraInstanceWrapper(mastraEntryFile),\n ];\n\n if (hasPostgresStore) {\n inputOptions.plugins.push(postgresStoreInstanceChecker());\n }\n }\n\n return inputOptions;\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot, enableEsmShim: false }, toolsPaths);\n }\n\n async deploy(): Promise<void> {\n this.logger?.info('Deploying to Cloudflare failed. Please use the Cloudflare dashboard to deploy.');\n }\n\n async tagWorker(): Promise<void> {\n throw new Error('tagWorker method is no longer supported. Use the Cloudflare dashboard or API directly.');\n }\n\n async lint(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n await super.lint(entryFile, outputDirectory, toolsPaths);\n\n const hasLibsql = (await this.deps.checkDependencies(['@mastra/libsql'])) === `ok`;\n\n if (hasLibsql) {\n this.logger.error(\n 'Cloudflare Deployer does not support @libsql/client (which may have been installed by @mastra/libsql) as a dependency. Please use Cloudflare D1 instead: @mastra/cloudflare-d1.',\n );\n process.exit(1);\n }\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Deployer } from '@mastra/deployer';
|
|
2
2
|
import type { analyzeBundle } from '@mastra/deployer/analyze';
|
|
3
|
+
import type { BundlerOptions } from '@mastra/deployer/bundler';
|
|
3
4
|
interface CFRoute {
|
|
4
5
|
pattern: string;
|
|
5
6
|
zone_name: string;
|
|
@@ -33,9 +34,7 @@ export declare class CloudflareDeployer extends Deployer {
|
|
|
33
34
|
writeFiles(outputDirectory: string): Promise<void>;
|
|
34
35
|
private getEntry;
|
|
35
36
|
prepare(outputDirectory: string): Promise<void>;
|
|
36
|
-
getBundlerOptions(serverFile: string, mastraEntryFile: string, analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>, toolsPaths: (string | string[])[],
|
|
37
|
-
enableSourcemap?: boolean;
|
|
38
|
-
}): Promise<import("rollup").InputOptions>;
|
|
37
|
+
protected getBundlerOptions(serverFile: string, mastraEntryFile: string, analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>, toolsPaths: (string | string[])[], bundlerOptions: BundlerOptions): Promise<import("rollup").InputOptions>;
|
|
39
38
|
bundle(entryFile: string, outputDirectory: string, { toolsPaths, projectRoot }: {
|
|
40
39
|
toolsPaths: (string | string[])[];
|
|
41
40
|
projectRoot: string;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAK/D,UAAU,OAAO;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,UAAU,iBAAiB;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MA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M,CACV,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,EACvB,EAAE,UAAU,EAAE,WAAW,EAAE,EAAE;QAAE,UAAU,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,GACtF,OAAO,CAAC,IAAI,CAAC;IAIV,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAIvB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAI1B,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAYzG"}
|
package/dist/index.js
CHANGED
|
@@ -183,9 +183,9 @@ var CloudflareDeployer = class extends Deployer {
|
|
|
183
183
|
await super.prepare(outputDirectory);
|
|
184
184
|
await this.writeFiles(outputDirectory);
|
|
185
185
|
}
|
|
186
|
-
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths,
|
|
186
|
+
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, bundlerOptions) {
|
|
187
187
|
const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {
|
|
188
|
-
|
|
188
|
+
...bundlerOptions,
|
|
189
189
|
enableEsmShim: false
|
|
190
190
|
});
|
|
191
191
|
const hasPostgresStore = await this.deps.checkDependencies(["@mastra/pg"]) === `ok`;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/babel/mastra-instance-wrapper.ts","../src/plugins/mastra-instance-wrapper.ts","../src/babel/postgres-store-instance-checker.ts","../src/plugins/postgres-store-instance-checker.ts","../src/index.ts"],"names":["mastraInstanceWrapper","babel2","postgresStoreInstanceChecker","transformSync"],"mappings":";;;;;;;;AAwBO,SAAS,qBAAA,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IAAI,gBAAA,EAAkB;AACpB,QAAA,YAAA,CAAa,OAAA,CAAQ,IAAA,CAAKE,6BAAAA,EAA8B,CAAA;AAAA,MAC1D;AAAA,IACF;AAEA,IAAA,OAAO,YAAA;AAAA,EACT;AAAA,EAEA,MAAM,MAAA,CACJ,SAAA,EACA,iBACA,EAAE,UAAA,EAAY,aAAY,EACX;AACf,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,QAAA,EAAS,EAAG,SAAA,EAAW,EAAE,eAAA,EAAiB,WAAA,EAAa,aAAA,EAAe,KAAA,EAAM,EAAG,UAAU,CAAA;AAAA,EACpH;AAAA,EAEA,MAAM,MAAA,GAAwB;AAC5B,IAAA,IAAA,CAAK,MAAA,EAAQ,KAAK,gFAAgF,CAAA;AAAA,EACpG;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,IAAI,MAAM,wFAAwF,CAAA;AAAA,EAC1G;AAAA,EAEA,MAAM,IAAA,CAAK,SAAA,EAAmB,eAAA,EAAyB,UAAA,EAAkD;AACvG,IAAA,MAAM,KAAA,CAAM,IAAA,CAAK,SAAA,EAAW,eAAA,EAAiB,UAAU,CAAA;AAEvD,IAAA,MAAM,SAAA,GAAa,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAkB,CAAC,gBAAgB,CAAC,CAAA,KAAO,CAAA,EAAA,CAAA;AAE9E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV;AAAA,OACF;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\n\n/**\n * Babel plugin that transforms Mastra exports for Cloudflare Workers compatibility.\n *\n * This plugin:\n * 1. Identifies named exports of the 'mastra' variable\n * 2. Checks if the export is a new instance of the 'Mastra' class\n * 3. Wraps the Mastra instantiation in an arrow function to ensure proper initialization\n * in the Cloudflare Workers environment\n *\n * The transformation ensures the Mastra instance is properly scoped and initialized\n * for each request in the Cloudflare Workers environment.\n *\n * @returns {PluginObj} A Babel plugin object with a visitor that performs the transformation\n *\n * @example\n * // Before transformation:\n * export const mastra = new Mastra();\n *\n * // After transformation:\n * export const mastra = () => new Mastra();\n */\nexport function mastraInstanceWrapper(): PluginObj {\n const exportName = 'mastra';\n const className = 'Mastra';\n const t = babel.types;\n\n return {\n name: 'wrap-mastra',\n visitor: {\n ExportNamedDeclaration(path) {\n if (t.isVariableDeclaration(path.node?.declaration)) {\n for (const declaration of path.node.declaration.declarations) {\n if (\n t.isIdentifier(declaration?.id, { name: exportName }) &&\n t.isNewExpression(declaration?.init) &&\n t.isIdentifier(declaration.init.callee, { name: className })\n ) {\n declaration.init = t.arrowFunctionExpression([], declaration.init);\n // there should be only one \"mastra\" export, so we can exit the loop\n break;\n }\n }\n }\n },\n },\n } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { mastraInstanceWrapper as mastraInstanceWrapperBabel } from '../babel/mastra-instance-wrapper';\n\nexport function mastraInstanceWrapper(mastraEntryFile: string): Plugin {\n return {\n name: 'mastra-wrapper',\n transform(code, id) {\n if (id !== mastraEntryFile) {\n return null;\n }\n\n const result = transformSync(code, {\n filename: id,\n babelrc: false,\n configFile: false,\n plugins: [mastraInstanceWrapperBabel],\n });\n\n if (!result?.code) {\n throw new Error('mastra-wrapper plugin did not return code, there is likely a bug in the plugin.');\n }\n\n return {\n code: result.code,\n map: result?.map,\n };\n },\n };\n}\n","import type { NodePath, PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\nimport type { NewExpression } from '@babel/types';\n\n/**\n * Babel plugin that enforces singleton PostgresStore instances in Cloudflare Workers.\n *\n * This plugin:\n * 1. Scans for all `new PostgresStore()` instantiations\n * 2. Records their file locations\n * 3. Throws an error if multiple instances are found\n *\n * Cloudflare Workers should only create one PostgresStore instance to avoid connection\n * pool exhaustion and ensure proper resource management.\n *\n * @returns {PluginObj} A Babel plugin object that validates PostgresStore usage\n *\n * @example\n * // Throws error if multiple instances found:\n * const store1 = new PostgresStore();\n * const store2 = new PostgresStore(); // Error thrown here\n */\nexport function postgresStoreInstanceChecker(): PluginObj {\n const t = babel.types;\n const instances: { path: NodePath<NewExpression>; location: string }[] = [];\n\n return {\n name: 'postgresstore-instance-checker',\n visitor: {\n NewExpression(path, state) {\n if (t.isIdentifier(path.node.callee) && path.node.callee.name === 'PostgresStore') {\n const filename = state.file?.opts?.filename || 'unknown file';\n const location = path.node.loc\n ? `${filename}: line ${path.node.loc.start.line}, column ${path.node.loc.start.column}`\n : 'unknown location';\n\n instances.push({\n path,\n location,\n });\n }\n },\n },\n post() {\n if (instances.length > 1) {\n const errorMessage = [\n `Found ${instances.length} PostgresStore instantiations:`,\n ...instances.map((instance, i) => ` ${i + 1}. At ${instance.location}`),\n 'Only one PostgresStore instance should be created per Cloudflare Worker.',\n ].join('\\n');\n\n const lastInstance = instances[instances.length - 1];\n throw lastInstance?.path.buildCodeFrameError(errorMessage);\n }\n },\n } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { postgresStoreInstanceChecker as postgresStoreInstanceCheckerBabel } from '../babel/postgres-store-instance-checker';\n\nexport function postgresStoreInstanceChecker(): Plugin {\n return {\n name: 'postgres-store-instance-checker',\n transform(code, id) {\n const result = transformSync(code, {\n filename: id,\n babelrc: false,\n configFile: false,\n plugins: [postgresStoreInstanceCheckerBabel],\n });\n\n // If Babel didn't transform anything or returned no code, pass through original source.\n if (!result || typeof result.code !== 'string') {\n return null;\n }\n\n return {\n code: result.code,\n map: result.map ?? null,\n };\n },\n };\n}\n","import { writeFile } from 'fs/promises';\nimport { join } from 'path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport virtual from '@rollup/plugin-virtual';\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\ninterface CFRoute {\n pattern: string;\n zone_name: string;\n custom_domain?: boolean;\n}\n\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n routes?: CFRoute[] = [];\n workerNamespace?: string;\n env?: Record<string, any>;\n projectName?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n\n constructor({\n env,\n projectName = 'mastra',\n routes,\n workerNamespace,\n d1Databases,\n kvNamespaces,\n }: {\n env?: Record<string, any>;\n projectName?: string;\n routes?: CFRoute[];\n workerNamespace?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n }) {\n super({ name: 'CLOUDFLARE' });\n\n this.projectName = projectName;\n this.routes = routes;\n this.workerNamespace = workerNamespace;\n\n if (env) {\n this.env = env;\n }\n\n if (d1Databases) this.d1Databases = d1Databases;\n if (kvNamespaces) this.kvNamespaces = kvNamespaces;\n }\n\n async writeFiles(outputDirectory: string): Promise<void> {\n const env = await this.loadEnvVars();\n const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);\n\n const cfWorkerName = this.projectName;\n\n const wranglerConfig: Record<string, any> = {\n name: cfWorkerName,\n main: './index.mjs',\n compatibility_date: '2025-04-01',\n compatibility_flags: ['nodejs_compat', 'nodejs_compat_populate_process_env'],\n observability: {\n logs: {\n enabled: true,\n },\n },\n vars: envsAsObject,\n };\n\n if (!this.workerNamespace && this.routes) {\n wranglerConfig.routes = this.routes;\n }\n\n if (this.d1Databases?.length) {\n wranglerConfig.d1_databases = this.d1Databases;\n }\n if (this.kvNamespaces?.length) {\n wranglerConfig.kv_namespaces = this.kvNamespaces;\n }\n await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig));\n }\n\n private getEntry(): string {\n return `\n import '#polyfills';\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\n export default {\n fetch: async (request, env, context) => {\n const { mastra } = await import('#mastra');\n const { tools } = await import('#tools');\n const {createHonoServer, getToolExports} = await import('#server');\n const _mastra = mastra();\n\n if (_mastra.getStorage()) {\n _mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n\n const app = await createHonoServer(_mastra, { tools: getToolExports(tools) });\n return app.fetch(request, env, context);\n }\n }\n`;\n }\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n await this.writeFiles(outputDirectory);\n }\n\n async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap = false }: { enableSourcemap?: boolean } = {},\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n enableSourcemap,\n enableEsmShim: false,\n });\n\n const hasPostgresStore = (await this.deps.checkDependencies(['@mastra/pg'])) === `ok`;\n\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins = [\n virtual({\n '#polyfills': `\nprocess.versions = process.versions || {};\nprocess.versions.node = '${process.versions.node}';\n `,\n }),\n ...inputOptions.plugins,\n mastraInstanceWrapper(mastraEntryFile),\n ];\n\n if (hasPostgresStore) {\n inputOptions.plugins.push(postgresStoreInstanceChecker());\n }\n }\n\n return inputOptions;\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot, enableEsmShim: false }, toolsPaths);\n }\n\n async deploy(): Promise<void> {\n this.logger?.info('Deploying to Cloudflare failed. Please use the Cloudflare dashboard to deploy.');\n }\n\n async tagWorker(): Promise<void> {\n throw new Error('tagWorker method is no longer supported. Use the Cloudflare dashboard or API directly.');\n }\n\n async lint(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n await super.lint(entryFile, outputDirectory, toolsPaths);\n\n const hasLibsql = (await this.deps.checkDependencies(['@mastra/libsql'])) === `ok`;\n\n if (hasLibsql) {\n this.logger.error(\n 'Cloudflare Deployer does not support @libsql/client (which may have been installed by @mastra/libsql) as a dependency. Please use Cloudflare D1 instead: @mastra/cloudflare-d1.',\n );\n process.exit(1);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/babel/mastra-instance-wrapper.ts","../src/plugins/mastra-instance-wrapper.ts","../src/babel/postgres-store-instance-checker.ts","../src/plugins/postgres-store-instance-checker.ts","../src/index.ts"],"names":["mastraInstanceWrapper","babel2","postgresStoreInstanceChecker","transformSync"],"mappings":";;;;;;;;AAwBO,SAAS,qBAAA,GAAmC;AACjD,EAAA,MAAM,UAAA,GAAa,QAAA;AACnB,EAAA,MAAM,SAAA,GAAY,QAAA;AAClB,EAAA,MAAM,CAAA,GAAU,KAAA,CAAA,KAAA;AAEhB,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,aAAA;AAAA,IACN,OAAA,EAAS;AAAA,MACP,uBAAuB,IAAA,EAAM;AAC3B,QAAA,IAAI,CAAA,CAAE,qBAAA,CAAsB,IAAA,CAAK,IAAA,EAAM,WAAW,CAAA,EAAG;AACnD,UAAA,KAAA,MAAW,WAAA,IAAe,IAAA,CAAK,IAAA,CAAK,WAAA,CAAY,YAAA,EAAc;AAC5D,YAAA,IACE,CAAA,CAAE,aAAa,WAAA,EAAa,EAAA,EAAI,EAAE,IAAA,EAAM,UAAA,EAAY,CAAA,IACpD,CAAA,CAAE,eAAA,CAAgB,aAAa,IAAI,CAAA,IACnC,CAAA,CAAE,YAAA,CAAa,WAAA,CAAY,IAAA,CAAK,QAAQ,EAAE,IAAA,EAAM,SAAA,EAAW,CAAA,EAC3D;AACA,cAAA,WAAA,CAAY,OAAO,CAA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,UAAU,CAAA;AAEvD,IAAA,MAAM,SAAA,GAAa,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAkB,CAAC,gBAAgB,CAAC,CAAA,KAAO,CAAA,EAAA,CAAA;AAE9E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV;AAAA,OACF;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\n\n/**\n * Babel plugin that transforms Mastra exports for Cloudflare Workers compatibility.\n *\n * This plugin:\n * 1. Identifies named exports of the 'mastra' variable\n * 2. Checks if the export is a new instance of the 'Mastra' class\n * 3. Wraps the Mastra instantiation in an arrow function to ensure proper initialization\n * in the Cloudflare Workers environment\n *\n * The transformation ensures the Mastra instance is properly scoped and initialized\n * for each request in the Cloudflare Workers environment.\n *\n * @returns {PluginObj} A Babel plugin object with a visitor that performs the transformation\n *\n * @example\n * // Before transformation:\n * export const mastra = new Mastra();\n *\n * // After transformation:\n * export const mastra = () => new Mastra();\n */\nexport function mastraInstanceWrapper(): PluginObj {\n const exportName = 'mastra';\n const className = 'Mastra';\n const t = babel.types;\n\n return {\n name: 'wrap-mastra',\n visitor: {\n ExportNamedDeclaration(path) {\n if (t.isVariableDeclaration(path.node?.declaration)) {\n for (const declaration of path.node.declaration.declarations) {\n if (\n t.isIdentifier(declaration?.id, { name: exportName }) &&\n t.isNewExpression(declaration?.init) &&\n t.isIdentifier(declaration.init.callee, { name: className })\n ) {\n declaration.init = t.arrowFunctionExpression([], declaration.init);\n // there should be only one \"mastra\" export, so we can exit the loop\n break;\n }\n }\n }\n },\n },\n } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { mastraInstanceWrapper as mastraInstanceWrapperBabel } from '../babel/mastra-instance-wrapper';\n\nexport function mastraInstanceWrapper(mastraEntryFile: string): Plugin {\n return {\n name: 'mastra-wrapper',\n transform(code, id) {\n if (id !== mastraEntryFile) {\n return null;\n }\n\n const result = transformSync(code, {\n filename: id,\n babelrc: false,\n configFile: false,\n plugins: [mastraInstanceWrapperBabel],\n });\n\n if (!result?.code) {\n throw new Error('mastra-wrapper plugin did not return code, there is likely a bug in the plugin.');\n }\n\n return {\n code: result.code,\n map: result?.map,\n };\n },\n };\n}\n","import type { NodePath, PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\nimport type { NewExpression } from '@babel/types';\n\n/**\n * Babel plugin that enforces singleton PostgresStore instances in Cloudflare Workers.\n *\n * This plugin:\n * 1. Scans for all `new PostgresStore()` instantiations\n * 2. Records their file locations\n * 3. Throws an error if multiple instances are found\n *\n * Cloudflare Workers should only create one PostgresStore instance to avoid connection\n * pool exhaustion and ensure proper resource management.\n *\n * @returns {PluginObj} A Babel plugin object that validates PostgresStore usage\n *\n * @example\n * // Throws error if multiple instances found:\n * const store1 = new PostgresStore();\n * const store2 = new PostgresStore(); // Error thrown here\n */\nexport function postgresStoreInstanceChecker(): PluginObj {\n const t = babel.types;\n const instances: { path: NodePath<NewExpression>; location: string }[] = [];\n\n return {\n name: 'postgresstore-instance-checker',\n visitor: {\n NewExpression(path, state) {\n if (t.isIdentifier(path.node.callee) && path.node.callee.name === 'PostgresStore') {\n const filename = state.file?.opts?.filename || 'unknown file';\n const location = path.node.loc\n ? `${filename}: line ${path.node.loc.start.line}, column ${path.node.loc.start.column}`\n : 'unknown location';\n\n instances.push({\n path,\n location,\n });\n }\n },\n },\n post() {\n if (instances.length > 1) {\n const errorMessage = [\n `Found ${instances.length} PostgresStore instantiations:`,\n ...instances.map((instance, i) => ` ${i + 1}. At ${instance.location}`),\n 'Only one PostgresStore instance should be created per Cloudflare Worker.',\n ].join('\\n');\n\n const lastInstance = instances[instances.length - 1];\n throw lastInstance?.path.buildCodeFrameError(errorMessage);\n }\n },\n } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { postgresStoreInstanceChecker as postgresStoreInstanceCheckerBabel } from '../babel/postgres-store-instance-checker';\n\nexport function postgresStoreInstanceChecker(): Plugin {\n return {\n name: 'postgres-store-instance-checker',\n transform(code, id) {\n const result = transformSync(code, {\n filename: id,\n babelrc: false,\n configFile: false,\n plugins: [postgresStoreInstanceCheckerBabel],\n });\n\n // If Babel didn't transform anything or returned no code, pass through original source.\n if (!result || typeof result.code !== 'string') {\n return null;\n }\n\n return {\n code: result.code,\n map: result.map ?? null,\n };\n },\n };\n}\n","import { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport type { BundlerOptions } from '@mastra/deployer/bundler';\nimport virtual from '@rollup/plugin-virtual';\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\ninterface CFRoute {\n pattern: string;\n zone_name: string;\n custom_domain?: boolean;\n}\n\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n routes?: CFRoute[] = [];\n workerNamespace?: string;\n env?: Record<string, any>;\n projectName?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n\n constructor({\n env,\n projectName = 'mastra',\n routes,\n workerNamespace,\n d1Databases,\n kvNamespaces,\n }: {\n env?: Record<string, any>;\n projectName?: string;\n routes?: CFRoute[];\n workerNamespace?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n }) {\n super({ name: 'CLOUDFLARE' });\n\n this.projectName = projectName;\n this.routes = routes;\n this.workerNamespace = workerNamespace;\n\n if (env) {\n this.env = env;\n }\n\n if (d1Databases) this.d1Databases = d1Databases;\n if (kvNamespaces) this.kvNamespaces = kvNamespaces;\n }\n\n async writeFiles(outputDirectory: string): Promise<void> {\n const env = await this.loadEnvVars();\n const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);\n\n const cfWorkerName = this.projectName;\n\n const wranglerConfig: Record<string, any> = {\n name: cfWorkerName,\n main: './index.mjs',\n compatibility_date: '2025-04-01',\n compatibility_flags: ['nodejs_compat', 'nodejs_compat_populate_process_env'],\n observability: {\n logs: {\n enabled: true,\n },\n },\n vars: envsAsObject,\n };\n\n if (!this.workerNamespace && this.routes) {\n wranglerConfig.routes = this.routes;\n }\n\n if (this.d1Databases?.length) {\n wranglerConfig.d1_databases = this.d1Databases;\n }\n if (this.kvNamespaces?.length) {\n wranglerConfig.kv_namespaces = this.kvNamespaces;\n }\n await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig));\n }\n\n private getEntry(): string {\n return `\n import '#polyfills';\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\n export default {\n fetch: async (request, env, context) => {\n const { mastra } = await import('#mastra');\n const { tools } = await import('#tools');\n const {createHonoServer, getToolExports} = await import('#server');\n const _mastra = mastra();\n\n if (_mastra.getStorage()) {\n _mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n\n const app = await createHonoServer(_mastra, { tools: getToolExports(tools) });\n return app.fetch(request, env, context);\n }\n }\n`;\n }\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n await this.writeFiles(outputDirectory);\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n bundlerOptions: BundlerOptions,\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n ...bundlerOptions,\n enableEsmShim: false,\n });\n\n const hasPostgresStore = (await this.deps.checkDependencies(['@mastra/pg'])) === `ok`;\n\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins = [\n virtual({\n '#polyfills': `\nprocess.versions = process.versions || {};\nprocess.versions.node = '${process.versions.node}';\n `,\n }),\n ...inputOptions.plugins,\n mastraInstanceWrapper(mastraEntryFile),\n ];\n\n if (hasPostgresStore) {\n inputOptions.plugins.push(postgresStoreInstanceChecker());\n }\n }\n\n return inputOptions;\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot, enableEsmShim: false }, toolsPaths);\n }\n\n async deploy(): Promise<void> {\n this.logger?.info('Deploying to Cloudflare failed. Please use the Cloudflare dashboard to deploy.');\n }\n\n async tagWorker(): Promise<void> {\n throw new Error('tagWorker method is no longer supported. Use the Cloudflare dashboard or API directly.');\n }\n\n async lint(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n await super.lint(entryFile, outputDirectory, toolsPaths);\n\n const hasLibsql = (await this.deps.checkDependencies(['@mastra/libsql'])) === `ok`;\n\n if (hasLibsql) {\n this.logger.error(\n 'Cloudflare Deployer does not support @libsql/client (which may have been installed by @mastra/libsql) as a dependency. Please use Cloudflare D1 instead: @mastra/cloudflare-d1.',\n );\n process.exit(1);\n }\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export const mastra: Mastra<{
|
|
2
2
|
weatherAgent: any;
|
|
3
|
-
}, Record<string, import("@mastra/core/workflows").Workflow<any, any, any, any, any, any, any>>, Record<string, import("@mastra/core/vector").MastraVector<
|
|
3
|
+
}, Record<string, import("@mastra/core/workflows").Workflow<any, any, any, any, any, any, any>>, Record<string, import("@mastra/core/vector").MastraVector<any>>, Record<string, import("@mastra/core/tts").MastraTTS>, import("@mastra/core/logger").ConsoleLogger, Record<string, import("@mastra/core/mcp").MCPServerBase<any>>, Record<string, import("@mastra/core/evals").MastraScorer<any, any, any, any>>, Record<string, import("@mastra/core/tools").ToolAction<any, any, any, any, any, any>>, Record<string, import("@mastra/core/processors").Processor<any, unknown>>, Record<string, import("@mastra/core/memory").MastraMemory>>;
|
|
4
4
|
import { Mastra } from '@mastra/core/mastra';
|
|
5
5
|
//# sourceMappingURL=basic.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"basic.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/basic.js"],"names":[],"mappings":"AAOA;;
|
|
1
|
+
{"version":3,"file":"basic.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/basic.js"],"names":[],"mappings":"AAOA;;inBAuBG;uBA7BoB,qBAAqB"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export const mastra: Mastra<Record<string, import("@mastra/core/agent").Agent<any, import("@mastra/core/agent").ToolsInput>>, Record<string, import("@mastra/core/workflows").Workflow<any, any, any, any, any, any, any>>, Record<string, import("@mastra/core/vector").MastraVector<
|
|
1
|
+
export const mastra: Mastra<Record<string, import("@mastra/core/agent").Agent<any, import("@mastra/core/agent").ToolsInput>>, Record<string, import("@mastra/core/workflows").Workflow<any, any, any, any, any, any, any>>, Record<string, import("@mastra/core/vector").MastraVector<any>>, Record<string, import("@mastra/core/tts").MastraTTS>, import("@mastra/core/logger").IMastraLogger, Record<string, import("@mastra/core/mcp").MCPServerBase<any>>, Record<string, import("@mastra/core/evals").MastraScorer<any, any, any, any>>, Record<string, import("@mastra/core/tools").ToolAction<any, any, any, any, any, any>>, Record<string, import("@mastra/core/processors").Processor<any, unknown>>, Record<string, import("@mastra/core/memory").MastraMemory>>;
|
|
2
2
|
import { Mastra } from '@mastra/core/mastra';
|
|
3
3
|
//# sourceMappingURL=empty-mastra.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"empty-mastra.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/empty-mastra.js"],"names":[],"mappings":"AACA,
|
|
1
|
+
{"version":3,"file":"empty-mastra.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/empty-mastra.js"],"names":[],"mappings":"AACA,4uBAAmC;uBADZ,qBAAqB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export const storage: any;
|
|
2
2
|
export const mastra: Mastra<{
|
|
3
3
|
weatherAgent: any;
|
|
4
|
-
}, Record<string, import("@mastra/core/workflows").Workflow<any, any, any, any, any, any, any>>, Record<string, import("@mastra/core/vector").MastraVector<
|
|
4
|
+
}, Record<string, import("@mastra/core/workflows").Workflow<any, any, any, any, any, any, any>>, Record<string, import("@mastra/core/vector").MastraVector<any>>, Record<string, import("@mastra/core/tts").MastraTTS>, import("@mastra/core/logger").ConsoleLogger, Record<string, import("@mastra/core/mcp").MCPServerBase<any>>, Record<string, import("@mastra/core/evals").MastraScorer<any, any, any, any>>, Record<string, import("@mastra/core/tools").ToolAction<any, any, any, any, any, any>>, Record<string, import("@mastra/core/processors").Processor<any, unknown>>, Record<string, import("@mastra/core/memory").MastraMemory>>;
|
|
5
5
|
import { Mastra } from '@mastra/core/mastra';
|
|
6
6
|
//# sourceMappingURL=multiple-postgres-stores.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multiple-postgres-stores.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/multiple-postgres-stores.js"],"names":[],"mappings":"AAOA,0BAEG;AAEH;;
|
|
1
|
+
{"version":3,"file":"multiple-postgres-stores.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/multiple-postgres-stores.js"],"names":[],"mappings":"AAOA,0BAEG;AAEH;;inBAuBG;uBAjCoB,qBAAqB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/deployer-cloudflare",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -41,21 +41,22 @@
|
|
|
41
41
|
"cloudflare": "^4.5.0",
|
|
42
42
|
"rollup": "~4.50.2",
|
|
43
43
|
"rollup-plugin-esbuild": "^6.2.1",
|
|
44
|
-
"@mastra/deployer": "^1.0.0-beta.
|
|
44
|
+
"@mastra/deployer": "^1.0.0-beta.14"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@babel/types": "^7.28.5",
|
|
48
|
-
"@microsoft/api-extractor": "^7.52.8",
|
|
49
48
|
"@types/babel__core": "^7.20.5",
|
|
50
|
-
"@types/node": "
|
|
49
|
+
"@types/node": "22.13.17",
|
|
50
|
+
"@vitest/coverage-v8": "4.0.12",
|
|
51
|
+
"@vitest/ui": "4.0.12",
|
|
51
52
|
"eslint": "^9.37.0",
|
|
52
53
|
"tsup": "^8.5.0",
|
|
53
54
|
"typescript": "^5.8.3",
|
|
54
|
-
"vitest": "
|
|
55
|
+
"vitest": "4.0.12",
|
|
55
56
|
"zod": "^3.25.76",
|
|
56
57
|
"@internal/lint": "0.0.53",
|
|
57
58
|
"@internal/types-builder": "0.0.28",
|
|
58
|
-
"@mastra/core": "1.0.0-beta.
|
|
59
|
+
"@mastra/core": "1.0.0-beta.14"
|
|
59
60
|
},
|
|
60
61
|
"homepage": "https://mastra.ai",
|
|
61
62
|
"repository": {
|