@mastra/temporal 0.2.11-alpha.0 → 0.2.11-alpha.2

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/dist/worker.js CHANGED
@@ -1,485 +1,321 @@
1
- import { toWorkflowType } from './chunk-BF6TR7JX.js';
2
- import { readFileSync } from 'fs';
3
- import { writeFile } from 'fs/promises';
4
- import path, { basename, join } from 'path';
5
- import { fileURLToPath, pathToFileURL } from 'url';
6
- import { generate } from '@babel/generator';
7
- import { parse } from '@babel/parser';
8
- import * as t3 from '@babel/types';
9
- import { rollup } from 'rollup';
10
-
11
- var parserPlugins = ["typescript", "jsx", "decorators-legacy"];
1
+ import { t as toWorkflowType } from "./utils-B_iPTfDi.js";
2
+ import { readFileSync } from "fs";
3
+ import { writeFile } from "fs/promises";
4
+ import path, { basename, join } from "path";
5
+ import { fileURLToPath, pathToFileURL } from "url";
6
+ import { generate } from "@babel/generator";
7
+ import { parse } from "@babel/parser";
8
+ import * as t from "@babel/types";
9
+ import { rollup } from "rollup";
10
+ //#region src/transforms/shared.ts
11
+ const parserPlugins = [
12
+ "typescript",
13
+ "jsx",
14
+ "decorators-legacy"
15
+ ];
12
16
  function parseModule(filePath, sourceText) {
13
- if (!sourceText) {
14
- sourceText = readFileSync(filePath, "utf8");
15
- }
16
- return parse(sourceText, {
17
- sourceType: "module",
18
- plugins: parserPlugins,
19
- sourceFilename: filePath
20
- });
17
+ if (!sourceText) sourceText = readFileSync(filePath, "utf8");
18
+ return parse(sourceText, {
19
+ sourceType: "module",
20
+ plugins: parserPlugins,
21
+ sourceFilename: filePath
22
+ });
21
23
  }
22
24
  function isIdentifierNamed(node, name) {
23
- return t3.isIdentifier(node) && node.name === name;
25
+ return t.isIdentifier(node) && node.name === name;
24
26
  }
25
27
  function isTemporalHelperModule(source) {
26
- return typeof source === "string" && /(^|\/)temporal\.(ts|tsx|js|jsx|mts|mjs)$/.test(source);
28
+ return typeof source === "string" && /(^|\/)temporal\.(ts|tsx|js|jsx|mts|mjs)$/.test(source);
27
29
  }
28
- var strippedExternalModules = /* @__PURE__ */ new Set(["@temporalio/client", "@temporalio/envconfig"]);
30
+ const strippedExternalModules = /* @__PURE__ */ new Set(["@temporalio/client", "@temporalio/envconfig"]);
29
31
  function isStrippedExternalModule(source) {
30
- return typeof source === "string" && strippedExternalModules.has(source);
32
+ return typeof source === "string" && strippedExternalModules.has(source);
31
33
  }
32
34
  function collectImportedNames(statement) {
33
- const names = /* @__PURE__ */ new Set();
34
- for (const specifier of statement.specifiers) {
35
- if (t3.isImportDefaultSpecifier(specifier) || t3.isImportNamespaceSpecifier(specifier) || t3.isImportSpecifier(specifier)) {
36
- if (t3.isIdentifier(specifier.local)) {
37
- names.add(specifier.local.name);
38
- }
39
- }
40
- }
41
- return names;
35
+ const names = /* @__PURE__ */ new Set();
36
+ for (const specifier of statement.specifiers) if (t.isImportDefaultSpecifier(specifier) || t.isImportNamespaceSpecifier(specifier) || t.isImportSpecifier(specifier)) {
37
+ if (t.isIdentifier(specifier.local)) names.add(specifier.local.name);
38
+ }
39
+ return names;
42
40
  }
43
41
  function nodeReferencesName(node, names) {
44
- let found = false;
45
- walk(node, (current) => {
46
- if (t3.isIdentifier(current) && names.has(current.name)) {
47
- found = true;
48
- return false;
49
- }
50
- });
51
- return found;
42
+ let found = false;
43
+ walk(node, (current) => {
44
+ if (t.isIdentifier(current) && names.has(current.name)) {
45
+ found = true;
46
+ return false;
47
+ }
48
+ });
49
+ return found;
52
50
  }
53
51
  function isWorkflowHelperDestructure(declaration) {
54
- if (!t3.isObjectPattern(declaration.id)) {
55
- return false;
56
- }
57
- return declaration.id.properties.some(
58
- (property) => t3.isObjectProperty(property) && !property.computed && t3.isIdentifier(property.value) && (property.value.name === "createStep" || property.value.name === "createWorkflow")
59
- );
52
+ if (!t.isObjectPattern(declaration.id)) return false;
53
+ return declaration.id.properties.some((property) => t.isObjectProperty(property) && !property.computed && t.isIdentifier(property.value) && (property.value.name === "createStep" || property.value.name === "createWorkflow"));
60
54
  }
61
55
  function isCreateWorkflowCall(node) {
62
- return t3.isCallExpression(node) && isIdentifierNamed(node.callee, "createWorkflow");
56
+ return t.isCallExpression(node) && isIdentifierNamed(node.callee, "createWorkflow");
63
57
  }
64
58
  function isCreateStepCall(node) {
65
- return t3.isCallExpression(node) && isIdentifierNamed(node.callee, "createStep");
59
+ return t.isCallExpression(node) && isIdentifierNamed(node.callee, "createStep");
66
60
  }
67
61
  function getObjectPropertyName(property) {
68
- if (property.computed) {
69
- return null;
70
- }
71
- if (t3.isIdentifier(property.key)) {
72
- return property.key.name;
73
- }
74
- if (t3.isStringLiteral(property.key)) {
75
- return property.key.value;
76
- }
77
- return null;
62
+ if (property.computed) return null;
63
+ if (t.isIdentifier(property.key)) return property.key.name;
64
+ if (t.isStringLiteral(property.key)) return property.key.value;
65
+ return null;
78
66
  }
79
67
  function walk(node, visitor) {
80
- if (!node) {
81
- return;
82
- }
83
- const result = visitor(node);
84
- if (result === false) {
85
- return;
86
- }
87
- const keys = t3.VISITOR_KEYS[node.type] ?? [];
88
- for (const key of keys) {
89
- const value = node[key];
90
- if (Array.isArray(value)) {
91
- for (const child of value) {
92
- if (child && typeof child.type === "string") {
93
- walk(child, visitor);
94
- }
95
- }
96
- continue;
97
- }
98
- if (value && typeof value.type === "string") {
99
- walk(value, visitor);
100
- }
101
- }
68
+ if (!node) return;
69
+ if (visitor(node) === false) return;
70
+ const keys = t.VISITOR_KEYS[node.type] ?? [];
71
+ for (const key of keys) {
72
+ const value = node[key];
73
+ if (Array.isArray(value)) {
74
+ for (const child of value) if (child && typeof child.type === "string") walk(child, visitor);
75
+ continue;
76
+ }
77
+ if (value && typeof value.type === "string") walk(value, visitor);
78
+ }
102
79
  }
103
80
  function hasCreateWorkflowCall(node) {
104
- let found = false;
105
- walk(node, (current) => {
106
- if (isCreateWorkflowCall(current)) {
107
- found = true;
108
- return false;
109
- }
110
- });
111
- return found;
81
+ let found = false;
82
+ walk(node, (current) => {
83
+ if (isCreateWorkflowCall(current)) {
84
+ found = true;
85
+ return false;
86
+ }
87
+ });
88
+ return found;
112
89
  }
113
90
  function getStepNameFromCall(node) {
114
- const stepId = getCreateStepId(node);
115
- if (!stepId) {
116
- return null;
117
- }
118
- return stepId.replace(/[^a-zA-Z0-9]+(.)/g, (_match, char) => char.toUpperCase()).replace(/^[^a-zA-Z_$]+/, "").replace(/^(.)/, (char) => char.toLowerCase());
91
+ const stepId = getCreateStepId(node);
92
+ if (!stepId) return null;
93
+ return stepId.replace(/[^a-zA-Z0-9]+(.)/g, (_match, char) => char.toUpperCase()).replace(/^[^a-zA-Z_$]+/, "").replace(/^(.)/, (char) => char.toLowerCase());
119
94
  }
120
95
  function createExportedStepStatement(name, initializer) {
121
- return t3.exportNamedDeclaration(
122
- t3.variableDeclaration("const", [t3.variableDeclarator(t3.identifier(name), t3.cloneNode(initializer, true))])
123
- );
96
+ return t.exportNamedDeclaration(t.variableDeclaration("const", [t.variableDeclarator(t.identifier(name), t.cloneNode(initializer, true))]));
124
97
  }
125
98
  function collectInlineCreateSteps(node, seenNames, statements, onStep) {
126
- walk(node, (current) => {
127
- if (!isCreateStepCall(current)) {
128
- return;
129
- }
130
- const stepName = getStepNameFromCall(current);
131
- if (!stepName || seenNames.has(stepName)) {
132
- return false;
133
- }
134
- seenNames.add(stepName);
135
- onStep?.(stepName, current);
136
- statements.push(createExportedStepStatement(stepName, current));
137
- return false;
138
- });
99
+ walk(node, (current) => {
100
+ if (!isCreateStepCall(current)) return;
101
+ const stepName = getStepNameFromCall(current);
102
+ if (!stepName || seenNames.has(stepName)) return false;
103
+ seenNames.add(stepName);
104
+ onStep?.(stepName, current);
105
+ statements.push(createExportedStepStatement(stepName, current));
106
+ return false;
107
+ });
139
108
  }
140
109
  function getReturnedCreateStepCall(node) {
141
- if (!node) {
142
- return null;
143
- }
144
- if (t3.isArrowFunctionExpression(node) && !t3.isBlockStatement(node.body)) {
145
- return t3.isCallExpression(node.body) && isIdentifierNamed(node.body.callee, "createStep") ? node.body : null;
146
- }
147
- if (!t3.isFunctionDeclaration(node) && !t3.isFunctionExpression(node) && !t3.isArrowFunctionExpression(node)) {
148
- return null;
149
- }
150
- if (!t3.isBlockStatement(node.body)) {
151
- return null;
152
- }
153
- for (const statement of node.body.body) {
154
- if (t3.isReturnStatement(statement) && t3.isCallExpression(statement.argument) && isIdentifierNamed(statement.argument.callee, "createStep")) {
155
- return statement.argument;
156
- }
157
- }
158
- return null;
110
+ if (!node) return null;
111
+ if (t.isArrowFunctionExpression(node) && !t.isBlockStatement(node.body)) return t.isCallExpression(node.body) && isIdentifierNamed(node.body.callee, "createStep") ? node.body : null;
112
+ if (!t.isFunctionDeclaration(node) && !t.isFunctionExpression(node) && !t.isArrowFunctionExpression(node)) return null;
113
+ if (!t.isBlockStatement(node.body)) return null;
114
+ for (const statement of node.body.body) if (t.isReturnStatement(statement) && t.isCallExpression(statement.argument) && isIdentifierNamed(statement.argument.callee, "createStep")) return statement.argument;
115
+ return null;
159
116
  }
