@smoothbricks/nx-plugin 0.2.3 → 0.2.5

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.
@@ -0,0 +1,26 @@
1
+ import type { CleanOutputsOptions } from './schema.js';
2
+ interface CleanOutputsContext {
3
+ root: string;
4
+ projectName?: string;
5
+ projectsConfigurations?: {
6
+ projects: Record<string, NxProject>;
7
+ };
8
+ }
9
+ interface CleanOutputsResult {
10
+ success: boolean;
11
+ }
12
+ interface NxProject {
13
+ root?: string;
14
+ targets?: Record<string, {
15
+ outputs?: string[];
16
+ }>;
17
+ }
18
+ export default function cleanOutputsExecutor(options: CleanOutputsOptions, context: CleanOutputsContext): Promise<CleanOutputsResult>;
19
+ export declare function resolveOutputDirs(options: {
20
+ outputs: string[];
21
+ projectName: string;
22
+ projectRoot: string;
23
+ workspaceRoot: string;
24
+ }): string[];
25
+ export {};
26
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/clean-outputs/executor.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEvD,UAAU,mBAAmB;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,sBAAsB,CAAC,EAAE;QACvB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;KACrC,CAAC;CACH;AAED,UAAU,kBAAkB;IAC1B,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,UAAU,SAAS;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC,CAAC;CAClD;AAED,wBAA8B,oBAAoB,CAChD,OAAO,EAAE,mBAAmB,EAC5B,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,kBAAkB,CAAC,CA8B7B;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE;IACzC,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;CACvB,GAAG,MAAM,EAAE,CAOX"}
@@ -0,0 +1,68 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { rm } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ export default async function cleanOutputsExecutor(options, context) {
5
+ const projectName = context.projectName;
6
+ if (!projectName) {
7
+ throw new Error('@smoothbricks/nx-plugin:clean-outputs requires a project context.');
8
+ }
9
+ const workspaceRoot = context.root;
10
+ const project = context.projectsConfigurations?.projects[projectName];
11
+ if (!project) {
12
+ throw new Error(`Project ${projectName} was not found in the Nx project graph.`);
13
+ }
14
+ const outputDirs = resolveOutputDirs({
15
+ outputs: options.outputs ?? project.targets?.build?.outputs ?? ['{projectRoot}/dist'],
16
+ projectName,
17
+ projectRoot: project.root ?? '.',
18
+ workspaceRoot,
19
+ });
20
+ for (const outputDir of outputDirs) {
21
+ assertSafeOutputDir(outputDir, project.root ?? '.', workspaceRoot);
22
+ if (containsTrackedFiles(outputDir, workspaceRoot)) {
23
+ console.log(`skipped ${path.relative(workspaceRoot, outputDir)} (contains tracked files)`);
24
+ continue;
25
+ }
26
+ await rm(outputDir, { force: true, recursive: true });
27
+ console.log(`removed ${path.relative(workspaceRoot, outputDir)}`);
28
+ }
29
+ return { success: true };
30
+ }
31
+ export function resolveOutputDirs(options) {
32
+ const concreteOutputDirs = options.outputs.map((output) => outputDir(output, options));
33
+ const dedupedOutputDirs = [...new Set(concreteOutputDirs)].sort((a, b) => a.length - b.length);
34
+ return dedupedOutputDirs.filter((candidate, index) => !dedupedOutputDirs.some((other, otherIndex) => otherIndex < index && isWithin(candidate, other)));
35
+ }
36
+ function outputDir(output, options) {
37
+ const interpolated = output
38
+ .replaceAll('{workspaceRoot}', '.')
39
+ .replaceAll('{projectRoot}', options.projectRoot)
40
+ .replaceAll('{projectName}', options.projectName);
41
+ const segments = interpolated.split(/[\\/]/);
42
+ const globIndex = segments.findIndex((segment) => segment.includes('*'));
43
+ const dirSegments = globIndex === -1 ? segments : segments.slice(0, globIndex);
44
+ const outputPath = dirSegments.join(path.sep);
45
+ return path.resolve(options.workspaceRoot, outputPath);
46
+ }
47
+ function assertSafeOutputDir(outputDir, projectRoot, workspaceRoot) {
48
+ const absoluteWorkspaceRoot = path.resolve(workspaceRoot);
49
+ const absoluteProjectRoot = path.resolve(workspaceRoot, projectRoot);
50
+ if (!isWithin(outputDir, absoluteWorkspaceRoot)) {
51
+ throw new Error(`Refusing to remove output outside workspace: ${outputDir}`);
52
+ }
53
+ if (outputDir === absoluteWorkspaceRoot || outputDir === absoluteProjectRoot) {
54
+ throw new Error(`Refusing to remove unsafe output directory: ${path.relative(workspaceRoot, outputDir) || '.'}`);
55
+ }
56
+ }
57
+ function isWithin(candidate, parent) {
58
+ const relative = path.relative(parent, candidate);
59
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
60
+ }
61
+ function containsTrackedFiles(outputDir, workspaceRoot) {
62
+ const relativeOutputDir = path.relative(workspaceRoot, outputDir);
63
+ const trackedFiles = execFileSync('git', ['ls-files', '--', relativeOutputDir], {
64
+ cwd: workspaceRoot,
65
+ encoding: 'utf8',
66
+ });
67
+ return trackedFiles.trim().length > 0;
68
+ }
@@ -0,0 +1,4 @@
1
+ export interface CleanOutputsOptions {
2
+ outputs?: string[];
3
+ }
4
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/executors/clean-outputs/schema.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACpB"}
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.js CHANGED
@@ -98,6 +98,10 @@ async function createProjectTargets(packageJsonPath, workspaceRoot) {
98
98
  cache: true,
99
99
  dependsOn: ['^build', ...BUILD_OUTPUT_DEPENDENCIES],
100
100
  };
101
+ targets.clean = {
102
+ executor: '@smoothbricks/nx-plugin:clean-outputs',
103
+ cache: false,
104
+ };
101
105
  }
