@smoothbricks/nx-plugin 0.2.5 → 0.3.1

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.
@@ -41,7 +41,11 @@ export function applyBoundedTestTargetPolicy(
41
41
  options: ApplyBoundedTestTargetPolicyOptions,
42
42
  ): void {
43
43
  const command = resolveTestCommand(packageJson, options.defaultCommand ?? 'bun test', options.projectJson);
44
- const targetOwner = options.projectJson ?? (packageJson.nx ??= {});
44
+ let targetOwner = options.projectJson;
45
+ if (!targetOwner) {
46
+ packageJson.nx ??= {};
47
+ targetOwner = packageJson.nx;
48
+ }
45
49
 
46
50
  targetOwner.targets ??= {};
47
51
 
@@ -251,7 +255,22 @@ function listWorkspacePackageJsonPaths(root: string): string[] {
251
255
  }
252
256
 
253
257
  function readPackageJson(path: string): BoundedTestPolicyPackageJson {
254
- return JSON.parse(readFileSync(path, 'utf8')) as BoundedTestPolicyPackageJson;
258
+ const parsed = readJsonObject(path);
259
+ const nx = isRecord(parsed.nx) ? parsed.nx : undefined;
260
+ const normalizedNx = nx
261
+ ? {
262
+ ...nx,
263
+ name: typeof nx.name === 'string' ? nx.name : undefined,
264
+ targets: readTargets(nx.targets),
265
+ }
266
+ : undefined;
267
+ return {
268
+ ...parsed,
269
+ name: typeof parsed.name === 'string' ? parsed.name : undefined,
270
+ workspaces: parsed.workspaces,
271
+ scripts: isRecord(parsed.scripts) ? parsed.scripts : undefined,
272
+ nx: normalizedNx,
273
+ };
255
274
  }
256
275
 
257
276
  function writePackageJson(path: string, packageJson: BoundedTestPolicyPackageJson): void {
@@ -259,7 +278,31 @@ function writePackageJson(path: string, packageJson: BoundedTestPolicyPackageJso
259
278
  }
260
279
 
261
280
  function readProjectJson(path: string): BoundedTestPolicyProjectJson {
262
- return JSON.parse(readFileSync(path, 'utf8')) as BoundedTestPolicyProjectJson;
281
+ const parsed = readJsonObject(path);
282
+ return {
283
+ ...parsed,
284
+ name: typeof parsed.name === 'string' ? parsed.name : undefined,
285
+ targets: readTargets(parsed.targets),
286
+ };
287
+ }
288
+
289
+ function readJsonObject(path: string): Record<string, unknown> {
290
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'));
291
+ if (!isRecord(parsed)) {
292
+ throw new Error(`${path} must contain a JSON object`);
293
+ }
294
+ return parsed;
295
+ }
296
+
297
+ function readTargets(value: unknown): Record<string, Record<string, unknown>> | undefined {
298
+ if (!isRecord(value)) {
299
+ return undefined;
300
+ }
301
+ const targets: Record<string, Record<string, unknown>> = {};
302
+ for (const [name, target] of Object.entries(value)) {
303
+ targets[name] = isRecord(target) ? target : {};
304
+ }
305
+ return targets;
263
306
  }
264
307
 
265
308
  function writeProjectJson(path: string, projectJson: BoundedTestPolicyProjectJson): void {
@@ -140,14 +140,18 @@ function buildPackageJson(
140
140
  packageJson.license = 'MIT';
141
141
  packageJson.publishConfig = { access: 'public' };
142
142
  const rootRepository = rootPkg.repository;
143
- if (rootRepository && typeof rootRepository === 'object') {
143
+ if (isRecord(rootRepository)) {
144
144
  packageJson.repository = {
145
- type: (rootRepository as Record<string, unknown>).type ?? 'git',
146
- url: (rootRepository as Record<string, unknown>).url,
145
+ type: rootRepository.type ?? 'git',
146
+ url: rootRepository.url,
147
147
  directory: projectRoot,
148
148
  };
149
149
  }
150
- (packageJson.nx as Record<string, unknown>).tags = ['npm:public'];
150
+ const nx = packageJson.nx;
151
+ if (!isRecord(nx)) {
152
+ throw new Error('generated package.json nx configuration must be an object');
153
+ }
154
+ nx.tags = ['npm:public'];
151
155
  } else {
152
156
  packageJson.private = true;
153
157
  }
@@ -160,13 +164,25 @@ function writeZigFiles(tree: Tree, schema: CreatePackageGeneratorSchema, project
160
164
  const packageJson = readJson<Record<string, unknown>>(tree, `${projectRoot}/package.json`);
161
165
 
162
166
  // Add wasm export and remove development condition
163
- const exports = packageJson.exports as Record<string, unknown>;
167
+ const exports = packageJson.exports;
168
+ if (!isRecord(exports)) {
169
+ // invariant throw: writeCommonFiles always emits an object-valued exports map.
170
+ throw new Error('generated package.json exports must be an object');
171
+ }
164
172
  exports['./wasm'] = `./dist/${schema.name}.wasm`;
165
- const dotExport = exports['.'] as Record<string, unknown>;
173
+ const dotExport = exports['.'];
174
+ if (!isRecord(dotExport)) {
175
+ // invariant throw: writeCommonFiles always emits an object-valued "." export.
176
+ throw new Error('generated package.json "." export must be an object');
177
+ }
166
178
  delete dotExport.development;
167
179
 
168
180
  // Add build scripts
169
- const scripts = packageJson.scripts as Record<string, string>;
181
+ const scripts = packageJson.scripts;
182
+ if (!isRecord(scripts)) {
183
+ // invariant throw: writeCommonFiles always emits an object-valued scripts map.
184
+ throw new Error('generated package.json scripts must be an object');
185
+ }
170
186
  scripts['build:zig'] = `nx run ${schema.name}:zig-wasm`;
171
187
  scripts['build:ts'] = `nx run ${schema.name}:tsc-js`;
172
188
  scripts.build = 'bun run build:ts && bun run build:zig';
@@ -178,7 +194,11 @@ function writeZigFiles(tree: Tree, schema: CreatePackageGeneratorSchema, project
178
194
 
179
195
  // Modify tsconfig.lib.json for ts-zig
180
196
  const tsconfigLib = readJson<Record<string, unknown>>(tree, `${projectRoot}/tsconfig.lib.json`);
181
- const libCompilerOptions = tsconfigLib.compilerOptions as Record<string, unknown>;
197
+ const libCompilerOptions = tsconfigLib.compilerOptions;
198
+ if (!isRecord(libCompilerOptions)) {
199
+ // invariant throw: writeCommonFiles always emits compilerOptions for library builds.
200
+ throw new Error('generated tsconfig.lib.json compilerOptions must be an object');
201
+ }
182
202
  libCompilerOptions.lib = ['es2022', 'webworker'];
183
203
  libCompilerOptions.declaration = true;
184
204
  libCompilerOptions.sourceMap = true;
@@ -187,7 +207,11 @@ function writeZigFiles(tree: Tree, schema: CreatePackageGeneratorSchema, project
187
207
 
188
208
  // Modify tsconfig.test.json for ts-zig
189
209
  const tsconfigTest = readJson<Record<string, unknown>>(tree, `${projectRoot}/tsconfig.test.json`);
190
- const testCompilerOptions = tsconfigTest.compilerOptions as Record<string, unknown>;
210
+ const testCompilerOptions = tsconfigTest.compilerOptions;
211
+ if (!isRecord(testCompilerOptions)) {
212
+ // invariant throw: writeCommonFiles always emits compilerOptions for test builds.
213
+ throw new Error('generated tsconfig.test.json compilerOptions must be an object');
214
+ }
191
215
  testCompilerOptions.lib = ['es2022', 'webworker'];
192
216
  writeJson(tree, `${projectRoot}/tsconfig.test.json`, tsconfigTest);
193
217
 
@@ -249,3 +273,7 @@ pub fn build(b: *std.Build) void {
249
273
  `,
250
274
  );
251
275
  }
276
+
277
+ function isRecord(value: unknown): value is Record<string, unknown> {
278
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
279
+ }
@@ -40,7 +40,7 @@ export default async function generator(tree: Tree, schema: MakePublicGeneratorS
40
40
  };
41
41
  }
42
42
 
43
- const nx = (pkg.nx ?? {}) as Record<string, unknown>;
43
+ const nx = isRecord(pkg.nx) ? pkg.nx : {};
44
44
  const tags = Array.isArray(nx.tags) ? [...nx.tags] : [];
45
45
  if (!tags.includes('npm:public')) {
46
46
  tags.push('npm:public');
@@ -56,6 +56,10 @@ export default async function generator(tree: Tree, schema: MakePublicGeneratorS
56
56
  });
57
57
  }
58
58
 
59
+ function isRecord(value: unknown): value is Record<string, unknown> {
60
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
61
+ }
62
+
59
63
  function resolveProject(tree: Tree, projectInput: string): { name: string; root: string } {
60
64
  const normalizedInput = normalizeLookupValue(projectInput);
61
65
 
package/src/index.test.ts CHANGED
@@ -22,7 +22,28 @@ const buildOutputDependencies = [
22
22
  ];
23
23
 
24
24
  describe('@smoothbricks/nx-plugin inferred targets', () => {
25
- it('infers validation and aggregate build targets without owning TypeScript lib build', async () => {
25
+ it('names standalone package projects from package metadata', async () => {
26
+ const workspace = await createWorkspace();
27
+ try {
28
+ await workspace.write(
29
+ 'specs/prototype/package.json',
30
+ '{"name":"standalone-package","nx":{"name":"standalone-project"}}\n',
31
+ );
32
+ await workspace.write('specs/package-fallback/package.json', '{"name":"package-fallback"}\n');
33
+
34
+ const explicit = await inferProject(workspace, 'specs/prototype/package.json');
35
+ const fallback = await inferProject(workspace, 'specs/package-fallback/package.json');
36
+
37
+ expect(explicit?.name).toBe('standalone-project');
38
+ expect(explicit?.targets).toEqual({});
39
+ expect(fallback?.name).toBe('package-fallback');
40
+ expect(fallback?.targets).toEqual({});
41
+ } finally {
42
+ await workspace.cleanup();
43
+ }
44
+ });
45
+
46
+ it('overrides inferred TypeScript compiler commands with ttsc', async () => {
26
47
  const workspace = await createWorkspace();
27
48
  try {
28
49
  await workspace.write(
@@ -34,7 +55,32 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
34
55
 
35
56
  const targets = await inferProjectTargets(workspace, 'packages/example/package.json');
36
57
 
37
- expect(targets['tsc-js']).toBeUndefined();
58
+ expect(targets['tsc-js']?.options).toMatchObject({
59
+ command: 'ttsc -p tsconfig.lib.json --emit',
60
+ cwd: 'packages/example',
61
+ });
62
+ const toolchainInputs = [
63
+ '{workspaceRoot}/package.json',
64
+ '{workspaceRoot}/bun.lock',
65
+ '{workspaceRoot}/patches/**/*',
66
+ '{workspaceRoot}/tsconfig.base.json',
67
+ ];
68
+ expect(targets['tsc-js']?.inputs).toEqual([
69
+ 'production',
70
+ '^production',
71
+ ...toolchainInputs,
72
+ '{projectRoot}/tsconfig.lib.json',
73
+ ]);
74
+ expect(targets.typecheck?.options).toMatchObject({
75
+ command: 'ttsc -p tsconfig.lib.json --noEmit',
76
+ cwd: 'packages/example',
77
+ });
78
+ expect(targets.typecheck?.inputs).toEqual([
79
+ 'production',
80
+ '^production',
81
+ ...toolchainInputs,
82
+ '{projectRoot}/tsconfig.lib.json',
83
+ ]);
38
84
  expect(targets.build?.executor).toBe('nx:noop');
39
85
  expect(targets.build?.cache).toBe(true);
40
86
  expect(targets.build?.dependsOn).toEqual(buildOutputDependencies);
@@ -45,14 +91,20 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
45
91
  expect(targets['typecheck-tests']?.cache).toBe(true);
46
92
  expect(targets['typecheck-tests']?.dependsOn).toEqual(['typecheck']);
47
93
  expect(targets['typecheck-tests']?.options).toMatchObject({
48
- command: 'tsc --noEmit -p tsconfig.test.json',
94
+ command: 'ttsc -p tsconfig.test.json --noEmit',
49
95
  cwd: 'packages/example',
50
96
  });
97
+ expect(targets['typecheck-tests']?.inputs).toEqual([
98
+ 'default',
99
+ '^production',
100
+ ...toolchainInputs,
101
+ '{projectRoot}/tsconfig.test.json',
102
+ ]);
51
103
 
52
104
  expect(targets['typecheck-tests:watch']?.executor).toBe('nx:run-commands');
53
105
  expect(targets['typecheck-tests:watch']?.continuous).toBe(true);
54
106
  expect(targets['typecheck-tests:watch']?.options).toMatchObject({
55
- command: 'tsc --noEmit -p tsconfig.test.json --watch',
107
+ command: 'ttsc -p tsconfig.test.json --noEmit --watch',
56
108
  cwd: 'packages/example',
57
109
  });
58
110
 
@@ -64,7 +116,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
64
116
  cwd: 'packages/example',
65
117
  });
66
118
 
67
- expect(targets.lint?.executor).toBe('nx:noop');
119
+ expect(targets.lint?.executor).toBeUndefined();
68
120
  expect(targets.lint?.cache).toBe(true);
69
121
  expect(targets.lint?.dependsOn).toEqual(['typecheck-tests']);
70
122
  } finally {
@@ -152,6 +204,123 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
152
204
  }
153
205
  });
154
206
 
207
+ it('infers cargo workspace targets including explicitly named wasm crate builds', async () => {
208
+ const workspace = await createWorkspace();
209
+ try {
210
+ await workspace.write('packages/ferris/package.json', '{"name":"ferris"}\n');
211
+ await workspace.write(
212
+ 'packages/ferris/Cargo.toml',
213
+ '[workspace]\nmembers = ["crates/ferris-core", "crates/ferris-wasm"]\n\n[profile.wasm-release]\ninherits = "release"\n',
214
+ );
215
+ await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
216
+ await workspace.write(
217
+ 'packages/ferris/crates/ferris-wasm/Cargo.toml',
218
+ '[package]\nname = "ferris-wasm"\n\n[lib]\ncrate-type = ["cdylib", "rlib"]\n',
219
+ );
220
+
221
+ const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
222
+
223
+ expect(Object.keys(targets).sort()).toEqual([
224
+ 'bench',
225
+ 'build',
226
+ 'cargo-lint',
227
+ 'cargo-test',
228
+ 'cargo-wasm',
229
+ 'clean',
230
+ 'lint',
231
+ 'mutation',
232
+ 'test',
233
+ ]);
234
+ expect(targets['cargo-test']?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
235
+ expect(targets['cargo-test']?.options).toMatchObject({
236
+ command: 'cargo test --workspace',
237
+ cwd: 'packages/ferris',
238
+ });
239
+ expect(targets['cargo-test']?.inputs).toEqual([
240
+ '{projectRoot}/**/*.rs',
241
+ '{projectRoot}/**/Cargo.toml',
242
+ '{projectRoot}/Cargo.lock',
243
+ '{projectRoot}/.cargo/config.toml',
244
+ '!{projectRoot}/target/**',
245
+ ]);
246
+ expect(targets['cargo-lint']?.options).toMatchObject({
247
+ commands: ['cargo fmt --all --check', 'cargo clippy --workspace --all-targets -- -D warnings'],
248
+ });
249
+ expect(targets.lint?.dependsOn).toEqual(['cargo-lint']);
250
+ expect(targets.test?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
251
+ expect(targets.test?.options).toMatchObject({
252
+ command: 'cargo test --workspace',
253
+ cwd: 'packages/ferris',
254
+ });
255
+ expect(targets.mutation?.cache).toBe(false);
256
+ expect(targets.mutation?.options).toMatchObject({ command: 'cargo mutants --workspace' });
257
+ expect(targets['cargo-wasm']?.outputs).toEqual(['{projectRoot}/dist/**/*.wasm']);
258
+ expect(targets['cargo-wasm']?.options).toMatchObject({
259
+ commands: [
260
+ 'cargo build --profile wasm-release --target wasm32-unknown-unknown -p ferris-wasm && mkdir -p dist && cp target/wasm32-unknown-unknown/wasm-release/ferris_wasm.wasm dist/ferris_wasm.wasm',
261
+ ],
262
+ });
263
+ expect(targets['cargo-wasm']?.configurations?.development).toEqual({
264
+ commands: [
265
+ 'cargo build --target wasm32-unknown-unknown -p ferris-wasm && mkdir -p dist && cp target/wasm32-unknown-unknown/debug/ferris_wasm.wasm dist/ferris_wasm.wasm',
266
+ ],
267
+ });
268
+ // cargo-wasm matches the *-wasm build-output pattern → aggregate build/clean exist
269
+ expect(targets.build?.executor).toBe('nx:noop');
270
+ } finally {
271
+ await workspace.cleanup();
272
+ }
273
+ });
274
+
275
+ it('does not infer wasm targets for native N-API cdylib crates', async () => {
276
+ const workspace = await createWorkspace();
277
+ try {
278
+ await workspace.write('packages/cowshed/package.json', '{"name":"cowshed"}\n');
279
+ await workspace.write('packages/cowshed/Cargo.toml', '[workspace]\nmembers = ["crates/cowshed-napi"]\n');
280
+ await workspace.write(
281
+ 'packages/cowshed/crates/cowshed-napi/Cargo.toml',
282
+ '[package]\nname = "cowshed-napi"\n\n[lib]\ncrate-type = ["cdylib"]\n',
283
+ );
284
+
285
+ const targets = await inferProjectTargets(workspace, 'packages/cowshed/package.json');
286
+
287
+ expect(targets['cargo-wasm']).toBeUndefined();
288
+ expect(targets.build).toBeUndefined();
289
+ expect(targets.clean).toBeUndefined();
290
+ expect(targets['cargo-test']).toBeDefined();
291
+ } finally {
292
+ await workspace.cleanup();
293
+ }
294
+ });
295
+
296
+ it('lets explicit nx.targets override wasm inference and skips non-workspace Cargo.toml', async () => {
297
+ const workspace = await createWorkspace();
298
+ try {
299
+ await workspace.write(
300
+ 'packages/custom/package.json',
301
+ '{"name":"custom","nx":{"targets":{"cargo-wasm":{"options":{"command":"custom"}},"test":{}}}}\n',
302
+ );
303
+ await workspace.write('packages/custom/Cargo.toml', '[workspace]\nmembers = ["crates/x-wasm"]\n');
304
+ await workspace.write(
305
+ 'packages/custom/crates/x-wasm/Cargo.toml',
306
+ '[package]\nname = "x-wasm"\n\n[lib]\ncrate-type = ["cdylib"]\n',
307
+ );
308
+
309
+ const targets = await inferProjectTargets(workspace, 'packages/custom/package.json');
310
+ expect(targets['cargo-wasm']).toBeUndefined();
311
+ expect(targets.test).toBeUndefined();
312
+ expect(targets['cargo-test']).toBeDefined();
313
+
314
+ // A member crate's own Cargo.toml (no [workspace]) infers nothing.
315
+ await workspace.write('packages/member/package.json', '{"name":"member"}\n');
316
+ await workspace.write('packages/member/Cargo.toml', '[package]\nname = "member"\n');
317
+ const memberTargets = await inferProjectTargets(workspace, 'packages/member/package.json');
318
+ expect(memberTargets).toEqual({});
319
+ } finally {
320
+ await workspace.cleanup();
321
+ }
322
+ });
323
+
155
324
  it('leaves build.zig without b.step declarations to smoo validation', async () => {
156
325
  const workspace = await createWorkspace();
157
326
  try {
@@ -192,12 +361,14 @@ interface WorkspaceFixture {
192
361
  cleanup(): Promise<void>;
193
362
  }
194
363
 
364
+ async function inferProject(workspace: WorkspaceFixture, packageJsonPath: string) {
365
+ const result = await inferTargets([packageJsonPath], undefined, workspace.context);
366
+ return result[0]?.[1].projects?.[dirname(packageJsonPath)];
367
+ }
368
+
195
369
  async function inferProjectTargets(
196
370
  workspace: WorkspaceFixture,
197
371
  packageJsonPath: string,
198
372
  ): Promise<Record<string, TargetConfiguration>> {
199
- const result = await inferTargets([packageJsonPath], undefined, workspace.context);
200
- const projectRoot = dirname(packageJsonPath);
201
-
202
- return result[0]?.[1].projects?.[projectRoot]?.targets ?? {};
373
+ return (await inferProject(workspace, packageJsonPath))?.targets ?? {};
203
374
  }