@mastra/temporal 0.0.0 → 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/LICENSE.md +30 -0
  3. package/README.md +104 -2
  4. package/dist/chunk-BF6TR7JX.js +9 -0
  5. package/dist/chunk-BF6TR7JX.js.map +1 -0
  6. package/dist/chunk-DYBSPLCJ.cjs +11 -0
  7. package/dist/chunk-DYBSPLCJ.cjs.map +1 -0
  8. package/dist/index.cjs +3 -946
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.ts +0 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2 -920
  13. package/dist/index.js.map +1 -1
  14. package/dist/mastra-deployer-UCBGECM5.js +39 -0
  15. package/dist/mastra-deployer-UCBGECM5.js.map +1 -0
  16. package/dist/mastra-deployer-YVT5GB5G.cjs +41 -0
  17. package/dist/mastra-deployer-YVT5GB5G.cjs.map +1 -0
  18. package/dist/mastra-deployer.d.ts +16 -0
  19. package/dist/mastra-deployer.d.ts.map +1 -0
  20. package/dist/plugin.d.ts +13 -15
  21. package/dist/plugin.d.ts.map +1 -1
  22. package/dist/temporal-workflow-runtime.mjs +295 -0
  23. package/dist/transforms/activities.d.ts +4 -3
  24. package/dist/transforms/activities.d.ts.map +1 -1
  25. package/dist/transforms/shared.d.ts +2 -7
  26. package/dist/transforms/shared.d.ts.map +1 -1
  27. package/dist/transforms/temporal-workflow-runtime.d.mts +7 -0
  28. package/dist/transforms/temporal-workflow-runtime.d.mts.map +1 -1
  29. package/dist/transforms/workflows.d.ts +3 -11
  30. package/dist/transforms/workflows.d.ts.map +1 -1
  31. package/dist/worker.cjs +1336 -0
  32. package/dist/worker.cjs.map +1 -0
  33. package/dist/worker.d.ts +2 -0
  34. package/dist/worker.d.ts.map +1 -0
  35. package/dist/worker.js +1310 -0
  36. package/dist/worker.js.map +1 -0
  37. package/package.json +30 -24
  38. package/dist/__tests__/__fixtures__/before/index.d.ts +0 -11
  39. package/dist/__tests__/__fixtures__/before/index.d.ts.map +0 -1
  40. package/dist/__tests__/__fixtures__/before/weather-workflow.d.ts +0 -8
  41. package/dist/__tests__/__fixtures__/before/weather-workflow.d.ts.map +0 -1
  42. package/dist/transforms/__fixtures__/activities/weather-workflow/input.d.ts +0 -8
  43. package/dist/transforms/__fixtures__/activities/weather-workflow/input.d.ts.map +0 -1
  44. package/dist/transforms/__fixtures__/activities/weather-workflow/output.d.ts +0 -3
  45. package/dist/transforms/__fixtures__/activities/weather-workflow/output.d.ts.map +0 -1
  46. package/dist/transforms/__fixtures__/workflow/weather-workflow/input.d.ts +0 -8
  47. package/dist/transforms/__fixtures__/workflow/weather-workflow/input.d.ts.map +0 -1
  48. package/dist/transforms/__fixtures__/workflow/weather-workflow/output.d.ts +0 -2
  49. package/dist/transforms/__fixtures__/workflow/weather-workflow/output.d.ts.map +0 -1
  50. package/dist/webpack-loader.cjs +0 -856
  51. package/dist/webpack-loader.cjs.map +0 -1
  52. package/dist/webpack-loader.d.ts +0 -8
  53. package/dist/webpack-loader.d.ts.map +0 -1
  54. package/dist/webpack-plugin.d.ts +0 -18
  55. package/dist/webpack-plugin.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,24 +1,6 @@
1
+ import { toWorkflowType } from './chunk-BF6TR7JX.js';
1
2
  import { createStep, Workflow, Run } from '@mastra/core/workflows';
2
- import { readFileSync, statSync } from 'fs';
3
- import { readFile, writeFile, mkdir } from 'fs/promises';
4
- import { createRequire } from 'module';
5
- import path4 from 'path';
6
- import { fileURLToPath, pathToFileURL } from 'url';
7
- import { SimplePlugin } from '@temporalio/plugin';
8
- import { generate } from '@babel/generator';
9
- import { parse } from '@babel/parser';
10
- import * as t from '@babel/types';
11
- import { transform } from 'esbuild';
12
3
 
13
- // src/workflow.ts
14
-
15
- // src/utils.ts
16
- function toWorkflowType(id) {
17
- const camelCased = id.replace(/[-_]+([a-zA-Z0-9])/g, (_, char) => char.toUpperCase());
18
- return camelCased.endsWith("Workflow") ? camelCased : `${camelCased}Workflow`;
19
- }
20
-
21
- // src/run.ts
22
4
  var TemporalRun = class extends Run {
23
5
  client;
24
6
  taskQueue;
@@ -142,907 +124,7 @@ function init(temporalParams) {
142
124
  createStep
143
125
  };
144
126
  }
