@mastra/deployer-cloudflare 0.11.6-alpha.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ import type { PluginObj } from '@babel/core';
2
+ /**
3
+ * Babel plugin that transforms Mastra exports for Cloudflare Workers compatibility.
4
+ *
5
+ * This plugin:
6
+ * 1. Identifies named exports of the 'mastra' variable
7
+ * 2. Checks if the export is a new instance of the 'Mastra' class
8
+ * 3. Wraps the Mastra instantiation in an arrow function to ensure proper initialization
9
+ * in the Cloudflare Workers environment
10
+ *
11
+ * The transformation ensures the Mastra instance is properly scoped and initialized
12
+ * for each request in the Cloudflare Workers environment.
13
+ *
14
+ * @returns {PluginObj} A Babel plugin object with a visitor that performs the transformation
15
+ *
16
+ * @example
17
+ * // Before transformation:
18
+ * export const mastra = new Mastra();
19
+ *
20
+ * // After transformation:
21
+ * export const mastra = () => new Mastra();
22
+ */
23
+ export declare function mastraInstanceWrapper(): PluginObj;
24
+ //# sourceMappingURL=mastra-instance-wrapper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mastra-instance-wrapper.d.ts","sourceRoot":"","sources":["../../src/babel/mastra-instance-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAG7C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,qBAAqB,IAAI,SAAS,CAyBjD"}
@@ -0,0 +1,21 @@
1
+ import type { PluginObj } from '@babel/core';
2
+ /**
3
+ * Babel plugin that enforces singleton PostgresStore instances in Cloudflare Workers.
4
+ *
5
+ * This plugin:
6
+ * 1. Scans for all `new PostgresStore()` instantiations
7
+ * 2. Records their file locations
8
+ * 3. Throws an error if multiple instances are found
9
+ *
10
+ * Cloudflare Workers should only create one PostgresStore instance to avoid connection
11
+ * pool exhaustion and ensure proper resource management.
12
+ *
13
+ * @returns {PluginObj} A Babel plugin object that validates PostgresStore usage
14
+ *
15
+ * @example
16
+ * // Throws error if multiple instances found:
17
+ * const store1 = new PostgresStore();
18
+ * const store2 = new PostgresStore(); // Error thrown here
19
+ */
20
+ export declare function postgresStoreInstanceChecker(): PluginObj;
21
+ //# sourceMappingURL=postgres-store-instance-checker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-store-instance-checker.d.ts","sourceRoot":"","sources":["../../src/babel/postgres-store-instance-checker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAY,SAAS,EAAE,MAAM,aAAa,CAAC;AAIvD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,4BAA4B,IAAI,SAAS,CAkCxD"}
package/dist/index.cjs CHANGED
@@ -4,10 +4,131 @@ var promises = require('fs/promises');
4
4
  var path = require('path');
5
5
  var deployer = require('@mastra/deployer');
6
6
  var virtual = require('@rollup/plugin-virtual');
7
+ var babel = require('@babel/core');
7
8
 
8
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
10
 
