@csszyx/unplugin 0.15.2 → 0.15.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.
@@ -4,6 +4,7 @@ import { Plugin } from 'esbuild';
4
4
  import { InputPluginOption } from 'rollup';
5
5
  import { UnpluginInstance, WebpackPluginInstance } from 'unplugin';
6
6
  import { PluginOption } from 'vite';
7
+ import { ClassAttributeSelector } from '../css-mangler.mjs';
7
8
 
8
9
  /** Source location for one CSS custom-property occurrence. */
9
10
  interface CssVarLocation {
@@ -655,6 +656,25 @@ interface MangleHybridHazards {
655
656
  * DOM class is rewritten to a token with no rule → the element loses styling.
656
657
  */
657
658
  orphans: string[];
659
+ /**
660
+ * Attribute selectors on `class` whose match depends on a name the map
661
+ * renamed. `[class*="bg-tag"]` matched `bg-tag-blue-bg` by text; after
662
+ * the rename the element carries `y4`, the rule stops applying, and
663
+ * nothing in the build says so — the CSS is intact and the page renders.
664
+ * Absent when the caller has no selector census.
665
+ */
666
+ selectorMatches?: MangleSelectorHazard[];
667
+ }
668
+ /** One attribute selector the mangle map breaks or newly satisfies. */
669
+ interface MangleSelectorHazard {
670
+ /** The selector as written: `[class*="bg-tag"]`, with ` i` when case-insensitive. */
671
+ selector: string;
672
+ /** The attribute value the selector compares against, unescaped. */
673
+ value: string;
674
+ /** Map keys the selector was matching by name, sorted; renamed, so it no longer does. */
675
+ renamed: string[];
676
+ /** Tokens the selector would start matching that no class name did before, sorted. */
677
+ matchedTokens: string[];
658
678
  }
659
679
  /**
660
680
  * Detect hybrid-mangle hazards from the accumulated per-asset mangle results.
@@ -662,9 +682,10 @@ interface MangleHybridHazards {
662
682
  * @param mangleMap - the full original→token map injected into the runtime.
663
683
  * @param mangledSources - map keys that were actually found and renamed in some CSS asset.
664
684
  * @param externalClasses - class names found in CSS that are NOT in the mangle map (non-csszyx).
665
- * @returns the colliding tokens and orphan sources (each sorted, deduped).
685
+ * @param attributeSelectors - every `[class …]` selector the emitted CSS contains.
686
+ * @returns the colliding tokens, orphan sources and selector hazards (each sorted, deduped).
666
687
  */
667
- declare function collectMangleHybridHazards(mangleMap: Record<string, string>, mangledSources: ReadonlySet<string>, externalClasses: ReadonlySet<string>): MangleHybridHazards;
688
+ declare function collectMangleHybridHazards(mangleMap: Record<string, string>, mangledSources: ReadonlySet<string>, externalClasses: ReadonlySet<string>, attributeSelectors?: readonly ClassAttributeSelector[]): MangleHybridHazards;
668
689
  /**
669
690
  * Build the hybrid-mangle hazard warning, or null when there is nothing to warn.
670
691
  *
@@ -1042,5 +1063,5 @@ declare const rollupPlugin: (options?: PartialCsszyxConfig) => InputPluginOption
1042
1063
  */
1043
1064
  declare const esbuildPlugin: (options?: PartialCsszyxConfig) => Plugin;
1044
1065
 
1045
- export { lateMangleCensusMessage as $, deleteRSCModuleRecord as A, emitMissingCssFallback as B, esbuildPlugin as D, extractGlobalVarAliasesForManifest as E, fileMayContainSafelistableSz as F, findLocalImportSources as H, findRSCBoundaryViolation as I, findRSCGraphViolation as J, hasInjectableTailwindCandidate as K, hasTokens as L, hasUseClientDirective as N, hasUseServerDirective as O, isAdvisoryDiagnostic as T, isCompileSourceOptedIn as U, isHardIgnoredPath as W, isMangleableCssId as X, isMonorepoPackage as Y, isPackagesSkippedSource as Z, isRSCServerModule as _, mangleCodeClassesSync as a0, mangleEligibleClasses as a1, mangleHybridHazardMessage as a2, mergeThemes as a3, missingTailwindEntryMessage as a4, normalizeGlobalVarAliasesForCache as a5, parseThemeBlocks as a6, parseUtilityBlocks as a7, realContentHashDisabledMessage as a8, recordGlobalVarSourceFile as a9, resolveCompileSourceDirs as aa, resolveNativeCacheIdentity as ab, resolveQuietMode as ac, rollupPlugin as ad, scanCustomPropertyNames as ae, shouldEmitMissingCssFallback as af, shouldEmitWarning as ag, shouldTrackGlobalVarSources as ah, shouldWarnMissingTailwindEntry as ai, shouldWarnUnscopedMonorepo as aj, skippedSzFilesMessage as ak, suppressedAdvisoryMessage as al, unscopedMonorepoMessage as am, vitePlugin as an, watchModeMangleMessage as ao, webpackPlugin as ap, allocateMangleTokens as s, assertNoRSCBoundaryViolation as t, assertNoRSCGraphViolation as u, collectMangleHybridHazards as v, createGlobalVarMapAssetSource as w, createRSCModuleRecord as x, cssHasContentScope as y, unplugin as z };
1046
- export type { CssVarScanResult as C, GlobalVarScanCacheKeyInput as G, MangleHybridHazards as M, PlanGlobalVarAliasesInput as P, QuietMode as Q, RewriteGlobalVarCssAliasesOptions as R, ScanGlobalVarCssOptions as S, ValidateGlobalVarAliasInputsOptions as V, GlobalVarAliasPlan as a, GlobalVarCssAliasRewriteResult as b, CreateGlobalVarAliasValidationOptionsInput as c, GlobalVarAliasValidationResult as d, CssVarDefinition as e, CssVarLocation as f, CssVarReference as g, GlobalVarAliasDiagnostic as h, GlobalVarAliasDiagnosticSeverity as i, GlobalVarAliasEntry as j, GlobalVarCodeSource as k, GlobalVarCssAssetSource as l, GlobalVarCssSource as m, GlobalVarScanCacheEntry as n, ParsedTheme as o, ParsedUtilities as p, RSCBoundaryViolation as q, RSCModuleRecord as r };
1066
+ export { isRSCServerModule as $, unplugin as A, deleteRSCModuleRecord as B, emitMissingCssFallback as D, esbuildPlugin as E, extractGlobalVarAliasesForManifest as F, fileMayContainSafelistableSz as H, findLocalImportSources as I, findRSCBoundaryViolation as J, findRSCGraphViolation as K, hasInjectableTailwindCandidate as L, hasTokens as N, hasUseClientDirective as O, hasUseServerDirective as T, isAdvisoryDiagnostic as U, isCompileSourceOptedIn as W, isHardIgnoredPath as X, isMangleableCssId as Y, isMonorepoPackage as Z, isPackagesSkippedSource as _, lateMangleCensusMessage as a0, mangleCodeClassesSync as a1, mangleEligibleClasses as a2, mangleHybridHazardMessage as a3, mergeThemes as a4, missingTailwindEntryMessage as a5, normalizeGlobalVarAliasesForCache as a6, parseThemeBlocks as a7, parseUtilityBlocks as a8, realContentHashDisabledMessage as a9, recordGlobalVarSourceFile as aa, resolveCompileSourceDirs as ab, resolveNativeCacheIdentity as ac, resolveQuietMode as ad, rollupPlugin as ae, scanCustomPropertyNames as af, shouldEmitMissingCssFallback as ag, shouldEmitWarning as ah, shouldTrackGlobalVarSources as ai, shouldWarnMissingTailwindEntry as aj, shouldWarnUnscopedMonorepo as ak, skippedSzFilesMessage as al, suppressedAdvisoryMessage as am, unscopedMonorepoMessage as an, vitePlugin as ao, watchModeMangleMessage as ap, webpackPlugin as aq, allocateMangleTokens as t, assertNoRSCBoundaryViolation as u, assertNoRSCGraphViolation as v, collectMangleHybridHazards as w, createGlobalVarMapAssetSource as x, createRSCModuleRecord as y, cssHasContentScope as z };
1067
+ export type { CssVarScanResult as C, GlobalVarScanCacheKeyInput as G, MangleHybridHazards as M, PlanGlobalVarAliasesInput as P, QuietMode as Q, RewriteGlobalVarCssAliasesOptions as R, ScanGlobalVarCssOptions as S, ValidateGlobalVarAliasInputsOptions as V, GlobalVarAliasPlan as a, GlobalVarCssAliasRewriteResult as b, CreateGlobalVarAliasValidationOptionsInput as c, GlobalVarAliasValidationResult as d, CssVarDefinition as e, CssVarLocation as f, CssVarReference as g, GlobalVarAliasDiagnostic as h, GlobalVarAliasDiagnosticSeverity as i, GlobalVarAliasEntry as j, GlobalVarCodeSource as k, GlobalVarCssAssetSource as l, GlobalVarCssSource as m, GlobalVarScanCacheEntry as n, MangleSelectorHazard as o, ParsedTheme as p, ParsedUtilities as q, RSCBoundaryViolation as r, RSCModuleRecord as s };
@@ -6,7 +6,7 @@ import * as path from 'node:path';
6
6
  import path__default, { dirname } from 'node:path';
7
7
  import { performance } from 'node:perf_hooks';
8
8
  import { fileURLToPath } from 'node:url';
9
- import { scanGlobalVarUsages, sortStrings as sortStrings$1, szFallbackConsequenceOf, ensureRustTransformAvailable, isWasmTransformAvailable, isRustTransformAvailable, transformRust, transformWasm, ASTBudgetExceededError, transformRustBatch, transform } from '@csszyx/compiler';
9
+ import { scanGlobalVarUsages, sortStrings as sortStrings$1, szFallbackConsequenceOf, isWasmTransformAvailable, isRustTransformAvailable, ensureRustTransformAvailable, ASTBudgetExceededError, transformRustBatch, transformRust, transformWasm, transform } from '@csszyx/compiler';
10
10
  import { encode, compute_mangle_checksum } from '@csszyx/core';
11
11
  import { getNativePackageName } from '@csszyx/core/native';
12
12
  import { preprocess as preprocess$1 } from '@csszyx/svelte-adapter';
@@ -14,9 +14,9 @@ import { isTailwindReservedCustomProperty, CSSZYX_GLOBAL_ALIAS_PREFIX, isCsszyxG
14
14
  import { preprocess } from '@csszyx/vue-adapter';
15
15
  import { createUnplugin } from 'unplugin';
16
16
  import { s as sortStrings, n as normalizePathSeparators, h as stripCssBlockComments, S as SAFELIST_FILE, i as findLegacySourceDirective, l as legacySourceMessage, b as cssImportsTailwind, c as computeSafelistRelPath, a as appendTailwindSourceDirective, r as renderSafelistFile, d as atomicWriteFileSync, e as removeLegacySafelists } from './unplugin.DH_ij6cf.mjs';
17
- import { c as collectSpecifierAliases, r as resolveTransformCacheDir, h as evictOldTransformCacheEntries, j as recordSzvRegistryFile, k as recordCrossModuleForwards, l as recordSzObjectRegistryFile, m as mayExportSzvFactories, n as resolveCrossModuleStaticsFor, e as createTransformCacheKey, w as writeTransformCache, o as resolveProviderPath, i as importedSpecifiersIn, s as specifierBases, a as resolveProviderPathWith, g as readTransformCache, p as evictMemoryCacheToBudget, d as isReadableProviderFile } from './unplugin.Bk9o8_RZ.mjs';
18
- import { mangleCSSSync } from '../css-mangler.mjs';
19
- import { c as createMangleRuntimeModule, M as MANGLE_RUNTIME_VIRTUAL_ID, d as createThemeGroupsModule, e as ensureThemeGroupsFile, R as RESOLVED_VIRTUAL_MODULE_ID, f as createMangleMapModule, g as RESOLVED_VIRTUAL_CHECKSUM_ID, j as createChecksumModule, k as RESOLVED_MANGLE_RUNTIME_VIRTUAL_ID, l as RESOLVED_THEME_GROUPS_VIRTUAL_ID, n as isVirtualModule, r as resolveVirtualModule, p as parseThemeBlocks, m as mergeThemes, o as discoverProjectTheme, C as CHECKSUM_PLACEHOLDER, q as CENSUS_PLACEHOLDER, u as importsRuntimeHelper, v as findRuntimeImportClause, T as THEME_GROUPS_VIRTUAL_ID, w as THEME_GROUPS_FILE_MARKER, t as themeGroupsSpecifier, a as parseUtilityBlocks, x as runtimeHelperGroupsFromUsage, b as insertAfterUseDirective, y as MANGLE_MAP_PLACEHOLDER, V as VAR_MANGLE_MAP_PLACEHOLDER } from './unplugin.DK0b4fr7.mjs';
17
+ import { c as collectSpecifierAliases, r as resolveTransformCacheDir, h as evictOldTransformCacheEntries, j as recordSzvRegistryFile, k as recordCrossModuleForwards, l as recordSzObjectRegistryFile, m as mayExportSzvFactories, n as resolveProviderPath, i as importedSpecifiersIn, s as specifierBases, a as resolveProviderPathWith, o as resolveCrossModuleStaticsFor, e as createTransformCacheKey, w as writeTransformCache, g as readTransformCache, p as evictMemoryCacheToBudget, d as isReadableProviderFile } from './unplugin.C-oQU1jl.mjs';
18
+ import { mangleCSSSync, classAttributeSelectorKey } from '../css-mangler.mjs';
19
+ import { c as createMangleRuntimeModule, M as MANGLE_RUNTIME_VIRTUAL_ID, e as ensureThemeGroupsFile, R as RESOLVED_VIRTUAL_MODULE_ID, d as createMangleMapModule, f as RESOLVED_VIRTUAL_CHECKSUM_ID, g as createChecksumModule, j as RESOLVED_MANGLE_RUNTIME_VIRTUAL_ID, k as RESOLVED_THEME_GROUPS_VIRTUAL_ID, l as createThemeGroupsModule, n as isVirtualModule, r as resolveVirtualModule, p as parseThemeBlocks, m as mergeThemes, o as discoverProjectTheme, C as CHECKSUM_PLACEHOLDER, q as CENSUS_PLACEHOLDER, u as importsRuntimeHelper, v as findRuntimeImportClause, T as THEME_GROUPS_VIRTUAL_ID, w as THEME_GROUPS_FILE_MARKER, t as themeGroupsSpecifier, a as parseUtilityBlocks, x as runtimeHelperGroupsFromUsage, b as insertAfterUseDirective, y as MANGLE_MAP_PLACEHOLDER, V as VAR_MANGLE_MAP_PLACEHOLDER } from './unplugin.Ceq-N4jI.mjs';
20
20
  import { gzipSync } from 'node:zlib';
21
21
  import postcss from 'postcss';
22
22
  import valueParser from 'postcss-value-parser';
@@ -1710,22 +1710,22 @@ function expandFilePatterns(rootDir, patterns) {
1710
1710
  return sortStrings(files);
1711
1711
  }
1712
1712
 
1713
- const BACKSLASH = String.fromCodePoint(92);
1713
+ const BACKSLASH$1 = String.fromCodePoint(92);
1714
1714
  function unicodeEscape(hexadecimal) {
1715
- return `${BACKSLASH}u${hexadecimal}`;
1715
+ return `${BACKSLASH$1}u${hexadecimal}`;
1716
1716
  }
1717
1717
  function replaceEveryLiteral(value, search, replacement) {
1718
1718
  return value.replaceAll(search, () => replacement);
1719
1719
  }
1720
1720
  function escapeSingleQuotedString(value) {
1721
- let escaped = replaceEveryLiteral(value, BACKSLASH, BACKSLASH.repeat(2));
1722
- escaped = replaceEveryLiteral(escaped, "'", `${BACKSLASH}'`);
1723
- escaped = replaceEveryLiteral(escaped, "\r", `${BACKSLASH}r`);
1724
- return replaceEveryLiteral(escaped, "\n", `${BACKSLASH}n`);
1721
+ let escaped = replaceEveryLiteral(value, BACKSLASH$1, BACKSLASH$1.repeat(2));
1722
+ escaped = replaceEveryLiteral(escaped, "'", `${BACKSLASH$1}'`);
1723
+ escaped = replaceEveryLiteral(escaped, "\r", `${BACKSLASH$1}r`);
1724
+ return replaceEveryLiteral(escaped, "\n", `${BACKSLASH$1}n`);
1725
1725
  }
1726
1726
  function escapeDoubleQuotedString(value) {
1727
- const escaped = replaceEveryLiteral(value, BACKSLASH, BACKSLASH.repeat(2));
1728
- return replaceEveryLiteral(escaped, '"', `${BACKSLASH}"`);
1727
+ const escaped = replaceEveryLiteral(value, BACKSLASH$1, BACKSLASH$1.repeat(2));
1728
+ return replaceEveryLiteral(escaped, '"', `${BACKSLASH$1}"`);
1729
1729
  }
1730
1730
 
1731
1731
  const LINE_SEPARATOR$1 = String.fromCodePoint(8232);
@@ -1914,6 +1914,60 @@ function removedMangleMapDeliveryMessage() {
1914
1914
  return "[csszyx] production.mangleMapDelivery has been removed and is ignored. The runtime mangle map is always registered from inside the JS bundle now, on every lane, so the built HTML never carries an executable inline <script> and a strict script-src 'self' policy needs no exception. Delete the option. (`window.__csszyx` is now opt-in through `production.mangleDebugGlobal`.)";
1915
1915
  }
1916
1916
 
1917
+ function compileManglePreserve(entries) {
1918
+ const exact = /* @__PURE__ */ new Set();
1919
+ const prefixes = [];
1920
+ const list = entries ?? [];
1921
+ list.forEach((entry, index) => {
1922
+ if (typeof entry !== "string" || entry.length === 0) {
1923
+ throw new TypeError(
1924
+ `[csszyx] production.manglePreserve[${index}] must be a non-empty string (an exact class name, or a prefix ending in \`*\`); got ${describe(entry)}.`
1925
+ );
1926
+ }
1927
+ if (entry === "*") {
1928
+ throw new TypeError(
1929
+ "[csszyx] production.manglePreserve must not contain a lone `*`: it would keep every class and silently turn `production.mangle` into a no-op. Name a prefix (`bg-tag-*`) or set `production.mangle: false`."
1930
+ );
1931
+ }
1932
+ if (entry.endsWith("*")) prefixes.push(entry.slice(0, -1));
1933
+ else exact.add(entry);
1934
+ });
1935
+ const test = (className) => exact.has(className) || prefixes.some((prefix) => className.startsWith(prefix));
1936
+ return {
1937
+ entries: list,
1938
+ test,
1939
+ unmatched(census) {
1940
+ const names = [...census];
1941
+ return list.filter((entry) => {
1942
+ if (entry.endsWith("*")) {
1943
+ const prefix = entry.slice(0, -1);
1944
+ return !names.some((name) => name.startsWith(prefix));
1945
+ }
1946
+ return !names.includes(entry);
1947
+ });
1948
+ }
1949
+ };
1950
+ }
1951
+ function describe(value) {
1952
+ if (typeof value === "string") return "an empty string";
1953
+ if (value instanceof RegExp) return `a RegExp (${String(value)})`;
1954
+ return `${typeof value} ${JSON.stringify(value) ?? String(value)}`;
1955
+ }
1956
+ function manglePreserveNoMatchMessage(entries) {
1957
+ const sample = entries.slice(0, 8).join(", ");
1958
+ const noun = entries.length === 1 ? "entry" : "entries";
1959
+ return `[csszyx] production.manglePreserve: ${entries.length} ${noun} matched no csszyx class in this build (${sample}) \u2014 nothing was preserved for them. Check the spelling against the class census; an entry keeps a class only when its name is exact, or when it ends in \`*\` and the class starts with the rest.`;
1960
+ }
1961
+ const TOKEN_CHARACTERS = /^[0-9a-z]+$/i;
1962
+ function mangleExcludeNeverTokenEntries(entries) {
1963
+ return [...entries].filter((entry) => !TOKEN_CHARACTERS.test(entry));
1964
+ }
1965
+ function mangleExcludeNeverTokenMessage(entries) {
1966
+ const sample = entries.slice(0, 8).join(", ");
1967
+ const noun = entries.length === 1 ? "name" : "names";
1968
+ return `[csszyx] production.mangleExclude: ${entries.length} ${noun} can never be a mangle token (${sample}) \u2014 tokens are short base62 strings, so those entries do nothing. To keep a class from being renamed, list it in \`production.manglePreserve\` instead.`;
1969
+ }
1970
+
1917
1971
  const MANGLE_RUNTIME_FILE = "mangle-runtime.mjs";
1918
1972
  function ensureMangleRuntimeFile(outputDir, globalVarAliasPrefix, exposeDebugGlobal) {
1919
1973
  const target = path__default.join(outputDir, MANGLE_RUNTIME_FILE);
@@ -2207,17 +2261,103 @@ function shouldWarnMissingTailwindEntry(ownedClassCount, sawTailwindEntry, sawAn
2207
2261
  function missingTailwindEntryMessage(ownedClassCount) {
2208
2262
  return `[csszyx] generated ${ownedClassCount} sz class(es) but found no CSS entry importing "tailwindcss" \u2014 those classes will produce no CSS. Import "tailwindcss" in a CSS file (csszyx auto-injects @source for the generated classes) so Tailwind emits their styles.`;
2209
2263
  }
2210
- function collectMangleHybridHazards(mangleMap, mangledSources, externalClasses) {
2264
+ function asciiLower(text) {
2265
+ return text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
2266
+ }
2267
+ function attributeSelectorPredicates(operator, value) {
2268
+ const eq = (v) => (name) => name === v;
2269
+ const startsWith = (v) => (name) => name.startsWith(v);
2270
+ const endsWith = (v) => (name) => name.endsWith(v);
2271
+ const includes = (v) => (name) => name.includes(v);
2272
+ const dashPrefix = (v) => (name) => name === v || name.startsWith(`${v}-`);
2273
+ const segments = value.split(/[\t\n\f\r ]+/);
2274
+ if (segments.length === 1) {
2275
+ switch (operator) {
2276
+ case "=":
2277
+ case "~=":
2278
+ return [eq(value)];
2279
+ case "|=":
2280
+ return [dashPrefix(value)];
2281
+ case "^=":
2282
+ return [startsWith(value)];
2283
+ case "$=":
2284
+ return [endsWith(value)];
2285
+ case "*=":
2286
+ return [includes(value)];
2287
+ default:
2288
+ return [];
2289
+ }
2290
+ }
2291
+ if (operator === "~=") return [];
2292
+ const first = segments[0];
2293
+ const last = segments[segments.length - 1];
2294
+ const predicates = [];
2295
+ if (first.length > 0) {
2296
+ predicates.push(operator === "$=" || operator === "*=" ? endsWith(first) : eq(first));
2297
+ }
2298
+ for (const middle of segments.slice(1, -1)) predicates.push(eq(middle));
2299
+ if (last.length > 0) {
2300
+ if (operator === "^=" || operator === "*=") predicates.push(startsWith(last));
2301
+ else if (operator === "|=") predicates.push(dashPrefix(last));
2302
+ else predicates.push(eq(last));
2303
+ }
2304
+ return predicates;
2305
+ }
2306
+ function renderClassAttributeSelector(selector) {
2307
+ const flag = selector.insensitive ? " i" : "";
2308
+ return `[class${selector.operator}"${selector.value}"${flag}]`;
2309
+ }
2310
+ function selectorHazardFor(mangleMap, selector) {
2311
+ const value = selector.insensitive ? asciiLower(selector.value) : selector.value;
2312
+ const predicates = attributeSelectorPredicates(selector.operator, value);
2313
+ if (predicates.length === 0) return null;
2314
+ const fold = selector.insensitive ? asciiLower : (name) => name;
2315
+ const matches = (name) => {
2316
+ const folded = fold(name);
2317
+ return predicates.some((predicate) => predicate(folded));
2318
+ };
2319
+ const renamed = sortStrings$1(Object.keys(mangleMap).filter(matches));
2320
+ const matchedTokens = sortStrings$1(Object.values(mangleMap).filter(matches));
2321
+ if (renamed.length === 0 && matchedTokens.length === 0) return null;
2322
+ return {
2323
+ selector: renderClassAttributeSelector(selector),
2324
+ value: selector.value,
2325
+ renamed,
2326
+ matchedTokens
2327
+ };
2328
+ }
2329
+ function collectMangleHybridHazards(mangleMap, mangledSources, externalClasses, attributeSelectors = []) {
2211
2330
  const tokenValues = new Set(Object.values(mangleMap));
2212
2331
  const collisions = sortStrings$1([...tokenValues].filter((token) => externalClasses.has(token)));
2213
2332
  const orphans = sortStrings$1(
2214
2333
  Object.keys(mangleMap).filter((source) => !mangledSources.has(source))
2215
2334
  );
2216
- return { collisions, orphans };
2335
+ const hazards = /* @__PURE__ */ new Map();
2336
+ for (const selector of attributeSelectors) {
2337
+ const hazard = selectorHazardFor(mangleMap, selector);
2338
+ if (hazard !== null) hazards.set(hazard.selector, hazard);
2339
+ }
2340
+ const selectorMatches = sortStrings$1([...hazards.keys()]).map(
2341
+ (key) => hazards.get(key)
2342
+ );
2343
+ return { collisions, orphans, selectorMatches };
2344
+ }
2345
+ const BACKSLASH = String.fromCodePoint(92);
2346
+ const SINGLE_QUOTE = String.fromCodePoint(39);
2347
+ function quoteForConfig(entry) {
2348
+ const escaped = entry.replaceAll(BACKSLASH, BACKSLASH + BACKSLASH).replaceAll(SINGLE_QUOTE, BACKSLASH + SINGLE_QUOTE);
2349
+ return SINGLE_QUOTE + escaped + SINGLE_QUOTE;
2350
+ }
2351
+ function preserveEntriesFor(hazard) {
2352
+ const quote = quoteForConfig;
2353
+ const { value } = hazard;
2354
+ if (hazard.renamed.every((name) => name === value)) return [quote(value)];
2355
+ if (hazard.renamed.every((name) => name.startsWith(value))) return [quote(`${value}*`)];
2356
+ return hazard.renamed.map(quote);
2217
2357
  }
2218
2358
  function mangleHybridHazardMessage(hazards) {
2219
- const { collisions, orphans } = hazards;
2220
- if (collisions.length === 0 && orphans.length === 0) {
2359
+ const { collisions, orphans, selectorMatches = [] } = hazards;
2360
+ if (collisions.length === 0 && orphans.length === 0 && selectorMatches.length === 0) {
2221
2361
  return null;
2222
2362
  }
2223
2363
  const parts = ["[csszyx] production mangle found hybrid hazards:"];
@@ -2233,15 +2373,35 @@ function mangleHybridHazardMessage(hazards) {
2233
2373
  ` ${orphans.length} mangled class(es) have no emitted CSS rule (e.g. ${sample}) \u2014 those elements lose styling.`
2234
2374
  );
2235
2375
  }
2376
+ const broken = selectorMatches.filter((hazard) => hazard.renamed.length > 0);
2377
+ const newlyMatched = selectorMatches.filter((hazard) => hazard.matchedTokens.length > 0);
2378
+ if (broken.length > 0) {
2379
+ const sample = broken.slice(0, 3).map((hazard) => `${hazard.selector} \u2192 ${hazard.renamed.slice(0, 4).join(", ")}`).join("; ");
2380
+ parts.push(
2381
+ ` ${broken.length} attribute selector(s) match class names by text (e.g. ${sample}) \u2014 those rules stop matching once the classes are renamed, so the elements lose those styles.`
2382
+ );
2383
+ }
2384
+ if (newlyMatched.length > 0) {
2385
+ const sample = newlyMatched.slice(0, 3).map((hazard) => `${hazard.selector} \u2192 ${hazard.matchedTokens.slice(0, 4).join(", ")}`).join("; ");
2386
+ parts.push(
2387
+ ` ${newlyMatched.length} attribute selector(s) would start matching mangled tokens instead (e.g. ${sample}).`
2388
+ );
2389
+ }
2236
2390
  if (collisions.length > 0) {
2237
2391
  parts.push(
2238
2392
  " HOTFIX: pass `production: { mangle: false }` to the csszyx plugin to ship now. THEN fix it: if these short names are in your OWN CSS, rename them to something specific (e.g. `.x` \u2192 `.resize-handle-x`) \u2014 short/common names also clash on specificity with other libraries. Only for names in a third-party stylesheet you cannot edit, list them in `production.mangleExclude` instead. Run `npx @csszyx/cli scan-collisions` to find every offending name."
2239
2393
  );
2240
- } else {
2394
+ } else if (orphans.length > 0) {
2241
2395
  parts.push(
2242
2396
  " Those classes are csszyx-owned but no CSS was emitted for them (e.g. a separate Tailwind plugin owns the utility CSS, or the class is not a real utility). Ensure that CSS is generated, or pass `production: { mangle: false }` to the csszyx plugin until the pipelines are reconciled."
2243
2397
  );
2244
2398
  }
2399
+ if (broken.length > 0) {
2400
+ const entries = [...new Set(broken.flatMap(preserveEntriesFor))].join(", ");
2401
+ parts.push(
2402
+ ` Keep those classes readable with production.manglePreserve: [${entries}] (paste-ready), or key the rule off a data attribute, which mangling never touches. production.mangleExclude cannot help here: it reserves token names and does not keep a class from being renamed.`
2403
+ );
2404
+ }
2245
2405
  return parts.join("");
2246
2406
  }
2247
2407
  const TAILWIND_IMPORT_SPECIFIER = /@import\s+["']tailwindcss(?:\/[^"']*)?["']/g;
@@ -3146,6 +3306,8 @@ function createCsszyxPlugins(options = {}) {
3146
3306
  const szObjectProvidersExamined = /* @__PURE__ */ new Set();
3147
3307
  let specifierAliases = [];
3148
3308
  const mangleReserved = new Set(options.production?.mangleExclude ?? []);
3309
+ const manglePreserve = compileManglePreserve(options.production?.manglePreserve);
3310
+ let manglePreserveNoMatchWarned = false;
3149
3311
  let mangleMapFrozen = false;
3150
3312
  let prescanSawServerModule = false;
3151
3313
  let skipRscRecords = false;
@@ -3156,6 +3318,7 @@ function createCsszyxPlugins(options = {}) {
3156
3318
  let projectCssFiles = [];
3157
3319
  const transformMangledSources = /* @__PURE__ */ new Set();
3158
3320
  const transformExternalClasses = /* @__PURE__ */ new Set();
3321
+ const transformAttributeSelectors = /* @__PURE__ */ new Map();
3159
3322
  if (options.production?.mangleMapDelivery !== void 0) {
3160
3323
  console.warn(removedMangleMapDeliveryMessage());
3161
3324
  }
@@ -3185,6 +3348,10 @@ function createCsszyxPlugins(options = {}) {
3185
3348
  if (unknownConfigKeys.length > 0) {
3186
3349
  emitWarning(unknownConfigKeysMessage(unknownConfigKeys));
3187
3350
  }
3351
+ const excludeNeverTokens = mangleExcludeNeverTokenEntries(mangleReserved);
3352
+ if (excludeNeverTokens.length > 0) {
3353
+ emitWarning(mangleExcludeNeverTokenMessage(excludeNeverTokens));
3354
+ }
3188
3355
  function emitWarning(message, opts = {}) {
3189
3356
  if (shouldEmitWarning(quiet, opts.devOnly ?? false, process.env.NODE_ENV === "production")) {
3190
3357
  console.warn(message);
@@ -4045,10 +4212,15 @@ function createCsszyxPlugins(options = {}) {
4045
4212
  ...state.authoredClasses,
4046
4213
  ...state.ownedClasses
4047
4214
  ]);
4048
- return allocateMangleTokens(
4049
- mangleEligibleClasses(state.ownedClasses, state.authoredClasses),
4050
- forbiddenTokens
4215
+ const eligible = mangleEligibleClasses(state.ownedClasses, state.authoredClasses).filter(
4216
+ (className) => !manglePreserve.test(className)
4051
4217
  );
4218
+ if (!manglePreserveNoMatchWarned && manglingEnabled && state.ownedClasses.size > 0) {
4219
+ manglePreserveNoMatchWarned = true;
4220
+ const unmatched = manglePreserve.unmatched(state.ownedClasses);
4221
+ if (unmatched.length > 0) emitWarning(manglePreserveNoMatchMessage(unmatched));
4222
+ }
4223
+ return allocateMangleTokens(eligible, forbiddenTokens);
4052
4224
  }
4053
4225
  function freezeMangleMap() {
4054
4226
  state.mangleMap = computeMangleMap();
@@ -4201,6 +4373,38 @@ function createCsszyxPlugins(options = {}) {
4201
4373
  }
4202
4374
  return modules;
4203
4375
  }
4376
+ function handleHotFile(pass, ctx) {
4377
+ const { isClientPass } = pass;
4378
+ if (isClientPass) {
4379
+ prescanResultHandoff.clear();
4380
+ }
4381
+ const scanCss = options.build?.scanCss;
4382
+ const reloadThemeGroupsModule = () => {
4383
+ const themeGroupsModule = ctx.server.moduleGraph.getModuleById(
4384
+ RESOLVED_THEME_GROUPS_VIRTUAL_ID
4385
+ );
4386
+ if (themeGroupsModule) {
4387
+ ctx.server.moduleGraph.invalidateModule(themeGroupsModule);
4388
+ }
4389
+ };
4390
+ if (isClientPass && ctx.file.endsWith(".css")) {
4391
+ const root = state.rootDir;
4392
+ const before = createThemeGroupsModule(themeGroupTokens());
4393
+ if (scanCss && matchesAnyPattern(ctx.file, scanCss, root)) {
4394
+ state.scanCssTheme = runThemeScan(root, scanCss) ?? state.scanCssTheme;
4395
+ }
4396
+ runAutoThemeScan(root);
4397
+ reloadThemeGroupsModule();
4398
+ if (createThemeGroupsModule(themeGroupTokens()) !== before) {
4399
+ ctx.server.ws.send({ type: "full-reload" });
4400
+ }
4401
+ }
4402
+ if (normalizePathSeparators(ctx.file) === normalizePathSeparators(path.join(state.rootDir, SAFELIST_FILENAME))) {
4403
+ return tailwindEntryModules(pass.moduleGraph());
4404
+ }
4405
+ if (isClientPass) discoverHotFileClasses(ctx.file, ctx.server.watcher);
4406
+ return void 0;
4407
+ }
4204
4408
  function transformTailwindCssEntry(code, id) {
4205
4409
  state.sawAnyCss = true;
4206
4410
  const [cssFile] = id.split("?");
@@ -4702,38 +4906,39 @@ ${transformedCode}`;
4702
4906
  * which leaves Vite's own handling in place.
4703
4907
  */
4704
4908
  hotUpdate(ctx) {
4705
- const isClientPass = (this.environment?.name ?? "client") === "client";
4706
- if (isClientPass) {
4707
- prescanResultHandoff.clear();
4708
- }
4709
- const scanCss = options.build?.scanCss;
4710
- const reloadThemeGroupsModule = () => {
4711
- const themeGroupsModule = ctx.server.moduleGraph.getModuleById(
4712
- RESOLVED_THEME_GROUPS_VIRTUAL_ID
4713
- );
4714
- if (themeGroupsModule) {
4715
- ctx.server.moduleGraph.invalidateModule(themeGroupsModule);
4716
- }
4717
- };
4718
- if (isClientPass && ctx.file.endsWith(".css")) {
4719
- const root = ctx.server.config.root || process.cwd();
4720
- const before = createThemeGroupsModule(themeGroupTokens());
4721
- if (scanCss && matchesAnyPattern(ctx.file, scanCss, root)) {
4722
- state.scanCssTheme = runThemeScan(root, scanCss) ?? state.scanCssTheme;
4723
- }
4724
- runAutoThemeScan(root);
4725
- reloadThemeGroupsModule();
4726
- if (createThemeGroupsModule(themeGroupTokens()) !== before) {
4727
- ctx.server.ws.send({ type: "full-reload" });
4728
- }
4729
- }
4730
- if (normalizePathSeparators(ctx.file) === normalizePathSeparators(path.join(state.rootDir, SAFELIST_FILENAME))) {
4731
- return tailwindEntryModules(
4732
- this.environment?.moduleGraph ?? ctx.server.environments.client.moduleGraph
4733
- );
4734
- }
4735
- if (isClientPass) discoverHotFileClasses(ctx.file, ctx.server.watcher);
4736
- return void 0;
4909
+ return handleHotFile(
4910
+ {
4911
+ isClientPass: (this.environment?.name ?? "client") === "client",
4912
+ // `server.moduleGraph` holds the backward-compatible
4913
+ // nodes Vite mapped back for the legacy hook only,
4914
+ // so they are the wrong objects to hand this one —
4915
+ // TypeScript says so too.
4916
+ moduleGraph: () => this.environment?.moduleGraph ?? ctx.server.environments.client.moduleGraph
4917
+ },
4918
+ ctx
4919
+ );
4920
+ },
4921
+ /**
4922
+ * The hook Vite 5 calls. Vite 6 and later never run it while
4923
+ * `hotUpdate` is declared, so declaring both costs nothing
4924
+ * there and keeps a Vite 5 dev server compiling `sz` live.
4925
+ *
4926
+ * Vite 5 routes only a file CHANGE here, never a create, so a
4927
+ * project with no `sz` at prescan still sees its first `sz`
4928
+ * edit answered by `@tailwindcss/vite`'s full reload on that
4929
+ * generation — the behaviour it always had there. The hook
4930
+ * runs once, with no environment, so it is the client pass
4931
+ * and answers from the server-wide graph.
4932
+ *
4933
+ * @param ctx - HMR context: the changed file and the dev server.
4934
+ * @returns The modules a safelist write affects; undefined
4935
+ * otherwise.
4936
+ */
4937
+ handleHotUpdate(ctx) {
4938
+ return handleHotFile(
4939
+ { isClientPass: true, moduleGraph: () => ctx.server.moduleGraph },
4940
+ ctx
4941
+ );
4737
4942
  },
4738
4943
  transformIndexHtml: {
4739
4944
  order: "pre",
@@ -4822,7 +5027,7 @@ ${transformedCode}`;
4822
5027
  recordCodePair(sizeAccount, before, after);
4823
5028
  return after;
4824
5029
  }
4825
- function rewriteOutputCss(source, file, shouldMangle, mangledSources, externalClasses) {
5030
+ function rewriteOutputCss(source, file, shouldMangle, mangledSources, externalClasses, attributeSelectors) {
4826
5031
  const css = rewriteCssWithValidatedGlobalVarPlan(
4827
5032
  source,
4828
5033
  file,
@@ -4836,6 +5041,9 @@ ${transformedCode}`;
4836
5041
  });
4837
5042
  for (const className of result.mangledClasses) mangledSources.add(className);
4838
5043
  for (const className of result.unmangledClasses) externalClasses.add(className);
5044
+ for (const selector of result.classAttributeSelectors) {
5045
+ attributeSelectors.set(classAttributeSelectorKey(selector), selector);
5046
+ }
4839
5047
  const mangled = result.transformedCount > 0 ? result.css : css;
4840
5048
  recordCssPair(sizeAccount, css, mangled);
4841
5049
  return mangled;
@@ -4844,10 +5052,12 @@ ${transformedCode}`;
4844
5052
  throw error;
4845
5053
  }
4846
5054
  }
4847
- function reportOutputMangleHazards(shouldMangle, mangledSources, externalClasses) {
5055
+ function reportOutputMangleHazards(shouldMangle, mangledSources, externalClasses, attributeSelectors) {
4848
5056
  if (!shouldMangle) return;
4849
5057
  const message = mangleHybridHazardMessage(
4850
- collectMangleHybridHazards(state.mangleMap, mangledSources, externalClasses)
5058
+ collectMangleHybridHazards(state.mangleMap, mangledSources, externalClasses, [
5059
+ ...attributeSelectors.values()
5060
+ ])
4851
5061
  );
4852
5062
  if (message) console.warn(message);
4853
5063
  }
@@ -4908,6 +5118,7 @@ ${transformedCode}`;
4908
5118
  }
4909
5119
  const mangledSources = /* @__PURE__ */ new Set();
4910
5120
  const externalClasses = /* @__PURE__ */ new Set();
5121
+ const attributeSelectors = /* @__PURE__ */ new Map();
4911
5122
  for (const file in assets) {
4912
5123
  const source = assets[file].source().toString();
4913
5124
  if (file.endsWith(".css")) {
@@ -4916,7 +5127,8 @@ ${transformedCode}`;
4916
5127
  file,
4917
5128
  shouldMangle,
4918
5129
  mangledSources,
4919
- externalClasses
5130
+ externalClasses,
5131
+ attributeSelectors
4920
5132
  );
4921
5133
  if (css !== source) {
4922
5134
  compilation.updateAsset(file, new compiler.webpack.sources.RawSource(css));
@@ -4925,10 +5137,15 @@ ${transformedCode}`;
4925
5137
  rewriteWebpackCodeAsset(file, source, shouldMangle, compilation, compiler);
4926
5138
  }
4927
5139
  }
4928
- reportOutputMangleHazards(shouldMangle, mangledSources, externalClasses);
5140
+ reportOutputMangleHazards(
5141
+ shouldMangle,
5142
+ mangledSources,
5143
+ externalClasses,
5144
+ attributeSelectors
5145
+ );
4929
5146
  reportBuildSummary();
4930
5147
  }
4931
- function rewriteViteBundleEntry(chunk, file, shouldMangle, mangledSources, externalClasses) {
5148
+ function rewriteViteBundleEntry(chunk, file, shouldMangle, mangledSources, externalClasses, attributeSelectors) {
4932
5149
  if (chunk.type !== "asset" || !chunk.fileName.endsWith(".css") || chunk.source === void 0) {
4933
5150
  return;
4934
5151
  }
@@ -4938,7 +5155,8 @@ ${transformedCode}`;
4938
5155
  file,
4939
5156
  shouldMangle,
4940
5157
  mangledSources,
4941
- externalClasses
5158
+ externalClasses,
5159
+ attributeSelectors
4942
5160
  );
4943
5161
  if (css !== originalCss) chunk.source = css;
4944
5162
  }
@@ -4949,7 +5167,8 @@ ${transformedCode}`;
4949
5167
  id,
4950
5168
  shouldMangle,
4951
5169
  transformMangledSources,
4952
- transformExternalClasses
5170
+ transformExternalClasses,
5171
+ transformAttributeSelectors
4953
5172
  );
4954
5173
  return css === code ? null : { code: css, map: null };
4955
5174
  }
@@ -4974,6 +5193,7 @@ ${transformedCode}`;
4974
5193
  }
4975
5194
  const mangledSources = new Set(transformMangledSources);
4976
5195
  const externalClasses = new Set(transformExternalClasses);
5196
+ const attributeSelectors = new Map(transformAttributeSelectors);
4977
5197
  if (!cssRewrittenInTransform) {
4978
5198
  for (const file in bundle) {
4979
5199
  rewriteViteBundleEntry(
@@ -4981,11 +5201,17 @@ ${transformedCode}`;
4981
5201
  file,
4982
5202
  shouldMangle,
4983
5203
  mangledSources,
4984
- externalClasses
5204
+ externalClasses,
5205
+ attributeSelectors
4985
5206
  );
4986
5207
  }
4987
5208
  }
4988
- reportOutputMangleHazards(shouldMangle, mangledSources, externalClasses);
5209
+ reportOutputMangleHazards(
5210
+ shouldMangle,
5211
+ mangledSources,
5212
+ externalClasses,
5213
+ attributeSelectors
5214
+ );
4989
5215
  }
4990
5216
  const postPlugin = createUnplugin(() => ({
4991
5217
  name: "csszyx:post",
@@ -587,4 +587,4 @@ function themeGroupsSpecifier(fromFile, themeGroupsFile) {
587
587
  return relative.startsWith("./") || relative.startsWith("../") ? relative : `./${relative}`;
588
588
  }
589
589
 
590
- export { CHECKSUM_PLACEHOLDER as C, MANGLE_RUNTIME_VIRTUAL_ID as M, RESOLVED_VIRTUAL_MODULE_ID as R, THEME_GROUPS_VIRTUAL_ID as T, VAR_MANGLE_MAP_PLACEHOLDER as V, parseUtilityBlocks as a, insertAfterUseDirective as b, createMangleRuntimeModule as c, createThemeGroupsModule as d, ensureThemeGroupsFile as e, createMangleMapModule as f, RESOLVED_VIRTUAL_CHECKSUM_ID as g, hasTokens as h, injectNextRuntimeImports as i, createChecksumModule as j, RESOLVED_MANGLE_RUNTIME_VIRTUAL_ID as k, RESOLVED_THEME_GROUPS_VIRTUAL_ID as l, mergeThemes as m, isVirtualModule as n, discoverProjectTheme as o, parseThemeBlocks as p, CENSUS_PLACEHOLDER as q, resolveVirtualModule as r, scanCustomPropertyNames as s, themeGroupsSpecifier as t, importsRuntimeHelper as u, findRuntimeImportClause as v, THEME_GROUPS_FILE_MARKER as w, runtimeHelperGroupsFromUsage as x, MANGLE_MAP_PLACEHOLDER as y };
590
+ export { CHECKSUM_PLACEHOLDER as C, MANGLE_RUNTIME_VIRTUAL_ID as M, RESOLVED_VIRTUAL_MODULE_ID as R, THEME_GROUPS_VIRTUAL_ID as T, VAR_MANGLE_MAP_PLACEHOLDER as V, parseUtilityBlocks as a, insertAfterUseDirective as b, createMangleRuntimeModule as c, createMangleMapModule as d, ensureThemeGroupsFile as e, RESOLVED_VIRTUAL_CHECKSUM_ID as f, createChecksumModule as g, hasTokens as h, injectNextRuntimeImports as i, RESOLVED_MANGLE_RUNTIME_VIRTUAL_ID as j, RESOLVED_THEME_GROUPS_VIRTUAL_ID as k, createThemeGroupsModule as l, mergeThemes as m, isVirtualModule as n, discoverProjectTheme as o, parseThemeBlocks as p, CENSUS_PLACEHOLDER as q, resolveVirtualModule as r, scanCustomPropertyNames as s, themeGroupsSpecifier as t, importsRuntimeHelper as u, findRuntimeImportClause as v, THEME_GROUPS_FILE_MARKER as w, runtimeHelperGroupsFromUsage as x, MANGLE_MAP_PLACEHOLDER as y };
@@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import { extractCrossModuleForwards, extractCrossModuleRegistryEntries, ensureRustTransformAvailable, transformRust, transformWasm, transform } from '@csszyx/compiler';
4
4
  import { DEFAULT_IMPORTED_STATIC_SZ } from '@csszyx/types';
5
- import { c as collectSpecifierAliases, i as importedSpecifiersIn, s as specifierBases, a as resolveProviderPathWith, b as recordResolvedEntry, f as forwardVisitKey, M as MAX_FORWARD_HOPS, d as isReadableProviderFile, e as createTransformCacheKey, g as readTransformCache, w as writeTransformCache } from './unplugin.Bk9o8_RZ.mjs';
5
+ import { c as collectSpecifierAliases, i as importedSpecifiersIn, s as specifierBases, a as resolveProviderPathWith, b as recordResolvedEntry, f as forwardVisitKey, M as MAX_FORWARD_HOPS, d as isReadableProviderFile, e as createTransformCacheKey, g as readTransformCache, w as writeTransformCache } from './unplugin.C-oQU1jl.mjs';
6
6
  import { n as normalizePathSeparators, s as sortStrings } from './unplugin.DH_ij6cf.mjs';
7
7
  import { createHash } from 'node:crypto';
8
8