@bamboocss/node 1.46.1 → 1.46.3

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
@@ -28,6 +28,7 @@ let _bamboocss_logger = require("@bamboocss/logger");
28
28
  let _bamboocss_config = require("@bamboocss/config");
29
29
  let _bamboocss_core = require("@bamboocss/core");
30
30
  let _bamboocss_shared = require("@bamboocss/shared");
31
+ let node_crypto = require("node:crypto");
31
32
  let fs = require("fs");
32
33
  let path = require("path");
33
34
  let _bamboocss_plugin_svelte = require("@bamboocss/plugin-svelte");
@@ -2506,22 +2507,23 @@ function parseDependency(fileOrGlob) {
2506
2507
  * nothing a scan of the raw file would recognise, and that is the hook working as intended.
2507
2508
  */
2508
2509
  function* sourceSnapshots(ctx) {
2509
- for (const file of ctx.getFiles()) {
2510
- const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
2511
- let onDisk;
2512
- try {
2513
- onDisk = ctx.runtime.fs.readFileSync(filePath);
2514
- } catch {
2515
- onDisk = void 0;
2516
- }
2517
- const sourceFile = ctx.project.getSourceFile(filePath);
2518
- yield {
2519
- filePath,
2520
- onDisk,
2521
- parsed: sourceFile?.getFullText(),
2522
- sourceFile
2523
- };
2510
+ for (const file of ctx.getFiles()) yield readSnapshot(ctx, ctx.runtime.path.abs(ctx.config.cwd, file));
2511
+ }
2512
+ /** One file's snapshot, for a walk that decides per file whether it needs to read at all. */
2513
+ function readSnapshot(ctx, filePath) {
2514
+ let onDisk;
2515
+ try {
2516
+ onDisk = ctx.runtime.fs.readFileSync(filePath);
2517
+ } catch {
2518
+ onDisk = void 0;
2524
2519
  }
2520
+ const sourceFile = ctx.project.getSourceFile(filePath);
2521
+ return {
2522
+ filePath,
2523
+ onDisk,
2524
+ parsed: sourceFile?.getFullText(),
2525
+ sourceFile
2526
+ };
2525
2527
  }
2526
2528
  /**
2527
2529
  * The distinct texts a snapshot carries.
@@ -3037,46 +3039,133 @@ const reachableFromJs = (text) => {
3037
3039
  function* sourceTexts(ctx) {
3038
3040
  for (const snapshot of sourceSnapshots(ctx)) yield* snapshotTexts(snapshot);
3039
3041
  }
3042
+ const createSourceScanCache = () => ({
3043
+ signature: "",
3044
+ entries: /* @__PURE__ */ new Map()
3045
+ });
3046
+ const OPEN_TAG = /<\s*([a-z][\w-]*)(?=[\s/>]|$)/g;
3047
+ const scanSnapshot = (ctx, snapshot, options, patterns) => {
3048
+ const tokenPaths = /* @__PURE__ */ new Set();
3049
+ const cssVars = /* @__PURE__ */ new Set();
3050
+ const elements = /* @__PURE__ */ new Set();
3051
+ const keyframeHits = /* @__PURE__ */ new Set();
3052
+ let reachable = false;
3053
+ for (const text of snapshotTexts(snapshot)) {
3054
+ for (const match of text.matchAll(TOKEN_CALL)) tokenPaths.add(match[1]);
3055
+ for (const name of (0, _bamboocss_shared.cssVarRefs)(text)) cssVars.add(name);
3056
+ if (!reachable && reachableFromJs(text)) reachable = true;
3057
+ if (options.elements) for (const match of text.matchAll(OPEN_TAG)) elements.add(match[1].toLowerCase());
3058
+ for (const [name, pattern] of patterns) if (!keyframeHits.has(name) && pattern.test(text)) keyframeHits.add(name);
3059
+ }
3060
+ const accounting = {
3061
+ paths: /* @__PURE__ */ new Set(),
3062
+ prefixes: /* @__PURE__ */ new Set(),
3063
+ declined: []
3064
+ };
3065
+ accountSnapshot(ctx, snapshot, accounting);
3066
+ return {
3067
+ tokenPaths: [...tokenPaths],
3068
+ cssVars: [...cssVars],
3069
+ reachableFromJs: reachable,
3070
+ elements: [...elements],
3071
+ keyframeHits: [...keyframeHits],
3072
+ accountingPaths: [...accounting.paths],
3073
+ accountingPrefixes: [...accounting.prefixes],
3074
+ accountingDeclined: accounting.declined
3075
+ };
3076
+ };
3040
3077
  /**
3041
- * The token prune, as all three build paths need to run it.
3078
+ * Every source-derived answer the pruning passes need, from one walk over the sources.
3042
3079
  *
3043
- * One function because it was three copies of one conditional, and the `false` branch went
3044
- * missing from a copy: a watch rebuild with `prune: { tokens: 'off' }` skipped `pruneTokens`
3045
- * altogether, so it kept `@property` registrations that a full build of the same source
3046
- * strips. The other two copies carried a comment pointing at that file for the reasoning,
3047
- * which is how a missing branch reads as intentional.
3080
+ * The token scan, the reachability gate, the strict accounting, the keyframe references and
3081
+ * the rendered-element set all read the same two copies of the same files, and each caller
3082
+ * used to run its own sweep — `Builder.toCss` paid the walk up to three times per stylesheet.
3083
+ * This is the same de-duplication `pruneTokensForBuild` already performed for its own three
3084
+ * answers, extended to all five.
3048
3085
  *
3049
- * Opting out still drops the registrations. Those are not tokens — nothing hands one to
3050
- * javascript, and none appear in the `token()` surface — so the reachability problem the flag
3051
- * exists for does not apply to them, and opting out of token pruning should not mean shipping
3052
- * a preset's whole filter and gradient set for nothing.
3086
+ * With a `cache`, a file whose mtime has not moved is not even read: its previous contribution
3087
+ * merges as-is, which is what turns the walk from O(project) to O(changed) on a rebuild.
3088
+ * Without one — the one-shot CLI paths — the keyframe scan keeps its historical early exit:
3089
+ * once every declared name is found, later files skip those tests.
3053
3090
  */
