@smoothbricks/nx-plugin 0.0.0-bootstrap.0 → 0.2.0

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.
Files changed (78) hide show
  1. package/README.md +93 -2
  2. package/dist/bounded-test-policy.d.ts +32 -0
  3. package/dist/bounded-test-policy.d.ts.map +1 -0
  4. package/dist/bounded-test-policy.js +184 -0
  5. package/dist/executors/bounded-exec/executor.d.ts +15 -0
  6. package/dist/executors/bounded-exec/executor.d.ts.map +1 -0
  7. package/dist/executors/bounded-exec/executor.js +179 -0
  8. package/dist/executors/bounded-exec/schema.d.ts +11 -0
  9. package/dist/executors/bounded-exec/schema.d.ts.map +1 -0
  10. package/dist/executors/bounded-exec/schema.js +1 -0
  11. package/dist/generators/bounded-test-targets/generator.d.ts +7 -0
  12. package/dist/generators/bounded-test-targets/generator.d.ts.map +1 -0
  13. package/dist/generators/bounded-test-targets/generator.js +40 -0
  14. package/dist/generators/bun-test-tracing/generator.d.ts +10 -0
  15. package/dist/generators/bun-test-tracing/generator.d.ts.map +1 -0
  16. package/dist/generators/bun-test-tracing/generator.js +247 -0
  17. package/dist/generators/create-package/generator.d.ts +4 -0
  18. package/dist/generators/create-package/generator.d.ts.map +1 -0
  19. package/dist/generators/create-package/generator.js +204 -0
  20. package/dist/generators/make-public/generator.d.ts +4 -0
  21. package/dist/generators/make-public/generator.d.ts.map +1 -0
  22. package/dist/generators/make-public/generator.js +55 -0
  23. package/dist/index.d.ts +7 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +197 -0
  26. package/dist/package-target-policy.d.ts +31 -0
  27. package/dist/package-target-policy.d.ts.map +1 -0
  28. package/dist/package-target-policy.js +930 -0
  29. package/dist/release-config-policy.d.ts +32 -0
  30. package/dist/release-config-policy.d.ts.map +1 -0
  31. package/dist/release-config-policy.js +225 -0
  32. package/dist/typecheck-test-policy.d.ts +56 -0
  33. package/dist/typecheck-test-policy.d.ts.map +1 -0
  34. package/dist/typecheck-test-policy.js +640 -0
  35. package/dist/version-actions.cjs +78 -0
  36. package/dist/version-actions.d.cts +6 -0
  37. package/dist/version-actions.d.cts.map +1 -0
  38. package/dist/workspace-config-policy.d.ts +33 -0
  39. package/dist/workspace-config-policy.d.ts.map +1 -0
  40. package/dist/workspace-config-policy.js +334 -0
  41. package/executors.json +9 -0
  42. package/generators.json +24 -0
  43. package/loader.js +16 -0
  44. package/package.json +89 -4
  45. package/src/bounded-test-policy.test.ts +257 -0
  46. package/src/bounded-test-policy.ts +257 -0
  47. package/src/bun-bootstrap.test.ts +52 -0
  48. package/src/executors/bounded-exec/executor.test.ts +258 -0
  49. package/src/executors/bounded-exec/executor.ts +228 -0
  50. package/src/executors/bounded-exec/schema.json +68 -0
  51. package/src/executors/bounded-exec/schema.ts +10 -0
  52. package/src/generators/bounded-test-targets/generator.test.ts +136 -0
  53. package/src/generators/bounded-test-targets/generator.ts +67 -0
  54. package/src/generators/bounded-test-targets/schema.d.ts +3 -0
  55. package/src/generators/bounded-test-targets/schema.json +14 -0
  56. package/src/generators/bun-test-tracing/generator.test.ts +243 -0
  57. package/src/generators/bun-test-tracing/generator.ts +348 -0
  58. package/src/generators/bun-test-tracing/schema.d.ts +8 -0
  59. package/src/generators/bun-test-tracing/schema.json +28 -0
  60. package/src/generators/create-package/generator.test.ts +206 -0
  61. package/src/generators/create-package/generator.ts +251 -0
  62. package/src/generators/create-package/schema.d.ts +5 -0
  63. package/src/generators/create-package/schema.json +24 -0
  64. package/src/generators/make-public/generator.test.ts +137 -0
  65. package/src/generators/make-public/generator.ts +83 -0
  66. package/src/generators/make-public/schema.d.ts +3 -0
  67. package/src/generators/make-public/schema.json +13 -0
  68. package/src/index.test.ts +200 -0
  69. package/src/index.ts +242 -0
  70. package/src/package-target-policy.test.ts +778 -0
  71. package/src/package-target-policy.ts +1127 -0
  72. package/src/release-config-policy.test.ts +280 -0
  73. package/src/release-config-policy.ts +258 -0
  74. package/src/typecheck-test-policy.test.ts +797 -0
  75. package/src/typecheck-test-policy.ts +752 -0
  76. package/src/version-actions.cts +94 -0
  77. package/src/workspace-config-policy.test.ts +376 -0
  78. package/src/workspace-config-policy.ts +390 -0
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # @smoothbricks/nx-plugin
1
+ # Nx Plugin
2
2
 