160
- function collectCreateStepFactoryBindings(program3) {
161
- const factories = /* @__PURE__ */ new Map();
162
- for (const statement of program3.body) {
163
- const declaration = t3.isExportNamedDeclaration(statement) ? statement.declaration : statement;
164
- if (t3.isFunctionDeclaration(declaration) && declaration.id) {
165
- const createStepCall = getReturnedCreateStepCall(declaration);
166
- if (createStepCall) {
167
- factories.set(declaration.id.name, createStepCall);
168
- }
169
- continue;
170
- }
171
- if (!t3.isVariableDeclaration(declaration)) {
172
- continue;
173
- }
174
- for (const declarator of declaration.declarations) {
175
- if (!t3.isIdentifier(declarator.id) || !declarator.init) {
176
- continue;
177
- }
178
- const createStepCall = getReturnedCreateStepCall(declarator.init);
179
- if (createStepCall) {
180
- factories.set(declarator.id.name, createStepCall);
181
- }
182
- }
183
- }
184
- return factories;
117
+ function collectCreateStepFactoryBindings(program) {
118
+ const factories = /* @__PURE__ */ new Map();
119
+ for (const statement of program.body) {
120
+ const declaration = t.isExportNamedDeclaration(statement) ? statement.declaration : statement;
121
+ if (t.isFunctionDeclaration(declaration) && declaration.id) {
122
+ const createStepCall = getReturnedCreateStepCall(declaration);
123
+ if (createStepCall) factories.set(declaration.id.name, createStepCall);
124
+ continue;
125
+ }
126
+ if (!t.isVariableDeclaration(declaration)) continue;
127
+ for (const declarator of declaration.declarations) {
128
+ if (!t.isIdentifier(declarator.id) || !declarator.init) continue;
129
+ const createStepCall = getReturnedCreateStepCall(declarator.init);
130
+ if (createStepCall) factories.set(declarator.id.name, createStepCall);
131
+ }
132
+ }
133
+ return factories;
185
134
  }
186
135
  function getCreateStepCallFromExpression(node, factoryBindings) {
187
- if (!node) {
188
- return null;
189
- }
190
- if (t3.isCallExpression(node)) {
191
- if (isIdentifierNamed(node.callee, "createStep")) {
192
- return node;
193
- }
194
- if (t3.isIdentifier(node.callee)) {
195
- return factoryBindings.get(node.callee.name) ?? null;
196
- }
197
- }
198
- const returnedCreateStepCall = getReturnedCreateStepCall(node);
199
- if (returnedCreateStepCall) {
200
- return returnedCreateStepCall;
201
- }
202
- return null;
136
+ if (!node) return null;
137
+ if (t.isCallExpression(node)) {
138
+ if (isIdentifierNamed(node.callee, "createStep")) return node;
139
+ if (t.isIdentifier(node.callee)) return factoryBindings.get(node.callee.name) ?? null;
140
+ }
141
+ const returnedCreateStepCall = getReturnedCreateStepCall(node);
142
+ if (returnedCreateStepCall) return returnedCreateStepCall;
143
+ return null;
203
144
  }
204
145
  function getCreateStepId(node) {
205
- if (!node || !isCreateStepCall(node)) {
206
- return null;
207
- }
208
- const [config] = node.arguments;
209
- if (!t3.isObjectExpression(config)) {
210
- return null;
211
- }
212
- for (const property of config.properties) {
213
- if (!t3.isObjectProperty(property) && !t3.isObjectMethod(property)) {
214
- continue;
215
- }
216
- if (getObjectPropertyName(property) !== "id") {
217
- continue;
218
- }
219
- const value = t3.isObjectMethod(property) ? null : property.value;
220
- return t3.isStringLiteral(value) ? value.value : null;
221
- }
222
- return null;
146
+ if (!node || !isCreateStepCall(node)) return null;
147
+ const [config] = node.arguments;
148
+ if (!t.isObjectExpression(config)) return null;
149
+ for (const property of config.properties) {
150
+ if (!t.isObjectProperty(property) && !t.isObjectMethod(property)) continue;
151
+ if (getObjectPropertyName(property) !== "id") continue;
152
+ const value = t.isObjectMethod(property) ? null : property.value;
153
+ return t.isStringLiteral(value) ? value.value : null;
154
+ }
155
+ return null;
223
156
  }
224
157
  function shouldCountIdentifierAsReference(parent, key) {
225
- if (!parent) {
226
- return true;
227
- }
228
- if ((t3.isObjectProperty(parent) || t3.isObjectMethod(parent)) && key === "key" && !parent.computed) {
229
- return false;
230
- }
231
- if (t3.isMemberExpression(parent) && key === "property" && !parent.computed) {
232
- return false;
233
- }
234
- if (t3.isVariableDeclarator(parent) && key === "id") {
235
- return false;
236
- }
237
- if ((t3.isFunctionDeclaration(parent) || t3.isFunctionExpression(parent) || t3.isArrowFunctionExpression(parent)) && key === "params") {
238
- return false;
239
- }
240
- if ((t3.isFunctionDeclaration(parent) || t3.isFunctionExpression(parent) || t3.isClassDeclaration(parent)) && key === "id") {
241
- return false;
242
- }
243
- if ((t3.isImportSpecifier(parent) || t3.isImportDefaultSpecifier(parent) || t3.isImportNamespaceSpecifier(parent)) && (key === "local" || key === "imported")) {
244
- return false;
245
- }
246
- if (t3.isExportSpecifier(parent) && key === "exported") {
247
- return false;
248
- }
249
- if (t3.isLabeledStatement(parent) && key === "label") {
250
- return false;
251
- }
252
- if (t3.isCatchClause(parent) && key === "param") {
253
- return false;
254
- }
255
- if (t3.isRestElement(parent) && key === "argument") {
256
- return false;
257
- }
258
- if (t3.isAssignmentPattern(parent) && key === "left") {
259
- return false;
260
- }
261
- if (t3.isTSPropertySignature(parent) || t3.isTSMethodSignature(parent) || t3.isTSInterfaceHeritage(parent)) {
262
- return false;
263
- }
264
- return true;
158
+ if (!parent) return true;
159
+ if ((t.isObjectProperty(parent) || t.isObjectMethod(parent)) && key === "key" && !parent.computed) return false;
160
+ if (t.isMemberExpression(parent) && key === "property" && !parent.computed) return false;
161
+ if (t.isVariableDeclarator(parent) && key === "id") return false;
162
+ if ((t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent) || t.isArrowFunctionExpression(parent)) && key === "params") return false;
163
+ if ((t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent) || t.isClassDeclaration(parent)) && key === "id") return false;
164
+ if ((t.isImportSpecifier(parent) || t.isImportDefaultSpecifier(parent) || t.isImportNamespaceSpecifier(parent)) && (key === "local" || key === "imported")) return false;
165
+ if (t.isExportSpecifier(parent) && key === "exported") return false;
166
+ if (t.isLabeledStatement(parent) && key === "label") return false;
167
+ if (t.isCatchClause(parent) && key === "param") return false;
168
+ if (t.isRestElement(parent) && key === "argument") return false;
169
+ if (t.isAssignmentPattern(parent) && key === "left") return false;
170
+ if (t.isTSPropertySignature(parent) || t.isTSMethodSignature(parent) || t.isTSInterfaceHeritage(parent)) return false;
171
+ return true;
265
172
  }
266
173
  function collectRuntimeReferencedIdentifiers(node) {
267
- const refs = /* @__PURE__ */ new Set();
268
- const visit = (current, parent, key) => {
269
- if (!current) {
270
- return;
271
- }
272
- if (current.type.startsWith("TS")) {
273
- return;
274
- }
275
- if (t3.isIdentifier(current)) {
276
- if (shouldCountIdentifierAsReference(parent, key)) {
277
- refs.add(current.name);
278
- }
279
- return;
280
- }
281
- for (const visitorKey of t3.VISITOR_KEYS[current.type] ?? []) {
282
- const value = current[visitorKey];
283
- if (Array.isArray(value)) {
284
- value.forEach((child) => {
285
- if (t3.isNode(child)) {
286
- visit(child, current, visitorKey);
287
- }
288
- });
289
- continue;
290
- }
291
- if (t3.isNode(value)) {
292
- visit(value, current, visitorKey);
293
- }
294
- }
295
- };
296
- visit(node, null, null);
297
- return refs;
174
+ const refs = /* @__PURE__ */ new Set();
175
+ const visit = (current, parent, key) => {
176
+ if (!current) return;
177
+ if (current.type.startsWith("TS")) return;
178
+ if (t.isIdentifier(current)) {
179
+ if (shouldCountIdentifierAsReference(parent, key)) refs.add(current.name);
180
+ return;
181
+ }
182
+ for (const visitorKey of t.VISITOR_KEYS[current.type] ?? []) {
183
+ const value = current[visitorKey];
184
+ if (Array.isArray(value)) {
185
+ value.forEach((child) => {
186
+ if (t.isNode(child)) visit(child, current, visitorKey);
187
+ });
188
+ continue;
189
+ }
190
+ if (t.isNode(value)) visit(value, current, visitorKey);
191
+ }
192
+ };
193
+ visit(node, null, null);
194
+ return refs;
298
195
  }
299
196
  function pruneUnusedTopLevelBindings(statements) {
300
- const bindings = /* @__PURE__ */ new Map();
301
- const liveStatements = /* @__PURE__ */ new Set();
302
- const queue = [];
303
- const markLive = (statementIndex) => {
304
- if (liveStatements.has(statementIndex)) {
305
- return;
306
- }
307
- liveStatements.add(statementIndex);
308
- queue.push(statementIndex);
309
- };
310
- statements.forEach((statement, statementIndex) => {
311
- if (t3.isImportDeclaration(statement)) {
312
- for (const specifier of statement.specifiers) {
313
- bindings.set(specifier.local.name, { refs: /* @__PURE__ */ new Set(), statementIndex });
314
- }
315
- return;
316
- }
317
- if (t3.isVariableDeclaration(statement)) {
318
- for (const declaration of statement.declarations) {
319
- if (t3.isIdentifier(declaration.id)) {
320
- bindings.set(declaration.id.name, {
321
- refs: declaration.init ? collectRuntimeReferencedIdentifiers(declaration.init) : /* @__PURE__ */ new Set(),
322
- statementIndex
323
- });
324
- }
325
- }
326
- return;
327
- }
328
- if (t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration)) {
329
- for (const declaration of statement.declaration.declarations) {
330
- if (t3.isIdentifier(declaration.id)) {
331
- bindings.set(declaration.id.name, {
332
- refs: declaration.init ? collectRuntimeReferencedIdentifiers(declaration.init) : /* @__PURE__ */ new Set(),
333
- statementIndex
334
- });
335
- }
336
- }
337
- markLive(statementIndex);
338
- return;
339
- }
340
- markLive(statementIndex);
341
- });
342
- while (queue.length > 0) {
343
- const statementIndex = queue.pop();
344
- const statement = statements[statementIndex];
345
- if (!statement) {
346
- continue;
347
- }
348
- const refs = /* @__PURE__ */ new Set();
349
- if (t3.isImportDeclaration(statement)) {
350
- continue;
351
- }
352
- if (t3.isVariableDeclaration(statement)) {
353
- for (const declaration of statement.declarations) {
354
- if (declaration.init) {
355
- for (const ref of collectRuntimeReferencedIdentifiers(declaration.init)) {
356
- refs.add(ref);
357
- }
358
- }
359
- }
360
- } else if (t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration)) {
361
- for (const declaration of statement.declaration.declarations) {
362
- if (declaration.init) {
363
- for (const ref of collectRuntimeReferencedIdentifiers(declaration.init)) {
364
- refs.add(ref);
365
- }
366
- }
367
- }
368
- } else {
369
- for (const ref of collectRuntimeReferencedIdentifiers(statement)) {
370
- refs.add(ref);
371
- }
372
- }
373
- for (const ref of refs) {
374
- const binding = bindings.get(ref);
375
- if (binding) {
376
- markLive(binding.statementIndex);
377
- }
378
- }
379
- }
380
- const prunedStatements = [];
381
- statements.forEach((statement, statementIndex) => {
382
- if (!liveStatements.has(statementIndex)) {
383
- return;
384
- }
385
- if (t3.isImportDeclaration(statement)) {
386
- const specifiers = statement.specifiers.filter(
387
- (specifier) => liveStatements.has(bindings.get(specifier.local.name)?.statementIndex ?? -1)
388
- );
389
- if (specifiers.length > 0) {
390
- prunedStatements.push(t3.importDeclaration(specifiers, statement.source));
391
- }
392
- return;
393
- }
394
- if (t3.isVariableDeclaration(statement)) {
395
- const declarations = statement.declarations.filter(
396
- (declaration) => !t3.isIdentifier(declaration.id) || liveStatements.has(bindings.get(declaration.id.name)?.statementIndex ?? -1)
397
- );
398
- if (declarations.length > 0) {
399
- prunedStatements.push(t3.variableDeclaration(statement.kind, declarations));
400
- }
401
- return;
402
- }
403
- if (t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration)) {
404
- const declarations = statement.declaration.declarations.filter(
405
- (declaration) => !t3.isIdentifier(declaration.id) || liveStatements.has(bindings.get(declaration.id.name)?.statementIndex ?? -1)
406
- );
407
- if (declarations.length > 0) {
408
- prunedStatements.push(
409
- t3.exportNamedDeclaration(t3.variableDeclaration(statement.declaration.kind, declarations))
410
- );
411
- }
412
- return;
413
- }
414
- prunedStatements.push(statement);
415
- });
416
- return prunedStatements;
197
+ const bindings = /* @__PURE__ */ new Map();
198
+ const liveStatements = /* @__PURE__ */ new Set();
199
+ const queue = [];
200
+ const markLive = (statementIndex) => {
201
+ if (liveStatements.has(statementIndex)) return;
202
+ liveStatements.add(statementIndex);
203
+ queue.push(statementIndex);
204
+ };
205
+ statements.forEach((statement, statementIndex) => {
206
+ if (t.isImportDeclaration(statement)) {
207
+ for (const specifier of statement.specifiers) bindings.set(specifier.local.name, {
208
+ refs: /* @__PURE__ */ new Set(),
209
+ statementIndex
210
+ });
211
+ return;
212
+ }
213
+ if (t.isVariableDeclaration(statement)) {
214
+ for (const declaration of statement.declarations) if (t.isIdentifier(declaration.id)) bindings.set(declaration.id.name, {
215
+ refs: declaration.init ? collectRuntimeReferencedIdentifiers(declaration.init) : /* @__PURE__ */ new Set(),
216
+ statementIndex
217
+ });
218
+ return;
219
+ }
220
+ if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
221
+ for (const declaration of statement.declaration.declarations) if (t.isIdentifier(declaration.id)) bindings.set(declaration.id.name, {
222
+ refs: declaration.init ? collectRuntimeReferencedIdentifiers(declaration.init) : /* @__PURE__ */ new Set(),
223
+ statementIndex
224
+ });
225
+ markLive(statementIndex);
226
+ return;
227
+ }
228
+ markLive(statementIndex);
229
+ });
230
+ while (queue.length > 0) {
231
+ const statement = statements[queue.pop()];
232
+ if (!statement) continue;
233
+ const refs = /* @__PURE__ */ new Set();
234
+ if (t.isImportDeclaration(statement)) continue;
235
+ if (t.isVariableDeclaration(statement)) {
236
+ for (const declaration of statement.declarations) if (declaration.init) for (const ref of collectRuntimeReferencedIdentifiers(declaration.init)) refs.add(ref);
237
+ } else if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
238
+ for (const declaration of statement.declaration.declarations) if (declaration.init) for (const ref of collectRuntimeReferencedIdentifiers(declaration.init)) refs.add(ref);
239
+ } else for (const ref of collectRuntimeReferencedIdentifiers(statement)) refs.add(ref);
240
+ for (const ref of refs) {
241
+ const binding = bindings.get(ref);
242
+ if (binding) markLive(binding.statementIndex);
243
+ }
244
+ }
245
+ const prunedStatements = [];
246
+ statements.forEach((statement, statementIndex) => {
247
+ if (!liveStatements.has(statementIndex)) return;
248
+ if (t.isImportDeclaration(statement)) {
249
+ const specifiers = statement.specifiers.filter((specifier) => liveStatements.has(bindings.get(specifier.local.name)?.statementIndex ?? -1));
250
+ if (specifiers.length > 0) prunedStatements.push(t.importDeclaration(specifiers, statement.source));
251
+ return;
252
+ }
253
+ if (t.isVariableDeclaration(statement)) {
254
+ const declarations = statement.declarations.filter((declaration) => !t.isIdentifier(declaration.id) || liveStatements.has(bindings.get(declaration.id.name)?.statementIndex ?? -1));
255
+ if (declarations.length > 0) prunedStatements.push(t.variableDeclaration(statement.kind, declarations));
256
+ return;
257
+ }
258
+ if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
259
+ const declarations = statement.declaration.declarations.filter((declaration) => !t.isIdentifier(declaration.id) || liveStatements.has(bindings.get(declaration.id.name)?.statementIndex ?? -1));
260
+ if (declarations.length > 0) prunedStatements.push(t.exportNamedDeclaration(t.variableDeclaration(statement.declaration.kind, declarations)));
261
+ return;
262
+ }
263
+ prunedStatements.push(statement);
264
+ });
265
+ return prunedStatements;
417
266
  }
