@hewel/zgui-build 0.0.0-stage → 0.1.2

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 +86 -2
  4. package/THIRD_PARTY_NOTICES.md +37 -0
  5. package/package.json +64 -4
  6. package/sdk/Cargo.lock +6814 -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 +1097 -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 +265 -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/css.ts ADDED
@@ -0,0 +1,337 @@
1
+ import { createRequire } from "node:module";
2
+ import { readdir, readFile, unlink, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { Features, transform, type MediaCondition, type SelectorComponent } from "lightningcss";
5
+ import { canonicalJson, moduleIdentity, sha256 } from "./identity.ts";
6
+
7
+ const require = createRequire(import.meta.url);
8
+ const lightningcssPkg = require("lightningcss/package.json") as { version: string };
9
+
10
+ export const CSS_MODULES_PATTERN = "[hash]_[local]";
11
+
12
+ export interface StyleSystem {
13
+ name: "lightningcss";
14
+ profile: "lightningcss-v1";
15
+ configDigest: string;
16
+ }
17
+
18
+ export interface TransformedCss {
19
+ css: string;
20
+ exports: Record<string, string>;
21
+ }
22
+
23
+ const STYLE_CONFIG = {
24
+ name: "lightningcss",
25
+ profile: "lightningcss-v1",
26
+ lightningcssVersion: lightningcssPkg.version,
27
+ cssModules: {
28
+ pattern: CSS_MODULES_PATTERN,
29
+ dashedIdents: false,
30
+ },
31
+ nesting: true,
32
+ targets: null,
33
+ } as const;
34
+
35
+ const STYLE_CONFIG_DIGEST = sha256(canonicalJson(STYLE_CONFIG));
36
+
37
+ export function styleSystem(): StyleSystem {
38
+ return {
39
+ name: "lightningcss",
40
+ profile: "lightningcss-v1",
41
+ configDigest: STYLE_CONFIG_DIGEST,
42
+ };
43
+ }
44
+
45
+ function hasPrefersReducedMotion(condition: MediaCondition | null | undefined): boolean {
46
+ if (!condition) return false;
47
+ switch (condition.type) {
48
+ case "feature": {
49
+ const feat = condition.value;
50
+ if (feat.type === "plain" || feat.type === "range" || feat.type === "boolean") {
51
+ return feat.name.toLowerCase() === "prefers-reduced-motion";
52
+ }
53
+ if (feat.type === "interval") {
54
+ return feat.name.toLowerCase() === "prefers-reduced-motion";
55
+ }
56
+ return false;
57
+ }
58
+ case "not":
59
+ return hasPrefersReducedMotion(condition.value);
60
+ case "operation":
61
+ return condition.conditions.some(item => hasPrefersReducedMotion(item));
62
+ default:
63
+ return false;
64
+ }
65
+ }
66
+
67
+ function selectorContainsDirAttr(components: readonly SelectorComponent[]): boolean {
68
+ for (const part of components) {
69
+ if (part.type === "attribute" && part.name.toLowerCase() === "dir") return true;
70
+ if (part.type === "pseudo-class" && "selectors" in part && Array.isArray(part.selectors)) {
71
+ for (const nested of part.selectors) {
72
+ if (Array.isArray(nested) && selectorContainsDirAttr(nested as SelectorComponent[])) {
73
+ return true;
74
+ }
75
+ }
76
+ }
77
+ }
78
+ return false;
79
+ }
80
+
81
+ function checkSelector(
82
+ components: readonly SelectorComponent[],
83
+ filename: string,
84
+ cssModules: boolean,
85
+ ): void {
86
+ let hasHtmlType = false;
87
+ let hasDirAttr = false;
88
+
89
+ const flushCompound = (): void => {
90
+ if (hasHtmlType && hasDirAttr) {
91
+ throw new Error(`Unsupported native CSS feature in ${filename}: html[dir]`);
92
+ }
93
+ hasHtmlType = false;
94
+ hasDirAttr = false;
95
+ };
96
+
97
+ for (const part of components) {
98
+ if (part.type === "combinator") {
99
+ flushCompound();
100
+ continue;
101
+ }
102
+ if (part.type === "type" && part.name.toLowerCase() === "html") {
103
+ hasHtmlType = true;
104
+ }
105
+ if (part.type === "attribute" && part.name.toLowerCase() === "dir") {
106
+ hasDirAttr = true;
107
+ }
108
+ if (cssModules && part.type === "pseudo-class") {
109
+ if (part.kind === "custom" && part.name === "export") {
110
+ throw new Error(`Unsupported CSS Modules ICSS :export rule in ${filename}`);
111
+ }
112
+ if (part.kind === "custom-function" && part.name === "import") {
113
+ throw new Error(`Unsupported CSS Modules ICSS :import rule in ${filename}`);
114
+ }
115
+ }
116
+ if (part.type === "pseudo-class" && "selectors" in part && Array.isArray(part.selectors)) {
117
+ for (const nested of part.selectors) {
118
+ if (Array.isArray(nested)) {
119
+ const list = nested as SelectorComponent[];
120
+ if (selectorContainsDirAttr(list)) hasDirAttr = true;
121
+ checkSelector(list, filename, cssModules);
122
+ }
123
+ }
124
+ }
125
+ }
126
+ flushCompound();
127
+ }
128
+
129
+ /**
130
+ * Validates and transforms native CSS or a locally scoped `*.module.css` file via Lightning CSS.
131
+ * Runs with no Browserslist targets so Stylo keeps native tokens (`oklch`, `color-mix`, `--zui-*`),
132
+ * flattens CSS nesting (`&`), and rejects unsupported Stylo/ICSS features at the AST level.
133
+ */
134
+ export function transformStylesheet(
135
+ css: string,
136
+ {
137
+ filename,
138
+ cssModules = false,
139
+ }: {
140
+ filename: string;
141
+ cssModules?: boolean;
142
+ },
143
+ ): TransformedCss {
144
+ let result;
145
+ try {
146
+ result = transform({
147
+ filename,
148
+ code: Buffer.from(css, "utf8"),
149
+ include: Features.Nesting,
150
+ cssModules: cssModules
151
+ ? {
152
+ pattern: CSS_MODULES_PATTERN,
153
+ dashedIdents: false,
154
+ }
155
+ : false,
156
+ visitor: {
157
+ Rule(rule) {
158
+ switch (rule.type) {
159
+ case "import":
160
+ throw new Error(`Unsupported native CSS feature in ${filename}: @import`);
161
+ case "font-face":
162
+ throw new Error(`Unsupported native CSS feature in ${filename}: @font-face`);
163
+ case "container":
164
+ throw new Error(`Unsupported native CSS feature in ${filename}: @container`);
165
+ case "property":
166
+ throw new Error(`Unsupported native CSS feature in ${filename}: @property`);
167
+ case "unknown":
168
+ if (rule.value.name.toLowerCase() === "value") {
169
+ throw new Error(`Unsupported CSS Modules @value rule in ${filename}`);
170
+ }
171
+ break;
172
+ default:
173
+ break;
174
+ }
175
+ },
176
+ Url(u) {
177
+ throw new Error(`Unsupported native CSS feature in ${filename}: url(${u.url})`);
178
+ },
179
+ Image(img) {
180
+ if (img.type === "image-set") {
181
+ throw new Error(`Unsupported native CSS feature in ${filename}: image-set()`);
182
+ }
183
+ },
184
+ Function(fn) {
185
+ const lower = fn.name.toLowerCase();
186
+ if (lower === "image-set" || lower === "-webkit-image-set") {
187
+ throw new Error(`Unsupported native CSS feature in ${filename}: ${fn.name}()`);
188
+ }
189
+ },
190
+ MediaQuery(mq) {
191
+ if (hasPrefersReducedMotion(mq.condition)) {
192
+ throw new Error(
193
+ `Unsupported native CSS feature in ${filename}: prefers-reduced-motion`,
194
+ );
195
+ }
196
+ },
197
+ Selector(sel) {
198
+ checkSelector(sel, filename, cssModules);
199
+ },
200
+ },
201
+ });
202
+ } catch (error) {
203
+ if (error instanceof Error && error.message.startsWith("Unsupported ")) {
204
+ throw error;
205
+ }
206
+ const message = error instanceof Error ? error.message : String(error);
207
+ throw new Error(`CSS compilation failed for ${filename}: ${message}`);
208
+ }
209
+
210
+ const exportsMap: Record<string, string> = {};
211
+ if (cssModules && result.exports) {
212
+ for (const key of Object.keys(result.exports).sort()) {
213
+ const entry = result.exports[key];
214
+ if (!entry) continue;
215
+ if (entry.composes.length > 0) {
216
+ throw new Error(
217
+ `Unsupported CSS Modules feature in ${filename}: 'composes' on '.${key}' is not supported in v1`,
218
+ );
219
+ }
220
+ exportsMap[key] = entry.name;
221
+ }
222
+ }
223
+
224
+ return {
225
+ css: Buffer.from(result.code).toString("utf8").trim(),
226
+ exports: exportsMap,
227
+ };
228
+ }
229
+
230
+ export function validateStylesheet(css: string, filename = "app.css"): string {
231
+ return transformStylesheet(css, { filename, cssModules: false }).css;
232
+ }
233
+
234
+ const VALID_TS_PROP = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
235
+
236
+ export function formatCssModuleDts(exportsMap: Readonly<Record<string, string>>): string {
237
+ const keys = Object.keys(exportsMap).sort();
238
+ if (keys.length === 0) {
239
+ return [
240
+ "// Generated by @hewel/zgui-build. Do not edit manually.",
241
+ "declare const styles: Readonly<Record<never, never>>;",
242
+ "export default styles;",
243
+ "",
244
+ ].join("\n");
245
+ }
246
+ const lines = [
247
+ "// Generated by @hewel/zgui-build. Do not edit manually.",
248
+ "declare const styles: {",
249
+ ...keys.map(key => {
250
+ const prop = VALID_TS_PROP.test(key) ? key : JSON.stringify(key);
251
+ return ` readonly ${prop}: string;`;
252
+ }),
253
+ "};",
254
+ "export default styles;",
255
+ "",
256
+ ];
257
+ return lines.join("\n");
258
+ }
259
+
260
+ async function scanCssModules(
261
+ directory: string,
262
+ modules: string[],
263
+ declarations: string[],
264
+ ): Promise<void> {
265
+ let entries;
266
+ try {
267
+ entries = await readdir(directory, { withFileTypes: true });
268
+ } catch (error) {
269
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
270
+ throw error;
271
+ }
272
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
273
+ for (const entry of entries) {
274
+ if (
275
+ entry.name === "node_modules" ||
276
+ entry.name === "dist" ||
277
+ entry.name === ".zgui-generations" ||
278
+ entry.name === ".git"
279
+ ) {
280
+ continue;
281
+ }
282
+ const full = path.join(directory, entry.name);
283
+ if (entry.isDirectory()) {
284
+ await scanCssModules(full, modules, declarations);
285
+ } else if (entry.isFile()) {
286
+ if (entry.name.endsWith(".module.css")) {
287
+ modules.push(full);
288
+ } else if (entry.name.endsWith(".module.css.d.ts")) {
289
+ declarations.push(full);
290
+ }
291
+ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Generates exact `*.module.css.d.ts` declarations for every `*.module.css` file under `src/`,
297
+ * skipping writes when unchanged (watch-safe) and deleting stale declarations on rename/delete.
298
+ */
299
+ export async function syncCssModuleTypes(
300
+ appDirectory: string,
301
+ { root }: { root: string },
302
+ ): Promise<string[]> {
303
+ const srcDir = path.join(appDirectory, "src");
304
+ const modules: string[] = [];
305
+ const existingDts: string[] = [];
306
+ await scanCssModules(srcDir, modules, existingDts);
307
+
308
+ const expectedDts = new Set<string>();
309
+ for (const cssPath of modules) {
310
+ const source = await readFile(cssPath, "utf8");
311
+ const idKey = moduleIdentity(cssPath, { root, appDirectory });
312
+ const { exports: exportsMap } = transformStylesheet(source, {
313
+ filename: idKey,
314
+ cssModules: true,
315
+ });
316
+ const dtsPath = `${cssPath}.d.ts`;
317
+ expectedDts.add(dtsPath);
318
+ const nextContent = formatCssModuleDts(exportsMap);
319
+ let currentContent: string | undefined;
320
+ try {
321
+ currentContent = await readFile(dtsPath, "utf8");
322
+ } catch (error) {
323
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
324
+ }
325
+ if (currentContent !== nextContent) {
326
+ await writeFile(dtsPath, nextContent, "utf8");
327
+ }
328
+ }
329
+
330
+ for (const dtsPath of existingDts) {
331
+ if (!expectedDts.has(dtsPath)) {
332
+ await unlink(dtsPath);
333
+ }
334
+ }
335
+
336
+ return modules;
337
+ }
package/src/dev.ts ADDED
@@ -0,0 +1,164 @@
1
+ import type { ApplicationWatcher, DevApplicationOptions } from "./index.ts";
2
+ import path from "node:path";
3
+ import type { EventEmitter } from "node:events";
4
+ import { resolveNativeHost } from "./host.ts";
5
+ import { workspaceRoot } from "./sdk.ts";
6
+ import { watchApplication } from "./watch.ts";
7
+ import { prepareNativeHost, runNativeHost } from "./native-process.ts";
8
+
9
+ interface DevDependencies {
10
+ watch?: typeof watchApplication;
11
+ prepare?: typeof prepareNativeHost;
12
+ run?: typeof runNativeHost;
13
+ signals?: Pick<EventEmitter, "on" | "removeListener">;
14
+ log?: (message: unknown) => void;
15
+ }
16
+
17
+ function errorMessage(error: unknown) {
18
+ return (
19
+ (error !== null && typeof error === "object" && "message" in error
20
+ ? error.message
21
+ : undefined) ?? String(error)
22
+ );
23
+ }
24
+
25
+ /** Own one publication watcher and one native session; return only after both have stopped.
26
+ * The optional third argument supplies lifecycle boundaries for deterministic embedding/tests.
27
+ */
28
+ export async function devApplication(
29
+ app: string,
30
+ {
31
+ root = workspaceRoot,
32
+ appDirectory = path.join(root, "apps/examples", app),
33
+ hostArgs = [],
34
+ hostRoot,
35
+ hostExecutable,
36
+ hostSearchFrom,
37
+ strictTypecheck = false,
38
+ mode = "desktop",
39
+ extraCapabilities,
40
+ capabilitiesFile,
41
+ signal,
42
+ }: DevApplicationOptions = {},
43
+ {
44
+ watch = watchApplication,
45
+ prepare = prepareNativeHost,
46
+ run = runNativeHost,
47
+ signals,
48
+ log = message => console.error(message),
49
+ }: DevDependencies = {},
50
+ ) {
51
+ const explicitHostRoot = hostRoot === undefined ? undefined : path.resolve(hostRoot);
52
+ const defaultRunRoot = explicitHostRoot ?? path.resolve(root);
53
+ appDirectory = path.resolve(appDirectory);
54
+ const controller = new AbortController();
55
+ const published = Promise.withResolvers<string>();
56
+ const stopped = Promise.withResolvers<void>();
57
+ let exitCode: number | undefined;
58
+ let watcher: ApplicationWatcher | undefined;
59
+ let startup: Promise<void> | undefined;
60
+ const stop = (code: number, reason?: unknown) => {
61
+ if (exitCode !== undefined) return;
62
+ exitCode = code;
63
+ controller.abort(reason);
64
+ stopped.resolve();
65
+ };
66
+ const interrupt = () => stop(130, "SIGINT");
67
+ const terminate = () => stop(143, "SIGTERM");
68
+ const abort = () => stop(signal?.reason === "SIGINT" ? 130 : 143, signal?.reason);
69
+ const fail = (error: unknown) => {
70
+ if (controller.signal.aborted) return;
71
+ log(errorMessage(error));
72
+ stop(
73
+ error !== null &&
74
+ typeof error === "object" &&
75
+ "exitCode" in error &&
76
+ typeof error.exitCode === "number"
77
+ ? error.exitCode
78
+ : 1,
79
+ );
80
+ };
81
+ signal?.addEventListener("abort", abort, { once: true });
82
+ signals?.on("SIGINT", interrupt);
83
+ signals?.on("SIGTERM", terminate);
84
+ if (signal?.aborted) abort();
85
+ try {
86
+ if (controller.signal.aborted) return exitCode ?? 143;
87
+ if (mode !== "desktop" && mode !== "preview")
88
+ throw new Error(`Unknown development mode: ${String(mode)}`);
89
+ watcher = watch(app, {
90
+ root,
91
+ appDirectory,
92
+ development: mode === "desktop",
93
+ strictTypecheck,
94
+ extraCapabilities,
95
+ capabilitiesFile,
96
+ signal: controller.signal,
97
+ onSuccess(result) {
98
+ if (controller.signal.aborted) return;
99
+ log(`Published ${result.dist} ${result.manifest.buildId}`);
100
+ published.resolve(result.dist);
101
+ },
102
+ onError(error) {
103
+ if (!controller.signal.aborted) log(errorMessage(error));
104
+ },
105
+ onTypecheck(event) {
106
+ if (controller.signal.aborted) return;
107
+ if (event.status === "failed") {
108
+ log(`[typecheck] ${event.diagnostics}`);
109
+ }
110
+ },
111
+ });
112
+ startup = (async () => {
113
+ try {
114
+ if (controller.signal.aborted) return;
115
+ let executable: string;
116
+ let runRoot = defaultRunRoot;
117
+ if (hostExecutable === undefined && prepare !== prepareNativeHost) {
118
+ executable = await prepare({ root: defaultRunRoot, signal: controller.signal });
119
+ } else {
120
+ const resolvedHost = await resolveNativeHost({
121
+ hostExecutable,
122
+ hostRoot: explicitHostRoot,
123
+ root,
124
+ cwd: appDirectory,
125
+ searchFrom: hostSearchFrom,
126
+ signal: controller.signal,
127
+ });
128
+ executable = resolvedHost.executable;
129
+ runRoot = explicitHostRoot ?? resolvedHost.cargoRoot ?? appDirectory;
130
+ }
131
+ if (controller.signal.aborted) return;
132
+ const dist = await Promise.race([published.promise, stopped.promise]);
133
+ if (controller.signal.aborted) return;
134
+ // Launch from this single startup path, never from a rebuild callback.
135
+ const args =
136
+ mode === "preview"
137
+ ? ["preview", "watch", "--bundle", dist!, ...hostArgs]
138
+ : ["--bundle", dist!, "--watch", ...hostArgs];
139
+ stop(await run(executable, args, { root: runRoot, signal: controller.signal }));
140
+ } catch (error) {
141
+ fail(error);
142
+ }
143
+ })();
144
+ await stopped.promise;
145
+ } catch (error) {
146
+ fail(error);
147
+ } finally {
148
+ controller.abort();
149
+ const cleanup = await Promise.allSettled([
150
+ startup,
151
+ Promise.resolve().then(() => watcher?.close()),
152
+ ]);
153
+ for (const result of cleanup) {
154
+ if (result.status === "rejected") {
155
+ log(errorMessage(result.reason));
156
+ if (exitCode === 0 || exitCode === undefined) exitCode = 1;
157
+ }
158
+ }
159
+ signal?.removeEventListener("abort", abort);
160
+ signals?.removeListener("SIGINT", interrupt);
161
+ signals?.removeListener("SIGTERM", terminate);
162
+ }
163
+ return exitCode ?? 1;
164
+ }