@hewel/zgui-build 0.1.0 → 0.1.3

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/src/host.ts CHANGED
@@ -1,4 +1,11 @@
1
- import type { NativeHostAbi, ResolvedNativeHost, ResolveNativeHostOptions } from "./index.ts";
1
+ import type {
2
+ NativeHostAbi,
3
+ PrepareNativeHostOptions,
4
+ ResolvedNativeHost,
5
+ ResolveNativeHostOptions,
6
+ RunNativeHostOptions,
7
+ } from "./index.ts";
8
+ import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
2
9
  import { createHash } from "node:crypto";
3
10
  import {
4
11
  accessSync,
@@ -10,8 +17,9 @@ import {
10
17
  } from "node:fs";
11
18
  import { chmod, copyFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
12
19
  import { createRequire } from "node:module";
20
+ import { constants } from "node:os";
13
21
  import path from "node:path";
14
- import { prepareNativeHost } from "./native-process.ts";
22
+ import { createInterface, type Interface } from "node:readline";
15
23
  import { packagedSdkRoot, workspaceRoot } from "./sdk.ts";
16
24
 
17
25
  export const EXPECTED_HOST_API_VERSION = 1;
@@ -39,6 +47,184 @@ function hostFailure(message: string, exitCode = 1): Error & { exitCode: number
39
47
  return Object.assign(new Error(message), { exitCode });
40
48
  }
41
49
 
50
+ interface ProcessOptions {
51
+ spawnProcess?: (
52
+ executable: string,
53
+ args: readonly string[],
54
+ options: SpawnOptions,
55
+ ) => ChildProcess;
56
+ killAfter?: number;
57
+ }
58
+
59
+ interface CargoMessage {
60
+ reason?: string;
61
+ message?: { rendered?: string };
62
+ target?: { name?: string; kind?: string[] };
63
+ executable?: string;
64
+ }
65
+
66
+ function errorMessage(error: unknown): string {
67
+ return error !== null && typeof error === "object" && "message" in error
68
+ ? String(error.message)
69
+ : String(error);
70
+ }
71
+
72
+ function signalCode(signal: NodeJS.Signals | null) {
73
+ return signal ? 128 + (constants.signals[signal] ?? constants.signals.SIGTERM) : 1;
74
+ }
75
+
76
+ function cancellationSignal(signal?: AbortSignal) {
77
+ return signal?.reason === "SIGINT" ? "SIGINT" : "SIGTERM";
78
+ }
79
+
80
+ // A separate POSIX process group also owns cargo's compiler/linker children and native workers.
81
+ function ownedProcess(
82
+ executable: string,
83
+ args: readonly string[],
84
+ {
85
+ root,
86
+ signal,
87
+ onLine,
88
+ capture,
89
+ }: {
90
+ root: string;
91
+ signal?: AbortSignal;
92
+ onLine?: (line: string) => void;
93
+ capture?: { stdout: string[]; stderr: string[] };
94
+ },
95
+ { spawnProcess = spawn, killAfter = 1500 }: ProcessOptions = {},
96
+ ): Promise<number> {
97
+ if (signal?.aborted) return Promise.resolve(signalCode(cancellationSignal(signal)));
98
+ const { promise, resolve, reject } = Promise.withResolvers<number>();
99
+ try {
100
+ let child: ChildProcess;
101
+ let timer: NodeJS.Timeout | undefined;
102
+ let spawnError: unknown;
103
+ let lines: Interface | undefined;
104
+ const grouped = process.platform !== "win32";
105
+ const kill = (name: NodeJS.Signals) => {
106
+ if (!child?.pid) return;
107
+ try {
108
+ if (grouped) process.kill(-child.pid, name);
109
+ else child.kill(name);
110
+ } catch (error) {
111
+ if (
112
+ !(
113
+ error !== null &&
114
+ typeof error === "object" &&
115
+ "code" in error &&
116
+ error.code === "ESRCH"
117
+ )
118
+ )
119
+ spawnError ??= error;
120
+ }
121
+ };
122
+ const abort = () => {
123
+ kill(cancellationSignal(signal));
124
+ timer ??= setTimeout(() => kill("SIGKILL"), killAfter);
125
+ };
126
+ try {
127
+ child = spawnProcess(executable, args, {
128
+ cwd: root,
129
+ detached: grouped,
130
+ stdio: [
131
+ capture ? "ignore" : "inherit",
132
+ onLine || capture ? "pipe" : "inherit",
133
+ capture ? "pipe" : "inherit",
134
+ ],
135
+ });
136
+ } catch (error) {
137
+ reject(hostFailure(`Cannot start ${executable}: ${errorMessage(error)}`));
138
+ return promise;
139
+ }
140
+ child.once("error", error => {
141
+ spawnError = error;
142
+ });
143
+ child.once("close", (code, terminatingSignal) => {
144
+ clearTimeout(timer);
145
+ signal?.removeEventListener("abort", abort);
146
+ lines?.close();
147
+ // A leader may exit before a worker. Never leave a member of our owned group behind.
148
+ if (grouped) kill("SIGKILL");
149
+ if (spawnError) reject(hostFailure(`Cannot run ${executable}: ${errorMessage(spawnError)}`));
150
+ else
151
+ resolve(
152
+ signal?.aborted
153
+ ? signalCode(cancellationSignal(signal))
154
+ : (code ?? signalCode(terminatingSignal)),
155
+ );
156
+ });
157
+ if (onLine) {
158
+ lines = createInterface({ input: child.stdout! });
159
+ lines.on("line", onLine);
160
+ }
161
+ if (capture) {
162
+ child.stdout?.setEncoding("utf8").on("data", (data: string) => capture.stdout.push(data));
163
+ child.stderr?.setEncoding("utf8").on("data", (data: string) => capture.stderr.push(data));
164
+ }
165
+ signal?.addEventListener("abort", abort, { once: true });
166
+ // Abort can arrive while spawn hooks are running, before the listener was attached.
167
+ if (signal?.aborted) abort();
168
+ } catch (error) {
169
+ reject(error);
170
+ }
171
+ return promise;
172
+ }
173
+
174
+ /** Build incrementally; reject with an exitCode on build/spawn/cancellation failure. */
175
+ export async function prepareNativeHost(
176
+ { root = workspaceRoot, signal }: PrepareNativeHostOptions = {},
177
+ processOptions?: ProcessOptions,
178
+ ) {
179
+ root = path.resolve(root);
180
+ if (root === packagedSdkRoot)
181
+ throw hostFailure(
182
+ "The installed SDK has no Cargo workspace; pass root pointing to a zgui-js checkout",
183
+ );
184
+ let executable: string | undefined;
185
+ const exitCode = await ownedProcess(
186
+ "cargo",
187
+ ["build", "-p", "zgui-host", "--locked", "--message-format=json-render-diagnostics"],
188
+ {
189
+ root,
190
+ signal,
191
+ onLine(line) {
192
+ let message: CargoMessage | null;
193
+ try {
194
+ message = JSON.parse(line) as CargoMessage | null;
195
+ } catch {
196
+ process.stderr.write(`${line}\n`);
197
+ return;
198
+ }
199
+ if (message?.reason === "compiler-message" && message.message?.rendered)
200
+ process.stderr.write(message.message.rendered);
201
+ if (
202
+ message?.reason === "compiler-artifact" &&
203
+ message.target?.name === "zgui-host" &&
204
+ message.target.kind?.includes("bin") &&
205
+ typeof message.executable === "string"
206
+ ) {
207
+ executable = path.resolve(root, message.executable);
208
+ }
209
+ },
210
+ },
211
+ processOptions,
212
+ );
213
+ if (exitCode !== 0) throw hostFailure(`zgui-host build exited with code ${exitCode}`, exitCode);
214
+ if (!executable) throw hostFailure("Cargo did not report a zgui-host executable");
215
+ return executable;
216
+ }
217
+
218
+ /** Inherit native stdio; return its numeric status (signals use 128 + signal number). */
219
+ export async function runNativeHost(
220
+ executable: string,
221
+ args: readonly string[],
222
+ { root = workspaceRoot, signal }: RunNativeHostOptions = {},
223
+ processOptions?: ProcessOptions,
224
+ ) {
225
+ return ownedProcess(executable, args, { root: path.resolve(root), signal }, processOptions);
226
+ }
227
+
42
228
  export function platformId(
43
229
  platform: string = process.platform,
44
230
  arch: string = process.arch,
@@ -127,6 +313,7 @@ export function probeNativeHost(
127
313
  expectedHostApiVersion?: number;
128
314
  expectedSchemaVersion?: number;
129
315
  } = {},
316
+ cwd?: string,
130
317
  ): NativeHostAbi {
131
318
  const resolved = path.resolve(executable);
132
319
  if (!existsSync(resolved)) {
@@ -138,6 +325,7 @@ export function probeNativeHost(
138
325
  throw hostFailure(`zgui-host executable is not executable: ${resolved}`);
139
326
  }
140
327
  const child = Bun.spawnSync([resolved, "--version", "--json"], {
328
+ cwd,
141
329
  stdin: "ignore",
142
330
  stdout: "pipe",
143
331
  stderr: "pipe",
@@ -279,6 +467,30 @@ function resolveEntryScriptDir(): string | undefined {
279
467
  }
280
468
  }
281
469
 
470
+ async function resolveCargoExecutable(
471
+ cargoRoot: string,
472
+ allowCargoBuild: boolean,
473
+ explicit: boolean,
474
+ signal?: AbortSignal,
475
+ ): Promise<string> {
476
+ if (explicit && !existsSync(cargoRoot)) {
477
+ throw hostFailure(`Explicit --host-root directory not found: ${cargoRoot}`);
478
+ }
479
+ if (allowCargoBuild) return prepareNativeHost({ root: cargoRoot, signal });
480
+ for (const rel of ["target/debug/zgui-host", "target/release/zgui-host"]) {
481
+ const built = path.join(cargoRoot, rel);
482
+ if (existsSync(built)) return built;
483
+ }
484
+ if (explicit && !hasCargoNativeHost(cargoRoot)) {
485
+ throw hostFailure(
486
+ `Explicit --host-root is not a zgui-js Cargo checkout (missing crates/zgui-host/Cargo.toml): ${cargoRoot}`,
487
+ );
488
+ }
489
+ throw hostFailure(
490
+ `Local Cargo checkout detected at ${cargoRoot}, but zgui-host has not been built yet. Run \`cargo build -p zgui-host\` or invoke \`zgui-js dev\`.`,
491
+ );
492
+ }
493
+
282
494
  export async function resolveNativeHost({
283
495
  hostExecutable,
284
496
  hostRoot,
@@ -294,6 +506,14 @@ export async function resolveNativeHost({
294
506
  }: ResolveNativeHostOptions = {}): Promise<ResolvedNativeHost> {
295
507
  signal?.throwIfAborted();
296
508
  const resolvedCwd = path.resolve(cwd);
509
+ const explicitRoot = hostRoot?.trim();
510
+ const explicitRunRoot = explicitRoot ? path.resolve(resolvedCwd, explicitRoot) : undefined;
511
+ const finish = (host: Omit<ResolvedNativeHost, "abi" | "runRoot">): ResolvedNativeHost => {
512
+ signal?.throwIfAborted();
513
+ const runRoot = explicitRunRoot ?? host.cargoRoot ?? resolvedCwd;
514
+ const abi = verifyAbi ? probeNativeHost(host.executable, undefined, runRoot) : undefined;
515
+ return { ...host, runRoot, ...(abi ? { abi } : {}) };
516
+ };
297
517
 
298
518
  // 1. Explicit --host-executable or ZGUI_JS_HOST_EXECUTABLE environment variable.
299
519
  const explicitRaw = hostExecutable?.trim() || undefined;
@@ -301,15 +521,16 @@ export async function resolveNativeHost({
301
521
  if (explicitRaw !== undefined || envRaw !== undefined) {
302
522
  const source = explicitRaw !== undefined ? "explicit" : "env";
303
523
  const candidate = path.resolve(resolvedCwd, (explicitRaw ?? envRaw)!);
304
- const abi = verifyAbi ? probeNativeHost(candidate) : undefined;
305
- return {
306
- executable: candidate,
307
- source,
308
- ...(abi ? { abi } : {}),
309
- };
524
+ return finish({ executable: candidate, source });
525
+ }
526
+
527
+ // 2. Explicit --host-root overrides any installed platform package so external checkouts can test local Rust builds deterministically.
528
+ if (explicitRunRoot !== undefined) {
529
+ const executable = await resolveCargoExecutable(explicitRunRoot, allowCargoBuild, true, signal);
530
+ return finish({ executable, source: "cargo", cargoRoot: explicitRunRoot });
310
531
  }
311
532
 
312
- // 2. Installed platform package (@hewel/zgui-host-<os>-<arch>) with mandatory manifest + ABI checks.
533
+ // 3. Installed platform package (@hewel/zgui-host-<os>-<arch>) with mandatory manifest + ABI checks.
313
534
  const currentPlatform = platformId(platform, arch);
314
535
  const packageName = platformHostPackageName(platform, arch);
315
536
  if (packageName) {
@@ -333,13 +554,7 @@ export async function resolveNativeHost({
333
554
  expectedPackage: packageName,
334
555
  expectedPlatform: currentPlatform,
335
556
  });
336
- const abi = verifyAbi ? probeNativeHost(binaryPath) : undefined;
337
- return {
338
- executable: binaryPath,
339
- source: "platform-package",
340
- packageName,
341
- ...(abi ? { abi } : {}),
342
- };
557
+ return finish({ executable: binaryPath, source: "platform-package", packageName });
343
558
  }
344
559
  if (existsSync(manifestPath)) {
345
560
  throw hostFailure(
@@ -349,42 +564,19 @@ export async function resolveNativeHost({
349
564
  }
350
565
  }
351
566
 
352
- // 3. Local Cargo workspace build (--host-root or detected checkout containing crates/zgui-host).
567
+ // 4. Autodetected local Cargo workspace checkout containing crates/zgui-host.
353
568
  const resolvedRoot = path.resolve(root);
354
- const cargoRoot =
355
- hostRoot !== undefined
356
- ? path.resolve(resolvedCwd, hostRoot)
357
- : resolvedRoot !== packagedSdkRoot && hasCargoNativeHost(resolvedRoot)
358
- ? resolvedRoot
359
- : findCargoCheckoutUpwards(resolvedCwd);
360
-
361
- if (cargoRoot !== undefined) {
362
- if (!allowCargoBuild) {
363
- for (const rel of ["target/debug/zgui-host", "target/release/zgui-host"]) {
364
- const built = path.join(cargoRoot, rel);
365
- if (existsSync(built)) {
366
- const abi = verifyAbi ? probeNativeHost(built) : undefined;
367
- return {
368
- executable: built,
369
- source: "cargo",
370
- cargoRoot,
371
- ...(abi ? { abi } : {}),
372
- };
373
- }
374
- }
375
- throw hostFailure(
376
- `Local Cargo checkout detected at ${cargoRoot}, but zgui-host has not been built yet. Run \`cargo build -p zgui-host\` or invoke \`zgui-js dev\`.`,
377
- );
378
- }
379
- const executable = await prepareNativeHost({ root: cargoRoot, signal });
380
- return {
381
- executable,
382
- source: "cargo",
383
- cargoRoot,
384
- };
569
+ const autoCargoRoot =
570
+ resolvedRoot !== packagedSdkRoot && hasCargoNativeHost(resolvedRoot)
571
+ ? resolvedRoot
572
+ : findCargoCheckoutUpwards(resolvedCwd);
573
+
574
+ if (autoCargoRoot !== undefined) {
575
+ const executable = await resolveCargoExecutable(autoCargoRoot, allowCargoBuild, false, signal);
576
+ return finish({ executable, source: "cargo", cargoRoot: autoCargoRoot });
385
577
  }
386
578
 
387
- // 4. Actionable error when no prebuilt host or Cargo checkout is available.
579
+ // 5. Actionable error when no prebuilt host or Cargo checkout is available.
388
580
  const installHint = packageName
389
581
  ? `Install the prebuilt host package (${packageName})`
390
582
  : `No prebuilt host package is published for ${currentPlatform}`;
@@ -522,7 +714,7 @@ export async function verifyHostPackage(
522
714
  }
523
715
 
524
716
  export async function compileModuleBytecode(
525
- hostExecutable: string,
717
+ host: ResolvedNativeHost,
526
718
  {
527
719
  input,
528
720
  output,
@@ -538,9 +730,10 @@ export async function compileModuleBytecode(
538
730
  },
539
731
  ): Promise<Buffer> {
540
732
  signal?.throwIfAborted();
541
- const child = Bun.spawn(
733
+ const capture = { stdout: [] as string[], stderr: [] as string[] };
734
+ const code = await ownedProcess(
735
+ host.executable,
542
736
  [
543
- path.resolve(hostExecutable),
544
737
  "compile-bytecode",
545
738
  "--input",
546
739
  path.resolve(input),
@@ -550,29 +743,14 @@ export async function compileModuleBytecode(
550
743
  moduleName,
551
744
  ...(sourceDir ? ["--source-dir", path.resolve(sourceDir)] : []),
552
745
  ],
553
- {
554
- stdin: "ignore",
555
- stdout: "pipe",
556
- stderr: "pipe",
557
- },
746
+ { root: host.runRoot, signal, capture },
558
747
  );
559
- const onAbort = () => child.kill("SIGTERM");
560
- signal?.addEventListener("abort", onAbort, { once: true });
561
- try {
562
- const [code, stdout, stderr] = await Promise.all([
563
- child.exited,
564
- new Response(child.stdout).text(),
565
- new Response(child.stderr).text(),
566
- ]);
567
- if (code !== 0 || child.signalCode) {
568
- const detail = `${stderr}${stdout}`.trim();
569
- throw hostFailure(
570
- `zgui-host compile-bytecode failed for ${moduleName} (exit ${child.signalCode ?? code})${detail ? `: ${detail}` : ""}`,
571
- );
572
- }
573
- return Buffer.from(await readFile(output));
574
- } finally {
575
- signal?.removeEventListener("abort", onAbort);
576
- signal?.throwIfAborted();
748
+ signal?.throwIfAborted();
749
+ if (code !== 0) {
750
+ const detail = `${capture.stderr.join("")}${capture.stdout.join("")}`.trim();
751
+ throw hostFailure(
752
+ `zgui-host compile-bytecode failed for ${moduleName} (exit ${code})${detail ? `: ${detail}` : ""}`,
753
+ );
577
754
  }
755
+ return readFile(output);
578
756
  }
package/src/index.ts CHANGED
@@ -2,9 +2,14 @@ import type * as Implementation from "./index.ts";
2
2
  import type * as Public from "./public-api.d.ts";
3
3
  import { resolveApplication as resolve } from "./application.ts";
4
4
  import { buildApplication as build } from "./build.ts";
5
+ import { syncCssModuleTypes as syncCssTypes } from "./css.ts";
5
6
  import { devApplication as dev } from "./dev.ts";
6
- import { probeNativeHost as probe, resolveNativeHost as resolveHost } from "./host.ts";
7
- import { prepareNativeHost as prepare, runNativeHost as run } from "./native-process.ts";
7
+ import {
8
+ prepareNativeHost as prepare,
9
+ probeNativeHost as probe,
10
+ resolveNativeHost as resolveHost,
11
+ runNativeHost as run,
12
+ } from "./host.ts";
8
13
  import { packageApplication as packApp } from "./package-app.ts";
9
14
  import { previewApplication as preview } from "./preview.ts";
10
15
  import { watchApplication as watch } from "./watch.ts";
@@ -12,6 +17,7 @@ import { watchApplication as watch } from "./watch.ts";
12
17
  export type * from "./public-api.d.ts";
13
18
 
14
19
  export const buildApplication: typeof Public.buildApplication = build;
20
+ export const syncCssModuleTypes: typeof Public.syncCssModuleTypes = syncCssTypes;
15
21
  export const watchApplication: typeof Public.watchApplication = watch;
16
22
  export const devApplication: typeof Public.devApplication = dev;
17
23
  export const previewApplication: typeof Public.previewApplication = preview;