@hewel/zgui-build 0.0.0-stage → 0.1.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 (45) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +95 -0
  3. package/README.md +84 -2
  4. package/THIRD_PARTY_NOTICES.md +37 -0
  5. package/package.json +64 -4
  6. package/sdk/Cargo.lock +6813 -0
  7. package/sdk/LICENSE +202 -0
  8. package/sdk/NOTICE +95 -0
  9. package/sdk/THIRD_PARTY_NOTICES.md +37 -0
  10. package/sdk/bun.lock +539 -0
  11. package/sdk/package.json +60 -0
  12. package/sdk/preview/fixtures/empty.json +6 -0
  13. package/sdk/preview/fonts/NotoSans-LICENSE.txt +94 -0
  14. package/sdk/preview/fonts/NotoSans-Regular.ttf +0 -0
  15. package/sdk/preview/fonts/NotoSansCJK-LICENSE.txt +92 -0
  16. package/sdk/preview/fonts/NotoSansCJKsc-Regular.otf +0 -0
  17. package/sdk/preview/fonts/PROVENANCE.md +25 -0
  18. package/sdk/preview/fonts/fonts.json +60 -0
  19. package/sdk/preview/profiles/default.json +32 -0
  20. package/sdk/preview/scenarios/counter-capture.json +9 -0
  21. package/sdk/smoke/solid-smoke.ts +53 -0
  22. package/sdk/smoke/tsconfig.smoke.json +21 -0
  23. package/src/application.ts +70 -0
  24. package/src/build.ts +963 -0
  25. package/src/check-smoke.ts +8 -0
  26. package/src/compiler.ts +701 -0
  27. package/src/css.ts +337 -0
  28. package/src/dev.ts +164 -0
  29. package/src/host.ts +578 -0
  30. package/src/identity.ts +60 -0
  31. package/src/index.ts +27 -0
  32. package/src/internal.ts +20 -0
  33. package/src/native-process.ts +178 -0
  34. package/src/package-app.ts +178 -0
  35. package/src/preview-check.ts +267 -0
  36. package/src/preview.ts +69 -0
  37. package/src/public-api.d.ts +258 -0
  38. package/src/publication.ts +108 -0
  39. package/src/sdk-packages.ts +376 -0
  40. package/src/sdk.ts +11 -0
  41. package/src/smoke.ts +99 -0
  42. package/src/sync-ui-resources.ts +171 -0
  43. package/src/typecheck.ts +177 -0
  44. package/src/validate.ts +1085 -0
  45. package/src/watch.ts +531 -0