3
- This is a bootstrap placeholder. Real package versions are published by SmoothBricks release automation.
3
+ Local Nx plugin for workspace-standard package setup and missing inferred targets.
4
+
5
+ ## Target Ownership
6
+
7
+ Official `@nx/js/typescript` owns TypeScript library inference. A package `tsconfig.lib.json` becomes the tool-output
8
+ target `tsc-js`; this plugin must not duplicate or rename that target.
9
+
10
+ `@smoothbricks/nx-plugin` owns only inferred targets Nx does not provide here:
11
+
12
+ - `typecheck-tests` and `typecheck-tests:watch` from `tsconfig.test.json`
13
+ - `test:watch` from explicit `test` commands for Bun and Vitest packages
14
+ - `zig-*` targets from `build.zig` steps such as `zig-wasm`
15
+ - aggregate `build` and `lint` targets
16
+
17
+ ## Nx Target Naming
18
+
19
+ Target names are `{tool}-{output}` names. Use names like `tsc-js`, `tsdown-js`, and `zig-wasm`; `build` and `lint` are
20
+ aggregates.
21
+
22
+ Concrete targets come from concrete files:
23
+
24
+ - `typecheck-tests` is inferred from `tsconfig.test.json` and runs `tsc --noEmit -p tsconfig.test.json`.
25
+ - `typecheck-tests:watch` is inferred from `tsconfig.test.json` and runs the same typecheck in watch mode.
26
+ - `test:watch` is inferred when the package already defines an explicit Bun or Vitest `test` command. The plugin derives
27
+ the corresponding watch command and makes it depend on `typecheck-tests`.
28
+ - `zig-*` is inferred from `build.zig`; each explicit `b.step("name", ...)` becomes `zig-name`.
29
+ - `build` is inferred only when the project has at least one concrete build target to run, such as `tsc-js` from the
30
+ official TypeScript plugin, a package-local target like `tsdown-js`, or a `zig-*` target from this plugin. It depends
31
+ on output-family wildcard targets: `*-js`, `*-web`, `*-html`, `*-css`, `*-ios`, `*-android`, `*-native`, `*-napi`,
32
+ `*-bun`, and `*-wasm`.
33
+
34
+ This is why Zig appears in the convention: the plugin is not guessing from arbitrary Zig source. SmoothBricks requires
35
+ `build.zig` to expose named build steps so Nx can create cacheable, addressable targets from those steps.
36
+
37
+ Do not use colon-style Nx target names such as `build:wasm` or `lint:fix`. Nx CLI syntax already uses colons for
38
+ `project:target:configuration`, so colon target names are hard to read, easy to confuse with configurations, and awkward
39
+ to expose through package scripts. Package scripts may still use names like `build:wasm`; they should delegate to a real
40
+ target such as `nx run pkg:zig-wasm`.
41
+
42
+ There is no Nx `lint:fix` target; repository formatting is handled by the root `lint:fix` script.
43
+
44
+ `typecheck-tests` and `typecheck-tests:watch` are inferred only when `tsconfig.test.json` exists. Test typechecking must
45
+ not emit `dist-test`. `test:watch` is continuous and depends on `typecheck-tests` before entering Bun or Vitest watch
46
+ mode. Smoo validation creates/requires this config for test runners that do not typecheck test files by default.
47
+
48
+ `tsconfig.test.json` is not a TypeScript build-mode project. It should reference library tsconfigs it needs to typecheck
49
+ against, but the package root `tsconfig.json` should not reference `./tsconfig.test.json`. Nx runs test typechecking
50
+ through the inferred `typecheck-tests` target, not through `tsc --build`.
51
+
52
+ Zig targets are inferred only when `build.zig` declares at least one `b.step(...)`. Each step becomes a `zig-*` target,
53
+ so a package `build.zig` must have at least one step.
54
+
55
+ ## Bun Test Tracing Generator
56
+
57
+ Configure a package for the Bun test tracing + no-emit test typechecking pattern used in this repo.
58
+
59
+ ```bash
60
+ nx generate ./packages/nx-plugin:bun-test-tracing \
61
+ --project @smoothbricks/my-package \
62
+ --opContextModule @smoothbricks/lmao \
63
+ --opContextExport lmaoOpContext \
64
+ --tracerModule @smoothbricks/lmao/testing/bun
65
+ ```
66
+
67
+ What it wires:
68
+
69
+ - `bunfig.toml` preloads for the LMAO Bun test tracing setup
70
+ - `src/test-suite-tracer.ts`
71
+ - `tsconfig.test.json` with `noEmit` for inferred `typecheck-tests`
72
+ - direct test config references to library tsconfigs; package root `tsconfig.json` is left out of the test config graph
73
+ - package `package.json` test/lint/devDependency wiring needed for the standard pattern
74
+
75
+ ## Bounded Test Targets
76
+
77
+ `@smoothbricks/nx-plugin:bounded-exec` runs a shell command with a timeout and force-kill grace period. Test targets use
78
+ this executor so hung test processes fail predictably instead of blocking Nx indefinitely.
79
+
80
+ The shared policy API is exported from `@smoothbricks/nx-plugin/bounded-test-policy` for generators or other workspace
81
+ tools that need to normalize package JSON consistently.
82
+
83
+ ```bash
84
+ nx generate ./packages/nx-plugin:bounded-test-targets --project @smoothbricks/my-package
85
+ ```
86
+
87
+ The generator rewrites `package.json` so `nx.targets.test` uses:
88
+
89
+ - executor `@smoothbricks/nx-plugin:bounded-exec`
90
+ - command preserved from an existing `nx:run-commands` test target or direct `scripts.test`
91
+ - `cwd: "{projectRoot}"`
92
+ - `timeoutMs: 600000`
93
+ - `killAfterMs: 10000`
94
+ - package script alias `nx run <project>:test --tui=false --outputStyle=stream`
@@ -0,0 +1,32 @@
1
+ export declare const BOUNDED_TEST_EXECUTOR = "@smoothbricks/nx-plugin:bounded-exec";
2
+ export declare const BOUNDED_TEST_TIMEOUT_MS = 120000;
3
+ export declare const BOUNDED_TEST_KILL_AFTER_MS = 10000;
4
+ export interface BoundedTestPolicyPackageJson {
5
+ name?: string;
6
+ workspaces?: unknown;
7
+ scripts?: Record<string, unknown>;
8
+ nx?: {
9
+ name?: string;
10
+ targets?: Record<string, Record<string, unknown>>;
11
+ };
12
+ }
13
+ export interface BoundedTestPolicyProjectJson {
14
+ name?: string;
15
+ targets?: Record<string, Record<string, unknown>>;
16
+ }
17
+ export interface BoundedTestPolicyIssue {
18
+ path: string;
19
+ message: string;
20
+ }
21
+ export interface ApplyBoundedTestTargetPolicyOptions {
22
+ projectName: string;
23
+ defaultCommand?: string;
24
+ projectJson?: BoundedTestPolicyProjectJson;
25
+ }
26
+ export declare function applyBoundedTestTargetPolicy(packageJson: BoundedTestPolicyPackageJson, options: ApplyBoundedTestTargetPolicyOptions): void;
27
+ export declare function applyWorkspaceBoundedTestTargetPolicy(root: string): boolean;
28
+ export declare function checkWorkspaceBoundedTestTargetPolicy(root: string): BoundedTestPolicyIssue[];
29
+ export declare function checkBoundedTestTargetPolicy(packageJson: BoundedTestPolicyPackageJson, options: ApplyBoundedTestTargetPolicyOptions): boolean;
30
+ export declare function boundedTestScriptAlias(projectName: string): string;
31
+ export declare function resolveTestCommand(packageJson: BoundedTestPolicyPackageJson, defaultCommand?: string, projectJson?: BoundedTestPolicyProjectJson): string;
32
+ //# sourceMappingURL=bounded-test-policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bounded-test-policy.d.ts","sourceRoot":"","sources":["../src/bounded-test-policy.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,qBAAqB,yCAAyC,CAAC;AAC5E,eAAO,MAAM,uBAAuB,SAAU,CAAC;AAC/C,eAAO,MAAM,0BAA0B,QAAS,CAAC;AAEjD,MAAM,WAAW,4BAA4B;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,EAAE,CAAC,EAAE;QACH,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;KACnD,CAAC;CACH;AAED,MAAM,WAAW,4BAA4B;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACnD;AAED,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mCAAmC;IAClD,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,4BAA4B,CAAC;CAC5C;AAED,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,4BAA4B,EACzC,OAAO,EAAE,mCAAmC,GAC3C,IAAI,CAmBN;AAED,wBAAgB,qCAAqC,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CA0B3E;AAED,wBAAgB,qCAAqC,CAAC,IAAI,EAAE,MAAM,GAAG,sBAAsB,EAAE,CAyB5F;AAED,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,4BAA4B,EACzC,OAAO,EAAE,mCAAmC,GAC3C,OAAO,CAkBT;AAED,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,4BAA4B,EACzC,cAAc,SAAa,EAC3B,WAAW,CAAC,EAAE,4BAA4B,GACzC,MAAM,CAiBR"}
@@ -0,0 +1,184 @@
1
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ export const BOUNDED_TEST_EXECUTOR = '@smoothbricks/nx-plugin:bounded-exec';
4
+ export const BOUNDED_TEST_TIMEOUT_MS = 120_000;
5
+ export const BOUNDED_TEST_KILL_AFTER_MS = 10_000;
6
+ export function applyBoundedTestTargetPolicy(packageJson, options) {
7
+ const command = resolveTestCommand(packageJson, options.defaultCommand ?? 'bun test', options.projectJson);
8
+ const targetOwner = options.projectJson ?? (packageJson.nx ??= {});
9
+ targetOwner.targets ??= {};
10
+ const existingTestTarget = targetOwner.targets.test;
11
+ const nextTestTarget = isRecord(existingTestTarget) ? { ...existingTestTarget } : {};
12
+ nextTestTarget.executor = BOUNDED_TEST_EXECUTOR;
13
+ nextTestTarget.options = {
14
+ command,
15
+ cwd: '{projectRoot}',
16
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
17
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
18
+ };
19
+ targetOwner.targets.test = nextTestTarget;
20
+ packageJson.scripts ??= {};
21
+ packageJson.scripts.test = boundedTestScriptAlias(options.projectName);
22
+ }
23
+ export function applyWorkspaceBoundedTestTargetPolicy(root) {
24
+ let changed = false;
25
+ for (const packageJsonPath of listWorkspacePackageJsonPaths(root)) {
26
+ const packageJson = readPackageJson(packageJsonPath);
27
+ const projectJsonPath = projectJsonPathForPackageJson(packageJsonPath);
28
+ const projectJson = existsSync(projectJsonPath) ? readProjectJson(projectJsonPath) : undefined;
29
+ if (!hasTestEntrypoint(packageJson, projectJson)) {
30
+ continue;
31
+ }
32
+ const projectName = packageProjectName(packageJson, projectJson);
33
+ if (!projectName) {
34
+ continue;
35
+ }
36
+ const beforePackageJson = JSON.stringify(packageJson);
37
+ const beforeProjectJson = JSON.stringify(projectJson);
38
+ applyBoundedTestTargetPolicy(packageJson, { projectName, projectJson });
39
+ if (JSON.stringify(packageJson) === beforePackageJson && JSON.stringify(projectJson) === beforeProjectJson) {
40
+ continue;
41
+ }
42
+ writePackageJson(packageJsonPath, packageJson);
43
+ if (projectJson) {
44
+ writeProjectJson(projectJsonPath, projectJson);
45
+ }
46
+ changed = true;
47
+ }
48
+ return changed;
49
+ }
50
+ export function checkWorkspaceBoundedTestTargetPolicy(root) {
51
+ const issues = [];
52
+ for (const packageJsonPath of listWorkspacePackageJsonPaths(root)) {
53
+ const packageJson = readPackageJson(packageJsonPath);
54
+ const projectJsonPath = projectJsonPathForPackageJson(packageJsonPath);
55
+ const projectJson = existsSync(projectJsonPath) ? readProjectJson(projectJsonPath) : undefined;
56
+ if (!hasTestEntrypoint(packageJson, projectJson)) {
57
+ continue;
58
+ }
59
+ const projectName = packageProjectName(packageJson, projectJson);
60
+ if (!projectName) {
61
+ issues.push({
62
+ path: packageJsonPath,
63
+ message: 'test entrypoint requires package.json name, nx.name, or project.json name',
64
+ });
65
+ continue;
66
+ }
67
+ if (!checkBoundedTestTargetPolicy(packageJson, { projectName, projectJson })) {
68
+ issues.push({
69
+ path: projectJson ? projectJsonPath : packageJsonPath,
70
+ message: `${projectJson ? 'targets' : 'nx.targets'}.test must use ${BOUNDED_TEST_EXECUTOR} with bounded test policy`,
71
+ });
72
+ }
73
+ }
74
+ return issues;
75
+ }
76
+ export function checkBoundedTestTargetPolicy(packageJson, options) {
77
+ const testTarget = options.projectJson ? options.projectJson.targets?.test : packageJson.nx?.targets?.test;
78
+ if (!isRecord(testTarget) || testTarget.executor !== BOUNDED_TEST_EXECUTOR) {
79
+ return false;
80
+ }
81
+ const targetOptions = testTarget.options;
82
+ if (!isRecord(targetOptions) ||
83
+ typeof targetOptions.command !== 'string' ||
84
+ targetOptions.command.length === 0 ||
85
+ isPackageTestScriptRunnerCommand(targetOptions.command) ||
86
+ targetOptions.cwd !== '{projectRoot}' ||
87
+ targetOptions.timeoutMs !== BOUNDED_TEST_TIMEOUT_MS ||
88
+ targetOptions.killAfterMs !== BOUNDED_TEST_KILL_AFTER_MS) {
89
+ return false;
90
+ }
91
+ return packageJson.scripts?.test === boundedTestScriptAlias(options.projectName);
92
+ }
93
+ export function boundedTestScriptAlias(projectName) {
94
+ return `nx run ${projectName}:test --tui=false --outputStyle=stream`;
95
+ }
96
+ export function resolveTestCommand(packageJson, defaultCommand = 'bun test', projectJson) {
97
+ const commandFromProjectTarget = resolveTargetCommand(projectJson?.targets?.test);
98
+ if (commandFromProjectTarget) {
99
+ return commandFromProjectTarget;
100
+ }
101
+ const commandFromPackageTarget = resolveTargetCommand(packageJson.nx?.targets?.test);
102
+ if (commandFromPackageTarget) {
103
+ return commandFromPackageTarget;
104
+ }
105
+ const scriptCommand = packageJson.scripts?.test;
106
+ if (typeof scriptCommand === 'string' && !isNxRunTestAlias(scriptCommand)) {
107
+ return scriptCommand;
108
+ }
109
+ return defaultCommand;
110
+ }
111
+ function resolveTargetCommand(existingTarget) {
112
+ if (isRecord(existingTarget)) {
113
+ const targetOptions = existingTarget.options;
114
+ if (isRecord(targetOptions) &&
115
+ typeof targetOptions.command === 'string' &&
116
+ targetOptions.command.length > 0 &&
117
+ !isPackageTestScriptRunnerCommand(targetOptions.command)) {
118
+ return targetOptions.command;
119
+ }
120
+ }
121
+ return null;
122
+ }
123
+ function isPackageTestScriptRunnerCommand(command) {
124
+ return /^(?:bun\s+run|npm(?:\s+run)?|pnpm(?:\s+run)?|yarn(?:\s+run)?)\s+test(?:\s|$)/.test(command.trim());
125
+ }
126
+ function isNxRunTestAlias(command) {
127
+ return /^nx\s+run\s+[^\s:]+:test(?:\s|$)/.test(command.trim());
128
+ }
129
+ function listWorkspacePackageJsonPaths(root) {
130
+ const rootPackagePath = join(root, 'package.json');
131
+ if (!existsSync(rootPackagePath)) {
132
+ return [];
133
+ }
134
+ const rootPackage = readPackageJson(rootPackagePath);
135
+ const workspacePatterns = Array.isArray(rootPackage.workspaces)
136
+ ? rootPackage.workspaces.filter((entry) => typeof entry === 'string')
137
+ : [];
138
+ const paths = [];
139
+ for (const pattern of workspacePatterns) {
140
+ if (!pattern.endsWith('/*')) {
141
+ continue;
142
+ }
143
+ const parent = join(root, pattern.slice(0, -2));
144
+ if (!existsSync(parent)) {
145
+ continue;
146
+ }
147
+ for (const entry of readdirSync(parent, { withFileTypes: true })) {
148
+ if (!entry.isDirectory()) {
149
+ continue;
150
+ }
151
+ const packageJsonPath = join(parent, entry.name, 'package.json');
152
+ if (existsSync(packageJsonPath)) {
153
+ paths.push(packageJsonPath);
154
+ }
155
+ }
156
+ }
157
+ return paths.sort((a, b) => a.localeCompare(b));
158
+ }
159
+ function readPackageJson(path) {
160
+ return JSON.parse(readFileSync(path, 'utf8'));
161
+ }
162
+ function writePackageJson(path, packageJson) {
163
+ writeFileSync(path, `${JSON.stringify(packageJson, null, 2)}\n`);
164
+ }
165
+ function readProjectJson(path) {
166
+ return JSON.parse(readFileSync(path, 'utf8'));
167
+ }
168
+ function writeProjectJson(path, projectJson) {
169
+ writeFileSync(path, `${JSON.stringify(projectJson, null, 2)}\n`);
170
+ }
171
+ function hasTestEntrypoint(packageJson, projectJson) {
172
+ return (typeof packageJson.scripts?.test === 'string' ||
173
+ isRecord(projectJson?.targets?.test) ||
174
+ isRecord(packageJson.nx?.targets?.test));
175
+ }
176
+ function packageProjectName(packageJson, projectJson) {
177
+ return projectJson?.name ?? packageJson.nx?.name ?? packageJson.name ?? null;
178
+ }
179
+ function projectJsonPathForPackageJson(packageJsonPath) {
180
+ return join(dirname(packageJsonPath), 'project.json');
181
+ }
182
+ function isRecord(value) {
183
+ return value !== null && typeof value === 'object';
184
+ }
@@ -0,0 +1,15 @@
1
+ import type { BoundedExecOptions } from './schema.js';
2
+ export interface BoundedExecContext {
3
+ root: string;
4
+ }
5
+ export interface BoundedExecResult {
6
+ success: boolean;
7
+ terminalOutput: string;
8
+ }
9
+ export interface ProcessTreeKiller {
10
+ kill(pid: number, signal: NodeJS.Signals): Promise<void>;
11
+ }
12
+ export default function boundedExecExecutor(options: BoundedExecOptions, context: BoundedExecContext): Promise<BoundedExecResult>;
13
+ export declare function runBoundedExec(options: BoundedExecOptions, context: BoundedExecContext, killer: ProcessTreeKiller): Promise<BoundedExecResult>;
14
+ export declare function createProcessTreeKiller(): ProcessTreeKiller;
15
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/bounded-exec/executor.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAStD,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;CACxB;AAQD,MAAM,WAAW,iBAAiB;IAChC,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1D;AAED,MAAM,CAAC,OAAO,UAAU,mBAAmB,CACzC,OAAO,EAAE,kBAAkB,EAC3B,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC,iBAAiB,CAAC,CAE5B;AAED,wBAAsB,cAAc,CAClC,OAAO,EAAE,kBAAkB,EAC3B,OAAO,EAAE,kBAAkB,EAC3B,MAAM,EAAE,iBAAiB,GACxB,OAAO,CAAC,iBAAiB,CAAC,CAsH5B;AAED,wBAAgB,uBAAuB,IAAI,iBAAiB,CAM3D"}
@@ -0,0 +1,179 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { isAbsolute, join } from 'node:path';
3
+ const DEFAULT_KILL_AFTER_MS = 10_000;
4
+ const EXIT_CODE_BY_SIGNAL = {
5
+ SIGHUP: 129,
6
+ SIGINT: 130,
7
+ SIGTERM: 143,
8
+ };
9
+ export default function boundedExecExecutor(options, context) {
10
+ return runBoundedExec(options, context, createProcessTreeKiller());
11
+ }
12
+ export async function runBoundedExec(options, context, killer) {
13
+ const cwd = resolveCwd(options.cwd, context.root);
14
+ const command = buildCommand(options);
15
+ const timeoutMs = options.timeoutMs;
16
+ const killAfterMs = options.killAfterMs ?? DEFAULT_KILL_AFTER_MS;
17
+ const startedAt = Date.now();
18
+ const outputChunks = [];
19
+ const state = { settled: false, timedOut: false, forceKillNeeded: false };
20
+ const child = spawn(command, [], {
21
+ cwd,
22
+ env: mergeEnv(options.env),
23
+ shell: true,
24
+ detached: process.platform !== 'win32',
25
+ windowsHide: true,
26
+ });
27
+ const appendStdout = (chunk) => {
28
+ const text = chunk.toString();
29
+ outputChunks.push(text);
30
+ process.stdout.write(text);
31
+ };
32
+ const appendStderr = (chunk) => {
33
+ const text = chunk.toString();
34
+ outputChunks.push(text);
35
+ process.stderr.write(text);
36
+ };
37
+ child.stdout?.on('data', appendStdout);
38
+ child.stderr?.on('data', appendStderr);
39
+ const killChildTree = async (force) => {
40
+ const pid = child.pid;
41
+ if (!pid) {
42
+ return;
43
+ }
44
+ await killer.kill(pid, force ? 'SIGKILL' : 'SIGTERM');
45
+ };
46
+ const onProcessExit = () => {
47
+ void killChildTree(false);
48
+ };
49
+ const onTerminationSignal = (signal) => {
50
+ removeSignalHandlers();
51
+ void killChildTree(false).finally(() => process.kill(process.pid, signal));
52
+ };
53
+ const onSigint = () => onTerminationSignal('SIGINT');
54
+ const onSigterm = () => onTerminationSignal('SIGTERM');
55
+ const onSighup = () => onTerminationSignal('SIGHUP');
56
+ const removeSignalHandlers = () => {
57
+ process.removeListener('exit', onProcessExit);
58
+ process.removeListener('SIGINT', onSigint);
59
+ process.removeListener('SIGTERM', onSigterm);
60
+ process.removeListener('SIGHUP', onSighup);
61
+ };
62
+ process.on('exit', onProcessExit);
63
+ process.on('SIGINT', onSigint);
64
+ process.on('SIGTERM', onSigterm);
65
+ process.on('SIGHUP', onSighup);
66
+ let timeout;
67
+ const timeoutPromise = new Promise((resolve) => {
68
+ timeout = setTimeout(() => {
69
+ state.timedOut = true;
70
+ const elapsedMs = Date.now() - startedAt;
71
+ appendStderr(`\nCommand timed out after ${elapsedMs}ms (timeoutMs=${timeoutMs}, cwd=${cwd}): ${command}\n`);
72
+ void (async () => {
73
+ await ignoreKillError(killChildTree(false));
74
+ if (!state.settled && killAfterMs > 0) {
75
+ await delay(killAfterMs);
76
+ }
77
+ if (!state.settled) {
78
+ state.forceKillNeeded = true;
79
+ appendStderr(`Force-killing timed out command after killAfterMs=${killAfterMs}: ${command}\n`);
80
+ await ignoreKillError(killChildTree(true));
81
+ }
82
+ resolve();
83
+ })();
84
+ }, timeoutMs);
85
+ });
86
+ const exitPromise = new Promise((resolve) => {
87
+ child.once('error', (error) => {
88
+ appendStderr(`${error.message}\n`);
89
+ resolve({ code: 1, signal: null });
90
+ });
91
+ child.once('exit', (code, signal) => {
92
+ resolve({ code, signal });
93
+ });
94
+ });
95
+ const exit = await exitPromise;
96
+ const exitedGracefullyAfterTimeout = state.timedOut && exit.code === 0 && exit.signal === null;
97
+ state.settled = !state.timedOut || exitedGracefullyAfterTimeout;
98
+ if (timeout) {
99
+ clearTimeout(timeout);
100
+ }
101
+ removeSignalHandlers();
102
+ if (state.timedOut) {
103
+ await timeoutPromise;
104
+ state.settled = true;
105
+ }
106
+ const code = exit.code ?? signalToExitCode(exit.signal);
107
+ if (code !== 0 && !state.timedOut) {
108
+ appendStderr(`Command exited with status ${code}: ${command}\n`);
109
+ }
110
+ if (state.timedOut && !state.forceKillNeeded) {
111
+ appendStderr(`Timed out command exited after graceful termination: ${command}\n`);
112
+ }
113
+ return {
114
+ success: !state.timedOut && code === 0,
115
+ terminalOutput: outputChunks.join(''),
116
+ };
117
+ }
118
+ export function createProcessTreeKiller() {
119
+ return {
120
+ kill(pid, signal) {
121
+ return killProcessGroup(pid, signal);
122
+ },
123
+ };
124
+ }
125
+ function killProcessGroup(pid, signal) {
126
+ return new Promise((resolve) => {
127
+ try {
128
+ // Send signal to the entire process group (negative PID).
129
+ // The executor spawns with detached: true on POSIX, which creates a
130
+ // dedicated process group. Signaling -pid is atomic and catches all
131
+ // descendants, including grandchildren that tree-walk libraries miss
132
+ // when parents die and children get reparented to init.
133
+ process.kill(-pid, signal);
134
+ }
135
+ catch {
136
+ // ESRCH: process group already exited between timeout and kill.
137
+ }
138
+ resolve();
139
+ });
140
+ }
141
+ function resolveCwd(cwd, root) {
142
+ if (!cwd) {
143
+ return root;
144
+ }
145
+ return isAbsolute(cwd) ? cwd : join(root, cwd);
146
+ }
147
+ function buildCommand(options) {
148
+ const parts = [options.command];
149
+ if (Array.isArray(options.args)) {
150
+ parts.push(...options.args);
151
+ }
152
+ else if (options.args) {
153
+ parts.push(options.args);
154
+ }
155
+ if (options.forwardAllArgs !== false && options.__unparsed__?.length) {
156
+ parts.push(...options.__unparsed__);
157
+ }
158
+ return parts.join(' ');
159
+ }
160
+ function mergeEnv(env) {
161
+ return env ? { ...process.env, ...env } : process.env;
162
+ }
163
+ function signalToExitCode(signal) {
164
+ if (!signal) {
165
+ return 1;
166
+ }
167
+ return EXIT_CODE_BY_SIGNAL[signal] ?? 1;
168
+ }
169
+ async function ignoreKillError(promise) {
170
+ try {
171
+ await promise;
172
+ }
173
+ catch {
174
+ // The process tree may have already exited between timeout and kill.
175
+ }
176
+ }
177
+ function delay(ms) {
178
+ return new Promise((resolve) => setTimeout(resolve, ms));
179
+ }
@@ -0,0 +1,11 @@
1
+ export interface BoundedExecOptions {
2
+ command: string;
3
+ cwd?: string;
4
+ env?: Record<string, string>;
5
+ timeoutMs: number;
6
+ killAfterMs?: number;
7
+ forwardAllArgs?: boolean;
8
+ args?: string | string[];
9
+ __unparsed__?: string[];
10
+ }
11
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/executors/bounded-exec/schema.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ import { type Tree } from 'nx/src/devkit-exports.js';
2
+ interface BoundedTestTargetsGeneratorSchema {
3
+ project: string;
4
+ }
5
+ export default function generator(tree: Tree, schema: BoundedTestTargetsGeneratorSchema): Promise<void>;
6
+ export {};
7
+ //# sourceMappingURL=generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/bounded-test-targets/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,IAAI,EAEV,MAAM,0BAA0B,CAAC;AAQlC,UAAU,iCAAiC;IACzC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,wBAA8B,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,iCAAiC,GAAG,OAAO,CAAC,IAAI,CAAC,CAqB5G"}
@@ -0,0 +1,40 @@
1
+ import { getProjects, joinPathFragments, normalizePath, readJson, updateJson, } from 'nx/src/devkit-exports.js';
2
+ import { applyBoundedTestTargetPolicy, } from '../../bounded-test-policy.js';
3
+ export default async function generator(tree, schema) {
4
+ const resolved = resolveProject(tree, schema.project);
5
+ const packageJsonPath = joinPathFragments(resolved.root, 'package.json');
6
+ const projectJsonPath = joinPathFragments(resolved.root, 'project.json');
7
+ if (!tree.exists(packageJsonPath)) {
8
+ throw new Error(`Project ${resolved.name} is missing ${packageJsonPath}`);
9
+ }
10
+ const projectJson = tree.exists(projectJsonPath)
11
+ ? readJson(tree, projectJsonPath)
12
+ : undefined;
13
+ updateJson(tree, packageJsonPath, (packageJson) => {
14
+ applyBoundedTestTargetPolicy(packageJson, { projectName: resolved.name, projectJson });
15
+ return packageJson;
16
+ });
17
+ if (projectJson) {
18
+ updateJson(tree, projectJsonPath, () => projectJson);
19
+ }
20
+ }
21
+ function resolveProject(tree, projectInput) {
22
+ const normalizedInput = normalizeLookupValue(projectInput);
23
+ for (const [name, config] of getProjects(tree)) {
24
+ if (normalizeLookupValue(name) === normalizedInput || normalizeLookupValue(config.root) === normalizedInput) {
25
+ return { name, root: config.root };
26
+ }
27
+ const packageJsonPath = joinPathFragments(config.root, 'package.json');
28
+ if (!tree.exists(packageJsonPath)) {
29
+ continue;
30
+ }
31
+ const packageJson = readJson(tree, packageJsonPath);
32
+ if (packageJson.name && normalizeLookupValue(packageJson.name) === normalizedInput) {
33
+ return { name, root: config.root };
34
+ }
35
+ }
36
+ throw new Error(`Could not resolve project ${projectInput}`);
37
+ }
38
+ function normalizeLookupValue(value) {
39
+ return normalizePath(value.replace(/^\.\//, ''));
40
+ }
@@ -0,0 +1,10 @@
1
+ import { type Tree } from 'nx/src/devkit-exports.js';
2
+ interface BunTestTracingGeneratorSchema {
3
+ project: string;
4
+ opContextModule: string;
5
+ opContextExport?: string;
6
+ tracerModule?: string;
7
+ }
8
+ export default function generator(tree: Tree, schema: BunTestTracingGeneratorSchema): Promise<void>;
9
+ export {};
10
+ //# sourceMappingURL=generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/bun-test-tracing/generator.ts"],"names":[],"mappings":"AACA,OAAO,EAML,KAAK,IAAI,EAEV,MAAM,0BAA0B,CAAC;AAIlC,UAAU,6BAA6B;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAiCD,wBAA8B,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC,CAuBxG"}