418
-
419
- // src/transforms/activities.ts
267
+ //#endregion
268
+ //#region src/transforms/activities.ts
420
269
  function normalizeImportPath(importPath, extension) {
421
- const normalizedPath = importPath.split(path.sep).join("/");
422
- const pathWithExtension = extension === ".mjs" || extension === ".cjs" ? normalizedPath : normalizedPath.replace(/\.[cm]?[jt]sx?$/, "");
423
- return pathWithExtension.startsWith(".") ? pathWithExtension : `./${pathWithExtension}`;
270
+ const normalizedPath = importPath.split(path.sep).join("/");
271
+ const pathWithExtension = extension === ".mjs" || extension === ".cjs" ? normalizedPath : normalizedPath.replace(/\.[cm]?[jt]sx?$/, "");
272
+ return pathWithExtension.startsWith(".") ? pathWithExtension : `./${pathWithExtension}`;
424
273
  }
425
274
  function rebaseModulePath(modulePath, sourceFilePath, outputFilePath) {
426
- if (!modulePath.startsWith(".")) {
427
- return modulePath;
428
- }
429
- const resolvedPath = path.resolve(path.dirname(sourceFilePath), modulePath);
430
- const relativePath = path.relative(path.dirname(outputFilePath), resolvedPath);
431
- return normalizeImportPath(relativePath, path.extname(resolvedPath));
275
+ if (!modulePath.startsWith(".")) return modulePath;
276
+ const resolvedPath = path.resolve(path.dirname(sourceFilePath), modulePath);
277
+ return normalizeImportPath(path.relative(path.dirname(outputFilePath), resolvedPath), path.extname(resolvedPath));
432
278
  }
433
279
  function collectWorkflowBindingNames(ast) {
434
- const workflowNames = /* @__PURE__ */ new Set();
435
- for (const statement of ast.program.body) {
436
- if (!t3.isVariableDeclaration(statement) && !(t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration))) {
437
- continue;
438
- }
439
- const declarationStatement = t3.isVariableDeclaration(statement) ? statement : statement.declaration;
440
- for (const declaration of declarationStatement.declarations) {
441
- if (t3.isIdentifier(declaration.id) && declaration.init && hasCreateWorkflowCall(declaration.init)) {
442
- workflowNames.add(declaration.id.name);
443
- }
444
- }
445
- }
446
- return workflowNames;
280
+ const workflowNames = /* @__PURE__ */ new Set();
281
+ for (const statement of ast.program.body) {
282
+ if (!t.isVariableDeclaration(statement) && !(t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration))) continue;
283
+ const declarationStatement = t.isVariableDeclaration(statement) ? statement : statement.declaration;
284
+ for (const declaration of declarationStatement.declarations) if (t.isIdentifier(declaration.id) && declaration.init && hasCreateWorkflowCall(declaration.init)) workflowNames.add(declaration.id.name);
285
+ }
286
+ return workflowNames;
447
287
  }
448
288
  function isMastraDeclaration(declaration) {
449
- return t3.isIdentifier(declaration.id) && declaration.id.name === "mastra";
289
+ return t.isIdentifier(declaration.id) && declaration.id.name === "mastra";
450
290
  }
451
291
  function removeStrippedReferencesFromMastraInitializer(init, strippedNames) {
452
- const clonedInit = t3.cloneNode(init, true);
453
- if (!t3.isNewExpression(clonedInit) && !t3.isCallExpression(clonedInit)) {
454
- return clonedInit;
455
- }
456
- const config = clonedInit.arguments[0];
457
- if (!t3.isObjectExpression(config)) {
458
- return clonedInit;
459
- }
460
- config.properties = config.properties.filter((property) => !nodeReferencesName(property, strippedNames));
461
- return clonedInit;
292
+ const clonedInit = t.cloneNode(init, true);
293
+ if (!t.isNewExpression(clonedInit) && !t.isCallExpression(clonedInit)) return clonedInit;
294
+ const config = clonedInit.arguments[0];
295
+ if (!t.isObjectExpression(config)) return clonedInit;
296
+ config.properties = config.properties.filter((property) => !nodeReferencesName(property, strippedNames));
297
+ return clonedInit;
462
298
  }
463
299
  function createPreservedDeclaration(declaration, strippedNames) {
464
- if (!isMastraDeclaration(declaration) || !declaration.init) {
465
- return t3.cloneNode(declaration, true);
466
- }
467
- return t3.variableDeclarator(
468
- t3.cloneNode(declaration.id, true),
469
- removeStrippedReferencesFromMastraInitializer(declaration.init, strippedNames)
470
- );
300
+ if (!isMastraDeclaration(declaration) || !declaration.init) return t.cloneNode(declaration, true);
301
+ return t.variableDeclarator(t.cloneNode(declaration.id, true), removeStrippedReferencesFromMastraInitializer(declaration.init, strippedNames));
471
302
  }
472
303
  function hasLocalMastraBinding(ast) {
473
- return ast.program.body.some((statement) => {
474
- const declaration = t3.isExportNamedDeclaration(statement) ? statement.declaration : statement;
475
- if (!t3.isVariableDeclaration(declaration)) {
476
- return false;
477
- }
478
- return declaration.declarations.some((declarator) => t3.isIdentifier(declarator.id, { name: "mastra" }));
479
- });
304
+ return ast.program.body.some((statement) => {
305
+ const declaration = t.isExportNamedDeclaration(statement) ? statement.declaration : statement;
306
+ if (!t.isVariableDeclaration(declaration)) return false;
307
+ return declaration.declarations.some((declarator) => t.isIdentifier(declarator.id, { name: "mastra" }));
308
+ });
480
309
  }
481
310
  function createTemporalActivitiesHelperStatements(mastraImportPath, hasMastraBinding) {
482
- const helperSource = hasMastraBinding ? `
311
+ return parse(mastraImportPath ? `
312
+ function createStep(args) {
313
+ return async (params) => {
314
+ const { mastra } = await import(${JSON.stringify(mastraImportPath)});
315
+ return args.execute({ ...params, mastra });
316
+ };
317
+ }
318
+ ` : hasMastraBinding ? `
483
319
  function createStep(args) {
484
320
  return async (params) => {
485
321
  return args.execute({ ...params, mastra });
@@ -491,947 +327,711 @@ function createTemporalActivitiesHelperStatements(mastraImportPath, hasMastraBin
491
327
  return args.execute(params);
492
328
  };
493
329
  }
494
- `;
495
- return parse(helperSource, {
496
- sourceType: "module",
497
- plugins: parserPlugins
498
- }).program.body;
330
+ `, {
331
+ sourceType: "module",
332
+ plugins: parserPlugins
333
+ }).program.body;
499
334
  }
