@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/css.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { createRequire } from "node:module";
2
- import { readdir, readFile, unlink, writeFile } from "node:fs/promises";
2
+ import { readdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { Features, transform, type MediaCondition, type SelectorComponent } from "lightningcss";
5
- import { canonicalJson, moduleIdentity, sha256 } from "./identity.ts";
5
+ import { canonicalJson, sha256 } from "./identity.ts";
6
6
 
7
7
  const require = createRequire(import.meta.url);
8
8
  const lightningcssPkg = require("lightningcss/package.json") as { version: string };
@@ -232,6 +232,382 @@ export function validateStylesheet(css: string, filename = "app.css"): string {
232
232
  }
233
233
 
234
234
  const VALID_TS_PROP = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
235
+ const GLOB_CHAR = /[*?[{]/;
236
+ const IGNORED_SCAN_DIRS = new Set([
237
+ "node_modules",
238
+ "dist",
239
+ "dist-package",
240
+ "target",
241
+ ".git",
242
+ ".zgui-generations",
243
+ ".direnv",
244
+ ".scratch",
245
+ ".cache",
246
+ ]);
247
+
248
+ export interface SyncCssModuleTypesOptions {
249
+ project?: string | undefined;
250
+ appDirectory?: string | undefined;
251
+ include?: readonly string[] | undefined;
252
+ cwd?: string | undefined;
253
+ }
254
+
255
+ interface ScanTarget {
256
+ dir: string;
257
+ recursive: boolean;
258
+ }
259
+
260
+ interface TsconfigSpec {
261
+ include?: { patterns: string[]; dir: string };
262
+ files?: { entries: string[]; dir: string };
263
+ exclude?: { patterns: string[]; dir: string };
264
+ }
265
+
266
+ function isIgnoredDirName(name: string): boolean {
267
+ return (
268
+ IGNORED_SCAN_DIRS.has(name) ||
269
+ name.startsWith(".dist-") ||
270
+ name.startsWith(".shell-compose-stage-")
271
+ );
272
+ }
273
+
274
+ function toPosix(p: string): string {
275
+ return p.split(path.sep).join("/");
276
+ }
277
+
278
+ function stripTrailingSlash(p: string): string {
279
+ if (p.length <= 1) return p;
280
+ return p.replace(/\/+$/, "") || "/";
281
+ }
282
+
283
+ function isSameOrInside(candidate: string, ancestor: string): boolean {
284
+ const rel = path.relative(ancestor, candidate);
285
+ return rel === "" || (!rel.startsWith(`..${path.sep}`) && rel !== ".." && !path.isAbsolute(rel));
286
+ }
287
+
288
+ async function safeStat(targetPath: string) {
289
+ try {
290
+ return await stat(targetPath);
291
+ } catch (error) {
292
+ const code = (error as NodeJS.ErrnoException).code;
293
+ if (code === "ENOENT" || code === "ENOTDIR") return undefined;
294
+ throw error;
295
+ }
296
+ }
297
+
298
+ function splitGlobBase(
299
+ baseDir: string,
300
+ posixPattern: string,
301
+ ): { staticBase: string; globRest: string } {
302
+ const segments = posixPattern.split("/");
303
+ const firstGlob = segments.findIndex(seg => GLOB_CHAR.test(seg));
304
+ if (firstGlob === -1) {
305
+ return { staticBase: path.resolve(baseDir, posixPattern), globRest: "" };
306
+ }
307
+ const prefix = segments.slice(0, firstGlob).join("/");
308
+ const staticBase =
309
+ firstGlob === 0
310
+ ? path.resolve(baseDir)
311
+ : path.resolve(baseDir, prefix === "" && posixPattern.startsWith("/") ? "/" : prefix);
312
+ return { staticBase, globRest: segments.slice(firstGlob).join("/") };
313
+ }
314
+
315
+ function expandConfigDir(pattern: string, leafConfigDir: string): string {
316
+ return pattern.replaceAll("${configDir}", toPosix(leafConfigDir));
317
+ }
318
+
319
+ async function resolveTsconfigExtendsPath(
320
+ specifier: string,
321
+ fromConfigPath: string,
322
+ leafConfigDir: string,
323
+ ): Promise<string> {
324
+ const expanded = expandConfigDir(specifier, leafConfigDir);
325
+ if (
326
+ expanded.startsWith("./") ||
327
+ expanded.startsWith("../") ||
328
+ expanded === "." ||
329
+ expanded === ".." ||
330
+ path.isAbsolute(expanded)
331
+ ) {
332
+ const base = path.resolve(path.dirname(fromConfigPath), expanded);
333
+ for (const candidate of [base, `${base}.json`, path.join(base, "tsconfig.json")]) {
334
+ const info = await safeStat(candidate);
335
+ if (info?.isFile()) return candidate;
336
+ }
337
+ throw new Error(`Cannot resolve tsconfig extends "${specifier}" from ${fromConfigPath}`);
338
+ }
339
+ const req = createRequire(fromConfigPath);
340
+ for (const candidate of [expanded, `${expanded}.json`, `${expanded}/tsconfig.json`]) {
341
+ try {
342
+ const resolved = req.resolve(candidate);
343
+ const info = await safeStat(resolved);
344
+ if (info?.isFile()) return resolved;
345
+ } catch (error) {
346
+ const code = (error as NodeJS.ErrnoException).code;
347
+ if (code !== "MODULE_NOT_FOUND" && code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw error;
348
+ }
349
+ }
350
+ throw new Error(`Cannot resolve tsconfig extends "${specifier}" from ${fromConfigPath}`);
351
+ }
352
+
353
+ function stringList(value: unknown): string[] | undefined {
354
+ if (!Array.isArray(value)) return undefined;
355
+ return value.filter((item): item is string => typeof item === "string");
356
+ }
357
+
358
+ async function collectTsconfigSpec(
359
+ configPath: string,
360
+ leafConfigDir: string,
361
+ visited: Set<string>,
362
+ ): Promise<TsconfigSpec> {
363
+ const resolved = path.resolve(configPath);
364
+ if (visited.has(resolved)) return {};
365
+ visited.add(resolved);
366
+
367
+ const rawText = await readFile(resolved, "utf8");
368
+ const parsed = Bun.JSONC.parse(rawText) as Record<string, unknown> | null;
369
+ if (!parsed || typeof parsed !== "object") return {};
370
+
371
+ const configDir = path.dirname(resolved);
372
+ const ownInclude = stringList(parsed.include);
373
+ const ownFiles = stringList(parsed.files);
374
+ const ownExclude = stringList(parsed.exclude);
375
+ const hasOwnInclusion = ownInclude !== undefined || ownFiles !== undefined;
376
+
377
+ const spec: TsconfigSpec = {
378
+ ...(ownInclude !== undefined ? { include: { patterns: ownInclude, dir: configDir } } : {}),
379
+ ...(ownFiles !== undefined ? { files: { entries: ownFiles, dir: configDir } } : {}),
380
+ ...(ownExclude !== undefined ? { exclude: { patterns: ownExclude, dir: configDir } } : {}),
381
+ };
382
+
383
+ if (hasOwnInclusion && spec.exclude !== undefined) {
384
+ return spec;
385
+ }
386
+
387
+ const extendsList =
388
+ typeof parsed.extends === "string" ? [parsed.extends] : (stringList(parsed.extends) ?? []);
389
+
390
+ let inheritedInclude = hasOwnInclusion ? spec.include : undefined;
391
+ let inheritedFiles = hasOwnInclusion ? spec.files : undefined;
392
+ let inheritedExclude = spec.exclude;
393
+
394
+ for (let i = extendsList.length - 1; i >= 0; i--) {
395
+ if (
396
+ (inheritedInclude !== undefined || inheritedFiles !== undefined) &&
397
+ inheritedExclude !== undefined
398
+ ) {
399
+ break;
400
+ }
401
+ const basePath = await resolveTsconfigExtendsPath(extendsList[i]!, resolved, leafConfigDir);
402
+ const parentSpec = await collectTsconfigSpec(basePath, leafConfigDir, visited);
403
+ if (inheritedInclude === undefined && inheritedFiles === undefined) {
404
+ inheritedInclude = parentSpec.include;
405
+ inheritedFiles = parentSpec.files;
406
+ }
407
+ if (inheritedExclude === undefined) {
408
+ inheritedExclude = parentSpec.exclude;
409
+ }
410
+ }
411
+
412
+ return {
413
+ ...(inheritedInclude !== undefined ? { include: inheritedInclude } : {}),
414
+ ...(inheritedFiles !== undefined ? { files: inheritedFiles } : {}),
415
+ ...(inheritedExclude !== undefined ? { exclude: inheritedExclude } : {}),
416
+ };
417
+ }
418
+
419
+ async function expandGlobDirectories(baseDir: string, posixDirPattern: string): Promise<string[]> {
420
+ if (!GLOB_CHAR.test(posixDirPattern)) {
421
+ const target = path.resolve(baseDir, posixDirPattern);
422
+ const info = await safeStat(target);
423
+ return info?.isDirectory() ? [target] : [];
424
+ }
425
+ const { staticBase, globRest } = splitGlobBase(baseDir, posixDirPattern);
426
+ const staticInfo = await safeStat(staticBase);
427
+ if (!staticInfo?.isDirectory()) return [];
428
+ const dirs: string[] = [];
429
+ const glob = new Bun.Glob(globRest);
430
+ for await (const match of glob.scan({
431
+ cwd: staticBase,
432
+ onlyFiles: false,
433
+ followSymlinks: true,
434
+ })) {
435
+ const candidate = path.resolve(staticBase, match);
436
+ const info = await safeStat(candidate);
437
+ if (info?.isDirectory()) dirs.push(candidate);
438
+ }
439
+ return dirs;
440
+ }
441
+
442
+ async function resolveTsconfigCssRoots(
443
+ projectPath: string,
444
+ targets: Map<string, boolean>,
445
+ directCssFiles: Set<string>,
446
+ directDtsFiles: Set<string>,
447
+ excludedDirs: Set<string>,
448
+ ): Promise<void> {
449
+ const resolvedProject = path.resolve(projectPath);
450
+ const leafConfigDir = path.dirname(resolvedProject);
451
+ const spec = await collectTsconfigSpec(resolvedProject, leafConfigDir, new Set());
452
+
453
+ const addTarget = (dir: string, recursive: boolean) => {
454
+ const abs = path.resolve(dir);
455
+ targets.set(abs, (targets.get(abs) ?? false) || recursive);
456
+ };
457
+
458
+ if (spec.exclude) {
459
+ for (const rawPattern of spec.exclude.patterns) {
460
+ const normalized = stripTrailingSlash(
461
+ toPosix(expandConfigDir(rawPattern, leafConfigDir)).replace(/\/+\*\*?(?:\/\*+)?$/, ""),
462
+ );
463
+ if (!normalized || GLOB_CHAR.test(normalized)) continue;
464
+ excludedDirs.add(path.resolve(spec.exclude.dir, normalized));
465
+ }
466
+ }
467
+
468
+ if (spec.files) {
469
+ for (const rawEntry of spec.files.entries) {
470
+ const expanded = expandConfigDir(rawEntry, leafConfigDir);
471
+ const target = path.resolve(spec.files.dir, expanded);
472
+ const info = await safeStat(target);
473
+ if (!info) continue;
474
+ if (info.isDirectory()) {
475
+ addTarget(target, true);
476
+ } else if (info.isFile()) {
477
+ if (target.endsWith(".module.css")) {
478
+ directCssFiles.add(target);
479
+ } else {
480
+ const parent = path.dirname(target);
481
+ addTarget(parent, parent !== leafConfigDir);
482
+ }
483
+ }
484
+ }
485
+ }
486
+
487
+ const includePatterns =
488
+ spec.include !== undefined
489
+ ? spec.include
490
+ : spec.files !== undefined
491
+ ? undefined
492
+ : { patterns: ["**/*"], dir: leafConfigDir };
493
+
494
+ if (includePatterns) {
495
+ for (const rawPattern of includePatterns.patterns) {
496
+ const normalized = stripTrailingSlash(toPosix(expandConfigDir(rawPattern, leafConfigDir)));
497
+ if (!normalized) continue;
498
+
499
+ if (!GLOB_CHAR.test(normalized)) {
500
+ const target = path.resolve(includePatterns.dir, normalized);
501
+ const info = await safeStat(target);
502
+ if (!info) continue;
503
+ if (info.isDirectory()) {
504
+ addTarget(target, true);
505
+ } else if (info.isFile()) {
506
+ if (target.endsWith(".module.css")) {
507
+ directCssFiles.add(target);
508
+ } else {
509
+ const parent = path.dirname(target);
510
+ addTarget(parent, parent !== leafConfigDir);
511
+ }
512
+ }
513
+ continue;
514
+ }
515
+
516
+ if (normalized.includes("**")) {
517
+ const segments = normalized.split("/");
518
+ const ddIndex = segments.findIndex(seg => seg.includes("**"));
519
+ const prefix =
520
+ ddIndex <= 0
521
+ ? "."
522
+ : segments.slice(0, ddIndex).join("/") || (normalized.startsWith("/") ? "/" : ".");
523
+ for (const dir of await expandGlobDirectories(includePatterns.dir, prefix)) {
524
+ addTarget(dir, true);
525
+ }
526
+ continue;
527
+ }
528
+
529
+ if (normalized.endsWith(".module.css")) {
530
+ const { staticBase, globRest } = splitGlobBase(includePatterns.dir, normalized);
531
+ if ((await safeStat(staticBase))?.isDirectory()) {
532
+ for await (const match of new Bun.Glob(globRest).scan({
533
+ cwd: staticBase,
534
+ onlyFiles: true,
535
+ followSymlinks: true,
536
+ })) {
537
+ directCssFiles.add(path.resolve(staticBase, match));
538
+ }
539
+ for await (const match of new Bun.Glob(`${globRest}.d.ts`).scan({
540
+ cwd: staticBase,
541
+ onlyFiles: true,
542
+ followSymlinks: true,
543
+ })) {
544
+ directDtsFiles.add(path.resolve(staticBase, match));
545
+ }
546
+ }
547
+ continue;
548
+ }
549
+
550
+ const dirPattern = path.posix.dirname(normalized);
551
+ for (const dir of await expandGlobDirectories(includePatterns.dir, dirPattern)) {
552
+ addTarget(dir, path.resolve(dir) !== leafConfigDir);
553
+ }
554
+ }
555
+ }
556
+ }
557
+
558
+ async function resolveExplicitIncludes(
559
+ include: readonly string[],
560
+ baseCwd: string,
561
+ targets: Map<string, boolean>,
562
+ directCssFiles: Set<string>,
563
+ directDtsFiles: Set<string>,
564
+ ): Promise<void> {
565
+ const addTarget = (dir: string, recursive: boolean) => {
566
+ const abs = path.resolve(dir);
567
+ targets.set(abs, (targets.get(abs) ?? false) || recursive);
568
+ };
569
+
570
+ for (const rawEntry of include) {
571
+ const normalized = stripTrailingSlash(toPosix(rawEntry));
572
+ if (!normalized) continue;
573
+ if (!GLOB_CHAR.test(normalized)) {
574
+ const target = path.resolve(baseCwd, normalized);
575
+ const info = await safeStat(target);
576
+ if (!info) continue;
577
+ if (info.isDirectory()) {
578
+ addTarget(target, true);
579
+ } else if (info.isFile() && target.endsWith(".module.css")) {
580
+ directCssFiles.add(target);
581
+ }
582
+ continue;
583
+ }
584
+
585
+ const { staticBase, globRest } = splitGlobBase(baseCwd, normalized);
586
+ if (!(await safeStat(staticBase))?.isDirectory()) continue;
587
+ for await (const match of new Bun.Glob(globRest).scan({
588
+ cwd: staticBase,
589
+ onlyFiles: false,
590
+ followSymlinks: true,
591
+ })) {
592
+ const candidate = path.resolve(staticBase, match);
593
+ const info = await safeStat(candidate);
594
+ if (info?.isDirectory()) {
595
+ addTarget(candidate, true);
596
+ } else if (info?.isFile() && candidate.endsWith(".module.css")) {
597
+ directCssFiles.add(candidate);
598
+ }
599
+ }
600
+ if (normalized.endsWith(".module.css")) {
601
+ for await (const match of new Bun.Glob(`${globRest}.d.ts`).scan({
602
+ cwd: staticBase,
603
+ onlyFiles: true,
604
+ followSymlinks: true,
605
+ })) {
606
+ directDtsFiles.add(path.resolve(staticBase, match));
607
+ }
608
+ }
609
+ }
610
+ }
235
611
 
236
612
  export function formatCssModuleDts(exportsMap: Readonly<Record<string, string>>): string {
237
613
  const keys = Object.keys(exportsMap).sort();
@@ -259,58 +635,215 @@ export function formatCssModuleDts(exportsMap: Readonly<Record<string, string>>)
259
635
 
260
636
  async function scanCssModules(
261
637
  directory: string,
262
- modules: string[],
263
- declarations: string[],
638
+ modules: Set<string>,
639
+ declarations: Set<string>,
640
+ {
641
+ recursive = true,
642
+ excludedDirs,
643
+ }: { recursive?: boolean; excludedDirs?: ReadonlySet<string> } = {},
264
644
  ): Promise<void> {
645
+ if (excludedDirs?.has(path.resolve(directory))) return;
265
646
  let entries;
266
647
  try {
267
648
  entries = await readdir(directory, { withFileTypes: true });
268
649
  } catch (error) {
269
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
650
+ const code = (error as NodeJS.ErrnoException).code;
651
+ if (code === "ENOENT" || code === "ENOTDIR") return;
270
652
  throw error;
271
653
  }
272
654
  entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
273
655
  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
- ) {
656
+ if (isIgnoredDirName(entry.name)) {
280
657
  continue;
281
658
  }
282
- const full = path.join(directory, entry.name);
659
+ const full = path.resolve(directory, entry.name);
283
660
  if (entry.isDirectory()) {
284
- await scanCssModules(full, modules, declarations);
661
+ if (recursive) {
662
+ await scanCssModules(full, modules, declarations, { recursive: true, excludedDirs });
663
+ }
285
664
  } else if (entry.isFile()) {
286
665
  if (entry.name.endsWith(".module.css")) {
287
- modules.push(full);
666
+ modules.add(full);
288
667
  } else if (entry.name.endsWith(".module.css.d.ts")) {
289
- declarations.push(full);
668
+ declarations.add(full);
290
669
  }
291
670
  }
292
671
  }
293
672
  }
294
673
 
674
+ async function resolveCssScanInputs(options: SyncCssModuleTypesOptions = {}): Promise<{
675
+ baseCwd: string;
676
+ resolvedAppDir?: string;
677
+ resolvedProject?: string;
678
+ targets: ScanTarget[];
679
+ directCssFiles: Set<string>;
680
+ directDtsFiles: Set<string>;
681
+ excludedDirs: Set<string>;
682
+ }> {
683
+ const baseCwd = path.resolve(options.cwd ?? process.cwd());
684
+ const resolvedAppDir =
685
+ options.appDirectory !== undefined ? path.resolve(baseCwd, options.appDirectory) : undefined;
686
+ const targets = new Map<string, boolean>();
687
+ const directCssFiles = new Set<string>();
688
+ const directDtsFiles = new Set<string>();
689
+ const excludedDirs = new Set<string>();
690
+
691
+ if (resolvedAppDir !== undefined) {
692
+ targets.set(path.resolve(resolvedAppDir, "src"), true);
693
+ }
694
+
695
+ let resolvedProject: string | undefined;
696
+ if (options.project !== undefined) {
697
+ resolvedProject = path.resolve(baseCwd, options.project);
698
+ const info = await safeStat(resolvedProject);
699
+ if (!info?.isFile()) {
700
+ throw new Error(`tsconfig.json not found: ${resolvedProject}`);
701
+ }
702
+ } else if (resolvedAppDir !== undefined) {
703
+ const candidate = path.join(resolvedAppDir, "tsconfig.json");
704
+ if ((await safeStat(candidate))?.isFile()) {
705
+ resolvedProject = candidate;
706
+ }
707
+ } else if (options.include === undefined) {
708
+ const candidate = path.join(baseCwd, "tsconfig.json");
709
+ if ((await safeStat(candidate))?.isFile()) {
710
+ resolvedProject = candidate;
711
+ }
712
+ const cwdSrc = path.join(baseCwd, "src");
713
+ if ((await safeStat(cwdSrc))?.isDirectory()) {
714
+ targets.set(cwdSrc, true);
715
+ }
716
+ }
717
+
718
+ if (resolvedProject !== undefined) {
719
+ await resolveTsconfigCssRoots(
720
+ resolvedProject,
721
+ targets,
722
+ directCssFiles,
723
+ directDtsFiles,
724
+ excludedDirs,
725
+ );
726
+ }
727
+
728
+ if (options.include !== undefined && options.include.length > 0) {
729
+ await resolveExplicitIncludes(
730
+ options.include,
731
+ baseCwd,
732
+ targets,
733
+ directCssFiles,
734
+ directDtsFiles,
735
+ );
736
+ }
737
+
738
+ const orderedTargets: ScanTarget[] = [...targets.entries()]
739
+ .map(([dir, recursive]) => ({ dir, recursive }))
740
+ .sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0));
741
+
742
+ return {
743
+ baseCwd,
744
+ ...(resolvedAppDir !== undefined ? { resolvedAppDir } : {}),
745
+ ...(resolvedProject !== undefined ? { resolvedProject } : {}),
746
+ targets: orderedTargets,
747
+ directCssFiles,
748
+ directDtsFiles,
749
+ excludedDirs,
750
+ };
751
+ }
752
+
753
+ export async function resolveCssModuleWatchDirectories(
754
+ options: SyncCssModuleTypesOptions = {},
755
+ ): Promise<string[]> {
756
+ const { targets, directCssFiles, excludedDirs } = await resolveCssScanInputs(options);
757
+ const candidates = new Set<string>();
758
+ for (const target of targets) {
759
+ if (excludedDirs.has(target.dir)) continue;
760
+ if ((await safeStat(target.dir))?.isDirectory()) {
761
+ candidates.add(target.dir);
762
+ }
763
+ }
764
+ for (const file of directCssFiles) {
765
+ const dir = path.dirname(file);
766
+ if (!excludedDirs.has(dir) && (await safeStat(dir))?.isDirectory()) {
767
+ candidates.add(dir);
768
+ }
769
+ }
770
+
771
+ const sorted = [...candidates].sort(
772
+ (a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0),
773
+ );
774
+ const kept: string[] = [];
775
+ for (const dir of sorted) {
776
+ if (kept.some(ancestor => isSameOrInside(dir, ancestor))) continue;
777
+ kept.push(dir);
778
+ }
779
+ return kept.sort();
780
+ }
781
+
782
+ function formatDiagnosticFilename(
783
+ cssPath: string,
784
+ diagnosticRoot: string,
785
+ baseCwd: string,
786
+ ): string {
787
+ const fromRoot = path.relative(diagnosticRoot, cssPath);
788
+ if (
789
+ fromRoot &&
790
+ !fromRoot.startsWith(`..${path.sep}`) &&
791
+ fromRoot !== ".." &&
792
+ !path.isAbsolute(fromRoot)
793
+ ) {
794
+ return toPosix(fromRoot);
795
+ }
796
+ const fromCwd = path.relative(baseCwd, cssPath);
797
+ if (
798
+ fromCwd &&
799
+ !fromCwd.startsWith(`..${path.sep}`) &&
800
+ fromCwd !== ".." &&
801
+ !path.isAbsolute(fromCwd)
802
+ ) {
803
+ return toPosix(fromCwd);
804
+ }
805
+ return fromRoot ? toPosix(fromRoot) : path.basename(cssPath);
806
+ }
807
+
295
808
  /**
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.
809
+ * Generates exact `*.module.css.d.ts` declarations for every `*.module.css` file under the
810
+ * configured app, tsconfig, and explicit include roots, skipping writes when unchanged
811
+ * (watch-safe) and deleting stale declarations on rename/delete.
298
812
  */
299
813
  export async function syncCssModuleTypes(
300
- appDirectory: string,
301
- { root }: { root: string },
814
+ options: SyncCssModuleTypesOptions = {},
302
815
  ): Promise<string[]> {
303
- const srcDir = path.join(appDirectory, "src");
304
- const modules: string[] = [];
305
- const existingDts: string[] = [];
306
- await scanCssModules(srcDir, modules, existingDts);
816
+ const {
817
+ baseCwd,
818
+ resolvedAppDir,
819
+ resolvedProject,
820
+ targets,
821
+ directCssFiles,
822
+ directDtsFiles,
823
+ excludedDirs,
824
+ } = await resolveCssScanInputs(options);
825
+
826
+ const moduleSet = new Set<string>(directCssFiles);
827
+ const existingDtsSet = new Set<string>(directDtsFiles);
828
+
829
+ for (const target of targets) {
830
+ await scanCssModules(target.dir, moduleSet, existingDtsSet, {
831
+ recursive: target.recursive,
832
+ excludedDirs,
833
+ });
834
+ }
835
+
836
+ const modules = [...moduleSet].sort();
837
+ const existingDts = [...existingDtsSet].sort();
838
+ const diagnosticRoot =
839
+ resolvedAppDir ?? (resolvedProject ? path.dirname(resolvedProject) : baseCwd);
307
840
 
308
841
  const expectedDts = new Set<string>();
309
842
  for (const cssPath of modules) {
310
843
  const source = await readFile(cssPath, "utf8");
311
- const idKey = moduleIdentity(cssPath, { root, appDirectory });
844
+ const diagnosticName = formatDiagnosticFilename(cssPath, diagnosticRoot, baseCwd);
312
845
  const { exports: exportsMap } = transformStylesheet(source, {
313
- filename: idKey,
846
+ filename: diagnosticName,
314
847
  cssModules: true,
315
848
  });
316
849
  const dtsPath = `${cssPath}.d.ts`;
package/src/dev.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  import type { ApplicationWatcher, DevApplicationOptions } from "./index.ts";
2
2
  import path from "node:path";
3
3
  import type { EventEmitter } from "node:events";
4
- import { resolveNativeHost } from "./host.ts";
4
+ import { prepareNativeHost, resolveNativeHost, runNativeHost } from "./host.ts";
5
5
  import { workspaceRoot } from "./sdk.ts";
6
6
  import { watchApplication } from "./watch.ts";
7
- import { prepareNativeHost, runNativeHost } from "./native-process.ts";
8
7
 
9
8
  interface DevDependencies {
10
9
  watch?: typeof watchApplication;
@@ -31,6 +30,7 @@ export async function devApplication(
31
30
  root = workspaceRoot,
32
31
  appDirectory = path.join(root, "apps/examples", app),
33
32
  hostArgs = [],
33
+ hostCwd,
34
34
  hostRoot,
35
35
  hostExecutable,
36
36
  hostSearchFrom,
@@ -38,6 +38,7 @@ export async function devApplication(
38
38
  mode = "desktop",
39
39
  extraCapabilities,
40
40
  capabilitiesFile,
41
+ cssModuleInclude,
41
42
  signal,
42
43
  }: DevApplicationOptions = {},
43
44
  {
@@ -93,6 +94,7 @@ export async function devApplication(
93
94
  strictTypecheck,
94
95
  extraCapabilities,
95
96
  capabilitiesFile,
97
+ cssModuleInclude,
96
98
  signal: controller.signal,
97
99
  onSuccess(result) {
98
100
  if (controller.signal.aborted) return;
@@ -126,7 +128,7 @@ export async function devApplication(
126
128
  signal: controller.signal,
127
129
  });
128
130
  executable = resolvedHost.executable;
129
- runRoot = explicitHostRoot ?? resolvedHost.cargoRoot ?? appDirectory;
131
+ runRoot = resolvedHost.runRoot;
130
132
  }
131
133
  if (controller.signal.aborted) return;
132
134
  const dist = await Promise.race([published.promise, stopped.promise]);
@@ -136,7 +138,7 @@ export async function devApplication(
136
138
  mode === "preview"
137
139
  ? ["preview", "watch", "--bundle", dist!, ...hostArgs]
138
140
  : ["--bundle", dist!, "--watch", ...hostArgs];
139
- stop(await run(executable, args, { root: runRoot, signal: controller.signal }));
141
+ stop(await run(executable, args, { root: hostCwd ?? runRoot, signal: controller.signal }));
140
142
  } catch (error) {
141
143
  fail(error);
142
144
  }