@smoothbricks/nx-plugin 0.4.31 → 0.5.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 (43) hide show
  1. package/README.md +15 -11
  2. package/dist/cargo-toolchain-policy.d.ts +6 -6
  3. package/dist/cargo-toolchain-policy.js +6 -6
  4. package/dist/cross-check-policy.d.ts +31 -14
  5. package/dist/cross-check-policy.d.ts.map +1 -1
  6. package/dist/cross-check-policy.js +43 -15
  7. package/dist/executors/cargo-zigbuild/executor.d.ts +60 -0
  8. package/dist/executors/cargo-zigbuild/executor.d.ts.map +1 -0
  9. package/dist/executors/cargo-zigbuild/executor.js +266 -0
  10. package/dist/executors/cargo-zigbuild/schema.d.ts +15 -0
  11. package/dist/executors/cargo-zigbuild/schema.d.ts.map +1 -0
  12. package/dist/index.d.ts +0 -15
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +56 -89
  15. package/dist/testing.d.ts.map +1 -1
  16. package/dist/testing.js +3 -2
  17. package/executors.json +4 -4
  18. package/managed/raw/patches/nx@23.2.1.patch +177 -9
  19. package/managed/raw/tooling/direnv/devenv.smoo.nix +46 -46
  20. package/managed/raw/tooling/git-hooks/pre-push.sh +41 -23
  21. package/package.json +1 -1
  22. package/src/cargo-toolchain-policy.ts +6 -6
  23. package/src/cross-check-policy.test.ts +90 -11
  24. package/src/cross-check-policy.ts +47 -17
  25. package/src/executors/cargo-zigbuild/executor.test.ts +129 -0
  26. package/src/executors/cargo-zigbuild/executor.ts +176 -0
  27. package/src/executors/cargo-zigbuild/schema.json +35 -0
  28. package/src/executors/cargo-zigbuild/schema.ts +14 -0
  29. package/src/index.test.ts +29 -61
  30. package/src/index.ts +60 -98
  31. package/src/nx-daemon-validity.test.ts +65 -0
  32. package/src/testing.ts +3 -2
  33. package/test-timings.json +1 -1
  34. package/dist/executors/napi-cross-toolchain/executor.d.ts +0 -42
  35. package/dist/executors/napi-cross-toolchain/executor.d.ts.map +0 -1
  36. package/dist/executors/napi-cross-toolchain/executor.js +0 -126
  37. package/dist/executors/napi-cross-toolchain/schema.d.ts +0 -4
  38. package/dist/executors/napi-cross-toolchain/schema.d.ts.map +0 -1
  39. package/src/executors/napi-cross-toolchain/executor.test.ts +0 -112
  40. package/src/executors/napi-cross-toolchain/executor.ts +0 -165
  41. package/src/executors/napi-cross-toolchain/schema.json +0 -15
  42. package/src/executors/napi-cross-toolchain/schema.ts +0 -3
  43. /package/dist/executors/{napi-cross-toolchain → cargo-zigbuild}/schema.js +0 -0
@@ -800,6 +800,71 @@ it('stops a daemon once the workspace nx link points at a different version', as
800
800
  );
801
801
  });
802
802
 
