Skip to content

Commit

Permalink
feat(workspace-plugin): various executor fixes and inferred ws plugin…
Browse files Browse the repository at this point in the history
… configuration capabilities (#33098)

Co-authored-by: Dmytro Kirpa <[email protected]>
  • Loading branch information
Hotell and dmytrokirpa authored Oct 23, 2024
1 parent 6baf51f commit 02d0cc1
Show file tree
Hide file tree
Showing 12 changed files with 192 additions and 115 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ describe('Build Executor', () => {
"
`);
expect(readFileSync(join(workspaceRoot, 'libs/proj/lib/greeter.js.map'), 'utf-8')).toMatchInlineSnapshot(
`"{\\"version\\":3,\\"sources\\":[\\"greeter.ts\\"],\\"sourcesContent\\":[\\"import { useStyles } from './greeter.styles';\\\\nexport function greeter(greeting: string, user: User): string {\\\\n const styles = useStyles();\\\\n return \`<h1 class=\\\\\\"\${styles}\\\\\\">\${greeting} \${user.name} from \${user.hometown?.name}</h1>\`;\\\\n}\\\\n\\\\ntype User = {\\\\n name: string;\\\\n hometown?: {\\\\n name: string;\\\\n };\\\\n};\\\\n\\"],\\"names\\":[\\"useStyles\\",\\"greeter\\",\\"greeting\\",\\"user\\",\\"styles\\",\\"name\\",\\"hometown\\"],\\"rangeMappings\\":\\";;;;;\\",\\"mappings\\":\\"AAAA,SAASA,SAAS,QAAQ,mBAAmB;AAC7C,OAAO,SAASC,QAAQC,QAAgB,EAAEC,IAAU;QAEYA;IAD9D,MAAMC,SAASJ;IACf,OAAO,CAAC,WAAW,EAAEI,OAAO,EAAE,EAAEF,SAAS,CAAC,EAAEC,KAAKE,IAAI,CAAC,MAAM,GAAEF,iBAAAA,KAAKG,QAAQ,cAAbH,qCAAAA,eAAeE,IAAI,CAAC,KAAK,CAAC;AAC1F\\"}"`,
`"{\\"version\\":3,\\"sources\\":[\\"../src/greeter.ts\\"],\\"sourcesContent\\":[\\"import { useStyles } from './greeter.styles';\\\\nexport function greeter(greeting: string, user: User): string {\\\\n const styles = useStyles();\\\\n return \`<h1 class=\\\\\\"\${styles}\\\\\\">\${greeting} \${user.name} from \${user.hometown?.name}</h1>\`;\\\\n}\\\\n\\\\ntype User = {\\\\n name: string;\\\\n hometown?: {\\\\n name: string;\\\\n };\\\\n};\\\\n\\"],\\"names\\":[\\"useStyles\\",\\"greeter\\",\\"greeting\\",\\"user\\",\\"styles\\",\\"name\\",\\"hometown\\"],\\"rangeMappings\\":\\";;;;;\\",\\"mappings\\":\\"AAAA,SAASA,SAAS,QAAQ,mBAAmB;AAC7C,OAAO,SAASC,QAAQC,QAAgB,EAAEC,IAAU;QAEYA;IAD9D,MAAMC,SAASJ;IACf,OAAO,CAAC,WAAW,EAAEI,OAAO,EAAE,EAAEF,SAAS,CAAC,EAAEC,KAAKE,IAAI,CAAC,MAAM,GAAEF,iBAAAA,KAAKG,QAAQ,cAAbH,qCAAAA,eAAeE,IAAI,CAAC,KAAK,CAAC;AAC1F\\"}"`,
);

expect(readFileSync(join(workspaceRoot, 'libs/proj/lib-commonjs/greeter.js'), 'utf-8')).toMatchInlineSnapshot(`
Expand Down
1 change: 1 addition & 0 deletions tools/workspace-plugin/src/executors/build/lib/babel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ async function babel(esmModuleOutput: NormalizedOptions['moduleOutput'][number],
const sourceCode = codeBuffer.toString().replace(EOL_REGEX, '\n');

const result = (await transformAsync(sourceCode, {
cwd: normalizedOptions.absoluteProjectRoot,
ast: false,
sourceMaps: true,

Expand Down
25 changes: 13 additions & 12 deletions tools/workspace-plugin/src/executors/build/lib/swc.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { readFileSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import { basename, dirname, join } from 'node:path';
import { dirname, join } from 'node:path';

import { globSync } from 'fast-glob';
import { isMatch } from 'micromatch';
import { transform, type Config } from '@swc/core';
import { transformFile, type Config } from '@swc/core';
import { logger, readJsonFile } from '@nx/devkit';

import { type NormalizedOptions } from './shared';

// extend @swc/core types by missing apis
declare module '@swc/core' {
interface BaseModuleConfig {
resolveFully?: boolean;
}
}

interface Options {
module: 'es6' | 'commonjs' | 'amd';
outputPath: string;
Expand All @@ -35,15 +41,10 @@ export async function compileSwc(options: Options, normalizedOptions: Normalized
continue;
}

const sourceCode = readFileSync(srcFilePath, 'utf-8');

const result = await transform(sourceCode, {
filename: fileName,
sourceFileName: basename(fileName),
module: { type: module },
outputPath,
// this is crucial in order to transpile with project config SWC
configFile: swcConfigPath,
const result = await transformFile(srcFilePath, {
module: { type: module, resolveFully: Boolean(swcConfig.jsc?.baseUrl) },
// srcFilePath is absolute path so outputPath needs to be as well in order to properly emit relative path within .map (eg: `"sources":["../src/utils/createDarkTheme.ts"]`)
outputPath: join(normalizedOptions.absoluteProjectRoot, outputPath),
});

// Strip @jsx comments, see https://github.com/microsoft/fluentui/issues/29126
Expand Down
9 changes: 1 addition & 8 deletions tools/workspace-plugin/src/executors/build/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,7 @@ export interface BuildExecutorSchema {
* Key-value pairs to replace in the output path
*/
substitutions?: {
/**
* The key to replace.
*/
key: string;
/**
* The value to replace.
*/
value: string;
[k: string]: string;
};
}
| string
Expand Down
9 changes: 3 additions & 6 deletions tools/workspace-plugin/src/executors/build/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,9 @@
"substitutions": {
"type": "object",
"description": "Key-value pairs to replace in the output path",
"properties": {
"key": { "type": "string", "description": "The key to replace." },
"value": { "type": "string", "description": "The value to replace." }
},
"additionalProperties": false,
"required": ["key", "value"]
"additionalProperties": {
"type": "string"
}
}
},
"additionalProperties": false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,10 @@ describe('GenerateApi Executor', () => {

const output = await executor(options, context);

const projectRootAbsolutePath = `${__dirname}/__fixtures__/proj`;

expect(execSyncMock.mock.calls.flat()).toEqual([
`tsc -p ${__dirname}/__fixtures__/proj/tsconfig.lib.json --pretty --emitDeclarationOnly --baseUrl .`,
`tsc -p ${projectRootAbsolutePath}/tsconfig.lib.json --pretty --emitDeclarationOnly --baseUrl ${projectRootAbsolutePath}`,
{ stdio: 'inherit' },
]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ function generateTypeDeclarations(options: NormalizedOptions) {
'--pretty',
'--emitDeclarationOnly',
// turn off path aliases.
'--baseUrl .',
`--baseUrl ${options.projectAbsolutePath}`,
].join(' ');

verboseLog(`Emitting '.d.ts' files via: "${cmd}"`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ describe('TypeCheck Executor', () => {
const output = await executor(options, mockContext);

expect(promisifyCallMock.mock.calls.flat()).toEqual([
'tsc -p /root/libs/my-lib/tsconfig.lib.json --pretty --noEmit --baseUrl .',
'tsc -p /root/libs/my-lib/tsconfig.spec.json --pretty --noEmit --baseUrl .',
'tsc -p /root/libs/my-lib/tsconfig.lib.json --pretty --noEmit --baseUrl /root/libs/my-lib',
'tsc -p /root/libs/my-lib/tsconfig.spec.json --pretty --noEmit --baseUrl /root/libs/my-lib',
]);

expect(output.success).toBe(true);
Expand All @@ -93,7 +93,7 @@ describe('TypeCheck Executor', () => {
const output = await executor({ ...options, excludeProject: { spec: true, e2e: false } }, mockContext);

expect(promisifyCallMock.mock.calls.flat()).toEqual([
'tsc -p /root/libs/my-lib/tsconfig.lib.json --pretty --noEmit --baseUrl .',
'tsc -p /root/libs/my-lib/tsconfig.lib.json --pretty --noEmit --baseUrl /root/libs/my-lib',
]);

expect(output.success).toBe(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ async function runTypeCheck(options: NormalizedOptions, context: ExecutorContext
const asyncQueue = [];

for (const ref of tsConfigsRefs) {
const program = `tsc -p ${ref} --pretty --noEmit --baseUrl .`;
const program = `tsc -p ${ref} --pretty --noEmit --baseUrl ${projectRootAbsolutePath}`;

verboseLog(`Running "${program}"`);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ function assertions(
);
}

if (isV8package) {
// apply only for non cross domain v8 packages (eg: react-migration-* is v9/v8)
if (isV8package && !isV9package) {
issues.push(assertEmpty(npmPackResult, '(lib|lib-commonjs)/**/*.d.ts', `ships dts`));

if (options.isProduction && shipsBundle) {
Expand Down
50 changes: 25 additions & 25 deletions tools/workspace-plugin/src/plugins/workspace-plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,32 +136,40 @@ describe(`workspace-plugin`, () => {
describe(`v9 project nodes`, () => {
it('should create default nodes for v9 library project', async () => {
await tempFs.createFiles({
'proj/project.json': serializeJson({
'proj/library/project.json': serializeJson({
root: 'proj',
name: 'proj',
projectType: 'library',
tags: ['vNext'],
} satisfies ProjectConfiguration),
'proj/package.json': serializeJson({ name: '@proj/proj', private: true } satisfies Partial<PackageJson>),
'proj/library/package.json': serializeJson({
name: '@proj/proj',
private: true,
} satisfies Partial<PackageJson>),
'proj/stories/project.json': serializeJson({
root: 'proj/stories',
name: 'proj-stories',
} satisfies ProjectConfiguration),
});
const results = await createNodesFunction(['proj/project.json'], {}, context);
const results = await createNodesFunction(['proj/library/project.json'], {}, context);

expect(getTargetsNames(results)).toEqual([
expect(getTargetsNames(results, 'proj/library')).toEqual([
'clean',
'format',
'type-check',
'generate-api',
'build',
'start',
'storybook',
'start',
]);

expect(results).toMatchInlineSnapshot(`
Array [
Array [
"proj/project.json",
"proj/library/project.json",
Object {
"projects": Object {
"proj": Object {
"proj/library": Object {
"targets": Object {
"build": Object {
"cache": true,
Expand Down Expand Up @@ -189,7 +197,7 @@ describe(`workspace-plugin`, () => {
],
"metadata": Object {
"help": Object {
"command": "yarn nx run undefined:build --help",
"command": "yarn nx run proj:build --help",
"example": Object {},
},
"technologies": Array [
Expand Down Expand Up @@ -217,7 +225,7 @@ describe(`workspace-plugin`, () => {
"{projectRoot}/lib-commonjs",
"{projectRoot}/dist",
"{projectRoot}/dist/index.d.ts",
"{projectRoot}/etc/undefined.api.md",
"{projectRoot}/etc/proj.api.md",
],
},
"clean": Object {
Expand Down Expand Up @@ -266,7 +274,7 @@ describe(`workspace-plugin`, () => {
],
"metadata": Object {
"help": Object {
"command": "yarn nx run undefined:generate-api --help",
"command": "yarn nx run proj:generate-api --help",
"example": Object {},
},
"technologies": Array [
Expand All @@ -276,26 +284,16 @@ describe(`workspace-plugin`, () => {
},
"outputs": Array [
"{projectRoot}/dist/index.d.ts",
"{projectRoot}/etc/undefined.api.md",
"{projectRoot}/etc/proj.api.md",
],
},
"start": Object {
"command": "yarn storybook",
"options": Object {
"cwd": "proj",
},
"cache": true,
"command": "nx run proj-stories:storybook",
},
"storybook": Object {
"cache": true,
"command": "yarn --cwd ../stories storybook",
"metadata": Object {
"technologies": Array [
"storybook",
],
},
"options": Object {
"cwd": "proj",
},
"command": "nx run proj-stories:storybook",
},
"type-check": Object {
"cache": true,
Expand Down Expand Up @@ -323,6 +321,7 @@ describe(`workspace-plugin`, () => {

it('should create default nodes for v9 stories project', async () => {
await tempFs.createFiles({
'proj/stories/.storybook/main.js': '',
'proj/stories/project.json': serializeJson({
root: 'proj/stories',
projectType: 'library',
Expand All @@ -339,15 +338,16 @@ describe(`workspace-plugin`, () => {
'clean',
'format',
'type-check',
'storybook',
'test-ssr',
'start',
'storybook',
]);

const targets = getTargets(results, 'proj/stories');

expect(targets?.storybook).toMatchInlineSnapshot(`
Object {
"cache": true,
"command": "yarn storybook dev",
"inputs": Array [
"production",
Expand Down
Loading

0 comments on commit 02d0cc1

Please sign in to comment.