@bamboocss/node 1.45.5 → 1.46.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.
package/dist/index.cjs CHANGED
@@ -22,6 +22,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  enumerable: true
23
23
  }) : target, mod));
24
24
  //#endregion
25
+ const require_static_compiler = require("./static-compiler.cjs");
25
26
  let _bamboocss_reporter = require("@bamboocss/reporter");
26
27
  let _bamboocss_logger = require("@bamboocss/logger");
27
28
  let _bamboocss_config = require("@bamboocss/config");
@@ -40,6 +41,11 @@ let node_os = require("node:os");
40
41
  node_os = __toESM(node_os, 1);
41
42
  let node_tty = require("node:tty");
42
43
  node_tty = __toESM(node_tty, 1);
44
+ let node_fs = require("node:fs");
45
+ node_fs = __toESM(node_fs);
46
+ let node_path = require("node:path");
47
+ node_path = __toESM(node_path);
48
+ let ts_morph = require("ts-morph");
43
49
  let chokidar = require("chokidar");
44
50
  chokidar = __toESM(chokidar);
45
51
  let fast_glob = require("fast-glob");
@@ -48,17 +54,12 @@ let fs_extra = require("fs-extra");
48
54
  fs_extra = __toESM(fs_extra);
49
55
  let picomatch = require("picomatch");
50
56
  picomatch = __toESM(picomatch);
51
- let node_path = require("node:path");
52
- node_path = __toESM(node_path);
53
- let node_fs = require("node:fs");
54
- node_fs = __toESM(node_fs);
55
57
  let is_glob = require("is-glob");
56
58
  is_glob = __toESM(is_glob);
57
59
  let glob_parent = require("glob-parent");
58
60
  glob_parent = __toESM(glob_parent);
59
61
  let matcher = require("matcher");
60
62
  let _bamboocss_config_ts_path = require("@bamboocss/config/ts-path");
61
- let ts_morph = require("ts-morph");
62
63
  let node_readline = require("node:readline");
63
64
  node_readline = __toESM(node_readline);
64
65
  let look_it_up = require("look-it-up");
@@ -1405,7 +1406,345 @@ const createBox = (options) => boxen(options.content, {
1405
1406
  titleAlignment: "center"
1406
1407
  });
1407
1408
  //#endregion