145
- var parserPlugins = [
146
- "typescript",
147
- "jsx",
148
- "classProperties",
149
- "classPrivateProperties",
150
- "classPrivateMethods",
151
- "topLevelAwait",
152
- "importAttributes",
153
- "decorators-legacy"
154
- ];
155
- function isIdentifierNamed(node, name) {
156
- return t.isIdentifier(node) && node.name === name;
157
- }
158
- function isTemporalHelperModule(source) {
159
- return typeof source === "string" && /(^|\/)temporal\.(ts|tsx|js|jsx|mts|mjs)?$/.test(source);
160
- }
161
- var strippedExternalModules = /* @__PURE__ */ new Set(["@temporalio/client", "@temporalio/envconfig"]);
162
- function isStrippedExternalModule(source) {
163
- return typeof source === "string" && strippedExternalModules.has(source);
164
- }
165
- function collectImportedNames(statement) {
166
- const names = /* @__PURE__ */ new Set();
167
- for (const specifier of statement.specifiers) {
168
- if (t.isImportDefaultSpecifier(specifier) || t.isImportNamespaceSpecifier(specifier) || t.isImportSpecifier(specifier)) {
169
- if (t.isIdentifier(specifier.local)) {
170
- names.add(specifier.local.name);
171
- }
172
- }
173
- }
174
- return names;
175
- }
176
- function nodeReferencesName(node, names) {
177
- let found = false;
178
- walk(node, (current) => {
179
- if (t.isIdentifier(current) && names.has(current.name)) {
180
- found = true;
181
- return false;
182
- }
183
- });
184
- return found;
185
- }
186
- function isWorkflowHelperDestructure(declaration) {
187
- if (!t.isObjectPattern(declaration.id)) {
188
- return false;
189
- }
190
- return declaration.id.properties.some(
191
- (property) => t.isObjectProperty(property) && !property.computed && t.isIdentifier(property.value) && (property.value.name === "createStep" || property.value.name === "createWorkflow")
192
- );
193
- }
194
- function isCreateWorkflowCall(node) {
195
- return t.isCallExpression(node) && isIdentifierNamed(node.callee, "createWorkflow");
196
- }
197
- function isCreateStepCall(node) {
198
- return t.isCallExpression(node) && isIdentifierNamed(node.callee, "createStep");
199
- }
200
- function getObjectPropertyName(property) {
201
- if (property.computed) {
202
- return null;
203
- }
204
- if (t.isIdentifier(property.key)) {
205
- return property.key.name;
206
- }
207
- if (t.isStringLiteral(property.key)) {
208
- return property.key.value;
209
- }
210
- return null;
211
- }
212
- function walk(node, visitor) {
213
- if (!node) {
214
- return;
215
- }
216
- const result = visitor(node);
217
- if (result === false) {
218
- return;
219
- }
220
- const keys = t.VISITOR_KEYS[node.type] ?? [];
221
- for (const key of keys) {
222
- const value = node[key];
223
- if (Array.isArray(value)) {
224
- for (const child of value) {
225
- if (child && typeof child.type === "string") {
226
- walk(child, visitor);
227
- }
228
- }
229
- continue;
230
- }
231
- if (value && typeof value.type === "string") {
232
- walk(value, visitor);
233
- }
234
- }
235
- }
236
- function hasCreateWorkflowCall(node) {
237
- let found = false;
238
- walk(node, (current) => {
239
- if (isCreateWorkflowCall(current)) {
240
- found = true;
241
- return false;
242
- }
243
- });
244
- return found;
245
- }
246
- function getStepNameFromCall(node) {
247
- const stepId = getCreateStepId(node);
248
- if (!stepId) {
249
- return null;
250
- }
251
- return stepId.replace(/[^a-zA-Z0-9]+(.)/g, (_match, char) => char.toUpperCase()).replace(/^[^a-zA-Z_$]+/, "").replace(/^(.)/, (char) => char.toLowerCase());
252
- }
253
- function createExportedStepStatement(name, initializer) {
254
- return t.exportNamedDeclaration(
255
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier(name), t.cloneNode(initializer, true))])
256
- );
257
- }
258
- function collectInlineCreateSteps(node, seenNames, statements) {
259
- walk(node, (current) => {
260
- if (!isCreateStepCall(current)) {
261
- return;
262
- }
263
- const stepName = getStepNameFromCall(current);
264
- if (!stepName || seenNames.has(stepName)) {
265
- return false;
266
- }
267
- seenNames.add(stepName);
268
- statements.push(createExportedStepStatement(stepName, current));
269
- return false;
270
- });
271
- }
272
- async function transpileModule(sourceText, filePath) {
273
- const loader = path4.extname(filePath).slice(1) || "js";
274
- const { code } = await transform(sourceText, {
275
- loader,
276
- format: "esm",
277
- platform: "node",
278
- target: "node22",
279
- sourcemap: false,
280
- sourcefile: filePath
281
- });
282
- return code ?? "";
283
- }
284
- function getCreateStepId(node) {
285
- if (!node || !isCreateStepCall(node)) {
286
- return null;
287
- }
288
- const [config] = node.arguments;
289
- if (!t.isObjectExpression(config)) {
290
- return null;
291
- }
292
- for (const property of config.properties) {
293
- if (!t.isObjectProperty(property) && !t.isObjectMethod(property)) {
294
- continue;
295
- }
296
- if (getObjectPropertyName(property) !== "id") {
297
- continue;
298
- }
299
- const value = t.isObjectMethod(property) ? null : property.value;
300
- return t.isStringLiteral(value) ? value.value : null;
301
- }
302
- return null;
303
- }
304
- function shouldCountIdentifierAsReference(parent, key) {
305
- if (!parent) {
306
- return true;
307
- }
308
- if ((t.isObjectProperty(parent) || t.isObjectMethod(parent)) && key === "key" && !parent.computed) {
309
- return false;
310
- }
311
- if (t.isMemberExpression(parent) && key === "property" && !parent.computed) {
312
- return false;
313
- }
314
- if (t.isVariableDeclarator(parent) && key === "id") {
315
- return false;
316
- }
317
- if ((t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent) || t.isArrowFunctionExpression(parent)) && key === "params") {
318
- return false;
319
- }
320
- if ((t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent) || t.isClassDeclaration(parent)) && key === "id") {
321
- return false;
322
- }
323
- if ((t.isImportSpecifier(parent) || t.isImportDefaultSpecifier(parent) || t.isImportNamespaceSpecifier(parent)) && (key === "local" || key === "imported")) {
324
- return false;
325
- }
326
- if (t.isExportSpecifier(parent) && key === "exported") {
327
- return false;
328
- }
329
- if (t.isLabeledStatement(parent) && key === "label") {
330
- return false;
331
- }
332
- if (t.isCatchClause(parent) && key === "param") {
333
- return false;
334
- }
335
- if (t.isRestElement(parent) && key === "argument") {
336
- return false;
337
- }
338
- if (t.isAssignmentPattern(parent) && key === "left") {
339
- return false;
340
- }
341
- if (t.isTSPropertySignature(parent) || t.isTSMethodSignature(parent) || t.isTSExpressionWithTypeArguments(parent)) {
342
- return false;
343
- }
344
- return true;
345
- }
346
- function collectRuntimeReferencedIdentifiers(node) {
347
- const refs = /* @__PURE__ */ new Set();
348
- const visit = (current, parent, key) => {
349
- if (!current) {
350
- return;
351
- }
352
- if (current.type.startsWith("TS")) {
353
- return;
354
- }
355
- if (t.isIdentifier(current)) {
356
- if (shouldCountIdentifierAsReference(parent, key)) {
357
- refs.add(current.name);
358
- }
359
- return;
360
- }
361
- for (const visitorKey of t.VISITOR_KEYS[current.type] ?? []) {
362
- const value = current[visitorKey];
363
- if (Array.isArray(value)) {
364
- value.forEach((child) => {
365
- if (t.isNode(child)) {
366
- visit(child, current, visitorKey);
367
- }
368
- });
369
- continue;
370
- }
371
- if (t.isNode(value)) {
372
- visit(value, current, visitorKey);
373
- }
374
- }
375
- };
376
- visit(node, null, null);
377
- return refs;
378
- }
379
- function pruneUnusedTopLevelBindings(statements) {
380
- const bindings = /* @__PURE__ */ new Map();
381
- const liveStatements = /* @__PURE__ */ new Set();
382
- const queue = [];
383
- const markLive = (statementIndex) => {
384
- if (liveStatements.has(statementIndex)) {
385
- return;
386
- }
387
- liveStatements.add(statementIndex);
388
- queue.push(statementIndex);
389
- };
390
- statements.forEach((statement, statementIndex) => {
391
- if (t.isImportDeclaration(statement)) {
392
- for (const specifier of statement.specifiers) {
393
- bindings.set(specifier.local.name, { refs: /* @__PURE__ */ new Set(), statementIndex });
394
- }
395
- return;
396
- }
397
- if (t.isVariableDeclaration(statement)) {
398
- for (const declaration of statement.declarations) {
399
- if (t.isIdentifier(declaration.id)) {
400
- bindings.set(declaration.id.name, {
401
- refs: declaration.init ? collectRuntimeReferencedIdentifiers(declaration.init) : /* @__PURE__ */ new Set(),
402
- statementIndex
403
- });
404
- }
405
- }
406
- return;
407
- }
408
- if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
409
- for (const declaration of statement.declaration.declarations) {
410
- if (t.isIdentifier(declaration.id)) {
411
- bindings.set(declaration.id.name, {
412
- refs: declaration.init ? collectRuntimeReferencedIdentifiers(declaration.init) : /* @__PURE__ */ new Set(),
413
- statementIndex
414
- });
415
- }
416
- }
417
- markLive(statementIndex);
418
- return;
419
- }
420
- markLive(statementIndex);
421
- });
422
- while (queue.length > 0) {
423
- const statementIndex = queue.pop();
424
- const statement = statements[statementIndex];
425
- if (!statement) {
426
- continue;
427
- }
428
- const refs = /* @__PURE__ */ new Set();
429
- if (t.isImportDeclaration(statement)) {
430
- continue;
431
- }
432
- if (t.isVariableDeclaration(statement)) {
433
- for (const declaration of statement.declarations) {
434
- if (declaration.init) {
435
- for (const ref of collectRuntimeReferencedIdentifiers(declaration.init)) {
436
- refs.add(ref);
437
- }
438
- }
439
- }
440
- } else if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
441
- for (const declaration of statement.declaration.declarations) {
442
- if (declaration.init) {
443
- for (const ref of collectRuntimeReferencedIdentifiers(declaration.init)) {
444
- refs.add(ref);
445
- }
446
- }
447
- }
448
- } else {
449
- for (const ref of collectRuntimeReferencedIdentifiers(statement)) {
450
- refs.add(ref);
451
- }
452
- }
453
- for (const ref of refs) {
454
- const binding = bindings.get(ref);
455
- if (binding) {
456
- markLive(binding.statementIndex);
457
- }
458
- }
459
- }
460
- const prunedStatements = [];
461
- statements.forEach((statement, statementIndex) => {
462
- if (!liveStatements.has(statementIndex)) {
463
- return;
464
- }
465
- if (t.isImportDeclaration(statement)) {
466
- const specifiers = statement.specifiers.filter(
467
- (specifier) => liveStatements.has(bindings.get(specifier.local.name)?.statementIndex ?? -1)
468
- );
469
- if (specifiers.length > 0) {
470
- prunedStatements.push(t.importDeclaration(specifiers, statement.source));
471
- }
472
- return;
473
- }
474
- if (t.isVariableDeclaration(statement)) {
475
- const declarations = statement.declarations.filter(
476
- (declaration) => !t.isIdentifier(declaration.id) || liveStatements.has(bindings.get(declaration.id.name)?.statementIndex ?? -1)
477
- );
478
- if (declarations.length > 0) {
479
- prunedStatements.push(t.variableDeclaration(statement.kind, declarations));
480
- }
481
- return;
482
- }
483
- if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
484
- const declarations = statement.declaration.declarations.filter(
485
- (declaration) => !t.isIdentifier(declaration.id) || liveStatements.has(bindings.get(declaration.id.name)?.statementIndex ?? -1)
486
- );
487
- if (declarations.length > 0) {
488
- prunedStatements.push(
489
- t.exportNamedDeclaration(t.variableDeclaration(statement.declaration.kind, declarations))
490
- );
491
- }
492
- return;
493
- }
494
- prunedStatements.push(statement);
495
- });
496
- return prunedStatements;
497
- }
498
-
499
- // src/transforms/activities.ts
500
- function collectTemporalActivityBindings(sourceText, filePath) {
501
- const ast = parse(sourceText, {
502
- sourceType: "module",
503
- plugins: parserPlugins,
504
- sourceFilename: filePath
505
- });
506
- const bindings = [];
507
- const seenNames = /* @__PURE__ */ new Set();
508
- const addBinding = (call) => {
509
- const exportName = getStepNameFromCall(call);
510
- const stepId = getCreateStepId(call);
511
- if (!exportName || !stepId || seenNames.has(exportName)) {
512
- return;
513
- }
514
- seenNames.add(exportName);
515
- bindings.push({ exportName, stepId });
516
- };
517
- const collectInlineBindings = (node) => {
518
- walk(node, (current) => {
519
- if (!isCreateStepCall(current)) {
520
- return;
521
- }
522
- addBinding(current);
523
- return false;
524
- });
525
- };
526
- for (const statement of ast.program.body) {
527
- if (t.isVariableDeclaration(statement) || t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
528
- const declarationStatement = t.isVariableDeclaration(statement) ? statement : statement.declaration;
529
- for (const declaration of declarationStatement.declarations) {
530
- if (!declaration.init) {
531
- continue;
532
- }
533
- if (isCreateStepCall(declaration.init)) {
534
- addBinding(declaration.init);
535
- continue;
536
- }
537
- if (hasCreateWorkflowCall(declaration.init)) {
538
- collectInlineBindings(declaration.init);
539
- }
540
- }
541
- continue;
542
- }
543
- if (hasCreateWorkflowCall(statement)) {
544
- collectInlineBindings(statement);
545
- }
546
- }
547
- return bindings;
548
- }
549
- function createTemporalActivitiesHelperStatements(mastraImportPath = "./index") {
550
- const helperSource = `
551
- function createStep(args) {
552
- return async (params) => {
553
- const { mastra } = await import(${JSON.stringify(mastraImportPath)});
554
- return args.execute({ ...params, mastra });
555
- };
556
- }
557
- `;
558
- return parse(helperSource, {
559
- sourceType: "module",
560
- plugins: parserPlugins
561
- }).program.body;
562
- }
563
- async function buildTemporalActivitiesModule(sourceText, filePath, options = {}) {
564
- const ast = parse(sourceText, {
565
- sourceType: "module",
566
- plugins: parserPlugins,
567
- sourceFilename: filePath
568
- });
569
- const statements = [];
570
- const seenNames = /* @__PURE__ */ new Set();
571
- const strippedNames = /* @__PURE__ */ new Set();
572
- let helperInserted = false;
573
- const ensureHelperInserted = () => {
574
- if (helperInserted) {
575
- return;
576
- }
577
- statements.push(...createTemporalActivitiesHelperStatements(options.mastraImportPath));
578
- helperInserted = true;
579
- };
580
- for (const statement of ast.program.body) {
581
- if (t.isImportDeclaration(statement)) {
582
- if (statement.source.value === "@mastra/core/workflows") {
583
- const retainedSpecifiers = statement.specifiers.filter(
584
- (specifier) => !(t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported) && (specifier.imported.name === "createStep" || specifier.imported.name === "createWorkflow"))
585
- );
586
- if (retainedSpecifiers.length > 0) {
587
- statements.push(t.importDeclaration(retainedSpecifiers, t.stringLiteral(statement.source.value)));
588
- }
589
- continue;
590
- }
591
- if (isTemporalHelperModule(statement.source.value) || isStrippedExternalModule(statement.source.value)) {
592
- for (const name of collectImportedNames(statement)) {
593
- strippedNames.add(name);
594
- }
595
- continue;
596
- }
597
- statements.push(statement);
598
- continue;
599
- }
600
- if (t.isFunctionDeclaration(statement) || t.isClassDeclaration(statement) || t.isTSTypeAliasDeclaration(statement) || t.isTSInterfaceDeclaration(statement) || t.isTSEnumDeclaration(statement)) {
601
- ensureHelperInserted();
602
- statements.push(statement);
603
- continue;
604
- }
605
- if (t.isExpressionStatement(statement) && nodeReferencesName(statement, strippedNames)) {
606
- continue;
607
- }
608
- ensureHelperInserted();
609
- if (t.isVariableDeclaration(statement)) {
610
- const declarations = [];
611
- for (const declaration of statement.declarations) {
612
- if (isWorkflowHelperDestructure(declaration)) {
613
- continue;
614
- }
615
- if (declaration.init && nodeReferencesName(declaration.init, strippedNames)) {
616
- if (t.isIdentifier(declaration.id)) {
617
- strippedNames.add(declaration.id.name);
618
- }
619
- continue;
620
- }
621
- if (!t.isIdentifier(declaration.id) || !declaration.init) {
622
- declarations.push(declaration);
623
- continue;
624
- }
625
- if (isCreateStepCall(declaration.init)) {
626
- seenNames.add(declaration.id.name);
627
- statements.push(createExportedStepStatement(declaration.id.name, declaration.init));
628
- continue;
629
- }
630
- if (hasCreateWorkflowCall(declaration.init)) {
631
- collectInlineCreateSteps(declaration.init, seenNames, statements);
632
- continue;
633
- }
634
- declarations.push(declaration);
635
- }
636
- if (declarations.length > 0) {
637
- statements.push(
638
- t.variableDeclaration(
639
- statement.kind,
640
- declarations.map((declaration) => t.cloneNode(declaration, true))
641
- )
642
- );
643
- }
644
- continue;
645
- }
646
- if (t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration)) {
647
- const declarations = [];
648
- for (const declaration of statement.declaration.declarations) {
649
- if (isWorkflowHelperDestructure(declaration)) {
650
- continue;
651
- }
652
- if (declaration.init && nodeReferencesName(declaration.init, strippedNames)) {
653
- if (t.isIdentifier(declaration.id)) {
654
- strippedNames.add(declaration.id.name);
655
- }
656
- continue;
657
- }
658
- if (!t.isIdentifier(declaration.id) || !declaration.init) {
659
- declarations.push(declaration);
660
- continue;
661
- }
662
- if (isCreateStepCall(declaration.init)) {
663
- seenNames.add(declaration.id.name);
664
- statements.push(createExportedStepStatement(declaration.id.name, declaration.init));
665
- continue;
666
- }
667
- if (hasCreateWorkflowCall(declaration.init)) {
668
- collectInlineCreateSteps(declaration.init, seenNames, statements);
669
- continue;
670
- }
671
- declarations.push(declaration);
672
- }
673
- if (declarations.length > 0) {
674
- statements.push(
675
- t.exportNamedDeclaration(
676
- t.variableDeclaration(
677
- statement.declaration.kind,
678
- declarations.map((declaration) => t.cloneNode(declaration, true))
679
- )
680
- )
681
- );
682
- }
683
- continue;
684
- }
685
- if (t.isExpressionStatement(statement) || t.isExportNamedDeclaration(statement) || t.isExportDefaultDeclaration(statement)) {
686
- collectInlineCreateSteps(statement, seenNames, statements);
687
- continue;
688
- }
689
- statements.push(statement);
690
- }
691
- ensureHelperInserted();
692
- const transformedSource = generate(t.file(t.program(pruneUnusedTopLevelBindings(statements), [], "module")), {
693
- sourceMaps: false
694
- }).code;
695
- return transpileModule(transformedSource, filePath);
696
- }
697
- function getWorkflowImportBindings(program3) {
698
- const bindings = /* @__PURE__ */ new Map();
699
- for (const statement of program3.body) {
700
- if (!t.isImportDeclaration(statement)) {
701
- continue;
702
- }
703
- for (const specifier of statement.specifiers) {
704
- if (t.isImportSpecifier(specifier)) {
705
- bindings.set(specifier.local.name, {
706
- exportName: specifier.local.name,
707
- importedName: t.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value,
708
- source: statement.source.value
709
- });
710
- continue;
711
- }
712
- if (t.isImportDefaultSpecifier(specifier)) {
713
- bindings.set(specifier.local.name, {
714
- exportName: specifier.local.name,
715
- importedName: "default",
716
- source: statement.source.value
717
- });
718
- }
719
- }
720
- }
721
- return bindings;
722
- }
723
- function getWorkflowEntryBindings(program3) {
724
- const workflowBindings = /* @__PURE__ */ new Set();
725
- walk(program3, (node) => {
726
- if (!t.isNewExpression(node) || !isIdentifierNamed(node.callee, "Mastra")) {
727
- return;
728
- }
729
- const [config] = node.arguments;
730
- if (!t.isObjectExpression(config)) {
731
- return;
732
- }
733
- const workflowsProperty = config.properties.find(
734
- (property) => t.isObjectProperty(property) && getObjectPropertyName(property) === "workflows"
735
- );
736
- if (!workflowsProperty || !t.isObjectExpression(workflowsProperty.value)) {
737
- return;
738
- }
739
- for (const property of workflowsProperty.value.properties) {
740
- if (!t.isObjectProperty(property)) {
741
- continue;
742
- }
743
- if (property.shorthand && t.isIdentifier(property.key)) {
744
- workflowBindings.add(property.key.name);
745
- continue;
746
- }
747
- if (t.isIdentifier(property.value)) {
748
- workflowBindings.add(property.value.name);
749
- }
750
- }
751
- });
752
- return workflowBindings;
753
- }
754
- readFileSync(new URL("./temporal-workflow-runtime.mjs", import.meta.url), "utf8");
755
- async function buildWorkflowEntryModuleFromRegistry(sourceText, filePath, registry) {
756
- const ast = parse(sourceText, {
757
- sourceType: "module",
758
- plugins: parserPlugins,
759
- sourceFilename: filePath
760
- });
761
- const workflowBindings = getWorkflowEntryBindings(ast.program);
762
- const importBindings = getWorkflowImportBindings(ast.program);
763
- const exportStatements = [];
764
- const seenExports = /* @__PURE__ */ new Set();
765
- for (const workflowBinding of workflowBindings) {
766
- const importedBinding = importBindings.get(workflowBinding);
767
- if (!importedBinding) {
768
- throw new Error(`Unable to find an import for workflow '${workflowBinding}' in ${filePath}`);
769
- }
770
- const workflowPath = resolveWorkflowPathSync(importedBinding.source, filePath);
771
- const exportNames = registry.get(workflowPath);
772
- if (!exportNames || exportNames.length === 0) {
773
- throw new Error(`Unable to find registered workflow exports for ${workflowPath}`);
774
- }
775
- for (const exportName of exportNames) {
776
- const exportKey = `${importedBinding.source}:${exportName}`;
777
- if (seenExports.has(exportKey)) {
778
- continue;
779
- }
780
- seenExports.add(exportKey);
781
- exportStatements.push(
782
- t.exportNamedDeclaration(
783
- null,
784
- [t.exportSpecifier(t.identifier(exportName), t.identifier(exportName))],
785
- t.stringLiteral(importedBinding.source)
786
- )
787
- );
788
- }
789
- }
790
- return generate(t.file(t.program(exportStatements, [], "module")), {
791
- sourceMaps: false
792
- }).code;
793
- }
794
- function getWorkflowImportSpecifiers(sourceText, filePath) {
795
- const ast = parse(sourceText, {
796
- sourceType: "module",
797
- plugins: parserPlugins,
798
- sourceFilename: filePath
799
- });
800
- const workflowBindings = getWorkflowEntryBindings(ast.program);
801
- const importBindings = getWorkflowImportBindings(ast.program);
802
- const workflowSpecifiers = [];
803
- for (const workflowBinding of workflowBindings) {
804
- const importedBinding = importBindings.get(workflowBinding);
805
- if (!importedBinding) {
806
- throw new Error(`Unable to find an import for workflow '${workflowBinding}' in ${filePath}`);
807
- }
808
- workflowSpecifiers.push(importedBinding.source);
809
- }
810
- return [...new Set(workflowSpecifiers)];
811
- }
812
- function getWorkflowPathCandidates(specifier, importerPath) {
813
- const basePath = path4.resolve(path4.dirname(importerPath), specifier);
814
- return [
815
- basePath,
816
- `${basePath}.ts`,
817
- `${basePath}.tsx`,
818
- `${basePath}.js`,
819
- `${basePath}.jsx`,
820
- `${basePath}.mts`,
821
- `${basePath}.mjs`,
822
- path4.join(basePath, "index.ts"),
823
- path4.join(basePath, "index.tsx"),
824
- path4.join(basePath, "index.js"),
825
- path4.join(basePath, "index.jsx"),
826
- path4.join(basePath, "index.mts"),
827
- path4.join(basePath, "index.mjs")
828
- ];
829
- }
830
- function resolveWorkflowPathSync(specifier, importerPath) {
831
- for (const candidate of getWorkflowPathCandidates(specifier, importerPath)) {
832
- try {
833
- if (statSync(candidate).isFile()) {
834
- return candidate;
835
- }
836
- } catch {
837
- }
838
- }
839
- throw new Error(`Unable to resolve workflow import '${specifier}' from ${importerPath}`);
840
- }
841
- function resolveWorkflowEntriesSync(sourceText, filePath) {
842
- return getWorkflowImportSpecifiers(sourceText, filePath).map(
843
- (specifier) => resolveWorkflowPathSync(specifier, filePath)
844
- );
845
- }
846
- function getModuleSource(module) {
847
- const source = module.originalSource?.() ?? module._source;
848
- if (!source) {
849
- return null;
850
- }
851
- return source.source().toString();
852
- }
853
- async function writeDebugEntryModule(entryFile, code, debugOutputDir) {
854
- if (!debugOutputDir) {
855
- return;
856
- }
857
- const baseDir = path4.dirname(entryFile);
858
- const relativePath = path4.relative(baseDir, entryFile);
859
- const safeRelativePath = relativePath.startsWith("..") ? path4.basename(entryFile) : relativePath;
860
- const outputPath = path4.join(debugOutputDir, "modules", safeRelativePath);
861
- await mkdir(path4.dirname(outputPath), { recursive: true });
862
- await writeFile(outputPath, code, "utf-8");
863
- }
864
- var WorkflowExportRegistry = class {
865
- exportsByFile = /* @__PURE__ */ new Map();
866
- register(filePath, exportNames) {
867
- if (exportNames.length === 0) {
868
- return;
869
- }
870
- this.exportsByFile.set(filePath, [...new Set(exportNames)]);
871
- }
872
- get(filePath) {
873
- return this.exportsByFile.get(filePath);
874
- }
875
- asMap() {
876
- return this.exportsByFile;
877
- }
878
- };
879
- var MastraWorkflowEntryPlugin = class {
880
- constructor(options) {
881
- this.options = options;
882
- }
883
- options;
884
- apply(compiler) {
885
- compiler.hooks.compilation.tap("MastraWorkflowEntryPlugin", (compilation) => {
886
- compilation.hooks.finishModules.tapPromise("MastraWorkflowEntryPlugin", async (modules) => {
887
- const entryModule = [...modules].find(
888
- (module) => "resource" in module && module.resource === this.options.entryFile
889
- );
890
- if (!entryModule) {
891
- return;
892
- }
893
- const source = getModuleSource(entryModule);
894
- if (!source) {
895
- return;
896
- }
897
- const code = await buildWorkflowEntryModuleFromRegistry(
898
- source,
899
- this.options.entryFile,
900
- this.options.registry.asMap()
901
- );
902
- entryModule._source = new compiler.webpack.sources.RawSource(code);
903
- entryModule._ast = null;
904
- entryModule._sourceSizes?.clear?.();
905
- await writeDebugEntryModule(this.options.entryFile, code, this.options.debugOutputDir);
906
- });
907
- });
908
- }
909
- };
910
-
911
- // src/plugin.ts
912
- function getDebugOutputDir() {
913
- return path4.resolve(process.cwd(), ".mastra/temporal");
914
- }
915
- function getGeneratedActivitiesModulePath(workflowPath) {
916
- const extension = path4.extname(workflowPath);
917
- const baseName = path4.basename(workflowPath, extension);
918
- return path4.join(path4.dirname(workflowPath), `.${baseName}.temporal.activities.mjs`);
919
- }
920
- function getMastraImportPath(workflowPath, entryFile) {
921
- const relativePath = path4.relative(path4.dirname(workflowPath), entryFile);
922
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
923
- }
924
- var WriteWebpackBundleDebugPlugin = class {
925
- constructor(outputDir) {
926
- this.outputDir = outputDir;
927
- }
928
- outputDir;
929
- apply(compiler) {
930
- compiler.hooks.assetEmitted.tapPromise(
931
- "MastraTemporalWriteWebpackBundleDebugPlugin",
932
- async (filename, { content }) => {
933
- const bundleDir = path4.join(this.outputDir, "bundle");
934
- const targetPath = path4.join(bundleDir, filename);
935
- await mkdir(path4.dirname(targetPath), { recursive: true });
936
- await writeFile(targetPath, content);
937
- }
938
- );
939
- }
940
- };
941
- var MastraPlugin = class extends SimplePlugin {
942
- src;
943
- debugOutputDir;
944
- compiledActivities = /* @__PURE__ */ new Map();
945
- constructor({ src, debug = false }) {
946
- super({
947
- name: "Mastra"
948
- });
949
- this.src = src.startsWith("file://") ? fileURLToPath(src) : src;
950
- this.debugOutputDir = debug ? getDebugOutputDir() : null;
951
- }
952
- loadWorkflowActivitiesModule(workflowPath) {
953
- const cachedModule = this.compiledActivities.get(workflowPath);
954
- if (cachedModule) {
955
- return cachedModule;
956
- }
957
- const modulePromise = (async () => {
958
- const sourceText = await readFile(workflowPath, "utf8");
959
- const generatedModulePath = getGeneratedActivitiesModulePath(workflowPath);
960
- const transformedModule = await buildTemporalActivitiesModule(sourceText, workflowPath, {
961
- mastraImportPath: getMastraImportPath(workflowPath, this.src)
962
- });
963
- await writeFile(generatedModulePath, transformedModule);
964
- const importedModule = await import(pathToFileURL(generatedModulePath).href);
965
- return importedModule;
966
- })();
967
- this.compiledActivities.set(workflowPath, modulePromise);
968
- return modulePromise;
969
- }
970
- configureWorker(options) {
971
- const entrySource = readFileSync(this.src, "utf8");
972
- const workflowPaths = resolveWorkflowEntriesSync(entrySource, this.src);
973
- const generatedActivities = Object.assign({}, options.activities);
974
- for (const workflowPath of workflowPaths) {
975
- const workflowSource = readFileSync(workflowPath, "utf8");
976
- const activityBindings = collectTemporalActivityBindings(workflowSource, workflowPath);
977
- for (const binding of activityBindings) {
978
- if (generatedActivities[binding.stepId]) {
979
- continue;
980
- }
981
- generatedActivities[binding.stepId] = async (...args) => {
982
- const activityModule = await this.loadWorkflowActivitiesModule(workflowPath);
983
- const activity = activityModule[binding.exportName];
984
- if (typeof activity !== "function") {
985
- throw new Error(`Unable to load activity '${binding.exportName}' from ${workflowPath}`);
986
- }
987
- return activity(...args);
988
- };
989
- }
990
- }
991
- return {
992
- ...options,
993
- workflowsPath: this.src,
994
- activities: generatedActivities
995
- };
996
- }
997
- configureBundler(options) {
998
- const require2 = createRequire(import.meta.url);
999
- const loader = require2.resolve("@mastra/temporal/webpack-loader");
1000
- const existingWebpackConfigHook = options.webpackConfigHook;
1001
- const registry = new WorkflowExportRegistry();
1002
- const webpackConfigHook = (config) => {
1003
- const nextConfig = existingWebpackConfigHook ? existingWebpackConfigHook(config) : config;
1004
- const rules = nextConfig.module?.rules ?? [];
1005
- const plugins = [
1006
- ...nextConfig.plugins ?? [],
1007
- new MastraWorkflowEntryPlugin({
1008
- entryFile: this.src,
1009
- registry,
1010
- debugOutputDir: this.debugOutputDir
1011
- })
1012
- ];
1013
- if (this.debugOutputDir) {
1014
- plugins.push(new WriteWebpackBundleDebugPlugin(this.debugOutputDir));
1015
- }
1016
- return {
1017
- ...nextConfig,
1018
- module: {
1019
- ...nextConfig.module,
1020
- rules: [
1021
- ...rules,
1022
- {
1023
- test: /\.(ts|tsx|js|jsx)$/,
1024
- exclude: /node_modules/,
1025
- use: {
1026
- loader,
1027
- options: {
1028
- entryFile: this.src,
1029
- debugOutputDir: this.debugOutputDir,
1030
- registry
1031
- }
1032
- }
1033
- }
1034
- ]
1035
- },
1036
- plugins
1037
- };
1038
- };
1039
- return {
1040
- ...options,
1041
- webpackConfigHook
1042
- };
1043
- }
1044
- };
1045
127
 
1046
- export { MastraPlugin, init };
128
+ export { init };
1047
129
  //# sourceMappingURL=index.js.map
1048
130
  //# sourceMappingURL=index.js.map