803
+ it('restarts a daemon once a plugin linked from outside the workspace changes its bytes, in place or by a moved link, and only then', async () => {
804
+ await withNxFixture(
805
+ 'nx-daemon-validity-plugin-',
806
+ async ({ root, socketDirectory, workspace }) => {
807
+ const inference = (version: string) =>
808
+ `// inference ${version}\nmodule.exports = { name: 'linked-plugin', createNodesV2: ['**/never.json', () => []] };\n`;
809
+ // A developer link: the plugin is a package of another checkout, which has its own lockfile.
810
+ const checkout = async (name: string) => {
811
+ const plugin = join(root, name, 'plugin');
812
+ await mkdir(join(plugin, 'dist'), { recursive: true });
813
+ await writeFile(join(root, name, 'bun.lock'), 'checkout lock one\n');
814
+ await writeFile(
815
+ join(plugin, 'package.json'),
816
+ JSON.stringify({ name: 'linked-plugin', version: '1.0.0', main: 'dist/index.js', files: ['dist'] }),
817
+ );
818
+ await writeFile(join(plugin, 'dist', 'index.js'), inference('one'));
819
+ return { plugin, entry: join(plugin, 'dist', 'index.js'), lock: join(root, name, 'bun.lock') };
820
+ };
821
+ const first = await checkout('checkout-a');
822
+ const copy = await checkout('checkout-b');
823
+ const link = join(workspace, 'node_modules', 'linked-plugin');
824
+ const relink = async (target: string) => {
825
+ await unlink(link);
826
+ await symlink(target, link, 'dir');
827
+ };
828
+ await fixtureWorkspace(workspace, join(repositoryRoot, 'node_modules', 'nx'));
829
+ await symlink(first.plugin, link, 'dir');
830
+ await writeFile(join(workspace, 'nx.json'), JSON.stringify({ plugins: ['linked-plugin'] }));
831
+ const env = fixtureNxEnv(workspace, socketDirectory);
832
+ // Nothing in the workspace changes, so no watcher event reaches the daemon: each request judges the link.
833
+ const serves = async (daemon: Daemon, what: string) => {
834
+ expect(
835
+ await requestOnce(daemon.record.socketPath, ping(workspace), `a PING after ${what}`),
836
+ `${what} was refused`,
837
+ ).toEqual({ answered: true, message: true });
838
+ expect(await recordedPid(workspace), `${what} replaced the daemon`).toBe(daemon.record.processId);
839
+ };
840
+ const replaced = async (daemon: Daemon, what: string) => {
841
+ assertNotServed(
842
+ await requestOnce(daemon.record.socketPath, ping(workspace), `a PING sent after ${what}`),
843
+ `a PING sent after ${what}`,
844
+ );
845
+ await awaitExit([daemon.entry], `daemon ${daemon.record.processId} after ${what}`);
846
+ return readyDaemon(
847
+ workspace,
848
+ await replacementAfter({ workspace, previous: daemon.record.processId, what: `a successor after ${what}` }),
849
+ );
850
+ };
851
+ let daemon = await startDaemon(workspace, env);
852
+ await writeFile(first.entry, inference('one'));
853
+ await serves(daemon, 'a same-bytes rewrite of the linked plugin');
854
+ await relink(copy.plugin);
855
+ await serves(daemon, 'the link moving to a copy with the same bytes');
856
+ await writeFile(copy.entry, inference('two'));
857
+ daemon = await replaced(daemon, 'the linked plugin changing in place');
858
+ await relink(first.plugin);
859
+ daemon = await replaced(daemon, 'the link moving to a plugin with other bytes');
860
+ // The checkout's lockfile selects the plugin's dependencies, so its change restarts the daemon as well.
861
+ await writeFile(first.lock, 'checkout lock two\n');
862
+ await replaced(daemon, "the linked plugin checkout's lockfile changing");
863
+ },
864
+ FIXTURE_WORKSPACE,
865
+ );
866
+ });
867
+
803
868
  it('leaves a successor record and socket in place when another process takes the record', async () => {
804
869
  await withNxFixture(
805
870
  'nx-daemon-validity-successor-',
package/src/testing.ts CHANGED
@@ -138,9 +138,10 @@ export async function awaitExit(
138
138
  owner: string,
139
139
  timeoutMs = EXIT_TIMEOUT_MS,
140
140
  ): Promise<void> {
141
- const deadline = Date.now() + timeoutMs;
141
+ // The monotonic clock: a wall-clock step (NTP, sleep and wake) must not move the deadline.
142
+ const deadline = performance.now() + timeoutMs;
142
143
  for (let waiting = processes.filter((entry) => isRunning(entry.pid)); waiting.length > 0; ) {
143
- if (Date.now() > deadline) {
144
+ if (performance.now() > deadline) {
144
145
  // A signal probe also answers for a zombie, which has already exited.
145
146
  const live = new Set(
146
147
  (await processTable()).filter((entry) => !entry.stat.startsWith('Z')).map((entry) => entry.pid),
package/test-timings.json CHANGED
@@ -14,7 +14,6 @@
14
14
  "src/executors/bounded-exec/ram-temp.test.ts": 10766,
15
15
  "src/producer-receipts.test.ts": 10581,
16
16
  "src/typescript-resolution.test.ts": 10482,
17
- "src/executors/napi-cross-toolchain/executor.test.ts": 10474,
18
17
  "src/nx-daemon-claim.test.ts": 9477,
19
18
  "src/cargo-source-hash.test.ts": 9179,
20
19
  "src/nx-use-local.test.ts": 8333,
@@ -81,6 +80,7 @@
81
80
  "src/managed-files/managed-content.test.ts": 31,
82
81
  "src/executors/nextest-group/executor.test.ts": 28,
83
82
  "src/executors/bounded-exec/ram-temp-held.test.ts": 22,
83
+ "src/executors/cargo-zigbuild/executor.test.ts": 20,
84
84
  "src/build-state-output-policy.test.ts": 20,
85
85
  "src/managed-files/tree-permissions.test.ts": 20,
86
86
  "src/executors/bounded-exec/progress.test.ts": 18,
@@ -1,42 +0,0 @@
1
- import type { NapiCrossToolchainOptions } from './schema.js';
2
- interface NapiCrossToolchainContext {
3
- root: string;
4
- projectName?: string;
5
- projectsConfigurations?: {
6
- projects: Record<string, {
7
- root?: string;
8
- }>;
9
- };
10
- }
11
- export type PrewarmOutcome = 'ready' | 'extracted' | 'unsupported-host';
12
- export default function napiCrossToolchainExecutor(options: NapiCrossToolchainOptions, context: NapiCrossToolchainContext): Promise<{
13
- success: boolean;
14
- }>;
15
- /**
16
- * Extract the pinned cross toolchain into the directory
17
- * `napi build --use-napi-cross` probes, so its own download never runs.
18
- *
19
- * WHY this exists: `@napi-rs/cross-toolchain@1.0.3`'s `download()` uses its own
20
- * package directory as scratch space — `npm pack` there, unpack, then a
21
- * non-`force` `rmSync` of the tarball. Under `linker = "isolated"` with
22
- * `globalStore = true` that directory is the shared Bun store (in CI a
23
- * host-wide mutable bind mount), so two concurrent `--use-napi-cross` builds of
24
- * one triple pack the same filename into the same directory and the loser dies
25
- * with `ENOENT ... lstat '<tarball>'`. Nx runs `cli-x64-linux` and
26
- * `napi-x64-linux` in one wave, which is exactly that race.
27
- *
28
- * Extraction stages into a private sibling directory and lands with `rename`,
29
- * so racing callers — and repeated runs after a crash — cannot corrupt the
30
- * result: `rename` replaces an empty directory (napi itself creates one before
31
- * probing) and fails with ENOTEMPTY against a populated one, which means
32
- * another caller already won.
33
- */
34
- export declare function prewarmCrossToolchain(options: {
35
- projectRoot: string;
36
- triple: string;
37
- platform?: string;
38
- hostArch?: string;
39
- home?: string;
40
- }): PrewarmOutcome;
41
- export {};
42
- //# sourceMappingURL=executor.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/napi-cross-toolchain/executor.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAE7D,UAAU,yBAAyB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,sBAAsB,CAAC,EAAE;QACvB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE;YAAE,IAAI,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KAC7C,CAAC;CACH;AAaD,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,WAAW,GAAG,kBAAkB,CAAC;AAExE,wBAA8B,0BAA0B,CACtD,OAAO,EAAE,yBAAyB,EAClC,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC;IAAE,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC,CAe/B;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE;IAC7C,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GAAG,cAAc,CAyEjB"}
@@ -1,126 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs';
3
- import { createRequire } from 'node:module';
4
- import { homedir } from 'node:os';
5
- import path from 'node:path';
6
- /** Package-name arch segment of `@napi-rs/cross-toolchain-<host>-target-<arch>`. */
7
- const TARGET_PACKAGE_ARCH = {
8
- 'aarch64-unknown-linux-gnu': 'aarch64',
9
- 'x86_64-unknown-linux-gnu': 'x86_64',
10
- };
11
- const HOST_PACKAGE_ARCH = {
12
- arm64: 'arm64',
13
- x64: 'x64',
14
- };
15
- export default async function napiCrossToolchainExecutor(options, context) {
16
- const projectName = context.projectName;
17
- if (!projectName) {
18
- throw new Error('@smoothbricks/nx-plugin:napi-cross-toolchain requires a project context.');
19
- }
20
- const project = context.projectsConfigurations?.projects[projectName];
21
- if (!project) {
22
- throw new Error(`Project ${projectName} was not found in the Nx project graph.`);
23
- }
24
- const projectRoot = path.resolve(context.root, project.root ?? '.');
25
- const triple = options.triple;
26
- console.log(`${triple}: ${prewarmCrossToolchain({ projectRoot, triple })}`);
27
- return { success: true };
28
- }
29
- /**
30
- * Extract the pinned cross toolchain into the directory
31
- * `napi build --use-napi-cross` probes, so its own download never runs.
32
- *
33
- * WHY this exists: `@napi-rs/cross-toolchain@1.0.3`'s `download()` uses its own
34
- * package directory as scratch space — `npm pack` there, unpack, then a
35
- * non-`force` `rmSync` of the tarball. Under `linker = "isolated"` with
36
- * `globalStore = true` that directory is the shared Bun store (in CI a
37
- * host-wide mutable bind mount), so two concurrent `--use-napi-cross` builds of
38
- * one triple pack the same filename into the same directory and the loser dies
39
- * with `ENOENT ... lstat '<tarball>'`. Nx runs `cli-x64-linux` and
40
- * `napi-x64-linux` in one wave, which is exactly that race.
41
- *
42
- * Extraction stages into a private sibling directory and lands with `rename`,
43
- * so racing callers — and repeated runs after a crash — cannot corrupt the
44
- * result: `rename` replaces an empty directory (napi itself creates one before
45
- * probing) and fails with ENOTEMPTY against a populated one, which means
46
- * another caller already won.
47
- */
48
- export function prewarmCrossToolchain(options) {
49
- const { projectRoot, triple } = options;
50
- const targetArch = TARGET_PACKAGE_ARCH[triple];
51
- if (!targetArch) {
52
- throw new Error(`Unsupported --use-napi-cross triple ${triple}. Supported: ${Object.keys(TARGET_PACKAGE_ARCH).join(', ')}.`);
53
- }
54
- const hostArch = HOST_PACKAGE_ARCH[options.hostArch ?? process.arch];
55
- // napi-rs ships these toolchains for Linux x64 and Linux arm64 hosts only,
56
- // and refuses `--use-napi-cross` anywhere else. Extracting on a host that can
57
- // never use the result would only demand pins nothing needs, so leave the
58
- // unsupported-host diagnostic to the build itself.
59
- if (!hostArch || (options.platform ?? process.platform) !== 'linux') {
60
- return 'unsupported-host';
61
- }
62
- const requireFromProject = createRequire(path.join(projectRoot, 'package.json'));
63
- const targetPackage = `@napi-rs/cross-toolchain-${hostArch}-target-${targetArch}`;
64
- let targetModule;
65
- try {
66
- targetModule = requireFromProject(targetPackage);
67
- }
68
- catch (error) {
69
- throw new Error(`${targetPackage} is not installed for ${projectRoot}. Add it to optionalDependencies so ${triple} ` +
70
- 'builds extract the pinned toolchain instead of downloading into the shared Bun store.', { cause: error });
71
- }
72
- if (typeof targetModule !== 'object' ||
73
- targetModule === null ||
74
- !('toolchainPath' in targetModule) ||
75
- typeof targetModule.toolchainPath !== 'string') {
76
- throw new Error(`${targetPackage} no longer exports a toolchainPath string.`);
77
- }
78
- const tarball = targetModule.toolchainPath;
79
- const home = options.home ?? homedir();
80
- const destination = path.join(home, '.napi-rs', 'cross-toolchain', crossToolchainVersion(requireFromProject), triple);
81
- const marker = path.join(destination, 'package.json');
82
- if (existsSync(marker)) {
83
- return 'ready';
84
- }
85
- mkdirSync(path.dirname(destination), { recursive: true });
86
- const staging = mkdtempSync(`${destination}.staging-`);
87
- const command = `tar -xJf ${tarball} -C ${staging}`;
88
- try {
89
- execFileSync('tar', ['-xJf', tarball, '-C', staging], { stdio: 'inherit' });
90
- if (!existsSync(path.join(staging, 'package.json'))) {
91
- throw new Error(`${tarball} did not contain the package.json marker napi probes; the toolchain archive layout changed.`);
92
- }
93
- renameSync(staging, destination);
94
- }
95
- catch (error) {
96
- rmSync(staging, { force: true, recursive: true });
97
- const code = error instanceof Error && 'code' in error ? error.code : undefined;
98
- if ((code === 'ENOTEMPTY' || code === 'EEXIST') && existsSync(marker)) {
99
- return 'ready';
100
- }
101
- const status = error instanceof Error && 'status' in error ? error.status : undefined;
102
- if (status !== undefined) {
103
- if (error instanceof Error) {
104
- console.error(error.message);
105
- }
106
- throw new Error(`${command} failed with exit code ${typeof status === 'number' ? status : 1}`, { cause: error });
107
- }
108
- throw error;
109
- }
110
- return 'extracted';
111
- }
112
- /**
113
- * `napi` derives the extraction directory from `@napi-rs/cross-toolchain`'s own
114
- * version, so read it from the package the CLI resolves — not from the
115
- * per-target package, whose version only happens to match today.
116
- */
117
- function crossToolchainVersion(requireFromProject) {
118
- const cliRequire = createRequire(requireFromProject.resolve('@napi-rs/cli/package.json'));
119
- const indexPath = cliRequire.resolve('@napi-rs/cross-toolchain');
120
- const manifest = JSON.parse(readFileSync(path.join(path.dirname(indexPath), 'package.json'), 'utf-8'));
121
- const version = typeof manifest === 'object' && manifest !== null && 'version' in manifest ? manifest.version : undefined;
122
- if (typeof version !== 'string' || version.length === 0) {
123
- throw new Error(`@napi-rs/cross-toolchain resolved at ${indexPath} has no version.`);
124
- }
125
- return version;
126
- }
@@ -1,4 +0,0 @@
1
- export interface NapiCrossToolchainOptions {
2
- triple: string;
3
- }
4
- //# sourceMappingURL=schema.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/executors/napi-cross-toolchain/schema.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,yBAAyB;IACxC,MAAM,EAAE,MAAM,CAAC;CAChB"}
@@ -1,112 +0,0 @@
1
- import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
2
- import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { join } from 'node:path';
5
-
6
- import { prewarmCrossToolchain } from './executor.js';
7
-
8
- // The pins that make extraction possible live on the consumer, so the real
9
- // extraction runs against that project: `cowshed` declares the
10
- // `@napi-rs/cross-toolchain-*-target-*` optionalDependencies its cross builds
11
- // need. aarch64 is the one triple pinned for both an arm64 and an x64 host, so
12
- // this covers developer machines and CI with the same archive.
13
- const consumerProjectRoot = join(import.meta.dir, '../../../../cowshed');
14
- const triple = 'aarch64-unknown-linux-gnu';
15
- const temporaryDirs: string[] = [];
16
-
17
- function temporaryDir(prefix: string): string {
18
- const dir = mkdtempSync(join(tmpdir(), prefix));
19
- temporaryDirs.push(dir);
20
- return dir;
21
- }
22
-
23
- let firstHome = '';
24
- let firstOutcome = '';
25
- let version = '';
26
-
27
- beforeAll(() => {
28
- firstHome = temporaryDir('napi-cross-toolchain-');
29
- firstOutcome = prewarmCrossToolchain({
30
- projectRoot: consumerProjectRoot,
31
- triple,
32
- platform: 'linux',
33
- home: firstHome,
34
- });
35
- // The directory napi probes is keyed by the resolved @napi-rs/cross-toolchain
36
- // version, so read it back instead of restating the pinned version here.
37
- const versions = readdirSync(join(firstHome, '.napi-rs', 'cross-toolchain'));
38
- expect(versions).toHaveLength(1);
39
- version = versions[0] ?? '';
40
- });
41
-
42
- afterAll(() => {
43
- for (const dir of temporaryDirs) {
44
- rmSync(dir, { force: true, recursive: true });
45
- }
46
- });
47
-
48
- describe('napi-cross-toolchain executor', () => {
49
- it('extracts the pinned toolchain once and then reports it ready', () => {
50
- expect(firstOutcome).toBe('extracted');
51
-
52
- // napi derives the compiler, sysroot and PATH entries from this layout and
53
- // skips extraction on the package.json marker alone: a marker without the
54
- // toolchain turns every later build into a missing-linker failure.
55
- const toolchain = join(firstHome, '.napi-rs', 'cross-toolchain', version, triple);
56
- expect(existsSync(join(toolchain, 'package.json'))).toBe(true);
57
- expect(existsSync(join(toolchain, 'bin', `${triple}-gcc`))).toBe(true);
58
- expect(existsSync(join(toolchain, triple, 'sysroot'))).toBe(true);
59
-
60
- expect(
61
- prewarmCrossToolchain({ projectRoot: consumerProjectRoot, triple, platform: 'linux', home: firstHome }),
62
- ).toBe('ready');
63
- });
64
-
65
- it('lands the toolchain in the empty directory napi creates before probing', () => {
66
- const home = temporaryDir('napi-cross-toolchain-');
67
- const destination = join(home, '.napi-rs', 'cross-toolchain', version, triple);
68
- mkdirSync(destination, { recursive: true });
69
-
70
- expect(prewarmCrossToolchain({ projectRoot: consumerProjectRoot, triple, platform: 'linux', home })).toBe(
71
- 'extracted',
72
- );
73
- expect(existsSync(join(destination, 'package.json'))).toBe(true);
74
- });
75
-
76
- it('leaves hosts that cannot run the toolchain to the build itself', () => {
77
- expect(
78
- prewarmCrossToolchain({
79
- projectRoot: consumerProjectRoot,
80
- triple,
81
- platform: 'darwin',
82
- home: temporaryDir('napi-cross-toolchain-'),
83
- }),
84
- ).toBe('unsupported-host');
85
- });
86
-
87
- it('rejects triples that have no cross toolchain package', () => {
88
- expect(() =>
89
- prewarmCrossToolchain({
90
- projectRoot: consumerProjectRoot,
91
- triple: 'armv7-unknown-linux-gnueabihf',
92
- platform: 'linux',
93
- home: temporaryDir('napi-cross-toolchain-'),
94
- }),
95
- ).toThrow('Unsupported --use-napi-cross triple armv7-unknown-linux-gnueabihf');
96
- });
97
-
98
- it('names the optional dependency a project is missing', () => {
99
- const projectRoot = temporaryDir('napi-cross-consumer-');
100
- writeFileSync(join(projectRoot, 'package.json'), '{"name":"unpinned"}\n');
101
-
102
- expect(() =>
103
- prewarmCrossToolchain({
104
- projectRoot,
105
- triple,
106
- platform: 'linux',
107
- hostArch: 'x64',
108
- home: temporaryDir('napi-cross-toolchain-'),
109
- }),
110
- ).toThrow('@napi-rs/cross-toolchain-x64-target-aarch64 is not installed');
111
- });
112
- });
@@ -1,165 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs';
3
- import { createRequire } from 'node:module';
4
- import { homedir } from 'node:os';
5
- import path from 'node:path';
6
-
7
- import type { NapiCrossToolchainOptions } from './schema.js';
8
-
9
- interface NapiCrossToolchainContext {
10
- root: string;
11
- projectName?: string;
12
- projectsConfigurations?: {
13
- projects: Record<string, { root?: string }>;
14
- };
15
- }
16
-
17
- /** Package-name arch segment of `@napi-rs/cross-toolchain-<host>-target-<arch>`. */
18
- const TARGET_PACKAGE_ARCH: Readonly<Record<string, string>> = {
19
- 'aarch64-unknown-linux-gnu': 'aarch64',
20
- 'x86_64-unknown-linux-gnu': 'x86_64',
21
- };
22
-
23
- const HOST_PACKAGE_ARCH: Readonly<Record<string, string>> = {
24
- arm64: 'arm64',
25
- x64: 'x64',
26
- };
27
-
28
- export type PrewarmOutcome = 'ready' | 'extracted' | 'unsupported-host';
29
-
30
- export default async function napiCrossToolchainExecutor(
31
- options: NapiCrossToolchainOptions,
32
- context: NapiCrossToolchainContext,
33
- ): Promise<{ success: boolean }> {
34
- const projectName = context.projectName;
35
- if (!projectName) {
36
- throw new Error('@smoothbricks/nx-plugin:napi-cross-toolchain requires a project context.');
37
- }
38
- const project = context.projectsConfigurations?.projects[projectName];
39
- if (!project) {
40
- throw new Error(`Project ${projectName} was not found in the Nx project graph.`);
41
- }
42
- const projectRoot = path.resolve(context.root, project.root ?? '.');
43
- const triple = options.triple;
44
-
45
- console.log(`${triple}: ${prewarmCrossToolchain({ projectRoot, triple })}`);
46
-
47
- return { success: true };
48
- }
49
-
50
- /**
51
- * Extract the pinned cross toolchain into the directory
52
- * `napi build --use-napi-cross` probes, so its own download never runs.
53
- *
54
- * WHY this exists: `@napi-rs/cross-toolchain@1.0.3`'s `download()` uses its own
55
- * package directory as scratch space — `npm pack` there, unpack, then a
56
- * non-`force` `rmSync` of the tarball. Under `linker = "isolated"` with
57
- * `globalStore = true` that directory is the shared Bun store (in CI a
58
- * host-wide mutable bind mount), so two concurrent `--use-napi-cross` builds of
59
- * one triple pack the same filename into the same directory and the loser dies
60
- * with `ENOENT ... lstat '<tarball>'`. Nx runs `cli-x64-linux` and
61
- * `napi-x64-linux` in one wave, which is exactly that race.
62
- *
63
- * Extraction stages into a private sibling directory and lands with `rename`,
64
- * so racing callers — and repeated runs after a crash — cannot corrupt the
65
- * result: `rename` replaces an empty directory (napi itself creates one before
66
- * probing) and fails with ENOTEMPTY against a populated one, which means
67
- * another caller already won.
68
- */
69
- export function prewarmCrossToolchain(options: {
70
- projectRoot: string;
71
- triple: string;
72
- platform?: string;
73
- hostArch?: string;
74
- home?: string;
75
- }): PrewarmOutcome {
76
- const { projectRoot, triple } = options;
77
- const targetArch = TARGET_PACKAGE_ARCH[triple];
78
- if (!targetArch) {
79
- throw new Error(
80
- `Unsupported --use-napi-cross triple ${triple}. Supported: ${Object.keys(TARGET_PACKAGE_ARCH).join(', ')}.`,
81
- );
82
- }
83
- const hostArch = HOST_PACKAGE_ARCH[options.hostArch ?? process.arch];
84
- // napi-rs ships these toolchains for Linux x64 and Linux arm64 hosts only,
85
- // and refuses `--use-napi-cross` anywhere else. Extracting on a host that can
86
- // never use the result would only demand pins nothing needs, so leave the
87
- // unsupported-host diagnostic to the build itself.
88
- if (!hostArch || (options.platform ?? process.platform) !== 'linux') {
89
- return 'unsupported-host';
90
- }
91
-
92
- const requireFromProject = createRequire(path.join(projectRoot, 'package.json'));
93
- const targetPackage = `@napi-rs/cross-toolchain-${hostArch}-target-${targetArch}`;
94
- let targetModule: unknown;
95
- try {
96
- targetModule = requireFromProject(targetPackage);
97
- } catch (error) {
98
- throw new Error(
99
- `${targetPackage} is not installed for ${projectRoot}. Add it to optionalDependencies so ${triple} ` +
100
- 'builds extract the pinned toolchain instead of downloading into the shared Bun store.',
101
- { cause: error },
102
- );
103
- }
104
- if (
105
- typeof targetModule !== 'object' ||
106
- targetModule === null ||
107
- !('toolchainPath' in targetModule) ||
108
- typeof targetModule.toolchainPath !== 'string'
109
- ) {
110
- throw new Error(`${targetPackage} no longer exports a toolchainPath string.`);
111
- }
112
- const tarball = targetModule.toolchainPath;
113
-
114
- const home = options.home ?? homedir();
115
- const destination = path.join(home, '.napi-rs', 'cross-toolchain', crossToolchainVersion(requireFromProject), triple);
116
- const marker = path.join(destination, 'package.json');
117
- if (existsSync(marker)) {
118
- return 'ready';
119
- }
120
-
121
- mkdirSync(path.dirname(destination), { recursive: true });
122
- const staging = mkdtempSync(`${destination}.staging-`);
123
- const command = `tar -xJf ${tarball} -C ${staging}`;
124
- try {
125
- execFileSync('tar', ['-xJf', tarball, '-C', staging], { stdio: 'inherit' });
126
- if (!existsSync(path.join(staging, 'package.json'))) {
127
- throw new Error(
128
- `${tarball} did not contain the package.json marker napi probes; the toolchain archive layout changed.`,
129
- );
130
- }
131
- renameSync(staging, destination);
132
- } catch (error) {
133
- rmSync(staging, { force: true, recursive: true });
134
- const code = error instanceof Error && 'code' in error ? error.code : undefined;
135
- if ((code === 'ENOTEMPTY' || code === 'EEXIST') && existsSync(marker)) {
136
- return 'ready';
137
- }
138
- const status = error instanceof Error && 'status' in error ? error.status : undefined;
139
- if (status !== undefined) {
140
- if (error instanceof Error) {
141
- console.error(error.message);
142
- }
143
- throw new Error(`${command} failed with exit code ${typeof status === 'number' ? status : 1}`, { cause: error });
144
- }
145
- throw error;
146
- }
147
- return 'extracted';
148
- }
149
-
150
- /**
151
- * `napi` derives the extraction directory from `@napi-rs/cross-toolchain`'s own
152
- * version, so read it from the package the CLI resolves — not from the
153
- * per-target package, whose version only happens to match today.
154
- */
155
- function crossToolchainVersion(requireFromProject: NodeJS.Require): string {
156
- const cliRequire = createRequire(requireFromProject.resolve('@napi-rs/cli/package.json'));
157
- const indexPath = cliRequire.resolve('@napi-rs/cross-toolchain');
158
- const manifest: unknown = JSON.parse(readFileSync(path.join(path.dirname(indexPath), 'package.json'), 'utf-8'));
159
- const version =
160
- typeof manifest === 'object' && manifest !== null && 'version' in manifest ? manifest.version : undefined;
161
- if (typeof version !== 'string' || version.length === 0) {
162
- throw new Error(`@napi-rs/cross-toolchain resolved at ${indexPath} has no version.`);
163
- }
164
- return version;
165
- }
@@ -1,15 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/schema",
3
- "version": 2,
4
- "title": "N-API Cross Toolchain Executor",
5
- "description": "Extract the pinned @napi-rs cross toolchain into ~/.napi-rs so `napi build --use-napi-cross` never downloads it.",
6
- "type": "object",
7
- "properties": {
8
- "triple": {
9
- "type": "string",
10
- "description": "Rust target triple to prepare, e.g. x86_64-unknown-linux-gnu."
11
- }
12
- },
13
- "required": ["triple"],
14
- "additionalProperties": false
15
- }
@@ -1,3 +0,0 @@
1
- export interface NapiCrossToolchainOptions {
2
- triple: string;
3
- }