@nm-lang/cli 0.3.0 → 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.
package/README.md CHANGED
@@ -1,140 +1,200 @@
1
- # @nm-lang/cli
2
-
3
- N/M 0.2.0 Preview command-line tools for running, formatting, linting, testing,
4
- exporting and managing local N/M workspaces.
5
-
6
- Package release **0.3.0** targets the N/M **0.2.0** language contract.
7
-
8
- ## Install / Kurulum
9
-
10
- Requires Node.js 20 or newer. Release checks use Node.js 22.23.1.
11
-
12
- ```sh
13
- npm install --global @nm-lang/cli
14
- nm --version
15
- ```
16
-
17
- Or run without a global install:
18
-
19
- ```sh
20
- npx --package=@nm-lang/cli nm --version
21
- ```
22
-
23
- An untagged install selects npm's `latest` channel. To pin this version after
24
- publication, append `@0.3.0` to the package name. The N/M language remains
25
- Preview independently of the npm channel. npm installs the matching Core dependency.
26
- No repository checkout or TypeScript build is needed to use a published package.
27
-
28
- Türkçe: Etiketsiz kurulum npm'in `latest` kanalını seçer. Yayından sonra
29
- `@0.3.0` ile sürümü sabitleyebilirsiniz. N/M dili, npm kanalından bağımsız
30
- olarak Önizleme durumundadır. Core bağımlılığı otomatik kurulur; depoyu
31
- indirmeniz gerekmez.
32
-
33
- ## First program / İlk program
34
-
35
- Save the following as `bell.nm`:
36
-
37
- ```nm
38
- module npm_bell;
39
- fn main() {
40
- let q = qreg[2];
41
- H(q[0]);
42
- CNOT(q[0], q[1]);
43
- let a = measure(q[0]);
44
- let b = measure(q[1]);
45
- return (a, b);
46
- }
47
- ```
48
-
49
- ```sh
50
- nm run bell.nm --json
51
- ```
52
-
53
- The program creates and measures a Bell pair using a local simulator.
54
- Türkçe: Kodu `bell.nm` olarak kaydedip komutla çalıştırın. Sonuç yerel
55
- simülasyondan gelir; gerçek kuantum donanımı kanıtı değildir.
56
-
57
- ## Language options / Dil seçenekleri
58
-
59
- ### Selected tests and CI reports / Test seçimi ve CI raporları
60
-
61
- The `0.3.0` package adds test selection, watch mode and JSON, JUnit and SARIF
62
- reports for CI integrations.
63
-
64
- Türkçe: `0.3.0` paketi test seçimini, izleme modunu ve CI entegrasyonları için
65
- JSON, JUnit ve SARIF raporlarını içerir.
66
-
67
- ```sh
68
- nm test main.nm --name "Bell contract" --json
69
- nm test main.nm --id nmtest-0123456789abcdef
70
- nm test main.nm --report-format junit --output results.xml
71
- nm test main.nm --report-format sarif --output results.sarif
72
- nm test main.nm --watch --json
73
- ```
74
-
75
- `--name` matches the exact declared name; repeat `--name` or `--id` to select a
76
- union. Copy real IDs from a JSON report for the same input path and source lines.
77
- Selection happens before execution, preserving surrounding setup and original
78
- source locations; unknown/stale IDs or names fail with `NM-TEST-SELECT-001`.
79
- Direct selection of a nested check fails with `NM-TEST-SELECT-002`; select its
80
- top-level enclosing check. Source syntax and capability validation still cover
81
- the complete file, including its original register allocation and qubit limits.
82
- Empty suites and failed execution exit 1.
83
-
84
- `--report-format json|junit|sarif` writes that format to stdout. `--output` also
85
- replaces the explicitly named `.json`, `.xml` or `.sarif` report on each run;
86
- parent directories must already exist. The default output remains human readable.
87
- `--json` cannot be combined with a non-JSON report format.
88
-
89
- `--watch` is available in the Node command-line host. It runs immediately, then
90
- debounces source and workspace-manifest changes, including imported modules,
91
- clears the workspace cache and queues runs without overlap. Ctrl+C/SIGTERM closes
92
- watchers. With `--json`, stdout is NDJSON: each `event:"run"` has a sequence,
93
- exitCode, report (or null for invocation errors) and diagnostics; lifecycle errors
94
- and stopping also have event objects. JUnit/SARIF watch mode requires `--output`
95
- and prints run summaries while replacing the report file. The exit status follows
96
- the latest run; signal termination uses 130/143.
97
-
98
- Türkçe: Tam test adı veya mevcut rapordaki kimlikle seçim yapın; seçenekler
99
- tekrarlanabilir. Seçilmeyen test blokları yürütülmez, ortak kurulum korunur.
100
- İç içe kontrolleri doğrudan seçmek yerine üst kontrolü seçin. Kaynağın tamamındaki
101
- kayıt tahsisi ve qubit sınırları seçimden sonra da geçerlidir. İzleme modu bağımlı
102
- `.nm` dosyaları ve manifest değişince yeniden çalışır. `--output` belirtilen rapor
103
- dosyasını her çalıştırmada yeniler.
104
-
105
- ### Toolchain doctor / Araç zinciri kontrolü
106
-
107
- The `0.3.0` CLI provides `nm doctor --json` and `nm doctor --locale tr`.
108
- It compares the loaded CLI/Core and locally resolvable LSP/MCP packages, reporting
109
- package, language and protocol versions separately. Missing optional packages and
110
- the VS Code installation remain unobserved; this is not a check of running servers.
111
- Exit code 1 means an observed mismatch or failed package probe; 0 may still mean
112
- partial coverage. The report format is `nm-toolchain-doctor` version `0.1`.
113
-
114
- Türkçe: `nm doctor` yüklenen CLI/Core ile yerelden çözümlenebilen LSP/MCP
115
- paketlerini karşılaştırır. Paket, dil ve protokol sürümleri ayrı değerlendirilir.
116
- Gözlenmeyen isteğe bağlı araçlar ve VS Code kurulumu doğrulanmış sayılmaz.
117
- Çıkış kodu 1 uyuşmazlık veya paket sorgusu hatasıdır; 0 kısmi gözlem anlamına da
118
- gelebilir. Bu komutlar `0.3.0` paketinin parçasıdır.
119
-
120
- New CLI invocations enable the default language profile: classical functions,
121
- typed values/Result, module visibility, parameter groups and compute/apply.
122
- Use `--legacy-features` for the previous opt-in behavior. Other experimental
123
- features still require their own flags; export/backend limits remain enforced.
124
-
125
- Türkçe: Yeni CLI çağrılarında varsayılan dil profili açıktır. Eski davranış için
126
- `--legacy-features` kullanın. Diğer deneysel özellikler ayrıca açılmalıdır.
127
-
128
- - [CLI documentation](https://quantumsoftware.tech/en/docs/nm-language/cli)
129
- - [Türkçe CLI rehberi](https://quantumsoftware.tech/tr/docs/nm-language/cli)
130
- - [Support / Destek](https://quantumsoftware.tech/en/#contact)
131
-
132
- ## License / Lisans
133
-
134
- Free personal, educational and commercial use; source-code rights are reserved.
135
- Modification or redistribution of QuantumSoftware-owned package code requires
136
- separate permission. Your N/M programs and results remain yours. See
137
- [LICENSE.txt](./LICENSE.txt) and [NOTICE.txt](./NOTICE.txt).
138
-
139
- Türkçe: Kullanım ücretsizdir; açık kaynak lisansı verilmez. Paket kodunu
140
- değiştirme ve yeniden dağıtma için ayrıca izin gerekir.
1
+ # @nm-lang/cli
2
+
3
+ N/M 0.2.0 Preview command-line tools for running, formatting, linting, testing,
4
+ exporting and managing local N/M workspaces.
5
+
6
+ Package **0.5.0** targets the N/M **0.2.0** language contract.
7
+
8
+ ## Install / Kurulum
9
+
10
+ Requires Node.js 20 or newer. Release checks use Node.js 22.23.1.
11
+
12
+ ```sh
13
+ npm install --global @nm-lang/cli
14
+ nm --version
15
+ ```
16
+
17
+ Or run without a global install:
18
+
19
+ ```sh
20
+ npx --package=@nm-lang/cli nm --version
21
+ ```
22
+
23
+ An untagged install selects npm's `latest` channel. To pin this version,
24
+ append `@0.5.0` to the package name. The N/M language remains
25
+ Preview independently of the npm channel. npm installs the matching Core dependency.
26
+ No repository checkout or TypeScript build is needed to use a published package.
27
+
28
+ Türkçe: Etiketsiz kurulum npm'in `latest` kanalını seçer.
29
+ `@0.5.0` ile sürümü sabitleyebilirsiniz. N/M dili, npm kanalından bağımsız
30
+ olarak Önizleme durumundadır. Core bağımlılığı otomatik kurulur; depoyu
31
+ indirmeniz gerekmez.
32
+
33
+ ## First program / İlk program
34
+
35
+ Save the following as `bell.nm`:
36
+
37
+ ```nm
38
+ module npm_bell;
39
+ fn main() {
40
+ let q = qreg[2];
41
+ H(q[0]);
42
+ CNOT(q[0], q[1]);
43
+ let a = measure(q[0]);
44
+ let b = measure(q[1]);
45
+ return (a, b);
46
+ }
47
+ ```
48
+
49
+ ```sh
50
+ nm run bell.nm --json
51
+ ```
52
+
53
+ The program creates and measures a Bell pair using a local simulator.
54
+ Türkçe: Kodu `bell.nm` olarak kaydedip komutla çalıştırın. Sonuç yerel
55
+ simülasyondan gelir; gerçek kuantum donanımı kanıtı değildir.
56
+
57
+ ## Language options / Dil seçenekleri
58
+
59
+ ### Selected tests and CI reports / Test seçimi ve CI raporları
60
+
61
+ The CLI provides test selection, watch mode and JSON, JUnit and SARIF
62
+ reports for CI integrations.
63
+
64
+ Türkçe: CLI test seçimini, izleme modunu ve CI entegrasyonları için
65
+ JSON, JUnit ve SARIF raporlarını içerir.
66
+
67
+ ```sh
68
+ nm test main.nm --name "Bell contract" --json
69
+ nm test main.nm --id nmtest-0123456789abcdef
70
+ nm test main.nm --report-format junit --output results.xml
71
+ nm test main.nm --report-format sarif --output results.sarif
72
+ nm test main.nm --watch --json
73
+ ```
74
+
75
+ `--name` matches the exact declared name; repeat `--name` or `--id` to select a
76
+ union. Copy real IDs from a JSON report for the same input path and source lines.
77
+ Selection happens before execution, preserving surrounding setup and original
78
+ source locations; unknown/stale IDs or names fail with `NM-TEST-SELECT-001`.
79
+ Direct selection of a nested check fails with `NM-TEST-SELECT-002`; select its
80
+ top-level enclosing check. Source syntax and capability validation still cover
81
+ the complete file, including its original register allocation and qubit limits.
82
+ Empty suites and failed execution exit 1.
83
+
84
+ `--report-format json|junit|sarif` writes that format to stdout. `--output` also
85
+ replaces the explicitly named `.json`, `.xml` or `.sarif` report on each run;
86
+ parent directories must already exist. The default output remains human readable.
87
+ `--json` cannot be combined with a non-JSON report format.
88
+
89
+ `--watch` is available in the Node command-line host. It runs immediately, then
90
+ debounces source and workspace-manifest changes, including imported modules,
91
+ clears the workspace cache and queues runs without overlap. Ctrl+C/SIGTERM closes
92
+ watchers. With `--json`, stdout is NDJSON: each `event:"run"` has a sequence,
93
+ exitCode, report (or null for invocation errors) and diagnostics; lifecycle errors
94
+ and stopping also have event objects. JUnit/SARIF watch mode requires `--output`
95
+ and prints run summaries while replacing the report file. The exit status follows
96
+ the latest run; signal termination uses 130/143.
97
+
98
+ Türkçe: Tam test adı veya mevcut rapordaki kimlikle seçim yapın; seçenekler
99
+ tekrarlanabilir. Seçilmeyen test blokları yürütülmez, ortak kurulum korunur.
100
+ İç içe kontrolleri doğrudan seçmek yerine üst kontrolü seçin. Kaynağın tamamındaki
101
+ kayıt tahsisi ve qubit sınırları seçimden sonra da geçerlidir. İzleme modu bağımlı
102
+ `.nm` dosyaları ve manifest değişince yeniden çalışır. `--output` belirtilen rapor
103
+ dosyasını her çalıştırmada yeniler.
104
+
105
+ ### Toolchain doctor / Araç zinciri kontrolü
106
+
107
+ The `0.3.0` CLI provides `nm doctor --json` and `nm doctor --locale tr`.
108
+ It compares the loaded CLI/Core and locally resolvable LSP/MCP packages, reporting
109
+ package, language and protocol versions separately. Missing optional packages and
110
+ the VS Code installation remain unobserved; this is not a check of running servers.
111
+ Exit code 1 means an observed mismatch or failed package probe; 0 may still mean
112
+ partial coverage. The report format is `nm-toolchain-doctor` version `0.1`.
113
+
114
+ Türkçe: `nm doctor` yüklenen CLI/Core ile yerelden çözümlenebilen LSP/MCP
115
+ paketlerini karşılaştırır. Paket, dil ve protokol sürümleri ayrı değerlendirilir.
116
+ Gözlenmeyen isteğe bağlı araçlar ve VS Code kurulumu doğrulanmış sayılmaz.
117
+ Çıkış kodu 1 uyuşmazlık veya paket sorgusu hatasıdır; 0 kısmi gözlem anlamına da
118
+ gelebilir. Bu komutlar `0.3.0` paketinin parçasıdır.
119
+
120
+ New CLI invocations enable the default language profile: classical functions,
121
+ typed values/Result, module visibility, parameter groups and compute/apply.
122
+ Use `--legacy-features` for the previous opt-in behavior. Other experimental
123
+ features still require their own flags; export/backend limits remain enforced.
124
+
125
+ Türkçe: Yeni CLI çağrılarında varsayılan dil profili açıktır. Eski davranış için
126
+ `--legacy-features` kullanın. Diğer deneysel özellikler ayrıca açılmalıdır.
127
+
128
+ - [CLI documentation](https://quantumsoftware.tech/en/docs/nm-language/cli)
129
+ - [Türkçe CLI rehberi](https://quantumsoftware.tech/tr/docs/nm-language/cli)
130
+ - [Support / Destek](https://quantumsoftware.tech/en/#contact)
131
+
132
+
133
+ ## 0.5.0: Trainable evolution / Eğitilebilir evrim
134
+
135
+ This package adds scalar-parameter evolution time and Hamiltonian coefficients,
136
+ fixed gate topology at zero time/weight, and exact-statevector circuit/operator
137
+ derivatives. The training host supports fixed or adaptive QWC allocation with
138
+ one total shot budget, separate pilots/held-out confidence evidence, and optional
139
+ final-cost precision targets. Required-shot estimates are informational; they do
140
+ not spend extra shots, increase the 4096 limit or certify convergence. These
141
+ features require the existing explicit Hamiltonian and grouping permissions.
142
+
143
+ Türkçe: Parametreli evrim süresi/katsayıları, sıfırda korunan kapı yapısı ve kesin
144
+ statevector devre/operatör türevleri eklenir. Eğitim host'u sabit/adaptif QWC,
145
+ tek toplam ölçüm bütçesi, ayrı pilot/değerlendirme güven kanıtı ve isteğe bağlı
146
+ son maliyet hassasiyetini destekler. Ölçüm tahmini bilgi amaçlıdır; ek ölçüm almaz,
147
+ 4096 sınırını artırmaz veya yakınsamayı belgelemez. Mevcut iki açık izin korunur.
148
+
149
+ The N/M language contract remains 0.2.0; package and artifact versions are separate.
150
+ N/M dil sözleşmesi 0.2.0 olarak kalır; paket ve dosya biçimi sürümleri ayrıdır.
151
+
152
+ ## Hamiltonian 0.4.0 / Hamiltonian 0.4.0
153
+
154
+ Version 0.4.0 includes Hamiltonian evolution and shared-shot QWC expectations.
155
+ Earlier releases do not include these additions.
156
+ Both `hamiltonianEvolution` and `measurementGrouping` require explicit permission.
157
+ Source printing and N/M IR v0.5 preserve original source, parser context, seed and
158
+ shot plans. Imports rebuild with caller permissions; stored flags never grant them.
159
+ QASM/framework export and source optimization/transpilation reject these semantics.
160
+
161
+ CLI: `--experimental-hamiltonian-evolution`, `--experimental-measurement-grouping`,
162
+ `--from-ir` for a saved v0.5 IR, `--locale en|tr` for diagnostics. MCP: the matching
163
+ `experimentalHamiltonianEvolution` / `experimentalMeasurementGrouping` booleans,
164
+ `nm_export` target `ir` and `nm_import_ir`. LSP initialization uses
165
+ `initializationOptions.nm.experimental`; VS Code uses
166
+ `nm.experimental.hamiltonianEvolution` / `nm.experimental.measurementGrouping`.
167
+ The editor offers completion/hover, closed-default diagnostics and original
168
+ source columns for generated gates in the recorded debugger.
169
+
170
+ Türkçe: 0.4.0 bu geliştirmeleri içerir; iki yeni izin varsayılan kapalıdır.
171
+ Yazdırma/IR özgün kaynağı ve ortak ölçüm bütçesini korur; içe aktarım
172
+ kaydı çalıştırma yetkisi saymaz. CLI/MCP/LSP/Monaco/VS Code aynı izinleri taşır;
173
+ tanılar ve ayarlar TR/EN destekler. TR/EN laboratuvarı sitede erişilebilirdir.
174
+ N/M dil sözleşmesi 0.2.0 ve ön izleme olgunluğu korunur.
175
+
176
+ [Release notes](https://quantumsoftware.tech/en/docs/nm-language/releases) ·
177
+ [Türkçe sürüm notları](https://quantumsoftware.tech/tr/docs/nm-language/releases)
178
+
179
+ ## License / Lisans
180
+
181
+ Free personal, educational and commercial use; source-code rights are reserved.
182
+ Modification or redistribution of QuantumSoftware-owned package code requires
183
+ separate permission. Your N/M programs and results remain yours. See
184
+ [LICENSE.txt](./LICENSE.txt) and [NOTICE.txt](./NOTICE.txt).
185
+
186
+ Türkçe: Kullanım ücretsizdir; açık kaynak lisansı verilmez. Paket kodunu
187
+ değiştirme ve yeniden dağıtma için ayrıca izin gerekir.
188
+
189
+ ## Python/Jupyter bridge / Python/Jupyter köprüsü
190
+
191
+ Version 0.5.0 adds `nm bridge` for bounded JSON `check`, `run` and
192
+ `train` requests through stdin. The `python/nm_bridge.py` stdlib adapter and
193
+ `python/examples/training.ipynb` preserve source, explicit caller permissions,
194
+ training options and complete measurement/confidence evidence. TR/EN output is
195
+ supported; saved records never self-grant replay permissions. No separate PyPI
196
+ release is provided. See `python/README.md` and the repository's
197
+ `docs/NM_PYTHON_JUPYTER_BRIDGE_GUIDE.md`. The earlier npm 0.4.0 release does not include this bridge.
198
+ Türkçe: 0.5.0, standart kütüphaneli yerel Python/Jupyter köprüsünü içerir;
199
+ kayıtlar özgün kaynak, eğitim seçenekleri, bütçe ve güven kanıtını korur.
200
+ Kayıt okumak çalıştırma izni vermez; ayrı bir PyPI paketi yayımlanmaz.
@@ -0,0 +1,78 @@
1
+ import { Worker } from "node:worker_threads";
2
+
3
+ // Transport caps also cover stdin waiting, runtime loading and forced termination.
4
+ export const nmBridgeTransportLimits = Object.freeze({ requestBytes: 262144, responseBytes: 4194304, defaultTimeoutMs: 30000, maxTimeoutMs: 60000 });
5
+ const copy = {
6
+ en: { input: "Invalid bridge arguments, UTF-8 input, or request size.", timeout: "Bridge deadline exceeded. The Worker was terminated; no completed measurement or precision evidence is available.", execution: "Bridge Worker failed. No completed result is available.", cancel: "Bridge cancelled; no completed result is available." },
7
+ tr: { input: "Köprü bağımsız değişkenleri, UTF-8 girdisi veya istek boyutu geçersiz.", timeout: "Köprü süre sınırı aşıldı. Worker sonlandırıldı; tamamlanmış ölçüm veya hassasiyet kanıtı yoktur.", execution: "Köprü Worker hatası. Tamamlanmış sonuç yoktur.", cancel: "Köprü iptal edildi; tamamlanmış sonuç yoktur." },
8
+ };
9
+ function rejection(key, locale) {
10
+ return { exitCode: 1, stdout: [JSON.stringify({ format: "nm-python-bridge", version: 1, success: false, status: "rejected", locale,
11
+ error: { code: key === "timeout" ? "NM-PY-008" : key === "cancel" ? "NM-PY-009" : key === "execution" ? "NM-PY-007" : "NM-PY-001", message: copy[locale][key] } })], stderr: [] };
12
+ }
13
+
14
+ export async function runNMBridgeHost(args) {
15
+ const locale = args[args.indexOf("--locale") + 1] === "tr" ? "tr" : "en";
16
+ const forwarded = [], seen = new Set(), features = new Set();
17
+ let timeoutMs = nmBridgeTransportLimits.defaultTimeoutMs;
18
+ for (let index = 0; index < args.length; index++) {
19
+ const flag = args[index];
20
+ if (flag === "--allow-feature") {
21
+ const feature = args[++index];
22
+ if (!/^[A-Za-z]+$/u.test(feature ?? "") || features.has(feature)) return emit(rejection("input", locale));
23
+ features.add(feature); forwarded.push(flag, feature); continue;
24
+ }
25
+ if (seen.has(flag)) return emit(rejection("input", locale));
26
+ seen.add(flag);
27
+ if (flag === "--json") { forwarded.push(flag); continue; }
28
+ if (flag === "--locale" && ["en", "tr"].includes(args[index + 1])) { forwarded.push(flag, args[++index]); continue; }
29
+ if (flag === "--timeout-ms") {
30
+ const value = args[++index];
31
+ if (!/^\d+$/u.test(value ?? "") || Number(value) < 100 || Number(value) > nmBridgeTransportLimits.maxTimeoutMs) return emit(rejection("input", locale));
32
+ timeoutMs = Number(value); continue;
33
+ }
34
+ return emit(rejection("input", locale));
35
+ }
36
+ await new Promise(resolve => {
37
+ let worker, settled = false, size = 0;
38
+ const chunks = [];
39
+ const finish = async result => {
40
+ if (settled) return;
41
+ settled = true; clearTimeout(timer);
42
+ process.stdin.removeListener("data", onData); process.stdin.removeListener("end", onEnd); process.stdin.removeListener("error", onInputError);
43
+ process.removeListener("SIGINT", onCancel); process.removeListener("SIGTERM", onCancel);
44
+ chunks.length = 0; process.stdin.destroy();
45
+ if (worker) await worker.terminate();
46
+ emit(result); resolve();
47
+ };
48
+ const onCancel = () => void finish(rejection("cancel", locale));
49
+ const onInputError = () => void finish(rejection("input", locale));
50
+ const onData = chunk => {
51
+ size += chunk.length;
52
+ if (size > nmBridgeTransportLimits.requestBytes) return void finish(rejection("input", locale));
53
+ chunks.push(chunk);
54
+ };
55
+ const onEnd = () => {
56
+ let input;
57
+ try { input = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)); }
58
+ catch { return void finish(rejection("input", locale)); }
59
+ chunks.length = 0;
60
+ try {
61
+ worker = new Worker(new URL("./bridge-worker.mjs", import.meta.url), {
62
+ workerData: { args: forwarded, input }, resourceLimits: { maxOldGenerationSizeMb: 512, stackSizeMb: 8 },
63
+ });
64
+ worker.once("message", result => {
65
+ const valid = result && [0, 1].includes(result.exitCode) && result.stdout?.length === 1 && result.stderr?.length === 0
66
+ && typeof result.stdout[0] === "string" && Buffer.byteLength(result.stdout[0]) <= nmBridgeTransportLimits.responseBytes;
67
+ void finish(valid ? result : rejection("execution", locale));
68
+ });
69
+ worker.once("error", () => void finish(rejection("execution", locale)));
70
+ worker.once("exit", () => { if (!settled) void finish(rejection("execution", locale)); });
71
+ } catch { void finish(rejection("execution", locale)); }
72
+ };
73
+ const timer = setTimeout(() => void finish(rejection("timeout", locale)), timeoutMs);
74
+ process.once("SIGINT", onCancel); process.once("SIGTERM", onCancel);
75
+ process.stdin.on("data", onData); process.stdin.once("end", onEnd); process.stdin.once("error", onInputError);
76
+ });
77
+ }
78
+ function emit(result) { process.exitCode = result.exitCode; process.stdout.write(`${result.stdout.join("\n")}\n`); }
@@ -0,0 +1,27 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import Module from "node:module";
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ // Same repository-source/installed-artifact selection as nm.mjs, inside the deadline.
8
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
9
+ const sourceCLI = path.join(root, "lib/nm/cli.ts");
10
+ let runtime;
11
+ if (existsSync(sourceCLI) && process.env.NM_CLI_FORCE_PACKED !== "1") {
12
+ const original = Module._resolveFilename;
13
+ Module._resolveFilename = function (request, ...args) {
14
+ if (typeof request === "string" && request.startsWith("@/")) {
15
+ const absolute = path.join(root, request.slice(2));
16
+ request = existsSync(`${absolute}.ts`) ? `${absolute}.ts` : absolute;
17
+ }
18
+ return original.call(this, request, ...args);
19
+ };
20
+ const { createJiti } = await import("jiti");
21
+ runtime = createJiti(import.meta.url)(sourceCLI);
22
+ } else runtime = await import("../dist/index.js");
23
+ const result = runtime.runNMCLI(["bridge", ...workerData.args], {
24
+ readStdin: () => workerData.input,
25
+ readFile: () => { throw new Error("The JSON bridge does not read filesystem sources."); },
26
+ });
27
+ parentPort.postMessage(result);
package/bin/nm.mjs CHANGED
@@ -25,7 +25,9 @@ const isPackedVersionCommand =
25
25
  process.env.NM_CLI_FORCE_PACKED === "1" &&
26
26
  (cliArgs[0] === "--version" || cliArgs[0] === "version");
27
27
 
28
- if (isPackedVersionCommand) {
28
+ if (cliArgs[0] === "bridge") {
29
+ await (await import("./bridge-host.mjs")).runNMBridgeHost(cliArgs.slice(1));
30
+ } else if (isPackedVersionCommand) {
29
31
  const { nmVersionManifest } = await import("../dist/version.js");
30
32
  process.stdout.write(
31
33
  cliArgs.includes("--json")