500
335
  async function buildTemporalActivitiesModule(entryFile, outputDirectory, outputFileName) {
501
- const activityBindings = [];
502
- const seenActivityBindingNames = /* @__PURE__ */ new Set();
503
- const addActivityBinding = (exportName, call) => {
504
- const stepId = getCreateStepId(call);
505
- if (!stepId || seenActivityBindingNames.has(exportName)) {
506
- return;
507
- }
508
- seenActivityBindingNames.add(exportName);
509
- activityBindings.push({ exportName, stepId });
510
- };
511
- const bundle = await rollup({
512
- input: entryFile,
513
- treeshake: "smallest",
514
- logLevel: "silent",
515
- plugins: [
516
- {
517
- name: "temporal-workflow-transform",
518
- transform(code, id) {
519
- const ast = parse(code, {
520
- sourceType: "module",
521
- plugins: parserPlugins,
522
- sourceFilename: id
523
- });
524
- const statements = [];
525
- const seenNames = /* @__PURE__ */ new Set();
526
- const strippedNames = /* @__PURE__ */ new Set();
527
- const workflowBindingNames = collectWorkflowBindingNames(ast);
528
- const stepFactoryBindings = collectCreateStepFactoryBindings(ast.program);
529
- const sourceFilePath = id;
530
- const hasMastraBinding = hasLocalMastraBinding(ast);
531
- let helperInserted = false;
532
- const ensureHelperInserted = () => {
533
- if (helperInserted) {
534
- return;
535
- }
536
- statements.push(...createTemporalActivitiesHelperStatements(null, hasMastraBinding));
537
- helperInserted = true;
538
- };
539
- for (const statement of ast.program.body) {
540
- if (t3.isImportDeclaration(statement)) {
541
- if (statement.source.value === "@mastra/core/workflows") {
542
- const retainedSpecifiers = statement.specifiers.filter(
543
- (specifier) => !(t3.isImportSpecifier(specifier) && t3.isIdentifier(specifier.imported) && (specifier.imported.name === "createStep" || specifier.imported.name === "createWorkflow"))
544
- );
545
- if (retainedSpecifiers.length > 0) {
546
- statements.push(t3.importDeclaration(retainedSpecifiers, t3.stringLiteral(statement.source.value)));
547
- }
548
- continue;
549
- }
550
- if (isTemporalHelperModule(statement.source.value) || isStrippedExternalModule(statement.source.value)) {
551
- for (const name of collectImportedNames(statement)) {
552
- strippedNames.add(name);
553
- }
554
- continue;
555
- }
556
- const rewrittenSource = rebaseModulePath(statement.source.value, sourceFilePath, id);
557
- if (rewrittenSource === statement.source.value) {
558
- statements.push(statement);
559
- } else {
560
- statements.push(
561
- t3.importDeclaration(
562
- statement.specifiers.map((specifier) => t3.cloneNode(specifier, true)),
563
- t3.stringLiteral(rewrittenSource)
564
- )
565
- );
566
- }
567
- continue;
568
- }
569
- if (t3.isFunctionDeclaration(statement) || t3.isClassDeclaration(statement) || t3.isTSTypeAliasDeclaration(statement) || t3.isTSInterfaceDeclaration(statement) || t3.isTSEnumDeclaration(statement)) {
570
- ensureHelperInserted();
571
- statements.push(statement);
572
- continue;
573
- }
574
- if (t3.isExpressionStatement(statement) && nodeReferencesName(statement, strippedNames)) {
575
- continue;
576
- }
577
- ensureHelperInserted();
578
- if (t3.isVariableDeclaration(statement)) {
579
- const declarations = [];
580
- for (const declaration of statement.declarations) {
581
- if (isWorkflowHelperDestructure(declaration)) {
582
- continue;
583
- }
584
- if (declaration.init && nodeReferencesName(declaration.init, strippedNames) && !isMastraDeclaration(declaration)) {
585
- if (t3.isIdentifier(declaration.id)) {
586
- strippedNames.add(declaration.id.name);
587
- }
588
- continue;
589
- }
590
- if (!t3.isIdentifier(declaration.id) || !declaration.init) {
591
- declarations.push(createPreservedDeclaration(declaration, strippedNames));
592
- continue;
593
- }
594
- const createStepCall = getCreateStepCallFromExpression(declaration.init, stepFactoryBindings);
595
- if (createStepCall) {
596
- const isFactoryCall = t3.isCallExpression(declaration.init) && t3.isIdentifier(declaration.init.callee) && stepFactoryBindings.has(declaration.init.callee.name);
597
- if (isFactoryCall) {
598
- seenNames.add(declaration.id.name);
599
- addActivityBinding(declaration.id.name, createStepCall);
600
- statements.push(
601
- t3.exportNamedDeclaration(t3.variableDeclaration(statement.kind, [t3.cloneNode(declaration, true)]))
602
- );
603
- continue;
604
- }
605
- if (isCreateStepCall(declaration.init)) {
606
- seenNames.add(declaration.id.name);
607
- addActivityBinding(declaration.id.name, createStepCall);
608
- statements.push(createExportedStepStatement(declaration.id.name, createStepCall));
609
- continue;
610
- }
611
- }
612
- if (hasCreateWorkflowCall(declaration.init)) {
613
- workflowBindingNames.add(declaration.id.name);
614
- strippedNames.add(declaration.id.name);
615
- collectInlineCreateSteps(declaration.init, seenNames, statements, addActivityBinding);
616
- continue;
617
- }
618
- declarations.push(createPreservedDeclaration(declaration, strippedNames));
619
- }
620
- if (declarations.length > 0) {
621
- statements.push(
622
- t3.variableDeclaration(
623
- statement.kind,
624
- declarations.map((declaration) => t3.cloneNode(declaration, true))
625
- )
626
- );
627
- }
628
- continue;
629
- }
630
- if (t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration)) {
631
- const exportedDeclarations = [];
632
- const localDeclarations = [];
633
- for (const declaration of statement.declaration.declarations) {
634
- if (isWorkflowHelperDestructure(declaration)) {
635
- continue;
636
- }
637
- if (declaration.init && nodeReferencesName(declaration.init, strippedNames) && !isMastraDeclaration(declaration)) {
638
- if (t3.isIdentifier(declaration.id)) {
639
- strippedNames.add(declaration.id.name);
640
- }
641
- continue;
642
- }
643
- if (!t3.isIdentifier(declaration.id) || !declaration.init) {
644
- exportedDeclarations.push(createPreservedDeclaration(declaration, strippedNames));
645
- continue;
646
- }
647
- const createStepCall = getCreateStepCallFromExpression(declaration.init, stepFactoryBindings);
648
- if (createStepCall) {
649
- const isFactoryCall = t3.isCallExpression(declaration.init) && t3.isIdentifier(declaration.init.callee) && stepFactoryBindings.has(declaration.init.callee.name);
650
- if (isFactoryCall) {
651
- seenNames.add(declaration.id.name);
652
- addActivityBinding(declaration.id.name, createStepCall);
653
- exportedDeclarations.push(createPreservedDeclaration(declaration, strippedNames));
654
- continue;
655
- }
656
- if (isCreateStepCall(declaration.init)) {
657
- seenNames.add(declaration.id.name);
658
- addActivityBinding(declaration.id.name, createStepCall);
659
- statements.push(createExportedStepStatement(declaration.id.name, createStepCall));
660
- continue;
661
- }
662
- }
663
- if (hasCreateWorkflowCall(declaration.init)) {
664
- workflowBindingNames.add(declaration.id.name);
665
- strippedNames.add(declaration.id.name);
666
- collectInlineCreateSteps(declaration.init, seenNames, statements, addActivityBinding);
667
- continue;
668
- }
669
- if (declaration.id.name === "mastra") {
670
- localDeclarations.push(createPreservedDeclaration(declaration, strippedNames));
671
- continue;
672
- }
673
- exportedDeclarations.push(createPreservedDeclaration(declaration, strippedNames));
674
- }
675
- if (localDeclarations.length > 0) {
676
- statements.push(
677
- t3.variableDeclaration(
678
- statement.declaration.kind,
679
- localDeclarations.map((declaration) => t3.cloneNode(declaration, true))
680
- )
681
- );
682
- }
683
- if (exportedDeclarations.length > 0) {
684
- statements.push(
685
- t3.exportNamedDeclaration(
686
- t3.variableDeclaration(
687
- statement.declaration.kind,
688
- exportedDeclarations.map((declaration) => t3.cloneNode(declaration, true))
689
- )
690
- )
691
- );
692
- }
693
- continue;
694
- }
695
- if (t3.isExpressionStatement(statement)) {
696
- if (nodeReferencesName(statement, workflowBindingNames) || nodeReferencesName(statement, strippedNames)) {
697
- collectInlineCreateSteps(statement, seenNames, statements, addActivityBinding);
698
- continue;
699
- }
700
- collectInlineCreateSteps(statement, seenNames, statements, addActivityBinding);
701
- continue;
702
- }
703
- if (t3.isExportNamedDeclaration(statement)) {
704
- if (t3.isFunctionDeclaration(statement.declaration) || t3.isClassDeclaration(statement.declaration) || t3.isTSTypeAliasDeclaration(statement.declaration) || t3.isTSInterfaceDeclaration(statement.declaration) || t3.isTSEnumDeclaration(statement.declaration)) {
705
- ensureHelperInserted();
706
- statements.push(statement);
707
- continue;
708
- }
709
- if (statement.declaration == null && statement.source == null) {
710
- const retainedSpecifiers = statement.specifiers.filter(
711
- (specifier) => t3.isExportSpecifier(specifier) && t3.isIdentifier(specifier.local) && specifier.local.name !== "mastra" && !workflowBindingNames.has(specifier.local.name) && !seenNames.has(specifier.local.name)
712
- );
713
- if (retainedSpecifiers.length > 0) {
714
- statements.push(t3.exportNamedDeclaration(null, retainedSpecifiers));
715
- }
716
- continue;
717
- }
718
- if (statement.declaration == null && statement.source) {
719
- const mastraSpecifiers = statement.specifiers.filter(
720
- (specifier) => t3.isExportSpecifier(specifier) && t3.isIdentifier(specifier.exported, { name: "mastra" }) && t3.isIdentifier(specifier.local, { name: "mastra" })
721
- );
722
- if (mastraSpecifiers.length > 0) {
723
- statements.push(
724
- t3.importDeclaration(
725
- [t3.importSpecifier(t3.identifier("mastra"), t3.identifier("mastra"))],
726
- t3.stringLiteral(rebaseModulePath(statement.source.value, sourceFilePath, id))
727
- )
728
- );
729
- }
730
- continue;
731
- }
732
- collectInlineCreateSteps(statement, seenNames, statements, addActivityBinding);
733
- continue;
734
- }
735
- if (t3.isExportDefaultDeclaration(statement)) {
736
- if (t3.isIdentifier(statement.declaration) && workflowBindingNames.has(statement.declaration.name)) {
737
- continue;
738
- }
739
- collectInlineCreateSteps(statement, seenNames, statements, addActivityBinding);
740
- continue;
741
- }
742
- statements.push(statement);
743
- }
744
- ensureHelperInserted();
745
- const transformedSource = generate(t3.file(t3.program(pruneUnusedTopLevelBindings(statements), [], "module")), {
746
- sourceMaps: true
747
- });
748
- return {
749
- code: transformedSource.code,
750
- map: transformedSource.map ? { ...transformedSource.map, file: transformedSource.map.file ?? void 0 } : void 0
751
- };
752
- }
753
- }
754
- ]
755
- });
756
- try {
757
- const baseName = basename(outputFileName);
758
- const { output } = await bundle.write({
759
- dir: outputDirectory,
760
- entryFileNames: outputFileName,
761
- chunkFileNames: `${baseName}-[hash].mjs`,
762
- format: "esm",
763
- sourcemap: "inline"
764
- });
765
- return {
766
- outputPath: join(outputDirectory, output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName),
767
- activityBindings
768
- };
769
- } finally {
770
- await bundle.close();
771
- }
336
+ const activityBindings = [];
337
+ const seenActivityBindingNames = /* @__PURE__ */ new Set();
338
+ const addActivityBinding = (exportName, call) => {
339
+ const stepId = getCreateStepId(call);
340
+ if (!stepId || seenActivityBindingNames.has(exportName)) return;
341
+ seenActivityBindingNames.add(exportName);
342
+ activityBindings.push({
343
+ exportName,
344
+ stepId
345
+ });
346
+ };
347
+ const bundle = await rollup({
348
+ input: entryFile,
349
+ treeshake: "smallest",
350
+ logLevel: "silent",
351
+ plugins: [{
352
+ name: "temporal-workflow-transform",
353
+ transform(code, id) {
354
+ const ast = parse(code, {
355
+ sourceType: "module",
356
+ plugins: parserPlugins,
357
+ sourceFilename: id
358
+ });
359
+ const statements = [];
360
+ const seenNames = /* @__PURE__ */ new Set();
361
+ const strippedNames = /* @__PURE__ */ new Set();
362
+ const workflowBindingNames = collectWorkflowBindingNames(ast);
363
+ const stepFactoryBindings = collectCreateStepFactoryBindings(ast.program);
364
+ const sourceFilePath = id;
365
+ const hasMastraBinding = hasLocalMastraBinding(ast);
366
+ let helperInserted = false;
367
+ const ensureHelperInserted = () => {
368
+ if (helperInserted) return;
369
+ statements.push(...createTemporalActivitiesHelperStatements(null, hasMastraBinding));
370
+ helperInserted = true;
371
+ };
372
+ for (const statement of ast.program.body) {
373
+ if (t.isImportDeclaration(statement)) {
374
+ if (statement.source.value === "@mastra/core/workflows") {
375
+ const retainedSpecifiers = statement.specifiers.filter((specifier) => !(t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported) && (specifier.imported.name === "createStep" || specifier.imported.name === "createWorkflow")));
376
+ if (retainedSpecifiers.length > 0) statements.push(t.importDeclaration(retainedSpecifiers, t.stringLiteral(statement.source.value)));
377
+ continue;
378
+ }
379
+ if (isTemporalHelperModule(statement.source.value) || isStrippedExternalModule(statement.source.value)) {
380
+ for (const name of collectImportedNames(statement)) strippedNames.add(name);
381
+ continue;
382
+ }
383
+ const rewrittenSource = rebaseModulePath(statement.source.value, sourceFilePath, id);
384
+ if (rewrittenSource === statement.source.value) statements.push(statement);
385
+ else statements.push(t.importDeclaration(statement.specifiers.map((specifier) => t.cloneNode(specifier, true)), t.stringLiteral(rewrittenSource)));
386
+ continue;
387
+ }
388
+ if (t.isFunctionDeclaration(statement) || t.isClassDeclaration(statement) || t.isTSTypeAliasDeclaration(statement) || t.isTSInterfaceDeclaration(statement) || t.isTSEnumDeclaration(statement)) {
389
+ ensureHelperInserted();
390
+ statements.push(statement);
391
+ continue;
392
+ }
393
+ if (t.isExpressionStatement(statement) && nodeReferencesName(statement, strippedNames)) continue;
394
+ ensureHelperInserted();
395
+ if (t.isVariableDeclaration(statement)) {
396
+ const declarations = [];
397
+ for (const declaration of statement.declarations) {
398
+ if (isWorkflowHelperDestructure(declaration)) continue;
399
+ if (declaration.init && nodeReferencesName(declaration.init, strippedNames) && !isMastraDeclaration(declaration)) {
400
+ if (t.isIdentifier(declaration.id)) strippedNames.add(declaration.id.name);
401
+ continue;
402
+ }
403
+ if (!t.isIdentifier(declaration.id) || !declaration.init) {
404
+ declarations.push(createPreservedDeclaration(declaration, strippedNames));
405
+ continue;
406
+ }
407
+ const createStepCall = getCreateStepCallFromExpression(declaration.init, stepFactoryBindings);
408
+ if (createStepCall) {
409
+ if (t.isCallExpression(declaration.init) && t.isIdentifier(declaration.init.callee) && stepFactoryBindings.has(declaration.init.callee.name)) {
410
+ seenNames.add(declaration.id.name);
411
+ addActivityBinding(declaration.id.name, createStepCall);
412
+ statements.push(t.exportNamedDeclaration(t.variableDeclaration(statement.kind, [t.cloneNode(declaration, true)])));
413
+ continue;
414
+ }
415
+ if (isCreateStepCall(declaration.init)) {
416
+ seenNames.add(declaration.id.name);
417
+ addActivityBinding(declaration.id.name, createStepCall);
418
+ statements.push(createExportedStepStatement(declaration.id.name, createStepCall));
419
+ continue;
420
+ }
421
+ }
422
+ if (hasCreateWorkflowCall(declaration.init)) {
423
+ workflowBindingNames.add(declaration.id.name);
424
+ strippedNames.add(declaration.id.name);
425
+ collectInlineCreateSteps(declaration.init, seenNames, statements, addActivityBinding);
426
+ continue;
427
+ }
428
+ declarations.push(createPreservedDeclaration(declaration, strippedNames));
429
+ }
430
+ if (declarations.length > 0) statements.push(t.variableDeclaration(statement.kind, declarations.map((declaration) => t.cloneNode(declaration, true))));
431
+ continue;
432
+ }
433
+ if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
434
+ const exportedDeclarations = [];
435
+ const localDeclarations = [];
436
+ for (const declaration of statement.declaration.declarations) {
437
+ if (isWorkflowHelperDestructure(declaration)) continue;
438
+ if (declaration.init && nodeReferencesName(declaration.init, strippedNames) && !isMastraDeclaration(declaration)) {
439
+ if (t.isIdentifier(declaration.id)) strippedNames.add(declaration.id.name);
440
+ continue;
441
+ }
442
+ if (!t.isIdentifier(declaration.id) || !declaration.init) {
443
+ exportedDeclarations.push(createPreservedDeclaration(declaration, strippedNames));
444
+ continue;
445
+ }
446
+ const createStepCall = getCreateStepCallFromExpression(declaration.init, stepFactoryBindings);
447
+ if (createStepCall) {
448
+ if (t.isCallExpression(declaration.init) && t.isIdentifier(declaration.init.callee) && stepFactoryBindings.has(declaration.init.callee.name)) {
449
+ seenNames.add(declaration.id.name);
450
+ addActivityBinding(declaration.id.name, createStepCall);
451
+ exportedDeclarations.push(createPreservedDeclaration(declaration, strippedNames));
452
+ continue;
453
+ }
454
+ if (isCreateStepCall(declaration.init)) {
455
+ seenNames.add(declaration.id.name);
456
+ addActivityBinding(declaration.id.name, createStepCall);
457
+ statements.push(createExportedStepStatement(declaration.id.name, createStepCall));
458
+ continue;
459
+ }
460
+ }
461
+ if (hasCreateWorkflowCall(declaration.init)) {
462
+ workflowBindingNames.add(declaration.id.name);
463
+ strippedNames.add(declaration.id.name);
464
+ collectInlineCreateSteps(declaration.init, seenNames, statements, addActivityBinding);
465
+ continue;
466
+ }
467
+ if (declaration.id.name === "mastra") {
468
+ localDeclarations.push(createPreservedDeclaration(declaration, strippedNames));
469
+ continue;
470
+ }
471
+ exportedDeclarations.push(createPreservedDeclaration(declaration, strippedNames));
472
+ }
473
+ if (localDeclarations.length > 0) statements.push(t.variableDeclaration(statement.declaration.kind, localDeclarations.map((declaration) => t.cloneNode(declaration, true))));
474
+ if (exportedDeclarations.length > 0) statements.push(t.exportNamedDeclaration(t.variableDeclaration(statement.declaration.kind, exportedDeclarations.map((declaration) => t.cloneNode(declaration, true)))));
475
+ continue;
476
+ }
477
+ if (t.isExpressionStatement(statement)) {
478
+ if (nodeReferencesName(statement, workflowBindingNames) || nodeReferencesName(statement, strippedNames)) {
479
+ collectInlineCreateSteps(statement, seenNames, statements, addActivityBinding);
480
+ continue;
481
+ }
482
+ collectInlineCreateSteps(statement, seenNames, statements, addActivityBinding);
483
+ continue;
484
+ }
485
+ if (t.isExportNamedDeclaration(statement)) {
486
+ if (t.isFunctionDeclaration(statement.declaration) || t.isClassDeclaration(statement.declaration) || t.isTSTypeAliasDeclaration(statement.declaration) || t.isTSInterfaceDeclaration(statement.declaration) || t.isTSEnumDeclaration(statement.declaration)) {
487
+ ensureHelperInserted();
488
+ statements.push(statement);
489
+ continue;
490
+ }
491
+ if (statement.declaration == null && statement.source == null) {
492
+ const retainedSpecifiers = statement.specifiers.filter((specifier) => t.isExportSpecifier(specifier) && t.isIdentifier(specifier.local) && specifier.local.name !== "mastra" && !workflowBindingNames.has(specifier.local.name) && !seenNames.has(specifier.local.name));
493
+ if (retainedSpecifiers.length > 0) statements.push(t.exportNamedDeclaration(null, retainedSpecifiers));
494
+ continue;
495
+ }
496
+ if (statement.declaration == null && statement.source) {
497
+ if (statement.specifiers.filter((specifier) => t.isExportSpecifier(specifier) && t.isIdentifier(specifier.exported, { name: "mastra" }) && t.isIdentifier(specifier.local, { name: "mastra" })).length > 0) statements.push(t.importDeclaration([t.importSpecifier(t.identifier("mastra"), t.identifier("mastra"))], t.stringLiteral(rebaseModulePath(statement.source.value, sourceFilePath, id))));
498
+ continue;
499
+ }
500
+ collectInlineCreateSteps(statement, seenNames, statements, addActivityBinding);
501
+ continue;
502
+ }
503
+ if (t.isExportDefaultDeclaration(statement)) {
504
+ if (t.isIdentifier(statement.declaration) && workflowBindingNames.has(statement.declaration.name)) continue;
505
+ collectInlineCreateSteps(statement, seenNames, statements, addActivityBinding);
506
+ continue;
507
+ }
508
+ statements.push(statement);
509
+ }
510
+ ensureHelperInserted();
511
+ const transformedSource = generate(t.file(t.program(pruneUnusedTopLevelBindings(statements), [], "module")), { sourceMaps: true });
512
+ return {
513
+ code: transformedSource.code,
514
+ map: transformedSource.map ? {
515
+ ...transformedSource.map,
516
+ file: transformedSource.map.file ?? void 0
517
+ } : void 0
518
+ };
519
+ }
520
+ }]
521
+ });
522
+ try {
523
+ const baseName = basename(outputFileName);
524
+ const { output } = await bundle.write({
525
+ dir: outputDirectory,
526
+ entryFileNames: outputFileName,
527
+ chunkFileNames: `${baseName}-[hash].mjs`,
528
+ format: "esm",
529
+ sourcemap: "inline"
530
+ });
531
+ return {
532
+ outputPath: join(outputDirectory, output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName),
533
+ activityBindings
534
+ };
535
+ } finally {
536
+ await bundle.close();
537
+ }
772
538
  }
