Skip to content
Open
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
6 changes: 6 additions & 0 deletions .changeset/rollup-tsconfig-decorators.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@workflow/rollup': patch
'@workflow/builders': patch
---

Read decorator options from tsconfig in the Rollup transform, so Nitro and Nuxt builds parse decorators in workflow files when `experimentalDecorators` is on.
5 changes: 2 additions & 3 deletions packages/builders/src/apply-swc-transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ import { resolveModuleSpecifier } from './module-specifier.js';

const require = createRequire(import.meta.url);

// Cache decorator options per directory - tsconfig doesn't change during a build
const decoratorOptionsCache = new Map<
string,
ReturnType<typeof getDecoratorOptionsForDirectory>
>();

function getDecoratorOptions(projectRoot?: string) {
export function getCachedDecoratorOptions(projectRoot?: string) {
const cwd = projectRoot ?? process.cwd();
let cached = decoratorOptionsCache.get(cwd);
if (!cached) {
Expand Down Expand Up @@ -74,7 +73,7 @@ export async function applySwcTransform(
const resolvedProjectRoot = projectRoot ?? process.cwd();
const resolvedModuleSpecifierRoot =
moduleSpecifierRoot ?? resolvedProjectRoot;
const decoratorOptions = await getDecoratorOptions(resolvedProjectRoot);
const decoratorOptions = await getCachedDecoratorOptions(resolvedProjectRoot);

const swcPluginPath = require.resolve('@workflow/swc-plugin', {
paths: [dirname(fileURLToPath(import.meta.url))],
Expand Down
5 changes: 4 additions & 1 deletion packages/builders/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
export type { WorkflowManifest } from './apply-swc-transform.js';
export { applySwcTransform } from './apply-swc-transform.js';
export {
applySwcTransform,
getCachedDecoratorOptions,
} from './apply-swc-transform.js';
export { BaseBuilder, type DiscoveredEntries } from './base-builder.js';
export { createBuildQueue } from './build-queue.js';
export {
Expand Down
122 changes: 122 additions & 0 deletions packages/rollup/src/decorators.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Options } from '@swc/core';
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest';

const { transformMock } = vi.hoisted(() => ({
transformMock: vi.fn(),
}));

vi.mock('@swc/core', () => ({
transform: transformMock,
}));

import { workflowTransformPlugin } from './index.js';

const decoratedStep = `declare function Injectable(): ClassDecorator;
declare function Log(): MethodDecorator;

@Injectable()
export class OrderService {
@Log()
total(id: string) {
return id.length;
}
}

export async function chargeOrder(id: string) {
'use step';
return new OrderService().total(id);
}
`;

function projectWith(files: Record<string, object>) {
const dir = mkdtempSync(join(tmpdir(), 'workflow-rollup-decorators-'));
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
for (const [name, content] of Object.entries(files)) {
writeFileSync(join(dir, name), JSON.stringify(content));
}
return dir;
}

async function swcOptionsFor(projectDir: string): Promise<Options> {
vi.spyOn(process, 'cwd').mockReturnValue(projectDir);
transformMock.mockResolvedValueOnce({ code: 'compiled', map: null });
const transform = workflowTransformPlugin().transform;
if (typeof transform !== 'function') {
throw new Error('expected transform to be a function');
}
await transform.call(
{} as never,
decoratedStep,
join(projectDir, 'workflows/order.ts')
);
return transformMock.mock.calls.at(-1)?.[1];
}

async function parseWithRealSwc(options: Options) {
const swc = await vi.importActual<typeof import('@swc/core')>('@swc/core');
return swc.transform(decoratedStep, options);
}

afterEach(() => {
vi.restoreAllMocks();
transformMock.mockReset();
});

describe('workflowTransformPlugin decorators', () => {
it('enables legacy decorators and metadata when tsconfig turns them on', async () => {
const options = await swcOptionsFor(
projectWith({
'tsconfig.json': {
compilerOptions: {
experimentalDecorators: true,
emitDecoratorMetadata: true,
},
},
})
);

expect(options.jsc?.parser?.decorators).toBe(true);
expect(options.jsc?.transform?.legacyDecorator).toBe(true);
expect(options.jsc?.transform?.decoratorMetadata).toBe(true);
await expect(parseWithRealSwc(options)).resolves.toMatchObject({
code: expect.stringContaining('_ts_decorate'),
});
});

it('follows tsconfig extends to find experimentalDecorators', async () => {
const options = await swcOptionsFor(
projectWith({
'tsconfig.base.json': {
compilerOptions: { experimentalDecorators: true },
},
'tsconfig.json': { extends: './tsconfig.base.json' },
})
);

expect(options.jsc?.parser?.decorators).toBe(true);
Comment on lines +89 to +99

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new inheritance test fails because the stable branch’s tsconfig reader ignores extends, leaving decorators disabled for its fixture.

Fix on Vercel

expect(options.jsc?.transform?.legacyDecorator).toBe(true);
expect(options.jsc?.transform?.decoratorMetadata).toBe(false);
await expect(parseWithRealSwc(options)).resolves.toBeDefined();
});

it.each([
[
'experimentalDecorators is off',
{ 'tsconfig.json': { compilerOptions: {} } },
],
[
'only emitDecoratorMetadata is set',
{ 'tsconfig.json': { compilerOptions: { emitDecoratorMetadata: true } } },
],
])('keeps decorators off when %s', async (_, files) => {
const options = await swcOptionsFor(projectWith(files));

expect(options.jsc?.parser?.decorators).toBe(false);
expect(options.jsc?.transform?.legacyDecorator).toBe(false);
expect(options.jsc?.transform?.decoratorMetadata).toBe(false);
await expect(parseWithRealSwc(options)).rejects.toThrow();
});
});
5 changes: 5 additions & 0 deletions packages/rollup/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { relative } from 'node:path';
import { transform } from '@swc/core';
import {
detectWorkflowPatterns,
getCachedDecoratorOptions,
isGeneratedWorkflowFile,
isWorkflowSdkFile,
resolveModuleSpecifier,
Expand Down Expand Up @@ -105,6 +106,7 @@ export function workflowTransformPlugin(

// Resolve module specifier for packages (node_modules or workspace packages)
const { moduleSpecifier } = resolveModuleSpecifier(id, workingDir);
const decoratorOptions = await getCachedDecoratorOptions(workingDir);

// Transform with SWC
const result = await transform(code, {
Expand All @@ -120,6 +122,7 @@ export function workflowTransformPlugin(
syntax: 'ecmascript',
jsx: id.endsWith('.jsx'),
}),
decorators: decoratorOptions.decorators,
},
target: 'es2022',
experimental: {
Expand All @@ -129,6 +132,8 @@ export function workflowTransformPlugin(
react: {
runtime: 'preserve',
},
legacyDecorator: decoratorOptions.legacyDecorator,
decoratorMetadata: decoratorOptions.decoratorMetadata,
},
},
minify: false,
Expand Down