domflax 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +214 -0
  2. package/dist/chunk-4HHISSMR.js +2227 -0
  3. package/dist/chunk-4HHISSMR.js.map +1 -0
  4. package/dist/chunk-6WVVF6AD.js +55 -0
  5. package/dist/chunk-6WVVF6AD.js.map +1 -0
  6. package/dist/chunk-77SLHRN6.js +2047 -0
  7. package/dist/chunk-77SLHRN6.js.map +1 -0
  8. package/dist/chunk-ZJ2S36GY.js +175 -0
  9. package/dist/chunk-ZJ2S36GY.js.map +1 -0
  10. package/dist/cli.cjs +5207 -0
  11. package/dist/cli.cjs.map +1 -0
  12. package/dist/cli.d.cts +1 -0
  13. package/dist/cli.d.ts +1 -0
  14. package/dist/cli.js +1310 -0
  15. package/dist/cli.js.map +1 -0
  16. package/dist/index.cjs +4383 -0
  17. package/dist/index.cjs.map +1 -0
  18. package/dist/index.d.cts +539 -0
  19. package/dist/index.d.ts +539 -0
  20. package/dist/index.js +110 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/pattern-CX6iBzTD.d.ts +237 -0
  23. package/dist/pattern-P4FIKAUB.d.cts +237 -0
  24. package/dist/pattern-kit.cjs +630 -0
  25. package/dist/pattern-kit.cjs.map +1 -0
  26. package/dist/pattern-kit.d.cts +80 -0
  27. package/dist/pattern-kit.d.ts +80 -0
  28. package/dist/pattern-kit.js +55 -0
  29. package/dist/pattern-kit.js.map +1 -0
  30. package/dist/types-BQ7l6dVe.d.cts +749 -0
  31. package/dist/types-BQ7l6dVe.d.ts +749 -0
  32. package/dist/verify.cjs +2747 -0
  33. package/dist/verify.cjs.map +1 -0
  34. package/dist/verify.d.cts +245 -0
  35. package/dist/verify.d.ts +245 -0
  36. package/dist/verify.js +2700 -0
  37. package/dist/verify.js.map +1 -0
  38. package/dist/webpack-loader.cjs +4149 -0
  39. package/dist/webpack-loader.cjs.map +1 -0
  40. package/dist/webpack-loader.d.cts +21 -0
  41. package/dist/webpack-loader.d.ts +21 -0
  42. package/dist/webpack-loader.js +30 -0
  43. package/dist/webpack-loader.js.map +1 -0
  44. package/package.json +99 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../patterns/src/flatten/empty-style-div.pattern.ts","../../patterns/src/flatten/flex-center-wrapper.pattern.ts","../../patterns/src/flatten/nested-flex-merge.pattern.ts","../../patterns/src/flatten/passthrough-wrapper.pattern.ts","../../patterns/src/flatten/redundant-fragment.pattern.ts","../../patterns/src/compress/dedupe-classes.pattern.ts","../../patterns/src/compress/inset-shorthand.pattern.ts","../../patterns/src/compress/margin-shorthand.pattern.ts","../../patterns/src/compress/padding-shorthand.pattern.ts","../../patterns/src/compress/size-shorthand.pattern.ts","../../patterns/src/_registry.generated.ts","../../patterns/src/index.ts","../../frontend-jsx/src/frontend.ts","../../frontend-jsx/src/backend.ts","../../frontend-jsx/src/index.ts","../../resolver-tailwind/src/index.ts","../../resolver-css/src/index.ts"],"sourcesContent":["/**\n * @domflax/patterns — flatten pattern: `empty-style-div`.\n *\n * Collapses the most common piece of structural noise of all: a `<div>` whose ONLY role is to wrap\n * a single child while contributing nothing to layout or paint —\n *\n * <div><Child/></div> (no styles at all)\n * <div style=\"display:block\"><Child/></div> (the default; still a no-op box)\n *\n * Such a div is layout-neutral: it is a plain block box with no own visual style, establishes no\n * box / formatting / stacking context, is not a containing block, and declares no custom properties\n * a descendant might read. Its box is therefore indistinguishable from \"not being there\", so it can\n * be unwrapped into its sole child.\n *\n * Authored with the declarative {@link pattern} API. The opacity-barrier + selector-safety guards\n * (ref/handlers/dynamic-children/raw-html/combinator/reparent-impact) are applied automatically for\n * every `flatten/*` pattern; the `where` predicates below add the LAYOUT-neutrality requirements\n * specific to this pattern (no non-block display, no box/formatting/stacking context, no containing\n * block, no custom-property coupling, no structural-pseudo targeting).\n */\n\nimport type {\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n StyleMap,\n} from '@domflax/core';\n\nimport { not, pattern, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local matcher helpers ───────────────────────── */\n\n/** Narrow a NodeLike to a (readonly) element, or null. */\nfunction asEl(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/** A boolean `meta` flag, lifted into a {@link Matcher}. Mirrors how core's combinators read meta. */\nfunction metaFlag(flag: keyof NodeMeta): Matcher {\n return (node) => Boolean(asEl(node)?.meta[flag]);\n}\n\n/** Wrapper establishes an intrinsic/explicit box (sizing) — NOT layout-neutral. */\nconst establishesBox = metaFlag('establishesBox');\n/** Wrapper establishes a formatting context (flex/grid/flow-root/…) — NOT layout-neutral. */\nconst establishesFormattingContext = metaFlag('establishesFormattingContext');\n/** Wrapper establishes a stacking context (transform/opacity<1/z-index/…) — NOT layout-neutral. */\nconst establishesStackingContext = metaFlag('establishesStackingContext');\n/** Wrapper is the containing block for abs/fixed descendants — removing it would reposition them. */\nconst isContainingBlock = metaFlag('isContainingBlock');\n/** Wrapper sets `--*` custom properties a descendant reads (author-var coupling). */\nconst declaresCustomProperties = metaFlag('declaresCustomProperties');\n\n/**\n * Wrapper is a structural-pseudo target (:first/:last/:only/:nth-child/-of-type). Honours the\n * frontend-set meta flag and the precomputed {@link SelectorIndex}. Unwrapping such a node would\n * change a selector's match-set.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\nconst DISPLAY = 'display' as CssProperty;\n\n/**\n * True when the wrapper sets `display` to anything other than the block default in ANY condition.\n * An `inline`/`inline-block`/`flex`/`grid`/`contents`/`none` div is NOT layout-neutral — its box (or\n * lack of one) participates in layout differently from its surviving child.\n */\nconst hasNonBlockDisplay: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n const sm: StyleMap = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n for (const block of sm.blocks.values()) {\n const decl = block.decls.get(DISPLAY);\n if (decl && String(decl.value) !== 'block') return true;\n }\n return false;\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a layout-neutral, style-free `<div>` wrapper into its sole element child.\n */\nexport const emptyStyleDiv = pattern({\n name: 'empty-style-div',\n category: 'flatten/empty-style-div',\n safety: 1,\n doc: {\n title: 'Flatten empty-style div wrapper',\n summary:\n 'A layout-neutral div (display:block default, no box/visual styles) that wraps a single ' +\n 'child is removed; the child is hoisted into its place.',\n before: '<div><Child/></div>',\n after: '<Child/>',\n safetyRationale:\n 'Wrapper is a plain block box that paints nothing, establishes no box/formatting/stacking ' +\n 'context, is no containing block, has no custom-property coupling, carries no ' +\n 'ref/handlers/dynamic children/raw HTML, and is neither a combinator subject nor a ' +\n 'structural-pseudo target; inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(hasNonBlockDisplay),\n not(establishesBox),\n not(establishesFormattingContext),\n not(establishesStackingContext),\n not(isContainingBlock),\n not(declaresCustomProperties),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n examples: [\n {\n before: '<div><span className=\"bg-red-200\">Hi</span></div>',\n after: '<span className=\"bg-red-200\">Hi</span>',\n },\n {\n // The wrapper paints its own background (own visual style) → not layout-neutral, kept.\n noMatch: '<div className=\"bg-blue-500\"><span className=\"bg-red-200\">Hi</span></div>',\n },\n ],\n});\n","/**\n * @domflax/patterns — flatten pattern: `flex-center-wrapper`.\n *\n * Collapses the ubiquitous \"centering wrapper\" idiom\n *\n * <div style=\"display:flex; align-items:center; justify-content:center\"><Child/></div>\n *\n * into its sole child, pushing the centering intent down onto the child as `place-self: center`.\n * The wrapper only exists to center one element; once `place-self:center` lives on the child the\n * wrapper is pure structural noise and can go.\n *\n * Authored with the declarative {@link pattern} API: the match is the flex-centering computed-style\n * signature on a single-element-child `<div>` that paints nothing of its own; the recipe folds\n * inheritable styles onto the child, grants it `place-self:center`, then unwraps the wrapper\n * (id-preserving). The opacity-barrier + selector-safety guards are applied automatically by the\n * `pattern()` factory for every `flatten/*` pattern.\n */\n\nimport { pattern } from '@domflax/pattern-kit';\n\n/**\n * Flatten a flex-centering `<div>` wrapper into its sole element child, granting the child\n * `place-self:center`.\n */\nexport const flexCenterWrapper = pattern({\n name: 'flex-center-wrapper',\n category: 'flatten/flex-center-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten flex-centering wrapper',\n summary:\n 'A div that only centers a single child (display:flex; align-items:center; ' +\n 'justify-content:center) is removed; the child gains place-self:center.',\n before: '<div style=\"display:flex;align-items:center;justify-content:center\"><Child/></div>',\n after: '<Child style=\"place-self:center\"/>',\n safetyRationale:\n 'Wrapper paints nothing, carries no ref/handlers/dynamic children, and is not a combinator ' +\n 'subject; inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n style: { display: 'flex', alignItems: 'center', justifyContent: 'center' },\n onlyChild: 'element',\n paintsNothing: true,\n },\n rewrite: {\n flattenInto: 'child',\n childGains: { placeSelf: 'center' },\n },\n examples: [\n {\n // The wrapper is removed; the surviving child gains `place-self-center` (reverse-emitted\n // from the folded computed style by the resolver).\n before:\n '<div className=\"flex justify-center items-center\">' +\n '<div className=\"bg-red-200\">Hello</div>' +\n '</div>',\n after: '<div className=\"bg-red-200 place-self-center\">Hello</div>',\n },\n {\n // onClick is a hard opacity barrier → the wrapper is load-bearing, no flatten.\n noMatch:\n '<div className=\"flex justify-center items-center\" onClick={handleClick}>' +\n '<div className=\"bg-red-200\">Hello</div>' +\n '</div>',\n },\n ],\n});\n","/**\n * @domflax/patterns — flatten pattern: `nested-flex-merge`.\n *\n * Collapses a redundant nesting of two flex containers\n *\n * <div style=\"display:flex; align-items:center; gap:8px\">\n * <div style=\"display:flex; flex-direction:column\"> … </div>\n * </div>\n *\n * where the OUTER flex container's sole element child is ITSELF a flex container, into a single\n * flex container that carries the union of both elements' flex declarations. The outer wrapper's\n * box is then structural noise (it paints nothing and only establishes a flex context that the\n * merged child now also establishes), so it is removed.\n *\n * Authored with the declarative {@link pattern} API: the match is a flex `<div>` with a single\n * element child painting nothing of its own (auto-guarded against opacity barriers / combinator\n * targeting like every `flatten/*` pattern). The value-relational reasoning — the child must also\n * be a (non-combinator) flex container, the wrapper must carry only transferable flex/inheritable\n * declarations, and the two must not conflict on any shared flex property — lives in the `rewrite`\n * op-draft factory escape hatch, which folds inherited styles, transfers the wrapper's flex\n * declarations onto the child (target-wins), then unwraps the wrapper.\n */\n\nimport type {\n ConditionKey,\n CssProperty,\n MatchContext,\n NodeLike,\n RewriteFactory,\n RewriteOpDraft,\n StyleBlock,\n StyleDecl,\n StyleMap,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n and,\n computed,\n isElement,\n normalizer,\n not,\n pattern,\n targetedByCombinator,\n type Matcher,\n} from '@domflax/pattern-kit';\n\n/* ───────────────────────── style fixtures ───────────────────────── */\n\n/** Build a single-(base-)condition StyleMap from raw `[property, value]` pairs via the shared normalizer. */\nfunction baseConditionStyleMap(decls: readonly (readonly [string, string])[]): StyleMap {\n const map = new Map<CssProperty, StyleDecl>();\n for (const [prop, value] of decls) {\n for (const decl of normalizer.normalizeDeclaration(prop, value, false)) {\n map.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls: map };\n const blocks = new Map<ConditionKey, StyleBlock>([[conditionKey(BASE_CONDITION), block]]);\n return { blocks };\n}\n\n/** Both containers must declare `display:flex` (the matched signature). */\nconst DISPLAY_FLEX: StyleMap = baseConditionStyleMap([['display', 'flex']]);\n\n/**\n * The flex-CONTAINER property set this pattern is allowed to transfer from the wrapper onto the\n * child. (Longhands only, since the shared normalizer expands `gap` → `row-gap`/`column-gap`.)\n */\nconst FLEX_CONTAINER_PROPERTIES: ReadonlySet<string> = new Set<string>([\n 'display',\n 'flex-direction',\n 'flex-wrap',\n 'justify-content',\n 'align-items',\n 'align-content',\n 'place-content',\n 'place-items',\n 'row-gap',\n 'column-gap',\n]);\n\n/* ───────────────────────── style reasoning helpers (pure) ───────────────────────── */\n\n/**\n * True iff every declaration on the wrapper is either a transferable flex-container property or an\n * inheritable property (which we fold onto the child). If the wrapper carries anything else\n * (padding/margin/sizing/position/…), removing its box would change layout, so the merge is unsafe.\n */\nfunction outerMergeSafe(sm: StyleMap): boolean {\n const norm = normalizer.normalizeStyleMap(sm);\n for (const block of norm.blocks.values()) {\n for (const decl of block.decls.values()) {\n if (FLEX_CONTAINER_PROPERTIES.has(String(decl.property))) continue;\n if (decl.inherited) continue;\n return false;\n }\n }\n return true;\n}\n\n/**\n * True iff the two containers disagree on any shared flex-container property (in any matching\n * condition) — e.g. `flex-direction:row` vs `flex-direction:column`. Such a conflict makes the\n * merge ambiguous, so the pattern skips.\n */\nfunction flexConflict(outer: StyleMap, inner: StyleMap): boolean {\n const a = normalizer.normalizeStyleMap(outer);\n const b = normalizer.normalizeStyleMap(inner);\n for (const [key, blockA] of a.blocks) {\n const blockB = b.blocks.get(key);\n if (!blockB) continue;\n for (const [prop, declA] of blockA.decls) {\n if (!FLEX_CONTAINER_PROPERTIES.has(String(prop))) continue;\n const declB = blockB.decls.get(prop);\n if (declB && declB.value !== declA.value) return true;\n }\n }\n return false;\n}\n\n/** Project the wrapper's transferable flex-container declarations into a fresh StyleMap. */\nfunction extractFlexStyle(sm: StyleMap): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (FLEX_CONTAINER_PROPERTIES.has(String(prop))) decls.set(prop, decl);\n }\n if (decls.size > 0) blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/** The inner (surviving) flex container: also a flex `<div>`, and not a combinator subject (it is reparented). */\nconst isInnerFlex: Matcher = and(\n isElement('div'),\n computed(DISPLAY_FLEX),\n not(targetedByCombinator),\n);\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a flex container whose sole child is a compatible flex container into a single container.\n */\nexport const nestedFlexMerge = pattern({\n name: 'nested-flex-merge',\n category: 'flatten/nested-flex-merge',\n safety: 2,\n doc: {\n title: 'Merge nested flex containers',\n summary:\n 'A flex container whose only child is itself a flex container with non-conflicting flex ' +\n 'properties is collapsed into one; the wrapper is removed and its flex declarations merge ' +\n 'onto the surviving child.',\n before:\n '<div style=\"display:flex;align-items:center;gap:8px\">' +\n '<div style=\"display:flex;flex-direction:column\"/></div>',\n after: '<div style=\"display:flex;flex-direction:column;align-items:center;gap:8px\"/>',\n safetyRationale:\n 'The wrapper paints nothing, declares only flex-container/inheritable properties, carries no ' +\n 'ref/handlers/dynamic children, and is not a combinator subject; the two containers do not ' +\n 'conflict on any flex property, so the union is unambiguous and lossless.',\n },\n match: {\n tag: 'div',\n style: { display: 'flex' },\n onlyChild: 'element',\n paintsNothing: true,\n },\n rewrite: (ctx: MatchContext, rw: RewriteFactory): readonly RewriteOpDraft[] | null => {\n const outer = ctx.node;\n const inner = ctx.onlyElementChild();\n if (!inner) return null;\n if (!isInnerFlex(inner as unknown as NodeLike, ctx)) return null;\n\n const outerStyle = ctx.computed();\n const innerStyle = ctx.computedOf(inner as unknown as NodeLike);\n\n // The wrapper must carry nothing that would be lost when its box is removed …\n if (!outerMergeSafe(outerStyle)) return null;\n // … and the two containers must agree on every shared flex property.\n if (flexConflict(outerStyle, innerStyle)) return null;\n\n return [\n // 1. Preserve inheritable values (color/font/…) by folding them onto the child first.\n rw.foldInheritedStyles(outer, inner, { conditions: 'all' }),\n // 2. Transfer the wrapper's flex-container declarations onto the child (target-wins keeps the\n // child's value for any shared property — identical anyway, we proved non-conflict).\n rw.mergeStyle(inner, null, extractFlexStyle(outerStyle), 'target-wins'),\n // 3. Remove the wrapper (structural-safe; hoists the child and preserves its IRNodeId).\n rw.unwrap(outer),\n ];\n },\n examples: [\n {\n // The wrapper's flex declarations (align-items / gap) merge onto the inner flex container,\n // then the wrapper is removed (its own `data-x` here just blocks the more aggressive\n // passthrough-wrapper so this merge is the one that fires).\n before:\n '<div className=\"flex items-center gap-2\" data-x=\"1\">' +\n '<div className=\"flex flex-col\">X</div>' +\n '</div>',\n after: '<div className=\"flex flex-col gap-2 items-center\">X</div>',\n },\n {\n // A non-flex wrapper does not match the flex-container signature → left unchanged.\n noMatch:\n '<div className=\"block bg-blue-500\">' +\n '<div className=\"flex flex-col\">X</div>' +\n '</div>',\n },\n ],\n});\n","/**\n * @domflax/patterns — flatten pattern: `passthrough-wrapper`.\n *\n * Collapses a purely-structural wrapper that exists for no reason at all:\n *\n * <div><Child/></div>\n *\n * The wrapper paints nothing, establishes no box / formatting / stacking context, carries no\n * attributes beyond an (optional) inert class, holds exactly one element child, and is free of every\n * opacity barrier (ref / event-handlers / dynamic children / dangerous html / spread / component).\n * Such a `<div>` is pure DOM noise: removing it and hoisting the child is invisible to both paint\n * and layout.\n *\n * Authored with the declarative {@link pattern} API. The opacity-barrier + selector-safety guards\n * (ref/handlers/dynamic-children/raw-html/combinator/reparent-impact) are applied automatically for\n * every `flatten/*` pattern; the `where` predicates add the passthrough-specific requirements (no\n * box/formatting/stacking context, no own attrs, no dynamic/spread classes, not a component, not a\n * structural-pseudo subject).\n */\n\nimport type {\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n} from '@domflax/core';\n\nimport { hasDynamicClasses, not, pattern, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local meta/attr/selector matchers ───────────────────────── */\n\nfunction metaOf(node: NodeLike): DeepReadonly<NodeMeta> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>).meta : null;\n}\n\nfunction elementOf(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/**\n * Element establishes some box / formatting / stacking context, is a containing block, or exposes\n * custom properties to a descendant — any of which means removing its box could shift layout or\n * break a `var()` coupling, so it is NOT a passthrough.\n */\nconst establishesContext: Matcher = (node) => {\n const m = metaOf(node);\n if (!m) return false;\n return (\n m.establishesBox ||\n m.establishesFormattingContext ||\n m.establishesStackingContext ||\n m.isContainingBlock ||\n m.declaresCustomProperties\n );\n};\n\n/** Hard opacity barriers beyond the auto-applied set: spread attrs, component identity. */\nconst hasSpreadAttrs: Matcher = (node) => metaOf(node)?.hasSpreadAttrs ?? false;\nconst isComponentNode: Matcher = (node) => metaOf(node)?.isComponent ?? false;\n\n/** Element carries own attributes (id / data-* / …) beyond its class list — possible selector/JS hook. */\nconst hasOwnAttrs: Matcher = (node) => {\n const el = elementOf(node);\n if (!el) return false;\n return el.attrs.entries.size > 0 || el.attrs.spreads.length > 0;\n};\n\n/**\n * Element is the subject of a structural pseudo (`:first/:last/:only/:nth-*`). Honours the meta flag\n * and the precomputed {@link SelectorIndex}.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = elementOf(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a do-nothing `<div>` wrapper into its sole element child, folding any inheritable styles\n * down first so inherited values survive the box removal.\n */\nexport const passthroughWrapper = pattern({\n name: 'passthrough-wrapper',\n category: 'flatten/passthrough-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten passthrough wrapper',\n summary:\n 'A div with no own visual/box style, no attributes beyond an inert class, exactly one ' +\n 'element child, and no opacity barriers is removed; its sole child is hoisted in its place.',\n before: '<div><Child/></div>',\n after: '<Child/>',\n safetyRationale:\n 'Wrapper paints nothing and establishes no layout/paint/var context, carries no ' +\n 'ref/handlers/dynamic-children/html/spread/component identity, owns no targetable attrs, ' +\n 'and is not a combinator/structural-pseudo subject (reparenting changes no match-set); ' +\n 'inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(establishesContext),\n not(hasOwnAttrs),\n not(hasDynamicClasses),\n not(hasSpreadAttrs),\n not(isComponentNode),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n examples: [\n {\n before: '<div className=\"flex\"><a className=\"bg-red-200\">Link</a></div>',\n after: '<a className=\"bg-red-200\">Link</a>',\n },\n {\n // A ref pins the wrapper's element identity (a hard opacity barrier) → not a passthrough.\n noMatch: '<div ref={rootRef}><a className=\"bg-red-200\">Link</a></div>',\n },\n ],\n});\n","/**\n * @domflax/patterns — flatten pattern: `redundant-fragment`.\n *\n * Collapses a fragment that wraps exactly one child\n *\n * <><Child/></> → <Child/>\n *\n * A fragment renders no box of its own, so a fragment whose sole purpose is to wrap a single node\n * is pure structural noise: splicing the child up into the fragment's slot is invisible in both\n * the rendered DOM and the project's CSS cascade.\n *\n * Anchoring: the pass manager only visits ELEMENT nodes (see core's `elementIds`), never fragments,\n * so this pattern is anchored on the fragment's sole *element* child and removes the PARENT fragment.\n * Because the match is PARENT-anchored (and reads a fragment's `meta`, which the element-only\n * combinator vocabulary cannot inspect), it uses the declarative API's two escape hatches: a raw\n * `match` predicate and a raw `rewrite` op-draft factory.\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n IRNode,\n IRNodeId,\n MatchContext,\n NodeLike,\n RewriteFactory,\n RewriteOpDraft,\n} from '@domflax/core';\n\nimport { pattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── match predicate (escape hatch) ───────────────────────── */\n\n/**\n * Matches an element whose PARENT is a redundant, unwrappable fragment: a non-root fragment with\n * exactly one child (this element), free of every opacity barrier and CSS-targeting coupling.\n */\nfunction parentIsRedundantFragment(node: NodeLike, ctx: MatchContext): boolean {\n const el = node as DeepReadonly<IRNode>;\n if (el.kind !== 'element') return false;\n\n const parentId = el.parent;\n if (parentId == null) return false;\n\n const parent = ctx.doc.nodes.get(parentId);\n if (!parent || parent.kind !== 'fragment') return false;\n\n // Never unwrap the document root (it must always be a fragment — IRDocument invariant).\n if (parent.parent == null) return false;\n\n // Exactly one child (counting EVERY kind) ⇒ the anchor element is the fragment's sole child.\n if (parent.children.length !== 1) return false;\n\n // Hard opacity barriers on the fragment: keyed `<Fragment key>`, ref/handlers/dynamic children/\n // dangerous HTML/spread/component identity. Any of these means the fragment is load-bearing.\n const m = parent.meta;\n if (\n m.hasKey ||\n m.hasRef ||\n m.hasEventHandlers ||\n m.hasDynamicChildren ||\n m.hasDangerousHtml ||\n m.hasSpreadAttrs ||\n m.isComponent\n ) {\n return false;\n }\n\n // CSS-selector safety: the fragment (or its reparented child) must not move any combinator /\n // structural-pseudo match-set. Honour both the frontend-set meta flags and the SelectorIndex.\n if (m.targetedByCombinator || m.targetedByStructuralPseudo) return false;\n const fid = parentId as unknown as IRNodeId;\n if (ctx.selectors.targetedByCombinator(fid) || ctx.selectors.targetedByStructuralPseudo(fid)) {\n return false;\n }\n if (ctx.selectors.reparentImpact(fid).size > 0) return false;\n\n return true;\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a fragment that wraps exactly one child into that child.\n *\n * Safety level 1 (`safe`): a purely structural, style-free, selector-transparent cleanup.\n */\nexport const redundantFragment = pattern({\n name: 'redundant-fragment',\n category: 'flatten/redundant-fragment',\n safety: 1,\n doc: {\n title: 'Flatten redundant single-child fragment',\n summary:\n 'A fragment whose only child is a single node is removed; the child is spliced up into the ' +\n \"fragment's slot, preserving its IRNodeId, siblings, attributes and the CSS cascade.\",\n before: '<><Child/></>',\n after: '<Child/>',\n safetyRationale:\n 'A fragment paints nothing and renders no box; with exactly one child its removal changes ' +\n 'no sibling/structural-pseudo match-set. Keyed fragments and fragments carrying ' +\n 'ref/handlers/dynamic-children/raw-html/spread are excluded as opacity barriers.',\n },\n match: parentIsRedundantFragment,\n rewrite: (ctx: MatchContext, rw: RewriteFactory): readonly RewriteOpDraft[] | null => {\n const parentId = ctx.node.parent;\n if (parentId == null) return null;\n const fragment = ctx.doc.nodes.get(parentId);\n if (!fragment || fragment.kind !== 'fragment') return null;\n // Splice the sole child up into the fragment's slot, deleting ONLY the fragment node.\n return [rw.unwrap(fragment as unknown as ElementLike)];\n },\n examples: [\n {\n before: '<><span className=\"bg-red-200\">Hi</span></>',\n after: '<span className=\"bg-red-200\">Hi</span>',\n },\n {\n // Two children ⇒ not a single-child fragment, so the fragment is load-bearing and stays.\n noMatch:\n '<><span className=\"bg-red-200\">A</span><span className=\"bg-green-200\">B</span></>',\n },\n ],\n});\n","/**\n * @domflax/patterns — compress pattern: `dedupe-classes`.\n *\n * Removes duplicate / fully-overridden class tokens that resolve to the same property where a\n * LATER token wins, leaving the minimal set of tokens with an IDENTICAL computed style. The\n * canonical case:\n *\n * <p class=\"text-sm text-lg\">…</p> → <p class=\"text-lg\">…</p>\n *\n * Both `text-sm` and `text-lg` set `font-size`; resolution already made `text-lg` win, so the\n * computed `font-size` is `text-lg`'s value and `text-sm` contributes NOTHING to the final\n * computed style. The earlier token is pure noise and can be dropped without changing a pixel.\n *\n * How redundancy is detected (purely from the already-resolved, normalized computed StyleMap):\n * • every declaration carries provenance — `origin` (the winning token) and `shadowed`\n * (the tokens it overrode);\n * • a class token is FULLY OVERRIDDEN iff it appears in some declaration's `shadowed` list but\n * is NOT the winning `origin` of any declaration across ANY style condition. Such a token can\n * be deleted with zero effect on the computed style.\n *\n * Authored with the declarative {@link pattern} API: the `where` guards exclude opacity barriers,\n * dynamic/opaque class lists, and combinator subjects; the `dropClasses` recipe returns the set of\n * fully-overridden, resolver-droppable tokens to delete (their `shadowed` provenance is pruned\n * automatically before the minimal class StyleMap is re-installed).\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n IRElement,\n IRNode,\n MatchContext,\n NodeLike,\n StyleMap,\n} from '@domflax/core';\n\nimport {\n hasDynamicChildren,\n hasDynamicClasses,\n hasEventHandlers,\n hasRef,\n not,\n pattern,\n targetedByCombinator,\n type Matcher,\n} from '@domflax/pattern-kit';\n\n/* ───────────────────────── local matchers (barriers the combinators don't expose) ───────────────────────── */\n\nfunction elementOf(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/** Element renders raw/`dangerouslySetInnerHTML` markup — a hard opacity barrier. */\nconst hasDangerousHtml: Matcher = (node) => elementOf(node)?.meta.hasDangerousHtml ?? false;\n\n/** Element's class list is wholly dynamic/spread-derived → we cannot see or splice its tokens. */\nconst isOpaque: Matcher = (node, ctx) => ctx.isOpaque(node as ElementLike);\n\n/* ───────────────────────── provenance analysis ───────────────────────── */\n\n/** Winners (tokens that win some declaration) and shadowed (tokens overridden somewhere). */\nfunction findRedundantClasses(computed: StyleMap): {\n winners: ReadonlySet<string>;\n shadowed: ReadonlySet<string>;\n} {\n const winners = new Set<string>();\n const shadowed = new Set<string>();\n for (const block of computed.blocks.values()) {\n for (const decl of block.decls.values()) {\n if (decl.origin && decl.origin.kind === 'class') winners.add(decl.origin.className);\n for (const o of decl.shadowed ?? []) {\n if (o.kind === 'class') shadowed.add(o.className);\n }\n }\n }\n return { winners, shadowed };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Collapse a class list to the minimal token set that yields an identical computed style, by\n * dropping tokens whose declarations are fully overridden by later tokens.\n */\nexport const dedupeClasses = pattern({\n name: 'dedupe-classes',\n category: 'compress/dedupe-classes',\n safety: 1,\n doc: {\n title: 'Dedupe fully-overridden class tokens',\n summary:\n 'Drops class tokens whose every declaration is overridden by a later token resolving to the ' +\n 'same property; the surviving token set produces a byte-for-byte identical computed style.',\n before: '<p class=\"text-sm text-lg\" />',\n after: '<p class=\"text-lg\" />',\n safetyRationale:\n 'A fully-overridden token contributes nothing to the computed style in any condition, so ' +\n 'removing it changes no pixels. Dynamic/opaque class lists, ref/handler/dynamic-children/raw-' +\n 'html barriers, combinator subjects, and selector-bound (non-droppable) tokens are excluded.',\n },\n match: {\n where: [\n not(hasRef),\n not(hasEventHandlers),\n not(hasDynamicChildren),\n not(hasDangerousHtml),\n not(hasDynamicClasses),\n not(isOpaque),\n not(targetedByCombinator),\n ],\n },\n rewrite: {\n dropClasses(computed: StyleMap, ctx: MatchContext): Iterable<string> {\n const { winners, shadowed } = findRedundantClasses(computed);\n const drop = new Set<string>();\n for (const cls of shadowed) {\n // A token that still wins SOME property elsewhere is not redundant — keep it.\n if (winners.has(cls)) continue;\n // Selector-membership safety: only drop a token referenced purely as a plain subject.\n if (!ctx.resolver.selectorUsage(cls).droppable) continue;\n drop.add(cls);\n }\n return drop;\n },\n },\n examples: [\n {\n // `text-sm` is fully overridden by `text-lg` (both set font-size + line-height). The resolver\n // records that shadowing in provenance and reports the Tailwind utility as droppable, so the\n // pattern drops `text-sm`; the reverse-emit then re-derives the minimal set (`text-lg`).\n before: '<p className=\"text-sm text-lg\">Hi</p>',\n after: '<p className=\"text-lg\">Hi</p>',\n },\n {\n // Both tokens win a distinct property (no full override) → nothing to dedupe.\n noMatch: '<p className=\"text-lg font-bold\">Hi</p>',\n },\n ],\n});\n","/**\n * @domflax/patterns — compress pattern: `inset-shorthand`.\n *\n * Recompacts the four physical inset longhands (`top`/`right`/`bottom`/`left`) on an element's\n * computed style back into the tightest CSS shorthand the values allow:\n *\n * • all four equal → `inset: <v>`\n * • top == bottom (a matching pair) → `inset-block: <v>` (Tailwind `inset-y-*`)\n * • left == right (a matching pair) → `inset-inline: <v>` (Tailwind `inset-x-*`)\n *\n * The two axis collapses are independent: an element whose `top == bottom` but `left != right`\n * collapses only the block axis and keeps the `left`/`right` longhands verbatim. When nothing\n * collapses (all four distinct, or fewer than a full pair present) the pattern declines.\n *\n * Authored with the declarative {@link pattern} API: the `where` guards exclude opacity barriers,\n * dynamic class lists, and combinator subjects; the `rewriteClasses` recipe rebuilds the class\n * StyleMap, declining (`null`) unless at least one inset axis collapses.\n */\n\nimport type {\n ConditionKey,\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n NodeLike,\n StyleBlock,\n StyleDecl,\n StyleMap,\n} from '@domflax/core';\nimport { BASE_CONDITION_KEY } from '@domflax/core';\n\nimport {\n hasDynamicChildren,\n hasDynamicClasses,\n hasEventHandlers,\n hasRef,\n normalizer,\n not,\n pattern,\n targetedByCombinator,\n type Matcher,\n} from '@domflax/pattern-kit';\n\n/* ───────────────────────── property handles ───────────────────────── */\n\nconst TOP = 'top' as CssProperty;\nconst RIGHT = 'right' as CssProperty;\nconst BOTTOM = 'bottom' as CssProperty;\nconst LEFT = 'left' as CssProperty;\nconst INSET = 'inset' as CssProperty;\nconst INSET_BLOCK = 'inset-block' as CssProperty; // top + bottom (Tailwind inset-y)\nconst INSET_INLINE = 'inset-inline' as CssProperty; // left + right (Tailwind inset-x)\n\n/* ───────────────────────── match guards ───────────────────────── */\n\n/** Element sets raw/dangerous HTML (`dangerouslySetInnerHTML`) — a hard opacity barrier. */\nconst hasRawHtml: Matcher = (node) => {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>).meta.hasDangerousHtml : false;\n};\n\n/* ───────────────────────── value helpers ───────────────────────── */\n\n/** Two side-decls collapse only if they agree on BOTH normalized value and `!important`. */\nfunction sameSide(a: StyleDecl | undefined, b: StyleDecl | undefined): boolean {\n return a !== undefined && b !== undefined && a.value === b.value && a.important === b.important;\n}\n\n/** Re-key a decl onto a new property, recomputing its inherited flag for that property. */\nfunction asProperty(src: StyleDecl, property: CssProperty): StyleDecl {\n return { ...src, property, inherited: normalizer.inherited.isInherited(property) };\n}\n\n/** Rebuild `src` with the base block's decls replaced; all other condition blocks pass through. */\nfunction withBaseDecls(src: StyleMap, baseDecls: ReadonlyMap<CssProperty, StyleDecl>): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of src.blocks) {\n const decls =\n key === BASE_CONDITION_KEY ? baseDecls : new Map<CssProperty, StyleDecl>(block.decls);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Collapse equal/paired physical inset longhands into the `inset` / `inset-block` / `inset-inline`\n * shorthands on an element's computed style.\n */\nexport const insetShorthand = pattern({\n name: 'inset-shorthand',\n category: 'compress/inset-shorthand',\n safety: 2,\n doc: {\n title: 'Compress inset longhands into a shorthand',\n summary:\n 'top/right/bottom/left set to one value collapse to `inset`; a matching top/bottom or ' +\n 'left/right pair collapses to `inset-block` / `inset-inline` (Tailwind inset-y / inset-x).',\n before: '<div style=\"top:10px;right:10px;bottom:10px;left:10px\"/>',\n after: '<div style=\"inset:10px\"/>',\n safetyRationale:\n 'Meaning-preserving shorthand compaction; the element is not a combinator subject and carries ' +\n 'no ref/handlers/dynamic children/raw HTML, so neither selector matching nor behaviour changes.',\n },\n match: {\n where: [\n not(hasRef),\n not(hasEventHandlers),\n not(hasDynamicChildren),\n not(hasRawHtml),\n not(hasDynamicClasses),\n not(targetedByCombinator),\n ],\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = computed.blocks.get(BASE_CONDITION_KEY);\n if (!base) return null;\n\n const top = base.decls.get(TOP);\n const right = base.decls.get(RIGHT);\n const bottom = base.decls.get(BOTTOM);\n const left = base.decls.get(LEFT);\n\n const next = new Map<CssProperty, StyleDecl>(base.decls);\n\n // 1. All four sides equal → single `inset`.\n if (top && sameSide(top, right) && sameSide(top, bottom) && sameSide(top, left)) {\n next.delete(TOP);\n next.delete(RIGHT);\n next.delete(BOTTOM);\n next.delete(LEFT);\n next.set(INSET, asProperty(top, INSET));\n } else {\n let collapsed = false;\n // 2a. Block axis: top == bottom → `inset-block`.\n if (sameSide(top, bottom)) {\n next.delete(TOP);\n next.delete(BOTTOM);\n next.set(INSET_BLOCK, asProperty(top!, INSET_BLOCK));\n collapsed = true;\n }\n // 2b. Inline axis: left == right → `inset-inline`.\n if (sameSide(left, right)) {\n next.delete(LEFT);\n next.delete(RIGHT);\n next.set(INSET_INLINE, asProperty(left!, INSET_INLINE));\n collapsed = true;\n }\n if (!collapsed) return null; // nothing to compress — decline\n }\n\n return withBaseDecls(computed, next);\n },\n },\n examples: [\n {\n // The four equal inset longhands collapse to an `inset` shorthand at the IR level; the\n // minimizing reverse-emit expands it back to top/right/bottom/left and picks the single utility\n // covering all four (`inset-0`), replacing the four physical-side tokens. `bg-red-200` survives.\n before: '<div className=\"top-0 right-0 bottom-0 left-0 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 inset-0\">box</div>',\n },\n {\n // No matching inset pair (all four distinct) → nothing collapses.\n noMatch: '<div className=\"top-0 right-1 bottom-2 left-3 bg-red-200\">box</div>',\n },\n ],\n});\n","/**\n * @domflax/patterns — compress pattern: `margin-shorthand`.\n *\n * Collapses the four explicit margin longhands\n *\n * margin-top / margin-right / margin-bottom / margin-left\n *\n * back into a single CSS `margin` shorthand declaration on the SAME element (the margin analogue of\n * `padding-shorthand`, covering the `m` / `mx` / `my` collapse), choosing the shortest legal\n * 1–4-value form:\n *\n * • all four equal → `margin: <v>` (the `m` case)\n * • top==bottom and left==right → `margin: <y> <x>` (the `my`/`mx` case)\n * • left==right (top!=bottom) → `margin: <t> <x> <b>`\n * • otherwise → `margin: <t> <r> <b> <l>`\n *\n * It is a pure representation change: the resolved box model is identical, only the declaration\n * count shrinks from four to one, which the backend can then re-emit as a single shorthand utility.\n *\n * Authored with the declarative {@link pattern} API: the `where` guards exclude opacity barriers,\n * dynamic class lists, and combinator subjects; the `rewriteClasses` recipe rebuilds the class\n * StyleMap, declining (`null`) unless all four margin longhands are present with a uniform\n * (non-)`!important` flag.\n */\n\nimport type {\n ConditionKey,\n CssProperty,\n CssValue,\n DeepReadonly,\n IRElement,\n IRNode,\n NodeLike,\n StyleBlock,\n StyleDecl,\n StyleMap,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n hasDynamicChildren,\n hasDynamicClasses,\n hasEventHandlers,\n hasRef,\n not,\n pattern,\n targetedByCombinator,\n type Matcher,\n} from '@domflax/pattern-kit';\n\n/* ───────────────────────── constants / helpers ───────────────────────── */\n\n/** The four margin longhands, in CSS shorthand order (top, right, bottom, left). */\nconst MARGIN_SIDES = [\n 'margin-top',\n 'margin-right',\n 'margin-bottom',\n 'margin-left',\n] as const satisfies readonly string[];\n\nconst MARGIN_SIDE_SET: ReadonlySet<string> = new Set(MARGIN_SIDES);\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\nfunction asElement(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/** Raw-html opacity barrier — no combinator exposes this, so narrow + read the meta flag locally. */\nconst hasDangerousHtml: Matcher = (node) => asElement(node)?.meta.hasDangerousHtml ?? false;\n\n/** Collapse four side values into the shortest legal CSS `margin` shorthand value string. */\nfunction collapseMarginValue(top: string, right: string, bottom: string, left: string): string {\n if (right === left) {\n if (top === bottom) {\n return top === right ? top : `${top} ${right}`;\n }\n return `${top} ${right} ${bottom}`;\n }\n return `${top} ${right} ${bottom} ${left}`;\n}\n\n/** Rebuild the computed StyleMap with the four BASE-block margin longhands replaced by `margin`. */\nfunction withFoldedMargin(sm: StyleMap, marginDecl: StyleDecl): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (!MARGIN_SIDE_SET.has(String(prop))) decls.set(prop, decl);\n }\n decls.set(marginDecl.property, marginDecl);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Fold four margin longhands into one `margin` shorthand on the element's base style block.\n */\nexport const marginShorthand = pattern({\n name: 'margin-shorthand',\n category: 'compress/margin-shorthand',\n safety: 2,\n doc: {\n title: 'Compress margin longhands into the `margin` shorthand',\n summary:\n 'An element with margin-top/right/bottom/left all set has them collapsed into the shortest ' +\n 'legal `margin` shorthand (the m / mx / my forms); meaning is preserved, declaration count drops.',\n before: '<div style=\"margin-top:8px;margin-right:8px;margin-bottom:8px;margin-left:8px\"/>',\n after: '<div style=\"margin:8px\"/>',\n safetyRationale:\n 'Pure representation change (no pixels move); skips nodes with ref/handlers/dynamic children/' +\n 'raw html, dynamic class segments, or combinator-subject selectors.',\n },\n match: {\n where: [\n not(hasRef),\n not(hasEventHandlers),\n not(hasDynamicChildren),\n not(hasDynamicClasses),\n not(hasDangerousHtml),\n not(targetedByCombinator),\n ],\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = computed.blocks.get(BASE_KEY);\n if (!base) return null;\n\n // Require all four longhands present in the base block (the `m` collapse only touches base).\n const sides = MARGIN_SIDES.map((p) => base.decls.get(p as CssProperty));\n if (sides.some((d) => d === undefined)) return null;\n const [mt, mr, mb, ml] = sides as readonly StyleDecl[];\n\n // A shorthand can only carry a uniform `!important`; mixing would change cascade behaviour.\n if (mt.important || mr.important || mb.important || ml.important) return null;\n\n const value = collapseMarginValue(\n String(mt.value),\n String(mr.value),\n String(mb.value),\n String(ml.value),\n );\n\n const marginDecl: StyleDecl = {\n property: 'margin' as CssProperty,\n value: value as CssValue,\n important: false,\n relativeToParent:\n mt.relativeToParent || mr.relativeToParent || mb.relativeToParent || ml.relativeToParent,\n inherited: false, // margin is not an inherited property\n };\n\n return withFoldedMargin(computed, marginDecl);\n },\n },\n examples: [\n {\n // The four equal margin longhands collapse to a `margin` shorthand at the IR level, and the\n // minimizing reverse-emit picks the single shortest utility (`m-2`) reproducing it, replacing\n // the four `m{t,r,b,l}-2` tokens. `bg-red-200` is preserved.\n before: '<div className=\"mt-2 mr-2 mb-2 ml-2 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 m-2\">box</div>',\n },\n {\n // Only two margin sides set → the four-longhand `margin` collapse does not apply.\n noMatch: '<div className=\"mt-2 mb-2 bg-red-200\">box</div>',\n },\n ],\n});\n","/**\n * @domflax/patterns — compress pattern: `padding-shorthand`.\n *\n * Collapses an element whose four padding sides are expressed as separate longhand declarations\n * back into the shortest equivalent shorthand:\n *\n * padding-top:16px; padding-right:16px; padding-bottom:16px; padding-left:16px\n * ⇒ padding:16px (Tailwind `p-4`)\n *\n * padding-top:8px; padding-bottom:8px; padding-left:16px; padding-right:16px\n * ⇒ padding:8px 16px (Tailwind `px-4 py-2`)\n *\n * The IR's computed StyleMap is canonically LONGHAND (the shared normalizer expands every box\n * shorthand at parse time). This pass runs the expansion in reverse on the computed map ONLY when\n * the four sides fold cleanly into a 1- or 2-value form — i.e. `top===bottom` AND `left===right`.\n *\n * Authored with the declarative {@link pattern} API: the `where` guards exclude opacity barriers,\n * dynamic class lists, spread/component identity, and combinator subjects; the `rewriteClasses`\n * recipe rebuilds the class StyleMap, declining (`null`) unless the four sides fold cleanly.\n */\n\nimport type {\n ConditionKey,\n CssProperty,\n CssValue,\n DeepReadonly,\n IRElement,\n IRNode,\n NodeLike,\n StyleBlock,\n StyleDecl,\n StyleMap,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n hasDynamicChildren,\n hasDynamicClasses,\n hasEventHandlers,\n hasRef,\n not,\n pattern,\n targetedByCombinator,\n type Matcher,\n} from '@domflax/pattern-kit';\n\n/* ───────────────────────── padding analysis ───────────────────────── */\n\n/** The four padding longhands, in CSS shorthand order: top, right, bottom, left. */\nconst PADDING_SIDES = [\n 'padding-top',\n 'padding-right',\n 'padding-bottom',\n 'padding-left',\n] as const;\n\nconst PADDING_SIDE_SET: ReadonlySet<string> = new Set<string>(PADDING_SIDES);\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/** The collapsed shorthand the four sides fold into (carrying important / relative-unit flags). */\ninterface PaddingFold {\n readonly value: string; // 1-value (`16px`) or 2-value (`8px 16px`) form\n readonly important: boolean;\n readonly relative: boolean;\n}\n\n/**\n * Inspect the BASE-condition block of `sm` and, iff all four padding longhands are present, share a\n * uniform `!important` flag, and form matching x/y pairs (`top===bottom` AND `left===right`), return\n * the shortest equivalent shorthand value. Returns `null` when the sides cannot fold.\n */\nfunction analyzePadding(sm: StyleMap): PaddingFold | null {\n const block = sm.blocks.get(BASE_KEY);\n if (!block) return null;\n\n const sides: StyleDecl[] = [];\n for (const side of PADDING_SIDES) {\n const decl = block.decls.get(side as CssProperty);\n if (!decl) return null;\n sides.push(decl);\n }\n const [top, right, bottom, left] = sides as [StyleDecl, StyleDecl, StyleDecl, StyleDecl];\n\n // A shorthand cannot carry per-side `!important`; only fold a uniform flag.\n if (\n !(\n top.important === right.important &&\n right.important === bottom.important &&\n bottom.important === left.important\n )\n ) {\n return null;\n }\n\n const tv = String(top.value);\n const rv = String(right.value);\n const bv = String(bottom.value);\n const lv = String(left.value);\n\n // Only the `p-*` (all equal) and `px-* py-*` (matching pairs) shapes are in scope.\n if (tv !== bv || lv !== rv) return null;\n\n const value = tv === lv ? tv : `${tv} ${lv}`;\n const relative = sides.some((d) => d.relativeToParent);\n return { value, important: top.important, relative };\n}\n\n/* ───────────────────────── match guards ───────────────────────── */\n\n/** Element carries no hard opacity barrier that rewriting its class list could disturb. */\nconst isInert: Matcher = (node) => {\n const n = node as DeepReadonly<IRNode>;\n if (n.kind !== 'element') return false;\n const el = n as DeepReadonly<IRElement>;\n return !el.meta.hasDangerousHtml && !el.meta.hasSpreadAttrs && !el.isComponent;\n};\n\n/* ───────────────────────── style rebuild ───────────────────────── */\n\n/** Rebuild `sm` with the four BASE-block padding longhands replaced by one `padding` shorthand. */\nfunction withFoldedPadding(sm: StyleMap, fold: PaddingFold): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (PADDING_SIDE_SET.has(String(prop))) continue; // drop the four longhands\n decls.set(prop, decl);\n }\n const shorthand: StyleDecl = {\n property: 'padding' as CssProperty,\n value: fold.value as CssValue,\n important: fold.important,\n relativeToParent: fold.relative,\n inherited: false, // padding is never inherited\n };\n decls.set(shorthand.property, shorthand);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Compress an element's four equal/paired padding longhands into the shortest `padding` shorthand.\n */\nexport const paddingShorthand = pattern({\n name: 'padding-shorthand',\n category: 'compress/padding-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse padding longhands to shorthand',\n summary:\n 'Equal padding on all four sides (or matching x/y pairs) expressed as separate longhand ' +\n 'declarations is collapsed to the shortest equivalent padding shorthand (p-* / px-* py-*).',\n before: '<div class=\"pt-4 pr-4 pb-4 pl-4\"/>',\n after: '<div class=\"p-4\"/>',\n safetyRationale:\n 'A value-preserving re-serialization of the same computed styles on the same node; it skips ' +\n 'nodes with ref/handlers/dynamic children/dynamic classes/dangerous html and combinator ' +\n 'subjects, so no JS identity, behaviour, or project selector is disturbed.',\n },\n match: {\n where: [\n not(hasRef),\n not(hasEventHandlers),\n not(hasDynamicChildren),\n not(hasDynamicClasses),\n not(targetedByCombinator),\n isInert,\n ],\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const fold = analyzePadding(computed);\n return fold ? withFoldedPadding(computed, fold) : null;\n },\n },\n examples: [\n {\n // The four equal padding longhands collapse to a `padding` shorthand at the IR level, and the\n // minimizing reverse-emit picks the single shortest utility (`p-4`) that reproduces it,\n // replacing the four `p{t,r,b,l}-4` tokens. `bg-red-200` is preserved (its order is stable).\n before: '<div className=\"pt-4 pr-4 pb-4 pl-4 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 p-4\">box</div>',\n },\n {\n // Asymmetric padding (top != bottom) cannot fold into a shorthand.\n noMatch: '<div className=\"pt-2 pr-4 pb-8 pl-4 bg-red-200\">box</div>',\n },\n ],\n});\n","/**\n * @domflax/patterns — compress pattern: `size-shorthand`.\n *\n * Collapses an element whose computed `width` and `height` are EQUAL into the single Tailwind\n * `size-*` utility:\n *\n * <div style=\"width:1rem; height:1rem\"/> → <div class=\"size-4\"/>\n *\n * At the IR level we work over the normalized computed StyleMap (CSS longhands), so the pattern\n * recognizes the `width === height` shape in the BASE condition and rebuilds the element's class\n * StyleMap with a single `size` declaration (the resolver reverse-emits the concrete `size-*` token\n * at codegen). Both longhands are removed and replaced by the merged `size` decl, so the rewrite is\n * idempotent — once collapsed there is no `width`+`height` pair left to re-match.\n *\n * Authored with the declarative {@link pattern} API: the `where` guards exclude opacity barriers,\n * dynamic class lists, and combinator subjects (compress patterns get NO auto-guards); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, returning `null` (decline) unless the BASE\n * width/height are equal, concrete, and share an `!important` flag.\n */\n\nimport type {\n ConditionKey,\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n NodeLike,\n StyleBlock,\n StyleDecl,\n StyleMap,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n hasDynamicChildren,\n hasDynamicClasses,\n hasEventHandlers,\n hasRef,\n normalizer,\n not,\n pattern,\n targetedByCombinator,\n type Matcher,\n} from '@domflax/pattern-kit';\n\nconst WIDTH = 'width' as CssProperty;\nconst HEIGHT = 'height' as CssProperty;\nconst SIZE = 'size' as CssProperty;\n\n/** Values for which collapsing the two axes is pointless or unsound (no concrete equal extent). */\nconst NON_COLLAPSIBLE_VALUES: ReadonlySet<string> = new Set<string>(['auto', 'initial', 'unset']);\n\n/* ───────────────────────── helpers ───────────────────────── */\n\nfunction asElement(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/** Read the BASE-condition block of the node's normalized computed StyleMap, if any. */\nfunction baseBlock(sm: StyleMap): StyleBlock | undefined {\n return sm.blocks.get(conditionKey(BASE_CONDITION));\n}\n\n/** Element carries raw/dangerous HTML (e.g. dangerouslySetInnerHTML) — a hard opacity barrier. */\nconst hasDangerousHtml: Matcher = (node) => asElement(node)?.meta.hasDangerousHtml ?? false;\n\n/**\n * Rebuild the computed StyleMap with the BASE block's `width`/`height` pair replaced by a single\n * `size` declaration; all other conditions/blocks are preserved verbatim.\n */\nfunction withSizeShorthand(sm: StyleMap, value: string, important: boolean): StyleMap {\n const baseKey = conditionKey(BASE_CONDITION);\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== baseKey) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>(block.decls);\n decls.delete(WIDTH);\n decls.delete(HEIGHT);\n for (const decl of normalizer.normalizeDeclaration(String(SIZE), value, important)) {\n decls.set(decl.property, decl);\n }\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold equal `width`/`height` into the `size-*` utility. */\nexport const sizeShorthand = pattern({\n name: 'size-shorthand',\n category: 'compress/size-shorthand',\n safety: 2,\n doc: {\n title: 'Collapse equal width/height into size-*',\n summary:\n 'An element whose computed width and height are equal is rewritten to the single Tailwind ' +\n 'size-* utility (size-* === width + height at the same value).',\n before: '<div style=\"width:1rem;height:1rem\"/>',\n after: '<div class=\"size-4\"/>',\n safetyRationale:\n 'size-* is value-identical to equal width+height; the element carries no ref/handlers/' +\n 'dynamic children/dangerous HTML, no dynamic class segment, and is not a combinator subject.',\n },\n match: {\n where: [\n not(hasRef),\n not(hasEventHandlers),\n not(hasDynamicChildren),\n not(hasDangerousHtml),\n not(hasDynamicClasses),\n not(targetedByCombinator),\n ],\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = baseBlock(computed);\n const w = base?.decls.get(WIDTH);\n const h = base?.decls.get(HEIGHT);\n if (!w || !h) return null;\n if (w.important !== h.important) return null;\n if (NON_COLLAPSIBLE_VALUES.has(String(w.value))) return null;\n if (w.value !== h.value) return null;\n return withSizeShorthand(computed, String(w.value), w.important);\n },\n },\n examples: [\n {\n // Equal width/height collapse to a `size` decl at the IR level; the minimizing reverse-emit\n // expands `size` back to width+height, finds the single utility covering both (`size-10`), and\n // replaces the `h-10`+`w-10` pair with it. `bg-red-200` is preserved.\n before: '<div className=\"h-10 w-10 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 size-10\">box</div>',\n },\n {\n // Width and height differ → no equal-axis collapse.\n noMatch: '<div className=\"h-10 w-20 bg-red-200\">box</div>',\n },\n ],\n});\n","/**\n * AUTO-GENERATED by `scripts/gen-registry.mjs` — DO NOT EDIT BY HAND.\n *\n * Regenerate with `npm run generate` (also runs automatically before build/typecheck/test).\n * Patterns are discovered by the `*.pattern.ts` file convention under `src/flatten` and\n * `src/compress`; the array below is sorted flatten-before-compress.\n */\n\nimport type { Pattern } from '@domflax/core';\n\nimport { emptyStyleDiv } from './flatten/empty-style-div.pattern';\nimport { flexCenterWrapper } from './flatten/flex-center-wrapper.pattern';\nimport { nestedFlexMerge } from './flatten/nested-flex-merge.pattern';\nimport { passthroughWrapper } from './flatten/passthrough-wrapper.pattern';\nimport { redundantFragment } from './flatten/redundant-fragment.pattern';\nimport { dedupeClasses } from './compress/dedupe-classes.pattern';\nimport { insetShorthand } from './compress/inset-shorthand.pattern';\nimport { marginShorthand } from './compress/margin-shorthand.pattern';\nimport { paddingShorthand } from './compress/padding-shorthand.pattern';\nimport { sizeShorthand } from './compress/size-shorthand.pattern';\n\nexport {\n emptyStyleDiv,\n flexCenterWrapper,\n nestedFlexMerge,\n passthroughWrapper,\n redundantFragment,\n dedupeClasses,\n insetShorthand,\n marginShorthand,\n paddingShorthand,\n sizeShorthand,\n};\n\n/** Every built-in pattern, in registration order (flatten patterns before compress). */\nexport const builtinPatterns: readonly Pattern[] = [\n emptyStyleDiv,\n flexCenterWrapper,\n nestedFlexMerge,\n passthroughWrapper,\n redundantFragment,\n dedupeClasses,\n insetShorthand,\n marginShorthand,\n paddingShorthand,\n sizeShorthand,\n];\n\nexport default builtinPatterns;\n","/**\n * @domflax/patterns — the built-in rewrite pattern library.\n *\n * Patterns are AUTO-DISCOVERED by file convention: any `*.pattern.ts` under `src/flatten/` or\n * `src/compress/` that default- or named-exports a `pattern()`-built Pattern is picked up by\n * `scripts/gen-registry.mjs`, which writes `src/_registry.generated.ts` (a gitignored build\n * artifact, regenerated before build/typecheck/test). Adding a pattern therefore needs no manual\n * edit to this file — just drop in a new `*.pattern.ts`.\n *\n * This barrel simply re-exports the generated registry: every pattern individually, the assembled\n * {@link builtinPatterns} array (flatten patterns before compress), and that array as the default.\n */\n\nimport { builtinPatterns } from './_registry.generated';\n\nexport * from './_registry.generated';\n\nexport default builtinPatterns;\n","/**\n * @domflax/frontend-jsx — Babel JSX/TSX → IR frontend.\n *\n * Walks a Babel AST (`@babel/parser` → `@babel/traverse`) and lowers JSXElement /\n * JSXFragment / JSXText / JSXExpressionContainer / JSXSpreadChild nodes into the\n * `@domflax/core` IR. ALL dynamic JavaScript stays out of the structural IR: every\n * expression container, spread, and dynamic className/child is interned into the\n * document's {@link ExprRegistry} as an opaque {@link ExprRef} (with its verbatim source\n * slice as payload), and only its source span survives in the tree.\n *\n * Static `class`/`className` literals are split into {@link ClassToken}s on a static\n * {@link ClassSegment}; a non-string-literal className becomes a single dynamic segment\n * (opaque, never optimized). Static classes are resolved through the supplied\n * {@link StyleResolver} + {@link StyleNormalizer} into `element.computed` so downstream\n * patterns can match on resolved style.\n *\n * NodeMeta opacity barriers populated here: hasRef (`ref=`), hasEventHandlers (`on*=`),\n * hasKey (`key=`), hasSpreadAttrs (`{...x}`), hasDangerousHtml\n * (`dangerouslySetInnerHTML=`), hasDynamicChildren (any expression / spread child),\n * isComponent (capitalized / member tag). \"hasDynamicClasses\" is carried on the\n * {@link ClassList} itself (`hasDynamic` / `opaque`), not on NodeMeta.\n */\n\nimport { parse as babelParse } from '@babel/parser';\nimport babelTraverse from '@babel/traverse';\nimport type { NodePath } from '@babel/traverse';\nimport type {\n Expression,\n JSXAttribute,\n JSXElement,\n JSXEmptyExpression,\n JSXFragment,\n JSXIdentifier,\n JSXMemberExpression,\n JSXNamespacedName,\n JSXOpeningElement,\n Node as BabelNode,\n} from '@babel/types';\n\nimport type {\n AttrMap,\n AttrValue,\n ClassList,\n ClassListForm,\n ClassSegment,\n ClassToken,\n Diagnostic,\n ExprKind,\n ExprRef,\n FileKind,\n Frontend,\n FrontendParseContext,\n IRDocument,\n IRElement,\n IRFragment,\n IRNamespace,\n IRNodeId,\n MutableBackrefTable,\n NodeMeta,\n ParseResult,\n SourceFile,\n SourceFileId,\n SourceSpan,\n StyleMap,\n} from '@domflax/core';\nimport {\n createDocument,\n createElement,\n createExpr,\n createFragment,\n createText,\n defaultMeta,\n emptyClassList,\n emptyStyleMap,\n} from '@domflax/core';\n\n/* ───────────────────────── @babel/traverse interop ───────────────────────── */\n\n// `@babel/traverse` is published as CJS (`module.exports = traverse; exports.default = traverse`).\n// Under an ESM default import the value may be the function OR `{ default: fn }` depending on the\n// interop layer (Node ESM vs. esbuild vs. tsup), so normalize defensively.\nconst traverse = (\n typeof babelTraverse === 'function'\n ? babelTraverse\n : (babelTraverse as unknown as { default: typeof babelTraverse }).default\n) as typeof babelTraverse;\n\n/** Languages this frontend claims. JSX/TSX only; HTML is owned by a sibling frontend. */\nconst JSX_LANGS: readonly FileKind[] = ['jsx', 'tsx'];\n\n/** The single registered source file id (one parse == one module). */\nconst FILE_ID = 1 as SourceFileId;\n\n/** Marker payload stored for every interned expression so the backend can re-print it. */\ninterface ExprPayload {\n readonly text: string;\n readonly spread: boolean;\n}\n\n/* ───────────────────────── name + classification helpers ───────────────────────── */\n\ntype JSXName = JSXIdentifier | JSXMemberExpression | JSXNamespacedName;\n\nfunction jsxName(node: JSXName): string {\n switch (node.type) {\n case 'JSXIdentifier':\n return node.name;\n case 'JSXMemberExpression':\n return `${jsxName(node.object)}.${node.property.name}`;\n case 'JSXNamespacedName':\n return `${node.namespace.name}:${node.name.name}`;\n }\n}\n\n/** Component vs. intrinsic: capitalized identifier or member expression ⇒ component. */\nfunction isComponentName(node: JSXName): boolean {\n if (node.type === 'JSXMemberExpression') return true;\n if (node.type === 'JSXNamespacedName') return false;\n return /^[A-Z]/.test(node.name);\n}\n\nfunction attrName(name: JSXAttribute['name']): string {\n return name.type === 'JSXNamespacedName'\n ? `${name.namespace.name}:${name.name.name}`\n : name.name;\n}\n\nfunction exprKind(node: BabelNode): ExprKind {\n switch (node.type) {\n case 'CallExpression':\n case 'OptionalCallExpression':\n return 'call';\n case 'MemberExpression':\n case 'OptionalMemberExpression':\n return 'member';\n case 'ConditionalExpression':\n case 'LogicalExpression':\n return 'conditional';\n case 'TemplateLiteral':\n case 'TaggedTemplateExpression':\n return 'template';\n case 'Identifier':\n return 'identifier';\n case 'SpreadElement':\n return 'spread';\n default:\n return 'other';\n }\n}\n\n/** Map a dynamic className expression to the closest {@link ClassListForm}. */\nfunction classFormOf(node: BabelNode): ClassListForm {\n switch (node.type) {\n case 'TemplateLiteral':\n case 'TaggedTemplateExpression':\n return 'template-literal';\n case 'CallExpression':\n case 'OptionalCallExpression':\n return 'call';\n case 'ConditionalExpression':\n case 'LogicalExpression':\n return 'conditional';\n case 'MemberExpression':\n case 'OptionalMemberExpression':\n case 'Identifier':\n return 'member';\n default:\n return 'call';\n }\n}\n\n/* ───────────────────────── the frontend ───────────────────────── */\n\nfunction looksLikeJsx(id: string, code: string): boolean {\n if (/\\.[jt]sx$/i.test(id)) return true;\n return /<\\/?[A-Za-z][\\w.-]*|<>/.test(code);\n}\n\nfunction doParse(code: string, ctx: FrontendParseContext): ParseResult {\n const diagnostics: Diagnostic[] = [];\n const doc: IRDocument = createDocument('jsx');\n const backref = doc.backref as MutableBackrefTable;\n\n const ast = babelParse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n const eol: '\\n' | '\\r\\n' = code.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const sourceFile: SourceFile = {\n id: FILE_ID,\n path: ctx.id,\n text: code,\n frontend: 'jsx',\n eol,\n indentUnit: ' ',\n native: ast,\n };\n doc.sources.set(FILE_ID, sourceFile);\n\n /* ----- span helpers (close over `code`) ----- */\n\n const spanOf = (node: BabelNode): SourceSpan | null => {\n if (node.start == null || node.end == null) return null;\n const span: SourceSpan = {\n file: FILE_ID,\n start: node.start,\n end: node.end,\n startLoc: node.loc\n ? { line: node.loc.start.line, column: node.loc.start.column }\n : undefined,\n endLoc: node.loc ? { line: node.loc.end.line, column: node.loc.end.column } : undefined,\n };\n return span;\n };\n\n const sliceOf = (node: BabelNode): string =>\n node.start == null || node.end == null ? '' : code.slice(node.start, node.end);\n\n /** Intern an expression as an opaque ExprRef, recording its verbatim source slice. */\n const internExpr = (node: Expression | JSXEmptyExpression, spread: boolean): ExprRef => {\n const payload: ExprPayload = { text: sliceOf(node), spread };\n return doc.exprs.intern({\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n kind: exprKind(node),\n payload,\n });\n };\n\n /* ----- class list ----- */\n\n const splitTokens = (raw: string): ClassToken[] =>\n raw\n .split(/\\s+/)\n .filter((t) => t.length > 0)\n .map((value) => ({ value }) as ClassToken);\n\n const buildClassList = (attr: JSXAttribute): ClassList => {\n const attrSpan = spanOf(attr) ?? undefined;\n const v = attr.value;\n\n const staticList = (tokens: ClassToken[], valueSpan: SourceSpan | null): ClassList => {\n const seg: ClassSegment = { kind: 'static', span: valueSpan ?? undefined, tokens };\n return {\n form: 'string-literal',\n segments: [seg],\n valueSpan,\n attrSpan,\n hasDynamic: false,\n opaque: false,\n rewritable: true,\n };\n };\n\n if (v == null) return staticList([], null);\n\n if (v.type === 'StringLiteral') {\n return staticList(splitTokens(v.value), spanOf(v));\n }\n\n if (v.type === 'JSXExpressionContainer') {\n const expr = v.expression;\n // `className={\"a b\"}` is still a static string literal.\n if (expr.type === 'StringLiteral') {\n return staticList(splitTokens(expr.value), spanOf(expr));\n }\n if (expr.type === 'JSXEmptyExpression') return staticList([], null);\n const ref = internExpr(expr, false);\n const valueSpan = spanOf(expr);\n const seg: ClassSegment = { kind: 'dynamic', span: valueSpan ?? undefined, expr: ref };\n return {\n form: classFormOf(expr),\n segments: [seg],\n valueSpan,\n attrSpan,\n hasDynamic: true,\n opaque: true,\n rewritable: false,\n };\n }\n\n return emptyClassList();\n };\n\n const staticTokensOf = (classes: ClassList): string[] => {\n const out: string[] = [];\n for (const seg of classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n };\n\n /* ----- attribute value ----- */\n\n const buildAttrValue = (attr: JSXAttribute): AttrValue => {\n const v = attr.value;\n if (v == null) return { kind: 'static', value: true, span: spanOf(attr) ?? undefined };\n if (v.type === 'StringLiteral') {\n return { kind: 'static', value: v.value, span: spanOf(v) ?? undefined };\n }\n if (v.type === 'JSXExpressionContainer') {\n if (v.expression.type === 'JSXEmptyExpression') {\n return { kind: 'static', value: true, span: spanOf(v) ?? undefined };\n }\n return { kind: 'dynamic', expr: internExpr(v.expression, false), span: spanOf(v) ?? undefined };\n }\n // JSXElement / JSXFragment used as an attribute value → opaque expression.\n return { kind: 'dynamic', expr: internExpr(v as Expression, false), span: spanOf(v) ?? undefined };\n };\n\n /* ----- node builders ----- */\n\n const buildChild = (node: JSXElement['children'][number], parentId: IRNodeId): IRNodeId | null => {\n switch (node.type) {\n case 'JSXText': {\n const id = doc.alloc.next();\n doc.nodes.set(\n id,\n createText(id, node.value, {\n parent: parentId,\n span: spanOf(node),\n collapsible: /^\\s*$/.test(node.value),\n }),\n );\n return id;\n }\n case 'JSXExpressionContainer': {\n if (node.expression.type === 'JSXEmptyExpression') return null; // `{/* comment */}`\n const id = doc.alloc.next();\n const ref = internExpr(node.expression, false);\n doc.nodes.set(id, createExpr(id, ref, { parent: parentId, span: spanOf(node) }));\n return id;\n }\n case 'JSXSpreadChild': {\n const id = doc.alloc.next();\n const ref = internExpr(node.expression, true);\n doc.nodes.set(id, createExpr(id, ref, { parent: parentId, span: spanOf(node) }));\n return id;\n }\n case 'JSXElement':\n return buildElement(node, parentId);\n case 'JSXFragment':\n return buildFragment(node, parentId);\n default:\n return null;\n }\n };\n\n const buildFragment = (node: JSXFragment, parentId: IRNodeId): IRNodeId => {\n const id = doc.alloc.next();\n const children: IRNodeId[] = [];\n for (const c of node.children) {\n const cid = buildChild(c, id);\n if (cid != null) children.push(cid);\n }\n doc.nodes.set(id, createFragment(id, { children, parent: parentId, span: spanOf(node) }));\n backref.set(id, {\n nodeId: id,\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n openTagSpan: spanOf(node.openingFragment),\n closeTagSpan: spanOf(node.closingFragment),\n innerSpan: null,\n selfClosing: false,\n });\n return id;\n };\n\n const buildElement = (node: JSXElement, parentId: IRNodeId): IRNodeId => {\n const id = doc.alloc.next();\n const opening: JSXOpeningElement = node.openingElement;\n const tag = jsxName(opening.name);\n const component = isComponentName(opening.name);\n\n const meta: NodeMeta = defaultMeta();\n meta.isComponent = component;\n\n let classes: ClassList = emptyClassList();\n const entries = new Map<string, AttrValue>();\n const order: string[] = [];\n const spreads: ExprRef[] = [];\n\n for (const attr of opening.attributes) {\n if (attr.type === 'JSXSpreadAttribute') {\n spreads.push(internExpr(attr.argument, true));\n meta.hasSpreadAttrs = true;\n continue;\n }\n const name = attrName(attr.name);\n if (name === 'className' || name === 'class') {\n classes = buildClassList(attr);\n continue;\n }\n if (name === 'ref') meta.hasRef = true;\n else if (name === 'key') meta.hasKey = true;\n else if (name === 'dangerouslySetInnerHTML') meta.hasDangerousHtml = true;\n else if (/^on[A-Z]/.test(name)) meta.hasEventHandlers = true;\n entries.set(name, buildAttrValue(attr));\n order.push(name);\n }\n\n const attrs: AttrMap = { entries, spreads, order };\n\n const children: IRNodeId[] = [];\n for (const c of node.children) {\n const cid = buildChild(c, id);\n if (cid != null) children.push(cid);\n }\n for (const cid of children) {\n const cn = doc.nodes.get(cid);\n if (cn && cn.kind === 'expr') {\n meta.hasDynamicChildren = true;\n break;\n }\n }\n\n // Resolve static classes (+ tag) into computed style via the injected resolver/normalizer.\n let computed: StyleMap = emptyStyleMap();\n if (!classes.hasDynamic) {\n const tokens = staticTokensOf(classes);\n if (tokens.length > 0) {\n const res = ctx.resolver.resolve({\n classes: tokens,\n element: { tagName: tag, namespace: component ? undefined : 'html' },\n });\n computed = ctx.normalizer.normalizeStyleMap(res.styles);\n for (const w of res.warnings) {\n diagnostics.push({\n code: 'DF_STYLE_CONFLICT_UNRESOLVED',\n severity: w.severity,\n message: w.message,\n nodeId: id,\n });\n }\n }\n }\n\n const namespace: IRNamespace = component ? 'component' : 'html';\n const el: IRElement = createElement(id, {\n tag,\n namespace,\n isComponent: component,\n selfClosing: opening.selfClosing,\n classes,\n computed,\n attrs,\n children,\n parent: parentId,\n span: spanOf(node),\n meta,\n });\n doc.nodes.set(id, el);\n\n const inner =\n children.length > 0\n ? spanOf(node.children[0]! as BabelNode) && spanOf(node.children.at(-1)! as BabelNode)\n ? {\n file: FILE_ID,\n start: spanOf(node.children[0]! as BabelNode)!.start,\n end: spanOf(node.children.at(-1)! as BabelNode)!.end,\n }\n : null\n : null;\n backref.set(id, {\n nodeId: id,\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n openTagSpan: spanOf(opening),\n closeTagSpan: node.closingElement ? spanOf(node.closingElement) : null,\n innerSpan: inner,\n selfClosing: opening.selfClosing,\n });\n return id;\n };\n\n /* ----- collect the outermost JSX islands and attach them to the root fragment ----- */\n\n const roots: (JSXElement | JSXFragment)[] = [];\n traverse(ast, {\n JSXElement(path: NodePath<JSXElement>) {\n roots.push(path.node);\n path.skip();\n },\n JSXFragment(path: NodePath<JSXFragment>) {\n roots.push(path.node);\n path.skip();\n },\n });\n\n const rootFrag = doc.nodes.get(doc.root) as IRFragment;\n for (const r of roots) {\n const id = r.type === 'JSXFragment' ? buildFragment(r, doc.root) : buildElement(r, doc.root);\n rootFrag.children.push(id);\n }\n\n return { doc, diagnostics };\n}\n\nexport const jsxFrontend: Frontend = {\n name: 'babel-jsx',\n langs: JSX_LANGS,\n canParse(id: string, code: string): boolean {\n return looksLikeJsx(id, code);\n },\n parse(code: string, ctx: FrontendParseContext): ParseResult {\n return doParse(code, ctx);\n },\n};\n\n/** Factory mirror — returns a fresh handle to the (stateless) JSX frontend. */\nexport function createJsxFrontend(): Frontend {\n return jsxFrontend;\n}\n","/**\n * @domflax/frontend-jsx — IR → JSX/TSX backend (SURGICAL, full-module round-trip).\n *\n * The pass manager mutates a tree of JSX *islands* that were lowered from a complete module\n * (imports, `export default function`, hooks, `return (…)`, `{expr}` holes, comments, …). The\n * backend's job is to emit a COMPLETE, valid module — not just the JSX subtree. It does this by\n * starting from the element's ORIGINAL verbatim source (retained on {@link SourceFile.text}) and\n * applying ONLY the diffs the passes produced, via `magic-string`:\n *\n * • CLASS CHANGE — for every surviving element whose static class list differs from its source\n * text, overwrite just the `class`/`className` attribute VALUE span (quotes included) with the\n * new tokens. If the element gained classes but had no class attribute, insert one on the\n * opening tag.\n * • UNWRAP (flatten) — when a wrapper element/fragment was removed but its children survived,\n * delete ONLY the wrapper's open- and close-tag spans; the children (and their entire subtrees,\n * including dynamic `{expr}` holes and `key=`) are preserved verbatim.\n * • FULL REMOVAL — when a node was removed with no surviving descendant, delete its whole span.\n *\n * Every other byte — imports, exports, function declarations, returns, hooks, `{expr}` holes,\n * whitespace, comments, attribute ordering — is left exactly as authored. Output is\n * `magicString.toString()`: a complete module.\n *\n * Fallback: a document with no retained source (e.g. a hand-synthesized IR) cannot be spliced, so\n * it falls back to a clean structural re-print ({@link rePrint}).\n */\n\nimport MagicString from 'magic-string';\n\nimport type {\n AttrValue,\n Backend,\n BackendContext,\n Backref,\n ClassList,\n CodegenResult,\n EditPlan,\n ExprRef,\n FileKind,\n IRDocument,\n IRElement,\n IRNode,\n IRNodeId,\n SourceFile,\n SourceSpan,\n} from '@domflax/core';\n\nconst JSX_LANGS: readonly FileKind[] = ['jsx', 'tsx'];\n\ninterface ExprPayload {\n readonly text: string;\n readonly spread: boolean;\n}\n\n/* ───────────────────────── shared expr/class helpers ───────────────────────── */\n\n/** Recover an interned expression's source text (payload first, span-slice fallback). */\nfunction exprText(doc: IRDocument, ref: ExprRef): ExprPayload {\n const rec = doc.exprs.get(ref);\n const payload = rec?.payload as Partial<ExprPayload> | undefined;\n if (payload && typeof payload.text === 'string') {\n return { text: payload.text, spread: payload.spread === true };\n }\n if (rec) {\n const sf = doc.sources.get(rec.span.file);\n if (sf) return { text: sf.text.slice(rec.span.start, rec.span.end), spread: false };\n }\n return { text: '', spread: false };\n}\n\n/** All static class tokens of a {@link ClassList}, in order. */\nfunction staticTokensOf(classes: ClassList): string[] {\n const out: string[] = [];\n for (const seg of classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/* ───────────────────────── surgical (magic-string) codegen ───────────────────────── */\n\n/** Pick the single retained source file this document was parsed from (if any). */\nfunction primarySource(doc: IRDocument): SourceFile | null {\n for (const sf of doc.sources.values()) {\n if (typeof sf.text === 'string' && sf.text.length > 0) return sf;\n }\n return null;\n}\n\n/** Collect every node reachable from the root of the (mutated) tree. */\nfunction collectKept(doc: IRDocument): IRNode[] {\n const out: IRNode[] = [];\n const seen = new Set<IRNodeId>();\n const visit = (id: IRNodeId): void => {\n if (seen.has(id)) return;\n seen.add(id);\n const n = doc.nodes.get(id);\n if (!n) return;\n out.push(n);\n if (n.kind === 'element' || n.kind === 'fragment') for (const c of n.children) visit(c);\n };\n visit(doc.root);\n return out;\n}\n\n/** Span `a` strictly contains span `b` (same file, b nested inside, not identical). */\nfunction strictlyContains(a: SourceSpan, b: SourceSpan): boolean {\n if (a.file !== b.file) return false;\n if (a.start <= b.start && b.end <= a.end) return !(a.start === b.start && a.end === b.end);\n return false;\n}\n\ninterface RemovedRegion {\n readonly backref: Backref;\n /** A surviving node nested inside this region ⇒ this was an UNWRAP (keep inner, drop tags). */\n readonly unwrapped: boolean;\n}\n\n/**\n * Apply the class-list diff for a single surviving element. Returns true if an edit was made.\n */\nfunction editClasses(ms: MagicString, doc: IRDocument, sf: SourceFile, el: IRElement): boolean {\n const classes = el.classes;\n // Wholly dynamic / opaque class lists are never rewritten by the passes — leave verbatim.\n if (classes.hasDynamic || classes.opaque) return false;\n\n const tokens = staticTokensOf(classes);\n const valueSpan = classes.valueSpan;\n\n if (valueSpan && valueSpan.file === sf.id) {\n const current = sf.text.slice(valueSpan.start, valueSpan.end);\n // Preserve the original quote style; default to double quotes when we can't detect one.\n const quote = current.startsWith(\"'\") ? \"'\" : '\"';\n const next = `${quote}${tokens.join(' ')}${quote}`;\n if (current !== next) {\n ms.overwrite(valueSpan.start, valueSpan.end, next);\n return true;\n }\n return false;\n }\n\n // No class attribute originally, but the passes added classes ⇒ insert one on the opening tag.\n if (tokens.length === 0) return false;\n if (el.isComponent) return false; // never synthesize className onto an opaque component\n const back = doc.backref.get(el.id);\n const openTag = back?.openTagSpan;\n if (!openTag || openTag.file !== sf.id) return false;\n // Insert immediately after the tag name: `<tag‸ …`.\n const insertAt = openTag.start + 1 + el.tag.length;\n ms.appendLeft(insertAt, ` className=\"${tokens.join(' ')}\"`);\n return true;\n}\n\n/** Surgical full-module codegen. Returns null when the document has no retained source. */\nfunction surgicalPrint(doc: IRDocument): string | null {\n const sf = primarySource(doc);\n if (!sf) return null;\n\n const ms = new MagicString(sf.text);\n\n const kept = collectKept(doc);\n const keptSpans: SourceSpan[] = [];\n for (const n of kept) if (n.span && n.span.file === sf.id) keptSpans.push(n.span);\n\n // 1) Structural removals. A node present in the backref table but absent from the live node map\n // was removed by the passes. Classify each as an UNWRAP (a surviving node nests inside it) or\n // a FULL removal (nothing survived inside).\n const removed: RemovedRegion[] = [];\n for (const id of backrefIds(doc)) {\n if (doc.nodes.has(id)) continue; // still live\n const back = doc.backref.get(id);\n if (!back || back.span.file !== sf.id) continue;\n const unwrapped = keptSpans.some((k) => strictlyContains(back.span, k));\n removed.push({ backref: back, unwrapped });\n }\n\n // Skip any removed region nested inside a FULL-removal region (its bytes are already deleted by\n // the ancestor) — this keeps every delete disjoint, which magic-string requires.\n const fullRemovals = removed.filter((r) => !r.unwrapped).map((r) => r.backref.span);\n for (const r of removed) {\n const span = r.backref.span;\n const coveredByFull = fullRemovals.some((f) => f !== span && strictlyContains(f, span));\n if (coveredByFull) continue;\n\n if (r.unwrapped) {\n // Delete only the wrapper's tags; keep its (surviving) inner content verbatim.\n const open = r.backref.openTagSpan;\n const close = r.backref.closeTagSpan;\n if (open && open.file === sf.id && open.end > open.start) ms.remove(open.start, open.end);\n if (close && close.file === sf.id && close.end > close.start) {\n ms.remove(close.start, close.end);\n }\n } else {\n ms.remove(span.start, span.end);\n }\n }\n\n // 2) Class-list diffs on every surviving element.\n for (const n of kept) {\n if (n.kind === 'element') editClasses(ms, doc, sf, n);\n }\n\n return ms.toString();\n}\n\n/** All ids the backref table knows about (every originally-parsed element / fragment). */\nfunction backrefIds(doc: IRDocument): IRNodeId[] {\n // The backref table is shared verbatim from parse time; collect ids by scanning original spans we\n // recorded for live + removed nodes. We don't have a public iterator, so reconstruct the universe\n // from the live nodes plus their (now-removed) original ancestry isn't possible directly — instead\n // ask the table for each id we can reach. The table exposes `get`; the set of candidate ids is the\n // contiguous allocation range [1, alloc.peek). Scanning that range is O(n) and dependency-free.\n const out: IRNodeId[] = [];\n const max = doc.alloc.peek as unknown as number;\n for (let i = 1; i < max; i += 1) {\n const id = i as IRNodeId;\n if (doc.backref.get(id)) out.push(id);\n }\n return out;\n}\n\n/* ───────────────────────── structural re-print (fallback) ───────────────────────── */\n\n/** Re-build the `className=…` attribute (or null when the element has no class list). */\nfunction classText(doc: IRDocument, classes: ClassList): string | null {\n if (classes.form === 'absent' || classes.segments.length === 0) return null;\n\n const dynamic = classes.segments.find((s) => s.kind === 'dynamic');\n if (dynamic && dynamic.kind === 'dynamic') {\n return `className={${exprText(doc, dynamic.expr).text}}`;\n }\n\n const tokens = staticTokensOf(classes);\n return `className=\"${tokens.join(' ')}\"`;\n}\n\nfunction attrText(doc: IRDocument, name: string, value: AttrValue): string {\n if (value.kind === 'static') {\n if (value.value === true) return name;\n if (value.value === false) return '';\n return `${name}=\"${String(value.value)}\"`;\n }\n return `${name}={${exprText(doc, value.expr).text}}`;\n}\n\nfunction printElement(doc: IRDocument, el: IRElement): string {\n const parts: string[] = [];\n\n const cls = classText(doc, el.classes);\n if (cls !== null) parts.push(cls);\n\n for (const name of el.attrs.order) {\n const v = el.attrs.entries.get(name);\n if (!v) continue;\n const text = attrText(doc, name, v);\n if (text.length > 0) parts.push(text);\n }\n\n for (const ref of el.attrs.spreads) parts.push(`{...${exprText(doc, ref).text}}`);\n\n const attrStr = parts.length > 0 ? ` ${parts.join(' ')}` : '';\n const tag = el.tag;\n\n if (el.children.length === 0) {\n return el.selfClosing ? `<${tag}${attrStr} />` : `<${tag}${attrStr}></${tag}>`;\n }\n\n const inner = el.children.map((c) => printNode(doc, c)).join('');\n return `<${tag}${attrStr}>${inner}</${tag}>`;\n}\n\nfunction printNode(doc: IRDocument, id: IRNodeId): string {\n const node = doc.nodes.get(id);\n if (!node) return '';\n switch (node.kind) {\n case 'text':\n return node.value;\n case 'comment':\n return `{/*${node.value}*/}`;\n case 'expr': {\n const { text, spread } = exprText(doc, node.expr);\n return spread ? `{...${text}}` : `{${text}}`;\n }\n case 'fragment':\n return `<>${node.children.map((c) => printNode(doc, c)).join('')}</>`;\n case 'element':\n return printElement(doc, node);\n }\n}\n\nfunction rePrint(doc: IRDocument): string {\n const root = doc.nodes.get(doc.root);\n if (!root || root.kind !== 'fragment') return printNode(doc, doc.root);\n return root.children.map((c) => printNode(doc, c)).join('');\n}\n\n/* ───────────────────────── public backend ───────────────────────── */\n\nfunction doPrint(doc: IRDocument): string {\n const surgical = surgicalPrint(doc);\n return surgical ?? rePrint(doc);\n}\n\nexport const jsxBackend: Backend = {\n name: 'babel-jsx',\n langs: JSX_LANGS,\n print(doc: IRDocument, _plan: EditPlan, _ctx: BackendContext): CodegenResult {\n const code = doPrint(doc);\n return { code, map: null, edits: [], diagnostics: [] };\n },\n};\n\n/** Factory mirror — returns a fresh handle to the (stateless) JSX backend. */\nexport function createJsxBackend(): Backend {\n return jsxBackend;\n}\n","/**\n * @domflax/frontend-jsx — Babel JSX ⇄ IR frontend + backend (TYPED STUB, Stage 1).\n *\n * Public surface:\n * • {@link jsxFrontend} / {@link createJsxFrontend} — Frontend (JSX/TSX → IR).\n * • {@link jsxBackend} / {@link createJsxBackend} — Backend (IR → JSX/TSX).\n *\n * Both define the SHAPE only: `parse`/`print` throw NotImplemented; the cheap\n * routing predicates (`canParse`, `langs`, `name`) are real.\n */\n\nexport { jsxFrontend, createJsxFrontend } from './frontend';\nexport { jsxBackend, createJsxBackend } from './backend';\n","/**\n * @domflax/resolver-tailwind — Tailwind-aware {@link StyleResolver}, backed by the REAL Tailwind\n * engine.\n *\n * ## Engine + approach\n *\n * This resolver is backed by **tailwindcss v3** (`resolveConfig` + the JIT context + `generateRules`),\n * NOT v4. The reason is the {@link StyleResolver} contract: `resolve()` is **synchronous**. Tailwind\n * v4's entire programmatic surface (`compile`, `compileAst`, `__unstable__loadDesignSystem`) returns\n * Promises and offers no synchronous design-system constructor, so backing a synchronous resolver\n * with v4 would require blocking-on-promise hacks. Tailwind v3's `createContext(resolveConfig(...))`\n * + `generateRules(candidates, ctx)` pipeline is fully synchronous — it is exactly the path that\n * tooling such as `prettier-plugin-tailwindcss` and the Tailwind IntelliSense engine use — so it\n * backs a synchronous resolver cleanly and is genuinely testable. The task explicitly permits this\n * fallback.\n *\n * ## Forward (`resolve`)\n *\n * `resolve(classes)` feeds each candidate class name to the real engine, reads back the generated\n * CSS rules, and converts them into a normalized, condition-keyed {@link StyleMap}:\n *\n * • a simple `.utility { … }` rule contributes to the unconditional `BASE_CONDITION` block,\n * • a `:hover` / `:focus` / … suffix becomes a `StyleCondition.states` entry,\n * • a `::before` / `::placeholder` / … suffix becomes a `StyleCondition.pseudoElement`,\n * • a wrapping `@media (…)` (responsive variants like `md:`) becomes `StyleCondition.media`.\n *\n * Every declaration is run through the SHARED {@link normalizer} from `@domflax/pattern-kit`, so\n * values are canonical and box shorthands (`p-4`, `gap-4`, `inset-0`, …) expand to longhands exactly\n * the way patterns + verify expect. BASE coverage is the must-have; variant conditions are produced\n * best-effort. Utilities whose selector uses a combinator / compound / attribute selector (e.g.\n * `space-x-4`, `divide-y`) cannot be folded onto the element's own box and are surfaced as\n * {@link OpaqueToken}s rather than contributing misleading declarations. Unknown / unresolvable\n * classes contribute nothing and are reported in `unknown` — `resolve` never throws.\n *\n * ## Reverse (`emit`)\n *\n * `emit(styleMap)` is best-effort reverse synthesis backed by a reverse index built from the engine's\n * own class list (`context.getClassList()`): each indexable utility is generated, its normalized BASE\n * declarations are recorded, and the index is greedily matched against the requested StyleMap\n * (largest declaration-sets first), consuming matched properties so each is mapped to at most one\n * utility. The index is built lazily on first `emit()` and cached.\n *\n * LIMITATION (v0.1.0): `emit` is intentionally less complete than `resolve`. It only matches against\n * the engine's enumerable named utilities and only their unconditional BASE declarations; variant\n * conditions (hover/responsive/pseudo-element) and arbitrary-value utilities are not reverse-synthesized,\n * and no synthetic class is produced for the residual (it is surfaced via `exact:false`). Anything\n * with no matching utility is simply left unmatched — `emit` never throws and never invents a class.\n */\n\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\nimport type {\n CssProperty,\n EmitContext,\n EmitResult,\n OpaqueToken,\n ResolveInput,\n ResolveResult,\n SelectorUsage,\n StyleBlock,\n StyleCondition,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n StyleResolver,\n SyntheticClass,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey, emptyStyleMap } from '@domflax/core';\nimport { normalizer } from '@domflax/pattern-kit';\n\n/* ───────────────────────── engine loading (synchronous v3 internals) ───────────────────────── */\n\n// The forward/reverse engine lives in tailwindcss' CommonJS internals. We load them through\n// `createRequire` (rather than `import`) so the exact same code path works whether this module is\n// bundled to ESM or CJS, and so the untyped internal subpaths don't need ambient declarations.\n//\n// CRITICAL (bundling): tailwindcss must be resolved from the CONSUMER'S project, NOT from the file\n// this module happens to live in. When `domflax` inlines this resolver into its own bundle\n// (`noExternal: [/^@domflax\\//]`), a require based on the bundle's location (`__filename`) would\n// look for `tailwindcss` next to `domflax/dist`, where it does not exist — so the engine silently\n// failed to load and `emit`'s reverse index came up empty. Instead we root the require in the user's\n// project (an explicit project root, then `process.cwd()`), exactly how prettier-plugin-tailwindcss\n// and the Tailwind IntelliSense engine locate a project's Tailwind. The bundle/source location is\n// kept only as a last-resort fallback (covers the non-bundled / in-repo dev case). The first base\n// from which `tailwindcss/package.json` resolves wins.\n\n/**\n * This module's own location, used as a last-resort require base. esbuild substitutes a real\n * `__filename` in a CJS bundle; in an ESM bundle `__filename` is undefined and we fall back to\n * `import.meta.url` (a `file://` URL, which `createRequire` accepts).\n */\nfunction moduleBase(): string {\n return typeof __filename === 'string' ? __filename : import.meta.url;\n}\n\n/**\n * Build a `require` rooted in the consumer's project so engine resolution is independent of where\n * this (possibly bundled) module physically lives. Returns `null` if `tailwindcss` resolves from no\n * candidate base.\n */\nfunction projectRequire(projectRoot?: string): NodeRequire | null {\n const bases: string[] = [];\n // A real file name is irrelevant — `createRequire` only uses the containing directory for\n // resolution; the file need not exist.\n if (projectRoot) bases.push(path.join(projectRoot, '__domflax__.js'));\n bases.push(path.join(process.cwd(), '__domflax__.js'));\n bases.push(moduleBase());\n for (const base of bases) {\n try {\n const candidate = createRequire(base);\n candidate.resolve('tailwindcss/package.json');\n return candidate;\n } catch {\n /* try the next base */\n }\n }\n return null;\n}\n\ninterface TwGeneratedDecl {\n readonly type: 'decl';\n readonly prop: string;\n readonly value: string;\n readonly important?: boolean;\n}\ninterface TwGeneratedRule {\n readonly type: 'rule';\n readonly selector: string;\n readonly nodes?: readonly TwNode[];\n}\ninterface TwGeneratedAtRule {\n readonly type: 'atrule';\n readonly name: string;\n readonly params: string;\n readonly nodes?: readonly TwNode[];\n}\ntype TwNode = TwGeneratedDecl | TwGeneratedRule | TwGeneratedAtRule | { readonly type: string };\n\ninterface TwContext {\n getClassList(): unknown[];\n}\n\ninterface TwEngine {\n readonly version: string;\n readonly context: TwContext;\n /** Generate the postcss rule nodes Tailwind emits for the given candidate class names. */\n generate(candidates: readonly string[]): TwNode[];\n}\n\n/** Build a synchronous Tailwind v3 engine for the given resolved config; returns `null` on failure. */\nfunction loadEngine(options: TailwindResolverConfig): TwEngine | null {\n const req = projectRequire(options.projectRoot);\n if (!req) return null;\n try {\n const resolveConfig = req('tailwindcss/resolveConfig.js') as (c: unknown) => unknown;\n const { createContext } = req('tailwindcss/lib/lib/setupContextUtils.js') as {\n createContext: (config: unknown) => TwContext;\n };\n const { generateRules } = req('tailwindcss/lib/lib/generateRules.js') as {\n generateRules: (candidates: Set<string>, context: TwContext) => Array<[number, TwNode]>;\n };\n const pkg = req('tailwindcss/package.json') as { version: string };\n\n let userConfig: unknown = options.config ?? { content: [{ raw: '' }] };\n if (options.configPath !== undefined) {\n const loadConfig = req('tailwindcss/loadConfig.js') as (p: string) => unknown;\n userConfig = loadConfig(options.configPath);\n }\n const resolved = resolveConfig(userConfig);\n const context = createContext(resolved);\n\n return {\n version: pkg.version,\n context,\n generate(candidates: readonly string[]): TwNode[] {\n const rules = generateRules(new Set(candidates), context);\n return rules.map(([, node]) => node);\n },\n };\n } catch {\n return null;\n }\n}\n\n/* ───────────────────────── configuration ───────────────────────── */\n\n/** Construction-time configuration for {@link createTailwindResolver}. */\nexport interface TailwindResolverConfig {\n /** Provider tag surfaced via {@link StyleResolver.provider}. Defaults to the engine version. */\n readonly provider?: string;\n /**\n * Cache-busting fingerprint. Defaults to a hash derived from the resolved Tailwind config (theme\n * etc.) combined with the provider tag, so it changes when the theme/config changes.\n */\n readonly fingerprint?: string;\n /**\n * A Tailwind (v3) config object, merged with the framework defaults via `resolveConfig`. Mutually\n * exclusive with {@link configPath} (path wins). Defaults to `{ content: [{ raw: '' }] }`.\n */\n readonly config?: Record<string, unknown>;\n /** Path to a project `tailwind.config.{js,cjs,mjs,ts}` file, loaded synchronously. */\n readonly configPath?: string;\n /**\n * Directory to resolve `tailwindcss` (and its v3 internals) from. Defaults to `process.cwd()`,\n * falling back to this module's location. Set this when the consumer's project root differs from\n * the working directory. Resolution is intentionally independent of where domflax's bundle lives.\n */\n readonly projectRoot?: string;\n}\n\n/* ───────────────────────── selector / condition parsing ───────────────────────── */\n\n/** Pseudo-elements that Tailwind may emit with a legacy single colon. */\nconst LEGACY_PSEUDO_ELEMENTS = new Set([\n ':before',\n ':after',\n ':first-line',\n ':first-letter',\n]);\n\ntype ParsedSelector =\n | { readonly kind: 'simple'; readonly states: readonly string[]; readonly pseudoElement: string }\n | { readonly kind: 'complex' };\n\n/**\n * Parse a generated selector into a {@link StyleCondition} fragment. Accepts ONLY a single class\n * selector optionally followed by pseudo-class / pseudo-element parts (`.x`, `.x:hover`,\n * `.x::before`, `.x:focus:hover`). Anything with a combinator, a second compound class, an attribute\n * selector, or a selector list is `complex` (⇒ opaque) because its declarations do not apply to the\n * element's own box.\n */\nfunction parseSelector(selector: string): ParsedSelector {\n const sel = selector.trim();\n if (sel.length === 0 || sel[0] !== '.') return { kind: 'complex' };\n\n // Consume the class identifier, honoring CSS backslash escapes (`\\:`, `\\/`, `\\[`, …).\n let i = 1;\n for (; i < sel.length; i += 1) {\n const c = sel[i]!;\n if (c === '\\\\') {\n i += 1; // skip the escaped char\n continue;\n }\n if (c === ':' || c === '.' || c === '[' || c === ' ' || c === '>' || c === '+' || c === '~' || c === ',') {\n break;\n }\n }\n\n const remainder = sel.slice(i);\n if (remainder.length === 0) {\n return { kind: 'simple', states: [], pseudoElement: '' };\n }\n // The remainder must be EXCLUSIVELY pseudo parts — no combinator / compound / attribute follows.\n if (!/^(?:::?[-a-z]+(?:\\([^()]*\\))?)+$/i.test(remainder)) {\n return { kind: 'complex' };\n }\n\n const parts = remainder.match(/::?[-a-z]+(?:\\([^()]*\\))?/gi) ?? [];\n const states: string[] = [];\n let pseudoElement = '';\n for (const part of parts) {\n if (part.startsWith('::') || LEGACY_PSEUDO_ELEMENTS.has(part)) {\n pseudoElement = part.startsWith('::') ? part : `:${part}`;\n } else {\n states.push(part);\n }\n }\n return { kind: 'simple', states, pseudoElement };\n}\n\nfunction makeCondition(media: string, states: readonly string[], pseudoElement: string): StyleCondition {\n return {\n media,\n states: [...new Set(states)].sort(),\n pseudoElement,\n };\n}\n\n/* ───────────────────────── rule extraction ───────────────────────── */\n\ninterface ExtractedBlock {\n readonly condition: StyleCondition;\n readonly decls: ReadonlyArray<readonly [string, string, boolean]>;\n}\n\ninterface ExtractedToken {\n /** Usable (BASE + supported-variant) blocks. */\n readonly blocks: readonly ExtractedBlock[];\n /** True if the engine emitted at least one rule for the token (even an opaque one). */\n readonly produced: boolean;\n /** Set when the token only resolves via combinator / unsupported at-rule selectors. */\n readonly opaque?: OpaqueToken;\n}\n\n/** Collect every leaf `rule` node together with the `@media` stack that wraps it. */\nfunction collectRules(\n node: TwNode,\n mediaStack: readonly string[],\n inUnsupportedAtRule: boolean,\n out: Array<{ rule: TwGeneratedRule; media: readonly string[]; unsupported: boolean }>,\n): void {\n if (node.type === 'rule') {\n out.push({ rule: node as TwGeneratedRule, media: mediaStack, unsupported: inUnsupportedAtRule });\n return;\n }\n if (node.type === 'atrule') {\n const at = node as TwGeneratedAtRule;\n const children = at.nodes ?? [];\n if (at.name === 'media') {\n const nextStack = at.params ? [...mediaStack, at.params] : mediaStack;\n for (const child of children) collectRules(child, nextStack, inUnsupportedAtRule, out);\n } else {\n // @supports / @container / etc. — recurse but flag as unsupported (⇒ opaque).\n for (const child of children) collectRules(child, mediaStack, true, out);\n }\n }\n}\n\n/** Extract usable blocks + opacity info for a single candidate token from its generated nodes. */\nfunction extractToken(token: string, nodes: readonly TwNode[]): ExtractedToken {\n if (nodes.length === 0) return { blocks: [], produced: false };\n\n const leaves: Array<{ rule: TwGeneratedRule; media: readonly string[]; unsupported: boolean }> = [];\n for (const node of nodes) collectRules(node, [], false, leaves);\n\n const blocks: ExtractedBlock[] = [];\n let sawComplex = false;\n\n for (const { rule, media, unsupported } of leaves) {\n const parsed = parseSelector(rule.selector);\n if (parsed.kind === 'complex' || unsupported) {\n sawComplex = true;\n continue;\n }\n const decls: Array<readonly [string, string, boolean]> = [];\n for (const child of rule.nodes ?? []) {\n if (child.type !== 'decl') continue; // skip @defaults markers, comments, nested rules\n const d = child as TwGeneratedDecl;\n if (typeof d.value !== 'string') continue;\n decls.push([d.prop, d.value, d.important === true]);\n }\n if (decls.length === 0) continue;\n const mediaQuery = media.join(' and ');\n blocks.push({ condition: makeCondition(mediaQuery, parsed.states, parsed.pseudoElement), decls });\n }\n\n const opaque: OpaqueToken | undefined =\n sawComplex && blocks.length === 0\n ? { token, reason: 'combinator-variant', detail: 'utility targets descendants/siblings, not its own box' }\n : undefined;\n\n return { blocks, produced: true, opaque };\n}\n\n/* ───────────────────────── StyleMap assembly ───────────────────────── */\n\nfunction buildStyleMap(\n blockMaps: Map<string, { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }>,\n): StyleMap {\n if (blockMaps.size === 0) return emptyStyleMap();\n const blocks = new Map<ReturnType<typeof conditionKey>, StyleBlock>();\n for (const { condition, decls } of blockMaps.values()) {\n if (decls.size === 0) continue;\n blocks.set(conditionKey(condition), { condition, decls });\n }\n if (blocks.size === 0) return emptyStyleMap();\n return normalizer.normalizeStyleMap({ blocks });\n}\n\n/**\n * The shadow chain a newly-winning declaration inherits when it overrides `prev` on the same\n * property: everything `prev` already shadowed, plus `prev`'s own origin (now shadowed too). Deduped\n * by class name and restricted to class origins (the only kind `dedupe-classes` acts on).\n */\nfunction shadowedBy(prev: StyleDecl): readonly StyleOrigin[] | undefined {\n const out: StyleOrigin[] = [];\n const seen = new Set<string>();\n const add = (o: StyleOrigin | undefined): void => {\n if (!o || o.kind !== 'class' || seen.has(o.className)) return;\n seen.add(o.className);\n out.push(o);\n };\n for (const o of prev.shadowed ?? []) add(o);\n add(prev.origin);\n return out.length > 0 ? out : undefined;\n}\n\n/* ───────────────────────── conservative selector usage ───────────────────────── */\n\n/**\n * A conservative, never-droppable {@link SelectorUsage}. Until a real project selector graph exists\n * we must assume a class could be referenced in any unsafe position, so nothing is safe to rewrite.\n */\nconst OPAQUE_USAGE: SelectorUsage = {\n asSubject: true,\n asAncestor: true,\n asCompound: true,\n asSibling: true,\n asHasArgument: true,\n asStructural: true,\n droppable: false,\n};\n\n/**\n * A plain-subject {@link SelectorUsage}: the class is a resolver-owned, base-only utility whose\n * whole effect is reproducible from `computed`, so it is safe to drop/replace during reverse-emit.\n */\nconst DROPPABLE_USAGE: SelectorUsage = {\n asSubject: true,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n droppable: true,\n};\n\n/* ───────────────────────── fingerprint ───────────────────────── */\n\n/** Tiny, dependency-free FNV-1a string hash (hex). Used to derive the cache-busting fingerprint. */\nfunction fnv1a(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i += 1) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/* ───────────────────────── the resolver ───────────────────────── */\n\nclass TailwindResolver implements StyleResolver {\n readonly id = 'tailwind';\n readonly provider: string;\n readonly fingerprint: string;\n\n readonly #engine: TwEngine | null;\n /** Per-token extraction cache (engine output is pure for a fixed config). */\n readonly #tokenCache = new Map<string, ExtractedToken>();\n /** Per-class-set forward-resolution cache. */\n readonly #resolveCache = new Map<string, ResolveResult>();\n /** Lazily built reverse index for {@link emit}. */\n #reverseIndex: ReadonlyArray<readonly [string, ReadonlyMap<CssProperty, string>]> | null = null;\n\n constructor(config: TailwindResolverConfig = {}) {\n this.#engine = loadEngine(config);\n this.provider =\n config.provider ?? (this.#engine ? `tailwindcss@${this.#engine.version}` : 'tailwindcss');\n const seed = JSON.stringify(config.config ?? {}) + (config.configPath ?? '');\n this.fingerprint = config.fingerprint ?? `${this.provider}/${fnv1a(seed)}`;\n }\n\n /** Engine-backed, cached single-token extraction. */\n #extract(token: string): ExtractedToken {\n const cached = this.#tokenCache.get(token);\n if (cached) return cached;\n let result: ExtractedToken;\n if (!this.#engine) {\n result = { blocks: [], produced: false };\n } else {\n try {\n result = extractToken(token, this.#engine.generate([token]));\n } catch {\n result = { blocks: [], produced: false };\n }\n }\n this.#tokenCache.set(token, result);\n return result;\n }\n\n owns(token: string): boolean {\n if (token.length === 0) return false;\n return this.#extract(token).produced;\n }\n\n resolve(input: ResolveInput): ResolveResult {\n const key = JSON.stringify(input.classes);\n const cached = this.#resolveCache.get(key);\n if (cached) return cached;\n\n // condition-key → { condition, longhand decls }. Iterating classes in source order means later\n // utilities overwrite earlier ones on the same property (equal-specificity cascade).\n const blockMaps = new Map<\n string,\n { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }\n >();\n const resolved: string[] = [];\n const unknown: string[] = [];\n const opaque: OpaqueToken[] = [];\n\n input.classes.forEach((token, tokenIndex) => {\n const extracted = this.#extract(token);\n if (!extracted.produced) {\n unknown.push(token);\n return;\n }\n if (extracted.opaque) opaque.push(extracted.opaque);\n if (extracted.blocks.length === 0) return; // produced only opaque rules\n\n const origin: StyleOrigin = { kind: 'class', tokenIndex, className: token };\n let contributed = false;\n for (const block of extracted.blocks) {\n const ck = conditionKey(block.condition);\n let bucket = blockMaps.get(ck);\n if (!bucket) {\n bucket = { condition: block.condition, decls: new Map() };\n blockMaps.set(ck, bucket);\n }\n for (const [prop, value, important] of block.decls) {\n for (const decl of normalizer.normalizeDeclaration(prop, value, important)) {\n // Record provenance: a LATER token on the same property shadows the earlier one. The\n // overridden origin (plus anything it already shadowed) is carried in `shadowed`, which\n // is exactly what the `dedupe-classes` pattern reads to find fully-overridden tokens.\n // This only enriches decl metadata — the resolved VALUES are unchanged.\n const prev = bucket.decls.get(decl.property);\n const shadowed = prev ? shadowedBy(prev) : undefined;\n bucket.decls.set(decl.property, shadowed ? { ...decl, origin, shadowed } : { ...decl, origin });\n contributed = true;\n }\n }\n }\n if (contributed) resolved.push(token);\n });\n\n const result: ResolveResult = {\n styles: buildStyleMap(blockMaps),\n resolved,\n unknown,\n opaque,\n warnings: [],\n };\n this.#resolveCache.set(key, result);\n return result;\n }\n\n /**\n * Lazily build the reverse index from the engine's own enumerable class list. Each indexable\n * utility maps to its NORMALIZED BASE longhand declarations (property → canonical value). Utilities\n * with variant conditions, combinator selectors, or no BASE declarations are skipped. Sorted by\n * declaration count (desc) so greedier (shorthand-like) utilities are tried first.\n */\n #buildReverseIndex(): ReadonlyArray<readonly [string, ReadonlyMap<CssProperty, string>]> {\n if (this.#reverseIndex) return this.#reverseIndex;\n const index: Array<readonly [string, Map<CssProperty, string>]> = [];\n if (this.#engine) {\n try {\n const classes = this.#engine.context\n .getClassList()\n .filter((c): c is string => typeof c === 'string');\n const nodes = this.#engine.generate(classes);\n // Re-extract per class would be costly; instead group decls by their (single) class selector.\n for (const node of nodes) {\n if (node.type !== 'rule') continue; // skip @media / @keyframes wrappers (⇒ variants only)\n const rule = node as TwGeneratedRule;\n const parsed = parseSelector(rule.selector);\n if (parsed.kind !== 'simple' || parsed.states.length > 0 || parsed.pseudoElement !== '') {\n continue; // BASE-only\n }\n const className = unescapeClass(rule.selector);\n if (className === null) continue;\n const decls = new Map<CssProperty, string>();\n for (const child of rule.nodes ?? []) {\n if (child.type !== 'decl') continue;\n const d = child as TwGeneratedDecl;\n if (typeof d.value !== 'string') continue;\n for (const decl of normalizer.normalizeDeclaration(d.prop, d.value, d.important === true)) {\n decls.set(decl.property, String(decl.value));\n }\n }\n if (decls.size > 0) index.push([className, decls]);\n }\n } catch {\n /* leave index empty on failure — emit degrades to a no-op */\n }\n }\n index.sort((a, b) => b[1].size - a[1].size || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n this.#reverseIndex = index;\n return index;\n }\n\n emit(styles: StyleMap, ctx: EmitContext): EmitResult {\n const norm = ctx.normalizer ?? normalizer;\n const normalized = norm.normalizeStyleMap(styles);\n const base = normalized.blocks.get(conditionKey(BASE_CONDITION));\n if (!base || base.decls.size === 0) return { classes: [], exact: true, warnings: [] };\n\n // Only the BASE block is reverse-synthesized (see module LIMITATION). Any non-base condition\n // present in the target means we cannot be exact.\n const hasNonBase = normalized.blocks.size > 1;\n\n // The target longhand map. The IR's compress passes hand us SHORTHAND properties (`padding`,\n // `margin`, `inset`, `inset-block`, `inset-inline`, `size`); we expand them to the same longhand\n // basis the reverse index is keyed on, so a single shorthand utility (`p-4`, `size-4`, `inset-0`)\n // can cover them.\n const target = new Map<CssProperty, string>();\n for (const [prop, decl] of base.decls) {\n for (const [lp, lv] of expandForEmit(norm, String(prop), String(decl.value), decl.important)) {\n target.set(lp, lv);\n }\n }\n\n // Keep only utilities every one of whose declarations matches the target (an exact-fit subset);\n // emitting a utility that sets an unwanted property/value would change the computed style.\n const candidates: Array<readonly [string, ReadonlyMap<CssProperty, string>]> = [];\n for (const entry of this.#buildReverseIndex()) {\n const [, declMap] = entry;\n if (declMap.size === 0 || declMap.size > target.size) continue;\n let fits = true;\n for (const [prop, value] of declMap) {\n if (target.get(prop) !== value) {\n fits = false;\n break;\n }\n }\n if (fits) candidates.push(entry);\n }\n\n // Greedy set-cover: repeatedly take the candidate covering the MOST still-needed declarations,\n // so a shorthand (`p-4`, 4 decls) beats `px-4`+`py-4`. Ties break toward the tighter decl-set\n // then lexicographically, for deterministic output.\n const remaining = new Map(target);\n const classes: string[] = [];\n while (remaining.size > 0) {\n let best: readonly [string, ReadonlyMap<CssProperty, string>] | null = null;\n let bestCover = 0;\n for (const entry of candidates) {\n const [token, declMap] = entry;\n let cover = 0;\n for (const prop of declMap.keys()) if (remaining.has(prop)) cover += 1;\n if (cover === 0) continue;\n const better =\n best === null ||\n cover > bestCover ||\n (cover === bestCover && declMap.size < best[1].size) ||\n (cover === bestCover && declMap.size === best[1].size && token < best[0]);\n if (better) {\n best = entry;\n bestCover = cover;\n }\n }\n if (!best) break; // nothing covers any still-needed declaration → residual\n classes.push(best[0]);\n for (const prop of best[1].keys()) remaining.delete(prop);\n }\n\n const exact = remaining.size === 0 && !hasNonBase;\n if (remaining.size === 0) return { classes, exact, warnings: [] };\n\n // Surface what no utility could cover as a residual synthetic (never thrown, never invented).\n const residual = synthesizeResidual(remaining, ctx);\n return residual\n ? { classes, residual, exact, warnings: [] }\n : { classes, exact, warnings: [] };\n }\n\n selectorUsage(token: string): SelectorUsage {\n // No project selector graph yet, so we cannot know how a CUSTOM (non-Tailwind) class is\n // referenced — treat it as load-bearing (preserved verbatim). A resolver-OWNED utility, by\n // contrast, is safe to drop/replace iff its whole effect is reproducible from `computed`: it\n // must be a plain (non-opaque) utility contributing ONLY base-condition declarations. Opaque\n // (combinator/at-rule) and variant-bound utilities are kept, because `emit` cannot rebuild them.\n const ex = this.#extract(token);\n if (!ex.produced || ex.opaque) return OPAQUE_USAGE;\n const baseOnly =\n ex.blocks.length > 0 &&\n ex.blocks.every((b) => conditionKey(b.condition) === conditionKey(BASE_CONDITION));\n if (!baseOnly) return OPAQUE_USAGE;\n return DROPPABLE_USAGE;\n }\n}\n\n/* ───────────────────────── emit-side shorthand expansion ───────────────────────── */\n\n/**\n * Expand a single computed declaration into the canonical LONGHAND `[property, value]` pairs the\n * reverse index is keyed on. The shared normalizer already expands the physical box shorthands\n * (`padding`/`margin`/`inset`/`border-*`); we additionally expand the few logical shorthands the\n * compress passes synthesize that the normalizer leaves intact (`size`, `inset-block`,\n * `inset-inline`). Values are re-canonicalized via the normalizer so they match the index exactly.\n */\nfunction expandForEmit(\n norm: { normalizeDeclaration: typeof normalizer.normalizeDeclaration },\n prop: string,\n value: string,\n important: boolean,\n): Array<readonly [CssProperty, string]> {\n const pairsFor = (p: string, v: string): Array<readonly [CssProperty, string]> =>\n norm.normalizeDeclaration(p, v, important).map((d) => [d.property, String(d.value)] as const);\n\n if (prop === 'size') {\n return [...pairsFor('width', value), ...pairsFor('height', value)];\n }\n if (prop === 'inset-block' || prop === 'inset-inline') {\n const parts = value.split(/\\s+/).filter((s) => s.length > 0);\n const a = parts[0] ?? value;\n const b = parts[1] ?? a;\n const sides = prop === 'inset-block' ? (['top', 'bottom'] as const) : (['left', 'right'] as const);\n return [...pairsFor(sides[0], a), ...pairsFor(sides[1], b)];\n }\n return pairsFor(prop, value);\n}\n\n/** Build a residual {@link SyntheticClass} for declarations no utility covered; `null` on failure. */\nfunction synthesizeResidual(\n remaining: ReadonlyMap<CssProperty, string>,\n ctx: EmitContext,\n): SyntheticClass | undefined {\n if (remaining.size === 0) return undefined;\n const norm = ctx.normalizer ?? normalizer;\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, value] of remaining) {\n for (const decl of norm.normalizeDeclaration(String(prop), value, false)) {\n decls.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls };\n const styleMap: StyleMap = { blocks: new Map([[conditionKey(BASE_CONDITION), block]]) };\n const css = [...remaining].map(([p, v]) => `${p}:${v}`).join(';');\n const className = `df-${fnv1a(css)}`;\n const synthetic: SyntheticClass = { className, decls: styleMap, css: `.${className}{${css}}` };\n try {\n ctx.sink.register(synthetic);\n } catch {\n /* a sink that rejects registration must not break emit */\n }\n return synthetic;\n}\n\n/** Recover a class name from a simple `.escaped-class` selector, or `null` if it isn't simple. */\nfunction unescapeClass(selector: string): string | null {\n const sel = selector.trim();\n if (sel[0] !== '.') return null;\n let out = '';\n for (let i = 1; i < sel.length; i += 1) {\n const c = sel[i]!;\n if (c === '\\\\') {\n i += 1;\n if (i < sel.length) out += sel[i];\n continue;\n }\n if (c === ':' || c === '.' || c === '[' || c === ' ' || c === '>' || c === '+' || c === '~' || c === ',') {\n return null; // not a bare single-class selector\n }\n out += c;\n }\n return out.length > 0 ? out : null;\n}\n\n/** Factory: build a Tailwind-backed {@link StyleResolver}. */\nexport function createTailwindResolver(config?: TailwindResolverConfig): StyleResolver {\n return new TailwindResolver(config);\n}\n","/**\n * @domflax/resolver-css — a {@link StyleResolver} backed by the project's own CSS files.\n *\n * Role: parse user-authored stylesheets with postcss, index every selector + declaration block, and\n * answer the resolver contract for plain `class=\"…\"` tokens:\n *\n * • `resolve(classes)` — FORWARD. Union the declarations of every rule whose selector is a simple\n * `.class` selector (optionally qualified by state pseudo-classes / a pseudo-element / wrapped in\n * an `@media`, which become {@link StyleCondition}s) into a normalized, condition-keyed\n * {@link StyleMap}. The shared {@link normalizer} expands shorthands and canonicalizes values so\n * resolver + patterns + verify agree byte-for-byte. Equal-specificity single-class rules cascade\n * by SOURCE order (later wins); BASE is the unconditional must-have block.\n * • `emit(styles)` — REVERSE. Best-effort map a {@link StyleMap} back to the minimal set of existing\n * class names whose own declarations are all present in the target. If nothing matches it returns\n * no classes and `exact:false`; it never throws.\n * • `selectorUsage(token)` — how a class participates in project selectors (subject / ancestor /\n * sibling / compound / `:has()` argument / structural pseudo), driving compress safety. Backed by\n * postcss-selector-parser so combinator and structural-pseudo facts are accurate.\n * • {@link CustomCSSResolver.complexSelectors} — the list of COMPLEX selectors (anything with a\n * combinator or a structural pseudo). This feeds domflax's CSS-selector-safety guard.\n *\n * CSS is accepted as raw sources (id + text) and/or as file paths read synchronously from disk, so\n * the resolver is fully unit-testable without touching the filesystem. Malformed CSS never throws —\n * an unparseable stylesheet simply contributes nothing; only genuine input errors (e.g. an\n * unreadable file path) surface as thrown errors.\n */\n\nimport type {\n ConditionKey,\n CssProperty,\n EmitContext,\n EmitResult,\n ResolveInput,\n ResolveResult,\n SelectorUsage,\n StyleBlock,\n StyleCondition,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n StyleResolver,\n} from '@domflax/core';\nimport { conditionKey, emptyStyleMap } from '@domflax/core';\nimport { normalizer } from '@domflax/pattern-kit';\nimport { readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport type { AtRule, Root as PostcssRoot, Rule } from 'postcss';\nimport type selectorParser from 'postcss-selector-parser';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Lazy engine loading (postcss + postcss-selector-parser)\n * ────────────────────────────────────────────────────────────────────────── *\n *\n * postcss and postcss-selector-parser are OPTIONAL peers of the published `domflax` package: a\n * Tailwind-only user need not install them. They must therefore be loaded LAZILY (only when this\n * resolver is actually constructed) and from the CONSUMER'S project — never via a static top-level\n * `import`, which would (a) crash on module load for a postcss-less install and (b), once this\n * resolver is inlined into domflax's bundle, resolve relative to `domflax/dist` instead of the\n * user's project. We root the require in `process.cwd()` (or an explicit project root), exactly as\n * the Tailwind resolver does, with the bundle/source location as a last-resort fallback.\n */\n\n/** This module's own location — esbuild fills `__filename` in CJS; ESM falls back to `import.meta.url`. */\nfunction moduleBase(): string {\n return typeof __filename === 'string' ? __filename : import.meta.url;\n}\n\n/** The single postcss entry point this resolver calls at runtime. */\ntype PostcssParseApi = (css: string, opts?: { from?: string }) => PostcssRoot;\n\n/** The subset of the postcss-selector-parser API this resolver calls at runtime (guards preserve narrowing). */\ninterface SelectorParserApi {\n (): { astSync(selector: string): selectorParser.Root };\n isClassName(n: selectorParser.Node): n is selectorParser.ClassName;\n isTag(n: selectorParser.Node): n is selectorParser.Tag;\n isIdentifier(n: selectorParser.Node): n is selectorParser.Identifier;\n isAttribute(n: selectorParser.Node): n is selectorParser.Attribute;\n isUniversal(n: selectorParser.Node): n is selectorParser.Universal;\n isNesting(n: selectorParser.Node): n is selectorParser.Nesting;\n isPseudo(n: selectorParser.Node): n is selectorParser.Pseudo;\n isPseudoClass(n: selectorParser.Node): n is selectorParser.Pseudo;\n isPseudoElement(n: selectorParser.Node): n is selectorParser.Pseudo;\n isCombinator(n: selectorParser.Node): n is selectorParser.Combinator;\n}\n\ninterface PostcssEngine {\n readonly parse: PostcssParseApi;\n readonly selectorParser: SelectorParserApi;\n}\n\n/** Resolve postcss + postcss-selector-parser from the consumer's project; `null` if unavailable. */\nfunction loadPostcssEngine(projectRoot?: string): PostcssEngine | null {\n const bases: string[] = [];\n if (projectRoot) bases.push(path.join(projectRoot, '__domflax__.js'));\n bases.push(path.join(process.cwd(), '__domflax__.js'));\n bases.push(moduleBase());\n for (const base of bases) {\n try {\n const req = createRequire(base);\n req.resolve('postcss');\n req.resolve('postcss-selector-parser');\n const postcss = req('postcss') as { parse: PostcssParseApi };\n const raw = req('postcss-selector-parser') as SelectorParserApi & { default?: SelectorParserApi };\n // postcss-selector-parser is CJS with a default export under interop; accept both shapes.\n const selector = raw.default ?? raw;\n return { parse: postcss.parse, selectorParser: selector };\n } catch {\n /* try the next base */\n }\n }\n return null;\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Public input shapes\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** A single user-authored stylesheet handed to the resolver as raw text. */\nexport interface CssFile {\n /** Stable identifier (usually the absolute path) — also feeds the fingerprint. */\n readonly id: string;\n /** Verbatim stylesheet text. */\n readonly css: string;\n}\n\n/** Construction options for {@link CustomCSSResolver}. */\nexport interface CssResolverOptions {\n /** Overrides the auto-derived cache-busting fingerprint (e.g. a content hash from the caller). */\n readonly fingerprint?: string;\n /**\n * Additional stylesheet paths read synchronously from disk and appended to the raw `cssFiles`.\n * A path that cannot be read is a genuine input error and is rethrown with context.\n */\n readonly files?: readonly string[];\n /**\n * Directory to resolve `postcss` / `postcss-selector-parser` from. Defaults to `process.cwd()`,\n * falling back to this module's location. Resolution is independent of where domflax's bundle lives.\n */\n readonly projectRoot?: string;\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Lazily-loaded postcss engine (module singleton)\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Runtime postcss `parse`, populated on first resolver construction. */\nlet pc: PostcssParseApi | null = null;\n/** Runtime postcss-selector-parser, populated on first resolver construction. */\nlet sp: SelectorParserApi | null = null;\n\n/** Ensure the postcss engine is loaded; throws a clear error if the optional peers are absent. */\nfunction ensurePostcss(projectRoot?: string): void {\n if (pc && sp) return;\n const engine = loadPostcssEngine(projectRoot);\n if (!engine) {\n throw new Error(\n '@domflax/resolver-css requires \"postcss\" and \"postcss-selector-parser\" to be installed in ' +\n 'your project (they are optional peer dependencies of domflax, loaded only when the custom-CSS ' +\n 'provider is used). Install them with: npm install postcss postcss-selector-parser',\n );\n }\n pc = engine.parse;\n sp = engine.selectorParser;\n}\n\n/** Stable resolver id surfaced on {@link StyleResolver.id}. */\nexport const CSS_RESOLVER_ID = 'css';\n\n/** Provider tag surfaced on {@link StyleResolver.provider}. */\nexport const CSS_RESOLVER_PROVIDER = 'custom-css';\n\n/** Version stamp for the index/cascade machinery; bump when its semantics change (cache-busting). */\nconst ENGINE_VERSION = 'css-index@1';\n\n/** Structural pseudo-classes — their presence makes a class structurally targeted (review-1 blocker). */\nconst STRUCTURAL_PSEUDOS: ReadonlySet<string> = new Set([\n ':nth-child',\n ':nth-last-child',\n ':first-child',\n ':last-child',\n ':only-child',\n ':nth-of-type',\n ':nth-last-of-type',\n ':first-of-type',\n ':last-of-type',\n ':only-of-type',\n]);\n\n/** Functional pseudos whose argument is itself a selector list — opaque to forward resolution. */\nconst FUNCTIONAL_PSEUDOS: ReadonlySet<string> = new Set([\n ':not',\n ':is',\n ':where',\n ':has',\n ':matches',\n]);\n\n/** Legacy single-colon pseudo-ELEMENTS that the parser may not flag via `isPseudoElement`. */\nconst LEGACY_PSEUDO_ELEMENTS: ReadonlySet<string> = new Set([\n ':before',\n ':after',\n ':first-line',\n ':first-letter',\n]);\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Internal index shapes\n * ────────────────────────────────────────────────────────────────────────── */\n\ntype RawDecl = readonly [property: string, value: string, important: boolean];\n\n/** One simple-`.class` rule's contribution, tagged with its document position for cascade ordering. */\ninterface RuleEntry {\n readonly order: number;\n readonly token: string;\n readonly condition: StyleCondition;\n readonly decls: readonly RawDecl[];\n}\n\ninterface MutableUsage {\n referenced: boolean;\n asSubject: boolean;\n asAncestor: boolean;\n asCompound: boolean;\n asSibling: boolean;\n asHasArgument: boolean;\n asStructural: boolean;\n /** Appears anywhere other than as the lone subject of a bare `.x {}` selector. */\n loadBearing: boolean;\n}\n\ninterface ReverseEntry {\n readonly token: string;\n /** `${conditionKey}\u0000${property}` → canonical value, over this class's own resolution. */\n readonly keyed: ReadonlyMap<string, string>;\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * CustomCSSResolver\n * ────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Resolves plain CSS classes against a fixed set of project stylesheets parsed with postcss.\n */\nexport class CustomCSSResolver implements StyleResolver {\n public readonly id: string = CSS_RESOLVER_ID;\n public readonly provider: string = CSS_RESOLVER_PROVIDER;\n public readonly fingerprint: string;\n\n readonly #files: readonly CssFile[];\n /** Forward map: class token → simple-`.class` rule contributions (source order). */\n readonly #classIndex = new Map<string, RuleEntry[]>();\n /** Selector-participation facts per class token. */\n readonly #usage = new Map<string, MutableUsage>();\n /** Every class referenced anywhere in the stylesheets (forward-resolvable or not). */\n readonly #known = new Set<string>();\n /** Distinct COMPLEX selectors (combinator or structural pseudo), sorted. */\n readonly #complex: readonly string[];\n\n #reverse: readonly ReverseEntry[] | null = null;\n\n public constructor(cssFiles: readonly CssFile[] = [], options: CssResolverOptions = {}) {\n ensurePostcss(options.projectRoot);\n const fromDisk = (options.files ?? []).map(readCssPath);\n this.#files = [...cssFiles, ...fromDisk];\n this.fingerprint = options.fingerprint ?? deriveFingerprint(this.provider, this.#files);\n\n const complex = new Set<string>();\n let order = 0;\n for (const file of this.#files) {\n order = this.#indexFile(file, order, complex);\n }\n this.#complex = [...complex].sort();\n }\n\n /** The stylesheets this resolver was constructed with (raw sources + any read from disk). */\n public get files(): readonly CssFile[] {\n return this.#files;\n }\n\n /** Owns any plain class token referenced by one of {@link files}. */\n public owns(token: string): boolean {\n return isPlainClassToken(token) && this.#known.has(token);\n }\n\n public resolve(input: ResolveInput): ResolveResult {\n const styles = this.#resolveTokens(input.classes, input.classes);\n const resolved: string[] = [];\n const unknown: string[] = [];\n for (const token of input.classes) {\n if (this.#classIndex.has(token)) resolved.push(token);\n else unknown.push(token);\n }\n return { styles, resolved, unknown, opaque: [], warnings: [] };\n }\n\n public emit(styles: StyleMap, ctx: EmitContext): EmitResult {\n const norm = ctx.normalizer ?? normalizer;\n const remaining = new Map<string, string>();\n for (const [ck, block] of norm.normalizeStyleMap(styles).blocks) {\n for (const [prop, decl] of block.decls) {\n remaining.set(`${ck}\u0000${prop}`, String(decl.value));\n }\n }\n if (remaining.size === 0) return { classes: [], exact: true, warnings: [] };\n\n const classes: string[] = [];\n // Greedy set-cover: larger classes first so the emitted set stays minimal.\n for (const { token, keyed } of this.#reverseIndex()) {\n let matches = true;\n for (const [key, value] of keyed) {\n if (remaining.get(key) !== value) {\n matches = false;\n break;\n }\n }\n if (!matches) continue;\n classes.push(token);\n for (const key of keyed.keys()) remaining.delete(key);\n if (remaining.size === 0) break;\n }\n\n // Unmatched declarations are left as-is (no synthetic residual) — surfaced via `exact:false`.\n return { classes, exact: remaining.size === 0, warnings: [] };\n }\n\n public selectorUsage(token: string): SelectorUsage {\n const u = this.#usage.get(token);\n if (!u) {\n return {\n asSubject: false,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n droppable: true,\n };\n }\n return {\n asSubject: u.asSubject,\n asAncestor: u.asAncestor,\n asCompound: u.asCompound,\n asSibling: u.asSibling,\n asHasArgument: u.asHasArgument,\n asStructural: u.asStructural,\n // Safe to drop/rename only when every reference is the lone subject of a bare `.x {}`.\n droppable: u.referenced && !u.loadBearing,\n };\n }\n\n /**\n * The distinct COMPLEX selectors found across all stylesheets — anything containing a combinator\n * (descendant / `>` / `+` / `~`) or a structural pseudo (`:nth-child`, `:first-child`, …). Feeds\n * domflax's CSS-selector-safety guard.\n */\n public complexSelectors(): readonly string[] {\n return this.#complex;\n }\n\n /* ─────────────────────────── internals ─────────────────────────── */\n\n /** Parse one stylesheet and fold its rules into the indexes. Returns the advanced order counter. */\n #indexFile(file: CssFile, startOrder: number, complex: Set<string>): number {\n let order = startOrder;\n let root;\n try {\n root = pc!(file.css, { from: file.id });\n } catch {\n // Malformed CSS contributes nothing (never throws — only clear input errors do).\n return order;\n }\n\n root.walkRules((rule) => {\n const media = mediaContext(rule);\n if (media.skip) return; // inside @keyframes / @font-face etc. — not class rules\n const decls = collectDecls(rule);\n\n let ast;\n try {\n ast = sp!().astSync(rule.selector);\n } catch {\n return;\n }\n\n for (const sel of ast.nodes) {\n const thisOrder = order;\n this.#analyzeSelector(sel as selectorParser.Selector, media.media, decls, thisOrder, complex);\n }\n order += 1;\n });\n\n return order;\n }\n\n /** Analyze one comma-segment selector: forward indexing, usage facts, complex detection. */\n #analyzeSelector(\n selector: selectorParser.Selector,\n media: string,\n decls: readonly RawDecl[],\n order: number,\n complex: Set<string>,\n ): void {\n const compounds = splitCompounds(selector);\n let hasCombinator = false;\n let hasStructural = false;\n\n compounds.forEach((compound, index) => {\n const isSubject = index === compounds.length - 1;\n const rightCombinator = index < compounds.length - 1 ? compounds[index + 1]!.leftCombinator : null;\n if (rightCombinator) hasCombinator = true;\n\n const classes = compound.nodes.filter((n) => sp!.isClassName(n));\n const otherSimple = compound.nodes.some(\n (n) =>\n sp!.isTag(n) ||\n sp!.isIdentifier(n) ||\n sp!.isAttribute(n) ||\n sp!.isUniversal(n) ||\n sp!.isNesting(n),\n );\n const pseudos = compound.nodes.filter((n) => sp!.isPseudo(n));\n const structuralPseudo = pseudos.some((p) => STRUCTURAL_PSEUDOS.has(pseudoName(p)));\n const functionalPseudo = pseudos.some((p) => FUNCTIONAL_PSEUDOS.has(pseudoName(p)));\n const statePseudos = pseudos.filter(\n (p) =>\n sp!.isPseudoClass(p) &&\n !STRUCTURAL_PSEUDOS.has(pseudoName(p)) &&\n !FUNCTIONAL_PSEUDOS.has(pseudoName(p)),\n );\n const elementPseudos = pseudos.filter((p) => isPseudoElement(p));\n const qualified = classes.length > 1 || otherSimple || functionalPseudo || statePseudos.length > 0;\n\n if (structuralPseudo) hasStructural = true;\n\n for (const cls of classes) {\n const token = cls.value;\n this.#known.add(token);\n const u = this.#getUsage(token);\n u.referenced = true;\n if (isSubject) u.asSubject = true;\n if (rightCombinator === ' ' || rightCombinator === '>') u.asAncestor = true;\n if (rightCombinator === '+' || rightCombinator === '~') u.asSibling = true;\n if (qualified) u.asCompound = true;\n if (structuralPseudo) u.asStructural = true;\n if (rightCombinator !== null || qualified || structuralPseudo || elementPseudos.length > 0) {\n u.loadBearing = true;\n }\n\n // Forward indexing: a single bare `.class` compound, optionally qualified by state\n // pseudo-classes and/or a pseudo-element, with NO other simple selector and NO\n // structural/functional pseudo and NO combinator on this compound's right edge.\n const forwardEligible =\n compounds.length === 1 &&\n classes.length === 1 &&\n !otherSimple &&\n !structuralPseudo &&\n !functionalPseudo &&\n elementPseudos.length <= 1;\n if (forwardEligible && decls.length > 0) {\n const condition: StyleCondition = {\n media,\n states: statePseudos.map(pseudoName).sort(),\n pseudoElement: elementPseudos.length === 1 ? normalizePseudoElement(elementPseudos[0]!) : '',\n };\n this.#addRuleEntry(token, { order, token, condition, decls });\n }\n }\n\n // Classes nested inside selector-argument pseudos (:has/:is/:where/:not) are references too.\n for (const p of pseudos) {\n const isHas = pseudoName(p) === ':has';\n p.walkClasses((inner) => {\n const token = inner.value;\n this.#known.add(token);\n const u = this.#getUsage(token);\n u.referenced = true;\n u.loadBearing = true;\n if (isHas) u.asHasArgument = true;\n });\n }\n });\n\n if (hasCombinator || hasStructural) {\n complex.add(selector.toString().trim());\n }\n }\n\n #addRuleEntry(token: string, entry: RuleEntry): void {\n const list = this.#classIndex.get(token);\n if (list) list.push(entry);\n else this.#classIndex.set(token, [entry]);\n }\n\n #getUsage(token: string): MutableUsage {\n let u = this.#usage.get(token);\n if (!u) {\n u = {\n referenced: false,\n asSubject: false,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n loadBearing: false,\n };\n this.#usage.set(token, u);\n }\n return u;\n }\n\n /**\n * Resolve a set of tokens into a normalized condition-keyed StyleMap. `tokenList` is the original\n * class list (for per-declaration `tokenIndex` provenance); `request` is the set being resolved.\n */\n #resolveTokens(request: readonly string[], tokenList: readonly string[]): StyleMap {\n const entries: RuleEntry[] = [];\n for (const token of new Set(request)) {\n const list = this.#classIndex.get(token);\n if (list) entries.push(...list);\n }\n if (entries.length === 0) return emptyStyleMap();\n\n // Equal-specificity single-class rules cascade by source order — later wins.\n entries.sort((a, b) => a.order - b.order);\n\n const acc = new Map<ConditionKey, { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }>();\n for (const entry of entries) {\n const key = conditionKey(entry.condition);\n let block = acc.get(key);\n if (!block) {\n block = { condition: entry.condition, decls: new Map() };\n acc.set(key, block);\n }\n const tokenIndex = tokenList.indexOf(entry.token);\n const origin: StyleOrigin = { kind: 'class', tokenIndex, className: entry.token };\n for (const [prop, value, important] of entry.decls) {\n for (const decl of normalizer.normalizeDeclaration(prop, value, important)) {\n block.decls.set(decl.property, { ...decl, origin });\n }\n }\n }\n\n const rawBlocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of acc) {\n if (block.decls.size === 0) continue;\n rawBlocks.set(key, { condition: block.condition, decls: block.decls });\n }\n if (rawBlocks.size === 0) return emptyStyleMap();\n return normalizer.normalizeStyleMap({ blocks: rawBlocks });\n }\n\n /** Build (once) the reverse index used by {@link emit}. */\n #reverseIndex(): readonly ReverseEntry[] {\n if (this.#reverse) return this.#reverse;\n const out: ReverseEntry[] = [];\n for (const token of this.#classIndex.keys()) {\n const styles = this.#resolveTokens([token], [token]);\n const keyed = new Map<string, string>();\n for (const [ck, block] of styles.blocks) {\n for (const [prop, decl] of block.decls) keyed.set(`${ck}\u0000${prop}`, String(decl.value));\n }\n if (keyed.size > 0) out.push({ token, keyed });\n }\n // Larger declaration sets first → greedy minimal cover in `emit`.\n out.sort((a, b) => b.keyed.size - a.keyed.size);\n this.#reverse = out;\n return out;\n }\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Factory\n * ────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Construct a {@link CustomCSSResolver} from raw CSS sources and/or file paths.\n *\n * @param cssFiles raw stylesheets (`{ id, css }`) — pass `[]` when loading only from disk.\n * @param options optional disk paths (`files`) and/or an explicit `fingerprint`.\n */\nexport function createCssResolver(\n cssFiles: readonly CssFile[] = [],\n options?: CssResolverOptions,\n): StyleResolver {\n return new CustomCSSResolver(cssFiles, options);\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Selector helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\ninterface Compound {\n /** The combinator immediately to this compound's LEFT (`null` for the first compound). */\n readonly leftCombinator: string | null;\n readonly nodes: readonly selectorParser.Node[];\n}\n\n/** Split a selector's flat node list into compounds delimited by combinator nodes. */\nfunction splitCompounds(selector: selectorParser.Selector): Compound[] {\n const compounds: Compound[] = [];\n let current: selectorParser.Node[] = [];\n let leftCombinator: string | null = null;\n for (const node of selector.nodes) {\n if (sp!.isCombinator(node)) {\n compounds.push({ leftCombinator, nodes: current });\n current = [];\n leftCombinator = combinatorValue(node);\n } else {\n current.push(node);\n }\n }\n compounds.push({ leftCombinator, nodes: current });\n return compounds;\n}\n\n/** A combinator's normalized value — descendant combinators are a single space. */\nfunction combinatorValue(node: selectorParser.Combinator): string {\n const v = node.value;\n return v.trim() === '' ? ' ' : v.trim();\n}\n\n/** The pseudo's lower-cased name including its leading colon(s), without any argument. */\nfunction pseudoName(node: selectorParser.Pseudo): string {\n return node.value.toLowerCase();\n}\n\nfunction isPseudoElement(node: selectorParser.Pseudo): boolean {\n return sp!.isPseudoElement(node) || LEGACY_PSEUDO_ELEMENTS.has(pseudoName(node));\n}\n\n/** Canonicalize a pseudo-element to the modern double-colon form (e.g. `:before` → `::before`). */\nfunction normalizePseudoElement(node: selectorParser.Pseudo): string {\n const name = pseudoName(node);\n return name.startsWith('::') ? name : `::${name.replace(/^:/, '')}`;\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * postcss helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\ninterface MediaContext {\n readonly media: string;\n /** True when the rule lives under an at-rule that is not a style context (keyframes/font-face). */\n readonly skip: boolean;\n}\n\n/** Walk a rule's at-rule ancestry, collecting `@media` params and detecting non-style contexts. */\nfunction mediaContext(rule: Rule): MediaContext {\n const parts: string[] = [];\n let skip = false;\n let parent = rule.parent;\n while (parent && parent.type === 'atrule') {\n const at = parent as AtRule;\n const name = at.name.toLowerCase();\n if (name === 'media') parts.unshift(at.params.trim().replace(/\\s+/g, ' '));\n else if (name === 'keyframes' || name.endsWith('keyframes') || name === 'font-face') skip = true;\n parent = parent.parent;\n }\n return { media: parts.join(' and '), skip };\n}\n\n/** A rule's direct declarations, in source order, as raw `[prop, value, important]` triples. */\nfunction collectDecls(rule: Rule): RawDecl[] {\n const out: RawDecl[] = [];\n for (const node of rule.nodes) {\n if (node.type === 'decl') out.push([node.prop, node.value, node.important === true]);\n }\n return out;\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Misc helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Cheap, allocation-free CSS-identifier check used by {@link CustomCSSResolver.owns}. */\nfunction isPlainClassToken(token: string): boolean {\n return token.length > 0 && !/[\\s.#>+~:[\\]()]/.test(token);\n}\n\n/** Read a CSS file from disk; surfaces unreadable paths as a clear input error. */\nfunction readCssPath(path: string): CssFile {\n try {\n return { id: path, css: readFileSync(path, 'utf8') };\n } catch (cause) {\n throw new Error(`resolver-css: cannot read CSS file \"${path}\"`, { cause });\n }\n}\n\n/**\n * Derive a deterministic fingerprint from the provider tag, engine version, and each file's id +\n * length. Cheap and good enough to bust downstream caches when the source CSS set changes.\n */\nfunction deriveFingerprint(provider: string, files: readonly CssFile[]): string {\n const parts = files.map((f) => `${f.id}:${f.css.length}`).sort();\n return `${provider}/${ENGINE_VERSION}::${parts.join('|')}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAqCA,SAAS,KAAK,MAAgD;AAC5D,QAAM,IAAI;AACV,SAAO,EAAE,SAAS,YAAa,IAAgC;AACjE;AAGA,SAAS,SAAS,MAA+B;AAC/C,SAAO,CAAC,SAAS,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC;AACjD;AAGA,IAAM,iBAAiB,SAAS,gBAAgB;AAEhD,IAAM,+BAA+B,SAAS,8BAA8B;AAE5E,IAAM,6BAA6B,SAAS,4BAA4B;AAExE,IAAM,oBAAoB,SAAS,mBAAmB;AAEtD,IAAM,2BAA2B,SAAS,0BAA0B;AAOpE,IAAM,6BAAsC,CAAC,MAAM,QAAQ;AACzD,QAAM,KAAK,KAAK,IAAI;AACpB,MAAI,CAAC,GAAI,QAAO;AAChB,MAAI,GAAG,KAAK,2BAA4B,QAAO;AAC/C,SAAO,IAAI,UAAU,2BAA2B,GAAG,EAAyB;AAC9E;AAEA,IAAM,UAAU;AAOhB,IAAM,qBAA8B,CAAC,MAAM,QAAQ;AACjD,QAAM,KAAK,KAAK,IAAI;AACpB,MAAI,CAAC,GAAI,QAAO;AAChB,QAAM,KAAe,IAAI,WAAW,EAAyB,KAAM,GAAG;AACtE,aAAW,SAAS,GAAG,OAAO,OAAO,GAAG;AACtC,UAAM,OAAO,MAAM,MAAM,IAAI,OAAO;AACpC,QAAI,QAAQ,OAAO,KAAK,KAAK,MAAM,QAAS,QAAO;AAAA,EACrD;AACA,SAAO;AACT;AAOO,IAAM,gBAAgB,QAAQ;AAAA,EACnC,MAAM;AAAA,EACN,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,KAAK;AAAA,IACH,OAAO;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QAAQ,MAAM,IAAI,CAAC,MAAM,GAAG,EAAE,EAAE,IAAI,EAAE,IAAI,MAAM,EAAE,EAAE,KAAK;AAC/D,SAAO,GAAG,QAAQ,IAAI,cAAc,KAAK,MAAM,KAAK,GAAG,CAAC;AAC1D;","names":["targetedByStructuralPseudo","elementOf","computed","computed","hasDangerousHtml","computed","BASE_KEY","computed","asElement","hasDangerousHtml","computed","staticTokensOf","computed","path","JSX_LANGS","createRequire","path","moduleBase","LEGACY_PSEUDO_ELEMENTS"]}
@@ -0,0 +1,55 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __esm = (fn, res) => function __init() {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
+ };
16
+ var __commonJS = (cb, mod) => function __require2() {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
+ // If the importer is in node compatibility mode or this is not an ESM
29
+ // file that has been converted to a CommonJS file using a Babel-
30
+ // compatible transform (i.e. "__esModule" has not been set), then set
31
+ // "default" to the CommonJS "module.exports" for node compatibility.
32
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
33
+ mod
34
+ ));
35
+
36
+ // ../../node_modules/tsup/assets/esm_shims.js
37
+ import path from "path";
38
+ import { fileURLToPath } from "url";
39
+ var getFilename, __filename;
40
+ var init_esm_shims = __esm({
41
+ "../../node_modules/tsup/assets/esm_shims.js"() {
42
+ "use strict";
43
+ getFilename = () => fileURLToPath(import.meta.url);
44
+ __filename = /* @__PURE__ */ getFilename();
45
+ }
46
+ });
47
+
48
+ export {
49
+ __require,
50
+ __commonJS,
51
+ __toESM,
52
+ __filename,
53
+ init_esm_shims
54
+ };
55
+ //# sourceMappingURL=chunk-6WVVF6AD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/tsup/assets/esm_shims.js"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B,IAIM,aAIO;AARb;AAAA;AAAA;AAIA,IAAM,cAAc,MAAM,cAAc,YAAY,GAAG;AAIhD,IAAM,aAA6B,4BAAY;AAAA;AAAA;","names":[]}