package/src/build.ts ADDED
@@ -0,0 +1,963 @@
1
+ import type {
2
+ BuildApplicationOptions,
3
+ BuildInfo,
4
+ Capabilities,
5
+ FontDeclaration,
6
+ Manifest,
7
+ PublishedApplication,
8
+ WindowDeclaration,
9
+ WorkerDeclaration,
10
+ } from "./index.ts";
11
+ import { readFileSync, realpathSync, type Dirent } from "node:fs";
12
+ import { lstat, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
13
+ import { createRequire } from "node:module";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { compileBundle, compileWorkerBundle, type CompilationResult } from "./compiler.ts";
17
+ import { typecheckProject } from "./typecheck.ts";
18
+ import { canonicalJson, sha256, moduleIdentity } from "./identity.ts";
19
+ import { compileModuleBytecode, resolveNativeHost } from "./host.ts";
20
+ import { publishGeneration, resourcePath } from "./publication.ts";
21
+ import { syncCssModuleTypes, validateStylesheet } from "./css.ts";
22
+ import { workspaceRoot } from "./sdk.ts";
23
+ import { ensureSdkPackagesBuilt } from "./sdk-packages.ts";
24
+
25
+ export { publishGeneration };
26
+ export { workspaceRoot };
27
+ const require = createRequire(import.meta.url);
28
+
29
+ type ManifestIdentity = Omit<Manifest, "buildId">;
30
+
31
+ function readPackage(directory: string): { name?: unknown; version?: unknown } | undefined {
32
+ try {
33
+ return JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8"));
34
+ } catch (error) {
35
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
36
+ return undefined;
37
+ }
38
+ }
39
+
40
+ function resolveModule(from: NodeJS.Require, id: string): string | undefined {
41
+ try {
42
+ return from.resolve(id);
43
+ } catch (error) {
44
+ const { code } = error as NodeJS.ErrnoException;
45
+ if (code !== "MODULE_NOT_FOUND" && code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw error;
46
+ return undefined;
47
+ }
48
+ }
49
+
50
+ function packageVersion(from: NodeJS.Require, id: string): string | undefined {
51
+ const manifest = resolveModule(from, `${id}/package.json`);
52
+ if (manifest) return manifestVersion(JSON.parse(readFileSync(manifest, "utf8")), id);
53
+ const entry = resolveModule(from, id);
54
+ if (!entry) return undefined;
55
+ let directory = path.dirname(realpathSync(entry));
56
+ while (true) {
57
+ const pkg = readPackage(directory);
58
+ if (pkg?.name === id) return manifestVersion(pkg, id);
59
+ const parent = path.dirname(directory);
60
+ if (parent === directory) throw new Error(`Cannot locate package.json for ${id}`);
61
+ directory = parent;
62
+ }
63
+ }
64
+
65
+ const runtimePackages = new Set(["solid-js", "@solidjs/universal", "@solidjs/signals"]);
66
+
67
+ function bundledRuntimeVersions(modules: Iterable<string> = []): Map<string, string> {
68
+ const versions = new Map<string, string>();
69
+ const visited = new Set<string>();
70
+ for (const filename of modules) {
71
+ for (
72
+ let directory = path.dirname(filename);
73
+ !visited.has(directory);
74
+ directory = path.dirname(directory)
75
+ ) {
76
+ visited.add(directory);
77
+ const pkg = readPackage(directory);
78
+ if (typeof pkg?.name !== "string" || !pkg.name) continue;
79
+ if (runtimePackages.has(pkg.name) && !versions.has(pkg.name))
80
+ versions.set(pkg.name, manifestVersion(pkg, pkg.name));
81
+ break;
82
+ }
83
+ if (versions.size === runtimePackages.size) break;
84
+ }
85
+ return versions;
86
+ }
87
+
88
+ export async function optionalFile(filename: string): Promise<Buffer | undefined> {
89
+ try {
90
+ return await readFile(filename);
91
+ } catch (error) {
92
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
93
+ throw error;
94
+ }
95
+ }
96
+
97
+ export async function bundle(
98
+ entry: string,
99
+ {
100
+ root = workspaceRoot,
101
+ appDirectory = path.dirname(entry),
102
+ hostEntry = true,
103
+ filename = "app.mjs",
104
+ development = false,
105
+ }: BuildApplicationOptions & { hostEntry?: boolean; filename?: string } = {},
106
+ ): Promise<CompilationResult> {
107
+ await ensureSdkPackagesBuilt(root);
108
+ return compileBundle(entry, {
109
+ root,
110
+ appDirectory,
111
+ hostEntry,
112
+ filename,
113
+ development,
114
+ });
115
+ }
116
+
117
+ function manifestVersion(manifest: unknown, id: string): string {
118
+ if (
119
+ manifest &&
120
+ typeof manifest === "object" &&
121
+ "version" in manifest &&
122
+ typeof manifest.version === "string"
123
+ ) {
124
+ return manifest.version;
125
+ }
126
+ throw new Error(`Missing package.json version for ${id}`);
127
+ }
128
+
129
+ export function dependencyVersions({
130
+ root = workspaceRoot,
131
+ appDirectory = root,
132
+ modules,
133
+ }: Pick<BuildApplicationOptions, "root" | "appDirectory"> & {
134
+ modules?: Iterable<string>;
135
+ } = {}): Record<string, string> {
136
+ const bundled = bundledRuntimeVersions(modules);
137
+ const appRequire = createRequire(path.resolve(appDirectory, "package.json"));
138
+ const rootRequire = createRequire(path.resolve(root, "package.json"));
139
+ const universalFromUi = (from: NodeJS.Require) => {
140
+ const ui = resolveModule(from, "@hewel/zgui");
141
+ return ui && packageVersion(createRequire(realpathSync(ui)), "@solidjs/universal");
142
+ };
143
+ const signalsFromSolid = (from: NodeJS.Require) => {
144
+ const solid = resolveModule(from, "solid-js/package.json");
145
+ return solid && packageVersion(createRequire(solid), "@solidjs/signals");
146
+ };
147
+ const solid =
148
+ bundled.get("solid-js") ??
149
+ packageVersion(appRequire, "solid-js") ??
150
+ manifestVersion(require("solid-js/package.json"), "solid-js");
151
+ const universal =
152
+ bundled.get("@solidjs/universal") ??
153
+ packageVersion(appRequire, "@solidjs/universal") ??
154
+ universalFromUi(appRequire) ??
155
+ packageVersion(rootRequire, "@solidjs/universal") ??
156
+ universalFromUi(rootRequire);
157
+ const signals =
158
+ bundled.get("@solidjs/signals") ??
159
+ packageVersion(appRequire, "@solidjs/signals") ??
160
+ signalsFromSolid(appRequire) ??
161
+ signalsFromSolid(require);
162
+ if (signals === undefined) throw new Error("Cannot locate @solidjs/signals");
163
+ const solidCompiler = packageVersion(require, "@solidjs/compiler");
164
+ if (solidCompiler === undefined) throw new Error("Cannot locate @solidjs/compiler");
165
+ return Object.fromEntries([
166
+ ["solid-js", solid],
167
+ ["@solidjs/signals", signals],
168
+ ["@solidjs/compiler", solidCompiler],
169
+ ...["lightningcss", "rolldown", "tsrs"].map(
170
+ name => [name, manifestVersion(require(`${name}/package.json`), name)] as const,
171
+ ),
172
+ ...(universal === undefined ? [] : [["@solidjs/universal", universal] as const]),
173
+ ]);
174
+ }
175
+
176
+ export async function buildInfo(
177
+ root: string,
178
+ result: CompilationResult,
179
+ { appDirectory = root, development = false } = {},
180
+ ): Promise<BuildInfo> {
181
+ const cargoLock = await Bun.file(path.join(root, "Cargo.lock")).text();
182
+ const revision = cargoLock.match(
183
+ /name = "rquickjs-sys"\nversion = "([^"]+)"\nsource = "[^"\n]+#([a-f0-9]+)"/,
184
+ );
185
+ // This gitlink was verified against the pinned rquickjs checkout, not inferred from its crate version.
186
+ const engines: Record<string, string | undefined> = {
187
+ "73fcd6062ee615aeb2a4675cd32be67a56e93973": "6d46d07d04041b40f4f49eaa7fdebe44c314c699",
188
+ };
189
+ const engineRevision = revision && engines[revision[2]];
190
+ if (!revision || !engineRevision)
191
+ throw new Error(
192
+ "Unknown resolved rquickjs engine; audit its QuickJS-NG gitlink before packaging",
193
+ );
194
+ const packageJson = (await Bun.file(path.join(root, "package.json")).json()) as {
195
+ packageManager: string;
196
+ };
197
+ const identity = (filename: string) => moduleIdentity(filename, { root, appDirectory });
198
+ return {
199
+ schemaVersion: 2,
200
+ hostApiVersion: 1,
201
+ bun: Bun.version,
202
+ packageManager: packageJson.packageManager,
203
+ packages: dependencyVersions({ root, appDirectory, modules: result.graph.modules }),
204
+ lockfile: {
205
+ path: "bun.lock",
206
+ digest: sha256(await Bun.file(path.join(root, "bun.lock")).bytes()),
207
+ },
208
+ cargoLock: { path: "Cargo.lock", digest: sha256(cargoLock) },
209
+ engine: {
210
+ name: "QuickJS-NG",
211
+ revision: engineRevision,
212
+ rquickjsVersion: revision[1],
213
+ rquickjsRevision: revision[2],
214
+ },
215
+ conditions: development ? ["development", "browser"] : ["browser", "production"],
216
+ target: "es2022",
217
+ solidRuntime: identity(result.solidRuntime),
218
+ graph: {
219
+ modules: result.graph.modules.map(identity).sort(),
220
+ chunks: result.graph.chunks.map(chunk => ({
221
+ ...chunk,
222
+ modules: chunk.modules.map(identity).sort(),
223
+ })),
224
+ },
225
+ styleSystem: result.styleSystem,
226
+ };
227
+ }
228
+
229
+ async function collectAssets(directory: string, prefix = "assets"): Promise<Map<string, Buffer>> {
230
+ let entries: Dirent[];
231
+ try {
232
+ if (!(await lstat(directory)).isDirectory())
233
+ throw new Error(`Assets must be regular files/directories, not links: ${prefix}`);
234
+ entries = await readdir(directory, { withFileTypes: true });
235
+ } catch (error) {
236
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return new Map();
237
+ throw error;
238
+ }
239
+ const files = new Map<string, Buffer>();
240
+ for (const entry of entries) {
241
+ const relative = resourcePath(`${prefix}/${entry.name}`);
242
+ const absolute = path.join(directory, entry.name);
243
+ if (entry.isDirectory()) {
244
+ for (const item of await collectAssets(absolute, relative)) files.set(...item);
245
+ } else if (entry.isFile()) files.set(relative, await readFile(absolute));
246
+ else throw new Error(`Assets must be regular files, not links/devices: ${relative}`);
247
+ }
248
+ return files;
249
+ }
250
+
251
+ // Identity covers every packaged byte through artifactDigests, including provenance/build info.
252
+ export function contentDigest(
253
+ files: ReadonlyMap<string, Uint8Array>,
254
+ manifest: ManifestIdentity & { buildId?: string },
255
+ ): string {
256
+ const { buildId: _buildId, ...identity } = manifest;
257
+ const names = Object.keys(manifest.artifactDigests).sort();
258
+ const packaged = [...files.keys()].filter(name => name !== "manifest.json").sort();
259
+ if (JSON.stringify(names) !== JSON.stringify(packaged))
260
+ throw new Error("Artifact digest inventory does not match packaged files");
261
+ for (const name of names) {
262
+ resourcePath(name);
263
+ const bytes = files.get(name);
264
+ if (!bytes) throw new Error(`Missing package resource: ${name}`);
265
+ if (sha256(bytes) !== manifest.artifactDigests[name])
266
+ throw new Error(`Artifact digest mismatch: ${name}`);
267
+ }
268
+ return sha256(canonicalJson(identity));
269
+ }
270
+
271
+ export async function buildApplication(
272
+ app: string,
273
+ {
274
+ root = workspaceRoot,
275
+ appDirectory = path.join(root, "apps/examples", app),
276
+ development = false,
277
+ bytecode = false,
278
+ hostRoot,
279
+ hostExecutable,
280
+ hostSearchFrom,
281
+ extraCapabilities,
282
+ capabilitiesFile,
283
+ }: BuildApplicationOptions = {},
284
+ ): Promise<PublishedApplication> {
285
+ if (!/^[a-z][a-z0-9-]*$/.test(app)) throw new Error(`Invalid application name: ${app}`);
286
+ root = path.resolve(root);
287
+ appDirectory = path.resolve(appDirectory);
288
+ await ensureSdkPackagesBuilt(root);
289
+ await syncCssModuleTypes(appDirectory, { root });
290
+ typecheckProject(path.join(appDirectory, "tsconfig.json"));
291
+ const result = await bundle(path.join(appDirectory, "src/main.tsx"), {
292
+ root,
293
+ appDirectory,
294
+ development,
295
+ });
296
+ return publishApplication(app, result, {
297
+ root,
298
+ appDirectory,
299
+ development,
300
+ bytecode,
301
+ hostRoot,
302
+ hostExecutable,
303
+ hostSearchFrom,
304
+ extraCapabilities,
305
+ capabilitiesFile,
306
+ });
307
+ }
308
+
309
+ function isFontDeclaration(font: unknown): font is FontDeclaration {
310
+ return (
311
+ !!font &&
312
+ typeof font === "object" &&
313
+ "family" in font &&
314
+ typeof font.family === "string" &&
315
+ !!font.family.trim() &&
316
+ font.family === font.family.trim() &&
317
+ "path" in font &&
318
+ typeof font.path === "string" &&
319
+ Object.keys(font).every(key => key === "family" || key === "path")
320
+ );
321
+ }
322
+
323
+ function capabilityString(value: unknown): value is string {
324
+ if (typeof value !== "string") return false;
325
+ let nonspace = false;
326
+ for (const char of value) {
327
+ const code = char.charCodeAt(0);
328
+ if (
329
+ code < 32 ||
330
+ (code >= 127 && code <= 159) ||
331
+ (char.length === 1 && code >= 0xd800 && code <= 0xdfff)
332
+ )
333
+ return false;
334
+ nonspace ||= code !== 32;
335
+ }
336
+ return nonspace;
337
+ }
338
+
339
+ function capabilityPath(value: string): boolean {
340
+ if (value === "/") return true;
341
+ if (value.includes("\\")) return false;
342
+ const parts = value.split("/");
343
+ const root = parts.shift();
344
+ const template = root === "$XDG_RUNTIME_DIR" || root === "$HOME" || root === "$XDG_DATA_HOME";
345
+ return (
346
+ (root === "" || template) &&
347
+ parts.every(
348
+ part =>
349
+ part !== "" &&
350
+ part !== "." &&
351
+ part !== ".." &&
352
+ (!template ||
353
+ part === "$WAYLAND_DISPLAY" ||
354
+ !part.replaceAll("${WAYLAND_DISPLAY}", "").includes("$")),
355
+ )
356
+ );
357
+ }
358
+
359
+ function fileDirectoryPath(value: string): boolean {
360
+ if (value === "/") return true;
361
+ if (value.includes("\\")) return false;
362
+ const parts = value.split("/");
363
+ const root = parts.shift();
364
+ const template = root === "$HOME" || root === "$XDG_DATA_HOME" || root === "$XDG_DOCUMENTS_DIR";
365
+ return (
366
+ (root === "" || template) &&
367
+ parts.every(part => part !== "" && part !== "." && part !== ".." && !part.includes("$"))
368
+ );
369
+ }
370
+
371
+ function isPrivateIpv4(host: string): boolean {
372
+ const parts = host.split(".");
373
+ if (parts.length !== 4 || !parts.every(p => /^\d{1,3}$/.test(p))) return false;
374
+ const nums = parts.map(Number);
375
+ if (nums.some(n => n > 255)) return false;
376
+ const [a, b] = nums as [number, number, number, number];
377
+ return (
378
+ a === 0 ||
379
+ a === 10 ||
380
+ a === 127 ||
381
+ (a === 100 && b >= 64 && b <= 127) ||
382
+ (a === 169 && b === 254) ||
383
+ (a === 172 && b >= 16 && b <= 31) ||
384
+ (a === 192 && b === 168) ||
385
+ a >= 224
386
+ );
387
+ }
388
+
389
+ function isPrivateHost(hostname: string): boolean {
390
+ const bare =
391
+ hostname.startsWith("[") && hostname.endsWith("]")
392
+ ? hostname.slice(1, -1).toLowerCase()
393
+ : hostname.toLowerCase();
394
+ if (bare === "localhost" || bare.endsWith(".localhost")) return true;
395
+ if (isPrivateIpv4(bare)) return true;
396
+ if (bare.includes(":")) {
397
+ // Reject loopback, unspecified, ULA (fc00::/7), link-local (fe80::/10), multicast (ff00::/8),
398
+ // and IPv4-mapped IPv6 addresses unless allowPrivateNetworks is explicitly opted in.
399
+ if (bare === "::1" || bare === "::") return true;
400
+ const first = bare.split(":")[0] ?? "";
401
+ const head = Number.parseInt(first || "0", 16);
402
+ if (!Number.isNaN(head)) {
403
+ if ((head & 0xfe00) === 0xfc00) return true;
404
+ if ((head & 0xffc0) === 0xfe80) return true;
405
+ if ((head & 0xff00) === 0xff00) return true;
406
+ }
407
+ if (bare.startsWith("::ffff:")) {
408
+ const mapped = bare.slice("::ffff:".length);
409
+ if (isPrivateIpv4(mapped)) return true;
410
+ // Also handle hex form e.g. ::ffff:7f00:1 produced by WHATWG URL parser
411
+ const hexParts = mapped.split(":");
412
+ if (hexParts.length === 2) {
413
+ const hi = Number.parseInt(hexParts[0]!, 16);
414
+ const lo = Number.parseInt(hexParts[1]!, 16);
415
+ if (!Number.isNaN(hi) && !Number.isNaN(lo)) {
416
+ const ipv4 = `${(hi >> 8) & 255}.${hi & 255}.${(lo >> 8) & 255}.${lo & 255}`;
417
+ if (isPrivateIpv4(ipv4)) return true;
418
+ }
419
+ }
420
+ }
421
+ }
422
+ return false;
423
+ }
424
+
425
+ function parseNetworkOrigin(
426
+ entry: unknown,
427
+ field: string,
428
+ ): {
429
+ canonical: string;
430
+ insecure: boolean;
431
+ host: string;
432
+ } {
433
+ if (!capabilityString(entry) || entry !== entry.trim() || entry.includes("*")) {
434
+ throw new Error(`${field} contains invalid origin ${JSON.stringify(entry)}`);
435
+ }
436
+ let parsed: URL;
437
+ try {
438
+ parsed = new URL(entry);
439
+ } catch {
440
+ throw new Error(`${field} contains invalid origin ${JSON.stringify(entry)}`);
441
+ }
442
+ const scheme = parsed.protocol.slice(0, -1).toLowerCase();
443
+ if (scheme !== "https" && scheme !== "http" && scheme !== "wss" && scheme !== "ws") {
444
+ throw new Error(`${field} origin scheme must be https, http, wss, or ws: ${entry}`);
445
+ }
446
+ if (parsed.username || parsed.password) {
447
+ throw new Error(`${field} origin must not include userinfo: ${entry}`);
448
+ }
449
+ if (parsed.search || parsed.hash) {
450
+ throw new Error(`${field} origin must not include query or fragment: ${entry}`);
451
+ }
452
+ const afterScheme = entry.slice(entry.indexOf("://") + 3);
453
+ if (afterScheme.includes("/") || afterScheme.includes("?") || afterScheme.includes("#")) {
454
+ throw new Error(`${field} origin must not include a path, query, or fragment: ${entry}`);
455
+ }
456
+ const host = parsed.hostname.toLowerCase();
457
+ if (!host) {
458
+ throw new Error(`${field} origin must include a host: ${entry}`);
459
+ }
460
+ const defaultPort = scheme === "https" || scheme === "wss" ? 443 : 80;
461
+ const port = parsed.port ? Number(parsed.port) : defaultPort;
462
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
463
+ throw new Error(`${field} origin has invalid port: ${entry}`);
464
+ }
465
+ const canonical = port === defaultPort ? `${scheme}://${host}` : `${scheme}://${host}:${port}`;
466
+ return { canonical, insecure: scheme === "http" || scheme === "ws", host };
467
+ }
468
+
469
+ function parseCapabilities(input: unknown, source: string): Capabilities {
470
+ if (input !== undefined && (input === null || typeof input !== "object" || Array.isArray(input)))
471
+ throw new Error(`${source} must be an object`);
472
+
473
+ const capabilities = Object.create(null) as Capabilities;
474
+ for (const [key, value] of Object.entries(input ?? {}) as [string, unknown][]) {
475
+ const field = `${source}.${key}`;
476
+ switch (key) {
477
+ case "shellSurfaces":
478
+ case "sessionLock":
479
+ case "controlChannel":
480
+ if (typeof value !== "boolean") throw new Error(`${field} must be a boolean`);
481
+ if (value) capabilities[key] = true;
482
+ break;
483
+ case "clipboard": {
484
+ if (!value || typeof value !== "object" || Array.isArray(value))
485
+ throw new Error(`${field} must be an object`);
486
+ for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
487
+ if (subKey !== "read") throw new Error(`Unknown capability: ${field}.${subKey}`);
488
+ if (typeof subVal !== "boolean") throw new Error(`${field}.read must be a boolean`);
489
+ if (subVal) capabilities.clipboard = { read: true };
490
+ }
491
+ break;
492
+ }
493
+ case "sqlite": {
494
+ if (!value || typeof value !== "object" || Array.isArray(value))
495
+ throw new Error(`${field} must be an object`);
496
+ for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
497
+ if (subKey !== "databases") throw new Error(`Unknown capability: ${field}.${subKey}`);
498
+ if (!Array.isArray(subVal)) throw new Error(`${field}.databases must be an array`);
499
+ const names = new Set<string>();
500
+ for (const item of subVal as unknown[]) {
501
+ if (typeof item !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(item))
502
+ throw new Error(`${field}.databases contains invalid entries`);
503
+ if (names.has(item)) throw new Error(`${field}.databases contains duplicates`);
504
+ names.add(item);
505
+ }
506
+ if (names.size) capabilities.sqlite = { databases: [...names] };
507
+ }
508
+ break;
509
+ }
510
+ case "files": {
511
+ if (!value || typeof value !== "object" || Array.isArray(value))
512
+ throw new Error(`${field} must be an object`);
513
+ for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
514
+ if (subKey !== "directories") throw new Error(`Unknown capability: ${field}.${subKey}`);
515
+ if (!Array.isArray(subVal)) throw new Error(`${field}.directories must be an array`);
516
+ const seen = new Set<string>();
517
+ const dirs: { path: string; mode: "read" | "readwrite" }[] = [];
518
+ for (const item of subVal as unknown[]) {
519
+ if (!item || typeof item !== "object" || Array.isArray(item))
520
+ throw new Error(`${field}.directories entries must be objects`);
521
+ const record = item as Record<string, unknown>;
522
+ const keys = Object.keys(record);
523
+ if (!keys.every(k => k === "path" || k === "mode"))
524
+ throw new Error(`${field}.directories entry contains unknown keys`);
525
+ if (
526
+ !capabilityString(record.path) ||
527
+ !fileDirectoryPath(record.path) ||
528
+ (record.mode !== "read" && record.mode !== "readwrite")
529
+ )
530
+ throw new Error(`${field}.directories contains invalid entries`);
531
+ if (seen.has(record.path))
532
+ throw new Error(`${field}.directories contains duplicate path ${record.path}`);
533
+ seen.add(record.path);
534
+ dirs.push({ path: record.path, mode: record.mode });
535
+ }
536
+ if (dirs.length) capabilities.files = { directories: dirs };
537
+ }
538
+ break;
539
+ }
540
+ case "network": {
541
+ if (!value || typeof value !== "object" || Array.isArray(value))
542
+ throw new Error(`${field} must be an object`);
543
+ const network: {
544
+ origins?: string[];
545
+ allowInsecureHttp?: boolean;
546
+ allowPrivateNetworks?: boolean;
547
+ } = {};
548
+ for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
549
+ switch (subKey) {
550
+ case "origins": {
551
+ if (!Array.isArray(subVal)) throw new Error(`${field}.origins must be an array`);
552
+ const origins = new Set<string>();
553
+ for (const item of subVal as unknown[]) {
554
+ const parsed = parseNetworkOrigin(item, `${field}.origins`);
555
+ if (origins.has(parsed.canonical))
556
+ throw new Error(`${field}.origins contains duplicate origin ${parsed.canonical}`);
557
+ origins.add(parsed.canonical);
558
+ }
559
+ if (origins.size) network.origins = [...origins];
560
+ break;
561
+ }
562
+ case "allowInsecureHttp":
563
+ case "allowPrivateNetworks": {
564
+ if (typeof subVal !== "boolean")
565
+ throw new Error(`${field}.${subKey} must be a boolean`);
566
+ if (subVal) network[subKey] = true;
567
+ break;
568
+ }
569
+ default:
570
+ throw new Error(`Unknown capability: ${field}.${subKey}`);
571
+ }
572
+ }
573
+ if (Object.keys(network).length) capabilities.network = network;
574
+ break;
575
+ }
576
+ case "imagePrefixes":
577
+ case "unixSockets":
578
+ case "commands":
579
+ case "namedSockets": {
580
+ if (!Array.isArray(value)) throw new Error(`${field} must be an array`);
581
+ const entries = new Set<string>();
582
+ for (const item of value as unknown[]) {
583
+ if (
584
+ !capabilityString(item) ||
585
+ (key === "namedSockets" && !/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(item)) ||
586
+ ((key === "imagePrefixes" || key === "unixSockets") && !capabilityPath(item))
587
+ )
588
+ throw new Error(`${field} contains invalid entries`);
589
+ if (entries.has(item)) throw new Error(`${field} contains duplicates`);
590
+ entries.add(item);
591
+ }
592
+ if (entries.size) capabilities[key] = [...entries];
593
+ break;
594
+ }
595
+ default:
596
+ throw new Error(`Unknown capability: ${field}`);
597
+ }
598
+ }
599
+ return capabilities;
600
+ }
601
+
602
+ function capabilityOverlay(input: unknown, source: string): Capabilities {
603
+ if (
604
+ input !== null &&
605
+ typeof input === "object" &&
606
+ "sessionLock" in input &&
607
+ input.sessionLock === true
608
+ )
609
+ throw new Error(`${source}.sessionLock: true may only be declared in base package.json`);
610
+ return parseCapabilities(input, source);
611
+ }
612
+
613
+ async function mergeCapabilities(
614
+ input: unknown,
615
+ {
616
+ extraCapabilities,
617
+ capabilitiesFile,
618
+ }: Pick<BuildApplicationOptions, "extraCapabilities" | "capabilitiesFile">,
619
+ ): Promise<Capabilities | undefined> {
620
+ const base = parseCapabilities(input, "package.json zgui.capabilities");
621
+ const sources = [base, capabilityOverlay(extraCapabilities, "extraCapabilities")];
622
+ if (capabilitiesFile !== undefined) {
623
+ const filename = path.resolve(capabilitiesFile);
624
+ const source = `capabilitiesFile (${filename})`;
625
+ let overlay: unknown;
626
+ try {
627
+ overlay = JSON.parse(await readFile(filename, "utf8"));
628
+ } catch (error) {
629
+ const message = error instanceof Error ? error.message : String(error);
630
+ throw new Error(`${source}: cannot read JSON: ${message}`, { cause: error });
631
+ }
632
+ sources.push(capabilityOverlay(overlay, source));
633
+ }
634
+ const merged: Capabilities = {};
635
+ for (const key of ["shellSurfaces", "controlChannel"] as const)
636
+ if (sources.some(source => source[key])) merged[key] = true;
637
+ if (base.sessionLock) merged.sessionLock = true;
638
+ for (const key of ["imagePrefixes", "unixSockets", "namedSockets", "commands"] as const) {
639
+ const union = new Set(sources.flatMap(source => source[key] ?? []));
640
+ if (union.size) merged[key] = [...union].sort();
641
+ }
642
+ if (sources.some(source => source.clipboard?.read)) merged.clipboard = { read: true };
643
+ const sqliteDatabases = new Set(sources.flatMap(source => source.sqlite?.databases ?? []));
644
+ if (sqliteDatabases.size) merged.sqlite = { databases: [...sqliteDatabases].sort() };
645
+ const fileDirs = new Map<string, "read" | "readwrite">();
646
+ for (const grant of sources.flatMap(source => source.files?.directories ?? [])) {
647
+ const existing = fileDirs.get(grant.path);
648
+ if (!existing || grant.mode === "readwrite") fileDirs.set(grant.path, grant.mode);
649
+ }
650
+ if (fileDirs.size) {
651
+ merged.files = {
652
+ directories: [...fileDirs.entries()]
653
+ .sort(([a], [b]) => a.localeCompare(b))
654
+ .map(([dirPath, mode]) => ({ path: dirPath, mode })),
655
+ };
656
+ }
657
+ const allowInsecureHttp = sources.some(source => source.network?.allowInsecureHttp);
658
+ const allowPrivateNetworks = sources.some(source => source.network?.allowPrivateNetworks);
659
+ const networkOrigins = new Set(sources.flatMap(source => source.network?.origins ?? []));
660
+ for (const origin of networkOrigins) {
661
+ const parsed = parseNetworkOrigin(origin, "capabilities.network.origins");
662
+ if (parsed.insecure && !allowInsecureHttp) {
663
+ throw new Error(
664
+ `capabilities.network.origins contains insecure origin ${origin} without allowInsecureHttp: true`,
665
+ );
666
+ }
667
+ if (isPrivateHost(parsed.host) && !allowPrivateNetworks) {
668
+ throw new Error(
669
+ `capabilities.network.origins contains private/loopback origin ${origin} without allowPrivateNetworks: true`,
670
+ );
671
+ }
672
+ }
673
+ if (networkOrigins.size || allowInsecureHttp || allowPrivateNetworks) {
674
+ merged.network = {
675
+ ...(networkOrigins.size ? { origins: [...networkOrigins].sort() } : {}),
676
+ ...(allowInsecureHttp ? { allowInsecureHttp: true } : {}),
677
+ ...(allowPrivateNetworks ? { allowPrivateNetworks: true } : {}),
678
+ };
679
+ }
680
+ return Object.keys(merged).length ? merged : undefined;
681
+ }
682
+
683
+ const WINDOW_KEYS = new Set(["title", "width", "height", "minWidth", "minHeight", "resizable"]);
684
+
685
+ function parseWindowDeclaration(input: unknown): WindowDeclaration | undefined {
686
+ if (input === undefined) return undefined;
687
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
688
+ throw new Error("package.json zgui.window must be an object");
689
+ }
690
+ const record = input as Record<string, unknown>;
691
+ for (const key of Object.keys(record)) {
692
+ if (!WINDOW_KEYS.has(key)) throw new Error(`Unknown package.json zgui.window key: ${key}`);
693
+ }
694
+ const result: WindowDeclaration = {};
695
+ if (record.title !== undefined) {
696
+ if (!capabilityString(record.title) || record.title !== record.title.trim()) {
697
+ throw new Error(
698
+ "package.json zgui.window.title must be a non-empty, trimmed string without control characters",
699
+ );
700
+ }
701
+ result.title = record.title;
702
+ }
703
+ for (const key of ["width", "height", "minWidth", "minHeight"] as const) {
704
+ const value = record[key];
705
+ if (value !== undefined) {
706
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 16384) {
707
+ throw new Error(`package.json zgui.window.${key} must be an integer between 1 and 16384`);
708
+ }
709
+ result[key] = value;
710
+ }
711
+ }
712
+ if (record.resizable !== undefined) {
713
+ if (typeof record.resizable !== "boolean") {
714
+ throw new Error("package.json zgui.window.resizable must be a boolean");
715
+ }
716
+ result.resizable = record.resizable;
717
+ }
718
+ return Object.keys(result).length ? result : undefined;
719
+ }
720
+
721
+ const WORKER_NAME_RE = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
722
+ const MAX_WORKERS = 32;
723
+
724
+ function parseWorkerDeclarations(
725
+ input: unknown,
726
+ appDirectory: string,
727
+ ): { name: string; entry: string }[] {
728
+ if (input === undefined) return [];
729
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
730
+ throw new Error(
731
+ "package.json zgui.workers must be an object mapping worker names to relative entry paths",
732
+ );
733
+ }
734
+ const entries = Object.entries(input as Record<string, unknown>);
735
+ if (entries.length > MAX_WORKERS) {
736
+ throw new Error(`package.json zgui.workers exceeds maximum of ${MAX_WORKERS} workers`);
737
+ }
738
+ const resolvedAppDir = path.resolve(appDirectory);
739
+ const parsed: { name: string; entry: string }[] = [];
740
+ for (const [name, relPath] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
741
+ if (!WORKER_NAME_RE.test(name)) {
742
+ throw new Error(`Invalid compute worker name: ${name}`);
743
+ }
744
+ if (typeof relPath !== "string" || !relPath.trim()) {
745
+ throw new Error(`package.json zgui.workers.${name} must be a non-empty relative path`);
746
+ }
747
+ resourcePath(relPath);
748
+ const fullPath = path.resolve(resolvedAppDir, relPath);
749
+ if (!fullPath.startsWith(`${resolvedAppDir}${path.sep}`)) {
750
+ throw new Error(
751
+ `package.json zgui.workers.${name} escapes application directory: ${relPath}`,
752
+ );
753
+ }
754
+ parsed.push({ name, entry: fullPath });
755
+ }
756
+ return parsed;
757
+ }
758
+
759
+ export async function publishApplication(
760
+ app: string,
761
+ result: CompilationResult,
762
+ {
763
+ root,
764
+ appDirectory,
765
+ signal,
766
+ development = false,
767
+ bytecode = false,
768
+ hostRoot,
769
+ hostExecutable,
770
+ hostSearchFrom,
771
+ extraCapabilities,
772
+ capabilitiesFile,
773
+ }: BuildApplicationOptions & { root: string; appDirectory: string; signal?: AbortSignal },
774
+ ): Promise<PublishedApplication> {
775
+ signal?.throwIfAborted();
776
+ const files = new Map(result.files);
777
+ const moduleStyles = files.get("app.css");
778
+ if (!moduleStyles || !result.styleSystem)
779
+ throw new Error("Missing Lightning CSS compilation output");
780
+ const componentsCss = files.get("components.css");
781
+ if (componentsCss !== undefined) {
782
+ validateStylesheet(componentsCss.toString("utf8"), "components.css");
783
+ }
784
+ const globalCssFile = await optionalFile(path.join(appDirectory, "src/app.css"));
785
+ const globalCss =
786
+ globalCssFile !== undefined
787
+ ? validateStylesheet(globalCssFile.toString("utf8"), "app.css")
788
+ : "";
789
+ const modulesCss = moduleStyles.toString("utf8").trim();
790
+ const mergedAppCssParts = [globalCss, modulesCss].filter(part => part.length > 0);
791
+ const mergedAppCss = mergedAppCssParts.length > 0 ? `${mergedAppCssParts.join("\n\n")}\n` : "";
792
+ files.set("app.css", Buffer.from(mergedAppCss, "utf8"));
793
+ const assets = await collectAssets(path.join(appDirectory, "assets"));
794
+ for (const item of assets) files.set(...item);
795
+ const pkg = await optionalFile(path.join(appDirectory, "package.json"));
796
+ const packageJson:
797
+ | {
798
+ zgui?: {
799
+ id?: unknown;
800
+ fonts?: unknown;
801
+ capabilities?: unknown;
802
+ window?: unknown;
803
+ workers?: unknown;
804
+ };
805
+ }
806
+ | undefined = pkg && JSON.parse(pkg.toString("utf8"));
807
+ const id = packageJson?.zgui?.id === undefined ? `dev.example.${app}` : packageJson.zgui.id;
808
+ if (!capabilityString(id) || id !== id.trim())
809
+ throw new Error(
810
+ "package.json zgui.id must be a non-empty, trimmed string without control characters",
811
+ );
812
+ const windowConfig = parseWindowDeclaration(packageJson?.zgui?.window);
813
+ const capabilities = await mergeCapabilities(packageJson?.zgui?.capabilities, {
814
+ extraCapabilities,
815
+ capabilitiesFile,
816
+ });
817
+ const workerEntries = parseWorkerDeclarations(packageJson?.zgui?.workers, appDirectory);
818
+ const workers: WorkerDeclaration[] = [];
819
+ for (const worker of workerEntries) {
820
+ signal?.throwIfAborted();
821
+ const compiled = await compileWorkerBundle(worker.entry, {
822
+ root,
823
+ appDirectory,
824
+ name: worker.name,
825
+ development,
826
+ });
827
+ for (const [fileName, bytes] of compiled.files) {
828
+ files.set(fileName, bytes);
829
+ }
830
+ workers.push({ name: compiled.name, path: compiled.path, sourceMap: compiled.sourceMap });
831
+ }
832
+ const declarations = packageJson?.zgui?.fonts ?? [];
833
+ if (!Array.isArray(declarations))
834
+ throw new Error("package.json zgui.fonts must be an array of {family,path}");
835
+ const fonts: FontDeclaration[] = [];
836
+ const families = new Set<string>();
837
+ for (const font of declarations as unknown[]) {
838
+ if (!isFontDeclaration(font))
839
+ throw new Error("Invalid application font mapping; expected {family,path}");
840
+ resourcePath(font.path);
841
+ if (!assets.has(font.path)) throw new Error(`Font path must be a declared asset: ${font.path}`);
842
+ const family = font.family.toLowerCase();
843
+ if (families.has(family)) throw new Error(`Duplicate application font family: ${font.family}`);
844
+ families.add(family);
845
+ fonts.push(font);
846
+ }
847
+ files.set(
848
+ "build-info.json",
849
+ Buffer.from(
850
+ JSON.stringify(await buildInfo(root, result, { appDirectory, development }), null, 2) + "\n",
851
+ ),
852
+ );
853
+ const chunks = result.graph.chunks
854
+ .map(chunk => chunk.fileName)
855
+ .filter(fileName => fileName !== "app.mjs")
856
+ .sort()
857
+ .map(chunkPath => ({ path: chunkPath, sourceMap: `${chunkPath}.map` }));
858
+ let entryPath = "app.mjs";
859
+ let bytecodeMeta: { bytecodeFormat: "qjs-bytecode-v1"; quickjsAbi: string } | undefined;
860
+ let finalChunks = chunks;
861
+ let finalWorkers = workers;
862
+ if (bytecode) {
863
+ const host = await resolveNativeHost({
864
+ hostExecutable,
865
+ hostRoot,
866
+ root,
867
+ cwd: appDirectory,
868
+ searchFrom: [...(hostSearchFrom ?? []), import.meta.url],
869
+ signal,
870
+ });
871
+ const bytecodeFormat = host.abi?.bytecodeFormat;
872
+ const quickjsAbi = host.abi?.quickjsAbi;
873
+ if (bytecodeFormat !== "qjs-bytecode-v1" || !quickjsAbi) {
874
+ throw new Error(
875
+ `Resolved zgui-host (${host.executable}) does not report qjs-bytecode-v1 ABI metadata for --bytecode compilation`,
876
+ );
877
+ }
878
+ const tempDir = await mkdtemp(path.join(os.tmpdir(), "zgui-bytecode-"));
879
+ try {
880
+ const toBytecodePath = (jsPath: string): string => {
881
+ if (!jsPath.endsWith(".mjs")) {
882
+ throw new Error(`Expected .mjs module path for bytecode compilation: ${jsPath}`);
883
+ }
884
+ return `${jsPath.slice(0, -4)}.qjsb`;
885
+ };
886
+ const sourceDir = path.join(tempDir, "src");
887
+ const outDir = path.join(tempDir, "out");
888
+ const modulePaths = [
889
+ "app.mjs",
890
+ ...chunks.map(chunk => chunk.path),
891
+ ...workers.map(worker => worker.path),
892
+ ];
893
+ for (const jsPath of modulePaths) {
894
+ const jsBytes = files.get(jsPath);
895
+ if (!jsBytes) throw new Error(`Missing compiled JS module for bytecode: ${jsPath}`);
896
+ const dest = path.join(sourceDir, jsPath);
897
+ await mkdir(path.dirname(dest), { recursive: true });
898
+ await writeFile(dest, jsBytes);
899
+ }
900
+ const compileFile = async (jsPath: string): Promise<string> => {
901
+ const bcPath = toBytecodePath(jsPath);
902
+ const inPath = path.join(sourceDir, jsPath);
903
+ const outPath = path.join(outDir, bcPath);
904
+ const bcBytes = await compileModuleBytecode(host.executable, {
905
+ input: inPath,
906
+ output: outPath,
907
+ moduleName: jsPath,
908
+ sourceDir,
909
+ signal,
910
+ });
911
+ files.delete(jsPath);
912
+ files.set(bcPath, bcBytes);
913
+ return bcPath;
914
+ };
915
+ entryPath = await compileFile("app.mjs");
916
+ finalChunks = [];
917
+ for (const chunk of chunks) {
918
+ finalChunks.push({
919
+ path: await compileFile(chunk.path),
920
+ sourceMap: chunk.sourceMap,
921
+ });
922
+ }
923
+ finalWorkers = [];
924
+ for (const worker of workers) {
925
+ finalWorkers.push({
926
+ name: worker.name,
927
+ path: await compileFile(worker.path),
928
+ sourceMap: worker.sourceMap,
929
+ });
930
+ }
931
+ bytecodeMeta = { bytecodeFormat: "qjs-bytecode-v1", quickjsAbi };
932
+ } finally {
933
+ await rm(tempDir, { recursive: true, force: true });
934
+ }
935
+ }
936
+ const identity: ManifestIdentity = {
937
+ schemaVersion: 2,
938
+ id,
939
+ hostApiVersion: 1,
940
+ entry: entryPath,
941
+ sourceMap: "app.mjs.map",
942
+ ...(bytecodeMeta ?? {}),
943
+ ...(finalChunks.length > 0 ? { chunks: finalChunks } : {}),
944
+ ...(finalWorkers.length > 0 ? { workers: finalWorkers } : {}),
945
+ styles: [...(componentsCss !== undefined ? ["components.css"] : []), "app.css"],
946
+ assets: [...assets.keys()].sort(),
947
+ fonts,
948
+ ...(windowConfig ? { window: windowConfig } : {}),
949
+ ...(capabilities ? { capabilities } : {}),
950
+ styleSystem: result.styleSystem,
951
+ artifactDigests: Object.fromEntries(
952
+ [...files]
953
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
954
+ .map(([name, bytes]) => [name, sha256(bytes)]),
955
+ ),
956
+ };
957
+ const manifest: Manifest = { ...identity, buildId: contentDigest(files, identity) };
958
+ signal?.throwIfAborted();
959
+ files.set("manifest.json", Buffer.from(JSON.stringify(manifest, null, 2) + "\n"));
960
+ signal?.throwIfAborted();
961
+ const dist = await publishGeneration(appDirectory, files);
962
+ return { dist, manifest };
963
+ }