3091
+ function collectSourceScans(ctx, options, cache, mtimeOf, files) {
3092
+ const result = {
3093
+ tokenPaths: /* @__PURE__ */ new Set(),
3094
+ cssVars: /* @__PURE__ */ new Set(),
3095
+ reachableFromJs: false,
3096
+ elements: /* @__PURE__ */ new Set(),
3097
+ keyframeHits: /* @__PURE__ */ new Set(),
3098
+ accounting: {
3099
+ paths: /* @__PURE__ */ new Set(),
3100
+ prefixes: /* @__PURE__ */ new Set(),
3101
+ declined: []
3102
+ }
3103
+ };
3104
+ const signature = `${options.elements ? 1 : 0}\n${options.keyframeNames.join("\n")}`;
3105
+ if (cache && cache.signature !== signature) {
3106
+ cache.entries.clear();
3107
+ cache.signature = signature;
3108
+ }
3109
+ const allPatterns = options.keyframeNames.map((name) => [name, new RegExp(`\\b${escapeRegExp(name)}\\b`)]);
3110
+ const remaining = cache ? void 0 : new Set(options.keyframeNames);
3111
+ const merge = (scan) => {
3112
+ for (const path of scan.tokenPaths) result.tokenPaths.add(path);
3113
+ for (const name of scan.cssVars) result.cssVars.add(name);
3114
+ if (scan.reachableFromJs) result.reachableFromJs = true;
3115
+ for (const element of scan.elements) result.elements.add(element);
3116
+ for (const name of scan.keyframeHits) {
3117
+ result.keyframeHits.add(name);
3118
+ remaining?.delete(name);
3119
+ }
3120
+ for (const path of scan.accountingPaths) result.accounting.paths.add(path);
3121
+ for (const prefix of scan.accountingPrefixes) result.accounting.prefixes.add(prefix);
3122
+ result.accounting.declined.push(...scan.accountingDeclined);
3123
+ };
3124
+ const seen = cache ? /* @__PURE__ */ new Set() : void 0;
3125
+ for (const file of files ?? ctx.getFiles()) {
3126
+ const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
3127
+ seen?.add(filePath);
3128
+ if (cache) {
3129
+ const mtime = mtimeOf?.(filePath) ?? ((0, fs.existsSync)(filePath) ? (0, fs.statSync)(filePath).mtimeMs : -Infinity);
3130
+ const entry = cache.entries.get(filePath);
3131
+ if (entry && entry.mtime === mtime) {
3132
+ merge(entry.scan);
3133
+ continue;
3134
+ }
3135
+ const scan = scanSnapshot(ctx, readSnapshot(ctx, filePath), options, allPatterns);
3136
+ cache.entries.set(filePath, {
3137
+ mtime,
3138
+ scan
3139
+ });
3140
+ merge(scan);
3141
+ continue;
3142
+ }
3143
+ const patterns = remaining.size ? allPatterns.filter(([name]) => remaining.has(name)) : [];
3144
+ merge(scanSnapshot(ctx, readSnapshot(ctx, filePath), options, patterns));
3145
+ }
3146
+ if (cache && seen) {
3147
+ for (const filePath of cache.entries.keys()) if (!seen.has(filePath)) cache.entries.delete(filePath);
3148
+ }
3149
+ return result;
3150
+ }
3054
3151
  /**
3055
3152
  * Returns the custom properties left standing, for `pruneKeyframes` to root its own walk
3056
3153
  * at — see `Generator.pruneKeyframes`. `'all'` when this pass had nothing to remove and so
3057
3154
  * never computed the closure, which is not a missing answer but the correct one: a sheet
3058
3155
  * nothing was removed from still declares everything it declared.
3059
3156
  */
3060
- function pruneTokensForBuild(ctx, sheet, results) {
3157
+ function pruneTokensForBuild(ctx, sheet, results, sourceScans) {
3061
3158
  if (ctx.config.prune?.tokens === false) return ctx.pruneTokens(sheet)?.reachable ?? "all";
3062
3159
  const unresolved = ctx.config.prune?.unresolvedPath ?? "off";
3063
- const paths = /* @__PURE__ */ new Set();
3064
- const vars = /* @__PURE__ */ new Set();
3065
- const accounting = {
3066
- paths: /* @__PURE__ */ new Set(),
3067
- prefixes: /* @__PURE__ */ new Set(),
3068
- declined: []
3069
- };
3070
- let reachable = false;
3160
+ const scans = sourceScans ?? collectSourceScans(ctx, {
3161
+ keyframeNames: [],
3162
+ elements: false
3163
+ });
3164
+ const paths = new Set(scans.tokenPaths);
3165
+ const vars = new Set(scans.cssVars);
3166
+ const accounting = scans.accounting;
3167
+ const reachable = scans.reachableFromJs;
3071
3168
  for (const result of results) for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
3072
- for (const snapshot of sourceSnapshots(ctx)) {
3073
- for (const text of snapshotTexts(snapshot)) {
3074
- for (const match of text.matchAll(TOKEN_CALL)) paths.add(match[1]);
3075
- for (const name of (0, _bamboocss_shared.cssVarRefs)(text)) vars.add(name);
3076
- if (!reachable && reachableFromJs(text)) reachable = true;
3077
- }
3078
- accountSnapshot(ctx, snapshot, accounting);
3079
- }
3080
3169
  for (const name of tokenVarsFor(ctx, paths)) vars.add(name);
3081
3170
  const declared = declaredKeeps(ctx);
3082
3171
  for (const name of tokenVarsFor(ctx, declared)) vars.add(name);
@@ -3167,31 +3256,6 @@ function formatDeclined(ctx, declined) {
3167
3256
  return [` ${filePath.startsWith(ctx.config.cwd) ? filePath.slice(ctx.config.cwd.length + 1) : filePath}`, ...entries.map((entry) => ` ${entry.line}: ${entry.reason}`)].join("\n");
3168
3257
  }).join("\n");
3169
3258
  }
3170
- /**
3171
- * Collect keyframe names that reading the generated css cannot reveal.
3172
- *
3173
- * A keyframe reached through `css({ animation: 'fade-in 1s' })` lands in the stylesheet
3174
- * and `pruneKeyframes` sees it there. What it cannot see is a name assembled at runtime,
3175
- * or one handed to an inline `style` rather than to bamboo — in both cases the animation
3176
- * plays against a `@keyframes` that no bamboo declaration references.
3177
- *
3178
- * So each declared name is looked for in the source text. Like the token scan this is
3179
- * deliberately over-inclusive: a name that happens to appear in a comment, or as a word
3180
- * in unrelated prose, keeps its keyframe alive. Keeping an unused keyframe costs bytes;
3181
- * dropping a used one silently stops an animation, which is the worse failure and the
3182
- * harder one to trace.
3183
- */
3184
- function collectKeyframeReferences(ctx, names) {
3185
- const declared = Array.from(names);
3186
- const found = /* @__PURE__ */ new Set();
3187
- if (!declared.length) return found;
3188
- const patterns = declared.map((name) => [name, new RegExp(`\\b${escapeRegExp(name)}\\b`)]);
3189
- for (const content of sourceTexts(ctx)) {
3190
- for (const [name, pattern] of patterns) if (!found.has(name) && pattern.test(content)) found.add(name);
3191
- if (found.size === declared.length) break;
3192
- }
3193
- return found;
3194
- }
3195
3259
  const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3196
3260
  /** The keyframes the theme declares — the allow-list `pruneKeyframes` works against. */
3197
3261
  const keyframeNames = (ctx) => Object.keys(ctx.config.theme?.keyframes ?? {});