1409
+ //#region src/tsconfig-utils.ts
1410
+ /**
1411
+ * If `filename` points to a `.json` file that exists as a regular file, return its absolute path.
1412
+ */
1413
+ async function resolveDirectTsconfigJson(filename) {
1414
+ if (node_path.default.extname(filename) !== ".json") return null;
1415
+ const resolved = node_path.default.resolve(filename);
1416
+ try {
1417
+ const stat = await node_fs.promises.stat(resolved);
1418
+ if (stat.isFile() || stat.isFIFO()) return resolved;
1419
+ throw new Error(`${filename} exists but is not a regular file.`);
1420
+ } catch (e) {
1421
+ if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return null;
1422
+ throw e;
1423
+ }
1424
+ }
1425
+ /**
1426
+ * Walk upward from `dirname(filename)` and return the first existing `configName`,
1427
+ * stopping at `root` (inclusive) or the filesystem root.
1428
+ */
1429
+ async function findClosestTsconfig(filename, root, configName = "tsconfig.json") {
1430
+ const resolvedRoot = node_path.default.resolve(root);
1431
+ let dir = node_path.default.dirname(node_path.default.resolve(filename));
1432
+ for (;;) {
1433
+ const candidate = node_path.default.join(dir, configName);
1434
+ try {
1435
+ const stat = await node_fs.promises.stat(candidate);
1436
+ if (stat.isFile() || stat.isFIFO()) return candidate;
1437
+ } catch {}
1438
+ if (dir === resolvedRoot || node_path.default.dirname(dir) === dir) return null;
1439
+ dir = node_path.default.dirname(dir);
1440
+ }
1441
+ }
1442
+ /**
1443
+ * Resolve `compilerOptions.baseUrl` the same way TypeScript does: relative to the tsconfig file.
1444
+ * Falls back to `cwd` when `baseUrl` is omitted.
1445
+ */
1446
+ function resolveBaseUrlForCompilerOptions(baseUrl, tsconfigFile, cwd) {
1447
+ if (baseUrl == null) return cwd;
1448
+ if (baseUrl.startsWith("${")) return baseUrl;
1449
+ if (node_path.default.isAbsolute(baseUrl)) return baseUrl;
1450
+ return node_path.default.resolve(node_path.default.dirname(tsconfigFile), baseUrl);
1451
+ }
1452
+ const SOURCE_EXTENSIONS = [
1453
+ ".ts",
1454
+ ".tsx",
1455
+ ".mts",
1456
+ ".cts"
1457
+ ];
1458
+ function resolveReferencedTsconfigPath(refPath, fromDir, configName = "tsconfig.json") {
1459
+ const p = refPath.endsWith(".json") ? refPath : node_path.default.join(refPath, configName);
1460
+ return node_path.default.resolve(fromDir, p);
1461
+ }
1462
+ /**
1463
+ * When a file belongs to a referenced project (TypeScript project references),
1464
+ * return that project's merged tsconfig for `compilerOptions`.
1465
+ */
1466
+ async function resolveSolutionTsconfigForFile(absoluteFilename, rootTsconfigPath, rootParsed, getTsconfigModule, cache) {
1467
+ const { parseTsconfig } = getTsconfigModule;
1468
+ if (isSourceFileIncludedInTsconfig(absoluteFilename, rootTsconfigPath, rootParsed)) return {
1469
+ tsconfig: rootParsed,
1470
+ tsconfigFile: rootTsconfigPath
1471
+ };
1472
+ const refs = rootParsed.references;
1473
+ if (!refs?.length) return {
1474
+ tsconfig: rootParsed,
1475
+ tsconfigFile: rootTsconfigPath
1476
+ };
1477
+ if (!SOURCE_EXTENSIONS.some((ext) => absoluteFilename.endsWith(ext))) return {
1478
+ tsconfig: rootParsed,
1479
+ tsconfigFile: rootTsconfigPath
1480
+ };
1481
+ const rootDir = node_path.default.dirname(rootTsconfigPath);
1482
+ for (const ref of refs) {
1483
+ const refPath = resolveReferencedTsconfigPath(ref.path, rootDir);
1484
+ try {
1485
+ await node_fs.promises.access(refPath);
1486
+ } catch {
1487
+ continue;
1488
+ }
1489
+ const childParsed = parseTsconfig(refPath, cache);
1490
+ if (isSourceFileIncludedInTsconfig(absoluteFilename, refPath, childParsed)) return {
1491
+ tsconfig: childParsed,
1492
+ tsconfigFile: refPath
1493
+ };
1494
+ }
1495
+ return {
1496
+ tsconfig: rootParsed,
1497
+ tsconfigFile: rootTsconfigPath
1498
+ };
1499
+ }
1500
+ const POSIX_SEP_RE = new RegExp("\\" + node_path.default.posix.sep, "g");
1501
+ const NATIVE_SEP_RE = new RegExp("\\" + node_path.default.sep, "g");
1502
+ const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
1503
+ const GLOB_ALL_PATTERN = `**/*`;
1504
+ const TS_EXTENSIONS = [
1505
+ ".ts",
1506
+ ".tsx",
1507
+ ".mts",
1508
+ ".cts"
1509
+ ];
1510
+ const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
1511
+ ".js",
1512
+ ".jsx",
1513
+ ".mjs",
1514
+ ".cjs"
1515
+ ]);
1516
+ const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
1517
+ const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
1518
+ const IS_POSIX = node_path.default.posix.sep === node_path.default.sep;
1519
+ const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, node_path.default.posix.sep);
1520
+ const resolve2posix = IS_POSIX ? (dir, filename) => dir ? node_path.default.resolve(dir, filename) : node_path.default.resolve(filename) : (dir, filename) => {
1521
+ const posix2native = (f) => f.replace(POSIX_SEP_RE, node_path.default.sep);
1522
+ return native2posix(dir ? node_path.default.resolve(posix2native(dir), posix2native(filename)) : node_path.default.resolve(posix2native(filename)));
1523
+ };
1524
+ function isGlobMatch(filename, dir, patterns, allowJs) {
1525
+ const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
1526
+ return patterns.some((patternArg) => {
1527
+ let pattern = patternArg;
1528
+ let lastWildcardIndex = pattern.length;
1529
+ let hasWildcard = false;
1530
+ let hasExtension = false;
1531
+ let hasSlash = false;
1532
+ let lastSlashIndex = -1;
1533
+ for (let i = pattern.length - 1; i > -1; i--) {
1534
+ const c = pattern[i];
1535
+ if (!hasWildcard) {
1536
+ if (c === "*" || c === "?") {
1537
+ lastWildcardIndex = i;
1538
+ hasWildcard = true;
1539
+ }
1540
+ }
1541
+ if (!hasSlash) {
1542
+ if (c === ".") hasExtension = true;
1543
+ else if (c === "/") {
1544
+ lastSlashIndex = i;
1545
+ hasSlash = true;
1546
+ }
1547
+ }
1548
+ if (hasWildcard && hasSlash) break;
1549
+ }
1550
+ if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
1551
+ pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
1552
+ lastWildcardIndex = pattern.length - 1;
1553
+ hasWildcard = true;
1554
+ }
1555
+ if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
1556
+ if (pattern.endsWith("*") && !extensions.some((ext) => filename.endsWith(ext))) return false;
1557
+ if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
1558
+ const resolvedPattern = resolve2posix(dir, pattern);
1559
+ let firstWildcardIndex = -1;
1560
+ for (let i = 0; i < resolvedPattern.length; i++) if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
1561
+ firstWildcardIndex = i;
1562
+ hasWildcard = true;
1563
+ break;
1564
+ }
1565
+ if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
1566
+ if (!hasWildcard) return filename === resolvedPattern;
1567
+ if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true;
1568
+ if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
1569
+ const regex = pattern2regex(resolvedPattern, allowJs);
1570
+ PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
1571
+ return regex.test(filename);
1572
+ });
1573
+ }
1574
+ function pattern2regex(resolvedPattern, allowJs) {
1575
+ let regexStr = "^";
1576
+ for (let i = 0; i < resolvedPattern.length; i++) {
1577
+ const char = resolvedPattern[i];
1578
+ if (char === "?") {
1579
+ regexStr += "[^\\/]";
1580
+ continue;
1581
+ }
1582
+ if (char === "*") {
1583
+ if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
1584
+ i += 2;
1585
+ regexStr += "(?:[^\\/]*\\/)*";
1586
+ continue;
1587
+ }
1588
+ regexStr += "[^\\/]*";
1589
+ continue;
1590
+ }
1591
+ if ("/.+^${}()|[]\\".includes(char)) regexStr += "\\";
1592
+ regexStr += char;
1593
+ }
1594
+ if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
1595
+ regexStr += "$";
1596
+ return new RegExp(regexStr);
1597
+ }
1598
+ function isIncluded(filename, tsconfigFile, tsconfig) {
1599
+ const dir = native2posix(node_path.default.dirname(tsconfigFile));
1600
+ const files = (tsconfig.files || []).map((file) => resolve2posix(dir, file));
1601
+ const absoluteFilename = resolve2posix(null, filename);
1602
+ if (files.includes(filename)) return true;
1603
+ const allowJs = tsconfig.compilerOptions?.allowJs;
1604
+ if (isGlobMatch(absoluteFilename, dir, tsconfig.include || (tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, tsconfig.exclude || [], allowJs);
1605
+ return false;
1606
+ }
1607
+ /** Whether `absoluteFilename` is part of the compilation set defined by this tsconfig. */
1608
+ function isSourceFileIncludedInTsconfig(absoluteFilename, tsconfigFile, tsconfig) {
1609
+ return isIncluded(absoluteFilename, tsconfigFile, tsconfig);
1610
+ }
1611
+ //#endregion
1612
+ //#region src/load-tsconfig.ts
1613
+ const readPathsFromCache = (cache) => {
1614
+ const prefix = "readFileSync:";
1615
+ const suffix = ":utf8";
1616
+ return Array.from(cache.keys()).filter((key) => key.startsWith(prefix) && key.endsWith(suffix)).map((key) => key.slice(13, -5));
1617
+ };
1618
+ /**
1619
+ * Exact tsconfig files read while producing one resolved Node config.
1620
+ *
1621
+ * This metadata is deliberately kept outside `LoadConfigResult`: it is incremental resolver
1622
+ * provenance, not Bamboo configuration, and must therefore neither participate in
1623
+ * `diffConfigs` nor become part of the public/serialized config shape.
1624
+ */
1625
+ const resolutionFilesByConfig = /* @__PURE__ */ new WeakMap();
1626
+ const rememberTsConfigResolutionFiles = (conf, files) => {
1627
+ resolutionFilesByConfig.set(conf, Object.freeze([...new Set(files)].sort()));
1628
+ };
1629
+ const getTsConfigResolutionFiles = (conf) => resolutionFilesByConfig.get(conf) ?? Object.freeze(conf.tsconfigFile ? [node_path.default.resolve(conf.tsconfigFile)] : []);
1630
+ const referencedTsconfigPath = (reference, rootPath) => node_path.default.resolve(node_path.default.dirname(rootPath), reference.endsWith(".json") ? reference : node_path.default.join(reference, "tsconfig.json"));
1631
+ const MAX_TSCONFIG_REFERENCE_FILES = 256;
1632
+ const getImplicitBaseUrl = (compilerOptions) => {
1633
+ if (!compilerOptions) return void 0;
1634
+ const matches = Object.getOwnPropertySymbols(compilerOptions).filter((candidate) => candidate.description === "implicitBaseUrl");
1635
+ if (matches.length !== 1) return void 0;
1636
+ const symbol = matches[0];
1637
+ const descriptor = Object.getOwnPropertyDescriptor(compilerOptions, symbol);
1638
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "string") return void 0;
1639
+ return {
1640
+ owner: compilerOptions,
1641
+ symbol,
1642
+ value: descriptor.value
1643
+ };
1644
+ };
1645
+ const collectReferenceGraph = async (rootPath, rootParsed, parseTsconfig, cache) => {
1646
+ const references = [];
1647
+ const unresolvedReferences = [];
1648
+ let traversalLimitExceeded = false;
1649
+ const visited = new Set([node_path.default.resolve(rootPath)]);
1650
+ const queue = [{
1651
+ parsed: rootParsed,
1652
+ path: rootPath
1653
+ }];
1654
+ for (let index = 0; index < queue.length; index++) {
1655
+ const current = queue[index];
1656
+ for (const reference of current.parsed.references ?? []) {
1657
+ const referencedPath = referencedTsconfigPath(reference.path, current.path);
1658
+ references.push({
1659
+ from: current.path,
1660
+ path: referencedPath
1661
+ });
1662
+ if (visited.has(referencedPath)) continue;
1663
+ if (visited.size >= MAX_TSCONFIG_REFERENCE_FILES) {
1664
+ traversalLimitExceeded = true;
1665
+ unresolvedReferences.push(referencedPath);
1666
+ continue;
1667
+ }
1668
+ visited.add(referencedPath);
1669
+ try {
1670
+ const source = await node_fs.promises.readFile(referencedPath, "utf8");
1671
+ if (ts_morph.ts.parseConfigFileTextToJson(referencedPath, source).error) throw new Error("Invalid tsconfig");
1672
+ queue.push({
1673
+ parsed: parseTsconfig(referencedPath, cache),
1674
+ path: referencedPath
1675
+ });
1676
+ } catch {
1677
+ unresolvedReferences.push(referencedPath);
1678
+ }
1679
+ }
1680
+ }
1681
+ return {
1682
+ references,
1683
+ traversalLimitExceeded,
1684
+ unresolvedReferences
1685
+ };
1686
+ };
1687
+ async function loadTsConfig(conf, cwd, provenance, resolutionFiles) {
1688
+ const root = cwd;
1689
+ let tsconfigFile = await resolveDirectTsconfigJson(conf.path);
1690
+ const direct = tsconfigFile !== null;
1691
+ if (!tsconfigFile) {
1692
+ if (resolutionFiles) resolutionFiles.value = Object.freeze([]);
1693
+ tsconfigFile = await findClosestTsconfig(conf.path, root, "tsconfig.json");
1694
+ }
1695
+ if (!tsconfigFile) {
1696
+ if (provenance) provenance.value = {
1697
+ direct: false,
1698
+ readPaths: [],
1699
+ references: [],
1700
+ traversalLimitExceeded: false,
1701
+ unresolvedReferences: []
1702
+ };
1703
+ return {
1704
+ tsconfig: {},
1705
+ tsconfigFile: void 0
1706
+ };
1707
+ }
1708
+ const gtc = await import("get-tsconfig");
1709
+ const cache = /* @__PURE__ */ new Map();
1710
+ const rootParsed = gtc.parseTsconfig(tsconfigFile, cache);
1711
+ const { tsconfig, tsconfigFile: effectiveTsconfigPath } = await resolveSolutionTsconfigForFile(node_path.default.resolve(conf.path), tsconfigFile, rootParsed, gtc, cache);
1712
+ const compilerOptions = tsconfig?.compilerOptions;
1713
+ const implicitBaseUrl = getImplicitBaseUrl(compilerOptions);
1714
+ const result = {
1715
+ tsconfig,
1716
+ tsconfigFile: effectiveTsconfigPath
1717
+ };
1718
+ if (resolutionFiles) resolutionFiles.value = Object.freeze([...new Set(readPathsFromCache(cache).map((file) => node_path.default.resolve(file)))].sort());
1719
+ if (compilerOptions?.paths) {
1720
+ const baseUrl = compilerOptions.baseUrl;
1721
+ result.tsOptions = {
1722
+ baseUrl,
1723
+ pathMappings: (0, _bamboocss_config.convertTsPathsToRegexes)(compilerOptions.paths, resolveBaseUrlForCompilerOptions(baseUrl, effectiveTsconfigPath, cwd))
1724
+ };
1725
+ }
1726
+ if (provenance) {
1727
+ const referenceGraph = await collectReferenceGraph(tsconfigFile, rootParsed, gtc.parseTsconfig, cache);
1728
+ provenance.value = {
1729
+ direct,
1730
+ effectivePath: effectiveTsconfigPath,
1731
+ implicitBaseUrl,
1732
+ readPaths: readPathsFromCache(cache),
1733
+ references: referenceGraph.references,
1734
+ rootPath: tsconfigFile,
1735
+ traversalLimitExceeded: referenceGraph.traversalLimitExceeded,
1736
+ unresolvedReferences: referenceGraph.unresolvedReferences
1737
+ };
1738
+ }
1739
+ return result;
1740
+ }
1741
+ //#endregion
1408
1742
  //#region src/diff-engine.ts
1743
+ const applyTsConfig = (conf, next) => {
1744
+ conf.tsconfig = next?.tsconfig ?? {};
1745
+ conf.tsconfigFile = next?.tsconfigFile;
1746
+ conf.tsOptions = next?.tsOptions;
1747
+ };
1409
1748
  var DiffEngine = class {
1410
1749
  ctx;
1411
1750
  prevConfig;
@@ -1421,14 +1760,19 @@ var DiffEngine = class {
1421
1760
  cwd: this.ctx.config.cwd,
1422
1761
  file: this.ctx.conf.path
1423
1762
  });
1424
- const { tsconfig, tsconfigFile, tsOptions } = this.ctx.conf;
1425
- Object.assign(conf, {
1426
- tsconfig,
1427
- tsconfigFile,
1428
- tsOptions
1429
- });
1430
- return this.refresh(conf, fn);
1763
+ const resolutionFiles = {};
1764
+ const tsconfig = await loadTsConfig(conf, conf.config.cwd || this.ctx.config.cwd, void 0, resolutionFiles);
1765
+ applyTsConfig(conf, tsconfig);
1766
+ rememberTsConfigResolutionFiles(conf, resolutionFiles.value ?? []);
1767
+ const affected = this.refresh(conf, fn);
1768
+ if (!affected.hasConfigChanged) {
1769
+ applyTsConfig(this.ctx.conf, tsconfig);
1770
+ rememberTsConfigResolutionFiles(this.ctx.conf, resolutionFiles.value ?? []);
1771
+ }
1772
+ return affected;
1431
1773
  }