539
+ //#endregion
540
+ //#region src/transforms/workflows.ts
541
+ /**
542
+ * Temporal workflow types must be static so the loader can deterministically map
543
+ * a source workflow to the runtime export name used by the worker.
544
+ */
773
545
  function getWorkflowIdMetadata(workflowConfig, workflowName, filePath) {
774
- for (const property of workflowConfig.properties) {
775
- if (!t3.isObjectProperty(property) || getObjectPropertyName(property) !== "id") {
776
- continue;
777
- }
778
- if (!t3.isExpression(property.value)) {
779
- break;
780
- }
781
- if (t3.isStringLiteral(property.value)) {
782
- return {
783
- expression: t3.cloneNode(property.value, true),
784
- workflowId: property.value.value
785
- };
786
- }
787
- if (t3.isTemplateLiteral(property.value) && property.value.expressions.length === 0) {
788
- return {
789
- expression: t3.cloneNode(property.value, true),
790
- workflowId: property.value.quasis[0]?.value.cooked ?? ""
791
- };
792
- }
793
- throw new Error(`Workflow id must be a static string for ${workflowName} in ${filePath}`);
794
- }
795
- throw new Error(`Unable to determine workflow id for ${workflowName} in ${filePath}`);
546
+ for (const property of workflowConfig.properties) {
547
+ if (!t.isObjectProperty(property) || getObjectPropertyName(property) !== "id") continue;
548
+ if (!t.isExpression(property.value)) break;
549
+ if (t.isStringLiteral(property.value)) return {
550
+ expression: t.cloneNode(property.value, true),
551
+ workflowId: property.value.value
552
+ };
553
+ if (t.isTemplateLiteral(property.value) && property.value.expressions.length === 0) return {
554
+ expression: t.cloneNode(property.value, true),
555
+ workflowId: property.value.quasis[0]?.value.cooked ?? ""
556
+ };
557
+ throw new Error(`Workflow id must be a static string for ${workflowName} in ${filePath}`);
558
+ }
559
+ throw new Error(`Unable to determine workflow id for ${workflowName} in ${filePath}`);
796
560
  }
561
+ /**
562
+ * The helper runtime lives in its own `.mjs` module so it can be linted and unit-tested
563
+ * like normal code. We parse that file directly here instead of using `Function#toString()`,
564
+ * which keeps fixture output stable under Vitest/Vite instrumentation.
565
+ */
797
566
  function createTemporalWorkflowHelperStatements() {
798
- const temporalWorkflowRuntimeSource = readFileSync(
799
- new URL("./temporal-workflow-runtime.mjs", import.meta.url),
800
- "utf8"
801
- );
802
- const helperProgram = parse(temporalWorkflowRuntimeSource, {
803
- sourceType: "module",
804
- plugins: parserPlugins
805
- }).program.body;
806
- return helperProgram.flatMap((statement) => {
807
- if (t3.isExportNamedDeclaration(statement) && statement.declaration) {
808
- return [statement.declaration];
809
- }
810
- return [statement];
811
- });
567
+ return parse(readFileSync(new URL("./temporal-workflow-runtime.mjs", import.meta.url), "utf8"), {
568
+ sourceType: "module",
569
+ plugins: parserPlugins
570
+ }).program.body.flatMap((statement) => {
571
+ if (t.isExportNamedDeclaration(statement) && statement.declaration) return [statement.declaration];
572
+ return [statement];
573
+ });
812
574
  }
813
- function getTemporalWorkflowRuntimeOptions(program3) {
814
- for (const statement of program3.body) {
815
- const declarationStatement = t3.isVariableDeclaration(statement) ? statement : t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration) ? statement.declaration : null;
816
- if (!declarationStatement) {
817
- continue;
818
- }
819
- for (const declaration of declarationStatement.declarations) {
820
- if (!isWorkflowHelperDestructure(declaration) || !t3.isCallExpression(declaration.init)) {
821
- continue;
822
- }
823
- const [temporalParams] = declaration.init.arguments;
824
- if (!temporalParams || !t3.isObjectExpression(temporalParams)) {
825
- continue;
826
- }
827
- for (const property of temporalParams.properties) {
828
- if (t3.isObjectProperty(property) && getObjectPropertyName(property) === "startToCloseTimeout" && t3.isExpression(property.value)) {
829
- return t3.objectExpression([
830
- t3.objectProperty(t3.identifier("startToCloseTimeout"), t3.cloneNode(property.value, true))
831
- ]);
832
- }
833
- }
834
- }
835
- }
575
+ function getTemporalWorkflowRuntimeOptions(program) {
576
+ for (const statement of program.body) {
577
+ const declarationStatement = t.isVariableDeclaration(statement) ? statement : t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration) ? statement.declaration : null;
578
+ if (!declarationStatement) continue;
579
+ for (const declaration of declarationStatement.declarations) {
580
+ if (!isWorkflowHelperDestructure(declaration) || !t.isCallExpression(declaration.init)) continue;
581
+ const [temporalParams] = declaration.init.arguments;
582
+ if (!temporalParams || !t.isObjectExpression(temporalParams)) continue;
583
+ for (const property of temporalParams.properties) if (t.isObjectProperty(property) && getObjectPropertyName(property) === "startToCloseTimeout" && t.isExpression(property.value)) return t.objectExpression([t.objectProperty(t.identifier("startToCloseTimeout"), t.cloneNode(property.value, true))]);
584
+ }
585
+ }
836
586
  }
587
+ /**
588
+ * Walks a chained workflow expression like `createWorkflow(...).then(...).commit()`
589
+ * back to its root `createWorkflow(...)` call while preserving method order.
590
+ */
837
591
  function parseWorkflowChain(node) {
838
- const methods = [];
839
- let current = node;
840
- while (t3.isCallExpression(current) && t3.isMemberExpression(current.callee) && !current.callee.computed) {
841
- if (!t3.isIdentifier(current.callee.property)) {
842
- return null;
843
- }
844
- methods.unshift({
845
- name: current.callee.property.name,
846
- args: current.arguments
847
- });
848
- current = current.callee.object;
849
- }
850
- if (!isCreateWorkflowCall(current)) {
851
- return null;
852
- }
853
- return {
854
- createWorkflowCall: current,
855
- methods
856
- };
592
+ const methods = [];
593
+ let current = node;
594
+ while (t.isCallExpression(current) && t.isMemberExpression(current.callee) && !current.callee.computed) {
595
+ if (!t.isIdentifier(current.callee.property)) return null;
596
+ methods.unshift({
597
+ name: current.callee.property.name,
598
+ args: current.arguments
599
+ });
600
+ current = current.callee.object;
601
+ }
602
+ if (!isCreateWorkflowCall(current)) return null;
603
+ return {
604
+ createWorkflowCall: current,
605
+ methods
606
+ };
857
607
  }
858
- function collectStepBindings(program3) {
859
- const stepBindings = /* @__PURE__ */ new Map();
860
- const stepFactoryBindings = collectCreateStepFactoryBindings(program3);
861
- for (const [factoryName, createStepCall] of stepFactoryBindings) {
862
- const stepId = getCreateStepId(createStepCall);
863
- if (stepId) {
864
- stepBindings.set(factoryName, stepId);
865
- }
866
- }
867
- for (const statement of program3.body) {
868
- if (!t3.isVariableDeclaration(statement) && !(t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration))) {
869
- continue;
870
- }
871
- const declarationStatement = t3.isVariableDeclaration(statement) ? statement : statement.declaration;
872
- for (const declaration of declarationStatement.declarations) {
873
- if (!t3.isIdentifier(declaration.id) || !declaration.init) {
874
- continue;
875
- }
876
- const createStepCall = getCreateStepCallFromExpression(declaration.init, stepFactoryBindings);
877
- const stepId = getCreateStepId(createStepCall);
878
- if (stepId) {
879
- stepBindings.set(declaration.id.name, stepId);
880
- }
881
- }
882
- }
883
- return stepBindings;
608
+ /**
609
+ * Maps local `const someStep = createStep({ id: 'some-step' })` bindings to their
610
+ * runtime ids so later chain rewriting can replace identifier references with ids.
611
+ */
612
+ function collectStepBindings(program) {
613
+ const stepBindings = /* @__PURE__ */ new Map();
614
+ const stepFactoryBindings = collectCreateStepFactoryBindings(program);
615
+ for (const [factoryName, createStepCall] of stepFactoryBindings) {
616
+ const stepId = getCreateStepId(createStepCall);
617
+ if (stepId) stepBindings.set(factoryName, stepId);
618
+ }
619
+ for (const statement of program.body) {
620
+ if (!t.isVariableDeclaration(statement) && !(t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration))) continue;
621
+ const declarationStatement = t.isVariableDeclaration(statement) ? statement : statement.declaration;
622
+ for (const declaration of declarationStatement.declarations) {
623
+ if (!t.isIdentifier(declaration.id) || !declaration.init) continue;
624
+ const stepId = getCreateStepId(getCreateStepCallFromExpression(declaration.init, stepFactoryBindings));
625
+ if (stepId) stepBindings.set(declaration.id.name, stepId);
626
+ }
627
+ }
628
+ return stepBindings;
884
629
  }
885
- function collectWorkflowBindings(program3, filePath) {
886
- const workflowBindings = /* @__PURE__ */ new Map();
887
- for (const statement of program3.body) {
888
- if (!t3.isVariableDeclaration(statement) && !(t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration))) {
889
- continue;
890
- }
891
- const declarationStatement = t3.isVariableDeclaration(statement) ? statement : statement.declaration;
892
- for (const declaration of declarationStatement.declarations) {
893
- if (!t3.isIdentifier(declaration.id) || !declaration.init) {
894
- continue;
895
- }
896
- const workflowChain = parseWorkflowChain(declaration.init);
897
- const [workflowConfig] = workflowChain?.createWorkflowCall.arguments ?? [];
898
- if (!workflowChain || !workflowConfig || !t3.isObjectExpression(workflowConfig)) {
899
- continue;
900
- }
901
- const { workflowId } = getWorkflowIdMetadata(workflowConfig, declaration.id.name, filePath);
902
- workflowBindings.set(declaration.id.name, toWorkflowType(workflowId));
903
- }
904
- }
905
- return workflowBindings;
630
+ function collectWorkflowBindings(program, filePath) {
631
+ const workflowBindings = /* @__PURE__ */ new Map();
632
+ for (const statement of program.body) {
633
+ if (!t.isVariableDeclaration(statement) && !(t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration))) continue;
634
+ const declarationStatement = t.isVariableDeclaration(statement) ? statement : statement.declaration;
635
+ for (const declaration of declarationStatement.declarations) {
636
+ if (!t.isIdentifier(declaration.id) || !declaration.init) continue;
637
+ const workflowChain = parseWorkflowChain(declaration.init);
638
+ const [workflowConfig] = workflowChain?.createWorkflowCall.arguments ?? [];
639
+ if (!workflowChain || !workflowConfig || !t.isObjectExpression(workflowConfig)) continue;
640
+ const { workflowId } = getWorkflowIdMetadata(workflowConfig, declaration.id.name, filePath);
641
+ workflowBindings.set(declaration.id.name, toWorkflowType(workflowId));
642
+ }
643
+ }
644
+ return workflowBindings;
906
645
  }
646
+ /**
647
+ * Accepts the few AST node shapes we allow as "step references" in workflow chains
648
+ * and normalizes them to a single step id string.
649
+ */
907
650
  function getWorkflowStepName(node, stepBindings) {
908
- if (!node) {
909
- return null;
910
- }
911
- if (t3.isIdentifier(node)) {
912
- return stepBindings.get(node.name) ?? node.name;
913
- }
914
- if (t3.isStringLiteral(node)) {
915
- return node.value;
916
- }
917
- if (t3.isCallExpression(node) && t3.isIdentifier(node.callee)) {
918
- return stepBindings.get(node.callee.name) ?? getCreateStepId(node);
919
- }
920
- return getCreateStepId(node);
651
+ if (!node) return null;
652
+ if (t.isIdentifier(node)) return stepBindings.get(node.name) ?? node.name;
653
+ if (t.isStringLiteral(node)) return node.value;
654
+ if (t.isCallExpression(node) && t.isIdentifier(node.callee)) return stepBindings.get(node.callee.name) ?? getCreateStepId(node);
655
+ return getCreateStepId(node);
921
656
  }
