Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/nested-step-function-expression.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@workflow/swc-plugin': patch
---

A `"use step"` function expression bound to a variable inside a workflow or another function (`const send = async function () { "use step"; ... }`) is now a nested step like the arrow form: hoisted, namespaced by the enclosing function and given the variables it captures. It was treated as a module-level step, so its step was never registered and the run failed with "Step ... is not registered".
2 changes: 2 additions & 0 deletions packages/swc-plugin-workflow/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,8 @@ example.workflowId = "workflow//./input//example";
})(example$innerStep, "step//./input//example/innerStep");
```

The same applies to every form of nested step: a function declaration (as above), an arrow function or function expression bound to a `const`/`let`/`var` (`const act = async () => { "use step"; ... }`, `const act = async function summarize() { "use step"; ... }`), and a function or arrow expression that is not bound to a variable (for example one that is returned). A step bound to a variable takes the variable's name (`example/act`), not the function expression's own name. An unbound function expression takes its own name, and an unbound anonymous one is named `_anonymousStepN`.

#### Same-named steps in different block scopes

Two nested steps with the same local name in different block scopes of one enclosing function are distinct functions. The first one (in source order) keeps the plain name; each later one gets a `~N` suffix in its step ID (`N` = 1, 2, ...). The same applies to object property steps on same-named objects (e.g. `helpers.act` in two branches), and nested steps and object property steps share a namespace (a step nested in a function `helpers` and a step property on an object `helpers` are both `helpers/act`).
Expand Down
74 changes: 74 additions & 0 deletions packages/swc-plugin-workflow/transform/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8320,6 +8320,80 @@ impl VisitMut for StepTransform {
// It's valid - proceed with transformation
self.insert_step_function_name(name.clone());

// Inside a function (for example a workflow body), a
// `const name = async function () { "use step" }` is a
// nested step, exactly like the arrow form below: it is
// hoisted, namespaced by the enclosing function and
// handed the closure variables it captures. Treating it
// as a module-level step registered nothing in step mode
// and called an unregistered, un-namespaced step ID
// without its closure variables in workflow mode.
if !self.in_module_level {
let parent_name = self
.current_parent_function_name
.clone()
.unwrap_or_default();
match self.mode {
TransformMode::Step => {
let mut cloned_function = fn_expr.function.clone();
self.remove_use_step_directive(&mut cloned_function.body);
let closure_vars =
ClosureVariableCollector::collect_from_function(
&cloned_function,
&self.module_imports,
&self.declared_identifiers,
);
let hoisted_fn_expr = FnExpr {
ident: Some(Ident::new(
name.clone().into(),
DUMMY_SP,
SyntaxContext::empty(),
)),
function: cloned_function,
};
self.push_nested_step_function((
name.clone(),
hoisted_fn_expr,
fn_expr.function.span,
closure_vars,
false, // Not an arrow function
parent_name,
false, // Regular functions have their own `this`
));
// Keep the original with the directive stripped, so
// direct (non-workflow) calls keep normal closure
// semantics; the hoisted copy is registered separately.
self.remove_use_step_directive(&mut fn_expr.function.body);
}
TransformMode::Workflow => {
let step_fn_name = self.record_nested_step_name(
&name,
&parent_name,
fn_expr.function.span,
);
let step_id = self.create_id(
Some(&step_fn_name),
fn_expr.function.span,
false,
);
let closure_vars =
ClosureVariableCollector::collect_from_function(
&fn_expr.function,
&self.module_imports,
&self.declared_identifiers,
);
*init = Box::new(
self.create_step_proxy_reference(
&step_id,
&closure_vars,
),
);
}
TransformMode::Detect => {}
}
continue;
}

match self.mode {
TransformMode::Step => {
self.remove_use_step_directive(&mut fn_expr.function.body);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// A `"use step"` function expression bound to a const inside a function is a
// nested step, like the arrow form: hoisted, namespaced by the enclosing
// function, and given the closure variables it captures.
export async function closureSteps(n, label) {
'use workflow';

const named = async function summarize() {
'use step';
return `${label}:${n + 1}`;
};

const anonymous = async function () {
'use step';
return n * 2;
};

return [await named(), await anonymous()];
}

function stepWrapperReturnNamedFunctionExprVar(a, b) {
const fn = async function inner() {
'use step';
return a + b;
};
return fn;
}

export async function usesWrapper() {
'use workflow';
return stepWrapperReturnNamedFunctionExprVar(1, 2)();
}

// At module level it stays a module-level step.
const moduleLevel = async function () {
'use step';
return 1;
};

export async function usesModuleLevel() {
'use workflow';
return moduleLevel();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**__internal_workflows{"workflows":{"input.js":{"closureSteps":{"workflowId":"workflow//./input//closureSteps"},"usesModuleLevel":{"workflowId":"workflow//./input//usesModuleLevel"},"usesWrapper":{"workflowId":"workflow//./input//usesWrapper"}}},"steps":{"input.js":{"closureSteps/anonymous":{"stepId":"step//./input//closureSteps/anonymous"},"closureSteps/named":{"stepId":"step//./input//closureSteps/named"},"moduleLevel":{"stepId":"step//./input//moduleLevel"},"stepWrapperReturnNamedFunctionExprVar/fn":{"stepId":"step//./input//stepWrapperReturnNamedFunctionExprVar/fn"}}}}*/;
async function closureSteps$named() {
const { label, n } = function() {
var __wf_ctx = globalThis[Symbol.for("WORKFLOW_STEP_CONTEXT_STORAGE")], __wf_store = __wf_ctx && __wf_ctx.getStore();
if (!__wf_store) throw new Error("Closure variables can only be accessed inside a step function");
return __wf_store.closureVars || {};
}();
return `${label}:${n + 1}`;
}
(function(__wf_fn, __wf_id) {
var __wf_sym = Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = new Map());
__wf_reg.set(__wf_id, __wf_fn);
__wf_fn.stepId = __wf_id;
Object.defineProperty(__wf_fn, "name", {
value: "closureSteps$named",
configurable: true
});
})(closureSteps$named, "step//./input//closureSteps/named");
async function closureSteps$anonymous() {
const { n } = function() {
var __wf_ctx = globalThis[Symbol.for("WORKFLOW_STEP_CONTEXT_STORAGE")], __wf_store = __wf_ctx && __wf_ctx.getStore();
if (!__wf_store) throw new Error("Closure variables can only be accessed inside a step function");
return __wf_store.closureVars || {};
}();
return n * 2;
}
(function(__wf_fn, __wf_id) {
var __wf_sym = Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = new Map());
__wf_reg.set(__wf_id, __wf_fn);
__wf_fn.stepId = __wf_id;
Object.defineProperty(__wf_fn, "name", {
value: "closureSteps$anonymous",
configurable: true
});
})(closureSteps$anonymous, "step//./input//closureSteps/anonymous");
async function stepWrapperReturnNamedFunctionExprVar$fn() {
const { a, b } = function() {
var __wf_ctx = globalThis[Symbol.for("WORKFLOW_STEP_CONTEXT_STORAGE")], __wf_store = __wf_ctx && __wf_ctx.getStore();
if (!__wf_store) throw new Error("Closure variables can only be accessed inside a step function");
return __wf_store.closureVars || {};
}();
return a + b;
}
(function(__wf_fn, __wf_id) {
var __wf_sym = Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = new Map());
__wf_reg.set(__wf_id, __wf_fn);
__wf_fn.stepId = __wf_id;
Object.defineProperty(__wf_fn, "name", {
value: "stepWrapperReturnNamedFunctionExprVar$fn",
configurable: true
});
})(stepWrapperReturnNamedFunctionExprVar$fn, "step//./input//stepWrapperReturnNamedFunctionExprVar/fn");
// A `"use step"` function expression bound to a const inside a function is a
// nested step, like the arrow form: hoisted, namespaced by the enclosing
// function, and given the closure variables it captures.
export async function closureSteps(n, label) {
throw new Error("You attempted to execute workflow closureSteps function directly. To start a workflow, use start(closureSteps) from workflow/api");
}
closureSteps.workflowId = "workflow//./input//closureSteps";
export async function usesWrapper() {
throw new Error("You attempted to execute workflow usesWrapper function directly. To start a workflow, use start(usesWrapper) from workflow/api");
}
usesWrapper.workflowId = "workflow//./input//usesWrapper";
// At module level it stays a module-level step.
const moduleLevel = async function() {
return 1;
};
(function(__wf_fn, __wf_id) {
var __wf_sym = Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = new Map());
__wf_reg.set(__wf_id, __wf_fn);
__wf_fn.stepId = __wf_id;
Object.defineProperty(__wf_fn, "name", {
value: "moduleLevel",
configurable: true
});
})(moduleLevel, "step//./input//moduleLevel");
export async function usesModuleLevel() {
throw new Error("You attempted to execute workflow usesModuleLevel function directly. To start a workflow, use start(usesModuleLevel) from workflow/api");
}
usesModuleLevel.workflowId = "workflow//./input//usesModuleLevel";
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**__internal_workflows{"workflows":{"input.js":{"closureSteps":{"workflowId":"workflow//./input//closureSteps"},"usesModuleLevel":{"workflowId":"workflow//./input//usesModuleLevel"},"usesWrapper":{"workflowId":"workflow//./input//usesWrapper"}}},"steps":{"input.js":{"closureSteps/anonymous":{"stepId":"step//./input//closureSteps/anonymous"},"closureSteps/named":{"stepId":"step//./input//closureSteps/named"},"moduleLevel":{"stepId":"step//./input//moduleLevel"},"stepWrapperReturnNamedFunctionExprVar/fn":{"stepId":"step//./input//stepWrapperReturnNamedFunctionExprVar/fn"}}}}*/;
// A `"use step"` function expression bound to a const inside a function is a
// nested step, like the arrow form: hoisted, namespaced by the enclosing
// function, and given the closure variables it captures.
export async function closureSteps(n, label) {
const named = globalThis[Symbol.for("WORKFLOW_USE_STEP")]("step//./input//closureSteps/named", ()=>({
label,
n
}));
const anonymous = globalThis[Symbol.for("WORKFLOW_USE_STEP")]("step//./input//closureSteps/anonymous", ()=>({
n
}));
return [
await named(),
await anonymous()
];
}
closureSteps.workflowId = "workflow//./input//closureSteps";
globalThis.__private_workflows.set("workflow//./input//closureSteps", closureSteps);
function stepWrapperReturnNamedFunctionExprVar(a, b) {
const fn = globalThis[Symbol.for("WORKFLOW_USE_STEP")]("step//./input//stepWrapperReturnNamedFunctionExprVar/fn", ()=>({
a,
b
}));
return fn;
}
export async function usesWrapper() {
return stepWrapperReturnNamedFunctionExprVar(1, 2)();
}
usesWrapper.workflowId = "workflow//./input//usesWrapper";
globalThis.__private_workflows.set("workflow//./input//usesWrapper", usesWrapper);
// At module level it stays a module-level step.
const moduleLevel = globalThis[Symbol.for("WORKFLOW_USE_STEP")]("step//./input//moduleLevel");
export async function usesModuleLevel() {
return moduleLevel();
}
usesModuleLevel.workflowId = "workflow//./input//usesModuleLevel";
globalThis.__private_workflows.set("workflow//./input//usesModuleLevel", usesModuleLevel);
13 changes: 12 additions & 1 deletion workbench/vitest/test/nested-step-ids.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest';
import { start } from 'workflow/api';
import { nestedStepBranchWorkflow } from '../workflows/nested-step-ids.js';
import {
nestedStepBranchWorkflow,
nestedStepFunctionExpressionWorkflow,
} from '../workflows/nested-step-ids.js';

describe('nested step IDs', () => {
it.each([
Expand All @@ -10,4 +13,12 @@ describe('nested step IDs', () => {
const run = await start(nestedStepBranchWorkflow, [branch]);
await expect(run.returnValue).resolves.toBe(expected);
});

it('runs a function expression step that captures workflow variables', async () => {
const run = await start(nestedStepFunctionExpressionWorkflow, [
20,
'total',
]);
await expect(run.returnValue).resolves.toEqual(['total:21', 40]);
});
});
19 changes: 19 additions & 0 deletions workbench/vitest/workflows/nested-step-ids.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,22 @@ export async function nestedStepBranchWorkflow(branch: 'a' | 'b') {
};
return act();
}

export async function nestedStepFunctionExpressionWorkflow(
n: number,
label: string
) {
'use workflow';

// Function expressions bound to a const are nested steps like the arrow
// form: hoisted, namespaced, and handed the variables they capture.
const named = async function summarize() {
'use step';
return `${label}:${n + 1}`;
};
const anonymous = async function () {
'use step';
return n * 2;
};
return [await named(), await anonymous()];
}
Loading