@hewel/zgui-build 0.1.2 → 0.1.4

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/watch.ts CHANGED
@@ -5,7 +5,7 @@ import { randomUUID } from "node:crypto";
5
5
  import path from "node:path";
6
6
  import { tmpdir } from "node:os";
7
7
  import { publishApplication } from "./build.ts";
8
- import { syncCssModuleTypes } from "./css.ts";
8
+ import { resolveCssModuleWatchDirectories, syncCssModuleTypes } from "./css.ts";
9
9
  import { workspaceRoot } from "./sdk.ts";
10
10
  import {
11
11
  buildSdkPackages,
@@ -107,6 +107,7 @@ export function watchApplication(
107
107
  strictTypecheck = false,
108
108
  extraCapabilities,
109
109
  capabilitiesFile,
110
+ cssModuleInclude,
110
111
  onSuccess = ({ dist, manifest }) => console.log(`Published ${dist} ${manifest.buildId}`),
111
112
  onError = error =>
112
113
  console.error(
@@ -127,6 +128,7 @@ export function watchApplication(
127
128
  }: WatchDependencies = {},
128
129
  ): ApplicationWatcher {
129
130
  if (!/^[a-z][a-z0-9-]*$/.test(app)) throw new Error(`Invalid application name: ${app}`);
131
+ const callerCwd = process.cwd();
130
132
  root = path.resolve(root);
131
133
  appDirectory = path.resolve(appDirectory);
132
134
  if (capabilitiesFile !== undefined) capabilitiesFile = path.resolve(capabilitiesFile);
@@ -152,7 +154,45 @@ export function watchApplication(
152
154
  const watchers: FSWatcher[] = [];
153
155
  let targetWatcher: FSWatcher | undefined;
154
156
  const dependencyWatchers = new Map<string, FSWatcher>();
157
+ const externalSourceWatchers = new Map<string, FSWatcher>();
155
158
  let graphModules = new Set<string>();
159
+ const isSameOrInside = (candidate: string, ancestor: string): boolean => {
160
+ const rel = path.relative(ancestor, candidate);
161
+ return (
162
+ rel === "" || (!rel.startsWith(`..${path.sep}`) && rel !== ".." && !path.isAbsolute(rel))
163
+ );
164
+ };
165
+ const syncCssTypesOptions = {
166
+ appDirectory,
167
+ include: cssModuleInclude,
168
+ cwd: callerCwd,
169
+ };
170
+ async function refreshExternalSourceWatchers() {
171
+ const directories = await resolveCssModuleWatchDirectories(syncCssTypesOptions);
172
+ const wanted = new Set(
173
+ directories.filter(
174
+ directory =>
175
+ !isSameOrInside(directory, appDirectory) &&
176
+ !isSameOrInside(directory, uiPackageDir) &&
177
+ !isSameOrInside(directory, servicesPackageDir),
178
+ ),
179
+ );
180
+ for (const [directory, watcher] of externalSourceWatchers) {
181
+ if (!wanted.has(directory)) {
182
+ watcher.close();
183
+ externalSourceWatchers.delete(directory);
184
+ }
185
+ }
186
+ for (const directory of wanted) {
187
+ if (externalSourceWatchers.has(directory)) continue;
188
+ if (closed || controller.signal.aborted) return;
189
+ const watcher = watch(directory, { recursive: true }, (_event, filename) =>
190
+ changed(filename, directory),
191
+ );
192
+ watcher.on("error", report);
193
+ externalSourceWatchers.set(directory, watcher);
194
+ }
195
+ }
156
196
  const report = (error: unknown) => {
157
197
  if (!closed && !controller.signal.aborted) onError(error);
158
198
  };
@@ -220,7 +260,8 @@ export function watchApplication(
220
260
  status = undefined;
221
261
  cancelActiveTypecheck();
222
262
  controller.signal.throwIfAborted();
223
- await syncCssModuleTypes(appDirectory, { root });
263
+ await refreshExternalSourceWatchers();
264
+ await syncCssModuleTypes(syncCssTypesOptions);
224
265
  let previousDirectory: string | null;
225
266
  try {
226
267
  previousDirectory = await realpath(path.join(appDirectory, "dist"));
@@ -255,7 +296,7 @@ export function watchApplication(
255
296
  async onCompile(result) {
256
297
  graphModules = new Set(result.graph.modules);
257
298
  await watchDependencyManifests(result.graph.modules);
258
- await syncCssModuleTypes(appDirectory, { root });
299
+ await syncCssModuleTypes(syncCssTypesOptions);
259
300
  if (!asyncTypecheck) {
260
301
  await typecheck(path.join(appDirectory, "tsconfig.json"), { signal: controller.signal });
261
302
  }
@@ -394,9 +435,12 @@ export function watchApplication(
394
435
  parts.some(
395
436
  part =>
396
437
  part === "dist" ||
438
+ part === "dist-package" ||
439
+ part === "target" ||
397
440
  part === ".zgui-generations" ||
398
441
  part === "node_modules" ||
399
442
  part.startsWith(".dist-") ||
443
+ part.startsWith(".shell-compose-stage-") ||
400
444
  part === BUILD_STATUS_FILE ||
401
445
  part.startsWith(`${BUILD_STATUS_FILE}.`) ||
402
446
  part === NATIVE_STATUS_FILE ||
@@ -505,6 +549,8 @@ export function watchApplication(
505
549
  const initialized = (async () => {
506
550
  await ensureSdk(root, { silent: true });
507
551
  if (closed || controller.signal.aborted) return;
552
+ await refreshExternalSourceWatchers();
553
+ if (closed || controller.signal.aborted) return;
508
554
  temporary = await mkdtemp(path.join(tmpdir(), "zgui-compiler-"));
509
555
  await writeFile(path.join(temporary, "invalidate"), "");
510
556
  if (!closed && !controller.signal.aborted) startCompiler();
@@ -517,6 +563,7 @@ export function watchApplication(
517
563
  cancelActiveTypecheck();
518
564
  controller.abort();
519
565
  signal?.removeEventListener("abort", abort);
566
+ for (const watcher of externalSourceWatchers.values()) watcher.close();
520
567
  for (const watcher of dependencyWatchers.values()) watcher.close();
521
568
  targetWatcher?.close();
522
569
  for (const watcher of watchers) watcher.close();
@@ -1,178 +0,0 @@
1
- import type { PrepareNativeHostOptions, RunNativeHostOptions } from "./index.ts";
2
- import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
3
- import { constants } from "node:os";
4
- import path from "node:path";
5
- import { createInterface, type Interface } from "node:readline";
6
- import { packagedSdkRoot, workspaceRoot } from "./sdk.ts";
7
-
8
- interface ProcessOptions {
9
- spawnProcess?: (
10
- executable: string,
11
- args: readonly string[],
12
- options: SpawnOptions,
13
- ) => ChildProcess;
14
- killAfter?: number;
15
- }
16
-
17
- interface CargoMessage {
18
- reason?: string;
19
- message?: { rendered?: string };
20
- target?: { name?: string; kind?: string[] };
21
- executable?: string;
22
- }
23
-
24
- function errorMessage(error: unknown): string {
25
- return error !== null && typeof error === "object" && "message" in error
26
- ? String(error.message)
27
- : String(error);
28
- }
29
-
30
- function signalCode(signal: NodeJS.Signals | null) {
31
- return signal ? 128 + (constants.signals[signal] ?? constants.signals.SIGTERM) : 1;
32
- }
33
-
34
- function cancellationSignal(signal?: AbortSignal) {
35
- return signal?.reason === "SIGINT" ? "SIGINT" : "SIGTERM";
36
- }
37
-
38
- function failure(message: string, exitCode = 1) {
39
- return Object.assign(new Error(message), { exitCode });
40
- }
41
-
42
- // A separate POSIX process group also owns cargo's compiler/linker children and native workers.
43
- function ownedProcess(
44
- executable: string,
45
- args: readonly string[],
46
- {
47
- root,
48
- signal,
49
- onLine,
50
- }: {
51
- root: string;
52
- signal?: AbortSignal;
53
- onLine?: (line: string) => void;
54
- },
55
- { spawnProcess = spawn, killAfter = 1500 }: ProcessOptions = {},
56
- ): Promise<number> {
57
- if (signal?.aborted) return Promise.resolve(signalCode(cancellationSignal(signal)));
58
- const { promise, resolve, reject } = Promise.withResolvers<number>();
59
- try {
60
- let child: ChildProcess;
61
- let timer: NodeJS.Timeout | undefined;
62
- let spawnError: unknown;
63
- let lines: Interface | undefined;
64
- const grouped = process.platform !== "win32";
65
- const kill = (name: NodeJS.Signals) => {
66
- if (!child?.pid) return;
67
- try {
68
- if (grouped) process.kill(-child.pid, name);
69
- else child.kill(name);
70
- } catch (error) {
71
- if (
72
- !(
73
- error !== null &&
74
- typeof error === "object" &&
75
- "code" in error &&
76
- error.code === "ESRCH"
77
- )
78
- )
79
- spawnError ??= error;
80
- }
81
- };
82
- const abort = () => {
83
- kill(cancellationSignal(signal));
84
- timer ??= setTimeout(() => kill("SIGKILL"), killAfter);
85
- };
86
- try {
87
- child = spawnProcess(executable, args, {
88
- cwd: root,
89
- detached: grouped,
90
- stdio: ["inherit", onLine ? "pipe" : "inherit", "inherit"],
91
- });
92
- } catch (error) {
93
- reject(failure(`Cannot start ${executable}: ${errorMessage(error)}`));
94
- return promise;
95
- }
96
- child.once("error", error => {
97
- spawnError = error;
98
- });
99
- child.once("close", (code, terminatingSignal) => {
100
- clearTimeout(timer);
101
- signal?.removeEventListener("abort", abort);
102
- lines?.close();
103
- // A leader may exit before a worker. Never leave a member of our owned group behind.
104
- if (grouped) kill("SIGKILL");
105
- if (spawnError) reject(failure(`Cannot run ${executable}: ${errorMessage(spawnError)}`));
106
- else
107
- resolve(
108
- signal?.aborted
109
- ? signalCode(cancellationSignal(signal))
110
- : (code ?? signalCode(terminatingSignal)),
111
- );
112
- });
113
- if (onLine) {
114
- lines = createInterface({ input: child.stdout! });
115
- lines.on("line", onLine);
116
- }
117
- signal?.addEventListener("abort", abort, { once: true });
118
- // Abort can arrive while spawn hooks are running, before the listener was attached.
119
- if (signal?.aborted) abort();
120
- } catch (error) {
121
- reject(error);
122
- }
123
- return promise;
124
- }
125
-
126
- /** Build incrementally; reject with an exitCode on build/spawn/cancellation failure. */
127
- export async function prepareNativeHost(
128
- { root = workspaceRoot, signal }: PrepareNativeHostOptions = {},
129
- processOptions?: ProcessOptions,
130
- ) {
131
- root = path.resolve(root);
132
- if (root === packagedSdkRoot)
133
- throw failure(
134
- "The installed SDK has no Cargo workspace; pass root pointing to a zgui-js checkout",
135
- );
136
- let executable: string | undefined;
137
- const exitCode = await ownedProcess(
138
- "cargo",
139
- ["build", "-p", "zgui-host", "--locked", "--message-format=json-render-diagnostics"],
140
- {
141
- root,
142
- signal,
143
- onLine(line) {
144
- let message: CargoMessage | null;
145
- try {
146
- message = JSON.parse(line) as CargoMessage | null;
147
- } catch {
148
- process.stderr.write(`${line}\n`);
149
- return;
150
- }
151
- if (message?.reason === "compiler-message" && message.message?.rendered)
152
- process.stderr.write(message.message.rendered);
153
- if (
154
- message?.reason === "compiler-artifact" &&
155
- message.target?.name === "zgui-host" &&
156
- message.target.kind?.includes("bin") &&
157
- typeof message.executable === "string"
158
- ) {
159
- executable = path.resolve(root, message.executable);
160
- }
161
- },
162
- },
163
- processOptions,
164
- );
165
- if (exitCode !== 0) throw failure(`zgui-host build exited with code ${exitCode}`, exitCode);
166
- if (!executable) throw failure("Cargo did not report a zgui-host executable");
167
- return executable;
168
- }
169
-
170
- /** Inherit native stdio; return its numeric status (signals use 128 + signal number). */
171
- export async function runNativeHost(
172
- executable: string,
173
- args: readonly string[],
174
- { root = workspaceRoot, signal }: RunNativeHostOptions = {},
175
- processOptions?: ProcessOptions,
176
- ) {
177
- return ownedProcess(executable, args, { root: path.resolve(root), signal }, processOptions);
178
- }