@@ -3277,6 +3341,20 @@ var Builder = class {
3277
3341
  tsconfigResolutionFiles = [];
3278
3342
  /** Config-graph mtimes as of the last completed setup, consulted by the dev fast path. */
3279
3343
  configGraphMtimes;
3344
+ /** Per-file source-scan results for `toCss`, valid while each file's mtime stands still. */
3345
+ sourceScanCache = createSourceScanCache();
3346
+ /** Cross-file value reads each owner's last extraction performed, with parse-time digests. */
3347
+ extractionReadsByOwner = /* @__PURE__ */ new Map();
3348
+ /** Each owner's recipe surface — declared cva/sva configs plus export-statement texts. */
3349
+ recipeSurfaceByOwner = /* @__PURE__ */ new Map();
3350
+ /** Whether each file changed this pass kept its recipe surface; consulted by dependents. */
3351
+ recipeSurfaceStable = /* @__PURE__ */ new Map();
3352
+ /** Files this pass re-extracts because their bytes moved, as `sourcePath` spellings. */
3353
+ changedThisPass = /* @__PURE__ */ new Set();
3354
+ /** Whether this pass selected any owner through resolution-configuration changes. */
3355
+ resolutionAffectedThisPass = false;
3356
+ /** Per-pass digests of re-read values, so N dependents of one edit digest each value once. */
3357
+ readDigestMemo = /* @__PURE__ */ new Map();
3280
3358
  /** @internal Current and missing resolver paths which can change the stylesheet. */
3281
3359
  getResolutionReadFiles = () => {
3282
3360
  const files = /* @__PURE__ */ new Set();
@@ -3400,6 +3478,9 @@ var Builder = class {
3400
3478
  this.resolutionCandidateSets.clear();
3401
3479
  this.resolutionConfigurationSets.clear();
3402
3480
  this.resolutionConfigurationBytes.clear();
3481
+ this.sourceScanCache.entries.clear();
3482
+ this.extractionReadsByOwner.clear();
3483
+ this.recipeSurfaceByOwner.clear();
3403
3484
  await ctx.hooks["config:change"]?.({
3404
3485
  config: ctx.config,
3405
3486
  changes: this.affecteds
@@ -3438,6 +3519,7 @@ var Builder = class {
3438
3519
  const resolutionAffected = /* @__PURE__ */ new Set();
3439
3520
  const resolutionLedger = changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0;
3440
3521
  for (const [owner, configurations] of this.resolutionConfigurationSets) if (configurations.some((file) => changedResolutionSet.has(file))) resolutionAffected.add(owner);
3522
+ this.resolutionAffectedThisPass = resolutionAffected.size > 0;
3441
3523
  if (changedResolutionConfigurations.length) {
3442
3524
  const tsconfigCandidates = new Set([...previousTsconfigFiles, ...this.tsconfigResolutionFiles]);
3443
3525
  const replaceCompilerOptions = changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file));
@@ -3584,6 +3666,45 @@ var Builder = class {
3584
3666
  if (!this.context) throw new _bamboocss_shared.BambooError("NO_CONTEXT", "context not loaded");
3585
3667
  return this.context;
3586
3668
  };
3669
+ /**
3670
+ * The changed file's recipe surface: every declared `cva`/`sva` config, in declaration
3671
+ * order, plus the text of every export statement. A value edit inside a `css()` call moves
3672
+ * neither; a recipe config edit moves the first; an export alias or re-export edit — which
3673
+ * can re-route what a consumer's call resolves to without any declaration changing — moves
3674
+ * the second. `undefined` when any part cannot be pinned down, which disables skipping.
3675
+ */
3676
+ digestRecipeSurface = (ctx, file, parserResult) => {
3677
+ try {
3678
+ const recipes = [];
3679
+ for (const set of [parserResult?.cva, parserResult?.sva]) for (const item of set ?? []) recipes.push([item.name ?? "", item.data]);
3680
+ const sourceFile = ctx.project?.getSourceFile?.(file);
3681
+ const exports = sourceFile ? sourceFile.getExportDeclarations().map((declaration) => declaration.getText()) : [];
3682
+ const json = JSON.stringify([recipes, exports], (_key, value) => value === void 0 ? "bamboo:undefined" : value);
3683
+ if (json === void 0) return void 0;
3684
+ return (0, node_crypto.createHash)("sha256").update(json).digest("base64");
3685
+ } catch {
3686
+ return;
3687
+ }
3688
+ };
3689
+ /** One canonical spelling for verification keys: absolute, forward slashes. */
3690
+ absOwner = (ctx, file) => this.sourcePath(ctx.runtime?.path?.abs ? ctx.runtime.path.abs(ctx.config.cwd, file) : file);
3691
+ /** Whether every changed file this dependent reads kept both its values and its surface. */
3692
+ dependentUnchangedByReads = (ctx, owner) => {
3693
+ if (this.resolutionAffectedThisPass || this.changedThisPass.size === 0) return false;
3694
+ const reads = this.extractionReadsByOwner.get(owner);
3695
+ if (reads === void 0) return false;
3696
+ for (const changed of this.changedThisPass) if (this.recipeSurfaceStable.get(changed) !== true) return false;
3697
+ for (const read of reads) {
3698
+ const readOwner = this.sourcePath(ctx.runtime.path.abs(ctx.config.cwd, read.file));
3699
+ if (!this.changedThisPass.has(readOwner)) continue;
3700
+ if (read.digest === void 0) return false;
3701
+ const key = `${read.file}\u0000${read.name}`;
3702
+ if (!this.readDigestMemo.has(key)) this.readDigestMemo.set(key, ctx.project.digestExportRead(read.file, read.name));
3703
+ const current = this.readDigestMemo.get(key);
3704
+ if (current === void 0 || current !== read.digest) return false;
3705
+ }
3706
+ return true;
3707
+ };
3587
3708
  getFileMeta = (file) => {
3588
3709
  const mtime = (0, fs.existsSync)(file) ? (0, fs.statSync)(file).mtimeMs : -Infinity;
3589
3710
  return {
@@ -3608,6 +3729,18 @@ var Builder = class {
3608
3729
  const meta = this.filesMeta?.changes.get(file) ?? this.getFileMeta(file);
3609
3730
  const hasConfigChanged = this.affecteds ? this.affecteds.hasConfigChanged : true;
3610
3731
  if (meta.isUnchanged && !hasConfigChanged && !this.affectedFiles?.has(this.sourcePath(file))) return;
3732
+ /**
3733
+ * A dependent selected only because a file it reads changed can be verified instead of
3734
+ * re-extracted: its own bytes did not move, so its extraction output moves only if a
3735
+ * value it read moved, or if the changed file's recipe surface — which decides how its
3736
+ * calls classify — moved. Both are checked against digests recorded when this owner was
3737
+ * last extracted; the changed file itself was re-extracted earlier in this same ordered
3738
+ * pass, which is what makes the surface comparison current. Any gap — a read that could
3739
+ * not be digested, a surface this pass has no verdict for, a JSX-component config whose
3740
+ * classification these records do not witness — falls through to the re-extraction this
3741
+ * replaces.
3742
+ */
3743
+ if (meta.isUnchanged && !hasConfigChanged && !this.changedThisPass.has(this.absOwner(ctx, file)) && !(ctx.jsx?.isEnabled ?? true) && this.dependentUnchangedByReads(ctx, this.absOwner(ctx, file))) return;
3611
3744
  const owner = this.sourcePath(file);
3612
3745
  const previousReads = this.resolutionReadSets.get(owner) ?? [];
3613
3746
  const previousPending = this.pendingResolutionReadSets.get(owner) ?? [];
@@ -3615,6 +3748,17 @@ var Builder = class {
3615
3748
  const previousConfigurations = this.resolutionConfigurationSets.get(owner) ?? [];
3616
3749
  const parserResult = ctx.parseFile(file);
3617
3750
  fileModifiedMap.set(file, meta.mtime);
3751
+ {
3752
+ const owner = this.absOwner(ctx, file);
3753
+ const reads = parserResult?.getExportReads?.() ?? [];
3754
+ this.extractionReadsByOwner.set(owner, reads);
3755
+ const surface = ctx.project ? this.digestRecipeSurface(ctx, file, parserResult) : void 0;
3756
+ if (this.changedThisPass.has(owner)) {
3757
+ const previous = this.recipeSurfaceByOwner.get(owner);
3758
+ this.recipeSurfaceStable.set(owner, previous !== void 0 && surface !== void 0 && previous === surface);
3759
+ }
3760
+ this.recipeSurfaceByOwner.set(owner, surface);
3761
+ }
3618
3762
  if (parserResult) {
3619
3763
  const previousReadSet = meta.isUnchanged ? {
3620
3764
  dependencies: (0, _bamboocss_shared.uniq)([...previousReads, ...previousPending]).sort(),
@@ -3658,6 +3802,9 @@ var Builder = class {
3658
3802
  }
3659
3803
  ctx.encoder?.reconcileFileOwnerOrder("extract", files);
3660
3804
  const filesToExtract = hasConfigChanged ? files : this.extractionOrder ?? files;
3805
+ this.changedThisPass = new Set([...this.filesMeta?.changes ?? []].filter(([, fileMeta]) => !fileMeta.isUnchanged).map(([changed]) => this.sourcePath(ctx.runtime.path.abs(ctx.config.cwd, changed))));
3806
+ this.recipeSurfaceStable.clear();
3807
+ this.readDigestMemo.clear();
3661
3808
  const done = _bamboocss_logger.logger.time.info("Extracted in");
3662
3809
  for (const file of filesToExtract) this.extractFile(ctx, file);
3663
3810
  done();
@@ -3714,9 +3861,15 @@ var Builder = class {
3714
3861
  sheet.layers.recipes_slots.removeAll();
3715
3862
  sheet.layers.recipes_slots_base.removeAll();
3716
3863
  }
3717
- const reachableVars = pruneTokensForBuild(ctx, sheet, []);
3718
- if ((0, _bamboocss_core.prunesPreflight)(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
3719
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)), reachableVars);
3864
+ const collectElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
3865
+ const declaredKeyframes = ctx.config.prune?.keyframes ? keyframeNames(ctx) : [];
3866
+ const scans = ctx.config.prune?.tokens !== false || collectElements || declaredKeyframes.length > 0 ? collectSourceScans(ctx, {
3867
+ keyframeNames: declaredKeyframes,
3868
+ elements: collectElements
3869
+ }, this.sourceScanCache, (filePath) => this.filesMeta?.changes.get(filePath)?.mtime, this.sourceInventory) : void 0;
3870
+ const reachableVars = pruneTokensForBuild(ctx, sheet, [], scans);
3871
+ if (collectElements && scans) ctx.prunePreflight(sheet, scans.elements);
3872
+ if (ctx.config.prune?.keyframes && scans) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3720
3873
  return ctx.getCss(sheet);
3721
3874
  };
3722
3875
  registerDependency = (fn) => {
@@ -3818,9 +3971,14 @@ const cssgen = async (ctx, options) => {
3818
3971
  ctx.appendLayerParams(sheet);
3819
3972
  ctx.appendBaselineCss(sheet);
3820
3973
  ctx.appendParserCss(sheet);
3821
- const reachableVars = pruneTokensForBuild(ctx, sheet, results);
3822
- if ((0, _bamboocss_core.prunesPreflight)(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
3823
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)), reachableVars);
3974
+ const collectElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
3975
+ const scans = collectSourceScans(ctx, {
3976
+ keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
3977
+ elements: collectElements
3978
+ });
3979
+ const reachableVars = pruneTokensForBuild(ctx, sheet, results, scans);
3980
+ if (collectElements) ctx.prunePreflight(sheet, scans.elements);
3981
+ if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3824
3982
  if (splitting) await ctx.writeSplitCss(sheet);
3825
3983
  else if (outfile) {
3826
3984
  const css = ctx.getCss(sheet);
@@ -3890,9 +4048,14 @@ async function build(ctx, artifactIds) {
3890
4048
  ctx.appendBaselineCss(sheet);
3891
4049
  const parsed = ctx.parseFiles();
3892
4050
  ctx.appendParserCss(sheet);
3893
- const reachableVars = pruneTokensForBuild(ctx, sheet, parsed.results);
3894
- if ((0, _bamboocss_core.prunesPreflight)(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
3895
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)), reachableVars);
4051
+ const collectElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
4052
+ const scans = collectSourceScans(ctx, {
4053
+ keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
4054
+ elements: collectElements
4055
+ });
4056
+ const reachableVars = pruneTokensForBuild(ctx, sheet, parsed.results, scans);
4057
+ if (collectElements) ctx.prunePreflight(sheet, scans.elements);
4058
+ if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3896
4059
  await ctx.writeCss(sheet);
3897
4060
  done(ctx.messages.buildComplete(parsed.files.length));
3898
4061
  }
@@ -3937,9 +4100,14 @@ async function generate(config, configPath) {
3937
4100
  ctx.appendLayerParams(sheet);
3938
4101
  ctx.appendBaselineCss(sheet);
3939
4102
  ctx.appendParserCss(sheet);
3940
- const reachableVars = pruneTokensForBuild(ctx, sheet, []);
3941
- if ((0, _bamboocss_core.prunesPreflight)(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
3942
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)), reachableVars);
4103
+ const collectWatchElements = (0, _bamboocss_core.prunesPreflight)(ctx.config.preflight);
4104
+ const watchScans = collectSourceScans(ctx, {
4105
+ keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
4106
+ elements: collectWatchElements
4107
+ });
4108
+ const reachableVars = pruneTokensForBuild(ctx, sheet, [], watchScans);
4109
+ if (collectWatchElements) ctx.prunePreflight(sheet, watchScans.elements);
4110
+ if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, watchScans.keyframeHits, reachableVars);
3943
4111
  const css = ctx.getCss(sheet);
3944
4112
  await ctx.runtime.fs.writeFile(outfile, css);
3945
4113
  done();
package/dist/index.d.cts CHANGED
@@ -248,6 +248,20 @@ declare class Builder {
248
248
  private tsconfigResolutionFiles;
249
249
  /** Config-graph mtimes as of the last completed setup, consulted by the dev fast path. */
250
250
  private configGraphMtimes;
251
+ /** Per-file source-scan results for `toCss`, valid while each file's mtime stands still. */
252
+ private sourceScanCache;
253
+ /** Cross-file value reads each owner's last extraction performed, with parse-time digests. */
254
+ private extractionReadsByOwner;
255
+ /** Each owner's recipe surface — declared cva/sva configs plus export-statement texts. */
256
+ private recipeSurfaceByOwner;
257
+ /** Whether each file changed this pass kept its recipe surface; consulted by dependents. */
258
+ private recipeSurfaceStable;
259
+ /** Files this pass re-extracts because their bytes moved, as `sourcePath` spellings. */
260
+ private changedThisPass;
261
+ /** Whether this pass selected any owner through resolution-configuration changes. */
262
+ private resolutionAffectedThisPass;
263
+ /** Per-pass digests of re-read values, so N dependents of one edit digest each value once. */
264
+ private readDigestMemo;
251
265
  /** @internal Current and missing resolver paths which can change the stylesheet. */
252
266
  getResolutionReadFiles: () => readonly string[];
253
267
  /** @internal Exact local package/tsconfig files which can change semantic resolution. */
@@ -311,6 +325,18 @@ declare class Builder {
311
325
  emit(): Promise<void>;
312
326
  setupContext: (options: SetupContextOptions) => Promise<BambooContext>;
313
327
  getContextOrThrow: () => BambooContext;
328
+ /**
329
+ * The changed file's recipe surface: every declared `cva`/`sva` config, in declaration
330
+ * order, plus the text of every export statement. A value edit inside a `css()` call moves
331
+ * neither; a recipe config edit moves the first; an export alias or re-export edit — which
332
+ * can re-route what a consumer's call resolves to without any declaration changing — moves
333
+ * the second. `undefined` when any part cannot be pinned down, which disables skipping.
334
+ */
335
+ private digestRecipeSurface;
336
+ /** One canonical spelling for verification keys: absolute, forward slashes. */
337
+ private absOwner;
338
+ /** Whether every changed file this dependent reads kept both its values and its surface. */
339
+ private dependentUnchangedByReads;
314
340
  getFileMeta: (file: string) => {
315
341
  mtime: number;
316
342
  isUnchanged: boolean;
package/dist/index.d.mts CHANGED
@@ -248,6 +248,20 @@ declare class Builder {
248
248
  private tsconfigResolutionFiles;
249
249
  /** Config-graph mtimes as of the last completed setup, consulted by the dev fast path. */
250
250
  private configGraphMtimes;
251
+ /** Per-file source-scan results for `toCss`, valid while each file's mtime stands still. */
252
+ private sourceScanCache;
253
+ /** Cross-file value reads each owner's last extraction performed, with parse-time digests. */
254
+ private extractionReadsByOwner;
255
+ /** Each owner's recipe surface — declared cva/sva configs plus export-statement texts. */
256
+ private recipeSurfaceByOwner;
257
+ /** Whether each file changed this pass kept its recipe surface; consulted by dependents. */
258
+ private recipeSurfaceStable;
259
+ /** Files this pass re-extracts because their bytes moved, as `sourcePath` spellings. */
260
+ private changedThisPass;
261
+ /** Whether this pass selected any owner through resolution-configuration changes. */
262
+ private resolutionAffectedThisPass;
263
+ /** Per-pass digests of re-read values, so N dependents of one edit digest each value once. */
264
+ private readDigestMemo;
251
265
  /** @internal Current and missing resolver paths which can change the stylesheet. */
252
266
  getResolutionReadFiles: () => readonly string[];
253
267
  /** @internal Exact local package/tsconfig files which can change semantic resolution. */
@@ -311,6 +325,18 @@ declare class Builder {
311
325
  emit(): Promise<void>;
312
326
  setupContext: (options: SetupContextOptions) => Promise<BambooContext>;
313
327
  getContextOrThrow: () => BambooContext;
328
+ /**
329
+ * The changed file's recipe surface: every declared `cva`/`sva` config, in declaration
330
+ * order, plus the text of every export statement. A value edit inside a `css()` call moves
331
+ * neither; a recipe config edit moves the first; an export alias or re-export edit — which
332
+ * can re-route what a consumer's call resolves to without any declaration changing — moves
333
+ * the second. `undefined` when any part cannot be pinned down, which disables skipping.
334
+ */
335
+ private digestRecipeSurface;
336
+ /** One canonical spelling for verification keys: absolute, forward slashes. */
337
+ private absOwner;
338
+ /** Whether every changed file this dependent reads kept both its values and its surface. */
339
+ private dependentUnchangedByReads;
314
340
  getFileMeta: (file: string) => {
315
341
  mtime: number;
316
342
  isUnchanged: boolean;
package/dist/index.mjs CHANGED
@@ -4,6 +4,7 @@ import { colors, logger, quote } from "@bamboocss/logger";
4
4
  import { convertTsPathsToRegexes, diffConfigs, findConfig, getConfigDependencies, loadConfig, mergeHooks } from "@bamboocss/config";
5
5
  import { checkNamingAgreement, formatNamingDisagreement, messages, prunesPreflight } from "@bamboocss/core";
6
6
  import { BambooError, cssVarRefs, groupBy, truncateList, uniq } from "@bamboocss/shared";
7
+ import { createHash } from "node:crypto";
7
8
  import { appendFileSync, existsSync, readFileSync, statSync, writeFileSync } from "fs";
8
9
  import { basename, dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "path";
9
10
  import { pluginSvelte } from "@bamboocss/plugin-svelte";
@@ -2492,22 +2493,23 @@ function parseDependency(fileOrGlob) {
2492
2493
  * nothing a scan of the raw file would recognise, and that is the hook working as intended.
2493
2494
  */
2494
2495
  function* sourceSnapshots(ctx) {
2495
- for (const file of ctx.getFiles()) {
2496
- const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
2497
- let onDisk;
2498
- try {
2499
- onDisk = ctx.runtime.fs.readFileSync(filePath);
2500
- } catch {
2501
- onDisk = void 0;
2502
- }
2503
- const sourceFile = ctx.project.getSourceFile(filePath);
2504
- yield {
2505
- filePath,
2506
- onDisk,
2507
- parsed: sourceFile?.getFullText(),
2508
- sourceFile
2509
- };
2496
+ for (const file of ctx.getFiles()) yield readSnapshot(ctx, ctx.runtime.path.abs(ctx.config.cwd, file));
2497
+ }
2498
+ /** One file's snapshot, for a walk that decides per file whether it needs to read at all. */
2499
+ function readSnapshot(ctx, filePath) {
2500
+ let onDisk;
2501
+ try {
2502
+ onDisk = ctx.runtime.fs.readFileSync(filePath);
2503
+ } catch {
2504
+ onDisk = void 0;
2510
2505
  }
2506
+ const sourceFile = ctx.project.getSourceFile(filePath);
2507
+ return {
2508
+ filePath,
2509
+ onDisk,
2510
+ parsed: sourceFile?.getFullText(),
2511
+ sourceFile
2512
+ };
2511
2513
  }
2512
2514
  /**
2513
2515
  * The distinct texts a snapshot carries.
@@ -3023,46 +3025,133 @@ const reachableFromJs = (text) => {
3023
3025
  function* sourceTexts(ctx) {
3024
3026
  for (const snapshot of sourceSnapshots(ctx)) yield* snapshotTexts(snapshot);
3025
3027
  }
3028
+ const createSourceScanCache = () => ({
3029
+ signature: "",
3030
+ entries: /* @__PURE__ */ new Map()
3031
+ });
3032
+ const OPEN_TAG = /<\s*([a-z][\w-]*)(?=[\s/>]|$)/g;
3033
+ const scanSnapshot = (ctx, snapshot, options, patterns) => {
3034
+ const tokenPaths = /* @__PURE__ */ new Set();
3035
+ const cssVars = /* @__PURE__ */ new Set();
3036
+ const elements = /* @__PURE__ */ new Set();
3037
+ const keyframeHits = /* @__PURE__ */ new Set();
3038
+ let reachable = false;
3039
+ for (const text of snapshotTexts(snapshot)) {
3040
+ for (const match of text.matchAll(TOKEN_CALL)) tokenPaths.add(match[1]);
3041
+ for (const name of cssVarRefs(text)) cssVars.add(name);
3042
+ if (!reachable && reachableFromJs(text)) reachable = true;
3043
+ if (options.elements) for (const match of text.matchAll(OPEN_TAG)) elements.add(match[1].toLowerCase());
3044
+ for (const [name, pattern] of patterns) if (!keyframeHits.has(name) && pattern.test(text)) keyframeHits.add(name);
3045
+ }
3046
+ const accounting = {
3047
+ paths: /* @__PURE__ */ new Set(),
3048
+ prefixes: /* @__PURE__ */ new Set(),
3049
+ declined: []
3050
+ };
3051
+ accountSnapshot(ctx, snapshot, accounting);
3052
+ return {
3053
+ tokenPaths: [...tokenPaths],
3054
+ cssVars: [...cssVars],
3055
+ reachableFromJs: reachable,
3056
+ elements: [...elements],
3057
+ keyframeHits: [...keyframeHits],
3058
+ accountingPaths: [...accounting.paths],
3059
+ accountingPrefixes: [...accounting.prefixes],
3060
+ accountingDeclined: accounting.declined
3061
+ };
3062
+ };
3026
3063
  /**
3027
- * The token prune, as all three build paths need to run it.
3064
+ * Every source-derived answer the pruning passes need, from one walk over the sources.
3028
3065
  *
3029
- * One function because it was three copies of one conditional, and the `false` branch went
3030
- * missing from a copy: a watch rebuild with `prune: { tokens: 'off' }` skipped `pruneTokens`
3031
- * altogether, so it kept `@property` registrations that a full build of the same source
3032
- * strips. The other two copies carried a comment pointing at that file for the reasoning,
3033
- * which is how a missing branch reads as intentional.
3066
+ * The token scan, the reachability gate, the strict accounting, the keyframe references and
3067
+ * the rendered-element set all read the same two copies of the same files, and each caller
3068
+ * used to run its own sweep — `Builder.toCss` paid the walk up to three times per stylesheet.
3069
+ * This is the same de-duplication `pruneTokensForBuild` already performed for its own three
3070
+ * answers, extended to all five.
3034
3071
  *
3035
- * Opting out still drops the registrations. Those are not tokens — nothing hands one to
3036
- * javascript, and none appear in the `token()` surface — so the reachability problem the flag
3037
- * exists for does not apply to them, and opting out of token pruning should not mean shipping
3038
- * a preset's whole filter and gradient set for nothing.
3072
+ * With a `cache`, a file whose mtime has not moved is not even read: its previous contribution
3073
+ * merges as-is, which is what turns the walk from O(project) to O(changed) on a rebuild.
3074
+ * Without one — the one-shot CLI paths — the keyframe scan keeps its historical early exit:
3075
+ * once every declared name is found, later files skip those tests.
3039
3076
  */
3077
+ function collectSourceScans(ctx, options, cache, mtimeOf, files) {
3078
+ const result = {
3079
+ tokenPaths: /* @__PURE__ */ new Set(),
3080
+ cssVars: /* @__PURE__ */ new Set(),
3081
+ reachableFromJs: false,
3082
+ elements: /* @__PURE__ */ new Set(),
3083
+ keyframeHits: /* @__PURE__ */ new Set(),
3084
+ accounting: {
3085
+ paths: /* @__PURE__ */ new Set(),
3086
+ prefixes: /* @__PURE__ */ new Set(),
3087
+ declined: []
3088
+ }
3089
+ };
3090
+ const signature = `${options.elements ? 1 : 0}\n${options.keyframeNames.join("\n")}`;
3091
+ if (cache && cache.signature !== signature) {
3092
+ cache.entries.clear();
3093
+ cache.signature = signature;
3094
+ }
3095
+ const allPatterns = options.keyframeNames.map((name) => [name, new RegExp(`\\b${escapeRegExp(name)}\\b`)]);
3096
+ const remaining = cache ? void 0 : new Set(options.keyframeNames);
3097
+ const merge = (scan) => {
3098
+ for (const path of scan.tokenPaths) result.tokenPaths.add(path);
3099
+ for (const name of scan.cssVars) result.cssVars.add(name);
3100
+ if (scan.reachableFromJs) result.reachableFromJs = true;
3101
+ for (const element of scan.elements) result.elements.add(element);
3102
+ for (const name of scan.keyframeHits) {
3103
+ result.keyframeHits.add(name);
3104
+ remaining?.delete(name);
3105
+ }
3106
+ for (const path of scan.accountingPaths) result.accounting.paths.add(path);
3107
+ for (const prefix of scan.accountingPrefixes) result.accounting.prefixes.add(prefix);
3108
+ result.accounting.declined.push(...scan.accountingDeclined);
3109
+ };
3110
+ const seen = cache ? /* @__PURE__ */ new Set() : void 0;
3111
+ for (const file of files ?? ctx.getFiles()) {
3112
+ const filePath = ctx.runtime.path.abs(ctx.config.cwd, file);
3113
+ seen?.add(filePath);
3114
+ if (cache) {
3115
+ const mtime = mtimeOf?.(filePath) ?? (existsSync(filePath) ? statSync(filePath).mtimeMs : -Infinity);
3116
+ const entry = cache.entries.get(filePath);
3117
+ if (entry && entry.mtime === mtime) {
3118
+ merge(entry.scan);
3119
+ continue;
3120
+ }
3121
+ const scan = scanSnapshot(ctx, readSnapshot(ctx, filePath), options, allPatterns);
3122
+ cache.entries.set(filePath, {
3123
+ mtime,
3124
+ scan
3125
+ });
3126
+ merge(scan);
3127
+ continue;
3128
+ }
3129
+ const patterns = remaining.size ? allPatterns.filter(([name]) => remaining.has(name)) : [];
3130
+ merge(scanSnapshot(ctx, readSnapshot(ctx, filePath), options, patterns));
3131
+ }
3132
+ if (cache && seen) {
3133
+ for (const filePath of cache.entries.keys()) if (!seen.has(filePath)) cache.entries.delete(filePath);
3134
+ }
3135
+ return result;
3136
+ }
3040
3137
  /**
3041
3138
  * Returns the custom properties left standing, for `pruneKeyframes` to root its own walk
3042
3139
  * at — see `Generator.pruneKeyframes`. `'all'` when this pass had nothing to remove and so
3043
3140
  * never computed the closure, which is not a missing answer but the correct one: a sheet
3044
3141
  * nothing was removed from still declares everything it declared.
3045
3142
  */
3046
- function pruneTokensForBuild(ctx, sheet, results) {
3143
+ function pruneTokensForBuild(ctx, sheet, results, sourceScans) {
3047
3144
  if (ctx.config.prune?.tokens === false) return ctx.pruneTokens(sheet)?.reachable ?? "all";
3048
3145
  const unresolved = ctx.config.prune?.unresolvedPath ?? "off";
3049
- const paths = /* @__PURE__ */ new Set();
3050
- const vars = /* @__PURE__ */ new Set();
3051
- const accounting = {
3052
- paths: /* @__PURE__ */ new Set(),
3053
- prefixes: /* @__PURE__ */ new Set(),
3054
- declined: []
3055
- };
3056
- let reachable = false;
3146
+ const scans = sourceScans ?? collectSourceScans(ctx, {
3147
+ keyframeNames: [],
3148
+ elements: false
3149
+ });
3150
+ const paths = new Set(scans.tokenPaths);
3151
+ const vars = new Set(scans.cssVars);
3152
+ const accounting = scans.accounting;
3153
+ const reachable = scans.reachableFromJs;
3057
3154
  for (const result of results) for (const item of result.token) for (const value of item.data ?? []) if (typeof value === "string") paths.add(value);
3058
- for (const snapshot of sourceSnapshots(ctx)) {
3059
- for (const text of snapshotTexts(snapshot)) {
3060
- for (const match of text.matchAll(TOKEN_CALL)) paths.add(match[1]);
3061
- for (const name of cssVarRefs(text)) vars.add(name);
3062
- if (!reachable && reachableFromJs(text)) reachable = true;
3063
- }
3064
- accountSnapshot(ctx, snapshot, accounting);
3065
- }
3066
3155
  for (const name of tokenVarsFor(ctx, paths)) vars.add(name);
3067
3156
  const declared = declaredKeeps(ctx);
3068
3157
  for (const name of tokenVarsFor(ctx, declared)) vars.add(name);
@@ -3153,31 +3242,6 @@ function formatDeclined(ctx, declined) {
3153
3242
  return [` ${filePath.startsWith(ctx.config.cwd) ? filePath.slice(ctx.config.cwd.length + 1) : filePath}`, ...entries.map((entry) => ` ${entry.line}: ${entry.reason}`)].join("\n");
3154
3243
  }).join("\n");
3155
3244
  }
3156
- /**
3157
- * Collect keyframe names that reading the generated css cannot reveal.
3158
- *
3159
- * A keyframe reached through `css({ animation: 'fade-in 1s' })` lands in the stylesheet
3160
- * and `pruneKeyframes` sees it there. What it cannot see is a name assembled at runtime,
3161
- * or one handed to an inline `style` rather than to bamboo — in both cases the animation
3162
- * plays against a `@keyframes` that no bamboo declaration references.
3163
- *
3164
- * So each declared name is looked for in the source text. Like the token scan this is
3165
- * deliberately over-inclusive: a name that happens to appear in a comment, or as a word
3166
- * in unrelated prose, keeps its keyframe alive. Keeping an unused keyframe costs bytes;
3167
- * dropping a used one silently stops an animation, which is the worse failure and the
3168
- * harder one to trace.
3169
- */
3170
- function collectKeyframeReferences(ctx, names) {
3171
- const declared = Array.from(names);
3172
- const found = /* @__PURE__ */ new Set();
3173
- if (!declared.length) return found;
3174
- const patterns = declared.map((name) => [name, new RegExp(`\\b${escapeRegExp(name)}\\b`)]);
3175
- for (const content of sourceTexts(ctx)) {
3176
- for (const [name, pattern] of patterns) if (!found.has(name) && pattern.test(content)) found.add(name);
3177
- if (found.size === declared.length) break;
3178
- }
3179
- return found;
3180
- }
3181
3245
  const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3182
3246
  /** The keyframes the theme declares — the allow-list `pruneKeyframes` works against. */
3183
3247
  const keyframeNames = (ctx) => Object.keys(ctx.config.theme?.keyframes ?? {});
@@ -3263,6 +3327,20 @@ var Builder = class {
3263
3327
  tsconfigResolutionFiles = [];
3264
3328
  /** Config-graph mtimes as of the last completed setup, consulted by the dev fast path. */
3265
3329
  configGraphMtimes;
3330
+ /** Per-file source-scan results for `toCss`, valid while each file's mtime stands still. */
3331
+ sourceScanCache = createSourceScanCache();
3332
+ /** Cross-file value reads each owner's last extraction performed, with parse-time digests. */
3333
+ extractionReadsByOwner = /* @__PURE__ */ new Map();
3334
+ /** Each owner's recipe surface — declared cva/sva configs plus export-statement texts. */
3335
+ recipeSurfaceByOwner = /* @__PURE__ */ new Map();
3336
+ /** Whether each file changed this pass kept its recipe surface; consulted by dependents. */
3337
+ recipeSurfaceStable = /* @__PURE__ */ new Map();
3338
+ /** Files this pass re-extracts because their bytes moved, as `sourcePath` spellings. */
3339
+ changedThisPass = /* @__PURE__ */ new Set();
3340
+ /** Whether this pass selected any owner through resolution-configuration changes. */
3341
+ resolutionAffectedThisPass = false;
3342
+ /** Per-pass digests of re-read values, so N dependents of one edit digest each value once. */
3343
+ readDigestMemo = /* @__PURE__ */ new Map();
3266
3344
  /** @internal Current and missing resolver paths which can change the stylesheet. */
3267
3345
  getResolutionReadFiles = () => {
3268
3346
  const files = /* @__PURE__ */ new Set();
@@ -3386,6 +3464,9 @@ var Builder = class {
3386
3464
  this.resolutionCandidateSets.clear();
3387
3465
  this.resolutionConfigurationSets.clear();
3388
3466
  this.resolutionConfigurationBytes.clear();
3467
+ this.sourceScanCache.entries.clear();
3468
+ this.extractionReadsByOwner.clear();
3469
+ this.recipeSurfaceByOwner.clear();
3389
3470
  await ctx.hooks["config:change"]?.({
3390
3471
  config: ctx.config,
3391
3472
  changes: this.affecteds
@@ -3424,6 +3505,7 @@ var Builder = class {
3424
3505
  const resolutionAffected = /* @__PURE__ */ new Set();
3425
3506
  const resolutionLedger = changedResolutionConfigurations.length ? ctx.project.getResolutionLedger() : void 0;
3426
3507
  for (const [owner, configurations] of this.resolutionConfigurationSets) if (configurations.some((file) => changedResolutionSet.has(file))) resolutionAffected.add(owner);
3508
+ this.resolutionAffectedThisPass = resolutionAffected.size > 0;
3427
3509
  if (changedResolutionConfigurations.length) {
3428
3510
  const tsconfigCandidates = new Set([...previousTsconfigFiles, ...this.tsconfigResolutionFiles]);
3429
3511
  const replaceCompilerOptions = changedResolutionConfigurations.some((file) => tsconfigCandidates.has(file));
@@ -3570,6 +3652,45 @@ var Builder = class {
3570
3652
  if (!this.context) throw new BambooError("NO_CONTEXT", "context not loaded");
3571
3653
  return this.context;
3572
3654
  };
3655
+ /**
3656
+ * The changed file's recipe surface: every declared `cva`/`sva` config, in declaration
3657
+ * order, plus the text of every export statement. A value edit inside a `css()` call moves
3658
+ * neither; a recipe config edit moves the first; an export alias or re-export edit — which
3659
+ * can re-route what a consumer's call resolves to without any declaration changing — moves
3660
+ * the second. `undefined` when any part cannot be pinned down, which disables skipping.
3661
+ */
3662
+ digestRecipeSurface = (ctx, file, parserResult) => {
3663
+ try {
3664
+ const recipes = [];
3665
+ for (const set of [parserResult?.cva, parserResult?.sva]) for (const item of set ?? []) recipes.push([item.name ?? "", item.data]);
3666
+ const sourceFile = ctx.project?.getSourceFile?.(file);
3667
+ const exports = sourceFile ? sourceFile.getExportDeclarations().map((declaration) => declaration.getText()) : [];
3668
+ const json = JSON.stringify([recipes, exports], (_key, value) => value === void 0 ? "bamboo:undefined" : value);
3669
+ if (json === void 0) return void 0;
3670
+ return createHash("sha256").update(json).digest("base64");
3671
+ } catch {
3672
+ return;
3673
+ }
3674
+ };
3675
+ /** One canonical spelling for verification keys: absolute, forward slashes. */
3676
+ absOwner = (ctx, file) => this.sourcePath(ctx.runtime?.path?.abs ? ctx.runtime.path.abs(ctx.config.cwd, file) : file);
3677
+ /** Whether every changed file this dependent reads kept both its values and its surface. */
3678
+ dependentUnchangedByReads = (ctx, owner) => {
3679
+ if (this.resolutionAffectedThisPass || this.changedThisPass.size === 0) return false;
3680
+ const reads = this.extractionReadsByOwner.get(owner);
3681
+ if (reads === void 0) return false;
3682
+ for (const changed of this.changedThisPass) if (this.recipeSurfaceStable.get(changed) !== true) return false;
3683
+ for (const read of reads) {
3684
+ const readOwner = this.sourcePath(ctx.runtime.path.abs(ctx.config.cwd, read.file));
3685
+ if (!this.changedThisPass.has(readOwner)) continue;
3686
+ if (read.digest === void 0) return false;
3687
+ const key = `${read.file}\u0000${read.name}`;
3688
+ if (!this.readDigestMemo.has(key)) this.readDigestMemo.set(key, ctx.project.digestExportRead(read.file, read.name));
3689
+ const current = this.readDigestMemo.get(key);
3690
+ if (current === void 0 || current !== read.digest) return false;
3691
+ }
3692
+ return true;
3693
+ };
3573
3694
  getFileMeta = (file) => {
3574
3695
  const mtime = existsSync(file) ? statSync(file).mtimeMs : -Infinity;
3575
3696
  return {
@@ -3594,6 +3715,18 @@ var Builder = class {
3594
3715
  const meta = this.filesMeta?.changes.get(file) ?? this.getFileMeta(file);
3595
3716
  const hasConfigChanged = this.affecteds ? this.affecteds.hasConfigChanged : true;
3596
3717
  if (meta.isUnchanged && !hasConfigChanged && !this.affectedFiles?.has(this.sourcePath(file))) return;
3718
+ /**
3719
+ * A dependent selected only because a file it reads changed can be verified instead of
3720
+ * re-extracted: its own bytes did not move, so its extraction output moves only if a
3721
+ * value it read moved, or if the changed file's recipe surface — which decides how its
3722
+ * calls classify — moved. Both are checked against digests recorded when this owner was
3723
+ * last extracted; the changed file itself was re-extracted earlier in this same ordered
3724
+ * pass, which is what makes the surface comparison current. Any gap — a read that could
3725
+ * not be digested, a surface this pass has no verdict for, a JSX-component config whose
3726
+ * classification these records do not witness — falls through to the re-extraction this
3727
+ * replaces.
3728
+ */
3729
+ if (meta.isUnchanged && !hasConfigChanged && !this.changedThisPass.has(this.absOwner(ctx, file)) && !(ctx.jsx?.isEnabled ?? true) && this.dependentUnchangedByReads(ctx, this.absOwner(ctx, file))) return;
3597
3730
  const owner = this.sourcePath(file);
3598
3731
  const previousReads = this.resolutionReadSets.get(owner) ?? [];
3599
3732
  const previousPending = this.pendingResolutionReadSets.get(owner) ?? [];
@@ -3601,6 +3734,17 @@ var Builder = class {
3601
3734
  const previousConfigurations = this.resolutionConfigurationSets.get(owner) ?? [];
3602
3735
  const parserResult = ctx.parseFile(file);
3603
3736
  fileModifiedMap.set(file, meta.mtime);
3737
+ {
3738
+ const owner = this.absOwner(ctx, file);
3739
+ const reads = parserResult?.getExportReads?.() ?? [];
3740
+ this.extractionReadsByOwner.set(owner, reads);
3741
+ const surface = ctx.project ? this.digestRecipeSurface(ctx, file, parserResult) : void 0;
3742
+ if (this.changedThisPass.has(owner)) {
3743
+ const previous = this.recipeSurfaceByOwner.get(owner);
3744
+ this.recipeSurfaceStable.set(owner, previous !== void 0 && surface !== void 0 && previous === surface);
3745
+ }
3746
+ this.recipeSurfaceByOwner.set(owner, surface);
3747
+ }
3604
3748
  if (parserResult) {
3605
3749
  const previousReadSet = meta.isUnchanged ? {
3606
3750
  dependencies: uniq([...previousReads, ...previousPending]).sort(),
@@ -3644,6 +3788,9 @@ var Builder = class {
3644
3788
  }
3645
3789
  ctx.encoder?.reconcileFileOwnerOrder("extract", files);
3646
3790
  const filesToExtract = hasConfigChanged ? files : this.extractionOrder ?? files;
3791
+ this.changedThisPass = new Set([...this.filesMeta?.changes ?? []].filter(([, fileMeta]) => !fileMeta.isUnchanged).map(([changed]) => this.sourcePath(ctx.runtime.path.abs(ctx.config.cwd, changed))));
3792
+ this.recipeSurfaceStable.clear();
3793
+ this.readDigestMemo.clear();
3647
3794
  const done = logger.time.info("Extracted in");
3648
3795
  for (const file of filesToExtract) this.extractFile(ctx, file);
3649
3796
  done();
@@ -3700,9 +3847,15 @@ var Builder = class {
3700
3847
  sheet.layers.recipes_slots.removeAll();
3701
3848
  sheet.layers.recipes_slots_base.removeAll();
3702
3849
  }
3703
- const reachableVars = pruneTokensForBuild(ctx, sheet, []);
3704
- if (prunesPreflight(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
3705
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)), reachableVars);
3850
+ const collectElements = prunesPreflight(ctx.config.preflight);
3851
+ const declaredKeyframes = ctx.config.prune?.keyframes ? keyframeNames(ctx) : [];
3852
+ const scans = ctx.config.prune?.tokens !== false || collectElements || declaredKeyframes.length > 0 ? collectSourceScans(ctx, {
3853
+ keyframeNames: declaredKeyframes,
3854
+ elements: collectElements
3855
+ }, this.sourceScanCache, (filePath) => this.filesMeta?.changes.get(filePath)?.mtime, this.sourceInventory) : void 0;
3856
+ const reachableVars = pruneTokensForBuild(ctx, sheet, [], scans);
3857
+ if (collectElements && scans) ctx.prunePreflight(sheet, scans.elements);
3858
+ if (ctx.config.prune?.keyframes && scans) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3706
3859
  return ctx.getCss(sheet);
3707
3860
  };
3708
3861
  registerDependency = (fn) => {
@@ -3804,9 +3957,14 @@ const cssgen = async (ctx, options) => {
3804
3957
  ctx.appendLayerParams(sheet);
3805
3958
  ctx.appendBaselineCss(sheet);
3806
3959
  ctx.appendParserCss(sheet);
3807
- const reachableVars = pruneTokensForBuild(ctx, sheet, results);
3808
- if (prunesPreflight(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
3809
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)), reachableVars);
3960
+ const collectElements = prunesPreflight(ctx.config.preflight);
3961
+ const scans = collectSourceScans(ctx, {
3962
+ keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
3963
+ elements: collectElements
3964
+ });
3965
+ const reachableVars = pruneTokensForBuild(ctx, sheet, results, scans);
3966
+ if (collectElements) ctx.prunePreflight(sheet, scans.elements);
3967
+ if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3810
3968
  if (splitting) await ctx.writeSplitCss(sheet);
3811
3969
  else if (outfile) {
3812
3970
  const css = ctx.getCss(sheet);
@@ -3876,9 +4034,14 @@ async function build(ctx, artifactIds) {
3876
4034
  ctx.appendBaselineCss(sheet);
3877
4035
  const parsed = ctx.parseFiles();
3878
4036
  ctx.appendParserCss(sheet);
3879
- const reachableVars = pruneTokensForBuild(ctx, sheet, parsed.results);
3880
- if (prunesPreflight(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
3881
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)), reachableVars);
4037
+ const collectElements = prunesPreflight(ctx.config.preflight);
4038
+ const scans = collectSourceScans(ctx, {
4039
+ keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
4040
+ elements: collectElements
4041
+ });
4042
+ const reachableVars = pruneTokensForBuild(ctx, sheet, parsed.results, scans);
4043
+ if (collectElements) ctx.prunePreflight(sheet, scans.elements);
4044
+ if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, scans.keyframeHits, reachableVars);
3882
4045
  await ctx.writeCss(sheet);
3883
4046
  done(ctx.messages.buildComplete(parsed.files.length));
3884
4047
  }
@@ -3923,9 +4086,14 @@ async function generate(config, configPath) {
3923
4086
  ctx.appendLayerParams(sheet);
3924
4087
  ctx.appendBaselineCss(sheet);
3925
4088
  ctx.appendParserCss(sheet);
3926
- const reachableVars = pruneTokensForBuild(ctx, sheet, []);
3927
- if (prunesPreflight(ctx.config.preflight)) ctx.prunePreflight(sheet, collectRenderedElements(ctx));
3928
- if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, collectKeyframeReferences(ctx, keyframeNames(ctx)), reachableVars);
4089
+ const collectWatchElements = prunesPreflight(ctx.config.preflight);
4090
+ const watchScans = collectSourceScans(ctx, {
4091
+ keyframeNames: ctx.config.prune?.keyframes ? keyframeNames(ctx) : [],
4092
+ elements: collectWatchElements
4093
+ });
4094
+ const reachableVars = pruneTokensForBuild(ctx, sheet, [], watchScans);
4095
+ if (collectWatchElements) ctx.prunePreflight(sheet, watchScans.elements);
4096
+ if (ctx.config.prune?.keyframes) ctx.pruneKeyframes(sheet, watchScans.keyframeHits, reachableVars);
3929
4097
  const css = ctx.getCss(sheet);
3930
4098
  await ctx.runtime.fs.writeFile(outfile, css);
3931
4099
  done();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bamboocss/node",
3
- "version": "1.46.1",
3
+ "version": "1.46.3",
4
4
  "description": "The core css bamboo library",
5
5
  "homepage": "https://bamboocss.com",
6
6
  "license": "MIT",
@@ -65,17 +65,17 @@
65
65
  "postcss": "8.5.26",
66
66
  "ts-morph": "28.0.0",
67
67
  "ts-pattern": "5.9.0",
68
- "@bamboocss/config": "1.46.1",
69
- "@bamboocss/core": "1.46.1",
70
- "@bamboocss/generator": "1.46.1",
71
- "@bamboocss/logger": "1.46.1",
72
- "@bamboocss/parser": "1.46.1",
73
- "@bamboocss/plugin-svelte": "1.46.1",
74
- "@bamboocss/plugin-vue": "1.46.1",
75
- "@bamboocss/reporter": "1.46.1",
76
- "@bamboocss/shared": "1.46.1",
77
- "@bamboocss/token-dictionary": "1.46.1",
78
- "@bamboocss/types": "1.46.1"
68
+ "@bamboocss/config": "1.46.3",
69
+ "@bamboocss/core": "1.46.3",
70
+ "@bamboocss/generator": "1.46.3",
71
+ "@bamboocss/logger": "1.46.3",
72
+ "@bamboocss/parser": "1.46.3",
73
+ "@bamboocss/plugin-svelte": "1.46.3",
74
+ "@bamboocss/plugin-vue": "1.46.3",
75
+ "@bamboocss/reporter": "1.46.3",
76
+ "@bamboocss/shared": "1.46.3",
77
+ "@bamboocss/token-dictionary": "1.46.3",
78
+ "@bamboocss/types": "1.46.3"
79
79
  },
80
80
  "devDependencies": {
81
81
  "@types/fs-extra": "11.0.4",