1774
+ /** @internal Exact tsconfig files behind the currently attached resolution options. */
1775
+ getResolutionConfigFiles = () => getTsConfigResolutionFiles(this.ctx.conf);
1432
1776
  /**
1433
1777
  * Update the context from the refreshed config
1434
1778
  * then persist the changes on each affected engines
@@ -1742,8 +2086,10 @@ var BambooContext = class extends _bamboocss_generator.Generator {
1742
2086
  if (config.logLevel) _bamboocss_logger.logger.level = config.logLevel;
1743
2087
  this.project = new _bamboocss_parser.Project({
1744
2088
  ...conf.tsconfig,
1745
- getFiles: this.getFiles.bind(this),
1746
- readFile: this.runtime.fs.readFileSync.bind(this),
2089
+ deferInitialSourceFiles: true,
2090
+ resolutionConfigFiles: getTsConfigResolutionFiles(conf),
2091
+ getFiles: () => this.getFiles(),
2092
+ readFile: (filePath) => this.runtime.fs.readFileSync(filePath),
1747
2093
  hooks: conf.hooks,
1748
2094
  parserOptions: {
1749
2095
  ...this.parserOptions,
@@ -2047,238 +2393,13 @@ async function reportRebuildFailure(run) {
2047
2393
  }
2048
2394
  }
2049
2395
  //#endregion
2050
- //#region src/tsconfig-utils.ts
2051
- /**
2052
- * If `filename` points to a `.json` file that exists as a regular file, return its absolute path.
2053
- */
2054
- async function resolveDirectTsconfigJson(filename) {
2055
- if (node_path.default.extname(filename) !== ".json") return null;
2056
- const resolved = node_path.default.resolve(filename);
2057
- try {
2058
- const stat = await node_fs.promises.stat(resolved);
2059
- if (stat.isFile() || stat.isFIFO()) return resolved;
2060
- throw new Error(`${filename} exists but is not a regular file.`);
2061
- } catch (e) {
2062
- if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return null;
2063
- throw e;
2064
- }
2065
- }
2066
- /**
2067
- * Walk upward from `dirname(filename)` and return the first existing `configName`,
2068
- * stopping at `root` (inclusive) or the filesystem root.
2069
- */
2070
- async function findClosestTsconfig(filename, root, configName = "tsconfig.json") {
2071
- const resolvedRoot = node_path.default.resolve(root);
2072
- let dir = node_path.default.dirname(node_path.default.resolve(filename));
2073
- for (;;) {
2074
- const candidate = node_path.default.join(dir, configName);
2075
- try {
2076
- const stat = await node_fs.promises.stat(candidate);
2077
- if (stat.isFile() || stat.isFIFO()) return candidate;
2078
- } catch {}
2079
- if (dir === resolvedRoot || node_path.default.dirname(dir) === dir) return null;
2080
- dir = node_path.default.dirname(dir);
2081
- }
2082
- }
2083
- /**
2084
- * Resolve `compilerOptions.baseUrl` the same way TypeScript does: relative to the tsconfig file.
2085
- * Falls back to `cwd` when `baseUrl` is omitted.
2086
- */
2087
- function resolveBaseUrlForCompilerOptions(baseUrl, tsconfigFile, cwd) {
2088
- if (baseUrl == null) return cwd;
2089
- if (baseUrl.startsWith("${")) return baseUrl;
2090
- if (node_path.default.isAbsolute(baseUrl)) return baseUrl;
2091
- return node_path.default.resolve(node_path.default.dirname(tsconfigFile), baseUrl);
2092
- }
2093
- const SOURCE_EXTENSIONS = [
2094
- ".ts",
2095
- ".tsx",
2096
- ".mts",
2097
- ".cts"
2098
- ];
2099
- function resolveReferencedTsconfigPath(refPath, fromDir, configName = "tsconfig.json") {
2100
- const p = refPath.endsWith(".json") ? refPath : node_path.default.join(refPath, configName);
2101
- return node_path.default.resolve(fromDir, p);
2102
- }
2103
- /**
2104
- * When a file belongs to a referenced project (TypeScript project references),
2105
- * return that project's merged tsconfig for `compilerOptions`.
2106
- */
2107
- async function resolveSolutionTsconfigForFile(absoluteFilename, rootTsconfigPath, rootParsed, getTsconfigModule) {
2108
- const { parseTsconfig } = getTsconfigModule;
2109
- if (isSourceFileIncludedInTsconfig(absoluteFilename, rootTsconfigPath, rootParsed)) return {
2110
- tsconfig: rootParsed,
2111
- tsconfigFile: rootTsconfigPath
2112
- };
2113
- const refs = rootParsed.references;
2114
- if (!refs?.length) return {
2115
- tsconfig: rootParsed,
2116
- tsconfigFile: rootTsconfigPath
2117
- };
2118
- if (!SOURCE_EXTENSIONS.some((ext) => absoluteFilename.endsWith(ext))) return {
2119
- tsconfig: rootParsed,
2120
- tsconfigFile: rootTsconfigPath
2121
- };
2122
- const rootDir = node_path.default.dirname(rootTsconfigPath);
2123
- for (const ref of refs) {
2124
- const refPath = resolveReferencedTsconfigPath(ref.path, rootDir);
2125
- try {
2126
- await node_fs.promises.access(refPath);
2127
- } catch {
2128
- continue;
2129
- }
2130
- const childParsed = parseTsconfig(refPath);
2131
- if (isSourceFileIncludedInTsconfig(absoluteFilename, refPath, childParsed)) return {
2132
- tsconfig: childParsed,
2133
- tsconfigFile: refPath
2134
- };
2135
- }
2136
- return {
2137
- tsconfig: rootParsed,
2138
- tsconfigFile: rootTsconfigPath
2139
- };
2140
- }
2141
- const POSIX_SEP_RE = new RegExp("\\" + node_path.default.posix.sep, "g");
2142
- const NATIVE_SEP_RE = new RegExp("\\" + node_path.default.sep, "g");
2143
- const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
2144
- const GLOB_ALL_PATTERN = `**/*`;
2145
- const TS_EXTENSIONS = [
2146
- ".ts",
2147
- ".tsx",
2148
- ".mts",
2149
- ".cts"
2150
- ];
2151
- const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
2152
- ".js",
2153
- ".jsx",
2154
- ".mjs",
2155
- ".cjs"
2156
- ]);
2157
- const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
2158
- const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})`;
2159
- const IS_POSIX = node_path.default.posix.sep === node_path.default.sep;
2160
- const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, node_path.default.posix.sep);
2161
- const resolve2posix = IS_POSIX ? (dir, filename) => dir ? node_path.default.resolve(dir, filename) : node_path.default.resolve(filename) : (dir, filename) => {
2162
- const posix2native = (f) => f.replace(POSIX_SEP_RE, node_path.default.sep);
2163
- return native2posix(dir ? node_path.default.resolve(posix2native(dir), posix2native(filename)) : node_path.default.resolve(posix2native(filename)));
2164
- };
2165
- function isGlobMatch(filename, dir, patterns, allowJs) {
2166
- const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
2167
- return patterns.some((patternArg) => {
2168
- let pattern = patternArg;
2169
- let lastWildcardIndex = pattern.length;
2170
- let hasWildcard = false;
2171
- let hasExtension = false;
2172
- let hasSlash = false;
2173
- let lastSlashIndex = -1;
2174
- for (let i = pattern.length - 1; i > -1; i--) {
2175
- const c = pattern[i];
2176
- if (!hasWildcard) {
2177
- if (c === "*" || c === "?") {
2178
- lastWildcardIndex = i;
2179
- hasWildcard = true;
2180
- }
2181
- }
2182
- if (!hasSlash) {
2183
- if (c === ".") hasExtension = true;
2184
- else if (c === "/") {
2185
- lastSlashIndex = i;
2186
- hasSlash = true;
2187
- }
2188
- }
2189
- if (hasWildcard && hasSlash) break;
2190
- }
2191
- if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
2192
- pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
2193
- lastWildcardIndex = pattern.length - 1;
2194
- hasWildcard = true;
2195
- }
2196
- if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
2197
- if (pattern.endsWith("*") && !extensions.some((ext) => filename.endsWith(ext))) return false;
2198
- if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
2199
- const resolvedPattern = resolve2posix(dir, pattern);
2200
- let firstWildcardIndex = -1;
2201
- for (let i = 0; i < resolvedPattern.length; i++) if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
2202
- firstWildcardIndex = i;
2203
- hasWildcard = true;
2204
- break;
2205
- }
2206
- if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
2207
- if (!hasWildcard) return filename === resolvedPattern;
2208
- if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true;
2209
- if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
2210
- const regex = pattern2regex(resolvedPattern, allowJs);
2211
- PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
2212
- return regex.test(filename);
2213
- });
2214
- }
2215
- function pattern2regex(resolvedPattern, allowJs) {
2216
- let regexStr = "^";
2217
- for (let i = 0; i < resolvedPattern.length; i++) {
2218
- const char = resolvedPattern[i];
2219
- if (char === "?") {
2220
- regexStr += "[^\\/]";
2221
- continue;
2222
- }
2223
- if (char === "*") {
2224
- if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
2225
- i += 2;
2226
- regexStr += "(?:[^\\/]*\\/)*";
2227
- continue;
2228
- }
2229
- regexStr += "[^\\/]*";
2230
- continue;
2231
- }
2232
- if ("/.+^${}()|[]\\".includes(char)) regexStr += "\\";
2233
- regexStr += char;
2234
- }
2235
- if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
2236
- regexStr += "$";
2237
- return new RegExp(regexStr);
2238
- }
2239
- function isIncluded(filename, tsconfigFile, tsconfig) {
2240
- const dir = native2posix(node_path.default.dirname(tsconfigFile));
2241
- const files = (tsconfig.files || []).map((file) => resolve2posix(dir, file));
2242
- const absoluteFilename = resolve2posix(null, filename);
2243
- if (files.includes(filename)) return true;
2244
- const allowJs = tsconfig.compilerOptions?.allowJs;
2245
- if (isGlobMatch(absoluteFilename, dir, tsconfig.include || (tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, tsconfig.exclude || [], allowJs);
2246
- return false;
2247
- }
2248
- /** Whether `absoluteFilename` is part of the compilation set defined by this tsconfig. */
2249
- function isSourceFileIncludedInTsconfig(absoluteFilename, tsconfigFile, tsconfig) {
2250
- return isIncluded(absoluteFilename, tsconfigFile, tsconfig);
2251
- }
2252
- //#endregion
2253
- //#region src/load-tsconfig.ts
2254
- async function loadTsConfig(conf, cwd) {
2255
- const root = cwd;
2256
- let tsconfigFile = await resolveDirectTsconfigJson(conf.path);
2257
- if (!tsconfigFile) tsconfigFile = await findClosestTsconfig(conf.path, root, "tsconfig.json");
2258
- if (!tsconfigFile) return {
2259
- tsconfig: {},
2260
- tsconfigFile: void 0
2261
- };
2262
- const gtc = await import("get-tsconfig");
2263
- const rootParsed = gtc.parseTsconfig(tsconfigFile);
2264
- const { tsconfig, tsconfigFile: effectiveTsconfigPath } = await resolveSolutionTsconfigForFile(node_path.default.resolve(conf.path), tsconfigFile, rootParsed, gtc);
2265
- const compilerOptions = tsconfig?.compilerOptions;
2266
- const result = {
2267
- tsconfig,
2268
- tsconfigFile: effectiveTsconfigPath
2269
- };
2270
- if (compilerOptions?.paths) {
2271
- const baseUrl = compilerOptions.baseUrl;
2272
- result.tsOptions = {
2273
- baseUrl,
2274
- pathMappings: (0, _bamboocss_config.convertTsPathsToRegexes)(compilerOptions.paths, resolveBaseUrlForCompilerOptions(baseUrl, effectiveTsconfigPath, cwd))
2275
- };
2276
- }
2277
- return result;
2278
- }
2279
- //#endregion
2280
2396
  //#region src/config.ts
2281
2397
  const RESOLVED_HOOKS_NAME = "__resolved__";
2398
+ const AUTO_PARSER_HOOKS = Object.freeze(["vue", "svelte"]);
2399
+ const autoPluginFactories = {
2400
+ svelte: _bamboocss_plugin_svelte.pluginSvelte,
2401
+ vue: _bamboocss_plugin_vue.pluginVue
2402
+ };
2282
2403
  /**
2283
2404
  * Built-in plugins that are auto-injected when using the CLI or PostCSS plugin.
2284
2405
  * These provide Vue/Svelte single-file-component support.
@@ -2291,13 +2412,10 @@ const RESOLVED_HOOKS_NAME = "__resolved__";
2291
2412
  * ever set. List the plugin yourself to use it.
2292
2413
  */
2293
2414
  function getAutoPlugins() {
2294
- return [(0, _bamboocss_plugin_vue.pluginVue)(), (0, _bamboocss_plugin_svelte.pluginSvelte)()];
2415
+ return AUTO_PARSER_HOOKS.map((identity) => autoPluginFactories[identity]());
2295
2416
  }
2296
- /**
2297
- * Load config and create context with auto-injected plugins.
2298
- * Used by the CLI and PostCSS plugin.
2299
- */
2300
- async function loadConfigAndCreateContext(options = {}) {
2417
+ /** Resolve all config state without constructing the parser Project owned by BambooContext. */
2418
+ async function prepareNodeConfig(options = {}) {
2301
2419
  const { config, configPath } = options;
2302
2420
  const cwd = options.cwd ?? options?.config?.cwd ?? process.cwd();
2303
2421
  const conf = await (0, _bamboocss_config.loadConfig)({
@@ -2313,8 +2431,18 @@ async function loadConfigAndCreateContext(options = {}) {
2313
2431
  hooks: conf.hooks
2314
2432
  }]);
2315
2433
  conf.config.plugins = [...autoPlugins, ...conf.config.plugins ?? []];
2316
- const tsConfResult = await loadTsConfig(conf, cwd);
2434
+ const tsconfigResolutionFiles = {};
2435
+ const tsConfResult = await loadTsConfig(conf, cwd, void 0, tsconfigResolutionFiles);
2317
2436
  if (tsConfResult) Object.assign(conf, tsConfResult);
2437
+ rememberTsConfigResolutionFiles(conf, tsconfigResolutionFiles.value ?? []);
2438
+ return { conf };
2439
+ }
2440
+ /**
2441
+ * Load config and create context with auto-injected plugins.
2442
+ * Used by the CLI and PostCSS plugin.
2443
+ */
2444
+ async function loadConfigAndCreateContext(options = {}) {
2445
+ const { conf } = await prepareNodeConfig(options);
2318
2446
  return new BambooContext(conf);
2319
2447
  }
2320
2448
  //#endregion
@@ -3128,20 +3256,82 @@ var Builder = class {
3128
3256
  explicitDepsMeta;
3129
3257
  affecteds;
3130
3258
  configDependencies = /* @__PURE__ */ new Set();
3259
+ pendingConfigCrawl;
3260
+ /** Last complete included inventory, including members which have since been deleted. */
3261
+ sourceInventory;
3262
+ /** Existing included owners selected by the last resolution-ledger invalidation pass. */
3263
+ affectedFiles;
3264
+ /** Dependency-before-importer parse order for the selected owners. */
3265
+ extractionOrder;
3266
+ /** Exact cross-file semantic reads retained per included extraction owner. */
3267
+ resolutionReadSets = /* @__PURE__ */ new Map();
3268
+ /** Previously semantic paths which are absent, retained only while their owner is unchanged. */
3269
+ pendingResolutionReadSets = /* @__PURE__ */ new Map();
3270
+ /** Missing local priority candidates which can redirect a current semantic resolution. */
3271
+ resolutionCandidateSets = /* @__PURE__ */ new Map();
3272
+ /** Exact resolver configuration reads retained per included semantic owner. */
3273
+ resolutionConfigurationSets = /* @__PURE__ */ new Map();
3274
+ /** Byte snapshots for resolver configuration files, independent of filesystem mtimes. */
3275
+ resolutionConfigurationBytes = /* @__PURE__ */ new Map();
3276
+ /** Previous effective tsconfig read-set, needed to classify its deletion as an option reload. */
3277
+ tsconfigResolutionFiles = [];
3278
+ /** @internal Current and missing resolver paths which can change the stylesheet. */
3279
+ getResolutionReadFiles = () => {
3280
+ const files = /* @__PURE__ */ new Set();
3281
+ for (const readSets of [
3282
+ this.resolutionReadSets,
3283
+ this.pendingResolutionReadSets,
3284
+ this.resolutionCandidateSets
3285
+ ]) for (const dependencies of readSets.values()) for (const dependency of dependencies) files.add(dependency);
3286
+ return Object.freeze([...files].sort());
3287
+ };
3288
+ /** @internal Exact local package/tsconfig files which can change semantic resolution. */
3289
+ getResolutionConfigurationFiles = () => {
3290
+ const files = /* @__PURE__ */ new Set();
3291
+ for (const configurations of this.resolutionConfigurationSets.values()) for (const configuration of configurations) files.add(configuration);
3292
+ return Object.freeze([...files].sort());
3293
+ };
3294
+ readResolutionConfiguration = (file) => {
3295
+ try {
3296
+ return (0, fs.readFileSync)(file).toString("base64");
3297
+ } catch (error) {
3298
+ if (error?.code === "ENOENT") return void 0;
3299
+ throw error;
3300
+ }
3301
+ };
3302
+ changedResolutionConfigurations = () => this.getResolutionConfigurationFiles().filter((file) => this.resolutionConfigurationBytes.get(file) !== this.readResolutionConfiguration(file));
3303
+ snapshotResolutionConfigurations = () => {
3304
+ const current = new Set(this.getResolutionConfigurationFiles());
3305
+ for (const file of current) this.resolutionConfigurationBytes.set(file, this.readResolutionConfiguration(file));
3306
+ for (const file of this.resolutionConfigurationBytes.keys()) if (!current.has(file)) this.resolutionConfigurationBytes.delete(file);
3307
+ };
3308
+ /**
3309
+ * Remember what to crawl; do not crawl yet.
3310
+ *
3311
+ * The crawl walks the config's own import graph, and resolving a bare specifier there loads a
3312
+ * whole TypeScript compiler. Only `registerDependency` reads the result, and only the PostCSS
3313
+ * plugin calls that — the CLI and the Vite plugin (which crawls separately, when it watches)
3314
+ * paid ~155ms of compiler load per build for a set neither of them ever read.
3315
+ */
3131
3316
  setConfigDependencies(options) {
3317
+ this.pendingConfigCrawl = options;
3318
+ const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
3319
+ for (const file of this.context?.conf.dependencies ?? []) this.configDependencies.add((0, path.resolve)(cwd, file));
3320
+ }
3321
+ /** Crawl on first read, once per `setConfigDependencies`. */
3322
+ crawlConfigDependencies() {
3323
+ const options = this.pendingConfigCrawl;
3324
+ if (!options) return;
3325
+ this.pendingConfigCrawl = void 0;
3132
3326
  const tsOptions = this.context?.conf.tsOptions ?? {
3133
3327
  baseUrl: void 0,
3134
3328
  pathMappings: []
3135
3329
  };
3136
3330
  const compilerOptions = this.context?.conf.tsconfig?.compilerOptions ?? {};
3137
- const { deps: foundDeps } = (0, _bamboocss_config.getConfigDependencies)(options.configPath, tsOptions, compilerOptions);
3138
- const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
3139
- const configDeps = new Set([...foundDeps, ...(this.context?.conf.dependencies ?? []).map((file) => (0, path.resolve)(cwd, file))]);
3140
- configDeps.forEach((file) => {
3141
- this.configDependencies.add(file);
3142
- });
3331
+ const { deps } = (0, _bamboocss_config.getConfigDependencies)(options.configPath, tsOptions, compilerOptions);
3332
+ deps.forEach((file) => this.configDependencies.add(file));
3143
3333
  _bamboocss_logger.logger.debug("builder", "Config dependencies");
3144
- _bamboocss_logger.logger.debug("builder", configDeps);
3334
+ _bamboocss_logger.logger.debug("builder", deps);
3145
3335
  }
3146
3336
  setup = async (options = {}) => {
3147
3337
  _bamboocss_logger.logger.debug("builder", "🚧 Setup");
@@ -3156,9 +3346,11 @@ var Builder = class {
3156
3346
  dev: options.dev
3157
3347
  });
3158
3348
  const ctx = this.getContextOrThrow();
3349
+ const previousTsconfigFiles = this.tsconfigResolutionFiles.length ? this.tsconfigResolutionFiles : ctx.diff.getResolutionConfigFiles();
3159
3350
  this.affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
3160
3351
  this.context = new BambooContext(conf);
3161
3352
  });
3353
+ this.tsconfigResolutionFiles = this.getContextOrThrow().diff.getResolutionConfigFiles();
3162
3354
  _bamboocss_logger.logger.debug("builder", this.affecteds);
3163
3355
  this.explicitDepsMeta = this.checkFilesChanged(this.context.explicitDeps);
3164
3356
  if (this.explicitDepsMeta.hasFilesChanged) {
@@ -3170,17 +3362,125 @@ var Builder = class {
3170
3362
  }
3171
3363
  if (this.affecteds.hasConfigChanged) {
3172
3364
  _bamboocss_logger.logger.debug("builder", "⚙️ Config changed, reloading");
3365
+ this.filesMeta = void 0;
3366
+ this.affectedFiles = void 0;
3367
+ this.extractionOrder = void 0;
3368
+ this.sourceInventory = void 0;
3369
+ this.resolutionReadSets.clear();
3370
+ this.pendingResolutionReadSets.clear();
3371
+ this.resolutionCandidateSets.clear();
3372
+ this.resolutionConfigurationSets.clear();
3373
+ this.resolutionConfigurationBytes.clear();
3173
3374
  await ctx.hooks["config:change"]?.({
3174
3375
  config: ctx.config,
3175
3376
  changes: this.affecteds
3176
3377
  });
3177
3378
  return;
3178
3379
  }
3179
- this.filesMeta = this.checkFilesChanged(ctx.getFiles());
3380
+ const changedResolutionConfigurations = this.changedResolutionConfigurations();
3381
+ const changedResolutionSet = new Set(changedResolutionConfigurations);
3382
+ const resolutionAffected = /* @__PURE__ */ new Set();
3383
+ const resolutionLedger = changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0;
3384
+ for (const [owner, configurations] of this.resolutionConfigurationSets) if (configurations.some((file) => changedResolutionSet.has(file))) resolutionAffected.add(owner);
3385
+ if (changedResolutionConfigurations.length) {
3386
+ const tsconfigCandidates = new Set([...previousTsconfigFiles, ...this.tsconfigResolutionFiles]);
3387
+ const replaceCompilerOptions = changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file));
3388
+ ctx.project.refreshResolutionConfiguration(ctx.conf.tsconfig?.compilerOptions, this.tsconfigResolutionFiles, replaceCompilerOptions);
3389
+ }
3390
+ const inventory = ctx.getFiles();
3391
+ const tracked = (0, _bamboocss_shared.uniq)([
3392
+ ...this.sourceInventory ?? inventory,
3393
+ ...inventory,
3394
+ ...this.getResolutionReadFiles()
3395
+ ]);
3396
+ this.filesMeta = this.checkFilesChanged(tracked);
3180
3397
  if (this.filesMeta.hasFilesChanged) {
3181
3398
  _bamboocss_logger.logger.debug("builder", "Files changed, invalidating them");
3182
- ctx.project.reloadSourceFiles();
3399
+ this.invalidateChangedSources(ctx, inventory, resolutionAffected, resolutionLedger);
3400
+ } else if (changedResolutionConfigurations.length) {
3401
+ ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
3402
+ this.extractionOrder = this.orderAffectedFiles(inventory, resolutionAffected, resolutionLedger ?? [], []);
3403
+ this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
3404
+ } else {
3405
+ this.affectedFiles = /* @__PURE__ */ new Set();
3406
+ this.extractionOrder = [];
3183
3407
  }
3408
+ this.sourceInventory = [...inventory];
3409
+ };
3410
+ /** Normalize the path identity shared by the Project ledger and file-owner keys. */
3411
+ sourcePath = (file) => file.replaceAll("\\", "/");
3412
+ /**
3413
+ * Reload only changed ledger members, then select their transitive included consumers.
3414
+ *
3415
+ * The dependency graph is snapshotted before mutation: reloading an importer retracts its
3416
+ * old forward edges, while deletion removes the target. Waiting until afterwards loses the
3417
+ * very closure the rebuild needs. New targets also select every pending importer and each
3418
+ * pending importer's dependent closure, because no edge to the new path existed yet.
3419
+ */
3420
+ invalidateChangedSources = (ctx, inventory, seededAffected = /* @__PURE__ */ new Set(), previousLedger) => {
3421
+ const project = ctx.project;
3422
+ const current = new Set(inventory.map(this.sourcePath));
3423
+ const changed = [...this.filesMeta?.changes ?? []].filter(([, meta]) => !meta.isUnchanged).map(([file]) => this.sourcePath(file));
3424
+ const ledger = previousLedger ?? project.getResolutionLedger();
3425
+ const pending = project.getUnresolvedImporters().map(this.sourcePath);
3426
+ const affected = new Set(seededAffected);
3427
+ const added = [];
3428
+ for (const file of changed) {
3429
+ if (current.has(file)) affected.add(file);
3430
+ for (const dependent of project.getDependents(file)) affected.add(this.sourcePath(dependent));
3431
+ if ((0, fs.existsSync)(file) && !project.getSourceFile(file)) added.push(file);
3432
+ }
3433
+ if (added.length) for (const importer of pending) {
3434
+ affected.add(importer);
3435
+ for (const dependent of project.getDependents(importer)) affected.add(this.sourcePath(dependent));
3436
+ }
3437
+ for (const file of changed) if (!(0, fs.existsSync)(file)) {
3438
+ project.removeSourceFile(file);
3439
+ fileModifiedMap.set(file, -Infinity);
3440
+ } else if (project.getSourceFile(file)) project.reloadSourceFile(file);
3441
+ else project.createSourceFile(file);
3442
+ ctx.encoder?.reconcileFileOwnerOrder("extract", inventory);
3443
+ const syntheticEdges = added.flatMap((target) => pending.map((importer) => [target, importer]));
3444
+ this.extractionOrder = this.orderAffectedFiles(inventory, affected, ledger, syntheticEdges);
3445
+ this.affectedFiles = new Set(this.extractionOrder.map(this.sourcePath));
3446
+ };
3447
+ /** Deterministic topological order, with current inventory order as the stable tie-break. */
3448
+ orderAffectedFiles = (inventory, affected, ledger, syntheticEdges) => {
3449
+ const files = inventory.filter((file) => affected.has(this.sourcePath(file)));
3450
+ const byPath = new Map(files.map((file) => [this.sourcePath(file), file]));
3451
+ const inventoryRank = new Map(files.map((file, index) => [this.sourcePath(file), index]));
3452
+ const outgoing = /* @__PURE__ */ new Map();
3453
+ const indegree = new Map(files.map((file) => [this.sourcePath(file), 0]));
3454
+ const addEdge = (rawTarget, rawImporter) => {
3455
+ if (!rawTarget) return;
3456
+ const target = this.sourcePath(rawTarget);
3457
+ const importer = this.sourcePath(rawImporter);
3458
+ if (target === importer || !byPath.has(target) || !byPath.has(importer)) return;
3459
+ const importers = outgoing.get(target) ?? /* @__PURE__ */ new Set();
3460
+ if (importers.has(importer)) return;
3461
+ importers.add(importer);
3462
+ outgoing.set(target, importers);
3463
+ indegree.set(importer, (indegree.get(importer) ?? 0) + 1);
3464
+ };
3465
+ for (const fact of ledger) addEdge(fact.target, fact.importer);
3466
+ for (const [target, importer] of syntheticEdges) addEdge(target, importer);
3467
+ const compare = (left, right) => (inventoryRank.get(left) ?? 0) - (inventoryRank.get(right) ?? 0);
3468
+ const ready = [...indegree].filter(([, degree]) => degree === 0).map(([file]) => file).sort(compare);
3469
+ const ordered = [];
3470
+ while (ready.length) {
3471
+ const file = ready.shift();
3472
+ ordered.push(file);
3473
+ for (const importer of [...outgoing.get(file) ?? []].sort(compare)) {
3474
+ const next = (indegree.get(importer) ?? 0) - 1;
3475
+ indegree.set(importer, next);
3476
+ if (next === 0) {
3477
+ ready.push(importer);
3478
+ ready.sort(compare);
3479
+ }
3480
+ }
3481
+ }
3482
+ for (const file of [...byPath.keys()].sort(compare)) if (!ordered.includes(file)) ordered.push(file);
3483
+ return ordered.map((file) => byPath.get(file));
3184
3484
  };
3185
3485
  /**
3186
3486
  * Write the generated `styled-system`, so an integration can be a project's only codegen.
@@ -3221,6 +3521,7 @@ var Builder = class {
3221
3521
  this.configDependencies.add((0, path.resolve)(cwd || ctx.conf.config.cwd, file));
3222
3522
  });
3223
3523
  this.context = ctx;
3524
+ this.tsconfigResolutionFiles = ctx.diff.getResolutionConfigFiles();
3224
3525
  return ctx;
3225
3526
  };
3226
3527
  getContextOrThrow = () => {
@@ -3250,9 +3551,32 @@ var Builder = class {
3250
3551
  extractFile = (ctx, file) => {
3251
3552
  const meta = this.filesMeta?.changes.get(file) ?? this.getFileMeta(file);
3252
3553
  const hasConfigChanged = this.affecteds ? this.affecteds.hasConfigChanged : true;
3253
- if (meta.isUnchanged && !hasConfigChanged) return;
3554
+ if (meta.isUnchanged && !hasConfigChanged && !this.affectedFiles?.has(this.sourcePath(file))) return;
3555
+ const owner = this.sourcePath(file);
3556
+ const previousReads = this.resolutionReadSets.get(owner) ?? [];
3557
+ const previousPending = this.pendingResolutionReadSets.get(owner) ?? [];
3558
+ const previousCandidates = this.resolutionCandidateSets.get(owner) ?? [];
3559
+ const previousConfigurations = this.resolutionConfigurationSets.get(owner) ?? [];
3254
3560
  const parserResult = ctx.parseFile(file);
3255
3561
  fileModifiedMap.set(file, meta.mtime);
3562
+ if (parserResult) {
3563
+ const previousReadSet = meta.isUnchanged ? {
3564
+ dependencies: (0, _bamboocss_shared.uniq)([...previousReads, ...previousPending]).sort(),
3565
+ pendingCandidates: previousCandidates
3566
+ } : void 0;
3567
+ const readSet = ctx.project.getResolutionReadSet(file, parserResult.getDependencies(), previousReadSet);
3568
+ const currentReads = readSet.dependencies;
3569
+ const currentConfigurations = ctx.project.getResolutionConfigurationFiles(file, parserResult.getDependencies(), meta.isUnchanged ? previousConfigurations : []);
3570
+ this.resolutionReadSets.set(owner, currentReads);
3571
+ if (readSet.pendingCandidates.length) this.resolutionCandidateSets.set(owner, readSet.pendingCandidates);
3572
+ else this.resolutionCandidateSets.delete(owner);
3573
+ const pending = meta.isUnchanged ? (0, _bamboocss_shared.uniq)([...previousPending, ...previousReads]).filter((dependency) => !(0, fs.existsSync)(dependency) && !currentReads.includes(dependency) && (!previousCandidates.includes(dependency) || readSet.pendingCandidates.includes(dependency))).sort() : [];
3574
+ if (pending.length) this.pendingResolutionReadSets.set(owner, pending);
3575
+ else this.pendingResolutionReadSets.delete(owner);
3576
+ const configurations = currentConfigurations.length || !meta.isUnchanged ? currentConfigurations : previousConfigurations;
3577
+ if (configurations.length) this.resolutionConfigurationSets.set(owner, configurations);
3578
+ else this.resolutionConfigurationSets.delete(owner);
3579
+ }
3256
3580
  return parserResult;
3257
3581
  };
3258
3582
  extract = () => {
@@ -3264,9 +3588,28 @@ var Builder = class {
3264
3588
  return ctx.assertNoDeadCalls();
3265
3589
  }
3266
3590
  const files = ctx.getFiles();
3591
+ const inventory = new Set(files.map(this.sourcePath));
3592
+ if (hasConfigChanged) {
3593
+ this.resolutionReadSets.clear();
3594
+ this.pendingResolutionReadSets.clear();
3595
+ this.resolutionCandidateSets.clear();
3596
+ this.resolutionConfigurationSets.clear();
3597
+ } else {
3598
+ for (const owner of this.resolutionReadSets.keys()) if (!inventory.has(owner)) this.resolutionReadSets.delete(owner);
3599
+ for (const owner of this.pendingResolutionReadSets.keys()) if (!inventory.has(owner)) this.pendingResolutionReadSets.delete(owner);
3600
+ for (const owner of this.resolutionCandidateSets.keys()) if (!inventory.has(owner)) this.resolutionCandidateSets.delete(owner);
3601
+ for (const owner of this.resolutionConfigurationSets.keys()) if (!inventory.has(owner)) this.resolutionConfigurationSets.delete(owner);
3602
+ }
3603
+ ctx.encoder?.reconcileFileOwnerOrder("extract", files);
3604
+ const filesToExtract = hasConfigChanged ? files : this.extractionOrder ?? files;
3267
3605
  const done = _bamboocss_logger.logger.time.info("Extracted in");
3268
- for (const file of files) this.extractFile(ctx, file);
3606
+ for (const file of filesToExtract) this.extractFile(ctx, file);
3269
3607
  done();
3608
+ this.sourceInventory = [...files];
3609
+ for (const file of (0, _bamboocss_shared.uniq)([...files, ...this.getResolutionReadFiles()])) fileModifiedMap.set(file, this.getFileMeta(file).mtime);
3610
+ this.snapshotResolutionConfigurations();
3611
+ this.affectedFiles = void 0;
3612
+ this.extractionOrder = void 0;
3270
3613
  ctx.assertExtracted(files);
3271
3614
  ctx.assertNoDeadCalls(files);
3272
3615
  };
@@ -3322,6 +3665,7 @@ var Builder = class {
3322
3665
  };
3323
3666
  registerDependency = (fn) => {
3324
3667
  const ctx = this.getContextOrThrow();
3668
+ this.crawlConfigDependencies();
3325
3669
  for (const fileOrGlob of ctx.config.include) {
3326
3670
  const dependency = parseDependency(fileOrGlob);
3327
3671
  if (dependency) fn(dependency);
@@ -3528,7 +3872,8 @@ async function generate(config, configPath) {
3528
3872
  */
3529
3873
  const bundleStyles = async (ctx, changedFilePaths) => {
3530
3874
  let parsed = 0;
3531
- for (const filePath of changedFilePaths) if (ctx.project.parseSourceFile(filePath)) parsed++;
3875
+ const encoder = ctx.parserOptions.encoder;
3876
+ for (const filePath of changedFilePaths) if (encoder.withOwner("extract", filePath, () => ctx.project.parseSourceFile(filePath, encoder))) parsed++;
3532
3877
  if (parsed === 0) return;
3533
3878
  const outfile = ctx.runtime.path.join(...ctx.paths.root, "styles.css");
3534
3879
  const done = _bamboocss_logger.logger.time.info(ctx.messages.buildComplete(parsed));
@@ -3553,12 +3898,13 @@ async function generate(config, configPath) {
3553
3898
  ctx.project.reloadSourceFile(filePath);
3554
3899
  await bundleStyles(ctx, [filePath, ...ctx.project.getDependents(filePath)]);
3555
3900
  } else if (event === "add") {
3901
+ const pendingClosure = ctx.project.getUnresolvedImporters().flatMap((importer) => [importer, ...ctx.project.getDependents(importer)]);
3556
3902
  ctx.project.createSourceFile(filePath);
3557
- await bundleStyles(ctx, [
3903
+ await bundleStyles(ctx, [...new Set([
3558
3904
  filePath,
3559
3905
  ...ctx.project.getDependents(filePath),
3560
- ...ctx.project.getUnresolvedImporters()
3561
- ]);
3906
+ ...pendingClosure
3907
+ ])]);
3562
3908
  }
3563
3909
  });
3564
3910
  }
@@ -3611,33 +3957,6 @@ const ensure = (outPath) => {
3611
3957
  //#endregion
3612
3958
  //#region src/vite-integration.ts
3613
3959
  /**
3614
- * Whether a Bamboo source compiler is running in this process.
3615
- *
3616
- * Two integrations can emit the stylesheet, and only one of them also compiles source.
3617
- * `@bamboocss/postcss` emits CSS and nothing else, so under it every `css()` and `cva()` call
3618
- * stays a runtime call and the generated style engine ships in the client bundle. That is a
3619
- * legitimate integration for a bundler with no Vite plugin — and a silent downgrade for a
3620
- * project that has Vite and simply did not add `@bamboocss/vite`, which is a setup Bamboo's
3621
- * own React Router guide used to describe. Nothing failed: the stylesheet was correct, the app
3622
- * rendered, and 20 kB of engine went out with it.
3623
- *
3624
- * On `globalThis` under a registered symbol rather than in a module variable, because the two
3625
- * packages that have to agree do not share a module instance. `@bamboocss/postcss` is required
3626
- * as CommonJS by a PostCSS config while `@bamboocss/vite` is imported as ESM by a Vite config,
3627
- * so even one installed copy of a shared dependency is loaded twice, once per format, with a
3628
- * variable each. The symbol is one value per realm regardless.
3629
- *
3630
- * A realm is as far as it goes: a worker thread, or PostCSS run from a separate process
3631
- * alongside the Vite build, sees no flag. Both fail towards saying something rather than
3632
- * staying quiet, and what they say names the option that silences it.
3633
- */
3634
- const FLAG = Symbol.for("bamboocss.static-compiler");
3635
- /** Called by an integration that compiles source, as it is constructed. */
3636
- const markStaticCompilerActive = () => {
3637
- globalThis[FLAG] = true;
3638
- };
3639
- const isStaticCompilerActive = () => Boolean(globalThis[FLAG]);
3640
- /**
3641
3960
  * Every extension Vite accepts for its config, so "is this a Vite project" is answered by the
3642
3961
  * same file Vite itself would load.
3643
3962
  *
@@ -3805,9 +4124,9 @@ Object.defineProperty(exports, "generatePackageExports", {
3805
4124
  }
3806
4125
  });
3807
4126
  exports.hasUncompilableSources = hasUncompilableSources;
3808
- exports.isStaticCompilerActive = isStaticCompilerActive;
4127
+ exports.isStaticCompilerActive = require_static_compiler.isStaticCompilerActive;
3809
4128
  exports.loadConfigAndCreateContext = loadConfigAndCreateContext;
3810
- exports.markStaticCompilerActive = markStaticCompilerActive;
4129
+ exports.markStaticCompilerActive = require_static_compiler.markStaticCompilerActive;
3811
4130
  exports.parseDependency = parseDependency;
3812
4131
  exports.setLogStream = setLogStream;
3813
4132
  exports.setupConfig = setupConfig;