657
+ /**
658
+ * Normalizes fluent workflow builder calls into the simpler Temporal runtime shape.
659
+ *
660
+ * Most step references collapse down to step ids so the generated workflow can call
661
+ * activities by id instead of keeping the original `createStep` definitions around.
662
+ */
922
663
  function rewriteChainMethod(method, filePath, workflowName, stepBindings, workflowBindings) {
923
- const argNode = (index) => method.args[index];
924
- const rewritten = (args, name = method.name) => ({ name, args });
925
- switch (method.name) {
926
- case "then": {
927
- const arg = argNode(0);
928
- if (t3.isIdentifier(arg)) {
929
- const workflowType = workflowBindings.get(arg.name);
930
- if (workflowType) {
931
- return rewritten([t3.stringLiteral(workflowType)], "thenWorkflow");
932
- }
933
- }
934
- const name = getWorkflowStepName(arg, stepBindings);
935
- if (!name) {
936
- throw new Error(
937
- `.then() in ${workflowName} (${filePath}) must take a step or workflow identifier (inline createStep calls are not supported)`
938
- );
939
- }
940
- return rewritten([t3.stringLiteral(name)]);
941
- }
942
- case "sleep": {
943
- const arg = argNode(0);
944
- if (t3.isNumericLiteral(arg)) {
945
- return rewritten([t3.cloneNode(arg, true)]);
946
- }
947
- const name = getWorkflowStepName(arg, stepBindings);
948
- if (!name) {
949
- throw new Error(`.sleep() in ${workflowName} (${filePath}) must be a numeric literal or an identifier`);
950
- }
951
- return rewritten([t3.stringLiteral(name)]);
952
- }
953
- case "sleepUntil": {
954
- const arg = argNode(0);
955
- if (t3.isNewExpression(arg) && t3.isIdentifier(arg.callee) && arg.callee.name === "Date") {
956
- return rewritten([t3.cloneNode(arg, true)]);
957
- }
958
- if (t3.isStringLiteral(arg) || t3.isNumericLiteral(arg)) {
959
- return rewritten([t3.cloneNode(arg, true)]);
960
- }
961
- const name = getWorkflowStepName(arg, stepBindings);
962
- if (!name) {
963
- throw new Error(
964
- `.sleepUntil() in ${workflowName} (${filePath}) must be a Date, string/number literal, or an identifier`
965
- );
966
- }
967
- return rewritten([t3.stringLiteral(name)]);
968
- }
969
- case "parallel": {
970
- const arg = argNode(0);
971
- if (!t3.isArrayExpression(arg)) {
972
- throw new Error(`.parallel() in ${workflowName} (${filePath}) requires an array literal argument`);
973
- }
974
- const names = arg.elements.map((el) => getWorkflowStepName(el, stepBindings));
975
- if (names.some((n) => !n)) {
976
- throw new Error(`Unable to determine step names inside .parallel() in ${workflowName} (${filePath})`);
977
- }
978
- return rewritten([t3.arrayExpression(names.map((n) => t3.stringLiteral(n)))]);
979
- }
980
- case "branch": {
981
- const arg = argNode(0);
982
- if (!t3.isArrayExpression(arg)) {
983
- throw new Error(
984
- `.branch() in ${workflowName} (${filePath}) requires an array literal of [condition, step] pairs`
985
- );
986
- }
987
- const pairs = arg.elements.map((pair) => {
988
- if (!t3.isArrayExpression(pair) || pair.elements.length !== 2) {
989
- throw new Error(
990
- `.branch() pair in ${workflowName} (${filePath}) must be a 2-element array [condition, step]`
991
- );
992
- }
993
- const condName = getWorkflowStepName(pair.elements[0], stepBindings);
994
- const stepName = getWorkflowStepName(pair.elements[1], stepBindings);
995
- if (!condName || !stepName) {
996
- throw new Error(`.branch() condition and step in ${workflowName} (${filePath}) must be identifiers`);
997
- }
998
- return t3.arrayExpression([t3.stringLiteral(condName), t3.stringLiteral(stepName)]);
999
- });
1000
- return rewritten([t3.arrayExpression(pairs)]);
1001
- }
1002
- case "dowhile":
1003
- case "dountil": {
1004
- const stepName = getWorkflowStepName(argNode(0), stepBindings);
1005
- const condName = getWorkflowStepName(argNode(1), stepBindings);
1006
- if (!stepName || !condName) {
1007
- throw new Error(`.${method.name}() in ${workflowName} (${filePath}) must take (step, condition) identifiers`);
1008
- }
1009
- return rewritten([t3.stringLiteral(stepName), t3.stringLiteral(condName)]);
1010
- }
1011
- case "foreach": {
1012
- const stepName = getWorkflowStepName(argNode(0), stepBindings);
1013
- if (!stepName) {
1014
- throw new Error(`.foreach() in ${workflowName} (${filePath}) must take a step identifier`);
1015
- }
1016
- const args = [t3.stringLiteral(stepName)];
1017
- const optsArg = method.args[1];
1018
- if (optsArg && t3.isExpression(optsArg)) {
1019
- args.push(t3.cloneNode(optsArg, true));
1020
- }
1021
- return rewritten(args);
1022
- }
1023
- case "commit":
1024
- return rewritten([]);
1025
- default:
1026
- throw new Error(`Unsupported workflow chain method .${method.name}() in ${workflowName} (${filePath})`);
1027
- }
664
+ const argNode = (index) => method.args[index];
665
+ const rewritten = (args, name = method.name) => ({
666
+ name,
667
+ args
668
+ });
669
+ switch (method.name) {
670
+ case "then": {
671
+ const arg = argNode(0);
672
+ if (t.isIdentifier(arg)) {
673
+ const workflowType = workflowBindings.get(arg.name);
674
+ if (workflowType) return rewritten([t.stringLiteral(workflowType)], "thenWorkflow");
675
+ }
676
+ const name = getWorkflowStepName(arg, stepBindings);
677
+ if (!name) throw new Error(`.then() in ${workflowName} (${filePath}) must take a step or workflow identifier (inline createStep calls are not supported)`);
678
+ return rewritten([t.stringLiteral(name)]);
679
+ }
680
+ case "sleep": {
681
+ const arg = argNode(0);
682
+ if (t.isNumericLiteral(arg)) return rewritten([t.cloneNode(arg, true)]);
683
+ const name = getWorkflowStepName(arg, stepBindings);
684
+ if (!name) throw new Error(`.sleep() in ${workflowName} (${filePath}) must be a numeric literal or an identifier`);
685
+ return rewritten([t.stringLiteral(name)]);
686
+ }
687
+ case "sleepUntil": {
688
+ const arg = argNode(0);
689
+ if (t.isNewExpression(arg) && t.isIdentifier(arg.callee) && arg.callee.name === "Date") return rewritten([t.cloneNode(arg, true)]);
690
+ if (t.isStringLiteral(arg) || t.isNumericLiteral(arg)) return rewritten([t.cloneNode(arg, true)]);
691
+ const name = getWorkflowStepName(arg, stepBindings);
692
+ if (!name) throw new Error(`.sleepUntil() in ${workflowName} (${filePath}) must be a Date, string/number literal, or an identifier`);
693
+ return rewritten([t.stringLiteral(name)]);
694
+ }
695
+ case "parallel": {
696
+ const arg = argNode(0);
697
+ if (!t.isArrayExpression(arg)) throw new Error(`.parallel() in ${workflowName} (${filePath}) requires an array literal argument`);
698
+ const names = arg.elements.map((el) => getWorkflowStepName(el, stepBindings));
699
+ if (names.some((n) => !n)) throw new Error(`Unable to determine step names inside .parallel() in ${workflowName} (${filePath})`);
700
+ return rewritten([t.arrayExpression(names.map((n) => t.stringLiteral(n)))]);
701
+ }
702
+ case "branch": {
703
+ const arg = argNode(0);
704
+ if (!t.isArrayExpression(arg)) throw new Error(`.branch() in ${workflowName} (${filePath}) requires an array literal of [condition, step] pairs`);
705
+ const pairs = arg.elements.map((pair) => {
706
+ if (!t.isArrayExpression(pair) || pair.elements.length !== 2) throw new Error(`.branch() pair in ${workflowName} (${filePath}) must be a 2-element array [condition, step]`);
707
+ const condName = getWorkflowStepName(pair.elements[0], stepBindings);
708
+ const stepName = getWorkflowStepName(pair.elements[1], stepBindings);
709
+ if (!condName || !stepName) throw new Error(`.branch() condition and step in ${workflowName} (${filePath}) must be identifiers`);
710
+ return t.arrayExpression([t.stringLiteral(condName), t.stringLiteral(stepName)]);
711
+ });
712
+ return rewritten([t.arrayExpression(pairs)]);
713
+ }
714
+ case "dowhile":
715
+ case "dountil": {
716
+ const stepName = getWorkflowStepName(argNode(0), stepBindings);
717
+ const condName = getWorkflowStepName(argNode(1), stepBindings);
718
+ if (!stepName || !condName) throw new Error(`.${method.name}() in ${workflowName} (${filePath}) must take (step, condition) identifiers`);
719
+ return rewritten([t.stringLiteral(stepName), t.stringLiteral(condName)]);
720
+ }
721
+ case "foreach": {
722
+ const stepName = getWorkflowStepName(argNode(0), stepBindings);
723
+ if (!stepName) throw new Error(`.foreach() in ${workflowName} (${filePath}) must take a step identifier`);
724
+ const args = [t.stringLiteral(stepName)];
725
+ const optsArg = method.args[1];
726
+ if (optsArg && t.isExpression(optsArg)) args.push(t.cloneNode(optsArg, true));
727
+ return rewritten(args);
728
+ }
729
+ case "commit": return rewritten([]);
730
+ default: throw new Error(`Unsupported workflow chain method .${method.name}() in ${workflowName} (${filePath})`);
731
+ }
1028
732
  }
1029
733
  function getExportedName(node) {
1030
- return t3.isIdentifier(node) ? node.name : node.value;
734
+ return t.isIdentifier(node) ? node.name : node.value;
1031
735
  }
736
+ /**
737
+ * Materializes one transformed workflow export.
738
+ *
739
+ * Instead of preserving the original `const workflow = createWorkflow(...)` shape,
740
+ * we emit a deterministic exported function whose name matches Temporal's runtime
741
+ * lookup and whose body delegates into the injected helper runtime.
742
+ */
1032
743
  function createTemporalWorkflowStatements(exportName, workflowId, methods, filePath, includeCommit, stepBindings, workflowBindings, runtimeOptions) {
1033
- const createWorkflowArgs = [t3.cloneNode(workflowId, true)];
1034
- if (runtimeOptions) {
1035
- createWorkflowArgs.push(t3.cloneNode(runtimeOptions, true));
1036
- }
1037
- let expression = t3.callExpression(t3.identifier("createWorkflow"), createWorkflowArgs);
1038
- for (const method of methods) {
1039
- const rewrittenMethod = rewriteChainMethod(method, filePath, exportName, stepBindings, workflowBindings);
1040
- expression = t3.callExpression(
1041
- t3.memberExpression(expression, t3.identifier(rewrittenMethod.name)),
1042
- rewrittenMethod.args
1043
- );
1044
- }
1045
- if (includeCommit && !methods.some((m) => m.name === "commit")) {
1046
- expression = t3.callExpression(t3.memberExpression(expression, t3.identifier("commit")), []);
1047
- }
1048
- const argsParam = t3.identifier("args");
1049
- const lambda = t3.arrowFunctionExpression(
1050
- [argsParam],
1051
- t3.blockStatement([t3.returnStatement(t3.callExpression(expression, [t3.identifier("args")]))])
1052
- );
1053
- const declaration = t3.variableDeclaration("const", [t3.variableDeclarator(t3.identifier(exportName), lambda)]);
1054
- return [t3.exportNamedDeclaration(declaration)];
744
+ const createWorkflowArgs = [t.cloneNode(workflowId, true)];
745
+ if (runtimeOptions) createWorkflowArgs.push(t.cloneNode(runtimeOptions, true));
746
+ let expression = t.callExpression(t.identifier("createWorkflow"), createWorkflowArgs);
747
+ for (const method of methods) {
748
+ const rewrittenMethod = rewriteChainMethod(method, filePath, exportName, stepBindings, workflowBindings);
749
+ expression = t.callExpression(t.memberExpression(expression, t.identifier(rewrittenMethod.name)), rewrittenMethod.args);
750
+ }
751
+ if (includeCommit && !methods.some((m) => m.name === "commit")) expression = t.callExpression(t.memberExpression(expression, t.identifier("commit")), []);
752
+ const argsParam = t.identifier("args");
753
+ const lambda = t.arrowFunctionExpression([argsParam], t.blockStatement([t.returnStatement(t.callExpression(expression, [t.identifier("args")]))]));
754
+ const declaration = t.variableDeclaration("const", [t.variableDeclarator(t.identifier(exportName), lambda)]);
755
+ return [t.exportNamedDeclaration(declaration)];
1055
756
  }
1056
757
  function getTemporalWorkflowExportFromDeclaration(declaration, filePath) {
1057
- if (!t3.isIdentifier(declaration.id) || !declaration.init) {
1058
- return null;
1059
- }
1060
- const workflowChain = parseWorkflowChain(declaration.init);
1061
- if (!workflowChain) {
1062
- return null;
1063
- }
1064
- const [workflowConfig] = workflowChain.createWorkflowCall.arguments;
1065
- if (!workflowConfig || !t3.isObjectExpression(workflowConfig)) {
1066
- throw new Error(`Unable to determine workflow config for ${declaration.id.name} in ${filePath}`);
1067
- }
1068
- const { workflowId } = getWorkflowIdMetadata(workflowConfig, declaration.id.name, filePath);
1069
- return {
1070
- exportName: toWorkflowType(workflowId),
1071
- workflowId
1072
- };
758
+ if (!t.isIdentifier(declaration.id) || !declaration.init) return null;
759
+ const workflowChain = parseWorkflowChain(declaration.init);
760
+ if (!workflowChain) return null;
761
+ const [workflowConfig] = workflowChain.createWorkflowCall.arguments;
762
+ if (!workflowConfig || !t.isObjectExpression(workflowConfig)) throw new Error(`Unable to determine workflow config for ${declaration.id.name} in ${filePath}`);
763
+ const { workflowId } = getWorkflowIdMetadata(workflowConfig, declaration.id.name, filePath);
764
+ return {
765
+ exportName: toWorkflowType(workflowId),
766
+ workflowId
767
+ };
1073
768
  }
1074
769
  function getVariableDeclarationFromStatement(statement) {
1075
- if (t3.isVariableDeclaration(statement)) {
1076
- return statement;
1077
- }
1078
- if (t3.isExportNamedDeclaration(statement) && t3.isVariableDeclaration(statement.declaration)) {
1079
- return statement.declaration;
1080
- }
1081
- return null;
770
+ if (t.isVariableDeclaration(statement)) return statement;
771
+ if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) return statement.declaration;
772
+ return null;
1082
773
  }
1083
774
  function getCommittedWorkflowName(statement) {
1084
- if (!t3.isExpressionStatement(statement)) {
1085
- return null;
1086
- }
1087
- const { expression } = statement;
1088
- if (!t3.isCallExpression(expression) || !t3.isMemberExpression(expression.callee) || expression.callee.computed || !isIdentifierNamed(expression.callee.property, "commit") || !t3.isIdentifier(expression.callee.object)) {
1089
- return null;
1090
- }
1091
- return expression.callee.object.name;
775
+ if (!t.isExpressionStatement(statement)) return null;
776
+ const { expression } = statement;
777
+ if (!t.isCallExpression(expression) || !t.isMemberExpression(expression.callee) || expression.callee.computed || !isIdentifierNamed(expression.callee.property, "commit") || !t.isIdentifier(expression.callee.object)) return null;
778
+ return expression.callee.object.name;
1092
779
  }
