* fix(next): always apply turbopack content condition regardless of builder mode
When lazy discovery is enabled (deferred builder), shouldApplyTurboCondition
was false, so turbopack.rules were added with no content filter — causing the
workflow loader to run on every JS/TS file. Apply the content condition
unconditionally so the loader only fires on files with workflow directives.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* add changeset
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
* [next] make lazyDiscovery the default in withWorkflow
Flips the default for `workflows.lazyDiscovery` from `false` to `true`
so new projects get deferred workflow discovery automatically on Next.js
versions that support deferred entries (>= 16.2.0-canary.48). Older
versions continue to fall back to eager discovery.
Users can still opt back into eager discovery explicitly by passing
`workflows: { lazyDiscovery: false }`.
Also:
- Remove the now-redundant `lazyDiscovery: true` from the Next.js
workbench apps.
- Reword the fallback warning for clarity when lazy is the default.
- Update the local-build e2e assertion to match the new warning text.
- Update the withWorkflow docs with the new default.
* [workbench] remove commented 'export default nextConfig' lines
* Warn when serverExternalPackages hides workflow-enabled packages
Add a build-time warning when packages in serverExternalPackages contain
workflow code ('use step', 'use workflow', or serialization classes).
These packages are completely invisible to the workflow compiler when
externalized, causing silent runtime failures.
The warning detects workflow patterns via two methods:
- Fast path: check package.json dependencies for @workflow/serde
- Thorough path: read the package entry file and run pattern detection
Also adds documentation in the serialization guide about the
externalization footgun for 3rd-party packages.
* Auto-remove workflow packages from serverExternalPackages
When workflow-enabled dependencies are externalized in Next.js, compiler transforms are skipped and runtime failures follow. Detect those packages in withWorkflow, remove them from serverExternalPackages for the current build, and keep a generalized externalPackages warning fallback for non-Next builders.
* Address review feedback: add entry-point limitation comment and missing test case
* Add stable Next.js eager and lazy test coverage
* Address PR review feedback
* Fix eager Next step route builds
* Fix eager Next manifest refreshes
* Fix eager Next e2e stack assertions
* Externalize native step bundle bindings
* Lazy load Vercel world runtime
* Fix Next dev step sourcemap assertions
* Consolidate eager build changesets
* Fix Vercel world tracing in Next deployments
* Externalize Vercel world in Next builds
* Fix webpack tracing for Vercel world deps
* Fix eager workflow route bundling
* Rely on Next server externals
* refactor(next): remove step file copy mechanism from deferred builder
Step sources are now imported directly into the generated `step/route.js`
using the same `getImportPath`-based logic already used for serde files.
This is possible because the SWC plugin's client mode was merged into
step mode (#1686), so the workflow loader always runs in step mode and
transforms every file it sees, including those from packages.
Removed:
- `__workflow_step_files__/` per-file copies with hashed names, metadata
comments, inline source maps, and bare-specifier rewriting via
`enhanced-resolve`
- `createResponseBuiltinsStepFile`; builtins are now imported via
`require.resolve('workflow/internal/builtins')` at build time
- `step-copy-utils.ts` and all copy-specific branches in `loader.ts`
- `enhanced-resolve` dependency
The deferred builder still removes the legacy `__workflow_step_files__/`
directory on boot so upgrades leave no stale artifacts behind.
Dev tests that inspected copied step file contents now inspect the
manifest.json entries (which list every discovered step keyed by source
path).
* refactor(next): scrub historical phrasing from code comments
* test: update next step stack expectations
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
* refactor(swc-plugin): remove client transform mode, merge into step mode
Remove the `client` transform mode from the SWC compiler plugin. The
`client` and `step` modes were nearly identical — both preserved step
function bodies, replaced workflow bodies with throw stubs, and emitted
the same JSON manifest. Step mode now absorbs all client-mode behaviors:
- Dead code elimination (previously only workflow + client)
- Hoisted variable references for object property steps
- All integrations use mode: 'step' instead of 'client'
BREAKING CHANGE: The `client` value for the SWC plugin `mode` option is
no longer accepted. Use `step` instead.
* fix(nitro): force-inline workflow packages in dev mode for serde classId registration
In dev mode, Nitro's Rollup externalizes npm packages like @workflow/core,
so the SWC transform plugin never processes files like run.js. This means
serde classes (e.g. Run) never get the classId registration IIFE, causing
serialization failures when step functions return Run instances.
Uses a Rollup resolveId hook to force workflow SDK packages to be bundled
(non-external) while leaving all other dependencies external. This is more
targeted than noExternals=true which bundles everything and causes TDZ
errors from circular imports in packages like vue-bundle-renderer/h3.
The Nitro module now also ignores .nitro/workflow/** in watchOptions so
writing generated workflow bundles does not retrigger Nitro's own dev
bundle rebuild loop.
Also wraps dev:reload workflow rebuilds and makes LocalBuilder.build()
atomic (writes to temp files, renames on success) to avoid partial output
state during HMR.
For Nuxt, also configures Vite's ssr.noExternal to bundle workflow
packages in the SSR context.
* fix(nitro,nuxt): address review feedback on dev-mode classId fix
- nitro builders: use crypto.randomUUID() for temp file suffix instead of
Date.now() to avoid collisions under rapid/concurrent build() calls,
and serialize concurrent build() calls through an internal queue so
two overlapping dev rebuilds cannot clobber each other's temp outputs.
- nitro index: use fileURLToPath() to convert file:// URLs to filesystem
paths, which correctly handles Windows paths (file:///C:/... -> C:\...)
and percent-decoding, instead of relying on new URL(...).pathname.
- nuxt module: normalize vite.ssr.noExternal to an array (preserving any
existing string/RegExp/array entry) before appending workflow package
matchers, so the force-bundle behavior is not a no-op when noExternal
is already set to a non-array value.
* fix(next): resolve next/package.json from working directory first
In npm workspaces monorepos, `@workflow/next` can be hoisted to the root
`node_modules/` while `next` stays in a workspace's local `node_modules/`.
The eager `require('next/package.json')` on the fallback path resolved
relative to `@workflow/next`'s own location, failing before the correct
working-directory-relative resolution could run.
Restructure `resolveNextVersion()` to try the working directory path first,
fall back to the package-relative path second, and wrap both in separate
try/catch blocks so neither can crash the process.
Closes#1680
* fix(next): capture resolution errors and include workingDir in error message
Address review feedback: capture caught errors from both resolution
attempts and attach them via `cause` on the final thrown error. Include
the working directory in the error message to aid debugging in monorepo
and CI environments.
* fix(next): resolve bare specifiers in copied step files for lazy discovery
When the deferred builder copies step files to __workflow_step_files__/,
bare specifiers that are transitive SDK deps can't resolve from the app
directory. Use enhanced-resolve with ESM conditions (preferring 'import'
over 'require') to resolve from the original source location, only when
the specifier can't be resolved from the app directory.
Also add enhanced-resolve to the pnpm catalog and use catalog: in both
@workflow/builders and @workflow/next.
* fix(next): address review feedback on lazy discovery resolver
- Cache ESM/CJS resolvers as class fields instead of re-creating per call
- Remove redundant try/catch (resolveBareCopiedStepSpecifier already
returns undefined on failure)
- Use shared NODE_RESOLVE_OPTIONS / NODE_ESM_RESOLVE_OPTIONS matching
the configuration in swc-esbuild-plugin.ts for consistent resolution
* Remove isWorkflowSdkFile serde exclusion
The SWC detect mode's AST-level manifest (hasManifestEntries) already
correctly filters files without serde class definitions. The broad
isWorkflowSdkFile path exclusion is redundant and was preventing
class definitions in SDK packages from being discovered.
Removed from: builders, next, rollup
* Address review feedback: major semver bump, fix doc comment, add tests
- Bump changeset to major (removing exported APIs is breaking)
- Fix misleading doc comment referencing 'detect mode' in shouldTransformFile
- Add unit tests for shouldTransformFile covering all code paths
* Add AST-level serde filtering to Next.js deferred builder
The isWorkflowSdkFile path-based exclusion was removed from all paths,
but the Next.js deferred builder (collectTransitiveSerdeFiles) was still
using regexp-only detection, causing SDK internal files to be bundled
into the workflow sandbox and triggering stack overflows.
Fix: add applySwcTransform('detect', ...) verification at the end of
collectTransitiveSerdeFiles(). Regex-matched serde candidates are now
verified via the SWC plugin's AST-level manifest to confirm they
actually define serde classes before inclusion in the bundle.
* Add detect mode to SWC plugin for false positive directive filtering
Add a new 'detect' mode to the SWC workflow plugin that walks the AST
to find directives and serde patterns and emits the manifest, but does
not transform any code. The discover-entries plugin now uses a two-phase
approach: fast regexp pre-scan to filter out most files, then SWC detect
mode on candidates to validate at the AST level. This eliminates false
positives where directive-like strings appear inside template literals
or other non-code contexts. The mode:false syntax-only transform is also
removed since esbuild handles TypeScript natively.
* Keep SWC syntax transform in discover phase for decorator support
esbuild does not support legacy decorators or emitDecoratorMetadata,
so all files still need the SWC syntax transform (TS→JS) during
discovery. For regexp-matched files the 'detect' mode handles both
the syntax transform and manifest in a single pass; for all other
files the existing mode:false call is used.
* Use Set for discoveredWorkflows/Steps/SerdeFiles
Eliminates the manual .includes() dedup check and prevents duplicate
entries structurally.
* Update DeferredDiscoveredEntries to use Set<string>
* Add @workflow/next to changeset
The `dataDir` option was accepted in the type definition but never
read — `WORKFLOW_LOCAL_DATA_DIR` was unconditionally set to
`.next/workflow-data`. Remove the dead option to avoid confusion.
* chore: bump next to 16.2.1
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test: run deferred Next dev e2e assertions on stable
Bump Next.js to 16.2.1 in docs and swc-playground and update lockfile.
* fix(next): copy all deferred step sources for step-mode transforms
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Peter Wielander <mittgfu@gmail.com>
* Set maxDuration: "max" in vc-config for workflow functions
* Use maxDuration: 60 for flow route, "max" for step/webhook
* Remove explicit maxDuration from webhook route, rely on plan default
## Summary
When `WORKFLOW_PUBLIC_MANIFEST=1` is set, each framework builder exposes the workflow manifest at `/.well-known/workflow/v1/manifest.json` via the most appropriate mechanism for the framework:
- **Next.js**: Copies manifest to `public/.well-known/workflow/v1/manifest.json` (served as a static file)
- **SvelteKit**: Copies manifest to `static/.well-known/workflow/v1/manifest.json` (served as a static file)
- **Vercel Build Output API** (example workbench): Copies manifest to `.vercel/output/static/.well-known/workflow/v1/manifest.json` (served as a static file)
- **Nitro** (vite, hono, express, fastify, nuxt, nitro-v2, nitro-v3): Registers a virtual handler that reads and serves the manifest JSON
- **Astro**: Generates a `manifest.json.js` page route that returns the manifest JSON
- **NestJS**: Adds a `@Get('manifest.json')` endpoint on the `WorkflowController` (gated by the env var at runtime)
### Other changes
- `BaseBuilder.createManifest()` now returns the manifest JSON string so framework builders can use it
- Added `shouldExposePublicManifest` getter to `BaseBuilder`
- Fixed Astro `LocalBuilder` which was missing the `createManifest()` call that all other framework builders have
- Removed unused `public/` directory and static file copy from the example workbench build script
- Added `WORKFLOW_PUBLIC_MANIFEST` to `turbo.json` build task env so Vercel builds can access it
- Added generated manifest paths to `.gitignore`
Fixed a bug in module specifier resolution and added support for package subpath exports in workflow IDs.
### What changed?
- Fixed a caching bug in the module specifier resolution system that could cause incorrect IDs
- Added support for subpath exports in package IDs (e.g., `workflow/internal/builtins@4.0.0`)
- Improved module resolution by passing absolute file paths to the SWC transform
- Enhanced manifest merging to properly combine results from both workflow and step bundles
- Updated builders to return and merge manifests from both workflow and step bundles
### How to test?
1. Build a project that uses subpath exports in packages
2. Verify that workflow IDs correctly include the subpath (e.g., `workflow/internal/builtins@4.0.0`)
3. Test with a project that has multiple builds to ensure module specifier caching works correctly
### Why make this change?
This change addresses an issue where the module specifier cache could return incorrect results, leading to inconsistent workflow IDs. It also adds support for packages with multiple entry points through subpath exports, ensuring that steps with the same name in different subpaths don't collide. This improves the reliability of cross-bundle references and makes the system more robust when working with complex package structures.
## Summary
This PR changes how the SWC compiler generates IDs for workflows, steps, and classes. Instead of using raw file paths, IDs are now based on **Node.js module specifiers** when the file belongs to a package (either in `node_modules` or a workspace package).
## Motivation
Previously, IDs were generated using file paths like `step//src/jobs/order.ts//fetchData`. This caused several issues:
1. **Package exports conditions**: When a package uses conditional exports (e.g., `"workflow"` vs `"default"` conditions in `package.json`), the same import specifier can resolve to different files. Using file paths meant IDs could differ based on which export condition was used.
2. **Cross-bundle consistency**: Classes serialized in one bundle couldn't be deserialized in another if the file paths differed.
3. **Version tracking**: No way to include package versions in IDs for cache invalidation.
## Changes
### New ID Format
IDs now use the format `{type}//{modulePath}//{identifier}` where `modulePath` is either:
- A **module specifier** like `point@0.0.1` or `@myorg/shared@1.2.3` for package files
- A **relative path** prefixed with `./` like `./src/jobs/order` for local app files
Examples:
- `step//workflow@4.0.1-beta.50//fetch` (SDK step)
- `step//./workflows/order//processOrder` (local step)
- `class//point@0.0.1//Point` (package class)
- `class//./src/models/User//User` (local class)
### New Module Specifier Resolution
Added `packages/builders/src/module-specifier.ts` which:
- Detects if a file is in `node_modules` or a workspace package
- Finds the nearest `package.json` and extracts name/version
- Returns the module specifier for the SWC plugin to use
### SWC Plugin Changes
- Added `moduleSpecifier` option to plugin config
- Updated `naming.rs` to support both module specifiers and relative paths
- Added `get_module_path()` helper that uses specifier when available, falls back to `./filename` format
### Special Cases
- **Builtin functions** (`__builtin_*`): Continue to use just the function name as the ID for stable, version-independent lookup from the workflow VM runtime.
## Testing
- Updated all 125+ SWC plugin test fixtures to use new ID format
- Added tests for module specifier resolution
- Added tests for Windows path normalization in naming
## Breaking Changes
This is technically a breaking change for any persisted workflow runs that reference the old ID format. However, since IDs are internal implementation details and not user-facing, this should not affect end users.
## Files Changed
- `packages/builders/src/module-specifier.ts` - **NEW**: Module specifier resolution logic
- `packages/builders/src/apply-swc-transform.ts` - Pass module specifier to SWC plugin
- `packages/builders/src/base-builder.ts` - Use `getImportPath` for virtual entry imports
- `packages/swc-plugin-workflow/transform/src/lib.rs` - Accept and use module specifier
- `packages/swc-plugin-workflow/transform/src/naming.rs` - New ID formatting with module paths
- `packages/swc-plugin-workflow/spec.md` - Updated documentation
- `packages/core/e2e/e2e.test.ts` - Updated test assertions for new ID format
Added automatic discovery for custom classes with workflow serialization, allowing serialization classes to be defined in separate files without requiring explicit directives.
### What changed?
- Added detection for files containing custom class serialization patterns:
- Files importing from `@workflow/serde`
- Files using `Symbol.for('workflow-serialize')` or `Symbol.for('workflow-deserialize')`
- Created shared utilities in `transform-utils.ts` for consistent pattern detection across all build tools
- Updated Next.js, Nitro, Rollup, and Vite plugins to use the new detection patterns
- Added exclusion logic to prevent re-processing of generated workflow files
- Added tests to verify the pattern detection works correctly
- Updated documentation in the SWC plugin spec to explain the new discovery mechanism
### How to test?
1. Create a class with custom serialization in a separate file:
```js
// models/point.js
export class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static [Symbol.for('workflow-serialize')](instance) {
return { x: instance.x, y: instance.y };
}
static [Symbol.for('workflow-deserialize')](data) {
return new Point(data.x, data.y);
}
}
```
1. Import and use this class in a workflow or step file:
```js
'use workflow';
import { Point } from '../models/point';
export function myWorkflow() {
const point = new Point(10, 20);
return point;
}
```
1. Verify the class is properly serialized when passed between client and server
### Why make this change?
Previously, files containing custom serialization classes needed to include a `'use step'` directive to be discovered and transformed, even if they weren't actual step functions. This was unintuitive and could lead to confusion.
This change allows for a more natural code organization pattern where model classes with serialization can be defined in their own files without requiring directives. The build system will automatically discover and transform these files to ensure the serialization works correctly when the classes are used in workflows or steps.
* perf(builders): optimize workflow discovery with hybrid SWC approach
Apply SWC transforms only to files containing workflow/step directives
instead of all files. Uses regex for fast filtering, then SWC where needed.
- esbuild follows imports to build dependency graph
- regex detects 'use workflow'/'use step' directives
- SWC applied only to files with directives (<1% typically)
- other files use esbuild's built-in TS handling
* Remove blank line
* feat(next): add configurable `dirs` option to withWorkflow
Allow users to specify which directories to scan for workflow directives,
helping reduce memory usage and build times in large Next.js applications.
- Add `dirs` option that overrides the default directories
- Document all configuration options in API reference
- Add troubleshooting guide for OOM errors during build
* fix(docs): add missing imports in withWorkflow code example
Add missing import statements and nextConfig declaration to the
troubleshooting code example to fix docs typecheck.
* docs: move OOM troubleshooting to getting-started/next
Move the OOM troubleshooting section from the API reference to the
existing troubleshooting section in docs/getting-started/next.mdx
for better discoverability.
* move dirs inside workflow config
* Add SDK version to workflow run executionContext for observability
Wire `@workflow/core` package version through the `executionContext` field
when creating workflow runs. Display the version in the observability UI
attribute panel. Uses genversion for build-time version injection.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix workflowCoreVersion extraction and add turbo.json for caching
- Extract workflowCoreVersion from executionContext in hydrateResourceIO
before stripping the context (addresses Copilot review comment)
- Add turbo.json to include src/version.ts in build outputs for caching
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Update workflowCoreVersion display name to @workflow/core version
Use a display name mapping to render the attribute as "@workflow/core version"
in the observability UI for better readability.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* fix: add TypeScript decorator support to SWC transform
Enable decorator parsing in SWC configuration to support codebases using
TypeScript decorators (TypeORM, NestJS, class-validator, custom decorators).
Without this fix, projects importing files with decorators fail with:
"Unexpected token `@`. Expected identifier..." syntax errors.
Changes:
- Add `decorators: true` to parser options for TypeScript and ECMAScript
- Add `legacyDecorator: true` for TypeScript's experimentalDecorators
- Add `decoratorMetadata: true` for emitDecoratorMetadata support
* fix: conditionally enable decorators based on tsconfig compilerOptions
Read experimentalDecorators and emitDecoratorMetadata from tsconfig.json
to match Next.js behavior. Decorators are now only enabled when explicitly
configured in the project's tsconfig.
- Add getDecoratorOptionsForDirectory() to read tsconfig settings
- Update applySwcTransform and Next.js loader to use tsconfig options
- Handle JSONC format (comments, trailing commas) in tsconfig parsing
* fix: use json5 for parsing tsconfig in decorator options
Replace manual regex-based JSONC parsing with json5 library for more
robust handling of comments and trailing commas in tsconfig.json files.
* bump
* apply fix
* DCO Remediation Commit for JJ Kasper <jj@jjsweb.site>
I, JJ Kasper <jj@jjsweb.site>, hereby add my Signed-off-by to this commit: aa1dc36db7
I, JJ Kasper <jj@jjsweb.site>, hereby add my Signed-off-by to this commit: e25f1748c6
Signed-off-by: JJ Kasper <jj@jjsweb.site>
* DCO Remediation Commit for Rishabh <rishabh.pugalia@gmail.com>
I, Rishabh <rishabh.pugalia@gmail.com>, hereby add my Signed-off-by to this commit: e2f93048aa
I, Rishabh <rishabh.pugalia@gmail.com>, hereby add my Signed-off-by to this commit: 3faee5d3c2
I, Rishabh <rishabh.pugalia@gmail.com>, hereby add my Signed-off-by to this commit: 9dbbda6362
Signed-off-by: Rishabh <rishabh.pugalia@gmail.com>
---------
Signed-off-by: JJ Kasper <jj@jjsweb.site>
Signed-off-by: Rishabh <rishabh.pugalia@gmail.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>