@smoothbricks/nx-plugin 0.4.17 → 0.4.18

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.
@@ -17,12 +17,25 @@
17
17
  lib,
18
18
  pkgs,
19
19
  ...
20
- }: {
20
+ }: let
21
+ # ttsc's native-plugin patch compiles microsoft/typescript-go with one
22
+ # corrected file. `go list -m` only fills `.Dir` after the module is already
23
+ # in GOMODCACHE, which CI does not restore (and GOPROXY is often off under
24
+ # nix). Pin the commit ttsc 0.30.4's patch requires so the tree is in the
25
+ # devenv closure and TTSC_TYPESCRIPT_GO_DIR names it.
26
+ typescriptGo = pkgs.fetchFromGitHub {
27
+ owner = "microsoft";
28
+ repo = "typescript-go";
29
+ rev = "56ab4af42157";
30
+ hash = "sha256-ebjX+1+9axEqsnZXCRZSumA38gPNdmoz98tMt2oftN4=";
31
+ };
32
+ in {
21
33
  env = lib.mkMerge [
22
34
  {
23
35
  # Nx otherwise defaults to three workers. Scale to the cores available in each
24
36
  # developer shell or CI runner; explicit --parallel flags still take precedence.
25
37
  NX_PARALLEL = "100%";
38
+ TTSC_TYPESCRIPT_GO_DIR = "${typescriptGo}";
26
39
  }
27
40
  # Playwright's downloaded Ubuntu browser has no runtime closure on NixOS
28
41
  # (CI reached the executable, then failed loading libglib-2.0.so.0). Use
@@ -2,7 +2,8 @@ name: Cache ttsc plugins
2
2
  description: >
3
3
  Restore/save compiled ttsc native plugin binaries (typia, etc.). These are content-keyed under TTSC_CACHE_DIR/plugins
4
4
  and skip the multi-minute `go build` when the cache key matches. The Go object cache (go-build/) is NOT cached — it is
5
- multi-GB and only helps when the plugin key misses.
5
+ multi-GB and only helps when the plugin key misses. Do not use restore-keys: a prefix hit restores plugins built for a
6
+ different lock/patch, then ttsc still compiles any missing plugin against a cold GOMODCACHE.
6
7
 
7
8
  runs:
8
9
  using: composite
@@ -14,6 +15,4 @@ runs:
14
15
  # workspace; devenv sets TTSC_CACHE_DIR to <repo>/.cache/ttsc.
15
16
  path: .cache/ttsc/plugins
16
17
  # prettier-ignore
17
- key: ${{ runner.os }}-${{ runner.arch }}-ttsc-plugins-v1-${{ hashFiles('bun.lock', 'package.json', 'patches/ttsc@*.patch', 'tooling/direnv/devenv.lock') }}
18
- restore-keys: |
19
- ${{ runner.os }}-${{ runner.arch }}-ttsc-plugins-v1-
18
+ key: ${{ runner.os }}-${{ runner.arch }}-ttsc-plugins-v1-${{ hashFiles('bun.lock', 'package.json', 'patches/ttsc@*.patch', 'tooling/direnv/devenv.lock', 'tooling/direnv/devenv.smoo.nix') }}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smoothbricks/nx-plugin",
3
- "version": "0.4.17",
3
+ "version": "0.4.18",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "main": "./loader.js",
@@ -189,15 +189,15 @@
189
189
  "dependencies": {
190
190
  "@nx/js": "latest",
191
191
  "nx": "latest",
192
- "prettier": "^3.6.1",
192
+ "prettier": "^3.9.8",
193
193
  "smol-toml": "^1.6.1",
194
194
  "tslib": "^2.8.1",
195
- "typia": "14.0.2",
195
+ "typia": "14.0.6",
196
196
  "yaml": "^2.9.0"
197
197
  },
198
198
  "devDependencies": {
199
- "@smoothbricks/lmao": "0.4.0",
200
- "@smoothbricks/validation": "0.1.9",
199
+ "@smoothbricks/lmao": "0.4.1",
200
+ "@smoothbricks/validation": "0.1.10",
201
201
  "fast-check": "^4.4.0"
202
202
  }
203
203
  }
@@ -123,6 +123,7 @@ describe('describeMiss', () => {
123
123
  describeMiss({ kind: 'not-cached', taskId: 'app:build' }),
124
124
  describeMiss({ kind: 'cached-failure', taskId: 'app:build', code: 7 }),
125
125
  describeMiss({ kind: 'stale-outputs', taskId: 'app:build' }),
126
+ describeMiss({ kind: 'stale-inputs', taskId: 'app:build' }),
126
127
  describeMiss({ kind: 'cache-disabled', taskId: 'app:build' }),
127
128
  describeMiss({ kind: 'no-daemon', taskId: 'app:build' }),
128
129
  ];
@@ -275,6 +276,9 @@ describe('smoo-nx-exec', () => {
275
276
  let workspace = '';
276
277
  const report = () => join(workspace, 'report');
277
278
  const marker = () => join(workspace, 'packages', 'app', 'dist', 'marker.txt');
279
+ // Outside the workspace: a log inside it would be an undeclared output the
280
+ // snapshot diff rightly reports as a changed input.
281
+ const builds = () => `${workspace}-lib-builds.log`;
278
282
 
279
283
  beforeAll(async () => {
280
284
  // Realpath because macOS puts the temp directory behind a /private
@@ -300,14 +304,20 @@ describe('smoo-nx-exec', () => {
300
304
  build: {
301
305
  executor: 'nx:run-commands',
302
306
  cache: true,
303
- inputs: ['{projectRoot}/source.txt'],
307
+ inputs: ['{projectRoot}/source*.txt'],
304
308
  outputs: ['{projectRoot}/dist'],
305
- options: { command: 'mkdir -p dist && cat source.txt > dist/lib.txt', cwd: '{projectRoot}' },
309
+ options: {
310
+ command: `mkdir -p dist && cat source*.txt > dist/lib.txt && cat dist/lib.txt >> ${builds()}`,
311
+ cwd: '{projectRoot}',
312
+ },
306
313
  },
307
314
  },
308
315
  }),
309
316
  );
310
- await writeFile(join(workspace, 'packages', 'lib', 'source.txt'), 'lib\n');
317
+ // Digit-suffixed so `source*.txt` expands in the same order under every
318
+ // locale: en_US.UTF-8 collation ignores punctuation at the first level and
319
+ // would put `source2.txt` before `source.txt`.
320
+ await writeFile(join(workspace, 'packages', 'lib', 'source1.txt'), 'lib\n');
311
321
  await writeFile(
312
322
  join(workspace, 'packages', 'app', 'project.json'),
313
323
  JSON.stringify({
@@ -323,7 +333,10 @@ describe('smoo-nx-exec', () => {
323
333
  inputs: ['{projectRoot}/source.txt', { dependentTasksOutputFiles: '**/*' }],
324
334
  outputs: ['{projectRoot}/dist'],
325
335
  dependsOn: ['^build'],
326
- options: { command: 'mkdir -p dist && cat source.txt > dist/marker.txt', cwd: '{projectRoot}' },
336
+ options: {
337
+ command: 'mkdir -p dist && cat source.txt ../lib/dist/lib.txt > dist/marker.txt',
338
+ cwd: '{projectRoot}',
339
+ },
327
340
  },
328
341
  broken: {
329
342
  executor: 'nx:run-commands',
@@ -349,6 +362,7 @@ describe('smoo-nx-exec', () => {
349
362
  if (workspace) {
350
363
  await nx(workspace, ['daemon', '--stop']);
351
364
  await rm(workspace, { recursive: true, force: true });
365
+ await rm(builds(), { force: true });
352
366
  }
353
367
  });
354
368
 
@@ -437,10 +451,13 @@ describe('smoo-nx-exec', () => {
437
451
  });
438
452
 
439
453
  it('runs again when a dependency\u0027s own inputs change', async () => {
440
- await writeFile(join(workspace, 'packages', 'lib', 'source.txt'), 'lib changed\n');
454
+ const before = await readFile(builds(), 'utf-8');
455
+ await writeFile(join(workspace, 'packages', 'lib', 'source1.txt'), 'lib changed\n');
441
456
  const changed = await runBin(workspace, ['app:build', '--', './report']);
442
457
  expect(changed.code).toBe(0);
443
458
  expect(await readFile(join(workspace, 'packages', 'lib', 'dist', 'lib.txt'), 'utf-8')).toBe('lib changed\n');
459
+ expect(await readFile(marker(), 'utf-8')).toBe('built\nlib changed\n');
460
+ expect(await readFile(builds(), 'utf-8')).toBe(`${before}lib changed\n`);
444
461
 
445
462
  // And the graph settles back to silence, which is only reachable if the
446
463
  // dependent-outputs task was hashed too.
@@ -448,6 +465,25 @@ describe('smoo-nx-exec', () => {
448
465
  expect(settled.code).toBe(0);
449
466
  expect(settled.stderr).toBe('');
450
467
  expect(settled.stdout.split('\n')[0]).toBe(MARKER);
468
+ expect(await readFile(builds(), 'utf-8')).toBe(`${before}lib changed\n`);
469
+ });
470
+
471
+ it('runs again when a dependency input is added or deleted', async () => {
472
+ const addedSource = join(workspace, 'packages', 'lib', 'source2.txt');
473
+ await writeFile(addedSource, 'added\n');
474
+ const added = await runBin(workspace, ['app:build', '--', './report']);
475
+ expect(added.code).toBe(0);
476
+ expect(await readFile(marker(), 'utf-8')).toBe('built\nlib changed\nadded\n');
477
+
478
+ await rm(addedSource);
479
+ const removed = await runBin(workspace, ['app:build', '--', './report']);
480
+ expect(removed.code).toBe(0);
481
+ expect(await readFile(marker(), 'utf-8')).toBe('built\nlib changed\n');
482
+
483
+ const settled = await runBin(workspace, ['app:build', '--', './report']);
484
+ expect(settled.code).toBe(0);
485
+ expect(settled.stderr).toBe('');
486
+ expect(settled.stdout.split('\n')[0]).toBe(MARKER);
451
487
  });
452
488
 
453
489
  it('forwards a failing target\u0027s exit code and never execs', async () => {
@@ -4,27 +4,45 @@ import { existsSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import { join, resolve } from 'node:path';
6
6
 
7
+ import type * as NxConfiguration from 'nx/src/config/nx-json';
7
8
  import type { NxJsonConfiguration } from 'nx/src/config/nx-json';
8
9
  import type { ProjectGraph, ProjectGraphProjectNode } from 'nx/src/config/project-graph';
9
- import type { Task } from 'nx/src/config/task-graph';
10
+ import type { Task, TaskGraph } from 'nx/src/config/task-graph';
11
+ import type * as NxDaemonClient from 'nx/src/daemon/client/client';
12
+ import type * as NxHashTask from 'nx/src/hasher/hash-task';
13
+ import type * as NxTaskHasher from 'nx/src/hasher/task-hasher';
14
+ import type * as NxNative from 'nx/src/native';
15
+ import type * as NxExecutionHooks from 'nx/src/project-graph/plugins/tasks-execution-hooks';
16
+ import type * as NxProjectGraph from 'nx/src/project-graph/project-graph';
17
+ import type * as NxCache from 'nx/src/tasks-runner/cache';
18
+ import type * as NxCreateTaskGraph from 'nx/src/tasks-runner/create-task-graph';
10
19
  import type { TaskResults } from 'nx/src/tasks-runner/life-cycle';
20
+ import type * as NxRunCommand from 'nx/src/tasks-runner/run-command';
21
+ import type * as NxTaskEnv from 'nx/src/tasks-runner/task-env';
22
+ import type * as NxCacheDirectory from 'nx/src/utils/cache-directory';
23
+ import type * as NxCommandLineUtils from 'nx/src/utils/command-line-utils';
11
24
  import type { NxArgs } from 'nx/src/utils/command-line-utils';
25
+ import type * as NxExitCodes from 'nx/src/utils/exit-codes';
26
+ import type * as NxPerfLogging from 'nx/src/utils/perf-logging';
27
+ import type * as NxWorkspaceRoot from 'nx/src/utils/workspace-root';
12
28
 
13
29
  interface NxRuntimeModules {
14
- readonly 'nx/src/config/nx-json': typeof import('nx/src/config/nx-json');
15
- readonly 'nx/src/daemon/client/client': typeof import('nx/src/daemon/client/client');
16
- readonly 'nx/src/hasher/hash-task': typeof import('nx/src/hasher/hash-task');
17
- readonly 'nx/src/hasher/task-hasher': typeof import('nx/src/hasher/task-hasher');
18
- readonly 'nx/src/project-graph/plugins/tasks-execution-hooks': typeof import('nx/src/project-graph/plugins/tasks-execution-hooks');
19
- readonly 'nx/src/project-graph/project-graph': typeof import('nx/src/project-graph/project-graph');
20
- readonly 'nx/src/tasks-runner/cache': typeof import('nx/src/tasks-runner/cache');
21
- readonly 'nx/src/tasks-runner/create-task-graph': typeof import('nx/src/tasks-runner/create-task-graph');
22
- readonly 'nx/src/tasks-runner/run-command': typeof import('nx/src/tasks-runner/run-command');
23
- readonly 'nx/src/tasks-runner/task-env': typeof import('nx/src/tasks-runner/task-env');
24
- readonly 'nx/src/utils/command-line-utils': typeof import('nx/src/utils/command-line-utils');
25
- readonly 'nx/src/utils/exit-codes': typeof import('nx/src/utils/exit-codes');
26
- readonly 'nx/src/utils/perf-logging': typeof import('nx/src/utils/perf-logging');
27
- readonly 'nx/src/utils/workspace-root': typeof import('nx/src/utils/workspace-root');
30
+ readonly 'nx/src/config/nx-json': typeof NxConfiguration;
31
+ readonly 'nx/src/daemon/client/client': typeof NxDaemonClient;
32
+ readonly 'nx/src/hasher/hash-task': typeof NxHashTask;
33
+ readonly 'nx/src/hasher/task-hasher': typeof NxTaskHasher;
34
+ readonly 'nx/src/native': typeof NxNative;
35
+ readonly 'nx/src/project-graph/plugins/tasks-execution-hooks': typeof NxExecutionHooks;
36
+ readonly 'nx/src/project-graph/project-graph': typeof NxProjectGraph;
37
+ readonly 'nx/src/tasks-runner/cache': typeof NxCache;
38
+ readonly 'nx/src/tasks-runner/create-task-graph': typeof NxCreateTaskGraph;
39
+ readonly 'nx/src/tasks-runner/run-command': typeof NxRunCommand;
40
+ readonly 'nx/src/tasks-runner/task-env': typeof NxTaskEnv;
41
+ readonly 'nx/src/utils/cache-directory': typeof NxCacheDirectory;
42
+ readonly 'nx/src/utils/command-line-utils': typeof NxCommandLineUtils;
43
+ readonly 'nx/src/utils/exit-codes': typeof NxExitCodes;
44
+ readonly 'nx/src/utils/perf-logging': typeof NxPerfLogging;
45
+ readonly 'nx/src/utils/workspace-root': typeof NxWorkspaceRoot;
28
46
  }
29
47
 
30
48
  type WorkspaceNxRequire = <Specifier extends keyof NxRuntimeModules>(
@@ -66,6 +84,7 @@ export type MissReason =
66
84
  | { readonly kind: 'not-cached'; readonly taskId: string }
67
85
  | { readonly kind: 'cached-failure'; readonly taskId: string; readonly code: number }
68
86
  | { readonly kind: 'stale-outputs'; readonly taskId: string }
87
+ | { readonly kind: 'stale-inputs'; readonly taskId: string }
69
88
  | { readonly kind: 'cache-disabled'; readonly taskId: string }
70
89
  | { readonly kind: 'no-daemon'; readonly taskId: string };
71
90
 
@@ -141,6 +160,8 @@ export function describeMiss(reason: MissReason): string {
141
160
  return `${reason.taskId} last failed with exit code ${reason.code}`;
142
161
  case 'stale-outputs':
143
162
  return `${reason.taskId} outputs are missing or modified on disk`;
163
+ case 'stale-inputs':
164
+ return `${reason.taskId} inputs changed since the Nx daemon last looked`;
144
165
  case 'cache-disabled':
145
166
  return `the Nx cache is disabled, so ${reason.taskId} must run`;
146
167
  case 'no-daemon':
@@ -202,10 +223,10 @@ export function firstStaleOutputs(tasks: readonly Task[], matches: readonly bool
202
223
  * when they already are.
203
224
  *
204
225
  * "Already built" is the hot path, because a checkout-local CLI wrapper pays it
205
- * on every invocation. So it never spawns the `nx` CLI: the project graph, the
206
- * task hashes and the on-disk output verification are daemon round-trips, the
207
- * cache lookup is a local SQLite read, and Nx's task runner is only invoked
208
- * once something is known to need running.
226
+ * on every invocation. So it never spawns the `nx` CLI: a native filesystem
227
+ * snapshot refreshes the daemon's inputs, the task hashes and on-disk output
228
+ * verification are daemon round-trips, and the cache lookup is a local SQLite
229
+ * read. Nx's task runner is only invoked once something needs running.
209
230
  *
210
231
  * With the daemon disabled there is no probe to make — hashing would have to
211
232
  * build the project graph in this process, and no service holds the recorded
@@ -284,6 +305,7 @@ async function ensureBuiltInWorkspace(
284
305
  const { readNxJson } = requireNx('nx/src/config/nx-json');
285
306
  const { splitArgsIntoNxArgsAndOverrides } = requireNx('nx/src/utils/command-line-utils');
286
307
  const { setEnvVarsBasedOnArgs } = requireNx('nx/src/tasks-runner/run-command');
308
+ const { createTaskGraph } = requireNx('nx/src/tasks-runner/create-task-graph');
287
309
  const hooks = requireNx('nx/src/project-graph/plugins/tasks-execution-hooks');
288
310
 
289
311
  const nxJson = readNxJson();
@@ -303,6 +325,23 @@ async function ensureBuiltInWorkspace(
303
325
  // the probe keys differently from the CLI.
304
326
  setEnvVarsBasedOnArgs(nxArgs, loadDotEnvFiles);
305
327
 
328
+ performance.mark('ensureBuilt:graph:start');
329
+ const { projectGraph } = await daemonClient.getProjectGraphAndSourceMaps();
330
+ requireProject(projectGraph, selector.project);
331
+ const taskGraph = createTaskGraph(
332
+ projectGraph,
333
+ {},
334
+ [selector.project],
335
+ [selector.target],
336
+ selector.configuration,
337
+ overrides,
338
+ false,
339
+ );
340
+ const tasks = Object.values(taskGraph.tasks);
341
+ performance.measure('ensureBuilt:graph', 'ensureBuilt:graph:start');
342
+
343
+ const inputsChanged = await refreshWorkspaceContext(workspaceRoot, tasks, requireNx);
344
+
306
345
  const runId = randomUUID();
307
346
  const startTime = Date.now();
308
347
  // Plugin `preTasksExecution` hooks inject environment variables, and declared
@@ -318,14 +357,16 @@ async function ensureBuiltInWorkspace(
318
357
 
319
358
  performance.mark('ensureBuilt:probe:start');
320
359
  let reason: MissReason | null;
360
+ const selectorTaskId =
361
+ selector.configuration === undefined
362
+ ? `${selector.project}:${selector.target}`
363
+ : `${selector.project}:${selector.target}:${selector.configuration}`;
321
364
  if (process.env.NX_SKIP_NX_CACHE === 'true' || process.env.NX_DISABLE_NX_CACHE === 'true') {
322
- const taskId =
323
- selector.configuration === undefined
324
- ? `${selector.project}:${selector.target}`
325
- : `${selector.project}:${selector.target}:${selector.configuration}`;
326
- reason = { kind: 'cache-disabled', taskId };
365
+ reason = { kind: 'cache-disabled', taskId: selectorTaskId };
366
+ } else if (inputsChanged) {
367
+ reason = { kind: 'stale-inputs', taskId: selectorTaskId };
327
368
  } else {
328
- reason = await probe(nxJson, nxArgs, overrides, selector, requireNx);
369
+ reason = await probe(nxJson, nxArgs, projectGraph, taskGraph, tasks, requireNx);
329
370
  }
330
371
  performance.measure('ensureBuilt:probe', 'ensureBuilt:probe:start');
331
372
  const outcome =
@@ -371,37 +412,80 @@ function bindWorkspaceRoot(workspaceRoot: string, requireNx: WorkspaceNxRequire)
371
412
  }
372
413
  }
373
414
 
415
+ /**
416
+ * The daemon drains delivered watcher events before serving its graph, but an
417
+ * OS event can still be in flight after a write has completed. Its graph and
418
+ * hashes can then agree with each other while both describe yesterday's files.
419
+ * Take Nx's native, ignore-aware disk snapshot and compare it with the
420
+ * daemon's file table; its metadata cache reuses unchanged file hashes.
421
+ *
422
+ * Any difference is handed to the daemon so its next graph is current, but
423
+ * that only schedules a recomputation, and a probe meanwhile would hash
424
+ * against the file map it already has. So the caller does not probe: if any
425
+ * differing path is not a declared output of a task in the graph, this
426
+ * returns true and the target is run, which lets Nx's own runner wait for the
427
+ * recomputation. Output paths are exempt because a build's own writes are the
428
+ * commonest thing to reach here before the watcher does, and treating them as
429
+ * a miss would make every hit after a build replay the cached log.
430
+ */
431
+ async function refreshWorkspaceContext(
432
+ workspaceRoot: string,
433
+ tasks: Task[],
434
+ requireNx: WorkspaceNxRequire,
435
+ ): Promise<boolean> {
436
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
437
+ const { WorkspaceContext, matchOutputPaths } = requireNx('nx/src/native');
438
+ const { workspaceDataDirectoryForWorkspace } = requireNx('nx/src/utils/cache-directory');
439
+ performance.mark('ensureBuilt:inputs:start');
440
+ const previousFiles = await daemonClient.getWorkspaceContextFileData();
441
+ const previousHashes = new Map<string, string>();
442
+ for (const { file, hash } of previousFiles) {
443
+ previousHashes.set(file, hash);
444
+ }
445
+ // A context is a snapshot, not a watcher. Do not reuse one across calls.
446
+ const context = new WorkspaceContext(workspaceRoot, workspaceDataDirectoryForWorkspace(workspaceRoot));
447
+ const createdFiles: string[] = [];
448
+ const updatedFiles: string[] = [];
449
+ for (const { file, hash } of context.allFileData()) {
450
+ const previousHash = previousHashes.get(file);
451
+ if (previousHash === undefined) {
452
+ createdFiles.push(file);
453
+ } else if (previousHash !== hash) {
454
+ updatedFiles.push(file);
455
+ }
456
+ previousHashes.delete(file);
457
+ }
458
+ const deletedFiles = [...previousHashes.keys()];
459
+ const changed = [...createdFiles, ...updatedFiles, ...deletedFiles];
460
+ let inputsChanged = false;
461
+ if (changed.length > 0) {
462
+ await daemonClient.updateWorkspaceContext(createdFiles, updatedFiles, deletedFiles);
463
+ // The same matcher the task runner uses to collect outputs, over the union
464
+ // of every task's declared outputs. A negation declared by one task then
465
+ // also excludes another task's output, which errs toward a miss.
466
+ const outputs = tasks.flatMap((task) => task.outputs);
467
+ inputsChanged = matchOutputPaths(outputs, changed).includes(false);
468
+ }
469
+ performance.measure('ensureBuilt:inputs', 'ensureBuilt:inputs:start');
470
+ return inputsChanged;
471
+ }
472
+
374
473
  /** `null` when the target is already built; otherwise the first reason it is not. */
375
474
  async function probe(
376
475
  nxJson: NxJsonConfiguration,
377
476
  nxArgs: NxArgs,
378
- overrides: Record<string, unknown>,
379
- selector: TargetSelector,
477
+ projectGraph: ProjectGraph,
478
+ taskGraph: TaskGraph,
479
+ tasks: Task[],
380
480
  requireNx: WorkspaceNxRequire,
381
481
  ): Promise<MissReason | null> {
382
482
  const { daemonClient } = requireNx('nx/src/daemon/client/client');
383
- const { createTaskGraph } = requireNx('nx/src/tasks-runner/create-task-graph');
384
483
  const { DaemonBasedTaskHasher } = requireNx('nx/src/hasher/task-hasher');
385
484
  const { getTaskDetails, hashTasks } = requireNx('nx/src/hasher/hash-task');
386
485
  const { getTaskSpecificEnv } = requireNx('nx/src/tasks-runner/task-env');
387
486
  const { getCache } = requireNx('nx/src/tasks-runner/cache');
388
487
  const { getRunnerOptions } = requireNx('nx/src/tasks-runner/run-command');
389
488
 
390
- performance.mark('ensureBuilt:graph:start');
391
- const { projectGraph } = await daemonClient.getProjectGraphAndSourceMaps();
392
- requireProject(projectGraph, selector.project);
393
- const taskGraph = createTaskGraph(
394
- projectGraph,
395
- {},
396
- [selector.project],
397
- [selector.target],
398
- selector.configuration,
399
- overrides,
400
- false,
401
- );
402
- const tasks = Object.values(taskGraph.tasks);
403
- performance.measure('ensureBuilt:graph', 'ensureBuilt:graph:start');
404
-
405
489
  // `isCloudDefault: false` because these options are only read here by the
406
490
  // hasher, which looks at `selectivelyHashTsConfig`; the cloud credentials the
407
491
  // flag would add belong to the cloud runner, and the run path calls Nx's own
@@ -1,132 +1,81 @@
1
1
  import { describe, expect, it } from 'bun:test';
2
- import { existsSync } from 'node:fs';
3
- import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { mkdir, mkdtemp, rm, stat, symlink, writeFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
4
  import { tmpdir } from 'node:os';
5
- import { join } from 'node:path';
5
+ import { dirname, join } from 'node:path';
6
+ import typescriptEmitExecutor from './executor.js';
6
7
 
7
- import { type CompilerInvocation, runTypeScriptEmit } from './executor.js';
8
+ async function fixture(source: string) {
9
+ const root = await mkdtemp(join(tmpdir(), 'smoo-typescript-emit-'));
10
+ await mkdir(join(root, 'src'));
11
+ await mkdir(join(root, 'node_modules'));
12
+ await symlink(
13
+ dirname(createRequire(import.meta.url).resolve('typia/package.json')),
14
+ join(root, 'node_modules/typia'),
15
+ 'dir',
16
+ );
17
+ await writeFile(join(root, 'package.json'), JSON.stringify({ type: 'module', dependencies: { typia: '*' } }));
18
+ await writeFile(
19
+ join(root, 'tsconfig.lib.json'),
20
+ JSON.stringify({
21
+ compilerOptions: {
22
+ target: 'ES2022',
23
+ module: 'NodeNext',
24
+ rootDir: 'src',
25
+ outDir: 'dist',
26
+ declaration: true,
27
+ declarationMap: true,
28
+ emitDeclarationOnly: true,
29
+ types: [],
30
+ skipLibCheck: true,
31
+ },
32
+ include: ['src/**/*.ts'],
33
+ }),
34
+ );
35
+ await writeFile(join(root, 'src/index.ts'), source);
36
+ return root;
37
+ }
8
38
 
9
39
  describe('@smoothbricks/nx-plugin TypeScript emit executor', () => {
10
- it('runs transformed JavaScript and native declaration lanes with project references preserved', async () => {
11
- const root = await mkdtemp(join(tmpdir(), 'smoo-typescript-emit-'));
12
- const projectRoot = join(root, 'packages/example');
13
- await mkdir(projectRoot, { recursive: true });
14
- await writeFile(
15
- join(projectRoot, 'tsconfig.lib.json'),
16
- '{\n // Project references are intentionally not inherited through extends.\n "references": [{ "path": "../dependency/tsconfig.lib.json" }]\n}\n',
40
+ it('emits executable transformed validation and declarations from the same program', async () => {
41
+ const root = await fixture(
42
+ "#!/usr/bin/env node\nimport typia from 'typia';\nexport const validate = typia.createValidate<{ value: number }>();\n",
17
43
  );
18
-
19
- const invocations: CompilerInvocation[] = [];
20
- let overlayContents = '';
21
- let overlayPath = '';
22
- try {
23
- const result = await runTypeScriptEmit(
24
- { cwd: 'packages/example', tsConfig: 'tsconfig.lib.json' },
25
- { root },
26
- async (invocation) => {
27
- invocations.push(invocation);
28
- if (invocation.command === 'ttsc') {
29
- overlayPath = invocation.args[1] ?? '';
30
- overlayContents = await readFile(overlayPath, 'utf8');
31
- }
32
- return true;
33
- },
34
- );
35
-
36
- expect(result).toEqual({ success: true });
37
- expect(invocations).toHaveLength(2);
38
- expect(invocations[0]).toEqual({
39
- command: 'ttsc',
40
- args: ['-p', overlayPath, '--emit'],
41
- cwd: projectRoot,
42
- });
43
- expect(overlayPath).toMatch(/\/\.ttsc-js-\d+-[0-9a-f-]+\.json$/);
44
- expect(overlayContents).toBe(
45
- `${JSON.stringify(
46
- {
47
- extends: './tsconfig.lib.json',
48
- compilerOptions: {
49
- composite: false,
50
- declaration: false,
51
- declarationMap: false,
52
- emitDeclarationOnly: false,
53
- incremental: false,
54
- },
55
- references: [{ path: '../dependency/tsconfig.lib.json' }],
56
- },
57
- null,
58
- 2,
59
- )}\n`,
60
- );
61
- expect(invocations[1]).toEqual({
62
- command: 'tsc',
63
- args: ['-p', overlayPath, '--emitDeclarationOnly', '--declaration', '--declarationMap'],
64
- cwd: projectRoot,
65
- });
66
- expect(existsSync(overlayPath)).toBe(false);
67
- } finally {
68
- await rm(root, { recursive: true, force: true });
69
- }
70
- });
71
-
72
- it('makes emitted package bins executable before declaration emit', async () => {
73
- const root = await mkdtemp(join(tmpdir(), 'smoo-typescript-emit-bin-'));
74
- const projectRoot = join(root, 'packages/example');
75
- const emittedBin = join(projectRoot, 'dist/bin/example.js');
76
- await mkdir(projectRoot, { recursive: true });
77
- await writeFile(join(projectRoot, 'tsconfig.lib.json'), '{}\n');
78
-
79
- let executableBeforeDeclarations = false;
80
44
  try {
81
- const result = await runTypeScriptEmit(
82
- {
83
- cwd: 'packages/example',
84
- executableOutputs: ['./dist/bin/example.js'],
85
- tsConfig: 'tsconfig.lib.json',
86
- },
87
- { root },
88
- async (invocation) => {
89
- if (invocation.command === 'ttsc') {
90
- await mkdir(join(projectRoot, 'dist/bin'), { recursive: true });
91
- await writeFile(emittedBin, '#!/usr/bin/env node\n');
92
- await chmod(emittedBin, 0o644);
93
- } else {
94
- executableBeforeDeclarations = ((await stat(emittedBin)).mode & 0o111) === 0o111;
95
- }
96
- return true;
97
- },
45
+ expect(
46
+ await typescriptEmitExecutor(
47
+ { cwd: root, tsConfig: 'tsconfig.lib.json', executableOutputs: ['dist/index.js'] },
48
+ { root },
49
+ ),
50
+ ).toEqual({ success: true });
51
+ expect((await stat(join(root, 'dist/index.js'))).mode & 0o111).toBe(0o111);
52
+ expect((await stat(join(root, 'dist/index.d.ts'))).isFile()).toBe(true);
53
+ const child = Bun.spawn(
54
+ [
55
+ 'bun',
56
+ '-e',
57
+ "import { validate } from './dist/index.js'; process.stdout.write(JSON.stringify([validate({value: 7}).success, validate({value: 'bad'}).success]))",
58
+ ],
59
+ { cwd: root, stdout: 'pipe', stderr: 'pipe' },
98
60
  );
99
-
100
- expect(result).toEqual({ success: true });
101
- expect(executableBeforeDeclarations).toBe(true);
102
- expect((await stat(emittedBin)).mode & 0o111).toBe(0o111);
61
+ const [text, errors, exit] = await Promise.all([
62
+ new Response(child.stdout).text(),
63
+ new Response(child.stderr).text(),
64
+ child.exited,
65
+ ]);
66
+ expect(exit, errors).toBe(0);
67
+ expect(text).toBe('[true,false]');
103
68
  } finally {
104
69
  await rm(root, { recursive: true, force: true });
105
70
  }
106
71
  });
107
72
 
108
- it('does not emit declarations when transformed JavaScript fails and still removes its overlay', async () => {
109
- const root = await mkdtemp(join(tmpdir(), 'smoo-typescript-emit-'));
110
- const projectRoot = join(root, 'packages/example');
111
- await mkdir(projectRoot, { recursive: true });
112
- await writeFile(join(projectRoot, 'tsconfig.lib.json'), '{}\n');
113
-
114
- const invocations: CompilerInvocation[] = [];
115
- let overlayPath = '';
73
+ it('reports real type errors instead of claiming a successful build', async () => {
74
+ const root = await fixture("export const amount: number = 'not a number';\n");
116
75
  try {
117
- const result = await runTypeScriptEmit(
118
- { cwd: projectRoot, tsConfig: 'tsconfig.lib.json' },
119
- { root },
120
- async (invocation) => {
121
- invocations.push(invocation);
122
- overlayPath = invocation.args[1] ?? '';
123
- return false;
124
- },
125
- );
126
-
127
- expect(result).toEqual({ success: false });
128
- expect(invocations.map(({ command }) => command)).toEqual(['ttsc']);
129
- expect(existsSync(overlayPath)).toBe(false);
76
+ expect(await typescriptEmitExecutor({ cwd: root, tsConfig: 'tsconfig.lib.json' }, { root })).toEqual({
77
+ success: false,
78
+ });
130
79
  } finally {
131
80
  await rm(root, { recursive: true, force: true });
132
81
  }
@@ -21,7 +21,7 @@ interface TsConfigJson {
21
21
  }
22
22
 
23
23
  export interface CompilerInvocation {
24
- command: 'tsc' | 'ttsc';
24
+ command: 'ttsc';
25
25
  args: string[];
26
26
  cwd: string;
27
27
  }
@@ -48,8 +48,8 @@ export async function runTypeScriptEmit(
48
48
  extends: `./${basename(tsConfigPath)}`,
49
49
  compilerOptions: {
50
50
  composite: false,
51
- declaration: false,
52
- declarationMap: false,
51
+ declaration: true,
52
+ declarationMap: true,
53
53
  emitDeclarationOnly: false,
54
54
  incremental: false,
55
55
  },
@@ -69,12 +69,7 @@ export async function runTypeScriptEmit(
69
69
 
70
70
  await makePackageBinsExecutable(cwd, options.executableOutputs ?? []);
71
71
 
72
- const declarationsSucceeded = await runner({
73
- command: 'tsc',
74
- args: ['-p', overlayPath, '--emitDeclarationOnly', '--declaration', '--declarationMap'],
75
- cwd,
76
- });
77
- return { success: declarationsSucceeded };
72
+ return { success: true };
78
73
  } finally {
79
74
  await rm(overlayPath, { force: true });
80
75
  }