@tenphi/tasty 0.0.0-snapshot.cb232f9 → 0.0.0-snapshot.cb3b623

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/{collector-DROCOiaT.js → collector-BZe0AMUR.js} +3 -3
  2. package/dist/{collector-DROCOiaT.js.map → collector-BZe0AMUR.js.map} +1 -1
  3. package/dist/{collector-BQHl-atL.d.ts → collector-osfWTeRd.d.ts} +2 -2
  4. package/dist/{config-CzzTHmtS.d.ts → config-BoZDUHW5.d.ts} +19 -2
  5. package/dist/{config-JokB1Lc8.js → config-LDodmgVz.js} +1235 -1123
  6. package/dist/config-LDodmgVz.js.map +1 -0
  7. package/dist/core/index.d.ts +4 -4
  8. package/dist/core/index.js +5 -5
  9. package/dist/{core-CW4XEUFk.js → core-CQfmSOQW.js} +5 -5
  10. package/dist/{core-CW4XEUFk.js.map → core-CQfmSOQW.js.map} +1 -1
  11. package/dist/{css-writer-Jv468wSl.js → css-writer-BjqQ_6-j.js} +3 -3
  12. package/dist/{css-writer-Jv468wSl.js.map → css-writer-BjqQ_6-j.js.map} +1 -1
  13. package/dist/{format-rules-B0vbh8Qz.js → format-rules-CkZinBt0.js} +2 -2
  14. package/dist/{format-rules-B0vbh8Qz.js.map → format-rules-CkZinBt0.js.map} +1 -1
  15. package/dist/{hydrate-BO6nlAeD.js → hydrate-M5WHyrmy.js} +2 -2
  16. package/dist/{hydrate-BO6nlAeD.js.map → hydrate-M5WHyrmy.js.map} +1 -1
  17. package/dist/{index-CgD29XlB.d.ts → index-J7y6BV89.d.ts} +9 -6
  18. package/dist/{index-Dy74C11K.d.ts → index-tcHuMPFt.d.ts} +15 -2
  19. package/dist/index.d.ts +4 -4
  20. package/dist/index.js +7 -53
  21. package/dist/index.js.map +1 -1
  22. package/dist/{keyframes-J_JNrpdh.js → keyframes-Bp3MU20J.js} +2 -2
  23. package/dist/{keyframes-J_JNrpdh.js.map → keyframes-Bp3MU20J.js.map} +1 -1
  24. package/dist/{merge-styles-BS-mpcci.d.ts → merge-styles-BMWcH6MF.d.ts} +2 -2
  25. package/dist/{merge-styles-Du-eC7zp.js → merge-styles-DQW8Anlk.js} +2 -2
  26. package/dist/{merge-styles-Du-eC7zp.js.map → merge-styles-DQW8Anlk.js.map} +1 -1
  27. package/dist/{resolve-recipes-DPRT3FMM.js → resolve-recipes-BIxxAwSm.js} +3 -3
  28. package/dist/{resolve-recipes-DPRT3FMM.js.map → resolve-recipes-BIxxAwSm.js.map} +1 -1
  29. package/dist/ssr/astro-client.js +1 -1
  30. package/dist/ssr/astro.js +3 -3
  31. package/dist/ssr/index.d.ts +1 -1
  32. package/dist/ssr/index.js +3 -3
  33. package/dist/ssr/next.d.ts +1 -1
  34. package/dist/ssr/next.js +4 -4
  35. package/dist/static/index.d.ts +2 -2
  36. package/dist/static/index.js +1 -1
  37. package/dist/zero/babel.d.ts +1 -1
  38. package/dist/zero/babel.js +4 -4
  39. package/dist/zero/index.d.ts +1 -1
  40. package/dist/zero/index.js +1 -1
  41. package/docs/methodology.md +10 -6
  42. package/docs/pipeline.md +40 -14
  43. package/docs/react-api.md +9 -3
  44. package/docs/styles.md +9 -7
  45. package/package.json +7 -7
  46. package/dist/config-JokB1Lc8.js.map +0 -1
@@ -3321,10 +3321,13 @@ function resolveFontFamily(font, fontFamily) {
3321
3321
  /**
3322
3322
  * Handles typography preset and individual font properties.
3323
3323
  *
3324
- * Preset syntax uses `/` to separate name from modifier:
3324
+ * Preset syntax uses `/` to separate the name from one or more
3325
+ * space-separated modifiers:
3325
3326
  * - `preset="h1"` — name only
3326
3327
  * - `preset="h2 / strong"` — name + modifier
3328
+ * - `preset="h2 / strong italic"` — name + multiple modifiers
3327
3329
  * - `preset="bold"` — modifier-only shorthand (name defaults to `inherit`)
3330
+ * - `preset="bold italic"` — modifier-only shorthand with multiple modifiers
3328
3331
  *
3329
3332
  * When `preset` is defined, it sets up CSS custom properties for typography.
3330
3333
  * Individual font props can be used with or without `preset`:
@@ -3344,14 +3347,17 @@ function presetStyle({ preset, fontSize, lineHeight, textTransform, letterSpacin
3344
3347
  const { parts } = parseStyle(preset === true ? "" : String(preset)).groups[0] ?? { parts: [] };
3345
3348
  const namePart = parts[0];
3346
3349
  const modPart = parts[1];
3350
+ const nameTokens = namePart?.all ?? [];
3351
+ const isModOnly = nameTokens.length > 0 && nameTokens.every((t) => PRESET_MODIFIERS.has(t));
3347
3352
  const nameToken = namePart?.mods[0] ?? namePart?.values[0] ?? "";
3348
- const isModOnly = PRESET_MODIFIERS.has(nameToken);
3349
3353
  const name = isModOnly ? "inherit" : nameToken || "inherit";
3350
- const modifier = isModOnly ? nameToken : modPart?.mods[0] ?? "";
3351
- const isStrong = modifier === "strong" || modifier === "bold";
3352
- const isItalic = modifier === "italic";
3353
- const isIcon = modifier === "icon";
3354
- const isTight = modifier === "tight";
3354
+ const modTokens = isModOnly ? nameTokens : modPart?.all ?? [];
3355
+ const activeMods = /* @__PURE__ */ new Set();
3356
+ for (const tok of modTokens) if (PRESET_MODIFIERS.has(tok)) activeMods.add(tok);
3357
+ const isStrong = activeMods.has("strong") || activeMods.has("bold");
3358
+ const isItalic = activeMods.has("italic");
3359
+ const isIcon = activeMods.has("icon");
3360
+ const isTight = activeMods.has("tight");
3355
3361
  if (fontSize == null) setCSSValue(styles, "font-size", name, { cssOnly: true });
3356
3362
  if (lineHeight == null) setCSSValue(styles, "line-height", name, { cssOnly: true });
3357
3363
  if (letterSpacing == null) setCSSValue(styles, "letter-spacing", name, { cssOnly: true });
@@ -4216,7 +4222,7 @@ var SheetManager = class {
4216
4222
  }
4217
4223
  }
4218
4224
  if (!anyInserted) {}
4219
- } else console.warn("[tasty] Browser rejected CSS rule:", fullRule, e);
4225
+ } else if (!(fullRule.startsWith("@property ") && !this.engineSupportsAtProperty(registry, styleSheet))) console.warn("[tasty] Browser rejected CSS rule:", fullRule, e);
4220
4226
  }
4221
4227
  } else if (styleElement) {
4222
4228
  const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);
@@ -4368,6 +4374,37 @@ var SheetManager = class {
4368
4374
  return sheet.ruleCount;
4369
4375
  }
4370
4376
  /**
4377
+ * Probe whether the underlying CSS engine supports `@property` at-rules.
4378
+ * Result is cached per registry on `registry.atPropertySupported`.
4379
+ *
4380
+ * The probe inserts and immediately deletes a minimal known-valid rule
4381
+ * (`@property --__tasty_probe__ { syntax: "*"; inherits: true; }`).
4382
+ * Engines that lack `@property` support (jsdom, happy-dom) reject any
4383
+ * `@property` rule including this one, so a probe failure is a reliable
4384
+ * signal that further `@property` rejections are environmental noise and
4385
+ * not user-authored bugs.
4386
+ *
4387
+ * The probe is intentionally a separate operation from the user's failing
4388
+ * insertion: we don't want to leak `--__tasty_probe__` into the sheet, so
4389
+ * on success we delete the probe rule immediately, leaving `ruleCount`
4390
+ * and `cssRules.length` unchanged.
4391
+ */
4392
+ engineSupportsAtProperty(registry, styleSheet) {
4393
+ if (registry.atPropertySupported !== void 0) return registry.atPropertySupported;
4394
+ const probeRule = "@property --__tasty_probe__ { syntax: \"*\"; inherits: true; }";
4395
+ try {
4396
+ const probeIdx = styleSheet.cssRules.length;
4397
+ styleSheet.insertRule(probeRule, probeIdx);
4398
+ try {
4399
+ styleSheet.deleteRule(probeIdx);
4400
+ } catch {}
4401
+ registry.atPropertySupported = true;
4402
+ } catch {
4403
+ registry.atPropertySupported = false;
4404
+ }
4405
+ return registry.atPropertySupported;
4406
+ }
4407
+ /**
4371
4408
  * Force cleanup of unused styles
4372
4409
  */
4373
4410
  forceCleanup(registry) {
@@ -5306,8 +5343,8 @@ var StyleInjector = class {
5306
5343
  selector: `@property ${cssName}`,
5307
5344
  declarations
5308
5345
  };
5309
- if (!this.sheetManager.insertGlobalRule(registry, [rule], `property:${cacheKey}`, root)) return;
5310
5346
  registry.injectedProperties.set(cssName, normalizePropertyDefinition(definition));
5347
+ this.sheetManager.insertGlobalRule(registry, [rule], `property:${cacheKey}`, root);
5311
5348
  }
5312
5349
  /**
5313
5350
  * Check whether a given @property name was already injected by this injector.
@@ -6889,942 +6926,558 @@ function pruneContradictedOrBranches(terms) {
6889
6926
  return flattened;
6890
6927
  }
6891
6928
  //#endregion
6892
- //#region src/pipeline/exclusive.ts
6929
+ //#region src/pipeline/materialize-contradictions.ts
6893
6930
  /**
6894
- * Build exclusive conditions for a list of parsed style entries.
6895
- *
6896
- * The entries should be ordered by priority (highest priority first).
6897
- *
6898
- * For each entry, we compute:
6899
- * exclusiveCondition = condition & !prior[0] & !prior[1] & ...
6900
- *
6901
- * This ensures exactly one condition matches at any time.
6902
- *
6903
- * Example:
6904
- * Input (ordered highest to lowest priority):
6905
- * A: value1 (priority 2)
6906
- * B: value2 (priority 1)
6907
- * C: value3 (priority 0)
6908
- *
6909
- * Output:
6910
- * A: A
6911
- * B: B & !A
6912
- * C: C & !A & !B
6913
- *
6914
- * @param entries Parsed style entries ordered by priority (highest first)
6915
- * @returns Entries with exclusive conditions, filtered to remove impossible ones
6931
+ * Generic deduplication by a key extraction function.
6932
+ * Preserves insertion order, keeping the first occurrence of each key.
6916
6933
  */
