@mastra/temporal 0.4.6-alpha.5 → 0.4.6-alpha.6

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
@@ -276,6 +276,80 @@ function rebaseModulePath(modulePath, sourceFilePath, outputFilePath) {
276
276
  const resolvedPath = path.resolve(path.dirname(sourceFilePath), modulePath);
277
277
  return normalizeImportPath(path.relative(path.dirname(outputFilePath), resolvedPath), path.extname(resolvedPath));
278
278
  }
279
+ function parseWorkflowChain$1(node) {
280
+ const methods = [];
281
+ let current = node;
282
+ while (t.isCallExpression(current) && t.isMemberExpression(current.callee) && !current.callee.computed) {
283
+ if (!t.isIdentifier(current.callee.property)) return null;
284
+ methods.unshift({
285
+ name: current.callee.property.name,
286
+ args: current.arguments
287
+ });
288
+ current = current.callee.object;
289
+ }
290
+ if (!t.isCallExpression(current) || !t.isIdentifier(current.callee, { name: "createWorkflow" })) return null;
291
+ return {
292
+ createWorkflowCall: current,
293
+ methods
294
+ };
295
+ }
296
+ function getStaticWorkflowId(call, filePath) {
297
+ const [config] = call.arguments;
298
+ if (!t.isObjectExpression(config)) throw new Error(`Unable to determine workflow config in ${filePath}`);
299
+ for (const property of config.properties) {
300
+ if (!t.isObjectProperty(property) || getObjectPropertyName(property) !== "id") continue;
301
+ if (t.isStringLiteral(property.value)) return property.value.value;
302
+ if (t.isTemplateLiteral(property.value) && property.value.expressions.length === 0) return property.value.quasis[0]?.value.cooked ?? "";
303
+ }
304
+ throw new Error(`Workflow id must be a static string in ${filePath}`);
305
+ }
306
+ function toExportName(id) {
307
+ return id.replace(/[^a-zA-Z0-9]+(.)/g, (_match, char) => char.toUpperCase()).replace(/^[^a-zA-Z_$]+/, "").replace(/^(.)/, (char) => char.toLowerCase());
308
+ }
309
+ function collectStaticFunctionBindings(program) {
310
+ const bindings = /* @__PURE__ */ new Set();
311
+ for (const statement of program.body) {
312
+ const declaration = t.isExportNamedDeclaration(statement) ? statement.declaration : statement;
313
+ if (t.isFunctionDeclaration(declaration) && declaration.id) {
314
+ bindings.add(declaration.id.name);
315
+ continue;
316
+ }
317
+ if (!t.isVariableDeclaration(declaration) || declaration.kind !== "const") continue;
318
+ for (const declarator of declaration.declarations) if (t.isIdentifier(declarator.id) && (t.isArrowFunctionExpression(declarator.init) || t.isFunctionExpression(declarator.init))) bindings.add(declarator.id.name);
319
+ }
320
+ return bindings;
321
+ }
322
+ function collectTopLevelBindingNames(program) {
323
+ const bindings = /* @__PURE__ */ new Set();
324
+ for (const statement of program.body) for (const name of Object.keys(t.getBindingIdentifiers(statement))) bindings.add(name);
325
+ return bindings;
326
+ }
327
+ function createMappingActivityStatements(workflowExpression, filePath, staticFunctionBindings, usedExportNames, addBinding) {
328
+ const chain = parseWorkflowChain$1(workflowExpression);
329
+ if (!chain) return [];
330
+ const workflowId = getStaticWorkflowId(chain.createWorkflowCall, filePath);
331
+ const statements = [];
332
+ let mappingOrdinal = 0;
333
+ for (const method of chain.methods) {
334
+ if (method.name !== "map") continue;
335
+ const [callback] = method.args;
336
+ if (t.isObjectExpression(callback)) throw new Error(`.map() in workflow ${workflowId} (${filePath}) does not yet support declarative object mappings`);
337
+ if (!t.isArrowFunctionExpression(callback) && !t.isFunctionExpression(callback) && !(t.isIdentifier(callback) && staticFunctionBindings.has(callback.name))) throw new Error(`.map() in workflow ${workflowId} (${filePath}) requires an inline function or a statically declared function identifier`);
338
+ const mappingId = `mapping_${workflowId}_${mappingOrdinal++}`;
339
+ const baseExportName = toExportName(mappingId);
340
+ let exportName = baseExportName;
341
+ let exportSuffix = 1;
342
+ while (usedExportNames.has(exportName)) exportName = `${baseExportName}${exportSuffix++}`;
343
+ usedExportNames.add(exportName);
344
+ const params = t.objectPattern([t.objectProperty(t.identifier("inputData"), t.identifier("inputData"), false, true), t.objectProperty(t.identifier("initData"), t.identifier("initData"), false, true)]);
345
+ const callbackContext = t.objectExpression([t.objectProperty(t.identifier("inputData"), t.identifier("inputData"), false, true), t.objectProperty(t.identifier("getInitData"), t.arrowFunctionExpression([], t.identifier("initData")))]);
346
+ const callbackExpression = t.cloneNode(callback, true);
347
+ const body = t.callExpression(callbackExpression, [callbackContext]);
348
+ statements.push(t.exportNamedDeclaration(t.variableDeclaration("const", [t.variableDeclarator(t.identifier(exportName), t.arrowFunctionExpression([params], body, true))])));
349
+ addBinding(exportName, mappingId);
350
+ }
351
+ return statements;
352
+ }
279
353
  function collectWorkflowBindingNames(ast) {
280
354
  const workflowNames = /* @__PURE__ */ new Set();
281
355
  for (const statement of ast.program.body) {
@@ -335,15 +409,18 @@ function createTemporalActivitiesHelperStatements(mastraImportPath, hasMastraBin
335
409
  async function buildTemporalActivitiesModule(entryFile, outputDirectory, outputFileName) {
336
410
  const activityBindings = [];
337
411
  const seenActivityBindingNames = /* @__PURE__ */ new Set();
338
- const addActivityBinding = (exportName, call) => {
339
- const stepId = getCreateStepId(call);
340
- if (!stepId || seenActivityBindingNames.has(exportName)) return;
412
+ const addGeneratedActivityBinding = (exportName, stepId) => {
413
+ if (seenActivityBindingNames.has(exportName)) return;
341
414
  seenActivityBindingNames.add(exportName);
342
415
  activityBindings.push({
343
416
  exportName,
344
417
  stepId
345
418
  });
346
419
  };
420
+ const addActivityBinding = (exportName, call) => {
421
+ const stepId = getCreateStepId(call);
422
+ if (stepId) addGeneratedActivityBinding(exportName, stepId);
423
+ };
347
424
  const bundle = await rollup({
348
425
  input: entryFile,
349
426
  treeshake: "smallest",
@@ -361,6 +438,8 @@ async function buildTemporalActivitiesModule(entryFile, outputDirectory, outputF
361
438
  const strippedNames = /* @__PURE__ */ new Set();
362
439
  const workflowBindingNames = collectWorkflowBindingNames(ast);
363
440
  const stepFactoryBindings = collectCreateStepFactoryBindings(ast.program);
441
+ const staticFunctionBindings = collectStaticFunctionBindings(ast.program);
442
+ const usedExportNames = collectTopLevelBindingNames(ast.program);
364
443
  const sourceFilePath = id;
365
444
  const hasMastraBinding = hasLocalMastraBinding(ast);
366
445
  let helperInserted = false;
@@ -422,6 +501,7 @@ async function buildTemporalActivitiesModule(entryFile, outputDirectory, outputF
422
501
  if (hasCreateWorkflowCall(declaration.init)) {
423
502
  workflowBindingNames.add(declaration.id.name);
424
503
  strippedNames.add(declaration.id.name);
504
+ statements.push(...createMappingActivityStatements(declaration.init, sourceFilePath, staticFunctionBindings, usedExportNames, addGeneratedActivityBinding));
425
505
  collectInlineCreateSteps(declaration.init, seenNames, statements, addActivityBinding);
426
506
  continue;
427
507
  }
@@ -461,6 +541,7 @@ async function buildTemporalActivitiesModule(entryFile, outputDirectory, outputF
461
541
  if (hasCreateWorkflowCall(declaration.init)) {
462
542
  workflowBindingNames.add(declaration.id.name);
463
543
  strippedNames.add(declaration.id.name);
544
+ statements.push(...createMappingActivityStatements(declaration.init, sourceFilePath, staticFunctionBindings, usedExportNames, addGeneratedActivityBinding));
464
545
  collectInlineCreateSteps(declaration.init, seenNames, statements, addActivityBinding);
465
546
  continue;
466
547
  }
@@ -660,7 +741,7 @@ function getWorkflowStepName(node, stepBindings) {
660
741
  * Most step references collapse down to step ids so the generated workflow can call
661
742
  * activities by id instead of keeping the original `createStep` definitions around.
662
743
  */
663
- function rewriteChainMethod(method, filePath, workflowName, stepBindings, workflowBindings) {
744
+ function rewriteChainMethod(method, filePath, workflowName, workflowId, mappingOrdinal, stepBindings, workflowBindings) {
664
745
  const argNode = (index) => method.args[index];
665
746
  const rewritten = (args, name = method.name) => ({
666
747
  name,
@@ -695,9 +776,16 @@ function rewriteChainMethod(method, filePath, workflowName, stepBindings, workfl
695
776
  case "parallel": {
696
777
  const arg = argNode(0);
697
778
  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)))]);
779
+ const entries = arg.elements.map((element) => {
780
+ if (t.isIdentifier(element)) {
781
+ const workflowType = workflowBindings.get(element.name);
782
+ if (workflowType) return t.objectExpression([t.objectProperty(t.identifier("type"), t.stringLiteral("childWorkflow")), t.objectProperty(t.identifier("workflowType"), t.stringLiteral(workflowType))]);
783
+ }
784
+ const stepId = getWorkflowStepName(element, stepBindings);
785
+ if (!stepId) throw new Error(`Unable to determine step names inside .parallel() in ${workflowName} (${filePath})`);
786
+ return t.objectExpression([t.objectProperty(t.identifier("type"), t.stringLiteral("step")), t.objectProperty(t.identifier("step"), t.objectExpression([t.objectProperty(t.identifier("id"), t.stringLiteral(stepId))]))]);
787
+ });
788
+ return rewritten([t.arrayExpression(entries)]);
701
789
  }
702
790
  case "branch": {
703
791
  const arg = argNode(0);
@@ -726,6 +814,15 @@ function rewriteChainMethod(method, filePath, workflowName, stepBindings, workfl
726
814
  if (optsArg && t.isExpression(optsArg)) args.push(t.cloneNode(optsArg, true));
727
815
  return rewritten(args);
728
816
  }
817
+ case "map": {
818
+ const callback = argNode(0);
819
+ if (t.isObjectExpression(callback)) throw new Error(`.map() in ${workflowName} (${filePath}) does not yet support declarative object mappings; use a callback mapping`);
820
+ if (!t.isArrowFunctionExpression(callback) && !t.isFunctionExpression(callback) && !t.isIdentifier(callback)) throw new Error(`.map() in ${workflowName} (${filePath}) requires an inline function or a statically declared function identifier`);
821
+ const args = [t.stringLiteral(`mapping_${workflowId}_${mappingOrdinal}`)];
822
+ const optsArg = method.args[1];
823
+ if (optsArg && t.isExpression(optsArg)) args.push(t.cloneNode(optsArg, true));
824
+ return rewritten(args);
825
+ }
729
826
  case "commit": return rewritten([]);
730
827
  default: throw new Error(`Unsupported workflow chain method .${method.name}() in ${workflowName} (${filePath})`);
731
828
  }
@@ -740,12 +837,14 @@ function getExportedName(node) {
740
837
  * we emit a deterministic exported function whose name matches Temporal's runtime
741
838
  * lookup and whose body delegates into the injected helper runtime.
742
839
  */
743
- function createTemporalWorkflowStatements(exportName, workflowId, methods, filePath, includeCommit, stepBindings, workflowBindings, runtimeOptions) {
840
+ function createTemporalWorkflowStatements(exportName, workflowId, workflowIdValue, methods, filePath, includeCommit, stepBindings, workflowBindings, runtimeOptions) {
744
841
  const createWorkflowArgs = [t.cloneNode(workflowId, true)];
745
842
  if (runtimeOptions) createWorkflowArgs.push(t.cloneNode(runtimeOptions, true));
746
843
  let expression = t.callExpression(t.identifier("createWorkflow"), createWorkflowArgs);
844
+ let mappingOrdinal = 0;
747
845
  for (const method of methods) {
748
- const rewrittenMethod = rewriteChainMethod(method, filePath, exportName, stepBindings, workflowBindings);
846
+ const rewrittenMethod = rewriteChainMethod(method, filePath, exportName, workflowIdValue, mappingOrdinal, stepBindings, workflowBindings);
847
+ if (method.name === "map") mappingOrdinal += 1;
749
848
  expression = t.callExpression(t.memberExpression(expression, t.identifier(rewrittenMethod.name)), rewrittenMethod.args);
750
849
  }
751
850
  if (includeCommit && !methods.some((m) => m.name === "commit")) expression = t.callExpression(t.memberExpression(expression, t.identifier("commit")), []);
@@ -866,12 +965,12 @@ function rewriteWorkflowVariableDeclaration(statement, filePath, state) {
866
965
  }
867
966
  const [workflowConfig] = workflowChain.createWorkflowCall.arguments;
868
967
  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);
968
+ const { expression: workflowId, workflowId: workflowIdValue } = getWorkflowIdMetadata(workflowConfig, declaration.id.name, filePath);
870
969
  const workflowExport = getTemporalWorkflowExportFromDeclaration(declaration, filePath);
871
970
  if (!workflowExport) throw new Error(`Unable to determine workflow export for ${declaration.id.name} in ${filePath}`);
872
971
  const { exportName } = workflowExport;
873
972
  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));
973
+ state.statements.push(...createTemporalWorkflowStatements(exportName, workflowId, workflowIdValue, workflowChain.methods, filePath, state.committedWorkflowNames.has(declaration.id.name), state.stepBindings, state.workflowBindings, state.runtimeOptions));
875
974
  }
876
975
  if (declarations.length > 0) {
877
976
  const cloned = declarations.map((declaration) => t.cloneNode(declaration, true));