11
+ function _interopNamespace(e) {
12
+ if (e && e.__esModule) return e;
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
10
29
  var virtual__default = /*#__PURE__*/_interopDefault(virtual);
30
+ var babel__namespace = /*#__PURE__*/_interopNamespace(babel);
31
+
32
+ // src/index.ts
33
+ function mastraInstanceWrapper() {
34
+ const exportName = "mastra";
35
+ const className = "Mastra";
36
+ const t = babel__namespace.types;
37
+ return {
38
+ name: "wrap-mastra",
39
+ visitor: {
40
+ ExportNamedDeclaration(path) {
41
+ if (t.isVariableDeclaration(path.node?.declaration)) {
42
+ for (const declaration of path.node.declaration.declarations) {
43
+ if (t.isIdentifier(declaration?.id, { name: exportName }) && t.isNewExpression(declaration?.init) && t.isIdentifier(declaration.init.callee, { name: className })) {
44
+ declaration.init = t.arrowFunctionExpression([], declaration.init);
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ }
50
+ }
51
+ };
52
+ }
53
+
54
+ // src/plugins/mastra-instance-wrapper.ts
55
+ function mastraInstanceWrapper2(mastraEntryFile) {
56
+ return {
57
+ name: "mastra-wrapper",
58
+ transform(code, id) {
59
+ if (id !== mastraEntryFile) {
60
+ return null;
61
+ }
62
+ const result = babel.transformSync(code, {
63
+ filename: id,
64
+ babelrc: false,
65
+ configFile: false,
66
+ plugins: [mastraInstanceWrapper]
67
+ });
68
+ if (!result?.code) {
69
+ throw new Error("mastra-wrapper plugin did not return code, there is likely a bug in the plugin.");
70
+ }
71
+ return {
72
+ code: result.code,
73
+ map: result?.map
74
+ };
75
+ }
76
+ };
77
+ }
78
+ function postgresStoreInstanceChecker() {
79
+ const t = babel__namespace.types;
80
+ const instances = [];
81
+ return {
82
+ name: "postgresstore-instance-checker",
83
+ visitor: {
84
+ NewExpression(path, state) {
85
+ if (t.isIdentifier(path.node.callee) && path.node.callee.name === "PostgresStore") {
86
+ const filename = state.file?.opts?.filename || "unknown file";
87
+ const location = path.node.loc ? `${filename}: line ${path.node.loc.start.line}, column ${path.node.loc.start.column}` : "unknown location";
88
+ instances.push({
89
+ path,
90
+ location
91
+ });
92
+ }
93
+ }
94
+ },
95
+ post() {
96
+ if (instances.length > 1) {
97
+ const errorMessage = [
98
+ `Found ${instances.length} PostgresStore instantiations:`,
99
+ ...instances.map((instance, i) => ` ${i + 1}. At ${instance.location}`),
100
+ "Only one PostgresStore instance should be created per Cloudflare Worker."
101
+ ].join("\n");
102
+ const lastInstance = instances[instances.length - 1];
103
+ throw lastInstance?.path.buildCodeFrameError(errorMessage);
104
+ }
105
+ }
106
+ };
107
+ }
108
+
109
+ // src/plugins/postgres-store-instance-checker.ts
110
+ function postgresStoreInstanceChecker2() {
111
+ return {
112
+ name: "postgres-store-instance-checker",
113
+ transform(code, id) {
114
+ const result = babel.transformSync(code, {
115
+ filename: id,
116
+ babelrc: false,
117
+ configFile: false,
118
+ plugins: [postgresStoreInstanceChecker]
119
+ });
120
+ if (!result?.code) {
121
+ throw new Error(
122
+ "postgres-store-instance-checker plugin did not return code, there is likely a bug in the plugin."
123
+ );
124
+ }
125
+ return {
126
+ code: result.code,
127
+ map: result?.map
128
+ };
129
+ }
130
+ };
131
+ }
11
132
 
12
133
  // src/index.ts
13
134
  var CloudflareDeployer = class extends deployer.Deployer {
@@ -73,47 +194,49 @@ var CloudflareDeployer = class extends deployer.Deployer {
73
194
  import { TABLE_EVALS } from '@mastra/core/storage';
74
195
  import { checkEvalStorageFields } from '@mastra/core/utils';
75
196
 
76
- registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
77
- evaluate({
78
- agentName,
79
- input,
80
- metric,
81
- output,
82
- runId,
83
- globalRunId: runId,
84
- instructions,
85
- });
86
- });
87
-
88
- registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {
89
- const storage = mastra.getStorage();
90
- if (storage) {
91
- // Check for required fields
92
- const logger = mastra?.getLogger();
93
- const areFieldsValid = checkEvalStorageFields(traceObject, logger);
94
- if (!areFieldsValid) return;
197
+ export default {
198
+ fetch: async (request, env, context) => {
199
+ const _mastra = mastra();
95
200
 
96
- await storage.insert({
97
- tableName: TABLE_EVALS,
98
- record: {
99
- input: traceObject.input,
100
- output: traceObject.output,
101
- result: JSON.stringify(traceObject.result || {}),
102
- agent_name: traceObject.agentName,
103
- metric_name: traceObject.metricName,
104
- instructions: traceObject.instructions,
105
- test_info: null,
106
- global_run_id: traceObject.globalRunId,
107
- run_id: traceObject.runId,
108
- created_at: new Date().toISOString(),
109
- },
201
+ registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
202
+ evaluate({
203
+ agentName,
204
+ input,
205
+ metric,
206
+ output,
207
+ runId,
208
+ globalRunId: runId,
209
+ instructions,
210
+ });
110
211
  });
111
- }
112
- });
113
212
 
114
- export default {
115
- fetch: async (request, env, context) => {
116
- const app = await createHonoServer(mastra, { tools: getToolExports(tools) });
213
+ registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {
214
+ const storage = _mastra.getStorage();
215
+ if (storage) {
216
+ // Check for required fields
217
+ const logger = _mastra?.getLogger();
218
+ const areFieldsValid = checkEvalStorageFields(traceObject, logger);
219
+ if (!areFieldsValid) return;
220
+
221
+ await storage.insert({
222
+ tableName: TABLE_EVALS,
223
+ record: {
224
+ input: traceObject.input,
225
+ output: traceObject.output,
226
+ result: JSON.stringify(traceObject.result || {}),
227
+ agent_name: traceObject.agentName,
228
+ metric_name: traceObject.metricName,
229
+ instructions: traceObject.instructions,
230
+ test_info: null,
231
+ global_run_id: traceObject.globalRunId,
232
+ run_id: traceObject.runId,
233
+ created_at: new Date().toISOString(),
234
+ },
235
+ });
236
+ }
237
+ });
238
+
239
+ const app = await createHonoServer(_mastra, { tools: getToolExports(tools) });
117
240
  return app.fetch(request, env, context);
118
241
  }
119
242
  }
@@ -133,7 +256,9 @@ process.versions = process.versions || {};
133
256
  process.versions.node = '${process.versions.node}';
134
257
  `
135
258
  }),
136
- ...inputOptions.plugins
259
+ ...inputOptions.plugins,
260
+ postgresStoreInstanceChecker2(),
261
+ mastraInstanceWrapper2(mastraEntryFile)
137
262
  ];
138
263
  }
139
264
  return inputOptions;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["Deployer","writeFile","join","virtual"],"mappings":";;;;;;;;;;;;AAwBO,IAAM,kBAAA,GAAN,cAAiCA,iBAAA,CAAS;AAAA,EAC/C,SAAqB,EAAC;AAAA,EACtB,eAAA;AAAA,EACA,GAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EAEA,WAAA,CAAY;AAAA,IACV,GAAA;AAAA,IAC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Q,SAAS,IAAI,CAAA;AAAA,MAAA;AAAA,SAEvC,CAAA;AAAA,QACD,GAAG,YAAA,CAAa;AAAA,OAClB;AAAA,IACF;AAEA,IAAA,OAAO,YAAA;AAAA,EACT;AAAA,EAEA,MAAM,MAAA,CAAO,SAAA,EAAmB,eAAA,EAAyB,UAAA,EAAqC;AAC5F,IAAA,OAAO,KAAK,OAAA,CAAQ,IAAA,CAAK,UAAS,EAAG,SAAA,EAAW,iBAAiB,UAAU,CAAA;AAAA,EAC7E;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,EAAqC;AAC1F,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 { 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';\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 { mastra } from '#mastra';\n import { createHonoServer, getToolExports } from '#server';\n import { tools } from '#tools';\n import { evaluate } from '@mastra/core/eval';\n import { AvailableHooks, registerHook } from '@mastra/core/hooks';\n import { TABLE_EVALS } from '@mastra/core/storage';\n import { checkEvalStorageFields } from '@mastra/core/utils';\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n const storage = mastra.getStorage();\n if (storage) {\n // Check for required fields\n const logger = mastra?.getLogger();\n const areFieldsValid = checkEvalStorageFields(traceObject, logger);\n if (!areFieldsValid) return;\n\n await storage.insert({\n tableName: TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result || {}),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\n });\n\n export default {\n fetch: async (request, env, context) => {\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[],\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths);\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 ];\n }\n\n return inputOptions;\n }\n\n async bundle(entryFile: string, outputDirectory: string, toolsPaths: string[]): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, outputDirectory, 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[]): 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,YAAA,CAAa,WAAA,CAAY,IAAA,CAAK,QAAQ,EAAE,IAAA,EAAM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AAkB,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 (!result?.code) {\n throw new Error(\n 'postgres-store-instance-checker plugin did not return code, there is likely a bug in the plugin.',\n );\n }\n\n return {\n code: result.code,\n map: result?.map,\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 { mastra } from '#mastra';\n import { createHonoServer, getToolExports } from '#server';\n import { tools } from '#tools';\n import { evaluate } from '@mastra/core/eval';\n import { AvailableHooks, registerHook } from '@mastra/core/hooks';\n import { TABLE_EVALS } from '@mastra/core/storage';\n import { checkEvalStorageFields } from '@mastra/core/utils';\n\n export default {\n fetch: async (request, env, context) => {\n const _mastra = mastra();\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n const storage = _mastra.getStorage();\n if (storage) {\n // Check for required fields\n const logger = _mastra?.getLogger();\n const areFieldsValid = checkEvalStorageFields(traceObject, logger);\n if (!areFieldsValid) return;\n\n await storage.insert({\n tableName: TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result || {}),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\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 ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths);\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 postgresStoreInstanceChecker(),\n mastraInstanceWrapper(mastraEntryFile),\n ];\n }\n\n return inputOptions;\n }\n\n async bundle(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, outputDirectory, 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
@@ -33,11 +33,11 @@ export declare class CloudflareDeployer extends Deployer {
33
33
  writeFiles(outputDirectory: string): Promise<void>;
34
34
  private getEntry;
35
35
  prepare(outputDirectory: string): Promise<void>;
36
- getBundlerOptions(serverFile: string, mastraEntryFile: string, analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>, toolsPaths: string[]): Promise<import("rollup").InputOptions>;
37
- bundle(entryFile: string, outputDirectory: string, toolsPaths: string[]): Promise<void>;
36
+ getBundlerOptions(serverFile: string, mastraEntryFile: string, analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>, toolsPaths: (string | string[])[]): Promise<import("rollup").InputOptions>;
37
+ bundle(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void>;
38
38
  deploy(): Promise<void>;
39
39
  tagWorker(): Promise<void>;
40
- lint(entryFile: string, outputDirectory: string, toolsPaths: string[]): Promise<void>;
40
+ lint(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void>;
41
41
  }
42
42
  export {};
43
43
  //# sourceMappingURL=index.d.ts.map
@@ -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;AAG9D,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,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,UAAU,kBAAkB;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,qBAAa,kBAAmB,SAAQ,QAAQ;IAC9C,MAAM,CAAC,EAAE,OAAO,EAAE,CAAM;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GA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;IA2DV,OAAO,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK/C,iBAAiB,CACrB,UAAU,EAAE,MAAM,EAClB,eAAe,EAAE,MAAM,EACvB,kBAAkB,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC,EAC7D,UAAU,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE;IAqB7B,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAIpG,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
@@ -2,6 +2,109 @@ import { writeFile } from 'fs/promises';
2
2
  import { join } from 'path';
3
3
  import { Deployer } from '@mastra/deployer';
4
4
  import virtual from '@rollup/plugin-virtual';
5
+ import * as babel from '@babel/core';
6
+ import { transformSync } from '@babel/core';
7
+
8
+ // src/index.ts
9
+ function mastraInstanceWrapper() {
10
+ const exportName = "mastra";
11
+ const className = "Mastra";
12
+ const t = babel.types;
13
+ return {
14
+ name: "wrap-mastra",
15
+ visitor: {
16
+ ExportNamedDeclaration(path) {
17
+ if (t.isVariableDeclaration(path.node?.declaration)) {
18
+ for (const declaration of path.node.declaration.declarations) {
19
+ if (t.isIdentifier(declaration?.id, { name: exportName }) && t.isNewExpression(declaration?.init) && t.isIdentifier(declaration.init.callee, { name: className })) {
20
+ declaration.init = t.arrowFunctionExpression([], declaration.init);
21
+ break;
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
27
+ };
28
+ }
29
+
30
+ // src/plugins/mastra-instance-wrapper.ts
31
+ function mastraInstanceWrapper2(mastraEntryFile) {
32
+ return {
33
+ name: "mastra-wrapper",
34
+ transform(code, id) {
35
+ if (id !== mastraEntryFile) {
36
+ return null;
37
+ }
38
+ const result = transformSync(code, {
39
+ filename: id,
40
+ babelrc: false,
41
+ configFile: false,
42
+ plugins: [mastraInstanceWrapper]
43
+ });
44
+ if (!result?.code) {
45
+ throw new Error("mastra-wrapper plugin did not return code, there is likely a bug in the plugin.");
46
+ }
47
+ return {
48
+ code: result.code,
49
+ map: result?.map
50
+ };
51
+ }
52
+ };
53
+ }
54
+ function postgresStoreInstanceChecker() {
55
+ const t = babel.types;
56
+ const instances = [];
57
+ return {
58
+ name: "postgresstore-instance-checker",
59
+ visitor: {
60
+ NewExpression(path, state) {
61
+ if (t.isIdentifier(path.node.callee) && path.node.callee.name === "PostgresStore") {
62
+ const filename = state.file?.opts?.filename || "unknown file";
63
+ const location = path.node.loc ? `${filename}: line ${path.node.loc.start.line}, column ${path.node.loc.start.column}` : "unknown location";
64
+ instances.push({
65
+ path,
66
+ location
67
+ });
68
+ }
69
+ }
70
+ },
71
+ post() {
72
+ if (instances.length > 1) {
73
+ const errorMessage = [
74
+ `Found ${instances.length} PostgresStore instantiations:`,
75
+ ...instances.map((instance, i) => ` ${i + 1}. At ${instance.location}`),
76
+ "Only one PostgresStore instance should be created per Cloudflare Worker."
77
+ ].join("\n");
78
+ const lastInstance = instances[instances.length - 1];
79
+ throw lastInstance?.path.buildCodeFrameError(errorMessage);
80
+ }
81
+ }
82
+ };
83
+ }
84
+
85
+ // src/plugins/postgres-store-instance-checker.ts
86
+ function postgresStoreInstanceChecker2() {
87
+ return {
88
+ name: "postgres-store-instance-checker",
89
+ transform(code, id) {
90
+ const result = transformSync(code, {
91
+ filename: id,
92
+ babelrc: false,
93
+ configFile: false,
94
+ plugins: [postgresStoreInstanceChecker]
95
+ });
96
+ if (!result?.code) {
97
+ throw new Error(
98
+ "postgres-store-instance-checker plugin did not return code, there is likely a bug in the plugin."
99
+ );
100
+ }
101
+ return {
102
+ code: result.code,
103
+ map: result?.map
104
+ };
105
+ }
106
+ };
107
+ }
5
108
 
6
109
  // src/index.ts
7
110
  var CloudflareDeployer = class extends Deployer {
@@ -67,47 +170,49 @@ var CloudflareDeployer = class extends Deployer {
67
170
  import { TABLE_EVALS } from '@mastra/core/storage';
68
171
  import { checkEvalStorageFields } from '@mastra/core/utils';
69
172
 
70
- registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
71
- evaluate({
72
- agentName,
73
- input,
74
- metric,
75
- output,
76
- runId,
77
- globalRunId: runId,
78
- instructions,
79
- });
80
- });
81
-
82
- registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {
83
- const storage = mastra.getStorage();
84
- if (storage) {
85
- // Check for required fields
86
- const logger = mastra?.getLogger();
87
- const areFieldsValid = checkEvalStorageFields(traceObject, logger);
88
- if (!areFieldsValid) return;
173
+ export default {
174
+ fetch: async (request, env, context) => {
175
+ const _mastra = mastra();
89
176
 
90
- await storage.insert({
91
- tableName: TABLE_EVALS,
92
- record: {
93
- input: traceObject.input,
94
- output: traceObject.output,
95
- result: JSON.stringify(traceObject.result || {}),
96
- agent_name: traceObject.agentName,
97
- metric_name: traceObject.metricName,
98
- instructions: traceObject.instructions,
99
- test_info: null,
100
- global_run_id: traceObject.globalRunId,
101
- run_id: traceObject.runId,
102
- created_at: new Date().toISOString(),
103
- },
177
+ registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
178
+ evaluate({
179
+ agentName,
180
+ input,
181
+ metric,
182
+ output,
183
+ runId,
184
+ globalRunId: runId,
185
+ instructions,
186
+ });
104
187
  });
105
- }
106
- });
107
188
 
108
- export default {
109
- fetch: async (request, env, context) => {
110
- const app = await createHonoServer(mastra, { tools: getToolExports(tools) });
189
+ registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {
190
+ const storage = _mastra.getStorage();
191
+ if (storage) {
192
+ // Check for required fields
193
+ const logger = _mastra?.getLogger();
194
+ const areFieldsValid = checkEvalStorageFields(traceObject, logger);
195
+ if (!areFieldsValid) return;
196
+
197
+ await storage.insert({
198
+ tableName: TABLE_EVALS,
199
+ record: {
200
+ input: traceObject.input,
201
+ output: traceObject.output,
202
+ result: JSON.stringify(traceObject.result || {}),
203
+ agent_name: traceObject.agentName,
204
+ metric_name: traceObject.metricName,
205
+ instructions: traceObject.instructions,
206
+ test_info: null,
207
+ global_run_id: traceObject.globalRunId,
208
+ run_id: traceObject.runId,
209
+ created_at: new Date().toISOString(),
210
+ },
211
+ });
212
+ }
213
+ });
214
+
215
+ const app = await createHonoServer(_mastra, { tools: getToolExports(tools) });
111
216
  return app.fetch(request, env, context);
112
217
  }
113
218
  }
@@ -127,7 +232,9 @@ process.versions = process.versions || {};
127
232
  process.versions.node = '${process.versions.node}';
128
233
  `
129
234
  }),
130
- ...inputOptions.plugins
235
+ ...inputOptions.plugins,
236
+ postgresStoreInstanceChecker2(),
237
+ mastraInstanceWrapper2(mastraEntryFile)
131
238
  ];
132
239
  }