6917
- function buildExclusiveConditions(entries) {
6934
+ function dedupeByKey(items, getKey) {
6935
+ const seen = /* @__PURE__ */ new Set();
6918
6936
  const result = [];
6919
- const priorConditions = [];
6920
- for (const entry of entries) {
6921
- let exclusive = entry.condition;
6922
- for (const prior of priorConditions) if (prior.kind !== "true") exclusive = and(exclusive, not(prior));
6923
- const simplified = simplifyCondition(exclusive);
6924
- if (simplified.kind === "false") continue;
6925
- result.push({
6926
- ...entry,
6927
- exclusiveCondition: simplified
6928
- });
6929
- if (entry.condition.kind !== "true") priorConditions.push(entry.condition);
6937
+ for (const item of items) {
6938
+ const key = getKey(item);
6939
+ if (!seen.has(key)) {
6940
+ seen.add(key);
6941
+ result.push(item);
6942
+ }
6930
6943
  }
6931
6944
  return result;
6932
6945
  }
6946
+ function dedupeMediaConditions(conditions) {
6947
+ return dedupeByKey(conditions, (c) => `${c.subtype}|${c.condition}|${c.negated}`);
6948
+ }
6949
+ function dedupeContainerConditions(conditions) {
6950
+ return dedupeByKey(conditions, (c) => `${c.name ?? ""}|${c.condition}|${c.negated}`);
6951
+ }
6952
+ function dedupeSupportsConditions(conditions) {
6953
+ return dedupeByKey(conditions, (c) => `${c.subtype}|${c.condition}|${c.negated}`);
6954
+ }
6933
6955
  /**
6934
- * Parse style entries from a value mapping object.
6935
- *
6936
- * @param styleKey The style key (e.g., 'padding')
6937
- * @param valueMap The value mapping { '': '2x', 'compact': '1x', '@media(w < 768px)': '0.5x' }
6938
- * @param parseCondition Function to parse state keys into conditions
6939
- * @returns Parsed entries ordered by priority (highest first)
6956
+ * Check if supports conditions contain contradictions
6957
+ * e.g., @supports(display: grid) AND NOT @supports(display: grid)
6940
6958
  */
6941
- function parseStyleEntries(styleKey, valueMap, parseCondition) {
6942
- const entries = [];
6943
- Object.keys(valueMap).forEach((stateKey, index) => {
6944
- const value = valueMap[stateKey];
6945
- const condition = stateKey === "" ? trueCondition() : parseCondition(stateKey);
6946
- entries.push({
6947
- styleKey,
6948
- stateKey,
6949
- value,
6950
- condition,
6951
- priority: index
6952
- });
6953
- });
6954
- entries.reverse();
6955
- return entries;
6959
+ function hasSupportsContradiction(conditions) {
6960
+ const conditionMap = /* @__PURE__ */ new Map();
6961
+ for (const cond of conditions) {
6962
+ const key = `${cond.subtype}|${cond.condition}`;
6963
+ const existing = conditionMap.get(key);
6964
+ if (existing !== void 0 && existing !== !cond.negated) return true;
6965
+ conditionMap.set(key, !cond.negated);
6966
+ }
6967
+ return false;
6956
6968
  }
6957
6969
  /**
6958
- * Merge parsed entries that share the same value.
6959
- *
6960
- * When multiple **non-default** state keys map to the same value, their
6961
- * conditions can be combined with OR and treated as a single entry.
6962
- * This must happen **before** exclusive expansion and OR branch splitting
6963
- * to avoid combinatorial explosion and duplicate CSS output.
6964
- *
6965
- * Default (TRUE) entries are **never** merged with non-default entries.
6966
- * Merging `TRUE | X` collapses to `TRUE`, destroying the non-default
6967
- * condition's participation in exclusive building. That causes
6968
- * intermediate-priority states to lose their `:not(X)` negation,
6969
- * breaking mutual exclusivity when X and an intermediate state are
6970
- * both active. Stage 6 `mergeByValue` handles combining rules with
6971
- * identical CSS output after exclusive conditions are correctly built.
6972
- *
6973
- * Example: `{ '@dark': 'red', '@dark & @hc': 'red' }` merges into a
6974
- * single entry with condition `@dark | (@dark & @hc)` = `@dark`.
6970
+ * Check if a set of media conditions contains contradictions
6971
+ * e.g., (prefers-color-scheme: light) AND NOT (prefers-color-scheme: light)
6972
+ * or (width >= 900px) AND (width < 600px)
6975
6973
  *
6976
- * Entries are ordered highest-priority-first. The merged entry keeps the
6977
- * highest priority of the group.
6974
+ * Uses parsed media conditions for efficient analysis without regex parsing.
6978
6975
  */
6979
- function mergeEntriesByValue(entries) {
6980
- if (entries.length <= 1) return entries;
6981
- const groups = /* @__PURE__ */ new Map();
6982
- for (const entry of entries) {
6983
- const valueKey = serializeValue(entry.value);
6984
- const group = groups.get(valueKey);
6985
- if (group) {
6986
- group.entries.push(entry);
6987
- group.maxPriority = Math.max(group.maxPriority, entry.priority);
6988
- } else groups.set(valueKey, {
6989
- entries: [entry],
6990
- maxPriority: entry.priority
6991
- });
6992
- }
6993
- if (groups.size === entries.length) return entries;
6994
- const merged = [];
6995
- for (const [, group] of groups) {
6996
- if (group.entries.length === 1) {
6997
- merged.push(group.entries[0]);
6998
- continue;
6999
- }
7000
- const defaultEntries = group.entries.filter((e) => e.condition.kind === "true");
7001
- const nonDefaultEntries = group.entries.filter((e) => e.condition.kind !== "true");
7002
- for (const entry of defaultEntries) merged.push(entry);
7003
- if (nonDefaultEntries.length === 1) merged.push(nonDefaultEntries[0]);
7004
- else if (nonDefaultEntries.length >= 2) {
7005
- const combinedCondition = simplifyCondition(or(...nonDefaultEntries.map((e) => e.condition)));
7006
- const combinedStateKey = nonDefaultEntries.map((e) => e.stateKey).join(" | ");
7007
- merged.push({
7008
- styleKey: nonDefaultEntries[0].styleKey,
7009
- stateKey: combinedStateKey,
7010
- value: nonDefaultEntries[0].value,
7011
- condition: combinedCondition,
7012
- priority: group.maxPriority
7013
- });
6976
+ function hasMediaContradiction(conditions) {
6977
+ const featureConditions = /* @__PURE__ */ new Map();
6978
+ const typeConditions = /* @__PURE__ */ new Map();
6979
+ const dimensionConditions = /* @__PURE__ */ new Map();
6980
+ const dimensionsByDim = /* @__PURE__ */ new Map();
6981
+ for (const cond of conditions) if (cond.subtype === "type") {
6982
+ const key = cond.mediaType || "all";
6983
+ const existing = typeConditions.get(key);
6984
+ if (existing !== void 0 && existing !== !cond.negated) return true;
6985
+ typeConditions.set(key, !cond.negated);
6986
+ } else if (cond.subtype === "feature") {
6987
+ const key = cond.condition;
6988
+ const existing = featureConditions.get(key);
6989
+ if (existing !== void 0 && existing !== !cond.negated) return true;
6990
+ featureConditions.set(key, !cond.negated);
6991
+ } else if (cond.subtype === "dimension") {
6992
+ const condKey = cond.condition;
6993
+ const existing = dimensionConditions.get(condKey);
6994
+ if (existing !== void 0 && existing !== !cond.negated) return true;
6995
+ dimensionConditions.set(condKey, !cond.negated);
6996
+ if (!cond.negated) {
6997
+ const dim = cond.dimension || "width";
6998
+ let bounds = dimensionsByDim.get(dim);
6999
+ if (!bounds) {
7000
+ bounds = {
7001
+ lowerBound: null,
7002
+ upperBound: null
7003
+ };
7004
+ dimensionsByDim.set(dim, bounds);
7005
+ }
7006
+ if (cond.lowerBound?.valueNumeric != null) {
7007
+ const value = cond.lowerBound.valueNumeric;
7008
+ if (bounds.lowerBound === null || value > bounds.lowerBound) bounds.lowerBound = value;
7009
+ }
7010
+ if (cond.upperBound?.valueNumeric != null) {
7011
+ const value = cond.upperBound.valueNumeric;
7012
+ if (bounds.upperBound === null || value < bounds.upperBound) bounds.upperBound = value;
7013
+ }
7014
+ if (bounds.lowerBound !== null && bounds.upperBound !== null && bounds.lowerBound >= bounds.upperBound) return true;
7014
7015
  }
7015
7016
  }
7016
- merged.sort((a, b) => b.priority - a.priority);
7017
- return merged;
7018
- }
7019
- function serializeValue(value) {
7020
- if (value === null || value === void 0) return "null";
7021
- if (typeof value === "string" || typeof value === "number") return String(value);
7022
- return JSON.stringify(value);
7017
+ return false;
7023
7018
  }
7024
7019
  /**
7025
- * Eliminate redundant state dimensions from a value map.
7026
- *
7027
- * When a value map contains compound AND state keys (e.g. `@dark & @hc`),
7028
- * checks whether any state atom is a "don't-care" variable — i.e. the
7029
- * value is the same whether that atom is present or absent. Redundant
7030
- * atoms are removed from all keys and duplicate entries are collapsed.
7031
- *
7032
- * This runs **before** condition parsing so that downstream stages
7033
- * (`mergeEntriesByValue`, `buildExclusiveConditions`, materialization)
7034
- * never see the irrelevant dimension, producing simpler, smaller CSS.
7035
- *
7036
- * Only pure top-level AND combinations are eligible. Keys that contain
7037
- * `|`, `^`, or `,` at the top level are treated as opaque single atoms.
7020
+ * Check if container conditions contain contradictions in style queries
7021
+ * e.g., style(--variant: danger) and style(--variant: success) together
7022
+ * Same property with different values = always false
7038
7023
  *
7039
- * @example
7040
- * { '': A, '@dark': B, '@hc': A, '@dark & @hc': B }
7041
- * // @hc is redundant → { '': A, '@dark': B }
7024
+ * Uses parsed container conditions for efficient analysis without regex parsing.
7042
7025
  */
7043
- function extractCompoundStates(valueMap) {
7044
- const keys = Object.keys(valueMap);
7045
- if (keys.length < 3 || !keys.some((k) => k.includes("&"))) return valueMap;
7046
- const entries = keys.map((key) => {
7047
- return {
7048
- atoms: splitTopLevelAnd(key) ?? [key],
7049
- value: valueMap[key]
7050
- };
7051
- });
7052
- const allAtoms = /* @__PURE__ */ new Set();
7053
- for (const e of entries) for (const a of e.atoms) allAtoms.add(a);
7054
- const redundant = /* @__PURE__ */ new Set();
7055
- for (const atom of allAtoms) if (isAtomRedundant(entries, atom)) redundant.add(atom);
7056
- if (redundant.size === 0) return valueMap;
7057
- const newMap = {};
7058
- for (const e of entries) {
7059
- const newKey = e.atoms.filter((a) => !redundant.has(a)).join(" & ");
7060
- if (!(newKey in newMap)) newMap[newKey] = e.value;
7026
+ function hasContainerStyleContradiction(conditions) {
7027
+ const styleQueries = /* @__PURE__ */ new Map();
7028
+ for (const cond of conditions) {
7029
+ if (cond.subtype !== "style" || !cond.property) continue;
7030
+ const property = cond.property;
7031
+ const value = cond.propertyValue;
7032
+ if (!styleQueries.has(property)) styleQueries.set(property, {
7033
+ hasExistence: false,
7034
+ values: /* @__PURE__ */ new Set(),
7035
+ hasNegatedExistence: false
7036
+ });
7037
+ const entry = styleQueries.get(property);
7038
+ if (cond.negated) {
7039
+ if (value === void 0) entry.hasNegatedExistence = true;
7040
+ } else if (value === void 0) entry.hasExistence = true;
7041
+ else entry.values.add(value);
7061
7042
  }
7062
- return newMap;
7043
+ for (const [, entry] of styleQueries) {
7044
+ if (entry.hasExistence && entry.hasNegatedExistence) return true;
7045
+ if (entry.values.size > 1) return true;
7046
+ if (entry.hasNegatedExistence && entry.values.size > 0) return true;
7047
+ }
7048
+ return false;
7063
7049
  }
7050
+ //#endregion
7051
+ //#region src/pipeline/materialize.ts
7064
7052
  /**
7065
- * Split a state key by top-level `&` operators.
7053
+ * CSS Materialization
7066
7054
  *
7067
- * Returns `null` if the key contains `|`, `^`, or `,` at the top level
7068
- * (making it ineligible for atom-level extraction).
7069
- * Returns `[]` for the empty string (default key).
7055
+ * Converts condition trees into CSS selectors and at-rules.
7056
+ * This is the final stage that produces actual CSS output.
7070
7057
  */
7071
- function splitTopLevelAnd(key) {
7072
- if (key === "") return [];
7073
- const parts = [];
7074
- let depth = 0;
7075
- let current = "";
7076
- for (const ch of key) {
7077
- if (ch === "(" || ch === "[") depth++;
7078
- else if (ch === ")" || ch === "]") depth--;
7079
- if (depth === 0) {
7080
- if (ch === "&") {
7081
- const trimmed = current.trim();
7082
- if (trimmed) parts.push(trimmed);
7083
- current = "";
7084
- continue;
7085
- }
7086
- if (ch === "|" || ch === "^" || ch === ",") return null;
7087
- }
7088
- current += ch;
7089
- }
7090
- const trimmed = current.trim();
7091
- if (trimmed) parts.push(trimmed);
7092
- return parts;
7093
- }
7058
+ const conditionCache = new Lru(3e3);
7094
7059
  /**
7095
- * An atom is redundant when every entry that contains it has a matching
7096
- * partner (same remaining atoms, atom absent) with the same value.
7060
+ * Convert a condition tree to CSS components
7097
7061
  */
7098
- function isAtomRedundant(entries, atom) {
7099
- const withAtom = entries.filter((e) => e.atoms.includes(atom));
7100
- if (withAtom.length === 0) return false;
7101
- for (const wa of withAtom) {
7102
- const remaining = wa.atoms.filter((a) => a !== atom);
7103
- const pair = entries.find((e) => !e.atoms.includes(atom) && e.atoms.length === remaining.length && remaining.every((r) => e.atoms.includes(r)));
7104
- if (!pair) return false;
7105
- if (serializeValue(wa.value) !== serializeValue(pair.value)) return false;
7106
- }
7107
- return true;
7062
+ function conditionToCSS(node) {
7063
+ const key = getConditionUniqueId(node);
7064
+ const cached = conditionCache.get(key);
7065
+ if (cached) return cached;
7066
+ const result = conditionToCSSInner(node);
7067
+ conditionCache.set(key, result);
7068
+ return result;
7108
7069
  }
7109
- /**
7110
- * Check if a value is a style value mapping (object with state keys)
7111
- */
7112
- function isValueMapping(value) {
7113
- return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
7070
+ function emptyVariant() {
7071
+ return {
7072
+ modifierConditions: [],
7073
+ pseudoConditions: [],
7074
+ selectorGroups: [],
7075
+ ownGroups: [],
7076
+ mediaConditions: [],
7077
+ containerConditions: [],
7078
+ supportsConditions: [],
7079
+ rootGroups: [],
7080
+ parentGroups: [],
7081
+ startingStyle: false
7082
+ };
7114
7083
  }
7115
- /**
7116
- * Expand OR conditions in parsed entries into multiple exclusive entries.
7117
- *
7118
- * For an entry with condition `A | B | C`, this creates 3 entries:
7119
- * - condition: A
7120
- * - condition: B & !A
7121
- * - condition: C & !A & !B
7122
- *
7123
- * This ensures OR branches are mutually exclusive BEFORE the main
7124
- * exclusive condition building pass.
7125
- *
7126
- * @param entries Parsed entries (may contain OR conditions)
7127
- * @returns Expanded entries with OR branches made exclusive
7128
- */
7129
- function expandOrConditions(entries) {
7130
- const result = [];
7131
- for (const entry of entries) {
7132
- const expanded = expandSingleEntry(entry);
7133
- result.push(...expanded);
7134
- }
7135
- return result;
7084
+ function conditionToCSSInner(node) {
7085
+ if (node.kind === "true") return {
7086
+ variants: [emptyVariant()],
7087
+ isImpossible: false
7088
+ };
7089
+ if (node.kind === "false") return {
7090
+ variants: [],
7091
+ isImpossible: true
7092
+ };
7093
+ if (node.kind === "state") return stateToCSS(node);
7094
+ if (node.kind === "compound") if (node.operator === "AND") return andToCSS(node.children);
7095
+ else return orToCSS(node.children);
7096
+ return {
7097
+ variants: [emptyVariant()],
7098
+ isImpossible: false
7099
+ };
7136
7100
  }
7137
7101
  /**
7138
- * Expand a single entry's OR condition into multiple exclusive entries.
7139
- *
7140
- * Note: branches are NOT sorted by at-rule context here (unlike the
7141
- * `expandExclusiveOrs` pass below). User-authored ORs in state keys aren't
7142
- * the product of De Morgan negation, so each branch is expected to render
7143
- * independently in its own scope and at-rule sort isn't load-bearing.
7144
- * The post-build pass needs the sort because it has to preserve at-rule
7145
- * wrapping across branches that came from negating a compound at-rule.
7102
+ * Convert a state condition to CSS
7146
7103
  */
7147
- function expandSingleEntry(entry) {
7148
- const orBranches = collectOrBranches(entry.condition);
7149
- if (orBranches.length <= 1) return [entry];
7150
- const result = [];
7151
- const priorBranches = [];
7152
- for (let i = 0; i < orBranches.length; i++) {
7153
- const branch = orBranches[i];
7154
- let exclusiveBranch = branch;
7155
- for (const prior of priorBranches) exclusiveBranch = and(exclusiveBranch, not(prior));
7156
- const simplified = simplifyCondition(exclusiveBranch);
7157
- if (simplified.kind === "false") {
7158
- priorBranches.push(branch);
7159
- continue;
7104
+ function stateToCSS(state) {
7105
+ switch (state.type) {
7106
+ case "media": return {
7107
+ variants: mediaToParsed(state).map((mediaCond) => {
7108
+ const v = emptyVariant();
7109
+ v.mediaConditions.push(mediaCond);
7110
+ return v;
7111
+ }),
7112
+ isImpossible: false
7113
+ };
7114
+ case "root": return innerConditionToVariants(state.innerCondition, state.negated ?? false, "rootGroups");
7115
+ case "parent": return parentConditionToVariants(state.innerCondition, state.negated ?? false, state.direct);
7116
+ case "own": return innerConditionToVariants(state.innerCondition, state.negated ?? false, "ownGroups");
7117
+ case "modifier": {
7118
+ const v = emptyVariant();
7119
+ v.modifierConditions.push(modifierToParsed(state));
7120
+ return {
7121
+ variants: [v],
7122
+ isImpossible: false
7123
+ };
7124
+ }
7125
+ case "pseudo": {
7126
+ const v = emptyVariant();
7127
+ v.pseudoConditions.push(pseudoToParsed(state));
7128
+ return {
7129
+ variants: [v],
7130
+ isImpossible: false
7131
+ };
7132
+ }
7133
+ case "container": {
7134
+ const v = emptyVariant();
7135
+ v.containerConditions.push(containerToParsed(state));
7136
+ return {
7137
+ variants: [v],
7138
+ isImpossible: false
7139
+ };
7140
+ }
7141
+ case "supports": {
7142
+ const v = emptyVariant();
7143
+ v.supportsConditions.push(supportsToParsed(state));
7144
+ return {
7145
+ variants: [v],
7146
+ isImpossible: false
7147
+ };
7148
+ }
7149
+ case "starting": {
7150
+ const v = emptyVariant();
7151
+ v.startingStyle = !state.negated;
7152
+ return {
7153
+ variants: [v],
7154
+ isImpossible: false
7155
+ };
7160
7156
  }
7161
- result.push({
7162
- ...entry,
7163
- stateKey: `${entry.stateKey}[${i}]`,
7164
- condition: simplified
7165
- });
7166
- priorBranches.push(branch);
7167
7157
  }
7168
- return result;
7169
7158
  }
7170
7159
  /**
7171
- * Collect top-level OR branches from a condition.
7172
- *
7173
- * For `A | B | C`, returns [A, B, C]
7174
- * For `A & B`, returns [A & B] (single branch)
7175
- * For `A | (B & C)`, returns [A, B & C]
7160
+ * Convert modifier condition to parsed structure
7176
7161
  */
7177
- function collectOrBranches(condition) {
7178
- if (condition.kind === "true" || condition.kind === "false") return [condition];
7179
- if (isCompoundCondition(condition) && condition.operator === "OR") {
7180
- const branches = [];
7181
- for (const child of condition.children) branches.push(...collectOrBranches(child));
7182
- return branches;
7183
- }
7184
- return [condition];
7162
+ function modifierToParsed(state) {
7163
+ return {
7164
+ attribute: state.attribute,
7165
+ value: state.value,
7166
+ operator: state.operator,
7167
+ negated: state.negated ?? false
7168
+ };
7185
7169
  }
7186
7170
  /**
7187
- * Expand OR conditions in exclusive entries AFTER buildExclusiveConditions.
7188
- *
7189
- * This handles ORs that arise from De Morgan expansion during negation:
7190
- * !(A & B) = !A | !B
7191
- *
7192
- * These ORs need to be made exclusive to avoid overlapping CSS rules:
7193
- * !A | !B → !A | (A & !B)
7194
- *
7195
- * This is logically equivalent but ensures each branch has proper context.
7196
- *
7197
- * Example:
7198
- * Input: { "": V1, "@supports(...) & :has()": V2 }
7199
- * V2's exclusive = @supports & :has
7200
- * V1's exclusive = !(@supports & :has) = !@supports | !:has
7201
- *
7202
- * Without this fix: V1 gets two rules:
7203
- * - @supports (not ...) → V1 ✓
7204
- * - :not(:has()) → V1 ✗ (missing @supports context!)
7205
- *
7206
- * With this fix: V1 gets two exclusive rules:
7207
- * - @supports (not ...) → V1 ✓
7208
- * - @supports (...) { :not(:has()) } → V1 ✓ (proper context!)
7171
+ * Convert parsed modifier to CSS selector string (for final output)
7209
7172
  */
7210
- function expandExclusiveOrs(entries) {
7211
- const result = [];
7212
- for (const entry of entries) {
7213
- const expanded = expandExclusiveConditionOrs(entry);
7214
- result.push(...expanded);
7215
- }
7216
- return result;
7173
+ function modifierToCSS(mod) {
7174
+ let selector;
7175
+ if (mod.value !== void 0) {
7176
+ const op = mod.operator || "=";
7177
+ selector = `[${mod.attribute}${op}"${mod.value}"]`;
7178
+ } else selector = `[${mod.attribute}]`;
7179
+ if (mod.negated) return `:not(${selector})`;
7180
+ return selector;
7217
7181
  }
7218
7182
  /**
7219
- * Check if a condition involves at-rules (media, container, supports, starting)
7183
+ * Convert pseudo condition to parsed structure
7220
7184
  */
7221
- function hasAtRuleContext(node) {
7222
- if (node.kind === "true" || node.kind === "false") return false;
7223
- if (node.kind === "state") return node.type === "media" || node.type === "container" || node.type === "supports" || node.type === "starting";
7224
- if (node.kind === "compound") return node.children.some(hasAtRuleContext);
7225
- return false;
7185
+ function pseudoToParsed(state) {
7186
+ return {
7187
+ pseudo: state.pseudo,
7188
+ negated: state.negated ?? false
7189
+ };
7226
7190
  }
7227
7191
  /**
7228
- * Sort OR branches to prioritize at-rule conditions first.
7192
+ * Convert parsed pseudo to CSS selector string (for final output).
7229
7193
  *
7230
- * This is critical for correct CSS generation. For `!A | !B` where A is at-rule
7231
- * and B is modifier, we want:
7232
- * - Branch 0: !A (at-rule negation - covers "no @supports/media" case)
7233
- * - Branch 1: A & !B (modifier negation with at-rule context)
7194
+ * :not() is normalized to negated :is() at parse time, so pseudo.pseudo
7195
+ * never starts with ':not(' here. When negated:
7196
+ * - :is(X) → :not(X) (unwrap :is)
7197
+ * - :where(X) → :not(X) (unwrap :where)
7198
+ * - :has(X) → :not(:has(X))
7199
+ * - other → :not(other)
7234
7200
  *
7235
- * If we process in wrong order (!B first), we'd get:
7236
- * - Branch 0: !B (modifier negation WITHOUT at-rule context - WRONG!)
7237
- * - Branch 1: B & !A (at-rule negation with modifier - incomplete coverage)
7201
+ * When not negated, single-argument :is()/:where() is unwrapped when the
7202
+ * inner content is a simple compound selector that can safely append to
7203
+ * the base selector (this happens after double-negation of :not()).
7238
7204
  */
7239
- function sortOrBranchesForExpansion(branches) {
7240
- return [...branches].sort((a, b) => {
7241
- const aHasAtRule = hasAtRuleContext(a);
7242
- const bHasAtRule = hasAtRuleContext(b);
7243
- if (aHasAtRule && !bHasAtRule) return -1;
7244
- if (!aHasAtRule && bHasAtRule) return 1;
7245
- return 0;
7246
- });
7205
+ function pseudoToCSS(pseudo) {
7206
+ const p = pseudo.pseudo;
7207
+ if (pseudo.negated) {
7208
+ if (p.startsWith(":is(") || p.startsWith(":where(")) return `:not(${p.slice(p.indexOf("(") + 1, -1)})`;
7209
+ return `:not(${p})`;
7210
+ }
7211
+ if ((p.startsWith(":is(") || p.startsWith(":where(")) && !p.includes(",")) {
7212
+ const inner = p.slice(p.indexOf("(") + 1, -1);
7213
+ const ch = inner[0];
7214
+ if ((ch === ":" || ch === "." || ch === "[" || ch === "#") && !/\s/.test(inner)) return inner;
7215
+ }
7216
+ return p;
7247
7217
  }
7248
7218
  /**
7249
- * Expand ORs in a single entry's exclusive condition
7219
+ * Convert media condition to parsed structure(s)
7220
+ * Returns an array because negated ranges produce OR branches (two separate conditions)
7250
7221
  */
7251
- function expandExclusiveConditionOrs(entry) {
7252
- let orBranches = collectOrBranches(entry.exclusiveCondition);
7253
- if (orBranches.length <= 1) return [entry];
7254
- orBranches = sortOrBranchesForExpansion(orBranches);
7255
- const result = [];
7256
- const priorBranches = [];
7257
- for (let i = 0; i < orBranches.length; i++) {
7258
- const branch = orBranches[i];
7259
- let exclusiveBranch = branch;
7260
- for (const prior of priorBranches) exclusiveBranch = and(exclusiveBranch, not(prior));
7261
- const simplified = simplifyCondition(exclusiveBranch);
7262
- if (simplified.kind === "false") {
7263
- priorBranches.push(branch);
7264
- continue;
7265
- }
7266
- result.push({
7267
- ...entry,
7268
- stateKey: `${entry.stateKey}[or:${i}]`,
7269
- exclusiveCondition: simplified
7270
- });
7271
- priorBranches.push(branch);
7272
- }
7273
- return result;
7222
+ function mediaToParsed(state) {
7223
+ if (state.subtype === "type") {
7224
+ const mediaType = state.mediaType || "all";
7225
+ return [{
7226
+ subtype: "type",
7227
+ negated: state.negated ?? false,
7228
+ condition: mediaType,
7229
+ mediaType: state.mediaType
7230
+ }];
7231
+ } else if (state.subtype === "feature") {
7232
+ let condition;
7233
+ if (state.featureValue) condition = `(${state.feature}: ${state.featureValue})`;
7234
+ else condition = `(${state.feature})`;
7235
+ return [{
7236
+ subtype: "feature",
7237
+ negated: state.negated ?? false,
7238
+ condition,
7239
+ feature: state.feature,
7240
+ featureValue: state.featureValue
7241
+ }];
7242
+ } else return dimensionToMediaParsed(state.dimension || "width", state.lowerBound, state.upperBound, state.negated ?? false);
7274
7243
  }
7275
- //#endregion
7276
- //#region src/pipeline/materialize-contradictions.ts
7277
7244
  /**
7278
- * Generic deduplication by a key extraction function.
7279
- * Preserves insertion order, keeping the first occurrence of each key.
7245
+ * Convert dimension bounds to parsed media condition(s)
7246
+ * Uses CSS Media Queries Level 4 `not (condition)` syntax for negation.
7280
7247
  */
7281
- function dedupeByKey(items, getKey) {
7282
- const seen = /* @__PURE__ */ new Set();
7283
- const result = [];
7284
- for (const item of items) {
7285
- const key = getKey(item);
7286
- if (!seen.has(key)) {
7287
- seen.add(key);
7288
- result.push(item);
7289
- }
7290
- }
7291
- return result;
7248
+ function dimensionToMediaParsed(dimension, lowerBound, upperBound, negated) {
7249
+ let condition;
7250
+ if (lowerBound && upperBound) {
7251
+ const lowerOp = lowerBound.inclusive ? "<=" : "<";
7252
+ const upperOp = upperBound.inclusive ? "<=" : "<";
7253
+ condition = `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;
7254
+ } else if (upperBound) condition = `(${dimension} ${upperBound.inclusive ? "<=" : "<"} ${upperBound.value})`;
7255
+ else if (lowerBound) condition = `(${dimension} ${lowerBound.inclusive ? ">=" : ">"} ${lowerBound.value})`;
7256
+ else condition = `(${dimension})`;
7257
+ return [{
7258
+ subtype: "dimension",
7259
+ negated: negated ?? false,
7260
+ condition,
7261
+ dimension,
7262
+ lowerBound,
7263
+ upperBound
7264
+ }];
7292
7265
  }
7293
- function dedupeMediaConditions(conditions) {
7294
- return dedupeByKey(conditions, (c) => `${c.subtype}|${c.condition}|${c.negated}`);
7266
+ /**
7267
+ * Convert container condition to parsed structure
7268
+ * This enables structured analysis for contradiction detection and condition combining
7269
+ */
7270
+ function containerToParsed(state) {
7271
+ let condition;
7272
+ if (state.subtype === "style") if (state.propertyValue) condition = `style(--${state.property}: ${state.propertyValue})`;
7273
+ else condition = `style(--${state.property})`;
7274
+ else if (state.subtype === "raw") condition = state.rawCondition;
7275
+ else condition = dimensionToContainerCondition(state.dimension || "width", state.lowerBound, state.upperBound);
7276
+ return {
7277
+ name: state.containerName,
7278
+ condition,
7279
+ negated: state.negated ?? false,
7280
+ subtype: state.subtype,
7281
+ property: state.property,
7282
+ propertyValue: state.propertyValue
7283
+ };
7295
7284
  }
7296
- function dedupeContainerConditions(conditions) {
7297
- return dedupeByKey(conditions, (c) => `${c.name ?? ""}|${c.condition}|${c.negated}`);
7285
+ /**
7286
+ * Convert dimension bounds to container query condition (single string)
7287
+ * Container queries support "not (condition)", so no need to invert manually
7288
+ */
7289
+ function dimensionToContainerCondition(dimension, lowerBound, upperBound) {
7290
+ if (lowerBound && upperBound) {
7291
+ const lowerOp = lowerBound.inclusive ? "<=" : "<";
7292
+ const upperOp = upperBound.inclusive ? "<=" : "<";
7293
+ return `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;
7294
+ } else if (upperBound) return `(${dimension} ${upperBound.inclusive ? "<=" : "<"} ${upperBound.value})`;
7295
+ else if (lowerBound) return `(${dimension} ${lowerBound.inclusive ? ">=" : ">"} ${lowerBound.value})`;
7296
+ return "(width)";
7298
7297
  }
7299
- function dedupeSupportsConditions(conditions) {
7300
- return dedupeByKey(conditions, (c) => `${c.subtype}|${c.condition}|${c.negated}`);
7298
+ /**
7299
+ * Convert supports condition to parsed structure
7300
+ */
7301
+ function supportsToParsed(state) {
7302
+ return {
7303
+ subtype: state.subtype,
7304
+ condition: state.condition,
7305
+ negated: state.negated ?? false
7306
+ };
7301
7307
  }
7302
7308
  /**
7303
- * Check if supports conditions contain contradictions
7304
- * e.g., @supports(display: grid) AND NOT @supports(display: grid)
7309
+ * Collect all modifier and pseudo conditions from a variant as a flat array.
7305
7310
  */
7306
- function hasSupportsContradiction(conditions) {
7307
- const conditionMap = /* @__PURE__ */ new Map();
7308
- for (const cond of conditions) {
7309
- const key = `${cond.subtype}|${cond.condition}`;
7310
- const existing = conditionMap.get(key);
7311
- if (existing !== void 0 && existing !== !cond.negated) return true;
7312
- conditionMap.set(key, !cond.negated);
7313
- }
7314
- return false;
7311
+ function collectSelectorConditions(variant) {
7312
+ return [...variant.modifierConditions, ...variant.pseudoConditions];
7315
7313
  }
7316
7314
  /**
7317
- * Check if a set of media conditions contains contradictions
7318
- * e.g., (prefers-color-scheme: light) AND NOT (prefers-color-scheme: light)
7319
- * or (width >= 900px) AND (width < 600px)
7315
+ * Convert an inner condition tree into a single SelectorVariant with
7316
+ * one SelectorGroup whose branches represent the inner OR alternatives.
7317
+ * Shared by @root() and @own().
7320
7318
  *
7321
- * Uses parsed media conditions for efficient analysis without regex parsing.
7319
+ * Both positive and negated cases produce one variant with one group.
7320
+ * Negation simply sets the `negated` flag, which swaps :is() for :not()
7321
+ * in the final CSS output — no De Morgan transformation is needed.
7322
+ *
7323
+ * This mirrors parentConditionToVariants: OR branches are kept inside
7324
+ * a single group and rendered as comma-separated arguments in
7325
+ * :is()/:not(), e.g. :root:is([a], [b]) or [el]:not([a], [b]).
7322
7326
  */
7323
- function hasMediaContradiction(conditions) {
7324
- const featureConditions = /* @__PURE__ */ new Map();
7325
- const typeConditions = /* @__PURE__ */ new Map();
7326
- const dimensionConditions = /* @__PURE__ */ new Map();
7327
- const dimensionsByDim = /* @__PURE__ */ new Map();
7328
- for (const cond of conditions) if (cond.subtype === "type") {
7329
- const key = cond.mediaType || "all";
7330
- const existing = typeConditions.get(key);
7331
- if (existing !== void 0 && existing !== !cond.negated) return true;
7332
- typeConditions.set(key, !cond.negated);
7333
- } else if (cond.subtype === "feature") {
7334
- const key = cond.condition;
7335
- const existing = featureConditions.get(key);
7336
- if (existing !== void 0 && existing !== !cond.negated) return true;
7337
- featureConditions.set(key, !cond.negated);
7338
- } else if (cond.subtype === "dimension") {
7339
- const condKey = cond.condition;
7340
- const existing = dimensionConditions.get(condKey);
7341
- if (existing !== void 0 && existing !== !cond.negated) return true;
7342
- dimensionConditions.set(condKey, !cond.negated);
7343
- if (!cond.negated) {
7344
- const dim = cond.dimension || "width";
7345
- let bounds = dimensionsByDim.get(dim);
7346
- if (!bounds) {
7347
- bounds = {
7348
- lowerBound: null,
7349
- upperBound: null
7350
- };
7351
- dimensionsByDim.set(dim, bounds);
7352
- }
7353
- if (cond.lowerBound?.valueNumeric != null) {
7354
- const value = cond.lowerBound.valueNumeric;
7355
- if (bounds.lowerBound === null || value > bounds.lowerBound) bounds.lowerBound = value;
7356
- }
7357
- if (cond.upperBound?.valueNumeric != null) {
7358
- const value = cond.upperBound.valueNumeric;
7359
- if (bounds.upperBound === null || value < bounds.upperBound) bounds.upperBound = value;
7360
- }
7361
- if (bounds.lowerBound !== null && bounds.upperBound !== null && bounds.lowerBound >= bounds.upperBound) return true;
7362
- }
7327
+ function innerConditionToVariants(innerCondition, negated, target) {
7328
+ const innerCSS = conditionToCSS(innerCondition);
7329
+ if (innerCSS.isImpossible || innerCSS.variants.length === 0) return {
7330
+ variants: [],
7331
+ isImpossible: true
7332
+ };
7333
+ const branches = [];
7334
+ for (const innerVariant of innerCSS.variants) {
7335
+ const conditions = collectSelectorConditions(innerVariant);
7336
+ if (conditions.length > 0) branches.push(conditions);
7363
7337
  }
7364
- return false;
7338
+ if (branches.length === 0) return {
7339
+ variants: [emptyVariant()],
7340
+ isImpossible: false
7341
+ };
7342
+ const v = emptyVariant();
7343
+ v[target].push({
7344
+ branches,
7345
+ negated
7346
+ });
7347
+ return {
7348
+ variants: [v],
7349
+ isImpossible: false
7350
+ };
7365
7351
  }
7366
7352
  /**
7367
- * Check if container conditions contain contradictions in style queries
7368
- * e.g., style(--variant: danger) and style(--variant: success) together
7369
- * Same property with different values = always false
7353
+ * Convert a @parent() inner condition into a single SelectorVariant with
7354
+ * one ParentGroup whose branches represent the inner OR alternatives.
7370
7355
  *
7371
- * Uses parsed container conditions for efficient analysis without regex parsing.
7356
+ * Both positive and negated cases produce one variant with one group.
7357
+ * Negation simply sets the `negated` flag, which swaps :is() for :not()
7358
+ * in the final CSS output — no structural transformation is needed.
7372
7359
  */
7373
- function hasContainerStyleContradiction(conditions) {
7374
- const styleQueries = /* @__PURE__ */ new Map();
7375
- for (const cond of conditions) {
7376
- if (cond.subtype !== "style" || !cond.property) continue;
7377
- const property = cond.property;
7378
- const value = cond.propertyValue;
7379
- if (!styleQueries.has(property)) styleQueries.set(property, {
7380
- hasExistence: false,
7381
- values: /* @__PURE__ */ new Set(),
7382
- hasNegatedExistence: false
7383
- });
7384
- const entry = styleQueries.get(property);
7385
- if (cond.negated) {
7386
- if (value === void 0) entry.hasNegatedExistence = true;
7387
- } else if (value === void 0) entry.hasExistence = true;
7388
- else entry.values.add(value);
7389
- }
7390
- for (const [, entry] of styleQueries) {
7391
- if (entry.hasExistence && entry.hasNegatedExistence) return true;
7392
- if (entry.values.size > 1) return true;
7393
- if (entry.hasNegatedExistence && entry.values.size > 0) return true;
7394
- }
7395
- return false;
7396
- }
7397
- //#endregion
7398
- //#region src/pipeline/materialize.ts
7399
- /**
7400
- * CSS Materialization
7401
- *
7402
- * Converts condition trees into CSS selectors and at-rules.
7403
- * This is the final stage that produces actual CSS output.
7404
- */
7405
- const conditionCache = new Lru(3e3);
7406
- /**
7407
- * Convert a condition tree to CSS components
7408
- */
7409
- function conditionToCSS(node) {
7410
- const key = getConditionUniqueId(node);
7411
- const cached = conditionCache.get(key);
7412
- if (cached) return cached;
7413
- const result = conditionToCSSInner(node);
7414
- conditionCache.set(key, result);
7415
- return result;
7416
- }
7417
- function emptyVariant() {
7418
- return {
7419
- modifierConditions: [],
7420
- pseudoConditions: [],
7421
- selectorGroups: [],
7422
- ownGroups: [],
7423
- mediaConditions: [],
7424
- containerConditions: [],
7425
- supportsConditions: [],
7426
- rootGroups: [],
7427
- parentGroups: [],
7428
- startingStyle: false
7360
+ function parentConditionToVariants(innerCondition, negated, direct) {
7361
+ const innerCSS = conditionToCSS(innerCondition);
7362
+ if (innerCSS.isImpossible || innerCSS.variants.length === 0) return {
7363
+ variants: [],
7364
+ isImpossible: true
7429
7365
  };
7430
- }
7431
- function conditionToCSSInner(node) {
7432
- if (node.kind === "true") return {
7366
+ const branches = [];
7367
+ for (const innerVariant of innerCSS.variants) {
7368
+ const conditions = collectSelectorConditions(innerVariant);
7369
+ if (conditions.length > 0) branches.push(conditions);
7370
+ }
7371
+ if (branches.length === 0) return {
7433
7372
  variants: [emptyVariant()],
7434
7373
  isImpossible: false
7435
7374
  };
7436
- if (node.kind === "false") return {
7437
- variants: [],
7438
- isImpossible: true
7439
- };
7440
- if (node.kind === "state") return stateToCSS(node);
7441
- if (node.kind === "compound") if (node.operator === "AND") return andToCSS(node.children);
7442
- else return orToCSS(node.children);
7375
+ const v = emptyVariant();
7376
+ v.parentGroups.push({
7377
+ branches,
7378
+ direct,
7379
+ negated
7380
+ });
7443
7381
  return {
7444
- variants: [emptyVariant()],
7382
+ variants: [v],
7445
7383
  isImpossible: false
7446
7384
  };
7447
7385
  }
7448
7386
  /**
7449
- * Convert a state condition to CSS
7387
+ * Sort key for canonical condition output within selectors.
7388
+ *
7389
+ * Priority order:
7390
+ * 0: Boolean attribute selectors ([data-hovered])
7391
+ * 1: Value attribute selectors ([data-size="small"])
7392
+ * 2: Negated boolean attributes (:not([data-disabled]))
7393
+ * 3: Negated value attributes (:not([data-size="small"]))
7394
+ * 4: Pseudo-classes (:hover, :focus)
7395
+ * 5: Negated pseudo-classes (:not(:disabled))
7396
+ *
7397
+ * Secondary sort: alphabetical by attribute name / pseudo string.
7450
7398
  */
7451
- function stateToCSS(state) {
7452
- switch (state.type) {
7453
- case "media": return {
7454
- variants: mediaToParsed(state).map((mediaCond) => {
7455
- const v = emptyVariant();
7456
- v.mediaConditions.push(mediaCond);
7457
- return v;
7458
- }),
7459
- isImpossible: false
7460
- };
7461
- case "root": return innerConditionToVariants(state.innerCondition, state.negated ?? false, "rootGroups");
7462
- case "parent": return parentConditionToVariants(state.innerCondition, state.negated ?? false, state.direct);
7463
- case "own": return innerConditionToVariants(state.innerCondition, state.negated ?? false, "ownGroups");
7464
- case "modifier": {
7465
- const v = emptyVariant();
7466
- v.modifierConditions.push(modifierToParsed(state));
7467
- return {
7468
- variants: [v],
7469
- isImpossible: false
7470
- };
7471
- }
7472
- case "pseudo": {
7473
- const v = emptyVariant();
7474
- v.pseudoConditions.push(pseudoToParsed(state));
7475
- return {
7476
- variants: [v],
7477
- isImpossible: false
7478
- };
7479
- }
7480
- case "container": {
7481
- const v = emptyVariant();
7482
- v.containerConditions.push(containerToParsed(state));
7483
- return {
7484
- variants: [v],
7485
- isImpossible: false
7486
- };
7487
- }
7488
- case "supports": {
7489
- const v = emptyVariant();
7490
- v.supportsConditions.push(supportsToParsed(state));
7491
- return {
7492
- variants: [v],
7493
- isImpossible: false
7494
- };
7495
- }
7496
- case "starting": {
7497
- const v = emptyVariant();
7498
- v.startingStyle = !state.negated;
7499
- return {
7500
- variants: [v],
7501
- isImpossible: false
7502
- };
7503
- }
7399
+ function conditionSortKey(cond) {
7400
+ if ("attribute" in cond) {
7401
+ const hasValue = cond.value !== void 0 ? 1 : 0;
7402
+ return `${(cond.negated ? 2 : 0) + hasValue}|${cond.attribute}|${cond.value ?? ""}`;
7504
7403
  }
7404
+ return `${cond.negated ? 5 : 4}|${cond.pseudo}`;
7405
+ }
7406
+ function sortConditions(conditions) {
7407
+ return conditions.toSorted((a, b) => conditionSortKey(a).localeCompare(conditionSortKey(b)));
7408
+ }
7409
+ function branchToCSS(branch) {
7410
+ let parts = "";
7411
+ for (const cond of sortConditions(branch)) parts += selectorConditionToCSS(cond);
7412
+ return parts;
7505
7413
  }
7506
7414
  /**
7507
- * Convert modifier condition to parsed structure
7415
+ * Wrap serialized selector arguments in :is() or :not().
7416
+ * Arguments are sorted for canonical output.
7508
7417
  */
7509
- function modifierToParsed(state) {
7510
- return {
7511
- attribute: state.attribute,
7512
- value: state.value,
7513
- operator: state.operator,
7514
- negated: state.negated ?? false
7515
- };
7418
+ function wrapInIsOrNot(args, negated) {
7419
+ return `${negated ? ":not" : ":is"}(${args.sort().join(", ")})`;
7516
7420
  }
7517
7421
  /**
7518
- * Convert parsed modifier to CSS selector string (for final output)
7422
+ * Convert a selector group to a CSS selector fragment.
7423
+ *
7424
+ * Single-branch groups are unwrapped (no :is() wrapper).
7425
+ * Multi-branch groups use :is() or :not().
7426
+ * Negation swaps :is() for :not().
7519
7427
  */
7520
- function modifierToCSS(mod) {
7521
- let selector;
7522
- if (mod.value !== void 0) {
7523
- const op = mod.operator || "=";
7524
- selector = `[${mod.attribute}${op}"${mod.value}"]`;
7525
- } else selector = `[${mod.attribute}]`;
7526
- if (mod.negated) return `:not(${selector})`;
7527
- return selector;
7428
+ function selectorGroupToCSS(group) {
7429
+ if (group.branches.length === 0) return "";
7430
+ if (group.branches.length === 1) {
7431
+ const parts = branchToCSS(group.branches[0]);
7432
+ if (group.negated) return `:not(${parts})`;
7433
+ return parts;
7434
+ }
7435
+ return wrapInIsOrNot(group.branches.map(branchToCSS), group.negated);
7528
7436
  }
7529
7437
  /**
7530
- * Convert pseudo condition to parsed structure
7438
+ * Collect facts about modifier conditions for subsumption analysis.
7439
+ * Tracks negated boolean attrs (:not([attr])) and positive exact values ([attr="X"]).
7531
7440
  */
7532
- function pseudoToParsed(state) {
7441
+ function collectSubsumptionFacts(modifiers) {
7442
+ const negatedBooleanAttrs = /* @__PURE__ */ new Set();
7443
+ const positiveExactValuesByAttr = /* @__PURE__ */ new Map();
7444
+ for (const mod of modifiers) {
7445
+ if (mod.negated && mod.value === void 0) negatedBooleanAttrs.add(mod.attribute);
7446
+ if (!mod.negated && mod.value !== void 0 && (mod.operator ?? "=") === "=") {
7447
+ let vals = positiveExactValuesByAttr.get(mod.attribute);
7448
+ if (!vals) {
7449
+ vals = /* @__PURE__ */ new Set();
7450
+ positiveExactValuesByAttr.set(mod.attribute, vals);
7451
+ }
7452
+ vals.add(mod.value);
7453
+ }
7454
+ }
7533
7455
  return {
7534
- pseudo: state.pseudo,
7535
- negated: state.negated ?? false
7456
+ negatedBooleanAttrs,
7457
+ positiveExactValuesByAttr
7536
7458
  };
7537
7459
  }
7538
7460
  /**
7539
- * Convert parsed pseudo to CSS selector string (for final output).
7540
- *
7541
- * :not() is normalized to negated :is() at parse time, so pseudo.pseudo
7542
- * never starts with ':not(' here. When negated:
7543
- * - :is(X) → :not(X) (unwrap :is)
7544
- * - :where(X) → :not(X) (unwrap :where)
7545
- * - :has(X) → :not(:has(X))
7546
- * - other → :not(other)
7461
+ * Check if a negated-value modifier is subsumed by stronger facts:
7462
+ * - :not([attr]) subsumes :not([attr="val"])
7463
+ * - [attr="X"] implies :not([attr="Y"]) is redundant (single exact value)
7547
7464
  *
7548
- * When not negated, single-argument :is()/:where() is unwrapped when the
7549
- * inner content is a simple compound selector that can safely append to
7550
- * the base selector (this happens after double-negation of :not()).
7465
+ * Only applies to exact-match (=) operators; substring operators don't
7466
+ * imply exclusivity between values.
7551
7467
  */
7552
- function pseudoToCSS(pseudo) {
7553
- const p = pseudo.pseudo;
7554
- if (pseudo.negated) {
7555
- if (p.startsWith(":is(") || p.startsWith(":where(")) return `:not(${p.slice(p.indexOf("(") + 1, -1)})`;
7556
- return `:not(${p})`;
7557
- }
7558
- if ((p.startsWith(":is(") || p.startsWith(":where(")) && !p.includes(",")) {
7559
- const inner = p.slice(p.indexOf("(") + 1, -1);
7560
- const ch = inner[0];
7561
- if ((ch === ":" || ch === "." || ch === "[" || ch === "#") && !/\s/.test(inner)) return inner;
7468
+ function isSubsumedNegatedModifier(mod, facts) {
7469
+ if (!mod.negated || mod.value === void 0) return false;
7470
+ if (facts.negatedBooleanAttrs.has(mod.attribute)) return true;
7471
+ if ((mod.operator ?? "=") === "=") {
7472
+ const posVals = facts.positiveExactValuesByAttr.get(mod.attribute);
7473
+ if (posVals && posVals.size === 1 && !posVals.has(mod.value)) return true;
7562
7474
  }
7563
- return p;
7475
+ return false;
7564
7476
  }
7565
7477
  /**
7566
- * Convert media condition to parsed structure(s)
7567
- * Returns an array because negated ranges produce OR branches (two separate conditions)
7568
- */
7569
- function mediaToParsed(state) {
7570
- if (state.subtype === "type") {
7571
- const mediaType = state.mediaType || "all";
7572
- return [{
7573
- subtype: "type",
7574
- negated: state.negated ?? false,
7575
- condition: mediaType,
7576
- mediaType: state.mediaType
7577
- }];
7578
- } else if (state.subtype === "feature") {
7579
- let condition;
7580
- if (state.featureValue) condition = `(${state.feature}: ${state.featureValue})`;
7581
- else condition = `(${state.feature})`;
7582
- return [{
7583
- subtype: "feature",
7584
- negated: state.negated ?? false,
7585
- condition,
7586
- feature: state.feature,
7587
- featureValue: state.featureValue
7588
- }];
7589
- } else return dimensionToMediaParsed(state.dimension || "width", state.lowerBound, state.upperBound, state.negated ?? false);
7590
- }
7591
- /**
7592
- * Convert dimension bounds to parsed media condition(s)
7593
- * Uses CSS Media Queries Level 4 `not (condition)` syntax for negation.
7594
- */
7595
- function dimensionToMediaParsed(dimension, lowerBound, upperBound, negated) {
7596
- let condition;
7597
- if (lowerBound && upperBound) {
7598
- const lowerOp = lowerBound.inclusive ? "<=" : "<";
7599
- const upperOp = upperBound.inclusive ? "<=" : "<";
7600
- condition = `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;
7601
- } else if (upperBound) condition = `(${dimension} ${upperBound.inclusive ? "<=" : "<"} ${upperBound.value})`;
7602
- else if (lowerBound) condition = `(${dimension} ${lowerBound.inclusive ? ">=" : ">"} ${lowerBound.value})`;
7603
- else condition = `(${dimension})`;
7604
- return [{
7605
- subtype: "dimension",
7606
- negated: negated ?? false,
7607
- condition,
7608
- dimension,
7609
- lowerBound,
7610
- upperBound
7611
- }];
7612
- }
7613
- /**
7614
- * Convert container condition to parsed structure
7615
- * This enables structured analysis for contradiction detection and condition combining
7616
- */
7617
- function containerToParsed(state) {
7618
- let condition;
7619
- if (state.subtype === "style") if (state.propertyValue) condition = `style(--${state.property}: ${state.propertyValue})`;
7620
- else condition = `style(--${state.property})`;
7621
- else if (state.subtype === "raw") condition = state.rawCondition;
7622
- else condition = dimensionToContainerCondition(state.dimension || "width", state.lowerBound, state.upperBound);
7623
- return {
7624
- name: state.containerName,
7625
- condition,
7626
- negated: state.negated ?? false,
7627
- subtype: state.subtype,
7628
- property: state.property,
7629
- propertyValue: state.propertyValue
7630
- };
7631
- }
7632
- /**
7633
- * Convert dimension bounds to container query condition (single string)
7634
- * Container queries support "not (condition)", so no need to invert manually
7635
- */
7636
- function dimensionToContainerCondition(dimension, lowerBound, upperBound) {
7637
- if (lowerBound && upperBound) {
7638
- const lowerOp = lowerBound.inclusive ? "<=" : "<";
7639
- const upperOp = upperBound.inclusive ? "<=" : "<";
7640
- return `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;
7641
- } else if (upperBound) return `(${dimension} ${upperBound.inclusive ? "<=" : "<"} ${upperBound.value})`;
7642
- else if (lowerBound) return `(${dimension} ${lowerBound.inclusive ? ">=" : ">"} ${lowerBound.value})`;
7643
- return "(width)";
7644
- }
7645
- /**
7646
- * Convert supports condition to parsed structure
7647
- */
7648
- function supportsToParsed(state) {
7649
- return {
7650
- subtype: state.subtype,
7651
- condition: state.condition,
7652
- negated: state.negated ?? false
7653
- };
7654
- }
7655
- /**
7656
- * Collect all modifier and pseudo conditions from a variant as a flat array.
7657
- */
7658
- function collectSelectorConditions(variant) {
7659
- return [...variant.modifierConditions, ...variant.pseudoConditions];
7660
- }
7661
- /**
7662
- * Convert an inner condition tree into a single SelectorVariant with
7663
- * one SelectorGroup whose branches represent the inner OR alternatives.
7664
- * Shared by @root() and @own().
7665
- *
7666
- * Both positive and negated cases produce one variant with one group.
7667
- * Negation simply sets the `negated` flag, which swaps :is() for :not()
7668
- * in the final CSS output — no De Morgan transformation is needed.
7669
- *
7670
- * This mirrors parentConditionToVariants: OR branches are kept inside
7671
- * a single group and rendered as comma-separated arguments in
7672
- * :is()/:not(), e.g. :root:is([a], [b]) or [el]:not([a], [b]).
7673
- */
7674
- function innerConditionToVariants(innerCondition, negated, target) {
7675
- const innerCSS = conditionToCSS(innerCondition);
7676
- if (innerCSS.isImpossible || innerCSS.variants.length === 0) return {
7677
- variants: [],
7678
- isImpossible: true
7679
- };
7680
- const branches = [];
7681
- for (const innerVariant of innerCSS.variants) {
7682
- const conditions = collectSelectorConditions(innerVariant);
7683
- if (conditions.length > 0) branches.push(conditions);
7684
- }
7685
- if (branches.length === 0) return {
7686
- variants: [emptyVariant()],
7687
- isImpossible: false
7688
- };
7689
- const v = emptyVariant();
7690
- v[target].push({
7691
- branches,
7692
- negated
7693
- });
7694
- return {
7695
- variants: [v],
7696
- isImpossible: false
7697
- };
7698
- }
7699
- /**
7700
- * Convert a @parent() inner condition into a single SelectorVariant with
7701
- * one ParentGroup whose branches represent the inner OR alternatives.
7702
- *
7703
- * Both positive and negated cases produce one variant with one group.
7704
- * Negation simply sets the `negated` flag, which swaps :is() for :not()
7705
- * in the final CSS output — no structural transformation is needed.
7706
- */
7707
- function parentConditionToVariants(innerCondition, negated, direct) {
7708
- const innerCSS = conditionToCSS(innerCondition);
7709
- if (innerCSS.isImpossible || innerCSS.variants.length === 0) return {
7710
- variants: [],
7711
- isImpossible: true
7712
- };
7713
- const branches = [];
7714
- for (const innerVariant of innerCSS.variants) {
7715
- const conditions = collectSelectorConditions(innerVariant);
7716
- if (conditions.length > 0) branches.push(conditions);
7717
- }
7718
- if (branches.length === 0) return {
7719
- variants: [emptyVariant()],
7720
- isImpossible: false
7721
- };
7722
- const v = emptyVariant();
7723
- v.parentGroups.push({
7724
- branches,
7725
- direct,
7726
- negated
7727
- });
7728
- return {
7729
- variants: [v],
7730
- isImpossible: false
7731
- };
7732
- }
7733
- /**
7734
- * Sort key for canonical condition output within selectors.
7735
- *
7736
- * Priority order:
7737
- * 0: Boolean attribute selectors ([data-hovered])
7738
- * 1: Value attribute selectors ([data-size="small"])
7739
- * 2: Negated boolean attributes (:not([data-disabled]))
7740
- * 3: Negated value attributes (:not([data-size="small"]))
7741
- * 4: Pseudo-classes (:hover, :focus)
7742
- * 5: Negated pseudo-classes (:not(:disabled))
7743
- *
7744
- * Secondary sort: alphabetical by attribute name / pseudo string.
7745
- */
7746
- function conditionSortKey(cond) {
7747
- if ("attribute" in cond) {
7748
- const hasValue = cond.value !== void 0 ? 1 : 0;
7749
- return `${(cond.negated ? 2 : 0) + hasValue}|${cond.attribute}|${cond.value ?? ""}`;
7750
- }
7751
- return `${cond.negated ? 5 : 4}|${cond.pseudo}`;
7752
- }
7753
- function sortConditions(conditions) {
7754
- return conditions.toSorted((a, b) => conditionSortKey(a).localeCompare(conditionSortKey(b)));
7755
- }
7756
- function branchToCSS(branch) {
7757
- let parts = "";
7758
- for (const cond of sortConditions(branch)) parts += selectorConditionToCSS(cond);
7759
- return parts;
7760
- }
7761
- /**
7762
- * Wrap serialized selector arguments in :is() or :not().
7763
- * Arguments are sorted for canonical output.
7764
- */
7765
- function wrapInIsOrNot(args, negated) {
7766
- return `${negated ? ":not" : ":is"}(${args.sort().join(", ")})`;
7767
- }
7768
- /**
7769
- * Convert a selector group to a CSS selector fragment.
7770
- *
7771
- * Single-branch groups are unwrapped (no :is() wrapper).
7772
- * Multi-branch groups use :is() or :not().
7773
- * Negation swaps :is() for :not().
7774
- */
7775
- function selectorGroupToCSS(group) {
7776
- if (group.branches.length === 0) return "";
7777
- if (group.branches.length === 1) {
7778
- const parts = branchToCSS(group.branches[0]);
7779
- if (group.negated) return `:not(${parts})`;
7780
- return parts;
7781
- }
7782
- return wrapInIsOrNot(group.branches.map(branchToCSS), group.negated);
7783
- }
7784
- /**
7785
- * Collect facts about modifier conditions for subsumption analysis.
7786
- * Tracks negated boolean attrs (:not([attr])) and positive exact values ([attr="X"]).
7787
- */
7788
- function collectSubsumptionFacts(modifiers) {
7789
- const negatedBooleanAttrs = /* @__PURE__ */ new Set();
7790
- const positiveExactValuesByAttr = /* @__PURE__ */ new Map();
7791
- for (const mod of modifiers) {
7792
- if (mod.negated && mod.value === void 0) negatedBooleanAttrs.add(mod.attribute);
7793
- if (!mod.negated && mod.value !== void 0 && (mod.operator ?? "=") === "=") {
7794
- let vals = positiveExactValuesByAttr.get(mod.attribute);
7795
- if (!vals) {
7796
- vals = /* @__PURE__ */ new Set();
7797
- positiveExactValuesByAttr.set(mod.attribute, vals);
7798
- }
7799
- vals.add(mod.value);
7800
- }
7801
- }
7802
- return {
7803
- negatedBooleanAttrs,
7804
- positiveExactValuesByAttr
7805
- };
7806
- }
7807
- /**
7808
- * Check if a negated-value modifier is subsumed by stronger facts:
7809
- * - :not([attr]) subsumes :not([attr="val"])
7810
- * - [attr="X"] implies :not([attr="Y"]) is redundant (single exact value)
7811
- *
7812
- * Only applies to exact-match (=) operators; substring operators don't
7813
- * imply exclusivity between values.
7814
- */
7815
- function isSubsumedNegatedModifier(mod, facts) {
7816
- if (!mod.negated || mod.value === void 0) return false;
7817
- if (facts.negatedBooleanAttrs.has(mod.attribute)) return true;
7818
- if ((mod.operator ?? "=") === "=") {
7819
- const posVals = facts.positiveExactValuesByAttr.get(mod.attribute);
7820
- if (posVals && posVals.size === 1 && !posVals.has(mod.value)) return true;
7821
- }
7822
- return false;
7823
- }
7824
- /**
7825
- * Remove redundant single-condition groups that are subsumed by stronger
7826
- * groups on the same attribute. O(n) — only inspects single-branch,
7827
- * single-condition groups.
7478
+ * Remove redundant single-condition groups that are subsumed by stronger
7479
+ * groups on the same attribute. O(n) — only inspects single-branch,
7480
+ * single-condition groups.
7828
7481
  */
7829
7482
  function optimizeGroups(groups) {
7830
7483
  if (groups.length <= 1) return groups;
@@ -8148,330 +7801,764 @@ function getParentGroupKey(g) {
8148
7801
  return `${g.negated ? "!" : ""}${g.direct ? ">" : ""}(${getBranchesKey(g.branches)})`;
8149
7802
  }
8150
7803
  /**
8151
- * Deduplicate variants
7804
+ * Deduplicate variants
7805
+ *
7806
+ * Removes:
7807
+ * 1. Exact duplicates (same key)
7808
+ * 2. Superset variants (more restrictive selectors that are redundant)
7809
+ */
7810
+ function dedupeVariants(variants) {
7811
+ if (variants.length <= 1) return variants;
7812
+ const seen = /* @__PURE__ */ new Set();
7813
+ const result = [];
7814
+ for (const v of variants) {
7815
+ const key = getVariantKey(v);
7816
+ if (!seen.has(key)) {
7817
+ seen.add(key);
7818
+ result.push(v);
7819
+ }
7820
+ }
7821
+ if (result.length <= 1) return result;
7822
+ result.sort((a, b) => variantConditionCount(a) - variantConditionCount(b));
7823
+ const filtered = [];
7824
+ for (const candidate of result) {
7825
+ let isRedundant = false;
7826
+ for (const kept of filtered) if (isVariantSuperset(candidate, kept)) {
7827
+ isRedundant = true;
7828
+ break;
7829
+ }
7830
+ if (!isRedundant) filtered.push(candidate);
7831
+ }
7832
+ return filtered;
7833
+ }
7834
+ /**
7835
+ * Combine AND conditions into CSS
7836
+ *
7837
+ * AND of conditions means cartesian product of variants:
7838
+ * (A1 | A2) & (B1 | B2) = A1&B1 | A1&B2 | A2&B1 | A2&B2
7839
+ *
7840
+ * Variants that result in contradictions (e.g., conflicting media rules)
7841
+ * are filtered out.
7842
+ */
7843
+ function andToCSS(children) {
7844
+ const exclusiveChildren = makeOrBranchesExclusive(children);
7845
+ let currentVariants = [emptyVariant()];
7846
+ for (const child of exclusiveChildren) {
7847
+ const childCSS = conditionToCSSInner(child);
7848
+ if (childCSS.isImpossible || childCSS.variants.length === 0) return {
7849
+ variants: [],
7850
+ isImpossible: true
7851
+ };
7852
+ const newVariants = [];
7853
+ for (const current of currentVariants) for (const childVariant of childCSS.variants) {
7854
+ const merged = mergeVariants(current, childVariant);
7855
+ if (merged !== null) newVariants.push(merged);
7856
+ }
7857
+ if (newVariants.length === 0) return {
7858
+ variants: [],
7859
+ isImpossible: true
7860
+ };
7861
+ currentVariants = dedupeVariants(newVariants);
7862
+ }
7863
+ return {
7864
+ variants: currentVariants,
7865
+ isImpossible: false
7866
+ };
7867
+ }
7868
+ /**
7869
+ * Make OR branches within AND children mutually exclusive.
7870
+ *
7871
+ * For an AND child that is OR(A, B), transforms it to OR(A, B & !A)
7872
+ * so that when andToCSS does a Cartesian product, the resulting
7873
+ * CSS variants don't overlap.
7874
+ *
7875
+ * Only transforms OR children whose branches actually produce
7876
+ * different at-rule contexts when materialized. This avoids
7877
+ * breaking cases where contradiction detection in the Cartesian
7878
+ * product naturally handles deduplication.
7879
+ */
7880
+ function makeOrBranchesExclusive(children) {
7881
+ return children.map((child) => {
7882
+ if (!isCompoundCondition(child) || child.operator !== "OR") return child;
7883
+ if (child.children.length <= 1) return child;
7884
+ if (!branchesProduceDifferentContexts(child.children)) return child;
7885
+ const exclusiveBranches = [];
7886
+ const priorBranches = [];
7887
+ for (const branch of child.children) {
7888
+ if (priorBranches.length === 0) exclusiveBranches.push(branch);
7889
+ else {
7890
+ let exclusive = branch;
7891
+ for (const prior of priorBranches) exclusive = and(exclusive, not(prior));
7892
+ const simplified = simplifyCondition(exclusive);
7893
+ if (simplified.kind !== "false") exclusiveBranches.push(simplified);
7894
+ }
7895
+ priorBranches.push(branch);
7896
+ }
7897
+ if (exclusiveBranches.length === 0) return child;
7898
+ if (exclusiveBranches.length === 1) return exclusiveBranches[0];
7899
+ return {
7900
+ kind: "compound",
7901
+ operator: "OR",
7902
+ children: exclusiveBranches
7903
+ };
7904
+ });
7905
+ }
7906
+ /**
7907
+ * Check if OR branches produce different at-rule contexts when
7908
+ * materialized. If so, the Cartesian product in andToCSS will
7909
+ * create overlapping CSS variants that need exclusive expansion.
7910
+ *
7911
+ * Exported so Stage 2a (`expandOrConditions` in `exclusive.ts`) can
7912
+ * reuse the same heuristic and skip OR expansion when every branch
7913
+ * lives in the same at-rule/root/parent/own context — pure-selector
7914
+ * ORs are better collapsed into `:is(...)` at materialization time
7915
+ * than expanded into mutually-exclusive `A | (B & !A) | …` cascades.
7916
+ */
7917
+ function branchesProduceDifferentContexts(branches) {
7918
+ const contextKeys = /* @__PURE__ */ new Set();
7919
+ for (const branch of branches) {
7920
+ const css = conditionToCSSInner(branch);
7921
+ if (css.isImpossible) continue;
7922
+ for (const v of css.variants) contextKeys.add(getVariantContextKey(v));
7923
+ }
7924
+ return contextKeys.size > 1;
7925
+ }
7926
+ /**
7927
+ * Combine OR conditions into CSS
7928
+ *
7929
+ * OR in CSS means multiple selector variants (DNF).
7930
+ * After deduplication, variants that differ only in their base
7931
+ * modifier/pseudo conditions are merged into :is() groups.
7932
+ *
7933
+ * Note: OR exclusivity is handled at the pipeline level (expandOrConditions),
7934
+ * so here we just collect all variants. Any remaining ORs in the condition
7935
+ * tree (e.g., from De Morgan expansion) are handled as simple alternatives.
7936
+ */
7937
+ function orToCSS(children) {
7938
+ const allVariants = [];
7939
+ for (const child of children) {
7940
+ const childCSS = conditionToCSSInner(child);
7941
+ if (childCSS.isImpossible) continue;
7942
+ allVariants.push(...childCSS.variants);
7943
+ }
7944
+ if (allVariants.length === 0) return {
7945
+ variants: [],
7946
+ isImpossible: true
7947
+ };
7948
+ return {
7949
+ variants: dedupeVariants(allVariants),
7950
+ isImpossible: false
7951
+ };
7952
+ }
7953
+ /**
7954
+ * Find keys present in ALL condition arrays.
7955
+ */
7956
+ function findCommonKeys(conditionSets, getKey) {
7957
+ if (conditionSets.length === 0) return /* @__PURE__ */ new Set();
7958
+ const common = new Set(conditionSets[0].map(getKey));
7959
+ for (let i = 1; i < conditionSets.length; i++) {
7960
+ const keys = new Set(conditionSets[i].map(getKey));
7961
+ for (const key of common) if (!keys.has(key)) common.delete(key);
7962
+ }
7963
+ return common;
7964
+ }
7965
+ /**
7966
+ * Merge OR variants that share the same "context" (at-rules, root, parent,
7967
+ * own, starting) into a single variant with a SelectorGroup.
7968
+ *
7969
+ * Variants with no modifier/pseudo conditions are kept separate (they match
7970
+ * unconditionally and can't be expressed inside :is()).
7971
+ */
7972
+ function mergeVariantsIntoSelectorGroups(variants) {
7973
+ if (variants.length <= 1) return variants;
7974
+ const groups = /* @__PURE__ */ new Map();
7975
+ for (const v of variants) {
7976
+ const key = getVariantContextKey(v);
7977
+ const group = groups.get(key);
7978
+ if (group) group.push(v);
7979
+ else groups.set(key, [v]);
7980
+ }
7981
+ const result = [];
7982
+ for (const group of groups.values()) {
7983
+ if (group.length === 1) {
7984
+ result.push(group[0]);
7985
+ continue;
7986
+ }
7987
+ const withSelectors = [];
7988
+ const withoutSelectors = [];
7989
+ for (const v of group) if (v.modifierConditions.length === 0 && v.pseudoConditions.length === 0) withoutSelectors.push(v);
7990
+ else withSelectors.push(v);
7991
+ result.push(...withoutSelectors);
7992
+ if (withSelectors.length <= 1) {
7993
+ result.push(...withSelectors);
7994
+ continue;
7995
+ }
7996
+ result.push(factorAndGroup(withSelectors));
7997
+ }
7998
+ return result;
7999
+ }
8000
+ /**
8001
+ * Factor common modifier/pseudo conditions out of variants and create
8002
+ * a single variant with a SelectorGroup for the remaining (differing)
8003
+ * conditions.
8004
+ *
8005
+ * Precondition: all variants must share the same context key (identical
8006
+ * at-rules, root/parent/own/selector groups, startingStyle).
8007
+ */
8008
+ function factorAndGroup(variants) {
8009
+ {
8010
+ const key0 = getVariantContextKey(variants[0]);
8011
+ for (let i = 1; i < variants.length; i++) {
8012
+ const keyI = getVariantContextKey(variants[i]);
8013
+ if (keyI !== key0) throw new Error(`factorAndGroup: context key mismatch at index ${i}.\n expected: ${key0}\n got: ${keyI}`);
8014
+ }
8015
+ }
8016
+ const commonModKeys = findCommonKeys(variants.map((v) => v.modifierConditions), getModifierKey);
8017
+ const commonPseudoKeys = findCommonKeys(variants.map((v) => v.pseudoConditions), getPseudoKey);
8018
+ const commonModifiers = variants[0].modifierConditions.filter((m) => commonModKeys.has(getModifierKey(m)));
8019
+ const commonPseudos = variants[0].pseudoConditions.filter((p) => commonPseudoKeys.has(getPseudoKey(p)));
8020
+ const branches = [];
8021
+ let hasEmptyBranch = false;
8022
+ for (const v of variants) {
8023
+ const branch = [];
8024
+ for (const mod of v.modifierConditions) if (!commonModKeys.has(getModifierKey(mod))) branch.push(mod);
8025
+ for (const pseudo of v.pseudoConditions) if (!commonPseudoKeys.has(getPseudoKey(pseudo))) branch.push(pseudo);
8026
+ if (branch.length > 0) branches.push(branch);
8027
+ else hasEmptyBranch = true;
8028
+ }
8029
+ if (hasEmptyBranch) return {
8030
+ ...variants[0],
8031
+ modifierConditions: commonModifiers,
8032
+ pseudoConditions: commonPseudos
8033
+ };
8034
+ const factoredGroups = tryFactorIntoDimensions(branches);
8035
+ if (factoredGroups) return {
8036
+ modifierConditions: commonModifiers,
8037
+ pseudoConditions: commonPseudos,
8038
+ selectorGroups: [...variants[0].selectorGroups, ...factoredGroups],
8039
+ ownGroups: [...variants[0].ownGroups],
8040
+ mediaConditions: [...variants[0].mediaConditions],
8041
+ containerConditions: [...variants[0].containerConditions],
8042
+ supportsConditions: [...variants[0].supportsConditions],
8043
+ rootGroups: [...variants[0].rootGroups],
8044
+ parentGroups: [...variants[0].parentGroups],
8045
+ startingStyle: variants[0].startingStyle
8046
+ };
8047
+ return {
8048
+ modifierConditions: commonModifiers,
8049
+ pseudoConditions: commonPseudos,
8050
+ selectorGroups: [...variants[0].selectorGroups, {
8051
+ branches,
8052
+ negated: false
8053
+ }],
8054
+ ownGroups: [...variants[0].ownGroups],
8055
+ mediaConditions: [...variants[0].mediaConditions],
8056
+ containerConditions: [...variants[0].containerConditions],
8057
+ supportsConditions: [...variants[0].supportsConditions],
8058
+ rootGroups: [...variants[0].rootGroups],
8059
+ parentGroups: [...variants[0].parentGroups],
8060
+ startingStyle: variants[0].startingStyle
8061
+ };
8062
+ }
8063
+ /**
8064
+ * Detect when branches form a complete Cartesian product of independent
8065
+ * modifier attribute dimensions and return one SelectorGroup per dimension.
8066
+ *
8067
+ * Example: 4 branches for 2 attributes × 2 values each →
8068
+ * :is(A1, A2):is(B1, B2) instead of :is(A1B1, A1B2, A2B1, A2B2)
8069
+ */
8070
+ function tryFactorIntoDimensions(branches) {
8071
+ if (branches.length < 4) return null;
8072
+ const dimensions = /* @__PURE__ */ new Map();
8073
+ for (const branch of branches) for (const cond of branch) {
8074
+ if (!("attribute" in cond)) return null;
8075
+ if (!dimensions.has(cond.attribute)) dimensions.set(cond.attribute, /* @__PURE__ */ new Map());
8076
+ dimensions.get(cond.attribute).set(getModifierKey(cond), cond);
8077
+ }
8078
+ if (dimensions.size < 2) return null;
8079
+ for (const branch of branches) {
8080
+ const seen = /* @__PURE__ */ new Set();
8081
+ for (const cond of branch) {
8082
+ const attr = cond.attribute;
8083
+ if (seen.has(attr)) return null;
8084
+ seen.add(attr);
8085
+ }
8086
+ if (seen.size !== dimensions.size) return null;
8087
+ }
8088
+ let expectedCount = 1;
8089
+ for (const vals of dimensions.values()) expectedCount *= vals.size;
8090
+ if (branches.length !== expectedCount) return null;
8091
+ return [...dimensions.values()].map((vals) => ({
8092
+ branches: [...vals.values()].map((cond) => [cond]),
8093
+ negated: false
8094
+ }));
8095
+ }
8096
+ /**
8097
+ * Build at-rules array from a variant
8098
+ */
8099
+ function buildAtRulesFromVariant(variant) {
8100
+ const atRules = [];
8101
+ if (variant.mediaConditions.length > 0) {
8102
+ const conditionParts = variant.mediaConditions.map((c) => {
8103
+ if (c.subtype === "type") return c.negated ? `not ${c.condition}` : c.condition;
8104
+ else return c.negated ? `(not ${c.condition})` : c.condition;
8105
+ });
8106
+ atRules.push(`@media ${conditionParts.sort().join(" and ")}`);
8107
+ }
8108
+ if (variant.containerConditions.length > 0) {
8109
+ const byName = /* @__PURE__ */ new Map();
8110
+ for (const cond of variant.containerConditions) {
8111
+ const group = byName.get(cond.name) || [];
8112
+ group.push(cond);
8113
+ byName.set(cond.name, group);
8114
+ }
8115
+ for (const [name, conditions] of byName) {
8116
+ const conditionParts = conditions.map((c) => c.negated ? `(not ${c.condition})` : c.condition);
8117
+ const namePrefix = name ? `${name} ` : "";
8118
+ atRules.push(`@container ${namePrefix}${conditionParts.join(" and ")}`);
8119
+ }
8120
+ }
8121
+ if (variant.supportsConditions.length > 0) {
8122
+ const conditionParts = variant.supportsConditions.map((c) => {
8123
+ if (c.subtype === "selector") {
8124
+ const selectorCond = `selector(${c.condition})`;
8125
+ return c.negated ? `(not ${selectorCond})` : selectorCond;
8126
+ } else {
8127
+ const featureCond = `(${c.condition})`;
8128
+ return c.negated ? `(not ${featureCond})` : featureCond;
8129
+ }
8130
+ });
8131
+ atRules.push(`@supports ${conditionParts.join(" and ")}`);
8132
+ }
8133
+ return atRules;
8134
+ }
8135
+ //#endregion
8136
+ //#region src/pipeline/exclusive.ts
8137
+ /**
8138
+ * Build exclusive conditions for a list of parsed style entries.
8139
+ *
8140
+ * The entries should be ordered by priority (highest priority first).
8141
+ *
8142
+ * For each entry, we compute:
8143
+ * exclusiveCondition = condition & !prior[0] & !prior[1] & ...
8144
+ *
8145
+ * This ensures exactly one condition matches at any time.
8146
+ *
8147
+ * Example:
8148
+ * Input (ordered highest to lowest priority):
8149
+ * A: value1 (priority 2)
8150
+ * B: value2 (priority 1)
8151
+ * C: value3 (priority 0)
8152
+ *
8153
+ * Output:
8154
+ * A: A
8155
+ * B: B & !A
8156
+ * C: C & !A & !B
8157
+ *
8158
+ * @param entries Parsed style entries ordered by priority (highest first)
8159
+ * @returns Entries with exclusive conditions, filtered to remove impossible ones
8160
+ */
8161
+ function buildExclusiveConditions(entries) {
8162
+ const result = [];
8163
+ const priorConditions = [];
8164
+ for (const entry of entries) {
8165
+ let exclusive = entry.condition;
8166
+ for (const prior of priorConditions) if (prior.kind !== "true") exclusive = and(exclusive, not(prior));
8167
+ const simplified = simplifyCondition(exclusive);
8168
+ if (simplified.kind === "false") continue;
8169
+ result.push({
8170
+ ...entry,
8171
+ exclusiveCondition: simplified
8172
+ });
8173
+ if (entry.condition.kind !== "true") priorConditions.push(entry.condition);
8174
+ }
8175
+ return result;
8176
+ }
8177
+ /**
8178
+ * Parse style entries from a value mapping object.
8179
+ *
8180
+ * @param styleKey The style key (e.g., 'padding')
8181
+ * @param valueMap The value mapping { '': '2x', 'compact': '1x', '@media(w < 768px)': '0.5x' }
8182
+ * @param parseCondition Function to parse state keys into conditions
8183
+ * @returns Parsed entries ordered by priority (highest first)
8184
+ */
8185
+ function parseStyleEntries(styleKey, valueMap, parseCondition) {
8186
+ const entries = [];
8187
+ Object.keys(valueMap).forEach((stateKey, index) => {
8188
+ const value = valueMap[stateKey];
8189
+ const condition = stateKey === "" ? trueCondition() : parseCondition(stateKey);
8190
+ entries.push({
8191
+ styleKey,
8192
+ stateKey,
8193
+ value,
8194
+ condition,
8195
+ priority: index
8196
+ });
8197
+ });
8198
+ entries.reverse();
8199
+ return entries;
8200
+ }
8201
+ /**
8202
+ * Merge parsed entries that share the same value.
8152
8203
  *
8153
- * Removes:
8154
- * 1. Exact duplicates (same key)
8155
- * 2. Superset variants (more restrictive selectors that are redundant)
8204
+ * When multiple **non-default** state keys map to the same value, their
8205
+ * conditions can be combined with OR and treated as a single entry.
8206
+ * This must happen **before** exclusive expansion and OR branch splitting
8207
+ * to avoid combinatorial explosion and duplicate CSS output.
8208
+ *
8209
+ * **Merging must preserve the authored cascade.** Merging two same-value
8210
+ * entries with priorities `p_h > p_l` lifts the lower-priority entry up
8211
+ * to `p_h` and changes the "blocker" for intermediate-priority entries
8212
+ * from `!C_h` to `!(C_h | C_l) = !C_h & !C_l`. The added `!C_l`
8213
+ * constraint can incorrectly block an intermediate entry that should
8214
+ * have won.
8215
+ *
8216
+ * Two same-value entries with conditions `C_h` (higher priority) and
8217
+ * `C_l` (lower priority) are safe to merge iff for every entry
8218
+ * `e_m` strictly between them in priority with a different value,
8219
+ *
8220
+ * simplify(C_m & C_l & !C_h) = FALSE
8221
+ *
8222
+ * i.e. there is no scenario where the intermediate state could have
8223
+ * matched (`C_m`), the lower-priority same-value entry would also have
8224
+ * matched (`C_l`), and the higher-priority entry would not (`!C_h`).
8225
+ * In such scenarios the intermediate is supposed to win; the merge
8226
+ * would block it by introducing `!C_l`.
8227
+ *
8228
+ * Example (UNSAFE — must not merge):
8229
+ * `{ hovered: 'red', pressed: 'blue', disabled: 'red' }`.
8230
+ * C_h = disabled, C_l = hovered, C_m = pressed. `pressed & hovered &
8231
+ * !disabled` is satisfiable (three independent modifiers), so the
8232
+ * intermediate `pressed` would lose to a merged red rule when both
8233
+ * `pressed` and `hovered` are active — breaking the cascade
8234
+ * `disabled > pressed > hovered`.
8235
+ *
8236
+ * Example (SAFE — still merges):
8237
+ * `{ '': light, '@dark': dark, '@hc': hc, '@dark & @hc': dark }`.
8238
+ * C_h = `@dark & @hc`, C_l = `@dark`, C_m = `@hc`.
8239
+ * `@hc & @dark & !(@dark & @hc) = @hc & @dark & (!@dark | !@hc)`
8240
+ * simplifies to FALSE, so merging the two darks into one `@dark` rule
8241
+ * at the higher priority does not affect the `@hc` rule.
8242
+ *
8243
+ * Default (TRUE) entries are never merged with non-default entries.
8244
+ * Merging `TRUE | X` collapses to `TRUE`, destroying the non-default
8245
+ * condition's participation in exclusive building. Stage 6
8246
+ * `mergeByValue` handles combining rules with identical CSS output
8247
+ * after exclusive conditions are correctly built.
8248
+ *
8249
+ * The merged entry keeps the highest priority of the merged entries.
8156
8250
  */
8157
- function dedupeVariants(variants) {
8158
- if (variants.length <= 1) return variants;
8159
- const seen = /* @__PURE__ */ new Set();
8160
- const result = [];
8161
- for (const v of variants) {
8162
- const key = getVariantKey(v);
8163
- if (!seen.has(key)) {
8164
- seen.add(key);
8165
- result.push(v);
8251
+ function mergeEntriesByValue(entries) {
8252
+ if (entries.length <= 1) return entries;
8253
+ const merged = [];
8254
+ for (const entry of entries) {
8255
+ if (entry.condition.kind === "true") {
8256
+ merged.push(entry);
8257
+ continue;
8166
8258
  }
8167
- }
8168
- if (result.length <= 1) return result;
8169
- result.sort((a, b) => variantConditionCount(a) - variantConditionCount(b));
8170
- const filtered = [];
8171
- for (const candidate of result) {
8172
- let isRedundant = false;
8173
- for (const kept of filtered) if (isVariantSuperset(candidate, kept)) {
8174
- isRedundant = true;
8175
- break;
8259
+ const valueKey = serializeValue(entry.value);
8260
+ let mergeIdx = -1;
8261
+ for (let j = merged.length - 1; j >= 0; j--) {
8262
+ const prev = merged[j];
8263
+ if (prev.condition.kind === "true") continue;
8264
+ if (serializeValue(prev.value) !== valueKey) continue;
8265
+ let safe = true;
8266
+ for (let k = j + 1; k < merged.length; k++) {
8267
+ const inter = merged[k];
8268
+ if (inter.condition.kind === "true") continue;
8269
+ if (serializeValue(inter.value) === valueKey) continue;
8270
+ if (simplifyCondition(and(inter.condition, entry.condition, not(prev.condition))).kind !== "false") {
8271
+ safe = false;
8272
+ break;
8273
+ }
8274
+ }
8275
+ if (safe) {
8276
+ mergeIdx = j;
8277
+ break;
8278
+ }
8176
8279
  }
8177
- if (!isRedundant) filtered.push(candidate);
8280
+ if (mergeIdx >= 0) {
8281
+ const prev = merged[mergeIdx];
8282
+ const newCondition = simplifyCondition(or(prev.condition, entry.condition));
8283
+ merged[mergeIdx] = {
8284
+ styleKey: prev.styleKey,
8285
+ stateKey: `${prev.stateKey} | ${entry.stateKey}`,
8286
+ value: prev.value,
8287
+ condition: newCondition,
8288
+ priority: Math.max(prev.priority, entry.priority)
8289
+ };
8290
+ } else merged.push(entry);
8178
8291
  }
8179
- return filtered;
8292
+ merged.sort((a, b) => b.priority - a.priority);
8293
+ return merged;
8294
+ }
8295
+ function serializeValue(value) {
8296
+ if (value === null || value === void 0) return "null";
8297
+ if (typeof value === "string" || typeof value === "number") return String(value);
8298
+ return JSON.stringify(value);
8180
8299
  }
8181
8300
  /**
8182
- * Combine AND conditions into CSS
8301
+ * Eliminate redundant state dimensions from a value map.
8183
8302
  *
8184
- * AND of conditions means cartesian product of variants:
8185
- * (A1 | A2) & (B1 | B2) = A1&B1 | A1&B2 | A2&B1 | A2&B2
8303
+ * When a value map contains compound AND state keys (e.g. `@dark & @hc`),
8304
+ * checks whether any state atom is a "don't-care" variable — i.e. the
8305
+ * value is the same whether that atom is present or absent. Redundant
8306
+ * atoms are removed from all keys and duplicate entries are collapsed.
8186
8307
  *
8187
- * Variants that result in contradictions (e.g., conflicting media rules)
8188
- * are filtered out.
8308
+ * This runs **before** condition parsing so that downstream stages
8309
+ * (`mergeEntriesByValue`, `buildExclusiveConditions`, materialization)
8310
+ * never see the irrelevant dimension, producing simpler, smaller CSS.
8311
+ *
8312
+ * Only pure top-level AND combinations are eligible. Keys that contain
8313
+ * `|`, `^`, or `,` at the top level are treated as opaque single atoms.
8314
+ *
8315
+ * @example
8316
+ * { '': A, '@dark': B, '@hc': A, '@dark & @hc': B }
8317
+ * // @hc is redundant → { '': A, '@dark': B }
8189
8318
  */
8190
- function andToCSS(children) {
8191
- const exclusiveChildren = makeOrBranchesExclusive(children);
8192
- let currentVariants = [emptyVariant()];
8193
- for (const child of exclusiveChildren) {
8194
- const childCSS = conditionToCSSInner(child);
8195
- if (childCSS.isImpossible || childCSS.variants.length === 0) return {
8196
- variants: [],
8197
- isImpossible: true
8198
- };
8199
- const newVariants = [];
8200
- for (const current of currentVariants) for (const childVariant of childCSS.variants) {
8201
- const merged = mergeVariants(current, childVariant);
8202
- if (merged !== null) newVariants.push(merged);
8203
- }
8204
- if (newVariants.length === 0) return {
8205
- variants: [],
8206
- isImpossible: true
8319
+ function extractCompoundStates(valueMap) {
8320
+ const keys = Object.keys(valueMap);
8321
+ if (keys.length < 3 || !keys.some((k) => k.includes("&"))) return valueMap;
8322
+ const entries = keys.map((key) => {
8323
+ return {
8324
+ atoms: splitTopLevelAnd(key) ?? [key],
8325
+ value: valueMap[key]
8207
8326
  };
8208
- currentVariants = dedupeVariants(newVariants);
8327
+ });
8328
+ const allAtoms = /* @__PURE__ */ new Set();
8329
+ for (const e of entries) for (const a of e.atoms) allAtoms.add(a);
8330
+ const redundant = /* @__PURE__ */ new Set();
8331
+ for (const atom of allAtoms) if (isAtomRedundant(entries, atom)) redundant.add(atom);
8332
+ if (redundant.size === 0) return valueMap;
8333
+ const newMap = {};
8334
+ for (const e of entries) {
8335
+ const newKey = e.atoms.filter((a) => !redundant.has(a)).join(" & ");
8336
+ if (!(newKey in newMap)) newMap[newKey] = e.value;
8209
8337
  }
8210
- return {
8211
- variants: currentVariants,
8212
- isImpossible: false
8213
- };
8338
+ return newMap;
8214
8339
  }
8215
8340
  /**
8216
- * Make OR branches within AND children mutually exclusive.
8217
- *
8218
- * For an AND child that is OR(A, B), transforms it to OR(A, B & !A)
8219
- * so that when andToCSS does a Cartesian product, the resulting
8220
- * CSS variants don't overlap.
8341
+ * Split a state key by top-level `&` operators.
8221
8342
  *
8222
- * Only transforms OR children whose branches actually produce
8223
- * different at-rule contexts when materialized. This avoids
8224
- * breaking cases where contradiction detection in the Cartesian
8225
- * product naturally handles deduplication.
8343
+ * Returns `null` if the key contains `|`, `^`, or `,` at the top level
8344
+ * (making it ineligible for atom-level extraction).
8345
+ * Returns `[]` for the empty string (default key).
8226
8346
  */
8227
- function makeOrBranchesExclusive(children) {
8228
- return children.map((child) => {
8229
- if (!isCompoundCondition(child) || child.operator !== "OR") return child;
8230
- if (child.children.length <= 1) return child;
8231
- if (!branchesProduceDifferentContexts(child.children)) return child;
8232
- const exclusiveBranches = [];
8233
- const priorBranches = [];
8234
- for (const branch of child.children) {
8235
- if (priorBranches.length === 0) exclusiveBranches.push(branch);
8236
- else {
8237
- let exclusive = branch;
8238
- for (const prior of priorBranches) exclusive = and(exclusive, not(prior));
8239
- const simplified = simplifyCondition(exclusive);
8240
- if (simplified.kind !== "false") exclusiveBranches.push(simplified);
8347
+ function splitTopLevelAnd(key) {
8348
+ if (key === "") return [];
8349
+ const parts = [];
8350
+ let depth = 0;
8351
+ let current = "";
8352
+ for (const ch of key) {
8353
+ if (ch === "(" || ch === "[") depth++;
8354
+ else if (ch === ")" || ch === "]") depth--;
8355
+ if (depth === 0) {
8356
+ if (ch === "&") {
8357
+ const trimmed = current.trim();
8358
+ if (trimmed) parts.push(trimmed);
8359
+ current = "";
8360
+ continue;
8241
8361
  }
8242
- priorBranches.push(branch);
8362
+ if (ch === "|" || ch === "^" || ch === ",") return null;
8243
8363
  }
8244
- if (exclusiveBranches.length === 0) return child;
8245
- if (exclusiveBranches.length === 1) return exclusiveBranches[0];
8246
- return {
8247
- kind: "compound",
8248
- operator: "OR",
8249
- children: exclusiveBranches
8250
- };
8251
- });
8364
+ current += ch;
8365
+ }
8366
+ const trimmed = current.trim();
8367
+ if (trimmed) parts.push(trimmed);
8368
+ return parts;
8252
8369
  }
8253
8370
  /**
8254
- * Check if OR branches produce different at-rule contexts when
8255
- * materialized. If so, the Cartesian product in andToCSS will
8256
- * create overlapping CSS variants that need exclusive expansion.
8371
+ * An atom is redundant when every entry that contains it has a matching
8372
+ * partner (same remaining atoms, atom absent) with the same value.
8257
8373
  */
8258
- function branchesProduceDifferentContexts(branches) {
8259
- const contextKeys = /* @__PURE__ */ new Set();
8260
- for (const branch of branches) {
8261
- const css = conditionToCSSInner(branch);
8262
- if (css.isImpossible) continue;
8263
- for (const v of css.variants) contextKeys.add(getVariantContextKey(v));
8374
+ function isAtomRedundant(entries, atom) {
8375
+ const withAtom = entries.filter((e) => e.atoms.includes(atom));
8376
+ if (withAtom.length === 0) return false;
8377
+ for (const wa of withAtom) {
8378
+ const remaining = wa.atoms.filter((a) => a !== atom);
8379
+ const pair = entries.find((e) => !e.atoms.includes(atom) && e.atoms.length === remaining.length && remaining.every((r) => e.atoms.includes(r)));
8380
+ if (!pair) return false;
8381
+ if (serializeValue(wa.value) !== serializeValue(pair.value)) return false;
8264
8382
  }
8265
- return contextKeys.size > 1;
8383
+ return true;
8266
8384
  }
8267
8385
  /**
8268
- * Combine OR conditions into CSS
8386
+ * Check if a value is a style value mapping (object with state keys)
8387
+ */
8388
+ function isValueMapping(value) {
8389
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
8390
+ }
8391
+ /**
8392
+ * Expand OR conditions in parsed entries into multiple exclusive entries.
8269
8393
  *
8270
- * OR in CSS means multiple selector variants (DNF).
8271
- * After deduplication, variants that differ only in their base
8272
- * modifier/pseudo conditions are merged into :is() groups.
8394
+ * For an entry with condition `A | B | C`, this creates 3 entries:
8395
+ * - condition: A
8396
+ * - condition: B & !A
8397
+ * - condition: C & !A & !B
8273
8398
  *
8274
- * Note: OR exclusivity is handled at the pipeline level (expandOrConditions),
8275
- * so here we just collect all variants. Any remaining ORs in the condition
8276
- * tree (e.g., from De Morgan expansion) are handled as simple alternatives.
8399
+ * This ensures OR branches are mutually exclusive BEFORE the main
8400
+ * exclusive condition building pass.
8401
+ *
8402
+ * @param entries Parsed entries (may contain OR conditions)
8403
+ * @returns Expanded entries with OR branches made exclusive
8277
8404
  */
8278
- function orToCSS(children) {
8279
- const allVariants = [];
8280
- for (const child of children) {
8281
- const childCSS = conditionToCSSInner(child);
8282
- if (childCSS.isImpossible) continue;
8283
- allVariants.push(...childCSS.variants);
8405
+ function expandOrConditions(entries) {
8406
+ const result = [];
8407
+ for (const entry of entries) {
8408
+ const expanded = expandSingleEntry(entry);
8409
+ result.push(...expanded);
8410
+ }
8411
+ return result;
8412
+ }
8413
+ /**
8414
+ * Expand a single entry's OR condition into multiple exclusive entries.
8415
+ *
8416
+ * Note: branches are NOT sorted by at-rule context here (unlike the
8417
+ * `expandExclusiveOrs` pass below). User-authored ORs in state keys aren't
8418
+ * the product of De Morgan negation, so each branch is expected to render
8419
+ * independently in its own scope and at-rule sort isn't load-bearing.
8420
+ * The post-build pass needs the sort because it has to preserve at-rule
8421
+ * wrapping across branches that came from negating a compound at-rule.
8422
+ *
8423
+ * Skip optimisation: when every branch renders into the same at-rule /
8424
+ * root / parent / own context (see "Key Design Decision #2" in
8425
+ * `docs/pipeline.md`), forcing mutual exclusivity here produces dead
8426
+ * `B & !A`-style branches that materialization later folds back into
8427
+ * `:is(A, B)`. Bail out and let `materialize.ts` collapse the OR via
8428
+ * `mergeVariantsIntoSelectorGroups`. Cross-entry exclusivity is still
8429
+ * enforced by `buildExclusiveConditions`; the post-build `expandExclusiveOrs`
8430
+ * pass still handles De Morgan ORs whose branches actually differ in
8431
+ * context.
8432
+ */
8433
+ function expandSingleEntry(entry) {
8434
+ const orBranches = collectOrBranches(entry.condition);
8435
+ if (orBranches.length <= 1) return [entry];
8436
+ if (!branchesProduceDifferentContexts(orBranches)) return [entry];
8437
+ const result = [];
8438
+ const priorBranches = [];
8439
+ for (let i = 0; i < orBranches.length; i++) {
8440
+ const branch = orBranches[i];
8441
+ let exclusiveBranch = branch;
8442
+ for (const prior of priorBranches) exclusiveBranch = and(exclusiveBranch, not(prior));
8443
+ const simplified = simplifyCondition(exclusiveBranch);
8444
+ if (simplified.kind === "false") {
8445
+ priorBranches.push(branch);
8446
+ continue;
8447
+ }
8448
+ result.push({
8449
+ ...entry,
8450
+ stateKey: `${entry.stateKey}[${i}]`,
8451
+ condition: simplified
8452
+ });
8453
+ priorBranches.push(branch);
8284
8454
  }
8285
- if (allVariants.length === 0) return {
8286
- variants: [],
8287
- isImpossible: true
8288
- };
8289
- return {
8290
- variants: dedupeVariants(allVariants),
8291
- isImpossible: false
8292
- };
8455
+ return result;
8293
8456
  }
8294
8457
  /**
8295
- * Find keys present in ALL condition arrays.
8458
+ * Collect top-level OR branches from a condition.
8459
+ *
8460
+ * For `A | B | C`, returns [A, B, C]
8461
+ * For `A & B`, returns [A & B] (single branch)
8462
+ * For `A | (B & C)`, returns [A, B & C]
8296
8463
  */
8297
- function findCommonKeys(conditionSets, getKey) {
8298
- if (conditionSets.length === 0) return /* @__PURE__ */ new Set();
8299
- const common = new Set(conditionSets[0].map(getKey));
8300
- for (let i = 1; i < conditionSets.length; i++) {
8301
- const keys = new Set(conditionSets[i].map(getKey));
8302
- for (const key of common) if (!keys.has(key)) common.delete(key);
8464
+ function collectOrBranches(condition) {
8465
+ if (condition.kind === "true" || condition.kind === "false") return [condition];
8466
+ if (isCompoundCondition(condition) && condition.operator === "OR") {
8467
+ const branches = [];
8468
+ for (const child of condition.children) branches.push(...collectOrBranches(child));
8469
+ return branches;
8303
8470
  }
8304
- return common;
8471
+ return [condition];
8305
8472
  }
8306
8473
  /**
8307
- * Merge OR variants that share the same "context" (at-rules, root, parent,
8308
- * own, starting) into a single variant with a SelectorGroup.
8474
+ * Expand OR conditions in exclusive entries AFTER buildExclusiveConditions.
8309
8475
  *
8310
- * Variants with no modifier/pseudo conditions are kept separate (they match
8311
- * unconditionally and can't be expressed inside :is()).
8476
+ * This handles ORs that arise from De Morgan expansion during negation:
8477
+ * !(A & B) = !A | !B
8478
+ *
8479
+ * These ORs need to be made exclusive to avoid overlapping CSS rules:
8480
+ * !A | !B → !A | (A & !B)
8481
+ *
8482
+ * This is logically equivalent but ensures each branch has proper context.
8483
+ *
8484
+ * Example:
8485
+ * Input: { "": V1, "@supports(...) & :has()": V2 }
8486
+ * V2's exclusive = @supports & :has
8487
+ * V1's exclusive = !(@supports & :has) = !@supports | !:has
8488
+ *
8489
+ * Without this fix: V1 gets two rules:
8490
+ * - @supports (not ...) → V1 ✓
8491
+ * - :not(:has()) → V1 ✗ (missing @supports context!)
8492
+ *
8493
+ * With this fix: V1 gets two exclusive rules:
8494
+ * - @supports (not ...) → V1 ✓
8495
+ * - @supports (...) { :not(:has()) } → V1 ✓ (proper context!)
8312
8496
  */
8313
- function mergeVariantsIntoSelectorGroups(variants) {
8314
- if (variants.length <= 1) return variants;
8315
- const groups = /* @__PURE__ */ new Map();
8316
- for (const v of variants) {
8317
- const key = getVariantContextKey(v);
8318
- const group = groups.get(key);
8319
- if (group) group.push(v);
8320
- else groups.set(key, [v]);
8321
- }
8497
+ function expandExclusiveOrs(entries) {
8322
8498
  const result = [];
8323
- for (const group of groups.values()) {
8324
- if (group.length === 1) {
8325
- result.push(group[0]);
8326
- continue;
8327
- }
8328
- const withSelectors = [];
8329
- const withoutSelectors = [];
8330
- for (const v of group) if (v.modifierConditions.length === 0 && v.pseudoConditions.length === 0) withoutSelectors.push(v);
8331
- else withSelectors.push(v);
8332
- result.push(...withoutSelectors);
8333
- if (withSelectors.length <= 1) {
8334
- result.push(...withSelectors);
8335
- continue;
8336
- }
8337
- result.push(factorAndGroup(withSelectors));
8499
+ for (const entry of entries) {
8500
+ const expanded = expandExclusiveConditionOrs(entry);
8501
+ result.push(...expanded);
8338
8502
  }
8339
8503
  return result;
8340
8504
  }
8341
8505
  /**
8342
- * Factor common modifier/pseudo conditions out of variants and create
8343
- * a single variant with a SelectorGroup for the remaining (differing)
8344
- * conditions.
8345
- *
8346
- * Precondition: all variants must share the same context key (identical
8347
- * at-rules, root/parent/own/selector groups, startingStyle).
8506
+ * Check if a condition involves at-rules (media, container, supports, starting)
8348
8507
  */
8349
- function factorAndGroup(variants) {
8350
- {
8351
- const key0 = getVariantContextKey(variants[0]);
8352
- for (let i = 1; i < variants.length; i++) {
8353
- const keyI = getVariantContextKey(variants[i]);
8354
- if (keyI !== key0) throw new Error(`factorAndGroup: context key mismatch at index ${i}.\n expected: ${key0}\n got: ${keyI}`);
8355
- }
8356
- }
8357
- const commonModKeys = findCommonKeys(variants.map((v) => v.modifierConditions), getModifierKey);
8358
- const commonPseudoKeys = findCommonKeys(variants.map((v) => v.pseudoConditions), getPseudoKey);
8359
- const commonModifiers = variants[0].modifierConditions.filter((m) => commonModKeys.has(getModifierKey(m)));
8360
- const commonPseudos = variants[0].pseudoConditions.filter((p) => commonPseudoKeys.has(getPseudoKey(p)));
8361
- const branches = [];
8362
- let hasEmptyBranch = false;
8363
- for (const v of variants) {
8364
- const branch = [];
8365
- for (const mod of v.modifierConditions) if (!commonModKeys.has(getModifierKey(mod))) branch.push(mod);
8366
- for (const pseudo of v.pseudoConditions) if (!commonPseudoKeys.has(getPseudoKey(pseudo))) branch.push(pseudo);
8367
- if (branch.length > 0) branches.push(branch);
8368
- else hasEmptyBranch = true;
8369
- }
8370
- if (hasEmptyBranch) return {
8371
- ...variants[0],
8372
- modifierConditions: commonModifiers,
8373
- pseudoConditions: commonPseudos
8374
- };
8375
- const factoredGroups = tryFactorIntoDimensions(branches);
8376
- if (factoredGroups) return {
8377
- modifierConditions: commonModifiers,
8378
- pseudoConditions: commonPseudos,
8379
- selectorGroups: [...variants[0].selectorGroups, ...factoredGroups],
8380
- ownGroups: [...variants[0].ownGroups],
8381
- mediaConditions: [...variants[0].mediaConditions],
8382
- containerConditions: [...variants[0].containerConditions],
8383
- supportsConditions: [...variants[0].supportsConditions],
8384
- rootGroups: [...variants[0].rootGroups],
8385
- parentGroups: [...variants[0].parentGroups],
8386
- startingStyle: variants[0].startingStyle
8387
- };
8388
- return {
8389
- modifierConditions: commonModifiers,
8390
- pseudoConditions: commonPseudos,
8391
- selectorGroups: [...variants[0].selectorGroups, {
8392
- branches,
8393
- negated: false
8394
- }],
8395
- ownGroups: [...variants[0].ownGroups],
8396
- mediaConditions: [...variants[0].mediaConditions],
8397
- containerConditions: [...variants[0].containerConditions],
8398
- supportsConditions: [...variants[0].supportsConditions],
8399
- rootGroups: [...variants[0].rootGroups],
8400
- parentGroups: [...variants[0].parentGroups],
8401
- startingStyle: variants[0].startingStyle
8402
- };
8508
+ function hasAtRuleContext(node) {
8509
+ if (node.kind === "true" || node.kind === "false") return false;
8510
+ if (node.kind === "state") return node.type === "media" || node.type === "container" || node.type === "supports" || node.type === "starting";
8511
+ if (node.kind === "compound") return node.children.some(hasAtRuleContext);
8512
+ return false;
8403
8513
  }
8404
8514
  /**
8405
- * Detect when branches form a complete Cartesian product of independent
8406
- * modifier attribute dimensions and return one SelectorGroup per dimension.
8515
+ * Sort OR branches to prioritize at-rule conditions first.
8407
8516
  *
8408
- * Example: 4 branches for 2 attributes × 2 values each →
8409
- * :is(A1, A2):is(B1, B2) instead of :is(A1B1, A1B2, A2B1, A2B2)
8517
+ * This is critical for correct CSS generation. For `!A | !B` where A is at-rule
8518
+ * and B is modifier, we want:
8519
+ * - Branch 0: !A (at-rule negation - covers "no @supports/media" case)
8520
+ * - Branch 1: A & !B (modifier negation with at-rule context)
8521
+ *
8522
+ * If we process in wrong order (!B first), we'd get:
8523
+ * - Branch 0: !B (modifier negation WITHOUT at-rule context - WRONG!)
8524
+ * - Branch 1: B & !A (at-rule negation with modifier - incomplete coverage)
8410
8525
  */
8411
- function tryFactorIntoDimensions(branches) {
8412
- if (branches.length < 4) return null;
8413
- const dimensions = /* @__PURE__ */ new Map();
8414
- for (const branch of branches) for (const cond of branch) {
8415
- if (!("attribute" in cond)) return null;
8416
- if (!dimensions.has(cond.attribute)) dimensions.set(cond.attribute, /* @__PURE__ */ new Map());
8417
- dimensions.get(cond.attribute).set(getModifierKey(cond), cond);
8418
- }
8419
- if (dimensions.size < 2) return null;
8420
- for (const branch of branches) {
8421
- const seen = /* @__PURE__ */ new Set();
8422
- for (const cond of branch) {
8423
- const attr = cond.attribute;
8424
- if (seen.has(attr)) return null;
8425
- seen.add(attr);
8426
- }
8427
- if (seen.size !== dimensions.size) return null;
8428
- }
8429
- let expectedCount = 1;
8430
- for (const vals of dimensions.values()) expectedCount *= vals.size;
8431
- if (branches.length !== expectedCount) return null;
8432
- return [...dimensions.values()].map((vals) => ({
8433
- branches: [...vals.values()].map((cond) => [cond]),
8434
- negated: false
8435
- }));
8526
+ function sortOrBranchesForExpansion(branches) {
8527
+ return [...branches].sort((a, b) => {
8528
+ const aHasAtRule = hasAtRuleContext(a);
8529
+ const bHasAtRule = hasAtRuleContext(b);
8530
+ if (aHasAtRule && !bHasAtRule) return -1;
8531
+ if (!aHasAtRule && bHasAtRule) return 1;
8532
+ return 0;
8533
+ });
8436
8534
  }
8437
8535
  /**
8438
- * Build at-rules array from a variant
8536
+ * Expand ORs in a single entry's exclusive condition
8439
8537
  */
8440
- function buildAtRulesFromVariant(variant) {
8441
- const atRules = [];
8442
- if (variant.mediaConditions.length > 0) {
8443
- const conditionParts = variant.mediaConditions.map((c) => {
8444
- if (c.subtype === "type") return c.negated ? `not ${c.condition}` : c.condition;
8445
- else return c.negated ? `(not ${c.condition})` : c.condition;
8446
- });
8447
- atRules.push(`@media ${conditionParts.sort().join(" and ")}`);
8448
- }
8449
- if (variant.containerConditions.length > 0) {
8450
- const byName = /* @__PURE__ */ new Map();
8451
- for (const cond of variant.containerConditions) {
8452
- const group = byName.get(cond.name) || [];
8453
- group.push(cond);
8454
- byName.set(cond.name, group);
8455
- }
8456
- for (const [name, conditions] of byName) {
8457
- const conditionParts = conditions.map((c) => c.negated ? `(not ${c.condition})` : c.condition);
8458
- const namePrefix = name ? `${name} ` : "";
8459
- atRules.push(`@container ${namePrefix}${conditionParts.join(" and ")}`);
8538
+ function expandExclusiveConditionOrs(entry) {
8539
+ let orBranches = collectOrBranches(entry.exclusiveCondition);
8540
+ if (orBranches.length <= 1) return [entry];
8541
+ if (!branchesProduceDifferentContexts(orBranches)) return [entry];
8542
+ orBranches = sortOrBranchesForExpansion(orBranches);
8543
+ const result = [];
8544
+ const priorBranches = [];
8545
+ for (let i = 0; i < orBranches.length; i++) {
8546
+ const branch = orBranches[i];
8547
+ let exclusiveBranch = branch;
8548
+ for (const prior of priorBranches) exclusiveBranch = and(exclusiveBranch, not(prior));
8549
+ const simplified = simplifyCondition(exclusiveBranch);
8550
+ if (simplified.kind === "false") {
8551
+ priorBranches.push(branch);
8552
+ continue;
8460
8553
  }
8461
- }
8462
- if (variant.supportsConditions.length > 0) {
8463
- const conditionParts = variant.supportsConditions.map((c) => {
8464
- if (c.subtype === "selector") {
8465
- const selectorCond = `selector(${c.condition})`;
8466
- return c.negated ? `(not ${selectorCond})` : selectorCond;
8467
- } else {
8468
- const featureCond = `(${c.condition})`;
8469
- return c.negated ? `(not ${featureCond})` : featureCond;
8470
- }
8554
+ result.push({
8555
+ ...entry,
8556
+ stateKey: `${entry.stateKey}[or:${i}]`,
8557
+ exclusiveCondition: simplified
8471
8558
  });
8472
- atRules.push(`@supports ${conditionParts.join(" and ")}`);
8559
+ priorBranches.push(branch);
8473
8560
  }
8474
- return atRules;
8561
+ return result;
8475
8562
  }
8476
8563
  //#endregion
8477
8564
  //#region src/utils/case-converter.ts
@@ -8538,6 +8625,15 @@ function emitWarning(code, message) {
8538
8625
  const MAX_XOR_CHAIN_LENGTH = 4;
8539
8626
  const parseCache = new Lru(5e3);
8540
8627
  /**
8628
+ * Chrome-internal pseudo-classes (e.g. `:-internal-autofill-selected`,
8629
+ * `:-internal-autofill-previewed`) cannot be targeted from user CSS and
8630
+ * may invalidate the surrounding rule in Safari even when wrapped in
8631
+ * forgiving `:is(...)`. The regex matches both bare uses and references
8632
+ * inside enhanced pseudo arguments like `:is(:-webkit-autofill,
8633
+ * :-internal-autofill-selected)`.
8634
+ */
8635
+ const INTERNAL_PSEUDO_PATTERN = /:-internal-[a-z0-9-]+/g;
8636
+ /**
8541
8637
  * Pattern for tokenizing state notation.
8542
8638
  * Matches: operators, parentheses, @-prefixed states, value mods, boolean mods,
8543
8639
  * pseudo-classes, class selectors, and attribute selectors.
@@ -8955,6 +9051,14 @@ function parseStateKey(stateKey, options = {}) {
8955
9051
  const cacheKey = trimmed + "\0" + (options.isSubElement ? "1" : "0") + "\0" + localStatesKey;
8956
9052
  const cached = parseCache.get(cacheKey);
8957
9053
  if (cached) return cached;
9054
+ if (isDevEnv()) {
9055
+ INTERNAL_PSEUDO_PATTERN.lastIndex = 0;
9056
+ const internalMatches = trimmed.match(INTERNAL_PSEUDO_PATTERN);
9057
+ if (internalMatches && internalMatches.length > 0) {
9058
+ const unique = Array.from(new Set(internalMatches));
9059
+ emitWarning("INTERNAL_PSEUDO_USED", `State key "${trimmed}" references internal pseudo-class${unique.length > 1 ? "es" : ""} ${unique.map((p) => `\`${p}\``).join(", ")}. These are unmatchable from user CSS and can invalidate the surrounding rule in Safari (even inside \`:is(...)\`). Use \`:-webkit-autofill | :autofill\` instead for autofill states.`);
9060
+ }
9061
+ }
8958
9062
  const result = new Parser(tokenize(trimmed), options).parse();
8959
9063
  parseCache.set(cacheKey, result);
8960
9064
  return result;
@@ -9024,7 +9128,15 @@ function runPipeline(styles, parserContext) {
9024
9128
  function processStyles(styles, selectorSuffix, parserContext, allRules) {
9025
9129
  const keys = Object.keys(styles);
9026
9130
  const selectorKeys = keys.filter((key) => isSelector(key));
9027
- const styleKeys = keys.filter((key) => !isSelector(key) && !key.startsWith("@"));
9131
+ const styleKeys = [];
9132
+ for (const key of keys) {
9133
+ if (isSelector(key) || key.startsWith("@")) continue;
9134
+ if (key.startsWith(":")) {
9135
+ emitWarning("INVALID_TOP_LEVEL_PSEUDO_KEY", `Style key "${key}" starts with ':' which is not a valid Tasty style key. Use "&${key}" for nested-selector form, or move the state into a value map (e.g. \`{ color: { '${key}': value } }\`). The key has been ignored.`);
9136
+ continue;
9137
+ }
9138
+ styleKeys.push(key);
9139
+ }
9028
9140
  processNestedSelectors(styles, selectorKeys, selectorSuffix, parserContext, allRules);
9029
9141
  processHandlerQueue(buildHandlerQueue(styleKeys, styles), selectorSuffix, parserContext, allRules);
9030
9142
  }
@@ -10348,4 +10460,4 @@ function resetConfig() {
10348
10460
  //#endregion
10349
10461
  export { parseColor as $, StyleInjector as A, strToRgb as At, styleHandlers as B, parseStateKey as C, getColorSpaceFunc as Ct, extractPredefinedStateRefs as D, getRgbValuesFromRgbaString as Dt, extractLocalPredefinedStates as E, getNamedColorHex as Et, fontFaceContentHash as F, CUSTOM_UNITS as G, warn as H, formatFontFaceRule as I, filterMods as J, DIRECTIONS as K, hasLocalFontFace as L, formatCounterStyleRule as M, hasLocalCounterStyle as N, getGlobalPredefinedStates as O, hexToRgb as Ot, extractLocalFontFace as P, normalizeColorTokenValue as Q, SheetManager as R, renderStyles as S, getColorSpaceComponents as St, createStateParserContext as T, getComponentPropertySyntax as Tt, createStyle as U, deprecationWarning as V, PropertyTypeResolver as W, getGlobalParser as X, getGlobalFuncs as Y, getGlobalPredefinedTokens as Z, markStylesGenerated as _, extractLocalProperties as _t, getGlobalCounterStyle as a, okhslPlugin as at, hasPipelineCacheEntry as b, parsePropertyToken as bt, getGlobalKeyframes as c, DEFAULT_NAME_PREFIX as ct, getNamePrefix as d, makeCounterStyleName as dt, parseStyle as et, hasGlobalKeyframes as f, makeKeyframeName as ft, isTestEnvironment as g, hashString as gt, isConfigLocked as h, isDevEnv as ht, getGlobalConfigTokens as i, okhslFunc as it, extractLocalCounterStyle as j, Lru as jt, setGlobalPredefinedStates as k, hslToRgbValues as kt, getGlobalRecipes as l, DEFAULT_ZERO_NAME_PREFIX as lt, hasStylesGenerated as m, validateNamePrefix as mt, getConfig as n, setGlobalPredefinedTokens as nt, getGlobalFontFace as o, StyleParser as ot, hasGlobalRecipes as p, tastyClassRegex as pt, customFunc as q, getEffectiveProperties as r, stringifyStyles as rt, getGlobalInjector as s, Bucket as st, configure as t, resetGlobalPredefinedTokens as tt, getGlobalStyles as u, makeClassName as ut, resetConfig as v, getEffectiveDefinition as vt, camelToKebab as w, getColorSpaceSuffix as wt, isSelector as x, colorInitialValueToComponents as xt, generateTypographyTokens as y, hasLocalProperties as yt, STYLE_HANDLER_MAP as z };
10350
10462
 
10351
- //# sourceMappingURL=config-JokB1Lc8.js.map
10463
+ //# sourceMappingURL=config-LDodmgVz.js.map