102
106
  if (targets['typecheck-tests']) {
103
107
  if (hasLibTsconfig) {
@@ -4,6 +4,8 @@ export type { NxPolicyIssue };
4
4
  export interface ResolvedProjectTargets {
5
5
  targets: ReadonlySet<string>;
6
6
  buildDependsOn?: readonly string[];
7
+ targetExecutors?: ReadonlyMap<string, string>;
8
+ targetScripts?: ReadonlyMap<string, string>;
7
9
  }
8
10
  export interface PackageTargetPolicyOptions {
9
11
  resolvedTargetsByProject?: ReadonlyMap<string, ReadonlySet<string> | ResolvedProjectTargets>;
@@ -1 +1 @@
1
- {"version":3,"file":"package-target-policy.d.ts","sourceRoot":"","sources":["../src/package-target-policy.ts"],"names":[],"mappings":"AAGA,OAAO,EAAyB,KAAK,IAAI,EAAc,MAAM,0BAA0B,CAAC;AAGxF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAElE,YAAY,EAAE,aAAa,EAAE,CAAC;AAE9B,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC7B,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AAED,MAAM,WAAW,0BAA0B;IACzC,wBAAwB,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,sBAAsB,CAAC,CAAC;CAC9F;AAED,eAAO,MAAM,yBAAyB,UAWrC,CAAC;AA0HF,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,IAAI,CAGhF;AA0ID,wBAAgB,UAAU,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,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAA;CAAO,GACtD,OAAO,CAMT;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,0BAA+B,GAAG,aAAa,EAAE,CAqBhH;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,0BAA+B,GAAG,OAAO,CA6BxG"}
@@ -141,11 +141,17 @@ function resolvedProjectBuildDependsOn(resolvedProject) {
141
141
  }
142
142
  return resolvedProject.buildDependsOn;
143
143
  }
144
+ function resolvedProjectTargetExecutor(resolvedProject, targetName) {
145
+ return isResolvedProjectTargets(resolvedProject) ? resolvedProject.targetExecutors?.get(targetName) : undefined;
146
+ }
147
+ function resolvedProjectTargetScript(resolvedProject, targetName) {
148
+ return isResolvedProjectTargets(resolvedProject) ? resolvedProject.targetScripts?.get(targetName) : undefined;
149
+ }
144
150
  function isResolvedProjectTargets(value) {
145
151
  return isRecord(value) && value.targets instanceof Set;
146
152
  }
147
153
  function targetExistsInResolvedProject(targetName, resolvedTargets) {
148
- return resolvedTargets?.has(targetName) === true;
154
+ return resolvedProjectTargetNames(resolvedTargets)?.has(targetName) === true;
149
155
  }
150
156
  function isBuildOutputDependencyPattern(dependency) {
151
157
  return BUILD_OUTPUT_DEPENDENCIES.includes(dependency);
@@ -218,6 +224,13 @@ export function nxRunAlias(projectName, targetName, continuous, command) {
218
224
  const flags = continuous ? ` --outputStyle=${nxRunOutputStyle(command)}` : '';
219
225
  return `nx run ${projectName}:${targetName}${flags}`;
220
226
  }
227
+ function nxRunAliasMatches(rawAlias, expectedAlias) {
228
+ const expected = parseNxRunAlias(expectedAlias);
229
+ return (!!rawAlias &&
230
+ !!expected &&
231
+ rawAlias.projectName === expected.projectName &&
232
+ rawAlias.targetName === expected.targetName);
233
+ }
221
234
  function nxRunOutputStyle(command) {
222
235
  if (command && /(?:^|\s)(?:astro|vite)\s+dev(?:\s|$)/.test(command)) {
223
236
  return 'dynamic-legacy';
@@ -523,6 +536,13 @@ function validatePackageScriptPolicy(pkg, packagePath, workspaceNames, options =
523
536
  continue;
524
537
  }
525
538
  const alias = parseNxRunAlias(rawCommand);
539
+ if (isResolvedSelfRecursiveScript(scriptName, alias, projectName, options.resolvedTargets)) {
540
+ issues.push({
541
+ path: packagePath,
542
+ message: `${packagePath}: scripts.${scriptName} recursively delegates to its own inferred Nx target; remove the script so the resolved Nx target can run`,
543
+ });
544
+ continue;
545
+ }
526
546
  const rewrite = alias
527
547
  ? { targetName: alias.targetName, continuous: isContinuousTarget(alias.targetName, '') }
528
548
  : classifyScriptRewrite(scriptName, rawCommand);
@@ -547,7 +567,7 @@ function validatePackageScriptPolicy(pkg, packagePath, workspaceNames, options =
547
567
  const command = targetOptions ? stringProperty(targetOptions, 'command') : null;
548
568
  const rewriteCommand = 'command' in rewrite ? rewrite.command : null;
549
569
  const expectedAlias = nxRunAlias(projectName, rewrite.targetName, rewrite.continuous, command ?? rewriteCommand);
550
- if (rawCommand !== expectedAlias) {
570
+ if (alias ? !nxRunAliasMatches(alias, expectedAlias) : rawCommand !== expectedAlias) {
551
571
  issues.push({
552
572
  path: packagePath,
553
573
  message: `${packagePath}: scripts.${scriptName} must delegate to ${expectedAlias}`,
@@ -829,6 +849,11 @@ function applyPackageScriptPolicyForPkg(pkg, _packagePath, workspaceNames, optio
829
849
  continue;
830
850
  }
831
851
  const parsedAlias = parseNxRunAlias(rawCommand);
852
+ if (isResolvedSelfRecursiveScript(scriptName, parsedAlias, projectName, options.resolvedTargets)) {
853
+ delete scripts[scriptName];
854
+ changed = true;
855
+ continue;
856
+ }
832
857
  if (parsedAlias?.projectName === projectName && parsedAlias.targetName === 'test') {
833
858
  continue;
834
859
  }
@@ -881,6 +906,12 @@ function applyPackageScriptPolicyForPkg(pkg, _packagePath, workspaceNames, optio
881
906
  }
882
907
  return changed;
883
908
  }
909
+ function isResolvedSelfRecursiveScript(scriptName, alias, projectName, resolvedTargets) {
910
+ return (alias?.projectName === projectName &&
911
+ alias.targetName === scriptName &&
912
+ resolvedProjectTargetExecutor(resolvedTargets, scriptName) === 'nx:run-script' &&
913
+ resolvedProjectTargetScript(resolvedTargets, scriptName) === scriptName);
914
+ }
884
915
  export function checkPackageTargets(pkg, packagePath, resolvedTargets) {
885
916
  return [...validateExplicitNxTargets(pkg, packagePath, resolvedTargets)];
886
917
  }
@@ -906,7 +937,7 @@ export function checkPackageTargetPolicy(root, options = {}) {
906
937
  issues.push(...validateExplicitNxTargets(pkg, packagePath, resolvedTargets));
907
938
  issues.push(...validateTestEntrypointPresence(root, packagePath, pkg));
908
939
  issues.push(...validateBuildZigPolicy(root, packagePath));
909
- issues.push(...validatePackageScriptPolicy(pkg, packagePath, workspaceNames, { resolvedTargets }));
940
+ issues.push(...validatePackageScriptPolicy(pkg, packagePath, workspaceNames, { resolvedTargets: resolvedProject }));
910
941
  }
911
942
  return issues;
912
943
  }
@@ -927,7 +958,8 @@ export function applyPackageTargetPolicy(root, options = {}) {
927
958
  packageChanged = removePackageColonTargets(pkg) || packageChanged;
928
959
  packageChanged = removeRedundantNoopBuildTarget(pkg, resolvedProject) || packageChanged;
929
960
  packageChanged =
930
- applyPackageScriptPolicyForPkg(pkg, packagePath, workspaceNames, { resolvedTargets }) || packageChanged;
961
+ applyPackageScriptPolicyForPkg(pkg, packagePath, workspaceNames, { resolvedTargets: resolvedProject }) ||
962
+ packageChanged;
931
963
  if (packageChanged) {
932
964
  writeJsonObject(packageJsonPath, pkg);
933
965
  changed = true;
@@ -1 +1 @@
1
- {"version":3,"file":"workspace-config-policy.d.ts","sourceRoot":"","sources":["../src/workspace-config-policy.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAGrD,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,yBAAyB,UAWrC,CAAC;AAcF;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C,IAAI,EAAE,MAAM,GAAG,aAAa,EAAE,CAYxE;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAWhE"}
@@ -15,6 +15,7 @@ export const BUILD_OUTPUT_DEPENDENCIES = [
15
15
  ];
16
16
  const nxJsTypescriptPlugin = '@nx/js/typescript';
17
17
  const smoothBricksNxPlugin = '@smoothbricks/nx-plugin';
18
+ const cleanOutputsExecutor = '@smoothbricks/nx-plugin:clean-outputs';
18
19
  const expectedSharedGlobalsNamedInput = ['{workspaceRoot}/.github/workflows/ci.yml'];
19
20
  const defaultProductionNamedInput = [
20
21
  '{projectRoot}/src/**/*',
@@ -44,6 +45,8 @@ export function checkWorkspaceConfig(nxJson) {
44
45
  }
45
46
  // Build target default
46
47
  validateBuildTargetDefault(nxJson, 'nx.json', issues);
48
+ // Clean target default
49
+ validateCleanTargetDefault(nxJson, 'nx.json', issues);
47
50
  // Named input defaults
48
51
  validateNamedInputDefaults(nxJson, 'nx.json', issues);
49
52
  // Plugin configuration
@@ -79,6 +82,7 @@ export function checkWorkspaceConfig(nxJson) {
79
82
  export function applyWorkspaceConfig(nxJson) {
80
83
  let changed = removeColonTargetDefaults(nxJson);
81
84
  changed = applyBuildTargetDefault(nxJson) || changed;
85
+ changed = applyCleanTargetDefault(nxJson) || changed;
82
86
  changed = applyNamedInputDefaults(nxJson) || changed;
83
87
  const currentPlugins = Array.isArray(nxJson.plugins) ? nxJson.plugins : [];
84
88
  const nextPlugins = upsertNxPlugin(upsertNxPlugin(currentPlugins, expectedNxJsTypescriptPlugin()), smoothBricksNxPlugin);
@@ -154,6 +158,16 @@ function validateBuildTargetDefault(nxJson, nxJsonPath, issues) {
154
158
  issues.push({ path: nxJsonPath, message: 'targetDefaults.build.outputs must be ["{projectRoot}/dist"]' });
155
159
  }
156
160
  }
161
+ function validateCleanTargetDefault(nxJson, nxJsonPath, issues) {
162
+ const targetDefaults = recordProperty(nxJson, 'targetDefaults');
163
+ const clean = targetDefaults ? recordProperty(targetDefaults, 'clean') : null;
164
+ if (!clean || clean.executor !== cleanOutputsExecutor) {
165
+ issues.push({ path: nxJsonPath, message: `targetDefaults.clean.executor must be ${cleanOutputsExecutor}` });
166
+ }
167
+ if (!clean || clean.cache !== false) {
168
+ issues.push({ path: nxJsonPath, message: 'targetDefaults.clean.cache must be false' });
169
+ }
170
+ }
157
171
  function validateNamedInputDefaults(nxJson, nxJsonPath, issues) {
158
172
  const namedInputs = recordProperty(nxJson, 'namedInputs');
159
173
  if (!namedInputs) {
@@ -197,6 +211,13 @@ function applyBuildTargetDefault(nxJson) {
197
211
  changed = setStringArrayProperty(build, 'outputs', ['{projectRoot}/dist']) || changed;
198
212
  return changed;
199
213
  }
214
+ function applyCleanTargetDefault(nxJson) {
215
+ const targetDefaults = getOrCreateRecord(nxJson, 'targetDefaults');
216
+ const clean = getOrCreateRecord(targetDefaults, 'clean');
217
+ let changed = setStringProperty(clean, 'executor', cleanOutputsExecutor);
218
+ changed = setBooleanProperty(clean, 'cache', false) || changed;
219
+ return changed;
220
+ }
200
221
  function applyNamedInputDefaults(nxJson) {
201
222
  const namedInputs = getOrCreateRecord(nxJson, 'namedInputs');
202
223
  let changed = false;
@@ -321,6 +342,13 @@ function setBooleanProperty(record, key, value) {
321
342
  record[key] = value;
322
343
  return true;
323
344
  }
345
+ function setStringProperty(record, key, value) {
346
+ if (record[key] === value) {
347
+ return false;
348
+ }
349
+ record[key] = value;
350
+ return true;
351
+ }
324
352
  function setStringArrayProperty(record, key, value) {
325
353
  const current = record[key];
326
354
  if (stringArrayEquals(current, value)) {
package/executors.json CHANGED
@@ -4,6 +4,11 @@
4
4
  "implementation": "./dist/executors/bounded-exec/executor.js",
5
5
  "schema": "./src/executors/bounded-exec/schema.json",
6
6
  "description": "Run a command with bounded timeout and force-kill behavior"
7
+ },
8
+ "clean-outputs": {
9
+ "implementation": "./dist/executors/clean-outputs/executor.js",
10
+ "schema": "./src/executors/clean-outputs/schema.json",
11
+ "description": "Remove declared build output directories unless they contain tracked files"
7
12
  }
8
13
  }
9
14
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smoothbricks/nx-plugin",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "main": "./loader.js",
@@ -0,0 +1,20 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ import { resolveOutputDirs } from './executor.js';
6
+
7
+ describe('clean-outputs executor', () => {
8
+ it('resolves declared output patterns to safe concrete directories', () => {
9
+ const workspaceRoot = join(tmpdir(), 'smoothbricks-clean-outputs');
10
+
11
+ expect(
12
+ resolveOutputDirs({
13
+ outputs: ['{projectRoot}/dist/**/*.js', '{projectRoot}/dist/types', '{projectRoot}/dist-wasm-web'],
14
+ projectName: 'example',
15
+ projectRoot: 'packages/example',
16
+ workspaceRoot,
17
+ }).map((outputDir) => outputDir.slice(workspaceRoot.length + 1)),
18
+ ).toEqual(['packages/example/dist', 'packages/example/dist-wasm-web']);
19
+ });
20
+ });
@@ -0,0 +1,116 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { rm } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ import type { CleanOutputsOptions } from './schema.js';
6
+
7
+ interface CleanOutputsContext {
8
+ root: string;
9
+ projectName?: string;
10
+ projectsConfigurations?: {
11
+ projects: Record<string, NxProject>;
12
+ };
13
+ }
14
+
15
+ interface CleanOutputsResult {
16
+ success: boolean;
17
+ }
18
+
19
+ interface NxProject {
20
+ root?: string;
21
+ targets?: Record<string, { outputs?: string[] }>;
22
+ }
23
+
24
+ export default async function cleanOutputsExecutor(
25
+ options: CleanOutputsOptions,
26
+ context: CleanOutputsContext,
27
+ ): Promise<CleanOutputsResult> {
28
+ const projectName = context.projectName;
29
+ if (!projectName) {
30
+ throw new Error('@smoothbricks/nx-plugin:clean-outputs requires a project context.');
31
+ }
32
+
33
+ const workspaceRoot = context.root;
34
+ const project = context.projectsConfigurations?.projects[projectName];
35
+ if (!project) {
36
+ throw new Error(`Project ${projectName} was not found in the Nx project graph.`);
37
+ }
38
+
39
+ const outputDirs = resolveOutputDirs({
40
+ outputs: options.outputs ?? project.targets?.build?.outputs ?? ['{projectRoot}/dist'],
41
+ projectName,
42
+ projectRoot: project.root ?? '.',
43
+ workspaceRoot,
44
+ });
45
+
46
+ for (const outputDir of outputDirs) {
47
+ assertSafeOutputDir(outputDir, project.root ?? '.', workspaceRoot);
48
+ if (containsTrackedFiles(outputDir, workspaceRoot)) {
49
+ console.log(`skipped ${path.relative(workspaceRoot, outputDir)} (contains tracked files)`);
50
+ continue;
51
+ }
52
+ await rm(outputDir, { force: true, recursive: true });
53
+ console.log(`removed ${path.relative(workspaceRoot, outputDir)}`);
54
+ }
55
+
56
+ return { success: true };
57
+ }
58
+
59
+ export function resolveOutputDirs(options: {
60
+ outputs: string[];
61
+ projectName: string;
62
+ projectRoot: string;
63
+ workspaceRoot: string;
64
+ }): string[] {
65
+ const concreteOutputDirs = options.outputs.map((output) => outputDir(output, options));
66
+ const dedupedOutputDirs = [...new Set(concreteOutputDirs)].sort((a, b) => a.length - b.length);
67
+ return dedupedOutputDirs.filter(
68
+ (candidate, index) =>
69
+ !dedupedOutputDirs.some((other, otherIndex) => otherIndex < index && isWithin(candidate, other)),
70
+ );
71
+ }
72
+
73
+ function outputDir(
74
+ output: string,
75
+ options: { projectName: string; projectRoot: string; workspaceRoot: string },
76
+ ): string {
77
+ const interpolated = output
78
+ .replaceAll('{workspaceRoot}', '.')
79
+ .replaceAll('{projectRoot}', options.projectRoot)
80
+ .replaceAll('{projectName}', options.projectName);
81
+
82
+ const segments = interpolated.split(/[\\/]/);
83
+ const globIndex = segments.findIndex((segment) => segment.includes('*'));
84
+ const dirSegments = globIndex === -1 ? segments : segments.slice(0, globIndex);
85
+ const outputPath = dirSegments.join(path.sep);
86
+
87
+ return path.resolve(options.workspaceRoot, outputPath);
88
+ }
89
+
90
+ function assertSafeOutputDir(outputDir: string, projectRoot: string, workspaceRoot: string): void {
91
+ const absoluteWorkspaceRoot = path.resolve(workspaceRoot);
92
+ const absoluteProjectRoot = path.resolve(workspaceRoot, projectRoot);
93
+
94
+ if (!isWithin(outputDir, absoluteWorkspaceRoot)) {
95
+ throw new Error(`Refusing to remove output outside workspace: ${outputDir}`);
96
+ }
97
+
98
+ if (outputDir === absoluteWorkspaceRoot || outputDir === absoluteProjectRoot) {
99
+ throw new Error(`Refusing to remove unsafe output directory: ${path.relative(workspaceRoot, outputDir) || '.'}`);
100
+ }
101
+ }
102
+
103
+ function isWithin(candidate: string, parent: string): boolean {
104
+ const relative = path.relative(parent, candidate);
105
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
106
+ }
107
+
108
+ function containsTrackedFiles(outputDir: string, workspaceRoot: string): boolean {
109
+ const relativeOutputDir = path.relative(workspaceRoot, outputDir);
110
+ const trackedFiles = execFileSync('git', ['ls-files', '--', relativeOutputDir], {
111
+ cwd: workspaceRoot,
112
+ encoding: 'utf8',
113
+ });
114
+
115
+ return trackedFiles.trim().length > 0;
116
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "version": 2,
4
+ "title": "Clean Outputs Executor",
5
+ "description": "Remove declared build output directories unless they contain tracked files.",
6
+ "type": "object",
7
+ "properties": {
8
+ "outputs": {
9
+ "type": "array",
10
+ "items": { "type": "string" },
11
+ "description": "Optional output patterns. Defaults to the project's build outputs, then {projectRoot}/dist."
12
+ }
13
+ },
14
+ "additionalProperties": false
15
+ }
@@ -0,0 +1,3 @@
1
+ export interface CleanOutputsOptions {
2
+ outputs?: string[];
3
+ }
package/src/index.test.ts CHANGED
@@ -38,6 +38,8 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
38
38
  expect(targets.build?.executor).toBe('nx:noop');
39
39
  expect(targets.build?.cache).toBe(true);
40
40
  expect(targets.build?.dependsOn).toEqual(buildOutputDependencies);
41
+ expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
42
+ expect(targets.clean?.cache).toBe(false);
41
43
 
42
44
  expect(targets['typecheck-tests']?.executor).toBe('nx:run-commands');
43
45
  expect(targets['typecheck-tests']?.cache).toBe(true);
@@ -112,7 +114,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
112
114
 
113
115
  const targets = await inferProjectTargets(workspace, 'packages/ziggy/package.json');
114
116
 
115
- expect(Object.keys(targets).sort()).toEqual(['build', 'zig-native', 'zig-wasm']);
117
+ expect(Object.keys(targets).sort()).toEqual(['build', 'clean', 'zig-native', 'zig-wasm']);
116
118
  expect(targets.build?.dependsOn).toEqual(buildOutputDependencies);
117
119
  expect(targets.build?.cache).toBe(true);
118
120
  expect(targets['zig-wasm']?.cache).toBe(true);
@@ -144,6 +146,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
144
146
  expect(targets['tsdown-js']).toBeUndefined();
145
147
  expect(targets.build?.executor).toBe('nx:noop');
146
148
  expect(targets.build?.dependsOn).toEqual(buildOutputDependencies);
149
+ expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
147
150
  } finally {
148
151
  await workspace.cleanup();
149
152
  }
package/src/index.ts CHANGED
@@ -118,6 +118,10 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
118
118
  cache: true,
119
119
  dependsOn: ['^build', ...BUILD_OUTPUT_DEPENDENCIES],
120
120
  };
121
+ targets.clean = {
122
+ executor: '@smoothbricks/nx-plugin:clean-outputs',
123
+ cache: false,
124
+ };
121
125
  }
122
126
 
123
127
  if (targets['typecheck-tests']) {
@@ -262,6 +262,141 @@ describe('package target policy', () => {
262
262
  }
263
263
  });
264
264
 
265
+ it('removes self-recursive scripts using resolved Nx target metadata', async () => {
266
+ const root = await mkdtemp(join(tmpdir(), 'smoothbricks-pkg-target-'));
267
+ try {
268
+ await writeJson(join(root, 'package.json'), {
269
+ name: '@scope/root',
270
+ private: true,
271
+ workspaces: ['packages/*'],
272
+ });
273
+ await writeJson(join(root, 'packages/app/package.json'), {
274
+ name: '@scope/app',
275
+ dependencies: { '@scope/lib': 'workspace:*' },
276
+ scripts: {
277
+ build: 'nx run app:build',
278
+ test: 'bun test',
279
+ },
280
+ nx: {
281
+ name: 'app',
282
+ targets: {
283
+ 'tsdown-js': {
284
+ executor: 'nx:run-commands',
285
+ options: { command: 'tsdown', cwd: '{projectRoot}' },
286
+ },
287
+ },
288
+ },
289
+ });
290
+ await writeJson(join(root, 'packages/lib/package.json'), {
291
+ name: '@scope/lib',
292
+ });
293
+ const resolvedTargetsByProject = new Map<string, ResolvedProjectTargets>([
294
+ [
295
+ 'app',
296
+ {
297
+ targets: new Set(['build', 'test', 'tsdown-js']),
298
+ targetExecutors: new Map([
299
+ ['build', 'nx:run-script'],
300
+ ['test', 'nx:run-script'],
301
+ ['tsdown-js', 'nx:run-commands'],
302
+ ]),
303
+ targetScripts: new Map([
304
+ ['build', 'build'],
305
+ ['test', 'test'],
306
+ ]),
307
+ },
308
+ ],
309
+ ]);
310
+
311
+ const issues = checkPackageTargetPolicy(root, { resolvedTargetsByProject });
312
+ expect(issues.some((i) => i.message.includes('scripts.build recursively delegates'))).toBe(true);
313
+ expect(applyPackageTargetPolicy(root, { resolvedTargetsByProject })).toBe(true);
314
+
315
+ const app = JSON.parse(await readFile(join(root, 'packages/app/package.json'), 'utf8'));
316
+ expect(app.scripts.build).toBeUndefined();
317
+ expect(app.scripts.test).toBe('bun test');
318
+ } finally {
319
+ await rm(root, { recursive: true, force: true });
320
+ }
321
+ });
322
+
323
+ it('keeps self-alias scripts when resolved target comes from project configuration', async () => {
324
+ const root = await mkdtemp(join(tmpdir(), 'smoothbricks-pkg-target-'));
325
+ try {
326
+ await writeJson(join(root, 'package.json'), {
327
+ name: '@scope/root',
328
+ private: true,
329
+ workspaces: ['packages/*'],
330
+ });
331
+ await writeJson(join(root, 'packages/app/package.json'), {
332
+ name: '@scope/app',
333
+ dependencies: { '@scope/lib': 'workspace:*' },
334
+ scripts: {
335
+ build: 'nx run app:build',
336
+ },
337
+ nx: { name: 'app' },
338
+ });
339
+ await writeJson(join(root, 'packages/lib/package.json'), {
340
+ name: '@scope/lib',
341
+ });
342
+ const resolvedTargetsByProject = new Map<string, ResolvedProjectTargets>([
343
+ [
344
+ 'app',
345
+ {
346
+ targets: new Set(['build']),
347
+ targetExecutors: new Map([['build', 'nx:run-commands']]),
348
+ },
349
+ ],
350
+ ]);
351
+
352
+ expect(applyPackageTargetPolicy(root, { resolvedTargetsByProject })).toBe(false);
353
+
354
+ const app = JSON.parse(await readFile(join(root, 'packages/app/package.json'), 'utf8'));
355
+ expect(app.scripts.build).toBe('nx run app:build');
356
+ } finally {
357
+ await rm(root, { recursive: true, force: true });
358
+ }
359
+ });
360
+
361
+ it('accepts stream output style on non-continuous nx aliases', async () => {
362
+ const root = await mkdtemp(join(tmpdir(), 'smoothbricks-pkg-target-'));
363
+ try {
364
+ await writeJson(join(root, 'package.json'), {
365
+ name: '@scope/root',
366
+ private: true,
367
+ workspaces: ['packages/*'],
368
+ });
369
+ await writeJson(join(root, 'packages/app/package.json'), {
370
+ name: '@scope/app',
371
+ dependencies: { '@scope/lib': 'workspace:*' },
372
+ scripts: {
373
+ deploy: 'nx run app:deploy:production --outputStyle=stream',
374
+ },
375
+ nx: {
376
+ name: 'app',
377
+ targets: {
378
+ deploy: {
379
+ executor: 'nx:run-commands',
380
+ options: { command: 'wrangler deploy --env production', cwd: '{projectRoot}' },
381
+ configurations: {
382
+ production: { command: 'wrangler deploy --env production' },
383
+ },
384
+ },
385
+ },
386
+ },
387
+ });
388
+ await writeJson(join(root, 'packages/lib/package.json'), {
389
+ name: '@scope/lib',
390
+ });
391
+
392
+ const issues = checkPackageTargetPolicy(root);
393
+ expect(issues.some((i) => i.message.includes('scripts.deploy must delegate'))).toBe(false);
394
+ expect(applyPackageTargetPolicy(root)).toBe(false);
395
+ } finally {
396
+ await rm(root, { recursive: true, force: true });
397
+ }
398
+ });
399
+
265
400
  it('moves env assignments into target options', async () => {
266
401
  const root = await mkdtemp(join(tmpdir(), 'smoothbricks-pkg-target-'));
267
402
  try {
@@ -11,6 +11,8 @@ export type { NxPolicyIssue };
11
11
  export interface ResolvedProjectTargets {
12
12
  targets: ReadonlySet<string>;
13
13
  buildDependsOn?: readonly string[];
14
+ targetExecutors?: ReadonlyMap<string, string>;
15
+ targetScripts?: ReadonlyMap<string, string>;
14
16
  }
15
17
 
16
18
  export interface PackageTargetPolicyOptions {
@@ -200,14 +202,31 @@ function resolvedProjectBuildDependsOn(
200
202
  return resolvedProject.buildDependsOn;
201
203
  }
202
204
 
205
+ function resolvedProjectTargetExecutor(
206
+ resolvedProject: ReadonlySet<string> | ResolvedProjectTargets | undefined,
207
+ targetName: string,
208
+ ): string | undefined {
209
+ return isResolvedProjectTargets(resolvedProject) ? resolvedProject.targetExecutors?.get(targetName) : undefined;
210
+ }
211
+
212
+ function resolvedProjectTargetScript(
213
+ resolvedProject: ReadonlySet<string> | ResolvedProjectTargets | undefined,
214
+ targetName: string,
215
+ ): string | undefined {
216
+ return isResolvedProjectTargets(resolvedProject) ? resolvedProject.targetScripts?.get(targetName) : undefined;
217
+ }
218
+
203
219
  function isResolvedProjectTargets(
204
220
  value: ReadonlySet<string> | ResolvedProjectTargets | undefined,
205
221
  ): value is ResolvedProjectTargets {
206
222
  return isRecord(value) && value.targets instanceof Set;
207
223
  }
208
224
 
209
- function targetExistsInResolvedProject(targetName: string, resolvedTargets?: ReadonlySet<string>): boolean {
210
- return resolvedTargets?.has(targetName) === true;
225
+ function targetExistsInResolvedProject(
226
+ targetName: string,
227
+ resolvedTargets?: ReadonlySet<string> | ResolvedProjectTargets,
228
+ ): boolean {
229
+ return resolvedProjectTargetNames(resolvedTargets)?.has(targetName) === true;
211
230
  }
212
231
 
213
232
  function isBuildOutputDependencyPattern(dependency: string): boolean {
@@ -304,6 +323,19 @@ export function nxRunAlias(
304
323
  return `nx run ${projectName}:${targetName}${flags}`;
305
324
  }
306
325
 
326
+ function nxRunAliasMatches(
327
+ rawAlias: { projectName: string; targetName: string } | null,
328
+ expectedAlias: string,
329
+ ): boolean {
330
+ const expected = parseNxRunAlias(expectedAlias);
331
+ return (
332
+ !!rawAlias &&
333
+ !!expected &&
334
+ rawAlias.projectName === expected.projectName &&
335
+ rawAlias.targetName === expected.targetName
336
+ );
337
+ }
338
+
307
339
  function nxRunOutputStyle(command?: string | null): 'stream' | 'dynamic-legacy' {
308
340
  if (command && /(?:^|\s)(?:astro|vite)\s+dev(?:\s|$)/.test(command)) {
309
341
  return 'dynamic-legacy';
@@ -652,7 +684,7 @@ function validatePackageScriptPolicy(
652
684
  pkg: Record<string, unknown>,
653
685
  packagePath: string,
654
686
  workspaceNames: ReadonlySet<string>,
655
- options: { resolvedTargets?: ReadonlySet<string> } = {},
687
+ options: { resolvedTargets?: ReadonlySet<string> | ResolvedProjectTargets } = {},
656
688
  ): NxPolicyIssue[] {
657
689
  if (!hasWorkspaceDependency(pkg, workspaceNames)) {
658
690
  return [];
@@ -670,6 +702,13 @@ function validatePackageScriptPolicy(
670
702
  continue;
671
703
  }
672
704
  const alias = parseNxRunAlias(rawCommand);
705
+ if (isResolvedSelfRecursiveScript(scriptName, alias, projectName, options.resolvedTargets)) {
706
+ issues.push({
707
+ path: packagePath,
708
+ message: `${packagePath}: scripts.${scriptName} recursively delegates to its own inferred Nx target; remove the script so the resolved Nx target can run`,
709
+ });
710
+ continue;
711
+ }
673
712
  const rewrite = alias
674
713
  ? { targetName: alias.targetName, continuous: isContinuousTarget(alias.targetName, '') }
675
714
  : classifyScriptRewrite(scriptName, rawCommand);
@@ -694,7 +733,7 @@ function validatePackageScriptPolicy(
694
733
  const command = targetOptions ? stringProperty(targetOptions, 'command') : null;
695
734
  const rewriteCommand = 'command' in rewrite ? rewrite.command : null;
696
735
  const expectedAlias = nxRunAlias(projectName, rewrite.targetName, rewrite.continuous, command ?? rewriteCommand);
697
- if (rawCommand !== expectedAlias) {
736
+ if (alias ? !nxRunAliasMatches(alias, expectedAlias) : rawCommand !== expectedAlias) {
698
737
  issues.push({
699
738
  path: packagePath,
700
739
  message: `${packagePath}: scripts.${scriptName} must delegate to ${expectedAlias}`,
@@ -989,7 +1028,7 @@ function applyPackageScriptPolicyForPkg(
989
1028
  pkg: Record<string, unknown>,
990
1029
  _packagePath: string,
991
1030
  workspaceNames: ReadonlySet<string>,
992
- options: { resolvedTargets?: ReadonlySet<string> } = {},
1031
+ options: { resolvedTargets?: ReadonlySet<string> | ResolvedProjectTargets } = {},
993
1032
  ): boolean {
994
1033
  if (!hasWorkspaceDependency(pkg, workspaceNames)) {
995
1034
  return false;
@@ -1010,6 +1049,11 @@ function applyPackageScriptPolicyForPkg(
1010
1049
  continue;
1011
1050
  }
1012
1051
  const parsedAlias = parseNxRunAlias(rawCommand);
1052
+ if (isResolvedSelfRecursiveScript(scriptName, parsedAlias, projectName, options.resolvedTargets)) {
1053
+ delete scripts[scriptName];
1054
+ changed = true;
1055
+ continue;
1056
+ }
1013
1057
  if (parsedAlias?.projectName === projectName && parsedAlias.targetName === 'test') {
1014
1058
  continue;
1015
1059
  }
@@ -1065,6 +1109,20 @@ function applyPackageScriptPolicyForPkg(
1065
1109
  return changed;
1066
1110
  }
1067
1111
 
1112
+ function isResolvedSelfRecursiveScript(
1113
+ scriptName: string,
1114
+ alias: { projectName: string; targetName: string } | null,
1115
+ projectName: string | null,
1116
+ resolvedTargets?: ReadonlySet<string> | ResolvedProjectTargets,
1117
+ ): boolean {
1118
+ return (
1119
+ alias?.projectName === projectName &&
1120
+ alias.targetName === scriptName &&
1121
+ resolvedProjectTargetExecutor(resolvedTargets, scriptName) === 'nx:run-script' &&
1122
+ resolvedProjectTargetScript(resolvedTargets, scriptName) === scriptName
1123
+ );
1124
+ }
1125
+
1068
1126
  export function checkPackageTargets(
1069
1127
  pkg: Record<string, unknown>,
1070
1128
  packagePath: string,
@@ -1103,7 +1161,7 @@ export function checkPackageTargetPolicy(root: string, options: PackageTargetPol
1103
1161
  issues.push(...validateExplicitNxTargets(pkg, packagePath, resolvedTargets));
1104
1162
  issues.push(...validateTestEntrypointPresence(root, packagePath, pkg));
1105
1163
  issues.push(...validateBuildZigPolicy(root, packagePath));
1106
- issues.push(...validatePackageScriptPolicy(pkg, packagePath, workspaceNames, { resolvedTargets }));
1164
+ issues.push(...validatePackageScriptPolicy(pkg, packagePath, workspaceNames, { resolvedTargets: resolvedProject }));
1107
1165
  }
1108
1166
 
1109
1167
  return issues;
@@ -1128,7 +1186,8 @@ export function applyPackageTargetPolicy(root: string, options: PackageTargetPol
1128
1186
  packageChanged = removePackageColonTargets(pkg) || packageChanged;
1129
1187
  packageChanged = removeRedundantNoopBuildTarget(pkg, resolvedProject) || packageChanged;
1130
1188
  packageChanged =
1131
- applyPackageScriptPolicyForPkg(pkg, packagePath, workspaceNames, { resolvedTargets }) || packageChanged;
1189
+ applyPackageScriptPolicyForPkg(pkg, packagePath, workspaceNames, { resolvedTargets: resolvedProject }) ||
1190
+ packageChanged;
1132
1191
 
1133
1192
  if (packageChanged) {
1134
1193
  writeJsonObject(packageJsonPath, pkg);
@@ -36,13 +36,18 @@ function validNxJson(): Record<string, unknown> {
36
36
  },
37
37
  '@smoothbricks/nx-plugin',
38
38
  ],
39
- targetDefaults: {
40
- build: { cache: true, outputs: ['{projectRoot}/dist'] },
41
- },
39
+ targetDefaults: validTargetDefaults(),
42
40
  namedInputs: validNamedInputs(),
43
41
  };
44
42
  }
45
43
 
44
+ function validTargetDefaults(): Record<string, unknown> {
45
+ return {
46
+ build: { cache: true, outputs: ['{projectRoot}/dist'] },
47
+ clean: { executor: '@smoothbricks/nx-plugin:clean-outputs', cache: false },
48
+ };
49
+ }
50
+
46
51
  function validNamedInputs(): Record<string, unknown> {
47
52
  return {
48
53
  default: ['{projectRoot}/**/*', 'sharedGlobals'],
@@ -95,7 +100,7 @@ describe('pure core: checkWorkspaceConfig', () => {
95
100
  it('detects missing plugins', () => {
96
101
  const issues = checkWorkspaceConfig({
97
102
  plugins: [],
98
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
103
+ targetDefaults: validTargetDefaults(),
99
104
  namedInputs: validNamedInputs(),
100
105
  });
101
106
  expect(issues.length).toBe(2);
@@ -107,7 +112,7 @@ describe('pure core: checkWorkspaceConfig', () => {
107
112
  const issues = checkWorkspaceConfig({
108
113
  ...validNxJson(),
109
114
  targetDefaults: {
110
- build: { cache: true, outputs: ['{projectRoot}/dist'] },
115
+ ...validTargetDefaults(),
111
116
  'build:wasm': { cache: true },
112
117
  },
113
118
  });
@@ -121,7 +126,7 @@ describe('pure core: checkWorkspaceConfig', () => {
121
126
  { plugin: '@nx/js/typescript', options: { build: { targetName: 'build' } } },
122
127
  '@smoothbricks/nx-plugin',
123
128
  ],
124
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
129
+ targetDefaults: validTargetDefaults(),
125
130
  namedInputs: validNamedInputs(),
126
131
  });
127
132
  expect(issues.some((i) => i.message.includes('build.targetName must be tsc-js'))).toBe(true);
@@ -130,7 +135,7 @@ describe('pure core: checkWorkspaceConfig', () => {
130
135
  it('detects imprecise production inputs', () => {
131
136
  const issues = checkWorkspaceConfig({
132
137
  plugins: validPlugins(),
133
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
138
+ targetDefaults: validTargetDefaults(),
134
139
  namedInputs: {
135
140
  ...validNamedInputs(),
136
141
  production: ['default'],
@@ -142,7 +147,10 @@ describe('pure core: checkWorkspaceConfig', () => {
142
147
  it('detects missing build cache', () => {
143
148
  const issues = checkWorkspaceConfig({
144
149
  plugins: validPlugins(),
145
- targetDefaults: { build: { cache: false } },
150
+ targetDefaults: {
151
+ build: { cache: false },
152
+ clean: { executor: '@smoothbricks/nx-plugin:clean-outputs', cache: false },
153
+ },
146
154
  namedInputs: validNamedInputs(),
147
155
  });
148
156
  expect(issues.some((i) => i.message.includes('build.cache must be true'))).toBe(true);
@@ -152,7 +160,7 @@ describe('pure core: checkWorkspaceConfig', () => {
152
160
  it('detects missing sharedGlobals', () => {
153
161
  const issues = checkWorkspaceConfig({
154
162
  plugins: validPlugins(),
155
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
163
+ targetDefaults: validTargetDefaults(),
156
164
  namedInputs: {
157
165
  ...validNamedInputs(),
158
166
  sharedGlobals: [],
@@ -171,7 +179,7 @@ describe('pure core: applyWorkspaceConfig', () => {
171
179
  it('fixes missing plugins', () => {
172
180
  const nxJson: Record<string, unknown> = {
173
181
  plugins: [],
174
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
182
+ targetDefaults: validTargetDefaults(),
175
183
  namedInputs: validNamedInputs(),
176
184
  };
177
185
  expect(applyWorkspaceConfig(nxJson)).toBe(true);
@@ -186,7 +194,7 @@ describe('pure core: applyWorkspaceConfig', () => {
186
194
  const nxJson = {
187
195
  ...validNxJson(),
188
196
  targetDefaults: {
189
- build: { cache: true, outputs: ['{projectRoot}/dist'] },
197
+ ...validTargetDefaults(),
190
198
  'build:wasm': { cache: true },
191
199
  },
192
200
  };
@@ -197,7 +205,7 @@ describe('pure core: applyWorkspaceConfig', () => {
197
205
  it('fixes imprecise production inputs', () => {
198
206
  const nxJson: Record<string, unknown> = {
199
207
  plugins: validPlugins(),
200
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
208
+ targetDefaults: validTargetDefaults(),
201
209
  namedInputs: {
202
210
  ...validNamedInputs(),
203
211
  production: ['default', '{projectRoot}/**/*'],
@@ -217,7 +225,7 @@ describe('pure core: applyWorkspaceConfig', () => {
217
225
  it('accepts custom precise production inputs unchanged', () => {
218
226
  const nxJson: Record<string, unknown> = {
219
227
  plugins: validPlugins(),
220
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
228
+ targetDefaults: validTargetDefaults(),
221
229
  namedInputs: {
222
230
  ...validNamedInputs(),
223
231
  production: ['{projectRoot}/src/**/*.rs', '{projectRoot}/Cargo.toml', '!{projectRoot}/**/*.test.*'],
@@ -245,7 +253,7 @@ describe('Tree: checkWorkspaceConfigTree', () => {
245
253
  const tree = createTreeWithEmptyWorkspace();
246
254
  writeJson(tree, 'nx.json', {
247
255
  plugins: [],
248
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
256
+ targetDefaults: validTargetDefaults(),
249
257
  namedInputs: validNamedInputs(),
250
258
  });
251
259
 
@@ -274,7 +282,7 @@ describe('Tree: applyWorkspaceConfigTree', () => {
274
282
  const tree = createTreeWithEmptyWorkspace();
275
283
  writeJson(tree, 'nx.json', {
276
284
  plugins: [],
277
- targetDefaults: { build: { cache: true, outputs: ['{projectRoot}/dist'] } },
285
+ targetDefaults: validTargetDefaults(),
278
286
  namedInputs: validNamedInputs(),
279
287
  });
280
288
 
@@ -313,6 +321,10 @@ describe('Tree: applyWorkspaceConfigTree', () => {
313
321
  cache: true,
314
322
  outputs: ['{projectRoot}/dist'],
315
323
  });
324
+ expect((nxJson.targetDefaults as Record<string, unknown>).clean).toEqual({
325
+ executor: '@smoothbricks/nx-plugin:clean-outputs',
326
+ cache: false,
327
+ });
316
328
  });
317
329
  });
318
330
 
@@ -23,6 +23,7 @@ export const BUILD_OUTPUT_DEPENDENCIES = [
23
23
 
24
24
  const nxJsTypescriptPlugin = '@nx/js/typescript';
25
25
  const smoothBricksNxPlugin = '@smoothbricks/nx-plugin';
26
+ const cleanOutputsExecutor = '@smoothbricks/nx-plugin:clean-outputs';
26
27
  const expectedSharedGlobalsNamedInput = ['{workspaceRoot}/.github/workflows/ci.yml'];
27
28
  const defaultProductionNamedInput = [
28
29
  '{projectRoot}/src/**/*',
@@ -57,6 +58,9 @@ export function checkWorkspaceConfig(nxJson: Record<string, unknown>): NxPolicyI
57
58
  // Build target default
58
59
  validateBuildTargetDefault(nxJson, 'nx.json', issues);
59
60
 
61
+ // Clean target default
62
+ validateCleanTargetDefault(nxJson, 'nx.json', issues);
63
+
60
64
  // Named input defaults
61
65
  validateNamedInputDefaults(nxJson, 'nx.json', issues);
62
66
 
@@ -97,6 +101,7 @@ export function checkWorkspaceConfig(nxJson: Record<string, unknown>): NxPolicyI
97
101
  export function applyWorkspaceConfig(nxJson: Record<string, unknown>): boolean {
98
102
  let changed = removeColonTargetDefaults(nxJson);
99
103
  changed = applyBuildTargetDefault(nxJson) || changed;
104
+ changed = applyCleanTargetDefault(nxJson) || changed;
100
105
  changed = applyNamedInputDefaults(nxJson) || changed;
101
106
  const currentPlugins = Array.isArray(nxJson.plugins) ? nxJson.plugins : [];
102
107
  const nextPlugins = upsertNxPlugin(
@@ -185,6 +190,21 @@ function validateBuildTargetDefault(
185
190
  }
186
191
  }
187
192
 
193
+ function validateCleanTargetDefault(
194
+ nxJson: Record<string, unknown>,
195
+ nxJsonPath: string,
196
+ issues: NxPolicyIssue[],
197
+ ): void {
198
+ const targetDefaults = recordProperty(nxJson, 'targetDefaults');
199
+ const clean = targetDefaults ? recordProperty(targetDefaults, 'clean') : null;
200
+ if (!clean || clean.executor !== cleanOutputsExecutor) {
201
+ issues.push({ path: nxJsonPath, message: `targetDefaults.clean.executor must be ${cleanOutputsExecutor}` });
202
+ }
203
+ if (!clean || clean.cache !== false) {
204
+ issues.push({ path: nxJsonPath, message: 'targetDefaults.clean.cache must be false' });
205
+ }
206
+ }
207
+
188
208
  function validateNamedInputDefaults(
189
209
  nxJson: Record<string, unknown>,
190
210
  nxJsonPath: string,
@@ -235,6 +255,14 @@ function applyBuildTargetDefault(nxJson: Record<string, unknown>): boolean {
235
255
  return changed;
236
256
  }
237
257
 
258
+ function applyCleanTargetDefault(nxJson: Record<string, unknown>): boolean {
259
+ const targetDefaults = getOrCreateRecord(nxJson, 'targetDefaults');
260
+ const clean = getOrCreateRecord(targetDefaults, 'clean');
261
+ let changed = setStringProperty(clean, 'executor', cleanOutputsExecutor);
262
+ changed = setBooleanProperty(clean, 'cache', false) || changed;
263
+ return changed;
264
+ }
265
+
238
266
  function applyNamedInputDefaults(nxJson: Record<string, unknown>): boolean {
239
267
  const namedInputs = getOrCreateRecord(nxJson, 'namedInputs');
240
268
  let changed = false;
@@ -374,6 +402,14 @@ function setBooleanProperty(record: Record<string, unknown>, key: string, value:
374
402
  return true;
375
403
  }
376
404
 
405
+ function setStringProperty(record: Record<string, unknown>, key: string, value: string): boolean {
406
+ if (record[key] === value) {
407
+ return false;
408
+ }
409
+ record[key] = value;
410
+ return true;
411
+ }
412
+
377
413
  function setStringArrayProperty(record: Record<string, unknown>, key: string, value: string[]): boolean {
378
414
  const current = record[key];
379
415
  if (stringArrayEquals(current, value)) {