domflax 0.1.0 → 0.1.2

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 (39) hide show
  1. package/README.md +159 -0
  2. package/dist/{chunk-4HHISSMR.js → chunk-DNHOGPYV.js} +2675 -1503
  3. package/dist/chunk-DNHOGPYV.js.map +1 -0
  4. package/dist/{chunk-ZJ2S36GY.js → chunk-DOQEBGWB.js} +33 -20
  5. package/dist/chunk-DOQEBGWB.js.map +1 -0
  6. package/dist/{chunk-77SLHRN6.js → chunk-DWLB7FRR.js} +341 -176
  7. package/dist/chunk-DWLB7FRR.js.map +1 -0
  8. package/dist/cli.cjs +2209 -774
  9. package/dist/cli.cjs.map +1 -1
  10. package/dist/cli.js +234 -116
  11. package/dist/cli.js.map +1 -1
  12. package/dist/index.cjs +3021 -1699
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +477 -54
  15. package/dist/index.d.ts +477 -54
  16. package/dist/index.js +49 -3
  17. package/dist/pattern-CV607P87.d.ts +547 -0
  18. package/dist/pattern-F5xBtIE-.d.cts +547 -0
  19. package/dist/pattern-kit.cjs +60 -39
  20. package/dist/pattern-kit.cjs.map +1 -1
  21. package/dist/pattern-kit.d.cts +3 -18
  22. package/dist/pattern-kit.d.ts +3 -18
  23. package/dist/pattern-kit.js +3 -1
  24. package/dist/pattern-kit.js.map +1 -1
  25. package/dist/{types-BQ7l6dVe.d.ts → resolve-ops-DIwEelH-.d.cts} +26 -251
  26. package/dist/{types-BQ7l6dVe.d.cts → resolve-ops-DIwEelH-.d.ts} +26 -251
  27. package/dist/verify.d.cts +1 -1
  28. package/dist/verify.d.ts +1 -1
  29. package/dist/webpack-loader.cjs +2975 -1699
  30. package/dist/webpack-loader.cjs.map +1 -1
  31. package/dist/webpack-loader.d.cts +2 -2
  32. package/dist/webpack-loader.d.ts +2 -2
  33. package/dist/webpack-loader.js +3 -3
  34. package/package.json +3 -6
  35. package/dist/chunk-4HHISSMR.js.map +0 -1
  36. package/dist/chunk-77SLHRN6.js.map +0 -1
  37. package/dist/chunk-ZJ2S36GY.js.map +0 -1
  38. package/dist/pattern-CX6iBzTD.d.ts +0 -237
  39. package/dist/pattern-P4FIKAUB.d.cts +0 -237
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../core/src/builders.ts","../../core/src/ops/runtime.ts","../../core/src/ops/apply.ts","../../core/src/ops.ts","../../core/src/pass-context.ts","../../core/src/flatten-safety.ts","../../core/src/pass-manager.ts","../../core/src/pipeline.ts","../../core/src/reverse-emit.ts","../../core/src/index.ts","../../pattern-kit/src/normalize.ts","../../pattern-kit/src/combinators.ts","../../pattern-kit/src/ops.ts","../../pattern-kit/src/pattern.ts","../../pattern-kit/src/define.ts","../../pattern-kit/src/index.ts"],"sourcesContent":["/**\n * @domflax/core — runtime builders + traversal.\n *\n * Pure, dependency-free helpers to construct IR nodes, assemble an {@link IRDocument},\n * and walk the tree honouring {@link VisitSignal}. No heavy third-party deps: only the\n * type contract in `./types`.\n */\n\nimport type {\n AttrMap,\n Backref,\n BackrefTable,\n ClassList,\n ConditionKey,\n CssProperty,\n ExprRecord,\n ExprRef,\n ExprRegistry,\n FrontendKind,\n IdAllocator,\n IRComment,\n IRDocument,\n IRElement,\n IRExpr,\n IRFragment,\n IRNamespace,\n IRNode,\n IRNodeId,\n IRText,\n InlineStyle,\n NodeMeta,\n SafetyLevel,\n SourceSpan,\n StyleBlock,\n StyleCondition,\n StyleMap,\n Visitor,\n VisitContext,\n VisitSignal,\n} from './types';\n\n/* ───────────────────────── id / registry primitives ───────────────────────── */\n\n/** Monotonic IRNodeId allocator. `peek` reports the id `next()` would return. */\nexport function createIdAllocator(start = 1): IdAllocator {\n let n = start;\n return {\n next(): IRNodeId {\n const id = n;\n n += 1;\n return id as IRNodeId;\n },\n get peek(): IRNodeId {\n return n as IRNodeId;\n },\n };\n}\n\n/** Minimal in-memory ExprRegistry. */\nexport function createExprRegistry(start = 1): ExprRegistry {\n const map = new Map<ExprRef, ExprRecord>();\n let n = start;\n return {\n get(r: ExprRef): ExprRecord | undefined {\n return map.get(r);\n },\n intern(rec: Omit<ExprRecord, 'ref'>): ExprRef {\n const ref = n as ExprRef;\n n += 1;\n map.set(ref, { ...rec, ref });\n return ref;\n },\n releasePayloads(): void {\n for (const [k, v] of map) map.set(k, { ...v, payload: undefined });\n },\n };\n}\n\n/** Mutable BackrefTable: frontends register backrefs as they parse. */\nexport interface MutableBackrefTable extends BackrefTable {\n set(id: IRNodeId, backref: Backref): void;\n}\n\nexport function createBackrefTable(): MutableBackrefTable {\n const map = new Map<IRNodeId, Backref>();\n return {\n get(id: IRNodeId): Backref | undefined {\n return map.get(id);\n },\n span(id: IRNodeId): SourceSpan | null {\n return map.get(id)?.span ?? null;\n },\n childrenSpan(id: IRNodeId): SourceSpan | null {\n return map.get(id)?.innerSpan ?? null;\n },\n set(id: IRNodeId, backref: Backref): void {\n map.set(id, backref);\n },\n };\n}\n\n/* ───────────────────────── default sub-structures ───────────────────────── */\n\n/** A NodeMeta with every barrier/flag cleared. */\nexport function defaultMeta(safetyFloor: SafetyLevel = 0): NodeMeta {\n return {\n hasRef: false,\n hasEventHandlers: false,\n hasKey: false,\n hasSpreadAttrs: false,\n hasDynamicChildren: false,\n isComponent: false,\n hasDangerousHtml: false,\n targetedByCombinator: false,\n targetedByStructuralPseudo: false,\n selectorDependents: 0,\n hasOwnVisualStyle: false,\n establishesBox: false,\n establishesStackingContext: false,\n isContainingBlock: false,\n establishesFormattingContext: false,\n declaresCustomProperties: false,\n whitespaceSensitive: false,\n touched: false,\n synthetic: false,\n safetyFloor,\n };\n}\n\n/** Canonical base style condition (`media:'' states:[] pseudoElement:''`). */\nexport const BASE_CONDITION: StyleCondition = { media: '', states: [], pseudoElement: '' };\n\n/** Stable serialization of a StyleCondition into a ConditionKey. */\nexport function conditionKey(c: StyleCondition): ConditionKey {\n const states = [...c.states].sort().join(',');\n return `${c.media}|${states}|${c.pseudoElement}` as ConditionKey;\n}\n\nexport const BASE_CONDITION_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/** An empty StyleMap (no blocks). */\nexport function emptyStyleMap(): StyleMap {\n return { blocks: new Map<ConditionKey, StyleBlock>() };\n}\n\n/** An empty (absent) ClassList. */\nexport function emptyClassList(): ClassList {\n return {\n form: 'absent',\n segments: [],\n valueSpan: null,\n hasDynamic: false,\n opaque: false,\n rewritable: false,\n };\n}\n\n/** An empty AttrMap. */\nexport function emptyAttrMap(): AttrMap {\n return { entries: new Map(), spreads: [], order: [] };\n}\n\n/** An empty InlineStyle. */\nexport function emptyInlineStyle(): InlineStyle {\n return { decls: new Map<CssProperty, never>() as InlineStyle['decls'], dynamic: null };\n}\n\n/* ───────────────────────── node factories ───────────────────────── */\n\nexport interface ElementInit {\n readonly tag: string;\n readonly namespace?: IRNamespace;\n readonly isComponent?: boolean;\n readonly selfClosing?: boolean;\n readonly classes?: ClassList;\n readonly inlineStyle?: InlineStyle;\n readonly computed?: StyleMap;\n readonly attrs?: AttrMap;\n readonly children?: IRNodeId[];\n readonly parent?: IRNodeId | null;\n readonly span?: SourceSpan | null;\n readonly meta?: NodeMeta;\n}\n\nexport function createElement(id: IRNodeId, init: ElementInit): IRElement {\n return {\n id,\n kind: 'element',\n parent: init.parent ?? null,\n span: init.span ?? null,\n meta: init.meta ?? defaultMeta(),\n tag: init.tag,\n namespace: init.namespace ?? 'html',\n isComponent: init.isComponent ?? false,\n selfClosing: init.selfClosing ?? false,\n classes: init.classes ?? emptyClassList(),\n inlineStyle: init.inlineStyle ?? emptyInlineStyle(),\n computed: init.computed ?? emptyStyleMap(),\n attrs: init.attrs ?? emptyAttrMap(),\n children: init.children ?? [],\n };\n}\n\nexport function createText(\n id: IRNodeId,\n value: string,\n opts?: { collapsible?: boolean; parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRText {\n return {\n id,\n kind: 'text',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n value,\n collapsible: opts?.collapsible ?? true,\n };\n}\n\nexport function createExpr(\n id: IRNodeId,\n expr: ExprRef,\n opts?: { parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRExpr {\n return {\n id,\n kind: 'expr',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n expr,\n };\n}\n\nexport function createFragment(\n id: IRNodeId,\n opts?: { children?: IRNodeId[]; parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRFragment {\n return {\n id,\n kind: 'fragment',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n children: opts?.children ?? [],\n };\n}\n\nexport function createComment(\n id: IRNodeId,\n value: string,\n opts?: { parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRComment {\n return {\n id,\n kind: 'comment',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n value,\n };\n}\n\n/** Build an empty document whose root is a fresh fragment. */\nexport function createDocument(frontend: FrontendKind): IRDocument {\n const alloc = createIdAllocator();\n const rootId = alloc.next();\n const root = createFragment(rootId);\n const nodes = new Map<IRNodeId, IRNode>([[rootId, root]]);\n return {\n root: rootId,\n nodes,\n exprs: createExprRegistry(),\n sources: new Map(),\n backref: createBackrefTable(),\n frontend,\n alloc,\n };\n}\n\n/* ───────────────────────── tree accessors ───────────────────────── */\n\n/** Returns the child id list for container nodes, or an empty array. */\nexport function childIds(node: IRNode): readonly IRNodeId[] {\n return node.kind === 'element' || node.kind === 'fragment' ? node.children : [];\n}\n\n/** Returns the node, or undefined. */\nexport function getNode(doc: IRDocument, id: IRNodeId): IRNode | undefined {\n return doc.nodes.get(id);\n}\n\n/** Returns the node iff it is an element. */\nexport function getElement(doc: IRDocument, id: IRNodeId): IRElement | undefined {\n const n = doc.nodes.get(id);\n return n && n.kind === 'element' ? n : undefined;\n}\n\n/** Pre-order list of every element id reachable from the root. */\nexport function elementIds(doc: IRDocument): IRNodeId[] {\n const out: IRNodeId[] = [];\n const visit = (id: IRNodeId): void => {\n const n = doc.nodes.get(id);\n if (!n) return;\n if (n.kind === 'element') out.push(id);\n for (const c of childIds(n)) visit(c);\n };\n visit(doc.root);\n return out;\n}\n\n/* ───────────────────────── traversal ───────────────────────── */\n\n/**\n * Depth-first pre/post-order walk. `enter` may return `'skip'` (don't descend) or `'stop'`\n * (abort the whole walk); `exit` may return `'stop'`. The visitor receives a live {@link IRNode}\n * plus a {@link VisitContext} exposing depth and the parent node.\n */\nexport function walk(doc: IRDocument, visitor: Visitor): void {\n const roDoc = doc as unknown as VisitContext['doc'];\n let stopped = false;\n\n const visit = (id: IRNodeId, depth: number): void => {\n if (stopped) return;\n const node = doc.nodes.get(id);\n if (!node) return;\n\n const ctx: VisitContext = {\n doc: roDoc,\n depth,\n parent(): IRNode | null {\n return node.parent == null ? null : doc.nodes.get(node.parent) ?? null;\n },\n };\n\n const entered: VisitSignal = visitor.enter ? visitor.enter(node, ctx) : undefined;\n if (entered === 'stop') {\n stopped = true;\n return;\n }\n if (entered !== 'skip') {\n for (const child of childIds(node)) {\n visit(child, depth + 1);\n if (stopped) return;\n }\n }\n\n const exited: VisitSignal = visitor.exit ? visitor.exit(node, ctx) : undefined;\n if (exited === 'stop') stopped = true;\n };\n\n visit(doc.root, 0);\n}\n","/**\n * @domflax/core — applier runtime helpers (shared by the per-op handlers in `./apply`).\n *\n * Pure, dependency-free building blocks for the trusted mutator: input-preserving cloning, the\n * mutable apply state, small tree helpers, detached-spec materialization, and style merging.\n * Only depends on the `../types` contract and `../builders` runtime helpers.\n */\n\nimport type {\n ApplyContext,\n ApplyResult,\n AttrMap,\n AttrValue,\n ConditionKey,\n CssProperty,\n Diagnostic,\n DiagnosticCode,\n ElementSpec,\n IRDocument,\n IRNode,\n IRNodeId,\n NodeSpec,\n RewriteOp,\n SkippedOpGroup,\n StyleBlock,\n StyleConflictPolicy,\n StyleDecl,\n StyleMap,\n} from '../types';\n\nimport {\n createComment,\n createElement,\n createExpr,\n createFragment,\n createText,\n defaultMeta,\n} from '../builders';\n\n/* ───────────────────────── result of an apply run ───────────────────────── */\n\nexport interface ApplyOutcome {\n /** The new document (the input doc is never mutated). */\n readonly doc: IRDocument;\n readonly result: ApplyResult;\n}\n\nexport interface MutState {\n readonly doc: IRDocument;\n readonly touched: Set<IRNodeId>;\n readonly removed: Set<IRNodeId>;\n readonly created: Set<IRNodeId>;\n readonly diagnostics: Diagnostic[];\n readonly skipped: SkippedOpGroup[];\n appliedGroups: number;\n readonly ceiling: number;\n readonly ctx: ApplyContext;\n}\n\n/* ───────────────────────── cloning (keep input pure) ───────────────────────── */\n\nexport function cloneStyleMap(sm: StyleMap): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n blocks.set(key, {\n condition: block.condition,\n decls: new Map<CssProperty, StyleDecl>(block.decls),\n });\n }\n return { blocks };\n}\n\nfunction cloneNode(node: IRNode): IRNode {\n const meta = { ...node.meta };\n switch (node.kind) {\n case 'element':\n return {\n ...node,\n meta,\n children: [...node.children],\n computed: cloneStyleMap(node.computed),\n };\n case 'fragment':\n return { ...node, meta, children: [...node.children] };\n default:\n return { ...node, meta };\n }\n}\n\n/** Shallow-immutable clone: input doc and its node objects are never mutated. */\nexport function cloneDocument(doc: IRDocument): IRDocument {\n const nodes = new Map<IRNodeId, IRNode>();\n for (const [id, n] of doc.nodes) nodes.set(id, cloneNode(n));\n return {\n root: doc.root,\n nodes,\n exprs: doc.exprs,\n sources: doc.sources,\n backref: doc.backref,\n frontend: doc.frontend,\n alloc: doc.alloc,\n };\n}\n\n/* ───────────────────────── small helpers ───────────────────────── */\n\nexport function diag(\n code: DiagnosticCode,\n message: string,\n extra?: Partial<Diagnostic>,\n): Diagnostic {\n return { code, severity: 'warn', message, ...extra };\n}\n\nexport function getParentChildren(doc: IRDocument, id: IRNodeId): IRNodeId[] | null {\n const node = doc.nodes.get(id);\n if (!node || node.parent == null) return null;\n const parent = doc.nodes.get(node.parent);\n if (!parent) return null;\n if (parent.kind === 'element' || parent.kind === 'fragment') return parent.children;\n return null;\n}\n\nexport function indexInParent(doc: IRDocument, id: IRNodeId): number {\n const siblings = getParentChildren(doc, id);\n return siblings ? siblings.indexOf(id) : -1;\n}\n\nexport function markTouched(state: MutState, id: IRNodeId): void {\n const n = state.doc.nodes.get(id);\n if (n) {\n n.meta.touched = true;\n state.touched.add(id);\n }\n}\n\nexport function removeSubtree(state: MutState, id: IRNodeId): void {\n const node = state.doc.nodes.get(id);\n if (!node) return;\n if (node.kind === 'element' || node.kind === 'fragment') {\n for (const child of [...node.children]) removeSubtree(state, child);\n }\n state.doc.nodes.delete(id);\n state.removed.add(id);\n}\n\nexport function precond(op: RewriteOp, nodeId: IRNodeId, message: string): Diagnostic {\n return diag('DF_OP_PRECONDITION_FAILED', message, {\n nodeId,\n pattern: op.origin.pattern,\n severity: 'error',\n });\n}\n\nexport function primaryTarget(op: RewriteOp): IRNodeId | null {\n switch (op.op) {\n case 'removeNode':\n case 'unwrap':\n case 'replaceWith':\n case 'wrap':\n case 'moveNode':\n case 'setClassList':\n case 'mergeStyle':\n return op.target;\n case 'insertBefore':\n case 'insertAfter':\n return op.anchor;\n case 'mergeSiblings':\n return op.first;\n case 'foldInheritedStyles':\n return op.from;\n }\n}\n\n/* ───────────────────────── spec materialization ───────────────────────── */\n\nfunction specToAttrs(map: ReadonlyMap<string, string | boolean> | undefined): AttrMap {\n if (!map || map.size === 0) return { entries: new Map(), spreads: [], order: [] };\n const entries = new Map<string, AttrValue>();\n const order: string[] = [];\n for (const [k, v] of map) {\n entries.set(k, { kind: 'static', value: v });\n order.push(k);\n }\n return { entries, spreads: [], order };\n}\n\n/** Materialize a detached {@link NodeSpec} into live nodes; returns the new (or reused) id. */\nexport function materialize(state: MutState, spec: NodeSpec, parent: IRNodeId | null): IRNodeId {\n const { doc } = state;\n if (spec.kind === 'ref') {\n const existing = doc.nodes.get(spec.ref);\n if (existing) existing.parent = parent;\n return spec.ref;\n }\n\n const id = doc.alloc.next();\n state.created.add(id);\n switch (spec.kind) {\n case 'element': {\n const childIds: IRNodeId[] = [];\n const el = createElement(id, {\n tag: spec.tag,\n namespace: spec.namespace,\n selfClosing: spec.selfClosing,\n attrs: specToAttrs(spec.attrs),\n parent,\n meta: { ...defaultMeta(), synthetic: true },\n });\n if (spec.classes) el.computed = cloneStyleMap(spec.classes);\n doc.nodes.set(id, el);\n for (const child of spec.children ?? []) {\n childIds.push(materialize(state, child, id));\n }\n el.children = childIds;\n return id;\n }\n case 'text': {\n const t = createText(id, spec.value, { parent });\n t.meta.synthetic = true;\n doc.nodes.set(id, t);\n return id;\n }\n case 'expr': {\n const e = createExpr(id, spec.expr, { parent });\n e.meta.synthetic = true;\n doc.nodes.set(id, e);\n return id;\n }\n case 'comment': {\n const c = createComment(id, spec.value, { parent });\n c.meta.synthetic = true;\n doc.nodes.set(id, c);\n return id;\n }\n case 'fragment': {\n const frag = createFragment(id, { parent });\n frag.meta.synthetic = true;\n doc.nodes.set(id, frag);\n const childIds: IRNodeId[] = [];\n for (const child of spec.children) childIds.push(materialize(state, child, id));\n frag.children = childIds;\n return id;\n }\n }\n}\n\nexport function elementSpecToNode(\n state: MutState,\n spec: ElementSpec,\n parent: IRNodeId | null,\n): IRNodeId {\n return materialize(state, spec, parent);\n}\n\n/* ───────────────────────── style merging ───────────────────────── */\n\nexport function isInherited(state: MutState, decl: StyleDecl): boolean {\n if (decl.inherited) return true;\n const table = state.ctx.normalizer?.inherited;\n if (table) {\n try {\n return table.isInherited(decl.property);\n } catch {\n return decl.inherited;\n }\n }\n return decl.inherited;\n}\n\nexport interface MergeReport {\n readonly map: StyleMap;\n readonly conflict: boolean;\n}\n\n/** Merge `source` decls into `target`, condition-by-condition, per the conflict policy. */\nexport function mergeStyleMaps(\n target: StyleMap,\n source: StyleMap,\n policy: StyleConflictPolicy,\n): MergeReport {\n // Mutable working copy; returned (widened) as an immutable StyleMap.\n const blocks = new Map<ConditionKey, StyleBlock>(cloneStyleMap(target).blocks);\n let conflict = false;\n\n for (const [key, srcBlock] of source.blocks) {\n const existing = blocks.get(key);\n if (!existing) {\n blocks.set(key, {\n condition: srcBlock.condition,\n decls: new Map<CssProperty, StyleDecl>(srcBlock.decls),\n });\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>(existing.decls);\n for (const [prop, srcDecl] of srcBlock.decls) {\n const had = decls.get(prop);\n if (had && had.value !== srcDecl.value) {\n conflict = true;\n if (policy === 'target-wins') continue;\n // 'abort' is handled by the caller before commit; 'source-wins' falls through.\n }\n if (policy === 'target-wins' && had) continue;\n decls.set(prop, srcDecl);\n }\n blocks.set(key, { condition: existing.condition, decls });\n }\n return { map: { blocks }, conflict };\n}\n","/**\n * @domflax/core — the per-op handlers + public apply entry points.\n *\n * {@link applyOps} validates each {@link RewriteOp} against the safety ceiling / node-local floor\n * and commits it to a clone of the document; {@link applyGroups} commits whole {@link RewriteGroup}s\n * atomically. Rejected ops are collected into {@link ApplyResult.skipped} rather than throwing.\n */\n\nimport type {\n ApplyContext,\n ApplyResult,\n ConditionKey,\n CssProperty,\n Diagnostic,\n IRDocument,\n IRNodeId,\n RewriteGroup,\n RewriteOp,\n SkippedOpGroup,\n StyleBlock,\n StyleDecl,\n} from '../types';\n\nimport { BASE_CONDITION_KEY } from '../builders';\n\nimport {\n cloneDocument,\n cloneStyleMap,\n diag,\n elementSpecToNode,\n getParentChildren,\n isInherited,\n markTouched,\n materialize,\n mergeStyleMaps,\n precond,\n primaryTarget,\n removeSubtree,\n type ApplyOutcome,\n type MutState,\n} from './runtime';\n\nexport type { ApplyOutcome } from './runtime';\nexport { cloneDocument } from './runtime';\n\n/* ───────────────────────── per-op handlers ───────────────────────── */\n\nfunction safetyOk(state: MutState, op: RewriteOp, targetId: IRNodeId): Diagnostic | null {\n const opSafety = op.origin.safety;\n if (opSafety > state.ceiling) {\n return diag(\n 'DF_SAFETY_CEILING_EXCEEDED',\n `op '${op.op}' safety ${opSafety} exceeds ceiling ${state.ceiling}`,\n { nodeId: targetId, pattern: op.origin.pattern, severity: 'error' },\n );\n }\n const node = state.doc.nodes.get(targetId);\n if (node && opSafety > node.meta.safetyFloor) {\n return diag(\n 'DF_SAFETY_CEILING_EXCEEDED',\n `op '${op.op}' safety ${opSafety} exceeds node ${targetId} floor ${node.meta.safetyFloor}`,\n { nodeId: targetId, pattern: op.origin.pattern, severity: 'error' },\n );\n }\n return null;\n}\n\n/** Returns a list of validation issues; empty ⇒ the op was applied. */\nfunction applyOne(state: MutState, op: RewriteOp): Diagnostic[] {\n const { doc } = state;\n\n const primary = primaryTarget(op);\n if (primary != null) {\n if (!doc.nodes.get(primary)) {\n return [\n diag('DF_OP_PRECONDITION_FAILED', `target node ${primary} not found`, {\n nodeId: primary,\n pattern: op.origin.pattern,\n severity: 'error',\n }),\n ];\n }\n const safety = safetyOk(state, op, primary);\n if (safety) return [safety];\n }\n\n switch (op.op) {\n case 'removeNode': {\n const siblings = getParentChildren(doc, op.target);\n if (siblings) {\n const i = siblings.indexOf(op.target);\n if (i >= 0) siblings.splice(i, 1);\n }\n removeSubtree(state, op.target);\n return [];\n }\n\n case 'unwrap': {\n const node = doc.nodes.get(op.target);\n if (!node || (node.kind !== 'element' && node.kind !== 'fragment')) {\n return [precond(op, op.target, 'unwrap target is not a container')];\n }\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'unwrap target has no parent')];\n const at = siblings.indexOf(op.target);\n const kids = node.children;\n for (const k of kids) {\n const kn = doc.nodes.get(k);\n if (kn) kn.parent = node.parent;\n }\n siblings.splice(at, 1, ...kids);\n doc.nodes.delete(op.target);\n state.removed.add(op.target);\n if (node.parent != null) markTouched(state, node.parent);\n return [];\n }\n\n case 'replaceWith': {\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'replaceWith target has no parent')];\n const at = siblings.indexOf(op.target);\n const parentId = doc.nodes.get(op.target)?.parent ?? null;\n const newId = materialize(state, op.replacement, parentId);\n siblings.splice(at, 1, newId);\n removeSubtree(state, op.target);\n if (parentId != null) markTouched(state, parentId);\n return [];\n }\n\n case 'wrap': {\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'wrap target has no parent')];\n const at = siblings.indexOf(op.target);\n const parentId = doc.nodes.get(op.target)?.parent ?? null;\n const wrapperId = elementSpecToNode(state, op.wrapper, parentId);\n const wrapper = doc.nodes.get(wrapperId);\n const targetNode = doc.nodes.get(op.target);\n if (wrapper && (wrapper.kind === 'element' || wrapper.kind === 'fragment')) {\n wrapper.children.push(op.target);\n }\n if (targetNode) targetNode.parent = wrapperId;\n siblings.splice(at, 1, wrapperId);\n return [];\n }\n\n case 'insertBefore':\n case 'insertAfter': {\n const siblings = getParentChildren(doc, op.anchor);\n if (!siblings) return [precond(op, op.anchor, 'insert anchor has no parent')];\n const at = siblings.indexOf(op.anchor);\n const parentId = doc.nodes.get(op.anchor)?.parent ?? null;\n const newId = materialize(state, op.node, parentId);\n siblings.splice(op.op === 'insertBefore' ? at : at + 1, 0, newId);\n if (parentId != null) markTouched(state, parentId);\n return [];\n }\n\n case 'moveNode': {\n const newParent = doc.nodes.get(op.newParent);\n if (!newParent || (newParent.kind !== 'element' && newParent.kind !== 'fragment')) {\n return [precond(op, op.newParent, 'moveNode newParent is not a container')];\n }\n const siblings = getParentChildren(doc, op.target);\n if (siblings) {\n const i = siblings.indexOf(op.target);\n if (i >= 0) siblings.splice(i, 1);\n }\n const target = doc.nodes.get(op.target);\n if (target) target.parent = op.newParent;\n const idx = Math.max(0, Math.min(op.index, newParent.children.length));\n newParent.children.splice(idx, 0, op.target);\n markTouched(state, op.newParent);\n return [];\n }\n\n case 'mergeSiblings': {\n const first = doc.nodes.get(op.first);\n const second = doc.nodes.get(op.second);\n if (!first || !second) return [precond(op, op.first, 'mergeSiblings node missing')];\n if (\n (first.kind === 'element' || first.kind === 'fragment') &&\n (second.kind === 'element' || second.kind === 'fragment')\n ) {\n for (const c of second.children) {\n const cn = doc.nodes.get(c);\n if (cn) cn.parent = op.first;\n first.children.push(c);\n }\n second.children = [];\n }\n const siblings = getParentChildren(doc, op.second);\n if (siblings) {\n const i = siblings.indexOf(op.second);\n if (i >= 0) siblings.splice(i, 1);\n }\n doc.nodes.delete(op.second);\n state.removed.add(op.second);\n markTouched(state, op.first);\n return [];\n }\n\n case 'setClassList': {\n const el = doc.nodes.get(op.target);\n if (!el || el.kind !== 'element') {\n return [precond(op, op.target, 'setClassList target is not an element')];\n }\n el.computed = cloneStyleMap(op.style);\n markTouched(state, op.target);\n return [];\n }\n\n case 'mergeStyle': {\n const el = doc.nodes.get(op.target);\n if (!el || el.kind !== 'element') {\n return [precond(op, op.target, 'mergeStyle target is not an element')];\n }\n const report = mergeStyleMaps(el.computed, op.style, op.onConflict);\n if (report.conflict && op.onConflict === 'abort') {\n return [\n diag('DF_STYLE_CONFLICT_UNRESOLVED', `mergeStyle aborted on conflict at ${op.target}`, {\n nodeId: op.target,\n pattern: op.origin.pattern,\n severity: 'error',\n }),\n ];\n }\n el.computed = report.map;\n if (op.source != null) {\n const src = doc.nodes.get(op.source);\n if (src) markTouched(state, op.source);\n }\n markTouched(state, op.target);\n return [];\n }\n\n case 'foldInheritedStyles':\n return applyFold(state, op);\n }\n}\n\nfunction applyFold(\n state: MutState,\n op: Extract<RewriteOp, { op: 'foldInheritedStyles' }>,\n): Diagnostic[] {\n const { doc } = state;\n const from = doc.nodes.get(op.from);\n if (!from || from.kind !== 'element') {\n return [precond(op, op.from, 'fold source is not an element')];\n }\n const issues: Diagnostic[] = [];\n const onlyProps: ReadonlySet<CssProperty> | null =\n op.properties === 'all-inherited' ? null : new Set(op.properties);\n\n const conditionKeys =\n op.conditions === 'all'\n ? [...from.computed.blocks.keys()]\n : [BASE_CONDITION_KEY];\n\n for (const intoId of op.into) {\n const into = doc.nodes.get(intoId);\n if (!into || into.kind !== 'element') {\n issues.push(precond(op, intoId, 'fold target is not an element'));\n continue;\n }\n // Mutable working copy; assigned back (widened) as an immutable StyleMap.\n const nextBlocks = new Map<ConditionKey, StyleBlock>(cloneStyleMap(into.computed).blocks);\n let folded = false;\n\n for (const key of conditionKeys) {\n const srcBlock = from.computed.blocks.get(key);\n if (!srcBlock) continue;\n const dstBlock = nextBlocks.get(key);\n const decls = dstBlock\n ? new Map<CssProperty, StyleDecl>(dstBlock.decls)\n : new Map<CssProperty, StyleDecl>();\n\n for (const [prop, decl] of srcBlock.decls) {\n if (onlyProps && !onlyProps.has(prop)) continue;\n if (!isInherited(state, decl)) continue;\n if (decl.relativeToParent) {\n issues.push(\n diag(\n 'DF_RELATIVE_UNIT_FOLD',\n `refused to fold relative-unit declaration '${decl.property}' onto ${intoId}`,\n { nodeId: intoId, pattern: op.origin.pattern, severity: 'warn' },\n ),\n );\n continue;\n }\n if (!decls.has(prop)) {\n decls.set(prop, decl);\n folded = true;\n }\n }\n nextBlocks.set(key, { condition: srcBlock.condition, decls });\n }\n\n if (folded) {\n into.computed = { blocks: nextBlocks };\n markTouched(state, intoId);\n }\n }\n // Non-blocking (DF_RELATIVE_UNIT_FOLD) diagnostics are recorded but do not skip the op.\n for (const d of issues) state.diagnostics.push(d);\n return [];\n}\n\n/* ───────────────────────── public entry points ───────────────────────── */\n\n/**\n * Apply a flat list of ops to a copy of `doc`. The input document is never mutated.\n * Each op is independently validated; failing ops are skipped (collected in\n * {@link ApplyResult.skipped}) instead of throwing.\n */\nexport function applyOps(\n doc: IRDocument,\n ops: readonly RewriteOp[],\n ctx?: Partial<ApplyContext>,\n): ApplyOutcome {\n const cloned = cloneDocument(doc);\n const state: MutState = {\n doc: cloned,\n touched: new Set(),\n removed: new Set(),\n created: new Set(),\n diagnostics: [],\n skipped: [],\n appliedGroups: 0,\n ceiling: ctx?.safetyCeiling ?? 3,\n ctx: { doc: cloned, safetyCeiling: ctx?.safetyCeiling ?? 3, ...ctx } as ApplyContext,\n };\n\n for (const op of ops) {\n const issues = applyOne(state, op);\n if (issues.length > 0) {\n state.skipped.push({\n group: { pattern: op.origin.pattern, anchor: primaryTarget(op) ?? doc.root, ops: [op] },\n issues: issues.map((d) => ({ op, code: d.code, message: d.message })),\n });\n for (const d of issues) state.diagnostics.push(d);\n } else {\n state.appliedGroups += 1;\n }\n }\n\n return { doc: cloned, result: finalize(state) };\n}\n\n/**\n * Apply pre-grouped ops (each {@link RewriteGroup} is committed atomically: if ANY op in the group\n * fails validation, the whole group is skipped and none of its ops mutate the tree).\n */\nexport function applyGroups(\n doc: IRDocument,\n groups: readonly RewriteGroup[],\n ctx?: Partial<ApplyContext>,\n): ApplyOutcome {\n // Group-atomicity is realized by working on a throwaway clone per group, then committing.\n let current = cloneDocument(doc);\n const touched = new Set<IRNodeId>();\n const removed = new Set<IRNodeId>();\n const created = new Set<IRNodeId>();\n const diagnostics: Diagnostic[] = [];\n const skipped: SkippedOpGroup[] = [];\n let appliedGroups = 0;\n\n for (const group of groups) {\n const attempt = applyOps(current, group.ops, ctx);\n if (attempt.result.skipped.length > 0) {\n skipped.push({\n group,\n issues: attempt.result.skipped.flatMap((s) => s.issues),\n });\n for (const s of attempt.result.skipped) for (const i of s.issues) {\n diagnostics.push(diag(i.code, i.message, { pattern: group.pattern }));\n }\n continue; // discard the attempt — group is atomic\n }\n current = attempt.doc;\n appliedGroups += 1;\n for (const id of attempt.result.touched) touched.add(id);\n for (const id of attempt.result.removed) removed.add(id);\n for (const id of attempt.result.created) created.add(id);\n for (const d of attempt.result.diagnostics) diagnostics.push(d);\n }\n\n const result: ApplyResult = {\n touched,\n removed,\n created,\n appliedGroups,\n skipped,\n journal: [],\n diagnostics,\n };\n return { doc: current, result };\n}\n\nfunction finalize(state: MutState): ApplyResult {\n return {\n touched: state.touched,\n removed: state.removed,\n created: state.created,\n appliedGroups: state.appliedGroups,\n skipped: state.skipped,\n journal: [],\n diagnostics: state.diagnostics,\n };\n}\n","/**\n * @domflax/core — the pure applier (the one trusted mutator) — public barrel.\n *\n * {@link applyOps} takes an {@link IRDocument} plus a flat list of {@link RewriteOp}s and returns a\n * NEW, mutated document (the input is left untouched — \"pure\" in the input-immutability sense). Every\n * op is validated against the safety ceiling and node-local safety floor before it runs; rejected ops\n * are collected into {@link ApplyResult.skipped} with {@link Diagnostic}s rather than throwing.\n * Dependency-free: only the `./types` contract and `./builders` runtime helpers.\n *\n * The implementation is split for size: `./ops/runtime` holds the input-preserving cloning, mutable\n * state, tree helpers, spec materialization, and style merging; `./ops/apply` holds the per-op\n * handlers and the public entry points. This barrel preserves the original public surface.\n */\n\nexport type { ApplyOutcome } from './ops/runtime';\nexport { cloneDocument } from './ops/runtime';\nexport { applyOps, applyGroups } from './ops/apply';\n","/**\n * @domflax/core — pass-manager supporting contexts (resolvers, selector index, rewrite factory,\n * match context).\n *\n * Split out of `pass-manager.ts` so the sync engine, the async verifier-gated engine, and the\n * classification module can all share the same context construction without any of those files\n * exceeding the module-size budget. Dependency-free: only the `./types` contract + `./builders`.\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n ElementSpec,\n EmitContext,\n EmitResult,\n IRDocument,\n IRElement,\n IRNode,\n IRNodeId,\n MatchContext,\n NodeLike,\n NodeSpec,\n PassPhase,\n ResolveInput,\n ResolveResult,\n RewriteFactory,\n RewriteOpDraft,\n SelectorIndex,\n SelectorUsage,\n StyleConflictPolicy,\n StyleMap,\n StyleResolver,\n} from './types';\n\nimport { elementIds, emptyStyleMap, getElement } from './builders';\n\n/* ───────────────────────── default resolvers / selector index ───────────────────────── */\n\n/** A no-op resolver: owns nothing, resolves to empty styles. Useful as an injection default. */\nexport function createNullResolver(): StyleResolver {\n const empty: ResolveResult = {\n styles: emptyStyleMap(),\n resolved: [],\n unknown: [],\n opaque: [],\n warnings: [],\n };\n const usage: SelectorUsage = {\n asSubject: false,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n droppable: true,\n };\n return {\n id: 'null',\n provider: 'null@0.0.0',\n fingerprint: 'null',\n owns(): boolean {\n return false;\n },\n resolve(_input: ResolveInput): ResolveResult {\n return empty;\n },\n emit(_styles: StyleMap, _ctx: EmitContext): EmitResult {\n return { classes: [], exact: true, warnings: [] };\n },\n selectorUsage(): SelectorUsage {\n return usage;\n },\n };\n}\n\n/** A SelectorIndex that reports zero CSS-targeting (no combinator/structural coupling). */\nexport function createNullSelectorIndex(): SelectorIndex {\n const none: ReadonlySet<IRNodeId> = new Set();\n return {\n targetedByCombinator(): boolean {\n return false;\n },\n targetedByStructuralPseudo(): boolean {\n return false;\n },\n reparentImpact(): ReadonlySet<IRNodeId> {\n return none;\n },\n };\n}\n\n/** Resolvers that can enumerate the project's COMPLEX selectors (the custom-CSS resolver) expose this. */\ninterface ComplexSelectorCapable {\n complexSelectors(): readonly string[];\n}\n\nfunction hasComplexSelectors(r: StyleResolver): r is StyleResolver & ComplexSelectorCapable {\n return typeof (r as Partial<ComplexSelectorCapable>).complexSelectors === 'function';\n}\n\n/**\n * Build a real {@link SelectorIndex} from the active resolver.\n *\n * For a resolver that reports project COMPLEX selectors — anything with a combinator (`>`/`+`/`~`/\n * descendant) or a structural pseudo, i.e. the custom-CSS resolver — every element whose static class\n * participates in such a selector is flagged so the flatten/compress guards (`targetedByCombinator` /\n * `affectsSelectorMatching`) fire and a wrapper a selector depends on is NOT flattened. An element is\n * combinator-coupled when one of its classes is used as a descendant/child ancestor, as a sibling\n * subject, or as a `:has()` argument; structural-coupled when used in `:nth-child(...)` etc.\n *\n * For a combinator-free resolver (Tailwind utilities — no `complexSelectors()`), this degrades to the\n * null index so behaviour is unchanged.\n */\nexport function buildSelectorIndex(doc: IRDocument, resolver: StyleResolver): SelectorIndex {\n if (!hasComplexSelectors(resolver) || resolver.complexSelectors().length === 0) {\n return createNullSelectorIndex();\n }\n\n const combinator = new Set<IRNodeId>();\n const structural = new Set<IRNodeId>();\n\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el) continue;\n for (const seg of el.classes.segments) {\n if (seg.kind !== 'static') continue;\n for (const t of seg.tokens) {\n const u = resolver.selectorUsage(t.value);\n // Combinator coupling: descendant/child ancestor, sibling subject, or `:has()` argument —\n // reparenting/removing the element would change a combinator match-set.\n if (u.asAncestor || u.asSibling || u.asHasArgument) combinator.add(id);\n if (u.asStructural) structural.add(id);\n }\n }\n }\n\n // reparentImpact(id): non-empty when removing/unwrapping `id` would change a combinator/structural\n // match-set — `id` itself is coupled (its own match), or it is the matched ancestor of a child\n // (removing it reparents that child out of the relation). Self + element children is conservative\n // and sufficient for the flatten guard.\n const impact = new Map<IRNodeId, Set<IRNodeId>>();\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el) continue;\n if (!combinator.has(id) && !structural.has(id)) continue;\n const set = new Set<IRNodeId>([id]);\n for (const c of el.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') set.add(c);\n }\n impact.set(id, set);\n }\n\n const empty: ReadonlySet<IRNodeId> = new Set();\n return {\n targetedByCombinator: (id: IRNodeId): boolean => combinator.has(id),\n targetedByStructuralPseudo: (id: IRNodeId): boolean => structural.has(id),\n reparentImpact: (id: IRNodeId): ReadonlySet<IRNodeId> => impact.get(id) ?? empty,\n };\n}\n\n/* ───────────────────────── rewrite factory (emits origin-free drafts) ───────────────────────── */\n\n/** Every {@link NodeLike}/{@link ElementLike} carries a readonly `id`. */\nfunction idOf(n: ElementLike | NodeLike): IRNodeId {\n return (n as IRElement).id;\n}\n\n/** The pattern-kit factory: produces op DRAFTS and detached NodeSpecs without any allocation. */\nexport function createRewriteFactory(): RewriteFactory {\n return {\n unwrap(target: ElementLike): RewriteOpDraft {\n return { op: 'unwrap', target: idOf(target) };\n },\n removeNode(target: NodeLike): RewriteOpDraft {\n return { op: 'removeNode', target: idOf(target) };\n },\n replaceWith(target: NodeLike, replacement: NodeSpec): RewriteOpDraft {\n return { op: 'replaceWith', target: idOf(target), replacement };\n },\n wrap(target: NodeLike, wrapper: ElementSpec): RewriteOpDraft {\n return { op: 'wrap', target: idOf(target), wrapper };\n },\n insertBefore(anchor: NodeLike, node: NodeSpec): RewriteOpDraft {\n return { op: 'insertBefore', anchor: idOf(anchor), node };\n },\n insertAfter(anchor: NodeLike, node: NodeSpec): RewriteOpDraft {\n return { op: 'insertAfter', anchor: idOf(anchor), node };\n },\n moveNode(target: NodeLike, newParent: ElementLike, index: number): RewriteOpDraft {\n return { op: 'moveNode', target: idOf(target), newParent: idOf(newParent), index };\n },\n mergeSiblings(first: NodeLike, second: NodeLike): RewriteOpDraft {\n return { op: 'mergeSiblings', first: idOf(first), second: idOf(second) };\n },\n setClassList(target: ElementLike, style: StyleMap, preserveOpaque = true): RewriteOpDraft {\n return { op: 'setClassList', target: idOf(target), style, preserveOpaque };\n },\n mergeStyle(\n target: ElementLike,\n source: ElementLike | null,\n style: StyleMap,\n onConflict: StyleConflictPolicy = 'abort',\n ): RewriteOpDraft {\n return {\n op: 'mergeStyle',\n target: idOf(target),\n source: source ? idOf(source) : null,\n style,\n onConflict,\n };\n },\n foldInheritedStyles(\n from: ElementLike,\n into: ElementLike | readonly ElementLike[],\n opts?: { only?: readonly import('./types').CssProperty[]; conditions?: 'base' | 'all' },\n ): RewriteOpDraft {\n const list: readonly ElementLike[] = Array.isArray(into)\n ? (into as readonly ElementLike[])\n : [into as ElementLike];\n return {\n op: 'foldInheritedStyles',\n from: idOf(from),\n into: list.map((t) => idOf(t)),\n properties: opts?.only ?? 'all-inherited',\n conditions: opts?.conditions ?? 'base',\n };\n },\n element(spec: ElementSpec): NodeSpec {\n return spec;\n },\n text(value: string): NodeSpec {\n return { kind: 'text', value };\n },\n keep(node: NodeLike): NodeSpec {\n return { kind: 'ref', ref: idOf(node) };\n },\n };\n}\n\n/* ───────────────────────── match context ───────────────────────── */\n\nfunction ro<T>(v: T): DeepReadonly<T> {\n return v as DeepReadonly<T>;\n}\n\n/** Build the read-only {@link MatchContext} a pattern's `evaluate` receives for one element. */\nexport function buildMatchContext(\n doc: IRDocument,\n elementId: IRNodeId,\n resolver: StyleResolver,\n selectors: SelectorIndex,\n safety: import('./types').SafetyLevel,\n phase: PassPhase,\n iteration: number,\n): MatchContext {\n const self = getElement(doc, elementId)!;\n\n const parentEl = (): DeepReadonly<IRElement> | null => {\n if (self.parent == null) return null;\n const p = doc.nodes.get(self.parent);\n return p && p.kind === 'element' ? ro(p) : null;\n };\n\n const elementChildren = (): readonly DeepReadonly<IRElement>[] => {\n const out: DeepReadonly<IRElement>[] = [];\n for (const c of self.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') out.push(ro(cn));\n }\n return out;\n };\n\n const ancestors = (): readonly DeepReadonly<IRElement>[] => {\n const out: DeepReadonly<IRElement>[] = [];\n let cur: IRNodeId | null = self.parent;\n while (cur != null) {\n const n: IRNode | undefined = doc.nodes.get(cur);\n if (!n) break;\n if (n.kind === 'element') out.push(ro(n));\n cur = n.parent;\n }\n return out;\n };\n\n const siblingAt = (delta: number): DeepReadonly<IRNode> | null => {\n if (self.parent == null) return null;\n const p = doc.nodes.get(self.parent);\n if (!p || (p.kind !== 'element' && p.kind !== 'fragment')) return null;\n const i = p.children.indexOf(elementId);\n const sib = p.children[i + delta];\n if (sib == null) return null;\n const sn = doc.nodes.get(sib);\n return sn ? ro(sn) : null;\n };\n\n const computedOf = (n: NodeLike): StyleMap => {\n const node = doc.nodes.get((n as IRNode).id);\n return node && node.kind === 'element' ? node.computed : emptyStyleMap();\n };\n\n return {\n node: ro(self),\n doc: ro(doc),\n resolver,\n selectors,\n safety,\n phase,\n iteration,\n parent: parentEl,\n elementChildren,\n onlyElementChild(): DeepReadonly<IRElement> | null {\n const els = elementChildren();\n return els.length === 1 ? els[0]! : null;\n },\n computed(): StyleMap {\n return self.computed;\n },\n computedOf,\n isOpaque(n?: ElementLike): boolean {\n const target = n ? doc.nodes.get((n as IRElement).id) : self;\n if (!target || target.kind !== 'element') return true;\n return target.classes.opaque || target.meta.hasSpreadAttrs;\n },\n ancestors,\n closest(pred): DeepReadonly<IRElement> | null {\n for (const a of ancestors()) if (pred(a)) return a;\n return null;\n },\n prevSibling(): DeepReadonly<IRNode> | null {\n return siblingAt(-1);\n },\n nextSibling(): DeepReadonly<IRNode> | null {\n return siblingAt(1);\n },\n nthChildIndex(): number {\n if (self.parent == null) return 1;\n const p = doc.nodes.get(self.parent);\n if (!p || (p.kind !== 'element' && p.kind !== 'fragment')) return 1;\n let idx = 0;\n for (const c of p.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') {\n idx += 1;\n if (c === elementId) return idx;\n }\n }\n return idx;\n },\n };\n}\n","/**\n * @domflax/core — static classification of a flatten (the VERIFIER-GATED safety core).\n *\n * A flatten pattern matches on `paintsNothing` + a structural/style signature, but unwrapping a\n * wrapper can still change rendering: a wrapper with non-paint layout styles (e.g. `px-4 py-4`) drops\n * that padding when removed (it is NOT reproduced on the surviving child), and a centering wrapper\n * collapsed to `place-self:center` only stays centered when the child's NEW parent is flex/grid. The\n * existing emittability revert only checks the ADDED style is re-emittable — not that the wrapper's\n * own styles survive, nor that the parent context holds.\n *\n * {@link classifyFlattenOps} answers, for one applied flatten op-group, whether it is:\n *\n * • `'provably-safe'` — removing the wrapper changes NOTHING renderable: the wrapper\n * establishes no box/formatting/stacking context, has no non-inherited\n * own declaration that the rewrite does not reproduce on the surviving\n * child, AND the rewrite adds no parent-context-dependent self-alignment\n * (unless the new parent is statically flex/grid). Examples: passthrough\n * / empty-style / display-contents / redundant-fragment wrappers.\n * • `'needs-verification'` — anything else (drops/relies on a style, or centering→place-self).\n *\n * Pure + dependency-free: only the `./types` contract + `./builders` accessors.\n */\n\nimport { conditionKey, getElement } from './builders';\nimport type {\n CssProperty,\n IRDocument,\n IRElement,\n IRNodeId,\n RewriteOp,\n StyleDecl,\n StyleMap,\n StyleNormalizer,\n} from './types';\n\n/** The static verdict for one flatten op-group. */\nexport type FlattenClass = 'provably-safe' | 'needs-verification';\n\n/** A classified flatten plus the structural anchors a verifier needs to render before/after. */\nexport interface FlattenClassification {\n readonly kind: FlattenClass;\n /** The unwrapped wrapper (in the BEFORE doc), or null when the group removes no element box. */\n readonly wrapperId: IRNodeId | null;\n /** The surviving child styles fold onto (the AFTER subtree root), or null. */\n readonly childId: IRNodeId | null;\n}\n\n/* ───────────────────────── display / context reasoning ───────────────────────── */\n\nconst DISPLAY = 'display' as CssProperty;\nconst POSITION = 'position' as CssProperty;\nconst TRANSFORM = 'transform' as CssProperty;\n\n/** Displays that generate no independent formatting context for the wrapper's children. */\nconst CONTEXT_SAFE_DISPLAYS: ReadonlySet<string> = new Set(['block', 'contents', '']);\n/** `position` values that neither establish a containing block nor offset the element. */\nconst STATIC_POSITIONS: ReadonlySet<string> = new Set(['static', '']);\n\n/** Self-alignment properties whose effect depends on the parent being a flex/grid container. */\nconst SELF_ALIGN_PROPS: readonly CssProperty[] = [\n 'place-self' as CssProperty,\n 'align-self' as CssProperty,\n 'justify-self' as CssProperty,\n];\n/** Self-alignment values that are no-ops (so adding them assumes nothing about the parent). */\nconst NEUTRAL_ALIGN: ReadonlySet<string> = new Set(['auto', 'normal', 'auto auto', '']);\n/** Parent displays under which `place-self`/`*-self` centering actually takes effect. */\nconst FLEX_GRID_DISPLAYS: ReadonlySet<string> = new Set(['flex', 'inline-flex', 'grid', 'inline-grid']);\n\n/**\n * True when the wrapper establishes a box/formatting/stacking context that positions or sizes its\n * children — so removing its box could move/resize the surviving child. Derived from the COMPUTED\n * style (the frontend leaves the `meta.establishes*` flags unset for class-resolved styles), exactly\n * how `hasOwnVisualStyle` reasons over the computed map.\n */\nfunction establishesChildContext(sm: StyleMap): boolean {\n for (const block of sm.blocks.values()) {\n const display = block.decls.get(DISPLAY);\n if (display && !CONTEXT_SAFE_DISPLAYS.has(String(display.value))) return true;\n const position = block.decls.get(POSITION);\n if (position && !STATIC_POSITIONS.has(String(position.value))) return true;\n const transform = block.decls.get(TRANSFORM);\n if (transform && String(transform.value) !== 'none') return true;\n }\n return false;\n}\n\n/* ───────────────────────── declaration reasoning ───────────────────────── */\n\nfunction isInherited(decl: StyleDecl, norm: StyleNormalizer): boolean {\n if (decl.inherited) return true;\n try {\n return norm.inherited.isInherited(decl.property);\n } catch {\n return false;\n }\n}\n\n/** True when the child reproduces this exact declaration (same property + value) in the same condition. */\nfunction childReproduces(\n childComputed: StyleMap | null,\n conditionK: string,\n prop: CssProperty,\n value: string,\n): boolean {\n if (!childComputed) return false;\n const block = childComputed.blocks.get(conditionK as never);\n if (!block) return false;\n const d = block.decls.get(prop);\n return d != null && String(d.value) === value;\n}\n\n/**\n * True when the wrapper carries a non-inherited declaration that is NOT reproduced on the surviving\n * child — i.e. flattening would DROP a renderable style. `display`/`position`/`transform` are skipped\n * because {@link establishesChildContext} already governs them (and when it passed they are no-ops).\n */\nfunction dropsOwnStyle(\n wrapperComputed: StyleMap,\n childComputed: StyleMap | null,\n norm: StyleNormalizer,\n): boolean {\n for (const block of wrapperComputed.blocks.values()) {\n const ck = conditionKey(block.condition);\n for (const [prop, decl] of block.decls) {\n if (prop === DISPLAY || prop === POSITION || prop === TRANSFORM) continue;\n if (isInherited(decl, norm)) continue; // folded onto the child by foldInheritedStyles\n if (!childReproduces(childComputed, ck, prop, String(decl.value))) return true;\n }\n }\n return false;\n}\n\n/* ───────────────────────── parent-context reasoning ───────────────────────── */\n\n/** The element's base-condition `display` value (normalized), or '' when unset/not an element. */\nfunction displayOf(el: IRElement | undefined, norm: StyleNormalizer): string {\n if (!el) return '';\n for (const block of norm.normalizeStyleMap(el.computed).blocks.values()) {\n if (block.condition.media === '' && block.condition.states.length === 0 && block.condition.pseudoElement === '') {\n const d = block.decls.get(DISPLAY);\n if (d) return String(d.value);\n }\n }\n return '';\n}\n\n/** True when unwrapping `wrapper` reparents the child UNDER a flex/grid container in the before-tree. */\nfunction newParentIsFlexOrGrid(before: IRDocument, wrapper: IRElement, norm: StyleNormalizer): boolean {\n if (wrapper.parent == null) return false;\n const p = before.nodes.get(wrapper.parent);\n if (!p || p.kind !== 'element') return false;\n return FLEX_GRID_DISPLAYS.has(displayOf(p, norm));\n}\n\n/**\n * True when the rewrite GRANTS the child a parent-context-dependent self-alignment (place-self /\n * align-self / justify-self with a non-neutral value) that was not already on it — centering that only\n * holds if the new parent is flex/grid.\n */\nfunction addsParentContextStyle(\n childBefore: StyleMap | null,\n childAfter: StyleMap | null,\n norm: StyleNormalizer,\n): boolean {\n if (!childAfter) return false;\n const before = childBefore ? norm.normalizeStyleMap(childBefore) : null;\n const after = norm.normalizeStyleMap(childAfter);\n for (const block of after.blocks.values()) {\n const ck = conditionKey(block.condition);\n for (const prop of SELF_ALIGN_PROPS) {\n const d = block.decls.get(prop);\n if (!d || NEUTRAL_ALIGN.has(String(d.value))) continue;\n const prev = before?.blocks.get(ck as never)?.decls.get(prop);\n if (!prev || String(prev.value) !== String(d.value)) return true;\n }\n }\n return false;\n}\n\n/* ───────────────────────── op-group anchors ───────────────────────── */\n\n/** The wrapper the group unwraps (the structural removal), or null when the group removes no box. */\nfunction unwrapTargetOf(ops: readonly RewriteOp[]): IRNodeId | null {\n for (const op of ops) if (op.op === 'unwrap') return op.target;\n return null;\n}\n\n/** The surviving child styles fold onto: the mergeStyle/fold target, else the wrapper's sole element child. */\nfunction survivingChildOf(ops: readonly RewriteOp[], wrapper: IRElement, before: IRDocument): IRNodeId | null {\n for (const op of ops) if (op.op === 'mergeStyle') return op.target;\n for (const op of ops) if (op.op === 'foldInheritedStyles' && op.into.length > 0) return op.into[0]!;\n for (const c of wrapper.children) {\n const n = before.nodes.get(c);\n if (n && n.kind === 'element') return c;\n }\n return null;\n}\n\n/* ───────────────────────── the classifier ───────────────────────── */\n\n/**\n * Statically classify one applied flatten op-group. `before` is the doc as it was BEFORE the group's\n * ops; `after` is the result of applying them.\n *\n * A group that unwraps no element box (e.g. {@link redundant-fragment}, or a style-only flatten) is\n * `provably-safe` — there is no box whose removal could move/resize anything. Otherwise the three\n * criteria above decide.\n */\nexport function classifyFlattenOps(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n norm: StyleNormalizer,\n): FlattenClassification {\n const wrapperId = unwrapTargetOf(ops);\n if (wrapperId == null) return { kind: 'provably-safe', wrapperId: null, childId: null };\n\n const wrapper = before.nodes.get(wrapperId);\n // A fragment carries no box and no computed style — unwrapping it is always layout-identical.\n if (!wrapper || wrapper.kind !== 'element') {\n return { kind: 'provably-safe', wrapperId: null, childId: null };\n }\n\n const childId = survivingChildOf(ops, wrapper, before);\n const wrapperComputed = norm.normalizeStyleMap(wrapper.computed);\n const childAfter = childId != null ? getElement(after, childId)?.computed ?? null : null;\n const childBefore = childId != null ? getElement(before, childId)?.computed ?? null : null;\n\n // (A) wrapper positions/sizes its children → removing its box can move/resize them.\n if (establishesChildContext(wrapperComputed)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n // (B) wrapper drops a non-inherited own style the child does not reproduce.\n if (dropsOwnStyle(wrapperComputed, childAfter ? norm.normalizeStyleMap(childAfter) : null, norm)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n // (C) rewrite adds parent-context-dependent centering, but the new parent is not statically flex/grid.\n if (addsParentContextStyle(childBefore, childAfter, norm) && !newParentIsFlexOrGrid(before, wrapper, norm)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n\n return { kind: 'provably-safe', wrapperId, childId };\n}\n","/**\n * @domflax/core — pass manager (the sync, static flatten driver).\n *\n * Runs {@link Pattern}s grouped by {@link PassPhase} in declared order, driving the `flatten` phase to\n * a fixpoint under a max-iteration budget, isolating per-node pattern errors into {@link Diagnostic}s\n * (a thrown pattern never aborts the run — it becomes `DF_PATTERN_THREW`), and applying the static\n * flatten policy ({@link ApplyContext.gate}) — under `'provably-safe'` only provably layout-neutral\n * flattens commit, so the transform never changes rendering and never launches a browser.\n *\n * The supporting contexts (resolvers, selector index, rewrite factory, match context) live in\n * `./pass-context`; the static flatten classifier in `./flatten-safety`. Dependency-free: only the\n * `./types` contract + sibling runtime helpers.\n */\n\nimport type {\n ApplyContext,\n Diagnostic,\n FixpointConfig,\n HaltReason,\n IRDocument,\n IRNodeId,\n Pass,\n PassManager,\n PassPhase,\n Pattern,\n PhaseRunResult,\n RewriteFactory,\n RewriteOp,\n RewriteOpDraft,\n StyleMap,\n StyleNormalizer,\n StyleResolver,\n SyntheticSink,\n EmitContext,\n} from './types';\n\nimport { childIds, elementIds, getElement } from './builders';\nimport { applyOps } from './ops';\nimport { buildMatchContext, createRewriteFactory } from './pass-context';\nimport { classifyFlattenOps } from './flatten-safety';\n\n// Re-export the supporting contexts so `@domflax/core` consumers keep importing them from here / the\n// barrel exactly as before this module was split.\nexport {\n buildMatchContext,\n buildSelectorIndex,\n createNullResolver,\n createNullSelectorIndex,\n createRewriteFactory,\n} from './pass-context';\n\n/* ───────────────────────── defaults ───────────────────────── */\n\nexport const DEFAULT_FIXPOINT: FixpointConfig = {\n maxIterations: 16,\n phases: { flatten: 16, compress: 8, extract: 4 },\n onBudgetExhausted: 'warn',\n detectOscillation: true,\n};\n\nexport const PHASE_ORDER: readonly PassPhase[] = ['flatten', 'compress', 'extract'];\n\n/* ───────────────────────── op stamping + phase grouping ───────────────────────── */\n\nexport function stampOrigin(draft: RewriteOpDraft, pattern: Pattern): RewriteOp {\n return {\n ...draft,\n origin: { pattern: pattern.name, category: pattern.category, safety: pattern.safety },\n } as RewriteOp;\n}\n\nexport function patternsForPhase(passes: readonly Pass[], phase: PassPhase): Pattern[] {\n const out: Pattern[] = [];\n for (const pass of passes) {\n if (pass.phase !== phase) continue;\n for (const p of pass.patterns) out.push(p);\n }\n out.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n return out;\n}\n\nexport interface RunState {\n doc: IRDocument;\n}\n\n/* ───────────────────────── flatten residual-skip (never drop an unreproducible style) ───────────────────────── */\n\n/** A throwaway {@link SyntheticSink} for the emit exactness probe (registrations are discarded). */\nfunction probeSink(): SyntheticSink {\n return {\n register(s): string {\n return s.className;\n },\n drain(): readonly never[] {\n return [];\n },\n };\n}\n\n/** Nodes a group writes STYLE onto (the survivors a flatten transfers declarations to). */\nfunction styleWriteTargets(ops: readonly RewriteOp[]): IRNodeId[] {\n const ids: IRNodeId[] = [];\n for (const op of ops) {\n if (op.op === 'mergeStyle' || op.op === 'setClassList') ids.push(op.target);\n else if (op.op === 'foldInheritedStyles') ids.push(...op.into);\n }\n return ids;\n}\n\n/** True iff the resolver can EXACTLY reverse-emit `sm` (no residual). An empty map is trivially exact. */\nfunction emitIsExact(resolver: StyleResolver, normalizer: StyleNormalizer, sm: StyleMap): boolean {\n if (sm.blocks.size === 0) return true;\n try {\n const ctx: EmitContext = { normalizer, sink: probeSink() };\n const r = resolver.emit(sm, ctx);\n return r.exact && r.residual == null;\n } catch {\n return true; // a throwing resolver must never block a flatten\n }\n}\n\n/**\n * T5 — flatten must never DROP a style it can't reproduce. After a flatten transfers declarations onto\n * a surviving (rewritable) element, if the resolver can no longer EXACTLY reverse-emit that element's\n * computed style — and it could before — the flatten would silently lose the residual declarations\n * during reverse-emit, so the whole flatten is reverted (the wrapper is kept). Pre-existing residue\n * (already non-exact before the flatten) is not blamed on the flatten and does not trigger a revert.\n */\nexport function flattenWouldDropStyle(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n resolver: StyleResolver,\n normalizer: StyleNormalizer,\n): boolean {\n for (const id of styleWriteTargets(ops)) {\n const newEl = getElement(after, id);\n if (!newEl) continue; // target was itself removed — its style lives on the survivor we also check\n // Opaque / dynamic class lists are kept verbatim by reverse-emit, so no style is dropped there.\n if (newEl.classes.opaque || newEl.classes.hasDynamic) continue;\n if (emitIsExact(resolver, normalizer, newEl.computed)) continue;\n const oldEl = getElement(before, id);\n const wasExact = !oldEl || emitIsExact(resolver, normalizer, oldEl.computed);\n if (wasExact) return true; // the flatten introduced an unreproducible style → revert\n }\n return false;\n}\n\n/* ───────────────────────── flatten gate decision (shared sync core) ───────────────────────── */\n\nexport type FlattenVerdict = 'commit' | 'revert';\n\n/**\n * Decide what to do with a freshly-applied flatten op-group, given the gate. Returns:\n * • `'commit'` — keep the outcome (the historical path for `'all'`, and provably-safe flattens).\n * • `'revert'` — discard + bar the node (residual-drop, or a needs-verification flatten under the\n * `'provably-safe'` gate).\n *\n * `before`/`after` are the docs immediately around the group's application.\n */\nexport function flattenVerdict(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n ctx: ApplyContext,\n): FlattenVerdict {\n // T5 (independent of the gate): a flatten must never drop a style the resolver can't re-emit.\n if (flattenWouldDropStyle(before, after, ops, ctx.resolver, ctx.normalizer)) return 'revert';\n\n const gate = ctx.gate ?? 'all';\n if (gate === 'all') return 'commit';\n\n const cls = classifyFlattenOps(before, after, ops, ctx.normalizer);\n return cls.kind === 'provably-safe' ? 'commit' : 'revert';\n}\n\n/* ───────────────────────── per-element pattern evaluation (shared) ───────────────────────── */\n\n/**\n * Evaluate every pattern against `elId` until one produces ops; returns the stamped op list (and its\n * pattern), or null when no pattern matched. Pattern throws become `DF_PATTERN_THREW` diagnostics.\n */\nexport function evaluateElement(\n doc: IRDocument,\n elId: IRNodeId,\n patterns: readonly Pattern[],\n ctx: ApplyContext,\n factory: RewriteFactory,\n phase: PassPhase,\n iteration: number,\n diagnostics: Diagnostic[],\n): { ops: RewriteOp[]; pattern: Pattern } | null {\n for (const pattern of patterns) {\n if (pattern.safety > ctx.safetyCeiling) continue;\n let drafts: readonly RewriteOpDraft[] = [];\n try {\n const mctx = buildMatchContext(doc, elId, ctx.resolver, ctx.selectors, ctx.safetyCeiling, phase, iteration);\n const result = pattern.evaluate(mctx, factory);\n if (!result) continue;\n drafts = result.ops;\n if (result.diagnostics) for (const d of result.diagnostics) diagnostics.push(d);\n } catch (err) {\n diagnostics.push({\n code: 'DF_PATTERN_THREW',\n severity: 'error',\n message: `pattern '${pattern.name}' threw: ${String((err as Error)?.message ?? err)}`,\n nodeId: elId,\n pattern: pattern.name,\n phase,\n iteration,\n cause: err,\n });\n continue;\n }\n if (drafts.length === 0) continue;\n return { ops: drafts.map((d) => stampOrigin(d, pattern)), pattern };\n }\n return null;\n}\n\n/** Emit the diagnostic recorded when a flatten is reverted by the gate / residual guard. */\nexport function revertDiagnostic(\n pattern: Pattern,\n elId: IRNodeId,\n phase: PassPhase,\n iteration: number,\n resolverId: string,\n): Diagnostic {\n return {\n code: 'DF_VERIFY_REVERTED',\n severity: 'warn',\n message:\n `flatten '${pattern.name}' reverted on node ${elId}: it would change rendering (drops a style, ` +\n `establishes layout context, or assumes a parent context) and was not proven safe by resolver ` +\n `'${resolverId}'`,\n nodeId: elId,\n pattern: pattern.name,\n phase,\n iteration,\n };\n}\n\n/* ───────────────────────── one sweep (sync) ───────────────────────── */\n\n/**\n * One sweep of a phase: evaluate every pattern against every live element, collect op drafts, stamp\n * origin, apply, then commit/revert per {@link flattenVerdict}. Returns the number of ops applied\n * (0 ⇒ fixpoint for this phase). Under the `'provably-safe'` gate, any flatten that is not provably\n * safe is reverted — the transform is fully static and never changes rendering.\n */\nfunction runSweep(\n state: RunState,\n patterns: readonly Pattern[],\n ctx: ApplyContext,\n factory: RewriteFactory,\n phase: PassPhase,\n iteration: number,\n touched: Set<IRNodeId>,\n diagnostics: Diagnostic[],\n flattenBarred: Set<IRNodeId>,\n): number {\n let appliedOps = 0;\n\n for (const elId of elementIds(state.doc)) {\n const el = getElement(state.doc, elId);\n if (!el) continue; // removed earlier in this sweep\n if (phase === 'flatten' && flattenBarred.has(elId)) continue;\n\n const evaluated = evaluateElement(state.doc, elId, patterns, ctx, factory, phase, iteration, diagnostics);\n if (!evaluated) continue;\n const { ops, pattern } = evaluated;\n\n const outcome = applyOps(state.doc, ops, ctx);\n for (const d of outcome.result.diagnostics) diagnostics.push(d);\n if (outcome.result.appliedGroups === 0) continue;\n\n if (phase === 'flatten') {\n const verdict = flattenVerdict(state.doc, outcome.doc, ops, ctx);\n if (verdict !== 'commit') {\n // Discard the outcome (keep the wrapper) AND bar this node from any further flatten this run.\n diagnostics.push(revertDiagnostic(pattern, elId, phase, iteration, ctx.resolver.id));\n flattenBarred.add(elId);\n continue;\n }\n }\n\n state.doc = outcome.doc;\n appliedOps += outcome.result.appliedGroups;\n for (const id of outcome.result.touched) touched.add(id);\n for (const id of outcome.result.created) touched.add(id);\n }\n return appliedOps;\n}\n\n/* ───────────────────────── oscillation fingerprint ───────────────────────── */\n\n/** Cheap structural fingerprint of the document for oscillation detection. */\nexport function docFingerprint(doc: IRDocument): string {\n const parts: string[] = [];\n const visit = (id: IRNodeId): void => {\n const n = doc.nodes.get(id);\n if (!n) return;\n parts.push(`${id}:${n.kind}`);\n for (const c of childIds(n)) visit(c);\n };\n visit(doc.root);\n return parts.join('|');\n}\n\n/* ───────────────────────── the fixpoint driver (sync) ───────────────────────── */\n\n/** A single phase's terminal result, built from the loop's accounting. */\nexport interface PhaseLoopState {\n iterations: number;\n converged: boolean;\n haltReason: HaltReason;\n readonly touched: Set<IRNodeId>;\n readonly diagnostics: Diagnostic[];\n readonly seen: Set<string>;\n}\n\n/** Record the budget-exhausted diagnostic + finalize a phase result. Shared by sync + async drivers. */\nexport function finalizePhase(\n phase: PassPhase,\n s: PhaseLoopState,\n budget: number,\n onBudgetExhausted: 'warn' | 'error',\n): PhaseRunResult {\n if (!s.converged && s.haltReason !== 'oscillation') {\n s.haltReason = 'budget';\n s.diagnostics.push({\n code: 'DF_FIXPOINT_BUDGET',\n severity: onBudgetExhausted === 'error' ? 'error' : 'warn',\n message: `phase '${phase}' exhausted ${budget}-iteration budget`,\n phase,\n iteration: s.iterations,\n });\n }\n return {\n phase,\n iterations: s.iterations,\n converged: s.converged,\n haltReason: s.haltReason,\n touched: s.touched,\n diagnostics: s.diagnostics,\n };\n}\n\n/**\n * Runs `passes` over `doc` to a per-phase fixpoint (synchronous). This is the concrete entry the\n * pipeline calls. Under the `'provably-safe'` gate, flattens that are not provably layout-neutral are\n * reverted — the transform is fully static and never changes rendering.\n */\nexport function runPasses(\n doc: IRDocument,\n passes: readonly Pass[],\n ctx: ApplyContext,\n config?: FixpointConfig,\n): { readonly doc: IRDocument; readonly results: readonly PhaseRunResult[] } {\n const cfg: FixpointConfig = { ...DEFAULT_FIXPOINT, ...config };\n const factory = createRewriteFactory();\n const state: RunState = { doc };\n const results: PhaseRunResult[] = [];\n // Nodes barred from flattening after a revert — persists across sweeps/phases.\n const flattenBarred = new Set<IRNodeId>();\n\n for (const phase of PHASE_ORDER) {\n const patterns = patternsForPhase(passes, phase);\n const budget = cfg.phases[phase] ?? cfg.maxIterations;\n const s: PhaseLoopState = {\n iterations: 0,\n converged: false,\n haltReason: 'converged',\n touched: new Set(),\n diagnostics: [],\n seen: new Set(),\n };\n\n if (patterns.length === 0) {\n s.converged = true;\n results.push(finalizePhase(phase, s, budget, cfg.onBudgetExhausted));\n continue;\n }\n\n while (s.iterations < budget) {\n s.iterations += 1;\n const applied = runSweep(\n state,\n patterns,\n ctx,\n factory,\n phase,\n s.iterations,\n s.touched,\n s.diagnostics,\n flattenBarred,\n );\n\n if (applied === 0) {\n s.converged = true;\n break;\n }\n\n if (cfg.detectOscillation) {\n const fp = docFingerprint(state.doc);\n if (s.seen.has(fp)) {\n s.haltReason = 'oscillation';\n s.diagnostics.push({\n code: 'DF_FIXPOINT_OSCILLATION',\n severity: 'warn',\n message: `phase '${phase}' oscillated; halting`,\n phase,\n iteration: s.iterations,\n });\n break;\n }\n s.seen.add(fp);\n }\n }\n\n results.push(finalizePhase(phase, s, budget, cfg.onBudgetExhausted));\n }\n\n return { doc: state.doc, results };\n}\n\n/** A {@link PassManager} that runs the given passes (carried on the manager instance). */\nexport function createPassManager(passes: readonly Pass[]): PassManager {\n return {\n run(doc: IRDocument, ctx: ApplyContext, config?: FixpointConfig): readonly PhaseRunResult[] {\n return runPasses(doc, passes, ctx, config).results;\n },\n };\n}\n","/**\n * @domflax/core — the pure, single-file pipeline.\n *\n * Wires injected interfaces together: {@link Frontend} → resolve → {@link PassManager} →\n * {@link Backend}. Core itself stays dependency-free; the resolver, frontend, and backend are all\n * supplied by the caller, so no heavy third-party libs ever reach this package.\n */\n\nimport type {\n ApplyContext,\n Backend,\n BackendContext,\n CodegenResult,\n Diagnostic,\n EditPlan,\n Frontend,\n FrontendParseContext,\n IRDocument,\n IRElement,\n PassPhase,\n Pipeline,\n PipelineInput,\n PipelineOutput,\n PipelineStats,\n SourceSpan,\n StyleMap,\n SyntheticClass,\n SyntheticSink,\n} from './types';\n\nimport { elementIds, getElement } from './builders';\nimport { createNullSelectorIndex, runPasses } from './pass-manager';\n\n/* ───────────────────────── synthetic sink ───────────────────────── */\n\n/** A minimal in-memory {@link SyntheticSink}: dedupes by className, drains in insertion order. */\nexport function createSyntheticSink(): SyntheticSink {\n const map = new Map<string, SyntheticClass>();\n return {\n register(s: SyntheticClass): string {\n if (!map.has(s.className)) map.set(s.className, s);\n return s.className;\n },\n drain(): readonly SyntheticClass[] {\n return [...map.values()];\n },\n };\n}\n\n/* ───────────────────────── resolve step ───────────────────────── */\n\nfunction staticClassTokens(el: IRElement): string[] {\n const out: string[] = [];\n for (const seg of el.classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/**\n * Populate each element's `computed` StyleMap from its author classes via the injected resolver.\n * Opaque/spread elements and elements without static classes are left untouched. Resolver throws\n * are isolated into diagnostics (a stub resolver may legitimately be NotImplemented).\n */\nfunction resolveStyles(\n doc: IRDocument,\n input: PipelineInput,\n diagnostics: Diagnostic[],\n): void {\n const { resolver, normalizer } = input;\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el || el.classes.opaque) continue;\n const tokens = staticClassTokens(el);\n if (tokens.length === 0) continue;\n try {\n const result = resolver.resolve({\n classes: tokens,\n element: {\n tagName: el.tag,\n namespace: el.namespace === 'svg' ? 'svg' : 'html',\n },\n });\n let styles: StyleMap = result.styles;\n try {\n styles = normalizer.normalizeStyleMap(styles);\n } catch {\n /* normalizer is optional/stubbed — keep raw styles */\n }\n el.computed = styles;\n for (const w of result.warnings) {\n diagnostics.push({\n code: 'DF_STYLE_CONFLICT_UNRESOLVED',\n severity: w.severity,\n message: w.message,\n nodeId: id,\n });\n }\n } catch (err) {\n diagnostics.push({\n code: 'DF_OP_PRECONDITION_FAILED',\n severity: 'debug',\n message: `resolve skipped for <${el.tag}>: ${String((err as Error)?.message ?? err)}`,\n nodeId: id,\n cause: err,\n });\n }\n }\n}\n\n/* ───────────────────────── the pipeline ───────────────────────── */\n\nconst ZERO_ITERATIONS: Readonly<Record<PassPhase, number>> = {\n flatten: 0,\n compress: 0,\n extract: 0,\n};\n\nclass DefaultPipeline implements Pipeline {\n run(input: PipelineInput): PipelineOutput {\n const startedAt = now();\n const diagnostics: Diagnostic[] = [];\n const report = (d: Diagnostic): void => {\n diagnostics.push(d);\n input.reporter?.report(d);\n };\n\n // 1. PARSE ────────────────────────────────────────────────────────────\n const parseCtx: FrontendParseContext = {\n id: input.id,\n kind: input.kind,\n resolver: input.resolver,\n normalizer: input.normalizer,\n config: { preserveComments: input.config?.preserveComments ?? true },\n onDiagnostic: report,\n };\n if (input.babelAst !== undefined) parseCtx.babelAst = input.babelAst;\n\n const parsed = input.frontend.parse(input.code, parseCtx);\n for (const d of parsed.diagnostics) report(d);\n const doc = parsed.doc;\n const nodesIn = doc.nodes.size;\n\n // 2. RESOLVE ──────────────────────────────────────────────────────────\n resolveStyles(doc, input, diagnostics);\n\n // 3. PASSES (fixpoint per phase) ──────────────────────────────────────\n const ctx: ApplyContext = {\n doc,\n safetyCeiling: input.config?.safety ?? 2,\n normalizer: input.normalizer,\n selectors: createNullSelectorIndex(),\n resolver: input.resolver,\n };\n const { doc: optimized, results } = runPasses(doc, input.passes, ctx, fixpointFrom(input));\n\n let opsApplied = 0;\n const iterations: Record<PassPhase, number> = { ...ZERO_ITERATIONS };\n for (const r of results) {\n iterations[r.phase] = r.iterations;\n for (const d of r.diagnostics) {\n diagnostics.push(d);\n input.reporter?.report(d);\n }\n opsApplied += r.touched.size;\n }\n\n // 4. PRINT ────────────────────────────────────────────────────────────\n const editPlan: EditPlan = {\n moduleId: input.id,\n ops: [],\n provenance: new Map(),\n };\n const backendCtx: BackendContext = {\n normalizer: input.normalizer,\n resolver: input.resolver,\n sink: createSyntheticSink(),\n eol: eolOf(optimized),\n onDiagnostic: report,\n };\n const printed: CodegenResult = input.backend.print(optimized, editPlan, backendCtx);\n for (const d of printed.diagnostics) {\n diagnostics.push(d);\n input.reporter?.report(d);\n }\n\n // 5. ASSEMBLE OUTPUT ──────────────────────────────────────────────────\n const stats: PipelineStats = {\n nodesIn,\n nodesOut: optimized.nodes.size,\n opsApplied,\n iterations,\n durationMs: now() - startedAt,\n };\n const touched: readonly SourceSpan[] = printed.edits.map((e) => e.span);\n\n return {\n code: printed.code,\n map: printed.map,\n changed: printed.code !== input.code,\n touched,\n diagnostics,\n stats,\n doc: optimized,\n editPlan,\n };\n }\n}\n\nfunction fixpointFrom(input: PipelineInput): import('./types').FixpointConfig | undefined {\n const fp = input.config?.fixpoint;\n if (!fp) return undefined;\n return {\n maxIterations: fp.maxIterations ?? 16,\n phases: fp.phases ?? {},\n onBudgetExhausted: fp.onBudgetExhausted ?? 'warn',\n detectOscillation: fp.detectOscillation ?? true,\n };\n}\n\nfunction eolOf(doc: IRDocument): '\\n' | '\\r\\n' {\n for (const src of doc.sources.values()) return src.eol;\n return '\\n';\n}\n\n// `performance` is a host global (node20 / browser) not covered by the ES2023 lib;\n// declared minimally so the runtime feature-detection below stays type-safe.\ndeclare const performance: { now(): number } | undefined;\n\nfunction now(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\n/** Build the pure single-file {@link Pipeline}. */\nexport function createPipeline(): Pipeline {\n return new DefaultPipeline();\n}\n","/**\n * @domflax/core — the shared reverse-emit step (computed → className).\n *\n * The backend re-prints `className` from each element's {@link ClassList}, but the pass manager\n * records optimized styles on `computed`. This module folds those optimized computed styles back\n * into the element's static class tokens, and is the SINGLE source of truth shared by every\n * orchestrator (the `domflax` meta package, `@domflax/cli`, and the pattern auto-test harness) so\n * their pipelines cannot diverge.\n *\n * ## REPLACE, not append\n *\n * For every TOUCHED, rewritable (non-opaque, non-dynamic) element we ask the resolver for the\n * MINIMAL class set reproducing the element's FULL computed style (`resolver.emit(el.computed)`),\n * then REPLACE the element's static tokens with it — rather than appending. Replacing is what lets\n * a compress pass actually shorten output: `px-4 py-4` collapses to `p-4`, equal `w/h` to `size-*`,\n * the four insets to `inset-0`, and fully-overridden duplicates simply disappear.\n *\n * ## Droppability gate (never lose a load-bearing class)\n *\n * A token is only removed when `resolver.selectorUsage(token).droppable` is true — i.e. it is a\n * plain, resolver-owned utility whose entire contribution is reproducible from `computed`. Tokens\n * that are unknown to the resolver, opaque (combinator/at-rule utilities whose effect never folds\n * onto the element's own box), variant-bound, or referenced by a custom-CSS selector are NOT\n * droppable and are preserved verbatim. As a safety net, if `emit` produces nothing at all we leave\n * the element's tokens untouched (a resolver that failed to load must never erase classes).\n */\n\nimport { elementIds, getElement } from './builders';\nimport { createSyntheticSink } from './pipeline';\nimport type {\n ClassList,\n ClassSegment,\n ClassToken,\n EmitContext,\n IRDocument,\n StyleNormalizer,\n StyleResolver,\n} from './types';\n\n/** All static class tokens of a {@link ClassList}, in source order. */\nfunction staticTokensOf(cl: ClassList): string[] {\n const out: string[] = [];\n for (const seg of cl.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/** A rewritable static {@link ClassList} over `tokens`, preserving the previous list's spans. */\nfunction staticClassList(prev: ClassList, tokens: readonly string[]): ClassList {\n const classTokens: ClassToken[] = tokens.map((value) => ({ value }));\n const seg: ClassSegment = { kind: 'static', tokens: classTokens };\n return {\n form: 'string-literal',\n segments: [seg],\n valueSpan: prev.valueSpan,\n attrSpan: prev.attrSpan,\n hasDynamic: false,\n opaque: false,\n rewritable: true,\n };\n}\n\n/** Two token lists are equal iff same length and same tokens in the same order. */\nfunction sameTokens(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;\n return true;\n}\n\n/**\n * Fold every TOUCHED, rewritable element's optimized computed style back into the MINIMAL static\n * class-token set (see module docs). Mutates `doc` in place.\n */\nexport function syncClassesFromComputed(\n doc: IRDocument,\n resolver: StyleResolver,\n norm: StyleNormalizer,\n): void {\n const sink = createSyntheticSink();\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el || !el.meta.touched) continue;\n if (el.classes.opaque || el.classes.hasDynamic) continue;\n\n const tokens = staticTokensOf(el.classes);\n\n // Minimal class set reproducing the FULL computed style.\n const ctx: EmitContext = { normalizer: norm, sink };\n const emitted = resolver.emit(el.computed, ctx).classes;\n // A resolver that reverse-synthesized nothing must never erase the element's classes.\n if (emitted.length === 0) continue;\n\n const emittedSet = new Set(emitted);\n const next: string[] = [];\n const seen = new Set<string>();\n\n // 1. Keep each existing token that is either NOT droppable (unknown / opaque / variant /\n // selector-bound) or still part of the emitted minimal set — preserving source order.\n for (const t of tokens) {\n if (seen.has(t)) continue;\n const keep = emittedSet.has(t) || !resolver.selectorUsage(t).droppable;\n if (keep) {\n next.push(t);\n seen.add(t);\n }\n }\n // 2. Append any newly-emitted classes not already present, in emit order.\n for (const c of emitted) {\n if (seen.has(c)) continue;\n next.push(c);\n seen.add(c);\n }\n\n if (sameTokens(next, tokens)) continue; // no churn when nothing actually changed\n el.classes = staticClassList(el.classes, next);\n }\n}\n","/**\n * @domflax/core — public API barrel.\n *\n * The type contract (`./types`) is the single source of truth for the whole monorepo; the runtime\n * modules below are the dependency-free reference implementations of the IR, the trusted applier,\n * the pass manager, and the pure pipeline.\n */\n\n// Type contract (pure types — zero runtime).\nexport type * from './types';\n\n// Runtime: IR builders + traversal.\nexport * from './builders';\n\n// Runtime: the trusted applier.\nexport * from './ops';\n\n// Runtime: pass manager + match/rewrite contexts (re-exports ./pass-context's public surface).\nexport * from './pass-manager';\n\n// Runtime: static flatten classifier (the safety core for the provably-safe gate).\nexport * from './flatten-safety';\n\n// Runtime: the pure single-file pipeline.\nexport * from './pipeline';\n\n// Runtime: the shared reverse-emit step (computed → className).\nexport * from './reverse-emit';\n","/**\n * @domflax/pattern-kit — the shared StyleMap normalizer.\n *\n * A single, syntactic-only {@link StyleNormalizer} implementation that core, the patterns, and the\n * verifier all reuse so they agree, byte-for-byte, on what two style declarations \"mean\". It NEVER\n * resolves initial/inherited/computed defaults (that is the verifier's job) — it only:\n *\n * • canonicalizes colors (`transparent` ⇒ `rgba(0, 0, 0, 0)`, hex lower-cased + 3→6 expanded,\n * `rgb()/rgba()/hsl()/hsla()` argument spacing normalized),\n * • canonicalizes units (whitespace collapsed, zero-lengths `0px`/`0%`/… ⇒ `0`),\n * • expands a fixed set of box shorthands to longhands (`padding`/`margin`/`inset`/`border-width`\n * into their four sides, `gap` into `row-gap`/`column-gap`),\n * • orders declarations by property for stable comparison.\n *\n * Dependency-free: only `@domflax/core` (types + the StyleMap builder helpers).\n */\n\nimport type {\n CssProperty,\n CssValue,\n ConditionKey,\n InheritedPropertyTable,\n StyleBlock,\n StyleDecl,\n StyleMap,\n StyleNormalizer,\n} from '@domflax/core';\n\nimport { conditionKey, emptyStyleMap } from '@domflax/core';\n\n/* ───────────────────────── inherited-property table ───────────────────────── */\n\n/**\n * Canonical, versioned set of inherited CSS longhands. Any author custom property (`--*`) is\n * also treated as inherited via the `isInherited` predicate.\n */\nconst INHERITED_PROPERTIES: readonly string[] = [\n 'azimuth',\n 'border-collapse',\n 'border-spacing',\n 'caption-side',\n 'color',\n 'cursor',\n 'direction',\n 'empty-cells',\n 'font-family',\n 'font-feature-settings',\n 'font-kerning',\n 'font-size',\n 'font-size-adjust',\n 'font-stretch',\n 'font-style',\n 'font-variant',\n 'font-variant-caps',\n 'font-variant-numeric',\n 'font-weight',\n 'hyphens',\n 'letter-spacing',\n 'line-height',\n 'list-style-image',\n 'list-style-position',\n 'list-style-type',\n 'orphans',\n 'overflow-wrap',\n 'quotes',\n 'tab-size',\n 'text-align',\n 'text-align-last',\n 'text-decoration-color',\n 'text-indent',\n 'text-justify',\n 'text-rendering',\n 'text-shadow',\n 'text-transform',\n 'text-underline-position',\n 'visibility',\n 'white-space',\n 'widows',\n 'word-break',\n 'word-spacing',\n 'writing-mode',\n '-webkit-font-smoothing',\n];\n\nfunction createInheritedTable(): InheritedPropertyTable {\n const properties = new Set<CssProperty>(INHERITED_PROPERTIES as unknown as CssProperty[]);\n return {\n version: 'domflax-inherited@1',\n properties,\n isInherited(property: CssProperty): boolean {\n // Author custom properties (`--*`) inherit by definition.\n return String(property).startsWith('--') || properties.has(property);\n },\n };\n}\n\n/* ───────────────────────── value canonicalization ───────────────────────── */\n\nconst ZERO_LENGTH_RE =\n /\\b0(?:px|em|rem|ex|ch|vh|vw|vmin|vmax|vi|vb|pt|pc|cm|mm|in|q|lh|rlh|fr|deg|rad|turn|s|ms|%)\\b/g;\n\nconst FUNC_ARGS_RE = /\\b(rgba?|hsla?|hwb|lab|lch|oklab|oklch)\\(([^()]*)\\)/gi;\n\nconst RELATIVE_UNIT_RE = /(?:\\d*\\.?\\d+)(?:em|ex|ch|lh)\\b|%/i;\n\n/**\n * Pure, syntactic value canonicalization. Idempotent: `canon(canon(v)) === canon(v)`.\n */\nfunction canonValue(raw: string): string {\n let v = raw.trim().replace(/\\s+/g, ' ');\n\n // Lower-case hex colors (#abc / #aabbcc / #aabbccff).\n v = v.replace(/#([0-9a-fA-F]{3,8})\\b/g, (_m, hex: string) => '#' + hex.toLowerCase());\n\n // Expand 3-digit hex (#abc → #aabbcc) — only when exactly 3 hex digits.\n v = v.replace(\n /#([0-9a-f])([0-9a-f])([0-9a-f])(?![0-9a-f])/g,\n (_m, r: string, g: string, b: string) => `#${r}${r}${g}${g}${b}${b}`,\n );\n\n // Canonical fully-transparent color.\n v = v.replace(/\\btransparent\\b/gi, 'rgba(0, 0, 0, 0)');\n v = v.replace(/#00000000\\b/g, 'rgba(0, 0, 0, 0)');\n\n // Collapse zero lengths/angles/times to a bare `0`.\n v = v.replace(ZERO_LENGTH_RE, '0');\n\n // Normalize the argument spacing of color/space functions: single space after each comma.\n v = v.replace(FUNC_ARGS_RE, (_m, fn: string, args: string) => {\n const parts = args\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return `${fn.toLowerCase()}(${parts.join(', ')})`;\n });\n\n return v;\n}\n\n/** True when the (canonicalized) value uses a parent-relative unit (em/ex/ch/lh/%). */\nfunction isRelativeValue(value: string): boolean {\n return RELATIVE_UNIT_RE.test(value);\n}\n\n/* ───────────────────────── shorthand expansion ───────────────────────── */\n\n/** Box-model shorthands whose 1–4 value form expands to four explicit sides. */\nconst BOX_SIDES: Readonly<Record<string, readonly [string, string, string, string]>> = {\n padding: ['padding-top', 'padding-right', 'padding-bottom', 'padding-left'],\n margin: ['margin-top', 'margin-right', 'margin-bottom', 'margin-left'],\n inset: ['top', 'right', 'bottom', 'left'],\n 'border-width': [\n 'border-top-width',\n 'border-right-width',\n 'border-bottom-width',\n 'border-left-width',\n ],\n 'border-style': [\n 'border-top-style',\n 'border-right-style',\n 'border-bottom-style',\n 'border-left-style',\n ],\n 'border-color': [\n 'border-top-color',\n 'border-right-color',\n 'border-bottom-color',\n 'border-left-color',\n ],\n};\n\n/** Split on top-level whitespace, keeping `fn(a, b)` groups intact. */\nfunction splitTopLevel(value: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let cur = '';\n for (const ch of value) {\n if (ch === '(') depth += 1;\n else if (ch === ')') depth = Math.max(0, depth - 1);\n if (depth === 0 && /\\s/.test(ch)) {\n if (cur.length > 0) {\n out.push(cur);\n cur = '';\n }\n continue;\n }\n cur += ch;\n }\n if (cur.length > 0) out.push(cur);\n return out;\n}\n\n/** Map a 1–4 value box shorthand onto its [top, right, bottom, left] sides. */\nfunction boxFourSides(values: readonly string[]): [string, string, string, string] {\n const [a, b, c, d] = values;\n switch (values.length) {\n case 1:\n return [a!, a!, a!, a!];\n case 2:\n return [a!, b!, a!, b!];\n case 3:\n return [a!, b!, c!, b!];\n default:\n return [a!, b!, c!, d!];\n }\n}\n\n/** Expand one declaration into longhand `[property, value]` pairs (single pair if not shorthand). */\nfunction expandShorthand(prop: string, value: string): Array<[string, string]> {\n const box = BOX_SIDES[prop];\n if (box) {\n const parts = splitTopLevel(value);\n if (parts.length >= 1 && parts.length <= 4) {\n const sides = boxFourSides(parts);\n return box.map((p, i) => [p, sides[i]!] as [string, string]);\n }\n return [[prop, value]];\n }\n\n if (prop === 'gap' || prop === 'grid-gap') {\n const parts = splitTopLevel(value);\n if (parts.length === 1) {\n return [\n ['row-gap', parts[0]!],\n ['column-gap', parts[0]!],\n ];\n }\n if (parts.length === 2) {\n return [\n ['row-gap', parts[0]!],\n ['column-gap', parts[1]!],\n ];\n }\n return [[prop, value]];\n }\n\n return [[prop, value]];\n}\n\n/* ───────────────────────── the normalizer ───────────────────────── */\n\nfunction makeDecl(\n table: InheritedPropertyTable,\n prop: string,\n rawValue: string,\n important: boolean,\n): StyleDecl {\n const property = prop.trim().toLowerCase() as CssProperty;\n const value = canonValue(rawValue) as CssValue;\n return {\n property,\n value,\n important,\n relativeToParent: isRelativeValue(value),\n inherited: table.isInherited(property),\n };\n}\n\nexport function createNormalizer(): StyleNormalizer {\n const inherited = createInheritedTable();\n\n const normalizeDeclaration = (\n prop: string,\n value: string,\n important: boolean,\n ): readonly StyleDecl[] => {\n const p = prop.trim().toLowerCase();\n const expanded = expandShorthand(p, value.trim());\n return expanded.map(([lp, lv]) => makeDecl(inherited, lp, lv, important));\n };\n\n const normalizeValue = (prop: CssProperty, raw: string): CssValue => {\n void prop;\n return canonValue(raw) as CssValue;\n };\n\n const normalizeStyleMap = (sm: StyleMap): StyleMap => {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const block of sm.blocks.values()) {\n const decls = new Map<CssProperty, StyleDecl>();\n // Re-canonicalize every value and re-key (the decls are already longhand).\n for (const decl of block.decls.values()) {\n const next: StyleDecl = {\n ...decl,\n value: canonValue(String(decl.value)) as CssValue,\n relativeToParent: isRelativeValue(String(decl.value)),\n inherited: inherited.isInherited(decl.property),\n };\n decls.set(next.property, next);\n }\n // Property-sorted for deterministic iteration/serialization.\n const sorted = new Map<CssProperty, StyleDecl>(\n [...decls.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)),\n );\n const key = conditionKey(block.condition);\n blocks.set(key, { condition: block.condition, decls: sorted });\n }\n return { blocks };\n };\n\n const equals = (a: StyleMap, b: StyleMap): boolean => {\n const na = normalizeStyleMap(a);\n const nb = normalizeStyleMap(b);\n if (na.blocks.size !== nb.blocks.size) return false;\n for (const [key, blockA] of na.blocks) {\n const blockB = nb.blocks.get(key);\n if (!blockB) return false;\n if (blockA.decls.size !== blockB.decls.size) return false;\n for (const [prop, declA] of blockA.decls) {\n const declB = blockB.decls.get(prop);\n if (!declB) return false;\n if (declA.value !== declB.value || declA.important !== declB.important) return false;\n }\n }\n return true;\n };\n\n return {\n version: 'domflax-normalizer@1',\n normalizeDeclaration,\n normalizeValue,\n normalizeStyleMap,\n equals,\n inherited,\n };\n}\n\n/** The shared, process-wide normalizer instance reused by core / patterns / verify. */\nexport const normalizer: StyleNormalizer = createNormalizer();\n\n/* ───────────────────────── superset helper (used by `computed()` matcher) ───────────────────────── */\n\n/**\n * True when `full` contains every declaration of `partial` with an equal normalized value\n * (a per-condition, per-declaration superset test). Both maps are normalized first so the\n * comparison is meaning-based, not string-based. Empty `partial` ⇒ always `true`.\n */\nexport function isStyleSuperset(\n full: StyleMap,\n partial: StyleMap,\n norm: StyleNormalizer = normalizer,\n): boolean {\n const nf = norm.normalizeStyleMap(full);\n const np = norm.normalizeStyleMap(partial);\n for (const [key, want] of np.blocks) {\n const have = nf.blocks.get(key) ?? nf.blocks.get(conditionKey(want.condition));\n if (!have) return false;\n for (const [prop, decl] of want.decls) {\n const got = have.decls.get(prop);\n if (!got || got.value !== decl.value) return false;\n }\n }\n return true;\n}\n\n/** Re-exported for callers that want to (de)construct keys without importing core directly. */\nexport { emptyStyleMap };\n","/**\n * @domflax/pattern-kit — composable matcher vocabulary.\n *\n * A {@link Matcher} is a PURE predicate over a node + its {@link MatchContext}. Matchers never\n * mutate; they only read the (DeepReadonly) IR and the precomputed targeting/selector facts the\n * context exposes. Authors compose them with {@link and}/{@link or}/{@link not} and feed the\n * result into a pattern's `evaluate`.\n *\n * Style-aware matchers (`computed`, `hasOwnVisualStyle`) reason over the NORMALIZED StyleMap via\n * the shared normalizer in `./normalize`, so they query meaning, not raw CSS strings.\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n IRElement,\n IRNode,\n IRNodeId,\n MatchContext,\n NodeLike,\n StyleMap,\n} from '@domflax/core';\n\nimport { isStyleSuperset, normalizer } from './normalize';\n\n/** A pure predicate: does `node` satisfy this condition in the given match context? */\nexport type Matcher = (node: NodeLike, ctx: MatchContext) => boolean;\n\n/* ───────────────────────── internal 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\nfunction elementChildrenOf(\n el: DeepReadonly<IRElement>,\n ctx: MatchContext,\n): DeepReadonly<IRElement>[] {\n const out: DeepReadonly<IRElement>[] = [];\n for (const childId of el.children) {\n const child = ctx.doc.nodes.get(childId);\n if (child && child.kind === 'element') out.push(child as DeepReadonly<IRElement>);\n }\n return out;\n}\n\n/* ───────────────────────── boolean combinators ───────────────────────── */\n\n/** Logical AND. Empty list ⇒ always matches. Short-circuits on the first failure. */\nexport function and(...matchers: readonly Matcher[]): Matcher {\n return (node, ctx) => matchers.every((m) => m(node, ctx));\n}\n\n/** Logical OR. Empty list ⇒ never matches. Short-circuits on the first success. */\nexport function or(...matchers: readonly Matcher[]): Matcher {\n return (node, ctx) => matchers.some((m) => m(node, ctx));\n}\n\n/** Logical NOT. */\nexport function not(matcher: Matcher): Matcher {\n return (node, ctx) => !matcher(node, ctx);\n}\n\n/* ───────────────────────── structural matchers ───────────────────────── */\n\n/** Matches any element; with `tag`, only elements whose (case-insensitive) tag equals it. */\nexport function isElement(tag?: string): Matcher {\n const want = tag?.toLowerCase();\n return (node) => {\n const el = asElement(node);\n if (!el) return false;\n return want === undefined || el.tag.toLowerCase() === want;\n };\n}\n\n/** Matches an element with exactly one ELEMENT child (text/expr/comment children ignored). */\nexport const hasSingleElementChild: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n return elementChildrenOf(el, ctx).length === 1;\n};\n\n/* ───────────────────────── style matchers ───────────────────────── */\n\n/**\n * Matches when the node's computed StyleMap is a SUPERSET of `partial` — i.e. every declaration\n * in `partial` is present in `node.computed` with an equal normalized value. Comparison is\n * meaning-based (both sides normalized first). Empty `partial` always matches.\n */\nexport function computed(partial: StyleMap): Matcher {\n return (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n const full = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n return isStyleSuperset(full as StyleMap, partial, normalizer);\n };\n}\n\n/** Visual (paint-establishing) properties that count as \"own visual style\", beyond pure layout. */\nconst VISUAL_PROPERTIES: ReadonlySet<string> = new Set<string>([\n 'background',\n 'background-color',\n 'background-image',\n 'border-top-width',\n 'border-right-width',\n 'border-bottom-width',\n 'border-left-width',\n 'border-top-style',\n 'border-right-style',\n 'border-bottom-style',\n 'border-left-style',\n 'border-top-color',\n 'border-right-color',\n 'border-bottom-color',\n 'border-left-color',\n 'border-radius',\n 'box-shadow',\n 'outline',\n 'outline-width',\n 'outline-style',\n 'outline-color',\n 'text-shadow',\n 'filter',\n 'backdrop-filter',\n 'mix-blend-mode',\n 'opacity',\n]);\n\n/** Values that mean \"no paint\" — a visual property set to one of these does NOT count. */\nconst EMPTY_VISUAL_VALUES: ReadonlySet<string> = new Set<string>([\n 'none',\n '0',\n 'normal',\n 'transparent',\n 'rgba(0, 0, 0, 0)',\n 'initial',\n 'unset',\n 'auto',\n]);\n\n/**\n * Matches when the element paints something of its own: a meaningful background, border, shadow,\n * outline, filter, etc. across ANY style condition. Honours the frontend-set `meta.hasOwnVisualStyle`\n * fast-path, then falls back to scanning the normalized computed StyleMap.\n */\nexport const hasOwnVisualStyle: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n if (el.meta.hasOwnVisualStyle) return true;\n\n const computedMap = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n const norm = normalizer.normalizeStyleMap(computedMap as StyleMap);\n for (const block of norm.blocks.values()) {\n for (const decl of block.decls.values()) {\n if (!VISUAL_PROPERTIES.has(String(decl.property))) continue;\n if (!EMPTY_VISUAL_VALUES.has(String(decl.value))) return true;\n }\n }\n return false;\n};\n\n/* ───────────────────────── opacity-barrier / meta matchers ───────────────────────── */\n\n/** Element carries a `ref` (hard opacity barrier). */\nexport const hasRef: Matcher = (node) => asElement(node)?.meta.hasRef ?? false;\n\n/** Element has event handlers (onClick, …). */\nexport const hasEventHandlers: Matcher = (node) => asElement(node)?.meta.hasEventHandlers ?? false;\n\n/** Element has dynamic children (mapped/conditional islands). */\nexport const hasDynamicChildren: Matcher = (node) =>\n asElement(node)?.meta.hasDynamicChildren ?? false;\n\n/** Element's class list contains a dynamic segment (template/expr) → not freely rewritable. */\nexport const hasDynamicClasses: Matcher = (node) => asElement(node)?.classes.hasDynamic ?? false;\n\n/**\n * Element's class list is wholly dynamic / spread-derived (`classes.opaque`, or spread attrs) — its\n * concrete tokens can't be seen or statically rewritten, so a class-rewriting (compress) pattern\n * must decline. Delegates to the context's authoritative {@link MatchContext.isOpaque}.\n */\nexport const opaque: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n return ctx.isOpaque(el as unknown as ElementLike);\n};\n\n/**\n * Element is the subject of a combinator selector (`>`/`+`/`~`). Honours the frontend-set meta\n * flag and the precomputed {@link SelectorIndex} in the context.\n */\nexport const targetedByCombinator: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n if (el.meta.targetedByCombinator) return true;\n // `el.id` is a branded number; DeepReadonly widens the brand, so re-narrow for the index call.\n return ctx.selectors.targetedByCombinator(el.id as unknown as IRNodeId);\n};\n","/**\n * @domflax/pattern-kit — ergonomic op-draft constructors.\n *\n * Thin, pure helpers that build the core {@link RewriteOpDraft} objects so pattern authors can\n * assemble a `MatchResult.ops` array without hand-writing discriminant literals. Drafts carry NO\n * `origin` — the pass-manager stamps `{ pattern, category, safety }` when it schedules the op\n * (see core's `stampOrigin`). Each helper accepts a live node, a DeepReadonly view, or a bare\n * {@link IRNodeId}.\n *\n * Mirrors the four ops a rewrite typically reaches for: `mergeStyle`, `foldInheritedStyles`,\n * `replaceWith`, `removeNode`.\n */\n\nimport type {\n CssProperty,\n ElementLike,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeSpec,\n RewriteOpDraft,\n StyleConflictPolicy,\n StyleMap,\n} from '@domflax/core';\n\n/** Accept a live/readonly node or a bare id. */\ntype Ref = NodeLike | ElementLike | IRNodeId;\n\nfunction idOf(ref: Ref): IRNodeId {\n return typeof ref === 'number' ? (ref as IRNodeId) : ((ref as IRNode).id as IRNodeId);\n}\n\n/* ───────────────────────── style ops ───────────────────────── */\n\n/**\n * Merge `style` onto `target`, optionally pulling from `source` (or `null` for a literal patch).\n * `onConflict` defaults to `'abort'` — the safest policy (the applier refuses rather than guess).\n */\nexport function mergeStyle(\n target: Ref,\n source: Ref | null,\n style: StyleMap,\n onConflict: StyleConflictPolicy = 'abort',\n): RewriteOpDraft {\n return {\n op: 'mergeStyle',\n target: idOf(target),\n source: source == null ? null : idOf(source),\n style,\n onConflict,\n };\n}\n\n/**\n * Fold inheritable declarations from `from` down into one or more descendants. `conditions:'all'`\n * folds across every StyleCondition (states/media/pseudo-elements); the default `'base'` folds only\n * the unconditional block. `only` restricts the property set (otherwise `'all-inherited'`).\n */\nexport function foldInheritedStyles(\n from: Ref,\n into: Ref | readonly Ref[],\n opts?: { only?: readonly CssProperty[]; conditions?: 'base' | 'all' },\n): RewriteOpDraft {\n const list: readonly Ref[] = Array.isArray(into) ? (into as readonly Ref[]) : [into as Ref];\n return {\n op: 'foldInheritedStyles',\n from: idOf(from),\n into: list.map(idOf),\n properties: opts?.only ?? 'all-inherited',\n conditions: opts?.conditions ?? 'base',\n };\n}\n\n/* ───────────────────────── structural ops ───────────────────────── */\n\n/** Replace `target` with a detached {@link NodeSpec} (the applier materializes ids on apply). */\nexport function replaceWith(target: Ref, replacement: NodeSpec): RewriteOpDraft {\n return { op: 'replaceWith', target: idOf(target), replacement };\n}\n\n/** Remove `target` (and its subtree) from the tree. */\nexport function removeNode(target: Ref): RewriteOpDraft {\n return { op: 'removeNode', target: idOf(target) };\n}\n","/**\n * @domflax/pattern-kit — `definePattern()`: THE declarative pattern-authoring surface.\n *\n * `definePattern(config)` is the single public way to author a rewrite pattern: definition AND its\n * tests are co-located in one call. It compiles down to the private lower-level\n * {@link import('./define').validatePattern}/{@link Pattern} contract (it never replaces the\n * engine). Authors describe the match as a plain DATA object and the rewrite as a named RECIPE; this\n * module maps each key to the existing matcher combinators and op-draft factories, auto-applies the\n * phase-appropriate safety guards (the full opacity-barrier + selector set for `flatten/*`; the\n * narrower class-rewrite-safety set for `compress/*`) so authors never hand-write them, and threads\n * `doc`/`test` through. Two escape hatches — a `match` predicate and a `rewrite` function — keep\n * exotic patterns (e.g. ones anchored on a parent fragment) expressible.\n *\n * The co-located {@link PatternTest} (`provider`/`cssFiles`/`cases`/`noMatch`/`custom`) is carried on\n * the compiled {@link AuthoredPattern} as `.test`, where the generic harness (`./testing`) reads it:\n * each `case` asserts `before → after`, each `noMatch` asserts the input is left unchanged, and the\n * optional `custom` hook runs arbitrary assertions against the built transform.\n *\n * `style` blocks in the declarative match (and in `childGains`/`mergeStyle` recipes) are PLAIN\n * objects (camelCase or kebab keys) auto-normalized into a superset StyleMap via the shared\n * normalizer — authors never import the normalizer or hand-build a StyleMap.\n *\n * `pattern` remains exported as a DEPRECATED alias of `definePattern` for backward compatibility.\n */\n\nimport type {\n Captures,\n ConditionKey,\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n MatchContext,\n MatchResult,\n NodeLike,\n NodeMeta,\n PassCategory,\n PassPhase,\n Pattern,\n PatternDoc,\n PreconditionSketch,\n RewriteFactory,\n RewriteOpDraft,\n SafetyLevel,\n StyleBlock,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n StyleConflictPolicy,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n and,\n computed,\n hasDynamicChildren,\n hasDynamicClasses,\n hasEventHandlers,\n hasOwnVisualStyle,\n hasRef,\n hasSingleElementChild,\n isElement,\n not,\n opaque,\n targetedByCombinator,\n type Matcher,\n} from './combinators';\nimport { validatePattern } from './define';\nimport { normalizer } from './normalize';\n\n/* ───────────────────────── public config shapes ───────────────────────── */\n\n/** A plain CSS style object: camelCase or kebab-case keys, string or number values. */\nexport type PlainStyle = Readonly<Record<string, string | number>>;\n\n/**\n * Declarative match as DATA. Every key maps to one of the existing matcher combinators; an empty\n * object matches any element. Use the `match` FUNCTION escape hatch for anything not expressible\n * here (relational/ancestor/sibling shapes, parent-anchored patterns, …).\n */\nexport interface DeclarativeMatch {\n /** Restrict to a tag (case-insensitive). Omit to match any element. */\n readonly tag?: string;\n /** Computed style the node must be a SUPERSET of (plain object, auto-normalized). */\n readonly style?: PlainStyle;\n /** Require exactly one ELEMENT child. */\n readonly onlyChild?: 'element';\n /** Require the element to paint nothing of its own (no own visual style). */\n readonly paintsNothing?: boolean;\n /** Extra, hand-written predicate AND-ed into the declarative match. */\n readonly where?: Matcher | readonly Matcher[];\n}\n\n/** Escape hatch: a raw match predicate (no auto-guards are added). */\nexport type MatchFn = (node: NodeLike, ctx: MatchContext) => boolean;\n\n/**\n * Flatten recipe: fold inherited styles onto the sole element child (default on), optionally merge\n * `childGains` onto it, then unwrap the node (id-preserving). Mirrors the flatten exemplars.\n */\nexport interface FlattenIntoRecipe {\n readonly flattenInto: 'child';\n /** Plain style merged onto the surviving child (source-wins) before unwrap. */\n readonly childGains?: PlainStyle;\n /** Fold inheritable declarations onto the child first. Default `true`. */\n readonly foldInherited?: boolean;\n}\n\n/** Compress recipe: rebuild the element's class StyleMap; return `null` to decline. */\nexport interface RewriteClassesRecipe {\n readonly rewriteClasses: (computed: StyleMap, ctx: MatchContext) => StyleMap | null;\n /** Keep opaque/selector-bound tokens verbatim. Default `true`. */\n readonly preserveOpaque?: boolean;\n}\n\n/** Compress recipe: drop fully-overridden class tokens (provenance is pruned automatically). */\nexport interface DropClassesRecipe {\n readonly dropClasses: (computed: StyleMap, ctx: MatchContext) => Iterable<string>;\n /** Keep opaque/selector-bound tokens verbatim. Default `true`. */\n readonly preserveOpaque?: boolean;\n}\n\n/** Merge a literal plain style onto the matched element. */\nexport interface MergeStyleRecipe {\n readonly mergeStyle: PlainStyle;\n readonly onConflict?: StyleConflictPolicy;\n}\n\nexport type RewriteRecipe =\n | FlattenIntoRecipe\n | RewriteClassesRecipe\n | DropClassesRecipe\n | MergeStyleRecipe;\n\n/** Escape hatch: a raw rewrite that returns op drafts (or `null`/`[]` for no-op). */\nexport type RewriteFn = (\n ctx: MatchContext,\n rw: RewriteFactory,\n) => readonly RewriteOpDraft[] | null;\n\n/** A single positive before→after assertion run through the pattern's built transform. */\nexport interface PatternTestCase {\n readonly name?: string;\n readonly before: string;\n readonly after: string;\n}\n\n/** Helpers handed to a {@link PatternTest.custom} hook (the built transform + expectation sugar). */\nexport interface TestHelpers {\n /** Run the pattern's transform on `code` (default filename `'X.tsx'`). */\n readonly transform: (code: string, filename?: string) => string;\n /** Assert `before` transforms to `after` (whitespace-normalized). */\n readonly expectTransforms: (before: string, after: string) => void;\n /** Assert `code` is left unchanged (whitespace-normalized). */\n readonly expectUnchanged: (code: string) => void;\n}\n\n/**\n * Co-located test spec for a pattern. The generic harness (`./testing`) builds a transform for the\n * declared `provider` (default `'tailwind'`; `'custom'` resolves the listed `cssFiles`), then runs\n * every `case` (`before → after`), every `noMatch` (left unchanged), and the optional `custom` hook.\n */\nexport interface PatternTest {\n /** Which style provider the harness builds the transform from. Default `'tailwind'`. */\n readonly provider?: 'tailwind' | 'custom';\n /** For `provider: 'custom'` — the project stylesheet paths backing the CSS resolver. */\n readonly cssFiles?: readonly string[];\n /** Positive before→after assertions. */\n readonly cases?: readonly PatternTestCase[];\n /** Inputs the pattern must leave UNCHANGED (barriers, non-matching shapes, safety reverts). */\n readonly noMatch?: readonly string[];\n /** Arbitrary extra assertions against the built transform. */\n readonly custom?: (h: TestHelpers) => void;\n}\n\nexport interface PatternConfig {\n readonly name: string;\n readonly category: PassCategory;\n readonly safety: SafetyLevel;\n readonly priority?: number;\n readonly precondition?: PreconditionSketch;\n readonly doc?: PatternDoc;\n /** Co-located tests consumed by the generic harness (`./testing`). */\n readonly test?: PatternTest;\n /** Declarative match DATA, or a raw predicate escape hatch. Defaults to \"any element\". */\n readonly match?: DeclarativeMatch | MatchFn;\n /** A named rewrite recipe, or a raw op-draft factory escape hatch. */\n readonly rewrite: RewriteRecipe | RewriteFn;\n}\n\n/** A {@link Pattern} that also carries its co-located {@link PatternTest} for the test harness. */\nexport interface AuthoredPattern<C extends Captures = Captures> extends Pattern {\n readonly test?: PatternTest;\n evaluate(ctx: MatchContext, rw: RewriteFactory): MatchResult<C> | null;\n}\n\n/* ───────────────────────── plain-style → StyleMap ───────────────────────── */\n\nfunction camelToKebab(key: string): string {\n if (key.startsWith('--')) return key; // custom property — leave verbatim\n return key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n}\n\n/** Build a single-(base-)condition StyleMap from a plain style object via the shared normalizer. */\nfunction plainToStyleMap(style: PlainStyle): StyleMap {\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [rawKey, rawValue] of Object.entries(style)) {\n const prop = camelToKebab(rawKey);\n for (const decl of normalizer.normalizeDeclaration(prop, String(rawValue), false)) {\n decls.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls };\n return { blocks: new Map<ConditionKey, StyleBlock>([[conditionKey(BASE_CONDITION), block]]) };\n}\n\n/* ───────────────────────── local meta / selector matchers ───────────────────────── */\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\nfunction metaFlag(flag: keyof NodeMeta): Matcher {\n return (node) => Boolean(asElement(node)?.meta[flag]);\n}\n\n/** Element renders raw/`dangerouslySetInnerHTML` markup — a hard opacity barrier. */\nconst hasRawHtml: Matcher = metaFlag('hasDangerousHtml');\n\n/**\n * Unwrapping/removing this node would change the combinator / structural-pseudo match-set of itself,\n * its child, or a former sibling. Empty `reparentImpact` ⇒ structurally safe to hoist.\n */\nconst affectsSelectorMatching: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n return ctx.selectors.reparentImpact(el.id as unknown as IRNodeId).size > 0;\n};\n\n/**\n * The opacity-barrier + selector-safety guards every `flatten/*` pattern must carry. Auto-applied to\n * the declarative match so authors never hand-write them (the flatten exemplars spell them out).\n *\n * Flatten UNWRAPS the element (moving its children into a new parent and dropping its box), so every\n * opacity barrier matters: a ref, event handler, dynamic child, or raw HTML on the wrapper — or any\n * selector the reparent would disturb — makes the flatten unsafe.\n */\nconst FLATTEN_GUARDS: Matcher = and(\n not(hasRef),\n not(hasEventHandlers),\n not(hasDynamicChildren),\n not(hasRawHtml),\n not(targetedByCombinator),\n not(affectsSelectorMatching),\n);\n\n/**\n * The guards every `compress/*` pattern must carry. Compress ONLY ever rewrites the element's OWN\n * class tokens (e.g. `px-4 py-4 → p-4`) — it never touches the element's structure, children, or\n * identity. A dynamic `{expr}` child, a ref, an event handler, or `dangerouslySetInnerHTML` is\n * therefore wholly unaffected by a class-only change, so — unlike flatten — those opacity barriers\n * must NOT gate compress. Compress is gated ONLY on what actually makes a class rewrite unsafe:\n * • a className we can't statically rewrite — a dynamic segment ({@link hasDynamicClasses}) or a\n * wholly dynamic / spread-derived list ({@link opaque}); and\n * • the selector-safety guard — a class a CSS combinator selector structurally depends on\n * ({@link targetedByCombinator}) must not be dropped or rewritten.\n */\nconst COMPRESS_GUARDS: Matcher = and(\n not(hasDynamicClasses),\n not(opaque),\n not(targetedByCombinator),\n);\n\n/* ───────────────────────── match compilation ───────────────────────── */\n\n/** The auto-applied guard set for a pattern's phase (compress vs flatten get different barriers). */\nfunction autoGuardsFor(category: PassCategory): Matcher | null {\n switch (category.split('/', 1)[0] as PassPhase) {\n case 'flatten':\n return FLATTEN_GUARDS;\n case 'compress':\n return COMPRESS_GUARDS;\n default:\n return null;\n }\n}\n\nfunction compileDeclarativeMatch(m: DeclarativeMatch): Matcher {\n const parts: Matcher[] = [isElement(m.tag)];\n if (m.style) parts.push(computed(plainToStyleMap(m.style)));\n if (m.onlyChild === 'element') parts.push(hasSingleElementChild);\n if (m.paintsNothing) parts.push(not(hasOwnVisualStyle));\n if (m.where) {\n const extra = Array.isArray(m.where) ? (m.where as readonly Matcher[]) : [m.where as Matcher];\n for (const w of extra) parts.push(w);\n }\n return and(...parts);\n}\n\nfunction compileMatch(\n match: DeclarativeMatch | MatchFn | undefined,\n category: PassCategory,\n): MatchFn {\n // Escape hatch: a raw predicate takes full control (no auto-guards).\n if (typeof match === 'function') return match;\n\n const declarative = compileDeclarativeMatch(match ?? {});\n const guards = autoGuardsFor(category);\n const guarded = guards ? and(declarative, guards) : declarative;\n return (node, ctx) => guarded(node, ctx);\n}\n\n/* ───────────────────────── rewrite compilation ───────────────────────── */\n\n/** Clone `sm`, pruning every `shadowed` provenance entry that references a dropped class token. */\nfunction pruneShadowed(sm: StyleMap, drop: ReadonlySet<string>): 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 const filtered = (decl.shadowed ?? []).filter(\n (o) => !(o.kind === 'class' && drop.has(o.className)),\n );\n const rest: StyleDecl = { ...decl };\n delete (rest as { shadowed?: readonly StyleOrigin[] }).shadowed;\n const next: StyleDecl = filtered.length > 0 ? { ...rest, shadowed: filtered } : rest;\n decls.set(prop, next);\n }\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\nfunction compileFlattenInto(recipe: FlattenIntoRecipe): RewriteFn {\n const childGains = recipe.childGains ? plainToStyleMap(recipe.childGains) : null;\n const fold = recipe.foldInherited !== false;\n return (ctx, rw) => {\n const wrapper = ctx.node;\n const child = ctx.onlyElementChild();\n if (!child) return null;\n const ops: RewriteOpDraft[] = [];\n if (fold) ops.push(rw.foldInheritedStyles(wrapper, child, { conditions: 'all' }));\n if (childGains) ops.push(rw.mergeStyle(child, null, childGains, 'source-wins'));\n ops.push(rw.unwrap(wrapper));\n return ops;\n };\n}\n\nfunction compileRewrite(rewrite: RewriteRecipe | RewriteFn): RewriteFn {\n if (typeof rewrite === 'function') return rewrite;\n\n if ('flattenInto' in rewrite) return compileFlattenInto(rewrite);\n\n if ('rewriteClasses' in rewrite) {\n const preserveOpaque = rewrite.preserveOpaque ?? true;\n return (ctx, rw) => {\n const next = rewrite.rewriteClasses(ctx.computed(), ctx);\n if (!next) return null;\n return [rw.setClassList(ctx.node, next, preserveOpaque)];\n };\n }\n\n if ('dropClasses' in rewrite) {\n const preserveOpaque = rewrite.preserveOpaque ?? true;\n return (ctx, rw) => {\n const drop = new Set<string>(rewrite.dropClasses(ctx.computed(), ctx));\n if (drop.size === 0) return null;\n return [rw.setClassList(ctx.node, pruneShadowed(ctx.computed(), drop), preserveOpaque)];\n };\n }\n\n // MergeStyleRecipe\n const style = plainToStyleMap(rewrite.mergeStyle);\n const onConflict = rewrite.onConflict ?? 'abort';\n return (ctx, rw) => [rw.mergeStyle(ctx.node, null, style, onConflict)];\n}\n\n/* ───────────────────────── the public factory ───────────────────────── */\n\n/**\n * THE declarative pattern-authoring function. Compile a {@link PatternConfig} (definition + co-located\n * {@link PatternTest}) into a validated {@link AuthoredPattern}: a normal {@link Pattern} (registerable\n * into any {@link import('@domflax/core').Pass}) that also exposes its `test` for the generic harness.\n */\nexport function definePattern(config: PatternConfig): AuthoredPattern {\n const matchFn = compileMatch(config.match, config.category);\n const rewriteFn = compileRewrite(config.rewrite);\n\n const spec: AuthoredPattern = {\n name: config.name,\n category: config.category,\n safety: config.safety,\n priority: config.priority,\n precondition: config.precondition,\n doc: config.doc,\n test: config.test,\n evaluate(ctx: MatchContext, rw: RewriteFactory): MatchResult | null {\n if (!matchFn(ctx.node as unknown as NodeLike, ctx)) return null;\n const ops = rewriteFn(ctx, rw);\n if (!ops || ops.length === 0) return null;\n return { ops };\n },\n };\n\n // `validatePattern` validates + freezes; the spread preserves `test` at runtime.\n return validatePattern(spec) as AuthoredPattern;\n}\n\n/**\n * @deprecated Use {@link definePattern}. Retained as a thin alias for backward compatibility.\n */\nexport const pattern = definePattern;\n","/**\n * @domflax/pattern-kit — `validatePattern` (INTERNAL).\n *\n * A small, eager validator + identity wrapper that turns a lowered {@link Pattern} spec into a\n * frozen, contract-checked Pattern. Catching shape errors here (bad category/phase, missing\n * `evaluate`, out-of-range safety) keeps the pass-manager's hot loop free of defensive checks and\n * gives authors an immediate, actionable error at module-load time.\n *\n * This is the PRIVATE lower-level core: it is consumed only by the declarative\n * {@link import('./pattern').definePattern} authoring surface (which compiles a high-level config\n * down to a {@link Pattern} and then runs it through this validator). It is intentionally NOT part\n * of the public package surface — authors use `definePattern` instead.\n */\n\nimport type { PassPhase, Pattern, SafetyLevel } from '@domflax/core';\n\nconst PHASES: ReadonlySet<PassPhase> = new Set<PassPhase>(['flatten', 'compress', 'extract']);\nconst SAFETY_LEVELS: ReadonlySet<SafetyLevel> = new Set<SafetyLevel>([0, 1, 2, 3]);\n\nfunction fail(name: string, why: string): never {\n throw new Error(`definePattern(${name || '<anonymous>'}): ${why}`);\n}\n\n/**\n * Validate and freeze a {@link Pattern}. Throws on any contract violation; otherwise returns the\n * (shallow-frozen) spec unchanged so it can be registered into a {@link Pass}. INTERNAL — see the\n * module header; authors call the declarative {@link import('./pattern').definePattern}.\n */\nexport function validatePattern(spec: Pattern): Pattern {\n if (spec == null || typeof spec !== 'object') {\n throw new Error('definePattern: spec must be an object');\n }\n\n const name = spec.name;\n if (typeof name !== 'string' || name.length === 0) {\n fail(String(name), 'name must be a non-empty string');\n }\n\n if (typeof spec.category !== 'string' || !spec.category.includes('/')) {\n fail(name, `category must be a \"<phase>/<slug>\" string (got ${JSON.stringify(spec.category)})`);\n }\n\n const phase = spec.category.split('/', 1)[0] as PassPhase;\n if (!PHASES.has(phase)) {\n fail(name, `category phase must be one of flatten|compress|extract (got \"${phase}\")`);\n }\n\n if (!SAFETY_LEVELS.has(spec.safety)) {\n fail(name, `safety must be 0|1|2|3 (got ${JSON.stringify(spec.safety)})`);\n }\n\n if (typeof spec.evaluate !== 'function') {\n fail(name, 'evaluate must be a function');\n }\n\n if (spec.priority !== undefined && !Number.isFinite(spec.priority)) {\n fail(name, 'priority must be a finite number when provided');\n }\n\n return Object.freeze({ ...spec });\n}\n","/**\n * @domflax/pattern-kit — the authoring surface for rewrite patterns.\n *\n * Re-exports the pillars pattern authors compose with:\n * • {@link definePattern} — THE declarative pattern factory (definition + co-located tests). The\n * lower-level validator it compiles down to is intentionally kept private (see `./define`).\n * • the matcher vocabulary (`and`/`or`/`not`/`isElement`/`computed`/… ) from `./combinators`.\n * • the op-draft constructors (`mergeStyle`/`foldInheritedStyles`/`replaceWith`/`removeNode`).\n * • the shared {@link normalizer} (also consumed by core + verify) from `./normalize`.\n *\n * The generic test harness lives in the separate `./testing` entry (it imports vitest) so the main\n * authoring surface stays runtime-light and frontend-agnostic.\n */\n\nexport * from './combinators';\nexport * from './ops';\nexport * from './normalize';\nexport * from './pattern';\n"],"mappings":";;;;;AAAA;AA4CO,SAAS,kBAAkB,QAAQ,GAAgB;AACxD,MAAI,IAAI;AACR,SAAO;AAAA,IACL,OAAiB;AACf,YAAM,KAAK;AACX,WAAK;AACL,aAAO;AAAA,IACT;AAAA,IACA,IAAI,OAAiB;AACnB,aAAO;AAAA,IACT;AAAA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