133
240
  return inputOptions;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;;;AAwBO,IAAM,kBAAA,GAAN,cAAiC,QAAA,CAAS;AAAA,EAC/C,SAAqB,EAAC;AAAA,EACtB,eAAA;AAAA,EACA,GAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EAEA,WAAA,CAAY;AAAA,IACV,GAAA;AAAA,IACA,WAAA,GAAc,QAAA;AAAA,IACd,MAAA;AAAA,IACA,eAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF,EAOG;AACD,IAAA,KAAA,CAAM,EAAE,IAAA,EAAM,YAAA,EAAc,CAAA;AAE5B,IAAA,IAAA,CAAK,WAAA,GAAc,WAAA;AACnB,IAAA,I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A,OAAO,KAAK,OAAA,CAAQ,IAAA,CAAK,UAAS,EAAG,SAAA,EAAW,iBAAiB,UAAU,CAAA;AAAA,EAC7E;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,EAAqC;AAC1F,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 { 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';\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 { mastra } from '#mastra';\n import { createHonoServer, getToolExports } from '#server';\n import { tools } from '#tools';\n import { evaluate } from '@mastra/core/eval';\n import { AvailableHooks, registerHook } from '@mastra/core/hooks';\n import { TABLE_EVALS } from '@mastra/core/storage';\n import { checkEvalStorageFields } from '@mastra/core/utils';\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n const storage = mastra.getStorage();\n if (storage) {\n // Check for required fields\n const logger = mastra?.getLogger();\n const areFieldsValid = checkEvalStorageFields(traceObject, logger);\n if (!areFieldsValid) return;\n\n await storage.insert({\n tableName: TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result || {}),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\n });\n\n export default {\n fetch: async (request, env, context) => {\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[],\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths);\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 ];\n }\n\n return inputOptions;\n }\n\n async bundle(entryFile: string, outputDirectory: string, toolsPaths: string[]): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, outputDirectory, 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[]): 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,CAAA,CAAE,uBAAA,CAAwB,EAAC,EAAG,YAAY,IAAI,CAAA;AAEjE,cAAA;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA;AACF,GACF;AACF;;;AC7CO,SAASA,uBAAsB,eAAA,EAAiC;AACrE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AA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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 (!result?.code) {\n throw new Error(\n 'postgres-store-instance-checker plugin did not return code, there is likely a bug in the plugin.',\n );\n }\n\n return {\n code: result.code,\n map: result?.map,\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 { mastra } from '#mastra';\n import { createHonoServer, getToolExports } from '#server';\n import { tools } from '#tools';\n import { evaluate } from '@mastra/core/eval';\n import { AvailableHooks, registerHook } from '@mastra/core/hooks';\n import { TABLE_EVALS } from '@mastra/core/storage';\n import { checkEvalStorageFields } from '@mastra/core/utils';\n\n export default {\n fetch: async (request, env, context) => {\n const _mastra = mastra();\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n const storage = _mastra.getStorage();\n if (storage) {\n // Check for required fields\n const logger = _mastra?.getLogger();\n const areFieldsValid = checkEvalStorageFields(traceObject, logger);\n if (!areFieldsValid) return;\n\n await storage.insert({\n tableName: TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result || {}),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\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 ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths);\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 postgresStoreInstanceChecker(),\n mastraInstanceWrapper(mastraEntryFile),\n ];\n }\n\n return inputOptions;\n }\n\n async bundle(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, outputDirectory, 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"]}
@@ -0,0 +1,5 @@
1
+ export const mastra: Mastra<{
2
+ weatherAgent: any;
3
+ }, Record<string, import("@mastra/core/workflows/legacy").LegacyWorkflow<import("@mastra/core/workflows/legacy").LegacyStep<string, any, any, import("@mastra/core/workflows/legacy").StepExecutionContext<any, import("@mastra/core/workflows/legacy").WorkflowContext<any, import("@mastra/core/workflows/legacy").LegacyStep<string, any, any, any>[], Record<string, any>>>>[], string, any, any>>, Record<string, import("@mastra/core/workflows").Workflow<any, import("@mastra/core").Step<string, any, any, any, any, any>[], string, import("zod").ZodType<any, import("zod").ZodTypeDef, any>, import("zod").ZodType<any, import("zod").ZodTypeDef, any>, import("zod").ZodType<any, import("zod").ZodTypeDef, any>>>, Record<string, import("@mastra/core/vector").MastraVector<import("@mastra/core/vector/filter").VectorFilter>>, Record<string, import("@mastra/core/tts").MastraTTS>, import("@mastra/core/logger").ConsoleLogger, Record<string, import("@mastra/core/network").AgentNetwork>, Record<string, import("@mastra/core/network/vNext").NewAgentNetwork>, Record<string, import("@mastra/core/mcp").MCPServerBase>>;
4
+ import { Mastra } from '@mastra/core/mastra';
5
+ //# sourceMappingURL=basic.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"basic.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/basic.js"],"names":[],"mappings":"AAOA;;glCA+BG;uBArCoB,qBAAqB"}
@@ -0,0 +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").Metric>>>, Record<string, import("@mastra/core/workflows/legacy").LegacyWorkflow<import("@mastra/core/workflows/legacy").LegacyStep<string, any, any, import("@mastra/core/workflows/legacy").StepExecutionContext<any, import("@mastra/core/workflows/legacy").WorkflowContext<any, import("@mastra/core/workflows/legacy").LegacyStep<string, any, any, any>[], Record<string, any>>>>[], string, any, any>>, Record<string, import("@mastra/core/workflows").Workflow<any, import("@mastra/core").Step<string, any, any, any, any, any>[], string, import("zod").ZodType<any, import("zod").ZodTypeDef, any>, import("zod").ZodType<any, import("zod").ZodTypeDef, any>, import("zod").ZodType<any, import("zod").ZodTypeDef, any>>>, Record<string, import("@mastra/core/vector").MastraVector<import("@mastra/core/vector/filter").VectorFilter>>, Record<string, import("@mastra/core/tts").MastraTTS>, import("@mastra/core/logger").IMastraLogger, Record<string, import("@mastra/core/network").AgentNetwork>, Record<string, import("@mastra/core/network/vNext").NewAgentNetwork>, Record<string, import("@mastra/core/mcp").MCPServerBase>>;
2
+ import { Mastra } from '@mastra/core/mastra';
3
+ //# sourceMappingURL=empty-mastra.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"empty-mastra.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/empty-mastra.js"],"names":[],"mappings":"AACA,0vCAAmC;uBADZ,qBAAqB"}
@@ -0,0 +1,6 @@
1
+ export const storage: any;
2
+ export const mastra: Mastra<{
3
+ weatherAgent: any;
4
+ }, Record<string, import("@mastra/core/workflows/legacy").LegacyWorkflow<import("@mastra/core/workflows/legacy").LegacyStep<string, any, any, import("@mastra/core/workflows/legacy").StepExecutionContext<any, import("@mastra/core/workflows/legacy").WorkflowContext<any, import("@mastra/core/workflows/legacy").LegacyStep<string, any, any, any>[], Record<string, any>>>>[], string, any, any>>, Record<string, import("@mastra/core/workflows").Workflow<any, import("@mastra/core").Step<string, any, any, any, any, any>[], string, import("zod").ZodType<any, import("zod").ZodTypeDef, any>, import("zod").ZodType<any, import("zod").ZodTypeDef, any>, import("zod").ZodType<any, import("zod").ZodTypeDef, any>>>, Record<string, import("@mastra/core/vector").MastraVector<import("@mastra/core/vector/filter").VectorFilter>>, Record<string, import("@mastra/core/tts").MastraTTS>, import("@mastra/core/logger").ConsoleLogger, Record<string, import("@mastra/core/network").AgentNetwork>, Record<string, import("@mastra/core/network/vNext").NewAgentNetwork>, Record<string, import("@mastra/core/mcp").MCPServerBase>>;
5
+ import { Mastra } from '@mastra/core/mastra';
6
+ //# sourceMappingURL=multiple-postgres-stores.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multiple-postgres-stores.d.ts","sourceRoot":"","sources":["../../../src/plugins/__fixtures__/multiple-postgres-stores.js"],"names":[],"mappings":"AAOA,0BAEG;AAEH;;glCA+BG;uBAzCoB,qBAAqB"}
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'rollup';
2
+ export declare function mastraInstanceWrapper(mastraEntryFile: string): Plugin;
3
+ //# sourceMappingURL=mastra-instance-wrapper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mastra-instance-wrapper.d.ts","sourceRoot":"","sources":["../../src/plugins/mastra-instance-wrapper.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGrC,wBAAgB,qBAAqB,CAAC,eAAe,EAAE,MAAM,GAAG,MAAM,CAyBrE"}
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'rollup';
2
+ export declare function postgresStoreInstanceChecker(): Plugin;
3
+ //# sourceMappingURL=postgres-store-instance-checker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-store-instance-checker.d.ts","sourceRoot":"","sources":["../../src/plugins/postgres-store-instance-checker.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGrC,wBAAgB,4BAA4B,IAAI,MAAM,CAuBrD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/deployer-cloudflare",
3
- "version": "0.11.6-alpha.0",
3
+ "version": "0.12.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [
@@ -40,18 +40,20 @@
40
40
  "cloudflare": "^4.5.0",
41
41
  "rollup": "~4.46.2",
42
42
  "zod": "^3.25.67",
43
- "@mastra/deployer": "^0.13.2-alpha.0"
43
+ "@mastra/deployer": "^0.13.2"
44
44
  },
45
45
  "devDependencies": {
46
+ "@babel/types": "^7.28.2",
46
47
  "@microsoft/api-extractor": "^7.52.8",
48
+ "@types/babel__core": "^7.20.5",
47
49
  "@types/node": "^20.19.0",
48
50
  "eslint": "^9.30.1",
49
51
  "tsup": "^8.5.0",
50
52
  "typescript": "^5.8.3",
51
53
  "vitest": "^3.2.4",
52
- "@internal/types-builder": "0.0.3",
53
- "@internal/lint": "0.0.28",
54
- "@mastra/core": "0.13.2-alpha.0"
54
+ "@internal/lint": "0.0.29",
55
+ "@mastra/core": "0.13.2",
56
+ "@internal/types-builder": "0.0.4"
55
57
  },
56
58
  "peerDependencies": {
57
59
  "@mastra/core": ">=0.10.1-0 <0.14.0-0"