1093
- function createWorkflowTransformState(program3, filePath) {
1094
- return {
1095
- statements: [...createTemporalWorkflowHelperStatements()],
1096
- workflowNames: /* @__PURE__ */ new Set(),
1097
- committedWorkflowNames: /* @__PURE__ */ new Set(),
1098
- inlineExportedWorkflowNames: /* @__PURE__ */ new Set(),
1099
- strippedNames: /* @__PURE__ */ new Set(),
1100
- stepBindings: collectStepBindings(program3),
1101
- workflowBindings: collectWorkflowBindings(program3, filePath),
1102
- workflowExports: [],
1103
- runtimeOptions: getTemporalWorkflowRuntimeOptions(program3)
1104
- };
780
+ function createWorkflowTransformState(program, filePath) {
781
+ return {
782
+ statements: [...createTemporalWorkflowHelperStatements()],
783
+ workflowNames: /* @__PURE__ */ new Set(),
784
+ committedWorkflowNames: /* @__PURE__ */ new Set(),
785
+ inlineExportedWorkflowNames: /* @__PURE__ */ new Set(),
786
+ strippedNames: /* @__PURE__ */ new Set(),
787
+ stepBindings: collectStepBindings(program),
788
+ workflowBindings: collectWorkflowBindings(program, filePath),
789
+ workflowExports: [],
790
+ runtimeOptions: getTemporalWorkflowRuntimeOptions(program)
791
+ };
1105
792
  }
1106
793
  function collectWorkflowDeclarationMetadata(statement, state) {
1107
- const declarationStatement = getVariableDeclarationFromStatement(statement);
1108
- if (!declarationStatement) {
1109
- return;
1110
- }
1111
- for (const declaration of declarationStatement.declarations) {
1112
- if (!t3.isIdentifier(declaration.id) || !declaration.init) {
1113
- continue;
1114
- }
1115
- if (!parseWorkflowChain(declaration.init)) {
1116
- continue;
1117
- }
1118
- state.workflowNames.add(declaration.id.name);
1119
- if (t3.isExportNamedDeclaration(statement)) {
1120
- state.inlineExportedWorkflowNames.add(declaration.id.name);
1121
- }
1122
- }
794
+ const declarationStatement = getVariableDeclarationFromStatement(statement);
795
+ if (!declarationStatement) return;
796
+ for (const declaration of declarationStatement.declarations) {
797
+ if (!t.isIdentifier(declaration.id) || !declaration.init) continue;
798
+ if (!parseWorkflowChain(declaration.init)) continue;
799
+ state.workflowNames.add(declaration.id.name);
800
+ if (t.isExportNamedDeclaration(statement)) state.inlineExportedWorkflowNames.add(declaration.id.name);
801
+ }
1123
802
  }
1124
803
  function collectWorkflowExportMetadata(statement, state) {
1125
- if (t3.isExportNamedDeclaration(statement) && statement.declaration == null && statement.source == null) {
1126
- for (const specifier of statement.specifiers) {
1127
- if (!t3.isExportSpecifier(specifier) || !t3.isIdentifier(specifier.local)) {
1128
- continue;
1129
- }
1130
- if (!state.workflowNames.has(specifier.local.name)) {
1131
- continue;
1132
- }
1133
- if (getExportedName(specifier.exported) === specifier.local.name) {
1134
- state.inlineExportedWorkflowNames.add(specifier.local.name);
1135
- }
1136
- }
1137
- }
804
+ if (t.isExportNamedDeclaration(statement) && statement.declaration == null && statement.source == null) for (const specifier of statement.specifiers) {
805
+ if (!t.isExportSpecifier(specifier) || !t.isIdentifier(specifier.local)) continue;
806
+ if (!state.workflowNames.has(specifier.local.name)) continue;
807
+ if (getExportedName(specifier.exported) === specifier.local.name) state.inlineExportedWorkflowNames.add(specifier.local.name);
808
+ }
1138
809
  }
1139
- function collectWorkflowTransformMetadata(program3, state) {
1140
- for (const statement of program3.body) {
1141
- collectWorkflowDeclarationMetadata(statement, state);
1142
- const committedWorkflowName = getCommittedWorkflowName(statement);
1143
- if (committedWorkflowName) {
1144
- state.committedWorkflowNames.add(committedWorkflowName);
1145
- }
1146
- collectWorkflowExportMetadata(statement, state);
1147
- }
810
+ function collectWorkflowTransformMetadata(program, state) {
811
+ for (const statement of program.body) {
812
+ collectWorkflowDeclarationMetadata(statement, state);
813
+ const committedWorkflowName = getCommittedWorkflowName(statement);
814
+ if (committedWorkflowName) state.committedWorkflowNames.add(committedWorkflowName);
815
+ collectWorkflowExportMetadata(statement, state);
816
+ }
1148
817
  }
1149
818
  function rewriteWorkflowImportDeclaration(statement, state) {
1150
- if (statement.source.value === "@mastra/core/workflows") {
1151
- const retainedSpecifiers = statement.specifiers.filter(
1152
- (specifier) => !(t3.isImportSpecifier(specifier) && t3.isIdentifier(specifier.imported) && (specifier.imported.name === "createWorkflow" || specifier.imported.name === "createStep"))
1153
- );
1154
- if (retainedSpecifiers.length > 0) {
1155
- state.statements.push(t3.importDeclaration(retainedSpecifiers, t3.stringLiteral(statement.source.value)));
1156
- }
1157
- return;
1158
- }
1159
- if (isTemporalHelperModule(statement.source.value) || isStrippedExternalModule(statement.source.value)) {
1160
- for (const name of collectImportedNames(statement)) {
1161
- state.strippedNames.add(name);
1162
- }
1163
- return;
1164
- }
1165
- state.statements.push(statement);
819
+ if (statement.source.value === "@mastra/core/workflows") {
820
+ const retainedSpecifiers = statement.specifiers.filter((specifier) => !(t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported) && (specifier.imported.name === "createWorkflow" || specifier.imported.name === "createStep")));
821
+ if (retainedSpecifiers.length > 0) state.statements.push(t.importDeclaration(retainedSpecifiers, t.stringLiteral(statement.source.value)));
822
+ return;
823
+ }
824
+ if (isTemporalHelperModule(statement.source.value) || isStrippedExternalModule(statement.source.value)) {
825
+ for (const name of collectImportedNames(statement)) state.strippedNames.add(name);
826
+ return;
827
+ }
828
+ state.statements.push(statement);
1166
829
  }
1167
830
  function getNormalizedWorkflowBindingName(name, state) {
1168
- if (!state.workflowNames.has(name)) {
1169
- return null;
1170
- }
1171
- return state.workflowBindings.get(name) ?? name;
831
+ if (!state.workflowNames.has(name)) return null;
832
+ return state.workflowBindings.get(name) ?? name;
1172
833
  }
1173
834
  function rewriteWorkflowNamedExport(statement, state) {
1174
- if (statement.source != null) {
1175
- return;
1176
- }
1177
- const retainedSpecifiers = statement.specifiers.flatMap((specifier) => {
1178
- if (!t3.isExportSpecifier(specifier) || !t3.isIdentifier(specifier.local)) {
1179
- return [];
1180
- }
1181
- const normalizedLocalName = getNormalizedWorkflowBindingName(specifier.local.name, state);
1182
- if (!normalizedLocalName || getExportedName(specifier.exported) === specifier.local.name) {
1183
- return [];
1184
- }
1185
- return [t3.exportSpecifier(t3.identifier(normalizedLocalName), t3.cloneNode(specifier.exported))];
1186
- });
1187
- if (retainedSpecifiers.length > 0) {
1188
- state.statements.push(t3.exportNamedDeclaration(null, retainedSpecifiers));
1189
- }
835
+ if (statement.source != null) return;
836
+ const retainedSpecifiers = statement.specifiers.flatMap((specifier) => {
837
+ if (!t.isExportSpecifier(specifier) || !t.isIdentifier(specifier.local)) return [];
838
+ const normalizedLocalName = getNormalizedWorkflowBindingName(specifier.local.name, state);
839
+ if (!normalizedLocalName || getExportedName(specifier.exported) === specifier.local.name) return [];
840
+ return [t.exportSpecifier(t.identifier(normalizedLocalName), t.cloneNode(specifier.exported))];
841
+ });
842
+ if (retainedSpecifiers.length > 0) state.statements.push(t.exportNamedDeclaration(null, retainedSpecifiers));
1190
843
  }
1191
844
  function rewriteWorkflowVariableDeclaration(statement, filePath, state) {
1192
- const declarationStatement = getVariableDeclarationFromStatement(statement);
1193
- if (!declarationStatement) {
1194
- return;
1195
- }
1196
- const declarations = [];
1197
- for (const declaration of declarationStatement.declarations) {
1198
- if (isWorkflowHelperDestructure(declaration)) {
1199
- continue;
1200
- }
1201
- if (t3.isIdentifier(declaration.id) && state.stepBindings.has(declaration.id.name)) {
1202
- state.strippedNames.add(declaration.id.name);
1203
- continue;
1204
- }
1205
- if (!t3.isIdentifier(declaration.id) || !declaration.init) {
1206
- declarations.push(declaration);
1207
- continue;
1208
- }
1209
- const workflowChain = parseWorkflowChain(declaration.init);
1210
- if (!workflowChain && nodeReferencesName(declaration.init, state.strippedNames)) {
1211
- state.strippedNames.add(declaration.id.name);
1212
- continue;
1213
- }
1214
- if (!workflowChain) {
1215
- declarations.push(declaration);
1216
- continue;
1217
- }
1218
- const [workflowConfig] = workflowChain.createWorkflowCall.arguments;
1219
- if (!workflowConfig || !t3.isObjectExpression(workflowConfig)) {
1220
- throw new Error(`Unable to determine workflow config for ${declaration.id.name} in ${filePath}`);
1221
- }
1222
- const { expression: workflowId } = getWorkflowIdMetadata(workflowConfig, declaration.id.name, filePath);
1223
- const workflowExport = getTemporalWorkflowExportFromDeclaration(declaration, filePath);
1224
- if (!workflowExport) {
1225
- throw new Error(`Unable to determine workflow export for ${declaration.id.name} in ${filePath}`);
1226
- }
1227
- const { exportName } = workflowExport;
1228
- state.workflowExports.push(workflowExport);
1229
- state.statements.push(
1230
- ...createTemporalWorkflowStatements(
1231
- exportName,
1232
- workflowId,
1233
- workflowChain.methods,
1234
- filePath,
1235
- state.committedWorkflowNames.has(declaration.id.name),
1236
- state.stepBindings,
1237
- state.workflowBindings,
1238
- state.runtimeOptions
1239
- )
1240
- );
1241
- }
1242
- if (declarations.length > 0) {
1243
- const cloned = declarations.map((declaration) => t3.cloneNode(declaration, true));
1244
- state.statements.push(t3.variableDeclaration(declarationStatement.kind, cloned));
1245
- }
845
+ const declarationStatement = getVariableDeclarationFromStatement(statement);
846
+ if (!declarationStatement) return;
847
+ const declarations = [];
848
+ for (const declaration of declarationStatement.declarations) {
849
+ if (isWorkflowHelperDestructure(declaration)) continue;
850
+ if (t.isIdentifier(declaration.id) && state.stepBindings.has(declaration.id.name)) {
851
+ state.strippedNames.add(declaration.id.name);
852
+ continue;
853
+ }
854
+ if (!t.isIdentifier(declaration.id) || !declaration.init) {
855
+ declarations.push(declaration);
856
+ continue;
857
+ }
858
+ const workflowChain = parseWorkflowChain(declaration.init);
859
+ if (!workflowChain && nodeReferencesName(declaration.init, state.strippedNames)) {
860
+ state.strippedNames.add(declaration.id.name);
861
+ continue;
862
+ }
863
+ if (!workflowChain) {
864
+ declarations.push(declaration);
865
+ continue;
866
+ }
867
+ const [workflowConfig] = workflowChain.createWorkflowCall.arguments;
868
+ if (!workflowConfig || !t.isObjectExpression(workflowConfig)) throw new Error(`Unable to determine workflow config for ${declaration.id.name} in ${filePath}`);
869
+ const { expression: workflowId } = getWorkflowIdMetadata(workflowConfig, declaration.id.name, filePath);
870
+ const workflowExport = getTemporalWorkflowExportFromDeclaration(declaration, filePath);
871
+ if (!workflowExport) throw new Error(`Unable to determine workflow export for ${declaration.id.name} in ${filePath}`);
872
+ const { exportName } = workflowExport;
873
+ state.workflowExports.push(workflowExport);
874
+ state.statements.push(...createTemporalWorkflowStatements(exportName, workflowId, workflowChain.methods, filePath, state.committedWorkflowNames.has(declaration.id.name), state.stepBindings, state.workflowBindings, state.runtimeOptions));
875
+ }
876
+ if (declarations.length > 0) {
877
+ const cloned = declarations.map((declaration) => t.cloneNode(declaration, true));
878
+ state.statements.push(t.variableDeclaration(declarationStatement.kind, cloned));
879
+ }
1246
880
  }
1247
881
  function rewriteWorkflowStatement(statement, filePath, state) {
1248
- if (t3.isImportDeclaration(statement)) {
1249
- rewriteWorkflowImportDeclaration(statement, state);
1250
- return;
1251
- }
1252
- if (getCommittedWorkflowName(statement)) {
1253
- return;
1254
- }
1255
- if (t3.isExportNamedDeclaration(statement)) {
1256
- if (statement.declaration == null) {
1257
- rewriteWorkflowNamedExport(statement, state);
1258
- return;
1259
- }
1260
- if (t3.isVariableDeclaration(statement.declaration)) {
1261
- rewriteWorkflowVariableDeclaration(statement, filePath, state);
1262
- return;
1263
- }
1264
- state.statements.push(statement.declaration);
1265
- return;
1266
- }
1267
- if (t3.isExportDefaultDeclaration(statement) && t3.isIdentifier(statement.declaration)) {
1268
- const normalizedLocalName = getNormalizedWorkflowBindingName(statement.declaration.name, state);
1269
- if (normalizedLocalName) {
1270
- state.statements.push(t3.exportDefaultDeclaration(t3.identifier(normalizedLocalName)));
1271
- }
1272
- return;
1273
- }
1274
- if (getVariableDeclarationFromStatement(statement)) {
1275
- rewriteWorkflowVariableDeclaration(statement, filePath, state);
1276
- return;
1277
- }
1278
- state.statements.push(statement);
882
+ if (t.isImportDeclaration(statement)) {
883
+ rewriteWorkflowImportDeclaration(statement, state);
884
+ return;
885
+ }
886
+ if (getCommittedWorkflowName(statement)) return;
887
+ if (t.isExportNamedDeclaration(statement)) {
888
+ if (statement.declaration == null) {
889
+ rewriteWorkflowNamedExport(statement, state);
890
+ return;
891
+ }
892
+ if (t.isVariableDeclaration(statement.declaration)) {
893
+ rewriteWorkflowVariableDeclaration(statement, filePath, state);
894
+ return;
895
+ }
896
+ state.statements.push(statement.declaration);
897
+ return;
898
+ }
899
+ if (t.isExportDefaultDeclaration(statement) && t.isIdentifier(statement.declaration)) {
900
+ const normalizedLocalName = getNormalizedWorkflowBindingName(statement.declaration.name, state);
901
+ if (normalizedLocalName) state.statements.push(t.exportDefaultDeclaration(t.identifier(normalizedLocalName)));
902
+ return;
903
+ }
904
+ if (getVariableDeclarationFromStatement(statement)) {
905
+ rewriteWorkflowVariableDeclaration(statement, filePath, state);
906
+ return;
907
+ }
908
+ state.statements.push(statement);
1279
909
  }
1280
910
  async function finalizeWorkflowModule(state) {
1281
- const transformedSource = generate(t3.file(t3.program(pruneUnusedTopLevelBindings(state.statements), [], "module")), {
1282
- sourceMaps: true
1283
- });
1284
- return {
1285
- ...transformedSource,
1286
- workflows: state.workflowExports
1287
- };
911
+ return {
912
+ ...generate(t.file(t.program(pruneUnusedTopLevelBindings(state.statements), [], "module")), { sourceMaps: true }),
913
+ workflows: state.workflowExports
914
+ };
1288
915
  }
916
+ /**
917
+ * Transforms a user-authored workflow module into a Temporal-friendly module:
918
+ * - strips Mastra/Temporal setup that cannot run in the workflow sandbox
919
+ * - rewrites fluent workflow chains into deterministic exported functions
920
+ * - returns registry metadata so the entry module can re-export the right names
921
+ */
1289
922
  async function buildTemporalWorkflowModule(entryFile, outputDirectory, outputFileName) {
1290
- const bundle = await rollup({
1291
- input: entryFile,
1292
- treeshake: "smallest",
1293
- logLevel: "silent",
1294
- plugins: [
1295
- {
1296
- name: "temporal-workflow-transform",
1297
- transform(code, id) {
1298
- const ast = parseModule(id, code);
1299
- const state = createWorkflowTransformState(ast.program, id);
1300
- collectWorkflowTransformMetadata(ast.program, state);
1301
- for (const statement of ast.program.body) {
1302
- rewriteWorkflowStatement(statement, id, state);
1303
- }
1304
- return finalizeWorkflowModule(state);
1305
- }
1306
- }
1307
- ]
1308
- });
1309
- try {
1310
- const baseName = basename(outputFileName);
1311
- const { output } = await bundle.write({
1312
- dir: outputDirectory,
1313
- entryFileNames: outputFileName,
1314
- chunkFileNames: `${baseName}-[hash].mjs`,
1315
- format: "esm",
1316
- sourcemap: "inline"
1317
- });
1318
- return {
1319
- outputPath: join(outputDirectory, output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName)
1320
- };
1321
- } finally {
1322
- await bundle.close();
1323
- }
923
+ const bundle = await rollup({
924
+ input: entryFile,
925
+ treeshake: "smallest",
926
+ logLevel: "silent",
927
+ plugins: [{
928
+ name: "temporal-workflow-transform",
929
+ transform(code, id) {
930
+ const ast = parseModule(id, code);
931
+ const state = createWorkflowTransformState(ast.program, id);
932
+ collectWorkflowTransformMetadata(ast.program, state);
933
+ for (const statement of ast.program.body) rewriteWorkflowStatement(statement, id, state);
934
+ return finalizeWorkflowModule(state);
935
+ }
936
+ }]
937
+ });
938
+ try {
939
+ const baseName = basename(outputFileName);
940
+ const { output } = await bundle.write({
941
+ dir: outputDirectory,
942
+ entryFileNames: outputFileName,
943
+ chunkFileNames: `${baseName}-[hash].mjs`,
944
+ format: "esm",
945
+ sourcemap: "inline"
946
+ });
947
+ return { outputPath: join(outputDirectory, output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName) };
948
+ } finally {
949
+ await bundle.close();
950
+ }
1324
951
  }
1325
-
1326
- // src/plugin.ts
1327
- var CACHE_PATH = "node_modules/.mastra";
1328
- var WORKFLOW_FILE_NAME = "workflow.mjs";
1329
- var ACTIVITIES_FILE_NAME = "activities.mjs";
1330
- var ACTIVITY_BINDINGS_FILE_NAME = "activity-bindings.json";
952
+ //#endregion
953
+ //#region src/plugin.ts
954
+ const CACHE_PATH = "node_modules/.mastra";
955
+ const WORKFLOW_FILE_NAME = "workflow.mjs";
956
+ const ACTIVITIES_FILE_NAME = "activities.mjs";
957
+ const ACTIVITY_BINDINGS_FILE_NAME = "activity-bindings.json";
1331
958
  function getGeneratedWorkflowModulePath(outputDir) {
1332
- return path.join(outputDir, WORKFLOW_FILE_NAME);
959
+ return path.join(outputDir, WORKFLOW_FILE_NAME);
1333
960
  }
1334
961
  function getGeneratedActivitiesModulePath(outputDir) {
1335
- return path.join(outputDir, ACTIVITIES_FILE_NAME);
962
+ return path.join(outputDir, ACTIVITIES_FILE_NAME);
1336
963
  }
1337
964
  function getActivityBindingsPath(outputDir) {
1338
- return path.join(outputDir, ACTIVITY_BINDINGS_FILE_NAME);
965
+ return path.join(outputDir, ACTIVITY_BINDINGS_FILE_NAME);
1339
966
  }
1340
967
  var MastraPlugin = class {
1341
- #prebuildPath = null;
1342
- #compiledActivitiesModules = /* @__PURE__ */ new Map();
1343
- name = "Mastra";
1344
- constructor() {
1345
- }
1346
- async #bundleMastra(entryFile, projectRoot, outputDirectory) {
1347
- const { BuildBundler } = await import('./mastra-deployer-UCBGECM5.js');
1348
- const normalizedEntryFile = entryFile.startsWith("file:/") ? fileURLToPath(entryFile) : entryFile;
1349
- const mastraBundler = new BuildBundler();
1350
- await mastraBundler.prepare(outputDirectory);
1351
- await mastraBundler.bundle(normalizedEntryFile, outputDirectory, {
1352
- toolsPaths: [],
1353
- projectRoot
1354
- });
1355
- return path.join(outputDirectory, "output", "index.mjs");
1356
- }
1357
- async prebuild({
1358
- entryFile,
1359
- projectRoot = process.cwd()
1360
- }) {
1361
- const temporalOutputDir = path.resolve(projectRoot, CACHE_PATH);
1362
- const compiledEntryPath = await this.#bundleMastra(entryFile, projectRoot, temporalOutputDir);
1363
- await buildTemporalWorkflowModule(compiledEntryPath, temporalOutputDir, WORKFLOW_FILE_NAME);
1364
- const { activityBindings } = await buildTemporalActivitiesModule(
1365
- compiledEntryPath,
1366
- temporalOutputDir,
1367
- ACTIVITIES_FILE_NAME
1368
- );
1369
- await writeFile(getActivityBindingsPath(temporalOutputDir), JSON.stringify(activityBindings, null, 2), "utf8");
1370
- this.#prebuildPath = temporalOutputDir;
1371
- return this.getTemporalWorkerOptions(temporalOutputDir);
1372
- }
1373
- #loadActivityBindings(activityBindingsPath) {
1374
- try {
1375
- const bindings = JSON.parse(readFileSync(activityBindingsPath, "utf8"));
1376
- return bindings;
1377
- } catch (error) {
1378
- throw new Error(`MastraPlugin.prebuild() must be called before use, or ${activityBindingsPath} must exist`, {
1379
- cause: error
1380
- });
1381
- }
1382
- }
1383
- #loadCompiledActivitiesModule(activitiesModulePath) {
1384
- const cachedModule = this.#compiledActivitiesModules.get(activitiesModulePath);
1385
- if (cachedModule) {
1386
- return cachedModule;
1387
- }
1388
- const modulePromise = import(`${pathToFileURL(activitiesModulePath).href}?t=${Date.now()}`);
1389
- this.#compiledActivitiesModules.set(activitiesModulePath, modulePromise);
1390
- return modulePromise;
1391
- }
1392
- #generateActivityBindings(activityBindings, compiledActivitiesPath) {
1393
- const generatedActivities = {};
1394
- for (const binding of activityBindings) {
1395
- if (generatedActivities[binding.stepId]) {
1396
- continue;
1397
- }
1398
- generatedActivities[binding.stepId] = async (...args) => {
1399
- const activityModule = await this.#loadCompiledActivitiesModule(compiledActivitiesPath);
1400
- const activity = activityModule[binding.exportName];
1401
- if (typeof activity !== "function") {
1402
- throw new Error(`Unable to load activity '${binding.exportName}' from ${compiledActivitiesPath}`);
1403
- }
1404
- return activity(...args);
1405
- };
1406
- }
1407
- return generatedActivities;
1408
- }
1409
- getTemporalWorkerOptions(temporalOutputDir) {
1410
- const workflowOutputPath = getGeneratedWorkflowModulePath(temporalOutputDir);
1411
- const activitiesOutputPath = getGeneratedActivitiesModulePath(temporalOutputDir);
1412
- const activityBindings = this.#loadActivityBindings(getActivityBindingsPath(temporalOutputDir));
1413
- return {
1414
- workflowsPath: workflowOutputPath,
1415
- // workflowBundle: {
1416
- // codePath: workflowOutputPath,
1417
- // sourceMapPath: `${workflowOutputPath}.map`,
1418
- // },
1419
- activities: this.#generateActivityBindings(activityBindings, activitiesOutputPath)
1420
- };
1421
- }
1422
- configureWorker(options) {
1423
- const augmentedOptions = Object.assign({}, options);
1424
- if (this.#prebuildPath) {
1425
- Object.assign(augmentedOptions, this.getTemporalWorkerOptions(this.#prebuildPath));
1426
- } else {
1427
- if (!options.workflowsPath || !options.activities) {
1428
- throw new Error("MastraPlugin.prebuild() must be called before use");
1429
- }
1430
- }
1431
- return augmentedOptions;
1432
- }
968
+ #prebuildPath = null;
969
+ #compiledActivitiesModules = /* @__PURE__ */ new Map();
970
+ name = "Mastra";
971
+ constructor() {}
972
+ async #bundleMastra(entryFile, projectRoot, outputDirectory) {
973
+ const { BuildBundler } = await import("./mastra-deployer-rZLKb1Em.js");
974
+ const normalizedEntryFile = entryFile.startsWith("file:/") ? fileURLToPath(entryFile) : entryFile;
975
+ const mastraBundler = new BuildBundler();
976
+ await mastraBundler.prepare(outputDirectory);
977
+ await mastraBundler.bundle(normalizedEntryFile, outputDirectory, {
978
+ toolsPaths: [],
979
+ projectRoot
980
+ });
981
+ return path.join(outputDirectory, "output", "index.mjs");
982
+ }
983
+ async prebuild({ entryFile, projectRoot = process.cwd() }) {
984
+ const temporalOutputDir = path.resolve(projectRoot, CACHE_PATH);
985
+ const compiledEntryPath = await this.#bundleMastra(entryFile, projectRoot, temporalOutputDir);
986
+ await buildTemporalWorkflowModule(compiledEntryPath, temporalOutputDir, WORKFLOW_FILE_NAME);
987
+ const { activityBindings } = await buildTemporalActivitiesModule(compiledEntryPath, temporalOutputDir, ACTIVITIES_FILE_NAME);
988
+ await writeFile(getActivityBindingsPath(temporalOutputDir), JSON.stringify(activityBindings, null, 2), "utf8");
989
+ this.#prebuildPath = temporalOutputDir;
990
+ return this.getTemporalWorkerOptions(temporalOutputDir);
991
+ }
992
+ #loadActivityBindings(activityBindingsPath) {
993
+ try {
994
+ return JSON.parse(readFileSync(activityBindingsPath, "utf8"));
995
+ } catch (error) {
996
+ throw new Error(`MastraPlugin.prebuild() must be called before use, or ${activityBindingsPath} must exist`, { cause: error });
997
+ }
998
+ }
999
+ #loadCompiledActivitiesModule(activitiesModulePath) {
1000
+ const cachedModule = this.#compiledActivitiesModules.get(activitiesModulePath);
1001
+ if (cachedModule) return cachedModule;
1002
+ const modulePromise = import(`${pathToFileURL(activitiesModulePath).href}?t=${Date.now()}`);
1003
+ this.#compiledActivitiesModules.set(activitiesModulePath, modulePromise);
1004
+ return modulePromise;
1005
+ }
1006
+ #generateActivityBindings(activityBindings, compiledActivitiesPath) {
1007
+ const generatedActivities = {};
1008
+ for (const binding of activityBindings) {
1009
+ if (generatedActivities[binding.stepId]) continue;
1010
+ generatedActivities[binding.stepId] = async (...args) => {
1011
+ const activity = (await this.#loadCompiledActivitiesModule(compiledActivitiesPath))[binding.exportName];
1012
+ if (typeof activity !== "function") throw new Error(`Unable to load activity '${binding.exportName}' from ${compiledActivitiesPath}`);
1013
+ return activity(...args);
1014
+ };
1015
+ }
1016
+ return generatedActivities;
1017
+ }
1018
+ getTemporalWorkerOptions(temporalOutputDir) {
1019
+ const workflowOutputPath = getGeneratedWorkflowModulePath(temporalOutputDir);
1020
+ const activitiesOutputPath = getGeneratedActivitiesModulePath(temporalOutputDir);
1021
+ const activityBindings = this.#loadActivityBindings(getActivityBindingsPath(temporalOutputDir));
1022
+ return {
1023
+ workflowsPath: workflowOutputPath,
1024
+ activities: this.#generateActivityBindings(activityBindings, activitiesOutputPath)
1025
+ };
1026
+ }
1027
+ configureWorker(options) {
1028
+ const augmentedOptions = Object.assign({}, options);
1029
+ if (this.#prebuildPath) Object.assign(augmentedOptions, this.getTemporalWorkerOptions(this.#prebuildPath));
1030
+ else if (!options.workflowsPath || !options.activities) throw new Error("MastraPlugin.prebuild() must be called before use");
1031
+ return augmentedOptions;
1032
+ }
1433
1033
  };
1434
-
1034
+ //#endregion
1435
1035
  export { MastraPlugin };
1436
- //# sourceMappingURL=worker.js.map
1036
+
1437
1037
  //# sourceMappingURL=worker.js.map