@jesscss/core 2.0.0-alpha.5 → 2.0.0-alpha.6

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 (637) hide show
  1. package/lib/index.cjs +20159 -0
  2. package/lib/index.d.cts +5993 -0
  3. package/lib/index.d.cts.map +1 -0
  4. package/lib/index.d.ts +5992 -21
  5. package/lib/index.d.ts.map +1 -1
  6. package/lib/index.js +19926 -22
  7. package/lib/index.js.map +1 -1
  8. package/package.json +15 -14
  9. package/src/__tests__/define-function-record.test.ts +58 -0
  10. package/src/__tests__/define-function-simple.test.ts +55 -0
  11. package/src/__tests__/define-function-split-sequence.test.ts +547 -0
  12. package/src/__tests__/define-function-type-parity.test.ts +9 -0
  13. package/src/__tests__/define-function.test.ts +763 -0
  14. package/src/__tests__/num-operations.test.ts +91 -0
  15. package/src/__tests__/safe-parse.test.ts +374 -0
  16. package/src/context.ts +896 -0
  17. package/src/conversions.ts +282 -0
  18. package/src/debug-log.ts +29 -0
  19. package/src/define-function.ts +1006 -0
  20. package/src/deprecation.ts +67 -0
  21. package/src/globals.d.ts +26 -0
  22. package/src/index.ts +31 -0
  23. package/src/jess-error.ts +773 -0
  24. package/src/logger/deprecation-processing.ts +109 -0
  25. package/src/logger.ts +31 -0
  26. package/src/plugin.ts +292 -0
  27. package/src/tree/LOOKUP_CHAINS.md +35 -0
  28. package/src/tree/README.md +18 -0
  29. package/src/tree/__tests__/__snapshots__/extend-eval-integration.test.ts.snap +1455 -0
  30. package/src/tree/__tests__/ampersand.test.ts +382 -0
  31. package/src/tree/__tests__/at-rule.test.ts +2047 -0
  32. package/src/tree/__tests__/basic-render.test.ts +212 -0
  33. package/src/tree/__tests__/block.test.ts +40 -0
  34. package/src/tree/__tests__/call.test.ts +346 -0
  35. package/src/tree/__tests__/color.test.ts +537 -0
  36. package/src/tree/__tests__/condition.test.ts +186 -0
  37. package/src/tree/__tests__/control.test.ts +564 -0
  38. package/src/tree/__tests__/declaration.test.ts +253 -0
  39. package/src/tree/__tests__/dependency-graph.test.ts +177 -0
  40. package/src/tree/__tests__/detached-rulesets.test.ts +213 -0
  41. package/src/tree/__tests__/dimension.test.ts +236 -0
  42. package/src/tree/__tests__/expression.test.ts +73 -0
  43. package/src/tree/__tests__/ext-node.test.ts +31 -0
  44. package/src/tree/__tests__/extend-eval-integration.test.ts +1033 -0
  45. package/src/tree/__tests__/extend-import-style.test.ts +929 -0
  46. package/src/tree/__tests__/extend-less-fixtures.test.ts +851 -0
  47. package/src/tree/__tests__/extend-list.test.ts +31 -0
  48. package/src/tree/__tests__/extend-roots.test.ts +1045 -0
  49. package/src/tree/__tests__/extend-rules.test.ts +740 -0
  50. package/src/tree/__tests__/func.test.ts +171 -0
  51. package/src/tree/__tests__/import-js.test.ts +33 -0
  52. package/src/tree/__tests__/import-style-test-helpers.ts +56 -0
  53. package/src/tree/__tests__/import-style.test.ts +1967 -0
  54. package/src/tree/__tests__/interpolated-reference.test.ts +44 -0
  55. package/src/tree/__tests__/interpolated.test.ts +41 -0
  56. package/src/tree/__tests__/list.test.ts +177 -0
  57. package/src/tree/__tests__/log.test.ts +83 -0
  58. package/src/tree/__tests__/mixin-recursion.test.ts +639 -0
  59. package/src/tree/__tests__/mixin.test.ts +2171 -0
  60. package/src/tree/__tests__/negative.test.ts +45 -0
  61. package/src/tree/__tests__/nesting-collapse.test.ts +519 -0
  62. package/src/tree/__tests__/node-flags-perf.test.ts +195 -0
  63. package/src/tree/__tests__/node-flags.test.ts +410 -0
  64. package/src/tree/__tests__/node-graph.test.ts +598 -0
  65. package/src/tree/__tests__/node-mutation.test.ts +182 -0
  66. package/src/tree/__tests__/operation.test.ts +18 -0
  67. package/src/tree/__tests__/paren.test.ts +90 -0
  68. package/src/tree/__tests__/preserve-mode-output.test.ts +50 -0
  69. package/src/tree/__tests__/quoted.test.ts +72 -0
  70. package/src/tree/__tests__/range.test.ts +59 -0
  71. package/src/tree/__tests__/reference.test.ts +743 -0
  72. package/src/tree/__tests__/rest.test.ts +29 -0
  73. package/src/tree/__tests__/rules-raw.test.ts +14 -0
  74. package/src/tree/__tests__/rules.test.ts +1271 -0
  75. package/src/tree/__tests__/ruleset.test.ts +597 -0
  76. package/src/tree/__tests__/selector-attr.test.ts +50 -0
  77. package/src/tree/__tests__/selector-basic.test.ts +44 -0
  78. package/src/tree/__tests__/selector-capture.test.ts +22 -0
  79. package/src/tree/__tests__/selector-complex.test.ts +120 -0
  80. package/src/tree/__tests__/selector-compound.test.ts +74 -0
  81. package/src/tree/__tests__/selector-interpolated.test.ts +50 -0
  82. package/src/tree/__tests__/selector-list.test.ts +59 -0
  83. package/src/tree/__tests__/selector-pseudo.test.ts +23 -0
  84. package/src/tree/__tests__/selector.test.ts +182 -0
  85. package/src/tree/__tests__/sequence.test.ts +226 -0
  86. package/src/tree/__tests__/serialize-types.test.ts +529 -0
  87. package/src/tree/__tests__/spaced.test.ts +8 -0
  88. package/src/tree/__tests__/url.test.ts +72 -0
  89. package/src/tree/__tests__/var-declaration.test.ts +90 -0
  90. package/src/tree/ampersand.ts +538 -0
  91. package/src/tree/any.ts +169 -0
  92. package/src/tree/at-rule.ts +760 -0
  93. package/src/tree/block.ts +72 -0
  94. package/src/tree/bool.ts +46 -0
  95. package/src/tree/call.ts +593 -0
  96. package/src/tree/collection.ts +52 -0
  97. package/src/tree/color.ts +629 -0
  98. package/src/tree/combinator.ts +30 -0
  99. package/src/tree/comment.ts +36 -0
  100. package/src/tree/condition.ts +194 -0
  101. package/src/tree/control.ts +452 -0
  102. package/src/tree/declaration-custom.ts +56 -0
  103. package/src/tree/declaration-var.ts +87 -0
  104. package/src/tree/declaration.ts +742 -0
  105. package/src/tree/default-guard.ts +35 -0
  106. package/src/tree/dimension.ts +392 -0
  107. package/src/tree/expression.ts +97 -0
  108. package/src/tree/extend-list.ts +51 -0
  109. package/src/tree/extend.ts +391 -0
  110. package/src/tree/function.ts +254 -0
  111. package/src/tree/import-js.ts +130 -0
  112. package/src/tree/import-style.ts +875 -0
  113. package/{lib/tree/index.js → src/tree/index.ts} +49 -22
  114. package/src/tree/interpolated.ts +346 -0
  115. package/src/tree/js-array.ts +21 -0
  116. package/src/tree/js-expr.ts +50 -0
  117. package/src/tree/js-function.ts +31 -0
  118. package/src/tree/js-object.ts +22 -0
  119. package/src/tree/list.ts +415 -0
  120. package/src/tree/log.ts +89 -0
  121. package/src/tree/mixin.ts +331 -0
  122. package/src/tree/negative.ts +58 -0
  123. package/src/tree/nil.ts +57 -0
  124. package/src/tree/node-base.ts +1716 -0
  125. package/src/tree/node-type.ts +122 -0
  126. package/src/tree/node.ts +118 -0
  127. package/src/tree/number.ts +54 -0
  128. package/src/tree/operation.ts +187 -0
  129. package/src/tree/paren.ts +132 -0
  130. package/src/tree/query-condition.ts +47 -0
  131. package/src/tree/quoted.ts +119 -0
  132. package/src/tree/range.ts +101 -0
  133. package/src/tree/reference.ts +1099 -0
  134. package/src/tree/rest.ts +55 -0
  135. package/src/tree/rules-raw.ts +52 -0
  136. package/src/tree/rules.ts +2896 -0
  137. package/src/tree/ruleset.ts +1217 -0
  138. package/src/tree/selector-attr.ts +172 -0
  139. package/src/tree/selector-basic.ts +75 -0
  140. package/src/tree/selector-capture.ts +85 -0
  141. package/src/tree/selector-complex.ts +189 -0
  142. package/src/tree/selector-compound.ts +205 -0
  143. package/src/tree/selector-interpolated.ts +95 -0
  144. package/src/tree/selector-list.ts +245 -0
  145. package/src/tree/selector-pseudo.ts +173 -0
  146. package/src/tree/selector-simple.ts +10 -0
  147. package/src/tree/selector.ts +152 -0
  148. package/src/tree/sequence.ts +463 -0
  149. package/src/tree/tree.ts +130 -0
  150. package/src/tree/url.ts +95 -0
  151. package/src/tree/util/EXTEND_ARCHITECTURE_ANALYSIS.md +215 -0
  152. package/src/tree/util/EXTEND_AUDIT.md +233 -0
  153. package/src/tree/util/EXTEND_BASELINE.md +64 -0
  154. package/src/tree/util/EXTEND_CALL_GRAPH_ANALYSIS.md +244 -0
  155. package/src/tree/util/EXTEND_DOCS.md +24 -0
  156. package/src/tree/util/EXTEND_FINAL_SUMMARY.md +95 -0
  157. package/src/tree/util/EXTEND_FUNCTION_AUDIT.md +1433 -0
  158. package/src/tree/util/EXTEND_OPTIMIZATION_PLAN.md +114 -0
  159. package/src/tree/util/EXTEND_REFACTORING_SUMMARY.md +152 -0
  160. package/src/tree/util/EXTEND_RULES.md +74 -0
  161. package/src/tree/util/EXTEND_UNUSED_FUNCTIONS.md +127 -0
  162. package/src/tree/util/EXTEND_UNUSED_FUNCTIONS_ANALYSIS.md +227 -0
  163. package/src/tree/util/NODE_COPY_REDUCTION_PLAN.md +12 -0
  164. package/src/tree/util/__tests__/EXTEND_TEST_INDEX.md +59 -0
  165. package/src/tree/util/__tests__/OPTIMIZATION-ANALYSIS.md +130 -0
  166. package/src/tree/util/__tests__/WALK_AND_CONSUME_DESIGN.md +138 -0
  167. package/src/tree/util/__tests__/_archive/2026-02-09__OPTIMIZATION-ANALYSIS.md +9 -0
  168. package/src/tree/util/__tests__/_archive/README.md +4 -0
  169. package/src/tree/util/__tests__/bitset.test.ts +142 -0
  170. package/src/tree/util/__tests__/debug-log.ts +50 -0
  171. package/src/tree/util/__tests__/extend-comment-handling.test.ts +187 -0
  172. package/src/tree/util/__tests__/extend-core-unit.test.ts +941 -0
  173. package/src/tree/util/__tests__/extend-pipeline-bench.test.ts +154 -0
  174. package/src/tree/util/__tests__/extend-pipeline-bench.ts +190 -0
  175. package/src/tree/util/__tests__/fast-reject.test.ts +377 -0
  176. package/src/tree/util/__tests__/is-node.test.ts +63 -0
  177. package/src/tree/util/__tests__/list-like.test.ts +63 -0
  178. package/src/tree/util/__tests__/outputwriter.test.ts +523 -0
  179. package/src/tree/util/__tests__/print.test.ts +183 -0
  180. package/src/tree/util/__tests__/process-extends.test.ts +226 -0
  181. package/src/tree/util/__tests__/process-leading-is.test.ts +205 -0
  182. package/src/tree/util/__tests__/recursion-helper.test.ts +184 -0
  183. package/src/tree/util/__tests__/selector-match-unit.test.ts +1427 -0
  184. package/src/tree/util/__tests__/sourcemap.test.ts +117 -0
  185. package/src/tree/util/ampersand-template.ts +9 -0
  186. package/src/tree/util/bitset.ts +194 -0
  187. package/src/tree/util/calculate.ts +11 -0
  188. package/src/tree/util/cast.ts +89 -0
  189. package/src/tree/util/cloning.ts +8 -0
  190. package/src/tree/util/collections.ts +299 -0
  191. package/src/tree/util/compare.ts +90 -0
  192. package/src/tree/util/cursor.ts +171 -0
  193. package/src/tree/util/extend-core.ts +2139 -0
  194. package/src/tree/util/extend-roots.ts +1108 -0
  195. package/src/tree/util/field-helpers.ts +354 -0
  196. package/src/tree/util/is-node.ts +43 -0
  197. package/src/tree/util/list-like.ts +93 -0
  198. package/src/tree/util/mixin-instance-primitives.ts +2020 -0
  199. package/src/tree/util/print.ts +303 -0
  200. package/src/tree/util/process-leading-is.ts +421 -0
  201. package/src/tree/util/recursion-helper.ts +54 -0
  202. package/src/tree/util/regex.ts +2 -0
  203. package/src/tree/util/registry-utils.ts +1953 -0
  204. package/src/tree/util/ruleset-trace.ts +17 -0
  205. package/src/tree/util/scoped-body-eval.ts +320 -0
  206. package/src/tree/util/selector-match-core.ts +2005 -0
  207. package/src/tree/util/selector-utils.ts +757 -0
  208. package/src/tree/util/serialize-helper.ts +535 -0
  209. package/src/tree/util/serialize-types.ts +318 -0
  210. package/src/tree/util/should-operate.ts +78 -0
  211. package/src/tree/util/sourcemap.ts +37 -0
  212. package/src/types/config.ts +247 -0
  213. package/src/types/index.ts +12 -0
  214. package/{lib/types/modes.d.ts → src/types/modes.ts} +2 -1
  215. package/src/types.d.ts +9 -0
  216. package/src/types.ts +68 -0
  217. package/src/use-webpack-resolver.ts +56 -0
  218. package/src/visitor/__tests__/visitor.test.ts +136 -0
  219. package/src/visitor/index.ts +263 -0
  220. package/{lib/visitor/less-visitor.js → src/visitor/less-visitor.ts} +3 -2
  221. package/lib/context.d.ts +0 -352
  222. package/lib/context.d.ts.map +0 -1
  223. package/lib/context.js +0 -636
  224. package/lib/context.js.map +0 -1
  225. package/lib/conversions.d.ts +0 -73
  226. package/lib/conversions.d.ts.map +0 -1
  227. package/lib/conversions.js +0 -253
  228. package/lib/conversions.js.map +0 -1
  229. package/lib/debug-log.d.ts +0 -2
  230. package/lib/debug-log.d.ts.map +0 -1
  231. package/lib/debug-log.js +0 -27
  232. package/lib/debug-log.js.map +0 -1
  233. package/lib/define-function.d.ts +0 -587
  234. package/lib/define-function.d.ts.map +0 -1
  235. package/lib/define-function.js +0 -726
  236. package/lib/define-function.js.map +0 -1
  237. package/lib/deprecation.d.ts +0 -34
  238. package/lib/deprecation.d.ts.map +0 -1
  239. package/lib/deprecation.js +0 -57
  240. package/lib/deprecation.js.map +0 -1
  241. package/lib/jess-error.d.ts +0 -343
  242. package/lib/jess-error.d.ts.map +0 -1
  243. package/lib/jess-error.js +0 -508
  244. package/lib/jess-error.js.map +0 -1
  245. package/lib/logger/deprecation-processing.d.ts +0 -41
  246. package/lib/logger/deprecation-processing.d.ts.map +0 -1
  247. package/lib/logger/deprecation-processing.js +0 -81
  248. package/lib/logger/deprecation-processing.js.map +0 -1
  249. package/lib/logger.d.ts +0 -10
  250. package/lib/logger.d.ts.map +0 -1
  251. package/lib/logger.js +0 -20
  252. package/lib/logger.js.map +0 -1
  253. package/lib/plugin.d.ts +0 -94
  254. package/lib/plugin.d.ts.map +0 -1
  255. package/lib/plugin.js +0 -174
  256. package/lib/plugin.js.map +0 -1
  257. package/lib/tree/ampersand.d.ts +0 -98
  258. package/lib/tree/ampersand.d.ts.map +0 -1
  259. package/lib/tree/ampersand.js +0 -319
  260. package/lib/tree/ampersand.js.map +0 -1
  261. package/lib/tree/any.d.ts +0 -58
  262. package/lib/tree/any.d.ts.map +0 -1
  263. package/lib/tree/any.js +0 -104
  264. package/lib/tree/any.js.map +0 -1
  265. package/lib/tree/at-rule.d.ts +0 -53
  266. package/lib/tree/at-rule.d.ts.map +0 -1
  267. package/lib/tree/at-rule.js +0 -503
  268. package/lib/tree/at-rule.js.map +0 -1
  269. package/lib/tree/block.d.ts +0 -22
  270. package/lib/tree/block.d.ts.map +0 -1
  271. package/lib/tree/block.js +0 -24
  272. package/lib/tree/block.js.map +0 -1
  273. package/lib/tree/bool.d.ts +0 -18
  274. package/lib/tree/bool.d.ts.map +0 -1
  275. package/lib/tree/bool.js +0 -28
  276. package/lib/tree/bool.js.map +0 -1
  277. package/lib/tree/call.d.ts +0 -66
  278. package/lib/tree/call.d.ts.map +0 -1
  279. package/lib/tree/call.js +0 -306
  280. package/lib/tree/call.js.map +0 -1
  281. package/lib/tree/collection.d.ts +0 -30
  282. package/lib/tree/collection.d.ts.map +0 -1
  283. package/lib/tree/collection.js +0 -37
  284. package/lib/tree/collection.js.map +0 -1
  285. package/lib/tree/color.d.ts +0 -101
  286. package/lib/tree/color.d.ts.map +0 -1
  287. package/lib/tree/color.js +0 -513
  288. package/lib/tree/color.js.map +0 -1
  289. package/lib/tree/combinator.d.ts +0 -13
  290. package/lib/tree/combinator.d.ts.map +0 -1
  291. package/lib/tree/combinator.js +0 -12
  292. package/lib/tree/combinator.js.map +0 -1
  293. package/lib/tree/comment.d.ts +0 -20
  294. package/lib/tree/comment.d.ts.map +0 -1
  295. package/lib/tree/comment.js +0 -19
  296. package/lib/tree/comment.js.map +0 -1
  297. package/lib/tree/condition.d.ts +0 -31
  298. package/lib/tree/condition.d.ts.map +0 -1
  299. package/lib/tree/condition.js +0 -103
  300. package/lib/tree/condition.js.map +0 -1
  301. package/lib/tree/control.d.ts +0 -104
  302. package/lib/tree/control.d.ts.map +0 -1
  303. package/lib/tree/control.js +0 -430
  304. package/lib/tree/control.js.map +0 -1
  305. package/lib/tree/declaration-custom.d.ts +0 -18
  306. package/lib/tree/declaration-custom.d.ts.map +0 -1
  307. package/lib/tree/declaration-custom.js +0 -24
  308. package/lib/tree/declaration-custom.js.map +0 -1
  309. package/lib/tree/declaration-var.d.ts +0 -35
  310. package/lib/tree/declaration-var.d.ts.map +0 -1
  311. package/lib/tree/declaration-var.js +0 -63
  312. package/lib/tree/declaration-var.js.map +0 -1
  313. package/lib/tree/declaration.d.ts +0 -78
  314. package/lib/tree/declaration.d.ts.map +0 -1
  315. package/lib/tree/declaration.js +0 -286
  316. package/lib/tree/declaration.js.map +0 -1
  317. package/lib/tree/default-guard.d.ts +0 -15
  318. package/lib/tree/default-guard.d.ts.map +0 -1
  319. package/lib/tree/default-guard.js +0 -19
  320. package/lib/tree/default-guard.js.map +0 -1
  321. package/lib/tree/dimension.d.ts +0 -34
  322. package/lib/tree/dimension.d.ts.map +0 -1
  323. package/lib/tree/dimension.js +0 -294
  324. package/lib/tree/dimension.js.map +0 -1
  325. package/lib/tree/expression.d.ts +0 -25
  326. package/lib/tree/expression.d.ts.map +0 -1
  327. package/lib/tree/expression.js +0 -32
  328. package/lib/tree/expression.js.map +0 -1
  329. package/lib/tree/extend-list.d.ts +0 -23
  330. package/lib/tree/extend-list.d.ts.map +0 -1
  331. package/lib/tree/extend-list.js +0 -23
  332. package/lib/tree/extend-list.js.map +0 -1
  333. package/lib/tree/extend.d.ts +0 -47
  334. package/lib/tree/extend.d.ts.map +0 -1
  335. package/lib/tree/extend.js +0 -296
  336. package/lib/tree/extend.js.map +0 -1
  337. package/lib/tree/function.d.ts +0 -48
  338. package/lib/tree/function.d.ts.map +0 -1
  339. package/lib/tree/function.js +0 -74
  340. package/lib/tree/function.js.map +0 -1
  341. package/lib/tree/import-js.d.ts +0 -35
  342. package/lib/tree/import-js.d.ts.map +0 -1
  343. package/lib/tree/import-js.js +0 -45
  344. package/lib/tree/import-js.js.map +0 -1
  345. package/lib/tree/import-style.d.ts +0 -156
  346. package/lib/tree/import-style.d.ts.map +0 -1
  347. package/lib/tree/import-style.js +0 -566
  348. package/lib/tree/import-style.js.map +0 -1
  349. package/lib/tree/index.d.ts +0 -71
  350. package/lib/tree/index.d.ts.map +0 -1
  351. package/lib/tree/index.js.map +0 -1
  352. package/lib/tree/interpolated-reference.d.ts +0 -24
  353. package/lib/tree/interpolated-reference.d.ts.map +0 -1
  354. package/lib/tree/interpolated-reference.js +0 -37
  355. package/lib/tree/interpolated-reference.js.map +0 -1
  356. package/lib/tree/interpolated.d.ts +0 -62
  357. package/lib/tree/interpolated.d.ts.map +0 -1
  358. package/lib/tree/interpolated.js +0 -204
  359. package/lib/tree/interpolated.js.map +0 -1
  360. package/lib/tree/js-array.d.ts +0 -10
  361. package/lib/tree/js-array.d.ts.map +0 -1
  362. package/lib/tree/js-array.js +0 -10
  363. package/lib/tree/js-array.js.map +0 -1
  364. package/lib/tree/js-expr.d.ts +0 -23
  365. package/lib/tree/js-expr.d.ts.map +0 -1
  366. package/lib/tree/js-expr.js +0 -28
  367. package/lib/tree/js-expr.js.map +0 -1
  368. package/lib/tree/js-function.d.ts +0 -20
  369. package/lib/tree/js-function.d.ts.map +0 -1
  370. package/lib/tree/js-function.js +0 -16
  371. package/lib/tree/js-function.js.map +0 -1
  372. package/lib/tree/js-object.d.ts +0 -10
  373. package/lib/tree/js-object.d.ts.map +0 -1
  374. package/lib/tree/js-object.js +0 -10
  375. package/lib/tree/js-object.js.map +0 -1
  376. package/lib/tree/list.d.ts +0 -38
  377. package/lib/tree/list.d.ts.map +0 -1
  378. package/lib/tree/list.js +0 -83
  379. package/lib/tree/list.js.map +0 -1
  380. package/lib/tree/log.d.ts +0 -29
  381. package/lib/tree/log.d.ts.map +0 -1
  382. package/lib/tree/log.js +0 -56
  383. package/lib/tree/log.js.map +0 -1
  384. package/lib/tree/mixin.d.ts +0 -87
  385. package/lib/tree/mixin.d.ts.map +0 -1
  386. package/lib/tree/mixin.js +0 -112
  387. package/lib/tree/mixin.js.map +0 -1
  388. package/lib/tree/negative.d.ts +0 -17
  389. package/lib/tree/negative.d.ts.map +0 -1
  390. package/lib/tree/negative.js +0 -22
  391. package/lib/tree/negative.js.map +0 -1
  392. package/lib/tree/nil.d.ts +0 -30
  393. package/lib/tree/nil.d.ts.map +0 -1
  394. package/lib/tree/nil.js +0 -35
  395. package/lib/tree/nil.js.map +0 -1
  396. package/lib/tree/node-base.d.ts +0 -361
  397. package/lib/tree/node-base.d.ts.map +0 -1
  398. package/lib/tree/node-base.js +0 -930
  399. package/lib/tree/node-base.js.map +0 -1
  400. package/lib/tree/node.d.ts +0 -10
  401. package/lib/tree/node.d.ts.map +0 -1
  402. package/lib/tree/node.js +0 -45
  403. package/lib/tree/node.js.map +0 -1
  404. package/lib/tree/number.d.ts +0 -21
  405. package/lib/tree/number.d.ts.map +0 -1
  406. package/lib/tree/number.js +0 -27
  407. package/lib/tree/number.js.map +0 -1
  408. package/lib/tree/operation.d.ts +0 -26
  409. package/lib/tree/operation.d.ts.map +0 -1
  410. package/lib/tree/operation.js +0 -103
  411. package/lib/tree/operation.js.map +0 -1
  412. package/lib/tree/paren.d.ts +0 -19
  413. package/lib/tree/paren.d.ts.map +0 -1
  414. package/lib/tree/paren.js +0 -92
  415. package/lib/tree/paren.js.map +0 -1
  416. package/lib/tree/query-condition.d.ts +0 -17
  417. package/lib/tree/query-condition.d.ts.map +0 -1
  418. package/lib/tree/query-condition.js +0 -39
  419. package/lib/tree/query-condition.js.map +0 -1
  420. package/lib/tree/quoted.d.ts +0 -28
  421. package/lib/tree/quoted.d.ts.map +0 -1
  422. package/lib/tree/quoted.js +0 -75
  423. package/lib/tree/quoted.js.map +0 -1
  424. package/lib/tree/range.d.ts +0 -33
  425. package/lib/tree/range.d.ts.map +0 -1
  426. package/lib/tree/range.js +0 -47
  427. package/lib/tree/range.js.map +0 -1
  428. package/lib/tree/reference.d.ts +0 -76
  429. package/lib/tree/reference.d.ts.map +0 -1
  430. package/lib/tree/reference.js +0 -521
  431. package/lib/tree/reference.js.map +0 -1
  432. package/lib/tree/rest.d.ts +0 -15
  433. package/lib/tree/rest.d.ts.map +0 -1
  434. package/lib/tree/rest.js +0 -32
  435. package/lib/tree/rest.js.map +0 -1
  436. package/lib/tree/rules-raw.d.ts +0 -17
  437. package/lib/tree/rules-raw.d.ts.map +0 -1
  438. package/lib/tree/rules-raw.js +0 -37
  439. package/lib/tree/rules-raw.js.map +0 -1
  440. package/lib/tree/rules.d.ts +0 -262
  441. package/lib/tree/rules.d.ts.map +0 -1
  442. package/lib/tree/rules.js +0 -2359
  443. package/lib/tree/rules.js.map +0 -1
  444. package/lib/tree/ruleset.d.ts +0 -92
  445. package/lib/tree/ruleset.d.ts.map +0 -1
  446. package/lib/tree/ruleset.js +0 -528
  447. package/lib/tree/ruleset.js.map +0 -1
  448. package/lib/tree/selector-attr.d.ts +0 -31
  449. package/lib/tree/selector-attr.d.ts.map +0 -1
  450. package/lib/tree/selector-attr.js +0 -99
  451. package/lib/tree/selector-attr.js.map +0 -1
  452. package/lib/tree/selector-basic.d.ts +0 -24
  453. package/lib/tree/selector-basic.d.ts.map +0 -1
  454. package/lib/tree/selector-basic.js +0 -38
  455. package/lib/tree/selector-basic.js.map +0 -1
  456. package/lib/tree/selector-capture.d.ts +0 -23
  457. package/lib/tree/selector-capture.d.ts.map +0 -1
  458. package/lib/tree/selector-capture.js +0 -34
  459. package/lib/tree/selector-capture.js.map +0 -1
  460. package/lib/tree/selector-complex.d.ts +0 -40
  461. package/lib/tree/selector-complex.d.ts.map +0 -1
  462. package/lib/tree/selector-complex.js +0 -143
  463. package/lib/tree/selector-complex.js.map +0 -1
  464. package/lib/tree/selector-compound.d.ts +0 -16
  465. package/lib/tree/selector-compound.d.ts.map +0 -1
  466. package/lib/tree/selector-compound.js +0 -114
  467. package/lib/tree/selector-compound.js.map +0 -1
  468. package/lib/tree/selector-interpolated.d.ts +0 -23
  469. package/lib/tree/selector-interpolated.d.ts.map +0 -1
  470. package/lib/tree/selector-interpolated.js +0 -27
  471. package/lib/tree/selector-interpolated.js.map +0 -1
  472. package/lib/tree/selector-list.d.ts +0 -17
  473. package/lib/tree/selector-list.d.ts.map +0 -1
  474. package/lib/tree/selector-list.js +0 -174
  475. package/lib/tree/selector-list.js.map +0 -1
  476. package/lib/tree/selector-pseudo.d.ts +0 -42
  477. package/lib/tree/selector-pseudo.d.ts.map +0 -1
  478. package/lib/tree/selector-pseudo.js +0 -204
  479. package/lib/tree/selector-pseudo.js.map +0 -1
  480. package/lib/tree/selector-simple.d.ts +0 -5
  481. package/lib/tree/selector-simple.d.ts.map +0 -1
  482. package/lib/tree/selector-simple.js +0 -6
  483. package/lib/tree/selector-simple.js.map +0 -1
  484. package/lib/tree/selector.d.ts +0 -43
  485. package/lib/tree/selector.d.ts.map +0 -1
  486. package/lib/tree/selector.js +0 -56
  487. package/lib/tree/selector.js.map +0 -1
  488. package/lib/tree/sequence.d.ts +0 -43
  489. package/lib/tree/sequence.d.ts.map +0 -1
  490. package/lib/tree/sequence.js +0 -151
  491. package/lib/tree/sequence.js.map +0 -1
  492. package/lib/tree/tree.d.ts +0 -87
  493. package/lib/tree/tree.d.ts.map +0 -1
  494. package/lib/tree/tree.js +0 -2
  495. package/lib/tree/tree.js.map +0 -1
  496. package/lib/tree/url.d.ts +0 -18
  497. package/lib/tree/url.d.ts.map +0 -1
  498. package/lib/tree/url.js +0 -35
  499. package/lib/tree/url.js.map +0 -1
  500. package/lib/tree/util/__tests__/debug-log.d.ts +0 -1
  501. package/lib/tree/util/__tests__/debug-log.d.ts.map +0 -1
  502. package/lib/tree/util/__tests__/debug-log.js +0 -36
  503. package/lib/tree/util/__tests__/debug-log.js.map +0 -1
  504. package/lib/tree/util/calculate.d.ts +0 -3
  505. package/lib/tree/util/calculate.d.ts.map +0 -1
  506. package/lib/tree/util/calculate.js +0 -10
  507. package/lib/tree/util/calculate.js.map +0 -1
  508. package/lib/tree/util/cast.d.ts +0 -10
  509. package/lib/tree/util/cast.d.ts.map +0 -1
  510. package/lib/tree/util/cast.js +0 -87
  511. package/lib/tree/util/cast.js.map +0 -1
  512. package/lib/tree/util/cloning.d.ts +0 -4
  513. package/lib/tree/util/cloning.d.ts.map +0 -1
  514. package/lib/tree/util/cloning.js +0 -8
  515. package/lib/tree/util/cloning.js.map +0 -1
  516. package/lib/tree/util/collections.d.ts +0 -57
  517. package/lib/tree/util/collections.d.ts.map +0 -1
  518. package/lib/tree/util/collections.js +0 -136
  519. package/lib/tree/util/collections.js.map +0 -1
  520. package/lib/tree/util/compare.d.ts +0 -11
  521. package/lib/tree/util/compare.d.ts.map +0 -1
  522. package/lib/tree/util/compare.js +0 -89
  523. package/lib/tree/util/compare.js.map +0 -1
  524. package/lib/tree/util/extend-helpers.d.ts +0 -2
  525. package/lib/tree/util/extend-helpers.d.ts.map +0 -1
  526. package/lib/tree/util/extend-helpers.js +0 -2
  527. package/lib/tree/util/extend-helpers.js.map +0 -1
  528. package/lib/tree/util/extend-roots.d.ts +0 -37
  529. package/lib/tree/util/extend-roots.d.ts.map +0 -1
  530. package/lib/tree/util/extend-roots.js +0 -700
  531. package/lib/tree/util/extend-roots.js.map +0 -1
  532. package/lib/tree/util/extend-roots.old.d.ts +0 -132
  533. package/lib/tree/util/extend-roots.old.d.ts.map +0 -1
  534. package/lib/tree/util/extend-roots.old.js +0 -2272
  535. package/lib/tree/util/extend-roots.old.js.map +0 -1
  536. package/lib/tree/util/extend-trace-debug.d.ts +0 -13
  537. package/lib/tree/util/extend-trace-debug.d.ts.map +0 -1
  538. package/lib/tree/util/extend-trace-debug.js +0 -34
  539. package/lib/tree/util/extend-trace-debug.js.map +0 -1
  540. package/lib/tree/util/extend-walk.d.ts +0 -53
  541. package/lib/tree/util/extend-walk.d.ts.map +0 -1
  542. package/lib/tree/util/extend-walk.js +0 -881
  543. package/lib/tree/util/extend-walk.js.map +0 -1
  544. package/lib/tree/util/extend.d.ts +0 -218
  545. package/lib/tree/util/extend.d.ts.map +0 -1
  546. package/lib/tree/util/extend.js +0 -3182
  547. package/lib/tree/util/extend.js.map +0 -1
  548. package/lib/tree/util/find-extendable-locations.d.ts +0 -2
  549. package/lib/tree/util/find-extendable-locations.d.ts.map +0 -1
  550. package/lib/tree/util/find-extendable-locations.js +0 -2
  551. package/lib/tree/util/find-extendable-locations.js.map +0 -1
  552. package/lib/tree/util/format.d.ts +0 -20
  553. package/lib/tree/util/format.d.ts.map +0 -1
  554. package/lib/tree/util/format.js +0 -67
  555. package/lib/tree/util/format.js.map +0 -1
  556. package/lib/tree/util/is-node.d.ts +0 -13
  557. package/lib/tree/util/is-node.d.ts.map +0 -1
  558. package/lib/tree/util/is-node.js +0 -43
  559. package/lib/tree/util/is-node.js.map +0 -1
  560. package/lib/tree/util/print.d.ts +0 -80
  561. package/lib/tree/util/print.d.ts.map +0 -1
  562. package/lib/tree/util/print.js +0 -205
  563. package/lib/tree/util/print.js.map +0 -1
  564. package/lib/tree/util/process-leading-is.d.ts +0 -25
  565. package/lib/tree/util/process-leading-is.d.ts.map +0 -1
  566. package/lib/tree/util/process-leading-is.js +0 -364
  567. package/lib/tree/util/process-leading-is.js.map +0 -1
  568. package/lib/tree/util/recursion-helper.d.ts +0 -15
  569. package/lib/tree/util/recursion-helper.d.ts.map +0 -1
  570. package/lib/tree/util/recursion-helper.js +0 -43
  571. package/lib/tree/util/recursion-helper.js.map +0 -1
  572. package/lib/tree/util/regex.d.ts +0 -4
  573. package/lib/tree/util/regex.d.ts.map +0 -1
  574. package/lib/tree/util/regex.js +0 -4
  575. package/lib/tree/util/regex.js.map +0 -1
  576. package/lib/tree/util/registry-utils.d.ts +0 -192
  577. package/lib/tree/util/registry-utils.d.ts.map +0 -1
  578. package/lib/tree/util/registry-utils.js +0 -1214
  579. package/lib/tree/util/registry-utils.js.map +0 -1
  580. package/lib/tree/util/ruleset-trace.d.ts +0 -4
  581. package/lib/tree/util/ruleset-trace.d.ts.map +0 -1
  582. package/lib/tree/util/ruleset-trace.js +0 -14
  583. package/lib/tree/util/ruleset-trace.js.map +0 -1
  584. package/lib/tree/util/selector-compare.d.ts +0 -2
  585. package/lib/tree/util/selector-compare.d.ts.map +0 -1
  586. package/lib/tree/util/selector-compare.js +0 -2
  587. package/lib/tree/util/selector-compare.js.map +0 -1
  588. package/lib/tree/util/selector-match-core.d.ts +0 -184
  589. package/lib/tree/util/selector-match-core.d.ts.map +0 -1
  590. package/lib/tree/util/selector-match-core.js +0 -1603
  591. package/lib/tree/util/selector-match-core.js.map +0 -1
  592. package/lib/tree/util/selector-utils.d.ts +0 -30
  593. package/lib/tree/util/selector-utils.d.ts.map +0 -1
  594. package/lib/tree/util/selector-utils.js +0 -100
  595. package/lib/tree/util/selector-utils.js.map +0 -1
  596. package/lib/tree/util/serialize-helper.d.ts +0 -13
  597. package/lib/tree/util/serialize-helper.d.ts.map +0 -1
  598. package/lib/tree/util/serialize-helper.js +0 -387
  599. package/lib/tree/util/serialize-helper.js.map +0 -1
  600. package/lib/tree/util/serialize-types.d.ts +0 -9
  601. package/lib/tree/util/serialize-types.d.ts.map +0 -1
  602. package/lib/tree/util/serialize-types.js +0 -216
  603. package/lib/tree/util/serialize-types.js.map +0 -1
  604. package/lib/tree/util/should-operate.d.ts +0 -23
  605. package/lib/tree/util/should-operate.d.ts.map +0 -1
  606. package/lib/tree/util/should-operate.js +0 -46
  607. package/lib/tree/util/should-operate.js.map +0 -1
  608. package/lib/tree/util/sourcemap.d.ts +0 -7
  609. package/lib/tree/util/sourcemap.d.ts.map +0 -1
  610. package/lib/tree/util/sourcemap.js +0 -25
  611. package/lib/tree/util/sourcemap.js.map +0 -1
  612. package/lib/types/config.d.ts +0 -205
  613. package/lib/types/config.d.ts.map +0 -1
  614. package/lib/types/config.js +0 -2
  615. package/lib/types/config.js.map +0 -1
  616. package/lib/types/index.d.ts +0 -15
  617. package/lib/types/index.d.ts.map +0 -1
  618. package/lib/types/index.js +0 -3
  619. package/lib/types/index.js.map +0 -1
  620. package/lib/types/modes.d.ts.map +0 -1
  621. package/lib/types/modes.js +0 -2
  622. package/lib/types/modes.js.map +0 -1
  623. package/lib/types.d.ts +0 -61
  624. package/lib/types.d.ts.map +0 -1
  625. package/lib/types.js +0 -2
  626. package/lib/types.js.map +0 -1
  627. package/lib/use-webpack-resolver.d.ts +0 -9
  628. package/lib/use-webpack-resolver.d.ts.map +0 -1
  629. package/lib/use-webpack-resolver.js +0 -41
  630. package/lib/use-webpack-resolver.js.map +0 -1
  631. package/lib/visitor/index.d.ts +0 -136
  632. package/lib/visitor/index.d.ts.map +0 -1
  633. package/lib/visitor/index.js +0 -135
  634. package/lib/visitor/index.js.map +0 -1
  635. package/lib/visitor/less-visitor.d.ts +0 -7
  636. package/lib/visitor/less-visitor.d.ts.map +0 -1
  637. package/lib/visitor/less-visitor.js.map +0 -1
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,oBAAoB,CAAC;AAC5B,0BAA0B;AAC1B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,oCAAoC,CAAC;AACnD,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,wBAAwB,CAAC;AACvC,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC;AACvC,cAAc,qBAAqB,CAAC;AACpC,cAAc,0CAA0C,CAAC;AACzD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,sBAAsB,CAAC;AACrC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.js","names":["isArray","getNodeValue","isRulesNode","isArray","isArray","ampersandTemplateInterpolationRegex","ampersandTemplateRegex","isBareAmpersandOwnSelector","isBareAmpersandOwnSelector","path","indent","isBareAmpersandOwnSelector","getImplicitSelectorUtil","indent","isArray","arraysEqual","clamp","isArray","isArray","isArray","isArray","VarDeclarationCtor","Registries","isArray","indent","Registries\n .getDirectDeclarationsByKey","Registries.getDirectDeclarationsByKey","indent","VarDeclarationCtor","AnyCtor","isArray","isPlainObject"],"sources":["../src/tree/util/is-node.ts","../src/tree/node-type.ts","../src/tree/util/collections.ts","../src/tree/util/print.ts","../src/tree/util/cursor.ts","../src/tree/node-base.ts","../src/tree/nil.ts","../src/tree/any.ts","../src/jess-error.ts","../src/tree/selector.ts","../src/tree/selector-compound.ts","../src/tree/selector-complex.ts","../src/tree/util/bitset.ts","../src/tree/util/selector-match-core.ts","../src/tree/selector-list.ts","../src/tree/selector-simple.ts","../src/tree/selector-pseudo.ts","../src/tree/combinator.ts","../src/tree/selector-basic.ts","../src/tree/util/ampersand-template.ts","../src/tree/util/field-helpers.ts","../src/tree/util/selector-utils.ts","../src/tree/util/extend-core.ts","../src/tree/util/extend-roots.ts","../src/tree/util/should-operate.ts","../src/tree/util/recursion-helper.ts","../src/context.ts","../src/tree/node.ts","../src/tree/util/compare.ts","../src/tree/bool.ts","../src/tree/util/serialize-helper.ts","../src/tree/util/process-leading-is.ts","../src/tree/ruleset.ts","../src/tree/util/regex.ts","../src/tree/list.ts","../src/tree/sequence.ts","../src/tree/js-function.ts","../src/tree/util/registry-utils.ts","../src/tree/interpolated.ts","../src/tree/util/calculate.ts","../src/tree/color.ts","../src/tree/js-object.ts","../src/tree/util/cast.ts","../src/tree/reference.ts","../src/define-function.ts","../src/tree/expression.ts","../src/logger.ts","../src/tree/dimension.ts","../src/tree/paren.ts","../src/tree/call.ts","../src/tree/operation.ts","../src/tree/declaration.ts","../src/tree/declaration-var.ts","../src/tree/util/mixin-instance-primitives.ts","../src/tree/rules.ts","../src/tree/ampersand.ts","../src/tree/at-rule.ts","../src/tree/block.ts","../src/tree/comment.ts","../src/tree/condition.ts","../src/tree/number.ts","../src/tree/util/scoped-body-eval.ts","../src/tree/control.ts","../src/tree/declaration-custom.ts","../src/tree/extend.ts","../src/tree/log.ts","../src/tree/mixin.ts","../src/tree/negative.ts","../src/tree/function.ts","../src/tree/js-array.ts","../src/tree/quoted.ts","../src/tree/range.ts","../src/tree/rules-raw.ts","../src/tree/collection.ts","../src/tree/selector-attr.ts","../src/tree/selector-capture.ts","../src/tree/query-condition.ts","../src/tree/url.ts","../src/tree/import-style.ts","../src/tree/import-js.ts","../src/tree/selector-interpolated.ts","../src/tree/default-guard.ts","../src/tree/rest.ts","../src/tree/index.ts","../src/logger/deprecation-processing.ts","../src/plugin.ts","../src/deprecation.ts","../src/tree/util/serialize-types.ts","../src/tree/util/list-like.ts","../src/conversions.ts","../src/visitor/index.ts"],"sourcesContent":["import type { NToNode } from '../tree.js';\nimport { Node } from '../node.js';\n\n/**\n * Fast bitmask-based node type check.\n *\n * With no type argument, checks if value is a Node (instanceof or duck-type).\n * With a bitmask argument, checks if the node's type matches via bitwise AND.\n *\n * Examples:\n * isNode(x) // is it any node?\n * isNode(x, N.Selector) // is it any Selector subtype? (narrows to Selector)\n * isNode(x, N.Mixin | N.Func) // is it a Mixin or Func? (boolean, no narrowing)\n * isNode(x, N.BasicSelector) // is it specifically a BasicSelector? (narrows)\n */\n\nexport function isNode(value: unknown): value is Node;\n\nexport function isNode<M extends keyof NToNode>(\n value: unknown,\n mask: M\n): value is NToNode[M];\n\nexport function isNode(value: unknown, mask: number): boolean;\n\nexport function isNode(\n value: unknown,\n mask?: number\n): boolean {\n if (!value) {\n return false;\n }\n if (mask === undefined) {\n /** No-arg: check if it's any Node (including types not in the bitmask table) */\n if (value instanceof Node) {\n return true;\n }\n const record = value as Record<string, unknown>;\n return typeof record.type === 'string' && typeof record.children === 'function';\n }\n const record = value as Record<string, unknown>;\n return ((record.nodeType as number) & mask) !== 0;\n}\n","/**\n * Bitmask-based node type system.\n *\n * Each concrete node type gets a single bit. Abstract parent types\n * (Selector, SimpleSelector) are masks combining their children's bits.\n * A node's `nodeType` field is the OR of its own bit and all ancestor bits.\n *\n * isNode(x, N.Foo) compiles to: x.nodeType & Foo (one bitwise AND)\n */\n\n// ── Leaf bits (one bit per concrete type) ──────────────────────────\n// These are types that are checked via isNode AND are concrete (not abstract).\n// Sorted roughly by hierarchy grouping.\n\nexport enum N {\n // Selector subtypes\n BasicSelector = 1 << 0,\n Ampersand = 1 << 1,\n PseudoSelector = 1 << 2,\n CompoundSelector = 1 << 3,\n ComplexSelector = 1 << 4,\n SelectorList = 1 << 5,\n Combinator = 1 << 6,\n\n // Value types\n Any = 1 << 7,\n Color = 1 << 8,\n Dimension = 1 << 9,\n Quoted = 1 << 10,\n Expression = 1 << 11,\n Operation = 1 << 12,\n Paren = 1 << 13,\n Range = 1 << 14,\n List = 1 << 15,\n Sequence = 1 << 16,\n Nil = 1 << 17,\n\n // Callable types\n Call = 1 << 18,\n Func = 1 << 19,\n Mixin = 1 << 20,\n\n // Declaration types\n Declaration = 1 << 21,\n VarDeclaration = 1 << 22,\n\n // Container types\n Rules = 1 << 23,\n Collection = 1 << 24,\n Ruleset = 1 << 25,\n AtRule = 1 << 26,\n\n // Other types\n Reference = 1 << 27,\n Comment = 1 << 28,\n JsFunction = 1 << 29,\n JsObject = 1 << 30,\n // Note: 1 << 31 is negative in JS (sign bit), so we use it carefully\n JsArray = 1 << 31,\n\n // ── Abstract / parent masks ──────────────────────────────────────\n // These combine child bits so isNode(x, N.Selector) matches any selector.\n\n SimpleSelector = BasicSelector | Ampersand | PseudoSelector,\n Selector = SimpleSelector | CompoundSelector | ComplexSelector | SelectorList | Combinator\n}\n\n/**\n * Map from type name string → bitmask.\n * Used by defineType to look up the mask for a given type name\n * when walking the prototype chain.\n */\n/**\n * Map from type name string → bitmask.\n * Used by defineType to look up the bit for a given type name\n * when walking the prototype chain.\n *\n * IMPORTANT: Abstract parent types (Selector, SimpleSelector) map to 0 here.\n * Their combined masks (N.Selector, N.SimpleSelector) are only used by\n * isNode callers, NOT by defineType. Each concrete child already has its own\n * bit, so when defineType walks the chain, the child's bit is sufficient.\n */\nexport const nodeTypeBits: Record<string, number> = {\n // Concrete leaf types — each gets its own bit\n BasicSelector: N.BasicSelector,\n Ampersand: N.Ampersand,\n PseudoSelector: N.PseudoSelector,\n CompoundSelector: N.CompoundSelector,\n ComplexSelector: N.ComplexSelector,\n SelectorList: N.SelectorList,\n Combinator: N.Combinator,\n Any: N.Any,\n Color: N.Color,\n Dimension: N.Dimension,\n Quoted: N.Quoted,\n Expression: N.Expression,\n Operation: N.Operation,\n Paren: N.Paren,\n Range: N.Range,\n List: N.List,\n Sequence: N.Sequence,\n Nil: N.Nil,\n Call: N.Call,\n Func: N.Func,\n Mixin: N.Mixin,\n Declaration: N.Declaration,\n VarDeclaration: N.VarDeclaration,\n Rules: N.Rules,\n Collection: N.Collection,\n Ruleset: N.Ruleset,\n AtRule: N.AtRule,\n Reference: N.Reference,\n Comment: N.Comment,\n JsFunction: N.JsFunction,\n JsObject: N.JsObject,\n JsArray: N.JsArray,\n\n // Abstract parent types — 0 because children already have their own bits.\n // The combined masks (N.Selector, N.SimpleSelector) are for isNode callers only.\n Selector: 0,\n SimpleSelector: 0\n};\n","/**\n * Originally I had custom Hashmaps and ArrayLists, in order to normalize\n * generators and iterators for each. But using non-native collections\n * adds complexity but, more importantly, performance overhead, especially\n * if you don't use those iterators.\n *\n * Even using a Map over an object for a dictionary, in theory, has faster\n * lookups, but in total evaluation time, when the file is parsed, it would\n * be passing in either a Map or an object, and converting the object\n * to a map has object creation overhead, and so does creating the map itself,\n * if you pass in an array of arrays.\n *\n * Maps are good for dynamic property additions and repeated lookups. Nodes\n * look up / evaluate properties, at most, once per node, so an object-as-map\n * will either be faster or the differences will be negligible.\n *\n * So now, data is exceedingly simple. It's all passed in as is when parsing or\n * using the API, and we just have some utility functions in this file to iterate over\n * arrays / objects / simple values and return the values or entries, in any order.\n */\nimport type { ConditionalExcept } from 'type-fest';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport type { Mixin } from '../mixin.js';\nimport type { Rules } from '../rules.js';\nimport type { Ruleset } from '../ruleset.js';\nimport type { Node } from '../node.js';\n\nconst { isArray } = Array;\n\n/** Fast replacement for lodash isPlainObject — checks constructor === Object */\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && value.constructor === Object;\n\nexport function atIndex<T>(array: readonly T[], index: number = -1): T | undefined {\n if (index >= 0) {\n return array[index];\n }\n /** Use a negative index to access from the last element */\n return array[array.length + index];\n}\n\n/**\n * Entry generators, and this type will yield\n * - [0] the value\n * - [1] the key, if applicable, or the key '__value' for non-objects\n * - [2] the containing object.\n *\n * The purpose of this structure is to iterate and allow replacement\n * of the value in its containing object.\n *\n * The function logic should mirror this type logic.\n */\ntype GetEntriesOf<T> = T extends readonly any[]\n ? [T[number], number, T]\n : T extends Node\n ? [Node, Node, Rules]\n : T extends Record<string, infer RecordValue>\n ? RecordValue extends readonly any[]\n ? [RecordValue[number], number, RecordValue]\n : [RecordValue, keyof ConditionalExcept<T, readonly any[]>, T]\n : [T, 'data', T];\n\n// type Test = GetEntriesOf<Node<string>>\n// type Test2 = GetEntriesOf<Node<string[]>>\n// type Test3 = GetEntriesOf<Node<{ selector: Node[], foo: 'string' }>>\n\nexport function* getValues<T>(collection: T, reverse = false): Generator<GetEntriesOf<{ data: T }>[0]> {\n if (isArray(collection)) {\n if (reverse) {\n for (let i = collection.length - 1; i >= 0; i--) {\n yield collection[i]!;\n }\n } else {\n let length = collection.length;\n for (let i = 0; i < length; i++) {\n yield collection[i]!;\n }\n }\n } else if (isPlainObject(collection)) {\n const values = Object.values(collection as Record<string, unknown>);\n for (let value of values) {\n if (isArray(value)) {\n yield* getValues(value, reverse);\n } else {\n yield value;\n }\n }\n } else {\n yield collection;\n }\n}\n\nexport function* getEntries<T>(collection: T, reverse = false): Generator<GetEntriesOf<T>> {\n if (isArray(collection)) {\n if (reverse) {\n for (let i = collection.length - 1; i >= 0; i--) {\n yield [collection[i]!, i, collection] as GetEntriesOf<T>;\n }\n } else {\n let length = collection.length;\n for (let i = 0; i < length; i++) {\n yield [collection[i]!, i, collection] as GetEntriesOf<T>;\n }\n }\n } else if (isPlainObject(collection)) {\n const entries = Object.entries(collection as Record<string, unknown>);\n for (let [key, value] of entries) {\n if (isArray(value)) {\n yield* getEntries(value, reverse) as Generator<GetEntriesOf<T>>;\n } else {\n yield [value, key, collection] as GetEntriesOf<T>;\n }\n }\n } else if (isNode(collection, N.Mixin | N.Ruleset | N.Rules)) {\n let rules: Node[];\n if ((collection as Node).type === 'Mixin') {\n if ((collection as Mixin).get('params')?.length) {\n throw new Error('We can\\'t iterate over a mixin with parameters');\n }\n rules = [...(collection as Mixin).get('rules').value];\n } else if ((collection as Node).type === 'Ruleset') {\n rules = [...(collection as Ruleset).get('rules').value];\n } else if ((collection as Node).type === 'Rules') {\n rules = [...(collection as Rules).value];\n }\n for (let [, value] of rules!.entries()) {\n if (value.type === 'Comment') {\n continue;\n }\n if (!isNode(value, N.Declaration)) {\n throw new Error('We can\\'t iterate over rules with non-declarations');\n }\n yield [value.value, value.name, rules!] as unknown as GetEntriesOf<T>;\n }\n } else if (isNode(collection) && isArray((collection as Rules).value)) {\n yield* getEntries((collection as Rules).value as unknown[], reverse) as Generator<GetEntriesOf<T>>;\n } else {\n yield [collection, 'value', collection] as unknown as GetEntriesOf<T>;\n }\n}\n\nexport function arraysEqual(a: string[], b: string[]) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\ntype TraversalFrame = {\n items: Node[];\n index: number;\n};\n\ntype TraversalMark = {\n stack: TraversalFrame[];\n};\n\ntype NodeTraversalOptions = {\n includeSelf?: boolean;\n deep?: boolean;\n reverse?: boolean;\n includePrePost?: boolean;\n};\n\nfunction cloneFrames(frames: TraversalFrame[]): TraversalFrame[] {\n return frames.map(frame => ({\n items: frame.items,\n index: frame.index\n }));\n}\n\nfunction collectDirectNodes(\n node: Node,\n reverse = false,\n includePrePost = false\n): Node[] {\n const result: Node[] = [];\n const keys = (node.constructor as typeof Node).childKeys;\n\n if (keys) {\n const keyList = reverse ? [...keys].reverse() : keys;\n\n for (const key of keyList) {\n // Read from instance field directly (node[key]) instead of node.data[key],\n // because array containers' .data getter returns the array itself, not { value: array }.\n const nodeVal = (node as unknown as Record<string, unknown>)[key!];\n if (isArray(nodeVal)) {\n const items = reverse ? [...nodeVal].reverse() : nodeVal;\n for (const item of items) {\n if (isNode(item)) {\n if (includePrePost) {\n result.push(...item.nodeAndPrePost());\n } else {\n result.push(item);\n }\n }\n }\n } else if (isNode(nodeVal)) {\n if (includePrePost) {\n result.push(...nodeVal.nodeAndPrePost());\n } else {\n result.push(nodeVal);\n }\n }\n }\n }\n // Leaf nodes (keys === null) have no child nodes to collect\n\n return result;\n}\n\nexport class NodeTraversalCursor implements IterableIterator<Node> {\n private stack: TraversalFrame[] = [];\n private readonly deep: boolean;\n private readonly reverse: boolean;\n private readonly includePrePost: boolean;\n\n constructor(root: Node, options: NodeTraversalOptions = {}) {\n const {\n includeSelf = false,\n deep = false,\n reverse = false,\n includePrePost = false\n } = options;\n\n this.deep = deep;\n this.reverse = reverse;\n this.includePrePost = includePrePost;\n\n const initialItems = includeSelf\n ? includePrePost\n ? [...root.nodeAndPrePost()]\n : [root]\n : collectDirectNodes(root, reverse, includePrePost);\n\n this.stack.push({\n items: initialItems,\n index: 0\n });\n }\n\n [Symbol.iterator](): IterableIterator<Node> {\n return this;\n }\n\n next(): IteratorResult<Node> {\n while (this.stack.length > 0) {\n const frame = this.stack[this.stack.length - 1]!;\n\n if (frame.index >= frame.items.length) {\n this.stack.pop();\n continue;\n }\n\n const node = frame.items[frame.index++]!;\n\n if (this.deep) {\n const children = collectDirectNodes(\n node,\n this.reverse,\n this.includePrePost\n );\n\n if (children.length > 0) {\n this.stack.push({\n items: children,\n index: 0\n });\n }\n }\n\n return {\n done: false,\n value: node\n };\n }\n\n return {\n done: true,\n value: undefined as never\n };\n }\n\n mark(): TraversalMark {\n return {\n stack: cloneFrames(this.stack)\n };\n }\n\n restore(mark: TraversalMark): void {\n this.stack = cloneFrames(mark.stack);\n }\n}","import type { Context } from '../../context.js';\nimport type { AtRule } from '../at-rule.js';\nimport type { Ruleset } from '../ruleset.js';\nimport type { Node } from '../node.js';\n\nexport type PrintOptions = {\n /** The actual tree frames we started from */\n treeFrames?: (Ruleset | AtRule)[] | undefined;\n /** Tracks what ruleset or at-rule body we're serializing to the root */\n inFrames?: (Ruleset | AtRule)[] | undefined;\n /** Stored frames if we hoist a ruleset */\n lastRenderedFrames?: (Ruleset | AtRule)[] | undefined;\n frameHeaders?: string[];\n /** Current indentation depth (set by parent, used by children) */\n depth?: number;\n writer?: OutputWriter;\n compress?: boolean;\n collapseNesting?: boolean;\n context?: Context;\n inCustom?: boolean;\n /** True while traversing a referenced import/use tree. */\n referenceMode?: boolean;\n /** Effective render state while in referenceMode. */\n referenceRenderEnabled?: boolean;\n /** Whether extended descendants can activate rendering while in referenceMode. */\n referenceRenderOnExtend?: boolean;\n /** Enable SelectorList-level filtering of extend target members during reference rendering. */\n referenceFilterTargets?: boolean;\n /** Skip Comment nodes during rendering (replaces copy(true) for comment suppression). */\n suppressComments?: boolean;\n /** Internal: allow a captured child container to keep its own frame open for sibling continuation. */\n preserveCapturedContainerFrame?: boolean;\n};\n\nexport type FinalPrintOptions = PrintOptions & {\n writer: OutputWriter;\n depth: number;\n inFrames: (Ruleset | AtRule)[];\n treeFrames: (Ruleset | AtRule)[];\n frameHeaders: string[];\n lastRenderedFrames: (Ruleset | AtRule)[];\n};\n\nexport interface OutputWriter {\n add(text: string, origin?: unknown): void;\n mark(): number;\n getSince(mark: number): string;\n captureWithMeta(fn: () => void): CapturedOutput;\n signalBoundaryIntent(side: 'pre' | 'post', intent: BoundaryIntent): void;\n toString(): string;\n toSourceMapV3(): any;\n getSegments(): SourceSegment[];\n}\n\nexport type BoundaryIntent = 'implicit' | 'explicit_none' | 'explicit_space';\n\nexport type CapturedOutput = {\n text: string;\n leadingIntent: BoundaryIntent;\n trailingIntent: BoundaryIntent;\n};\n\nexport type SourceSegment = {\n genLine: number; // 0-based\n genColumn: number; // 0-based\n source?: string; // file full path or name\n origLine: number; // 0-based\n origColumn: number; // 0-based\n};\n\nexport function getPrintOptions(options?: PrintOptions): FinalPrintOptions {\n options = options ?? {};\n options.depth ??= 0;\n options.writer ??= new OutputWriter();\n // Derive collapseNesting from context when missing so nested vs flat is correct for & serialization\n if (options.collapseNesting === undefined && options.context?.opts?.collapseNesting !== undefined) {\n options.collapseNesting = Boolean(options.context.opts.collapseNesting);\n }\n // Always ensure frameState exists - nodes should not need to check for it\n options.inFrames ??= [];\n options.frameHeaders ??= [];\n options.treeFrames ??= [];\n options.lastRenderedFrames ??= [];\n options.referenceMode ??= false;\n options.referenceRenderEnabled ??= true;\n options.referenceRenderOnExtend ??= true;\n options.referenceFilterTargets ??= false;\n return options as FinalPrintOptions;\n}\n\nexport class OutputWriter implements OutputWriter {\n private chunks: string[] = [];\n private _length = 0;\n private _line = 0;\n private _column = 0;\n private _segments: SourceSegment[] = [];\n private _positions: Array<{ line: number; column: number; segments: number; length: number }> = [];\n private _boundarySignals: Array<{ side: 'pre' | 'post'; intent: BoundaryIntent; offset: number }> = [];\n private _signalPositions: number[] = [];\n /** Diagnostic: remember the origin that last wrote a trailing newline */\n private _lastNewlineOrigin: unknown = undefined;\n /** Store segments from the most recent capture for merging when content is added back */\n private _capturedSegments: SourceSegment[] | null = null;\n\n get line() {\n return this._line;\n }\n\n get column() {\n return this._column;\n }\n\n add(text: string, originParam?: unknown): void {\n if (!text) {\n return;\n }\n this.chunks.push(text);\n this._length += text.length;\n\n const currentLine = this._line;\n const currentColumn = this._column;\n\n // If we have captured segments and we're adding with an origin, merge them\n // This happens when captured content is added back (e.g., in Declaration.declTrimmedString)\n if (this._capturedSegments && originParam) {\n // Adjust captured segment positions to current writer position and add them\n for (const seg of this._capturedSegments) {\n // If segment is on the same line as capture start, add column offset\n // If segment is on a different line, column is already correct (relative to that line)\n const adjustedColumn = seg.genLine === 0 ? currentColumn + seg.genColumn : seg.genColumn;\n this._segments.push({\n genLine: currentLine + seg.genLine,\n genColumn: adjustedColumn,\n source: seg.source,\n origLine: seg.origLine,\n origColumn: seg.origColumn\n });\n }\n this._capturedSegments = null; // Clear after merging\n }\n\n // Record a mapping segment if we have origin location info\n const origin = originParam as { location?: unknown; treeContext?: { file?: { fullPath?: string; path?: string; name?: string } } } | undefined;\n const loc = origin?.location;\n if (loc && Array.isArray(loc) && loc.length === 6) {\n const startLine = ((loc[1] as number) ?? 1) - 1; // convert to 0-based\n const startColumn = ((loc[2] as number) ?? 1) - 1; // convert to 0-based\n const file = origin?.treeContext?.file?.fullPath || origin?.treeContext?.file?.path || origin?.treeContext?.file?.name;\n this._segments.push({\n genLine: this._line,\n genColumn: this._column,\n source: file,\n origLine: startLine,\n origColumn: startColumn\n });\n }\n\n // Track if the chunk ends with a newline and record its origin (for diagnostics)\n if (text.endsWith('\\n')) {\n this._lastNewlineOrigin = originParam;\n }\n\n // Fast path: no newlines\n let i = text.indexOf('\\n');\n if (i === -1) {\n this._column += text.length;\n this._positions.push({ line: this._line, column: this._column, segments: this._segments.length, length: this._length });\n this._signalPositions.push(this._boundarySignals.length);\n // Clear captured segments if we added content without origin (normal add, not merging captured content)\n if (!originParam) {\n this._capturedSegments = null;\n }\n return;\n }\n\n // Count newlines and compute trailing column after last newline\n this._line++;\n for (;;) {\n const next = text.indexOf('\\n', i + 1);\n if (next === -1) {\n break;\n }\n this._line++;\n i = next;\n }\n this._column = text.length - (i + 1);\n this._positions.push({ line: this._line, column: this._column, segments: this._segments.length, length: this._length });\n this._signalPositions.push(this._boundarySignals.length);\n // Clear captured segments if we added content without origin\n if (!originParam) {\n this._capturedSegments = null;\n }\n }\n\n mark(): number {\n return this.chunks.length;\n }\n\n getSince(mark: number): string {\n if (mark < 0 || mark > this.chunks.length) {\n return '';\n }\n return this.chunks.slice(mark).join('');\n }\n\n /** Restore writer state to a given mark, discarding appended chunks and segments */\n restore(mark: number): void {\n if (mark < 0 || mark > this.chunks.length) {\n return;\n }\n this.chunks.length = mark;\n const pos = this._positions[mark - 1];\n if (pos) {\n this._line = pos.line;\n this._column = pos.column;\n this._segments.length = pos.segments;\n this._length = pos.length;\n } else {\n this._line = 0;\n this._column = 0;\n this._segments.length = 0;\n this._length = 0;\n }\n this._positions.length = mark;\n const signalCount = this._signalPositions[mark - 1] ?? 0;\n this._boundarySignals.length = signalCount;\n this._signalPositions.length = mark;\n }\n\n /** Capture output from a function without committing to the main buffer */\n capture(fn: () => void): string {\n const m = this.mark();\n const segmentsBefore = this._segments.length;\n fn();\n const s = this.getSince(m);\n // Store segments created during capture (but don't add to main buffer)\n const segmentsCreated = this._segments.slice(segmentsBefore);\n this.restore(m);\n // Store captured segments for potential merging when content is added back\n this._capturedSegments = segmentsCreated.length > 0 ? segmentsCreated : null;\n return s;\n }\n\n captureWithMeta(fn: () => void): CapturedOutput {\n const m = this.mark();\n const segmentsBefore = this._segments.length;\n const startLen = this._length;\n const signalStart = this._boundarySignals.length;\n fn();\n const text = this.getSince(m);\n const endLen = this._length;\n const capturedSignals = this._boundarySignals.slice(signalStart);\n const segmentsCreated = this._segments.slice(segmentsBefore);\n this.restore(m);\n this._capturedSegments = segmentsCreated.length > 0 ? segmentsCreated : null;\n\n let leadingIntent: BoundaryIntent = 'implicit';\n let trailingIntent: BoundaryIntent = 'implicit';\n for (const signal of capturedSignals) {\n if (signal.side === 'pre' && signal.offset === startLen) {\n leadingIntent = signal.intent;\n break;\n }\n }\n for (let i = capturedSignals.length - 1; i >= 0; i--) {\n const signal = capturedSignals[i]!;\n if (signal.side === 'post' && signal.offset === endLen) {\n trailingIntent = signal.intent;\n break;\n }\n }\n return { text, leadingIntent, trailingIntent };\n }\n\n signalBoundaryIntent(side: 'pre' | 'post', intent: BoundaryIntent): void {\n this._boundarySignals.push({ side, intent, offset: this._length });\n }\n\n toString(): string {\n return this.chunks.join('');\n }\n\n toSourceMapV3(): any {\n return null;\n }\n\n getSegments(): SourceSegment[] {\n return this._segments;\n }\n\n /** Diagnostic accessor */\n getLastNewlineOrigin(): unknown {\n return this._lastNewlineOrigin;\n }\n}\n\n/**\n * Render a node to a string with optional print options.\n * Use `suppressComments: true` to skip Comment nodes without cloning.\n */\nexport function render(node: Node, options?: PrintOptions): string {\n return node.toString(options);\n}\n","import { CANONICAL, type Cursor, type Node, type NodeEdge, type RenderKey } from '../node.js';\n\nfunction nodeFields(node: Node): Record<string, unknown> {\n return node as unknown as Record<string, unknown>;\n}\n\nfunction getSingularEdgeStore(\n node: Node,\n key: string\n): NodeEdge<Node> | undefined {\n return nodeFields(node)[`${key}Edge`] as NodeEdge<Node> | undefined;\n}\n\nfunction getIndexedEdgeStore(\n node: Node,\n key: string\n): Array<NodeEdge<Node> | undefined> | undefined {\n return nodeFields(node)[`${key}Edges`] as Array<NodeEdge<Node> | undefined> | undefined;\n}\n\nfunction setSingularEdgeStore(\n node: Node,\n key: string,\n edge: NodeEdge<Node>\n): void {\n nodeFields(node)[`${key}Edge`] = edge;\n}\n\nfunction setIndexedEdgeStore(\n node: Node,\n key: string,\n edges: Array<NodeEdge<Node> | undefined>\n): void {\n nodeFields(node)[`${key}Edges`] = edges;\n}\n\nexport function lookupEdge<T>(\n edges: NodeEdge<T> | undefined,\n key: RenderKey\n): T | undefined {\n return edges?.get(key);\n}\n\n/**\n * Resolve the primary parent cursor for a node/render-key pair.\n *\n * This mirrors `getParent(...)` at the cursor layer:\n * - prefer the active render-key parent edge\n * - fall back to canonical `node.parent`\n *\n * It deliberately does not follow secondary lanes such as `CALLER`. Traversals that\n * want caller fallback must opt into that separately so the main render path stays\n * stable and predictable.\n */\nexport function getParentEdge(cursor: Cursor): Cursor | undefined {\n const overridden = lookupEdge(cursor.node.parentEdges, cursor.renderKey);\n if (overridden !== undefined) {\n return overridden ? { node: overridden, renderKey: cursor.renderKey } : undefined;\n }\n\n return cursor.node.parent\n ? { node: cursor.node.parent, renderKey: cursor.renderKey }\n : undefined;\n}\n\nexport function getEdge(cursor: Cursor, key: string): Cursor | undefined {\n const edge = getSingularEdgeStore(cursor.node, key);\n if (edge) {\n const overridden = lookupEdge(edge, cursor.renderKey);\n if (overridden !== undefined) {\n return overridden ? { node: overridden, renderKey: cursor.renderKey } : undefined;\n }\n }\n\n const canonicalChild = nodeFields(cursor.node)[key] as Node | undefined;\n return canonicalChild ? { node: canonicalChild, renderKey: cursor.renderKey } : undefined;\n}\n\nexport function getEdgeAt(cursor: Cursor, key: string, index: number): Cursor | undefined {\n const edges = getIndexedEdgeStore(cursor.node, key);\n if (edges) {\n const overridden = lookupEdge(edges[index], cursor.renderKey);\n if (overridden !== undefined) {\n return overridden ? { node: overridden, renderKey: cursor.renderKey } : undefined;\n }\n }\n\n const canonicalList = nodeFields(cursor.node)[key] as Node[] | undefined;\n const canonicalChild = canonicalList?.[index];\n return canonicalChild ? { node: canonicalChild, renderKey: cursor.renderKey } : undefined;\n}\n\nexport function addEdge(\n node: Node,\n key: string,\n renderKey: RenderKey,\n child: Node\n): void {\n if (renderKey === CANONICAL) {\n const canonicalChild = nodeFields(node)[key] as Node | undefined;\n if (canonicalChild === child) {\n return;\n }\n throw new Error(`Cannot add a second CANONICAL edge for ${node.type}.${key}`);\n }\n const edge = getSingularEdgeStore(node, key) ?? new Map<RenderKey, Node>();\n edge.set(renderKey, child);\n setSingularEdgeStore(node, key, edge);\n}\n\nexport function addEdgeAt(\n node: Node,\n key: string,\n index: number,\n renderKey: RenderKey,\n child: Node\n): void {\n if (renderKey === CANONICAL) {\n const canonicalList = nodeFields(node)[key] as Node[] | undefined;\n const canonicalChild = canonicalList?.[index];\n if (canonicalChild === child) {\n return;\n }\n throw new Error(`Cannot add a second CANONICAL edge for ${node.type}.${key}[${index}]`);\n }\n const indexedEdges = getIndexedEdgeStore(node, key) ?? [];\n const edge = indexedEdges[index] ?? new Map<RenderKey, Node>();\n edge.set(renderKey, child);\n indexedEdges[index] = edge;\n setIndexedEdgeStore(node, key, indexedEdges);\n}\n\nexport function addParentEdge(\n node: Node,\n renderKey: RenderKey,\n parent: Node\n): void {\n /**\n * Parent edges represent render-placement overrides, not a second canonical parent.\n *\n * Invariants:\n * - `CANONICAL` must continue to live on `node.parent`\n * - non-canonical writes may override the active parent for a render key\n * - special keys such as `CALLER` are allowed here, but they are secondary lanes;\n * they should not be treated as the default upward render path unless a traversal\n * explicitly asks for them\n */\n if (renderKey === CANONICAL) {\n if (node.parent === parent) {\n return;\n }\n throw new Error(`Cannot add a second CANONICAL parent edge for ${node.type}`);\n }\n const edge = node.parentEdges ?? new Map<RenderKey, Node>();\n edge.set(renderKey, parent);\n node.parentEdges = edge;\n}\n\nexport function removeParentEdge(\n node: Node,\n renderKey: RenderKey\n): void {\n const edge = node.parentEdges;\n if (!edge) {\n return;\n }\n edge.delete(renderKey);\n if (edge.size === 0) {\n node.parentEdges = undefined;\n }\n}\n","import { NodeTraversalCursor } from './util/collections.js';\nimport {\n type TreeContext,\n type Context\n} from '../context.js';\nimport { type Visitor } from '../visitor/index.js';\nimport { type Operator } from './util/calculate.js';\nimport type { AbstractClass, Tagged } from 'type-fest';\nimport type { Comment } from './comment.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, pipe, isThenable, serialForEach } from '@jesscss/awaitable-pipe';\nimport type { Rules } from './rules.js';\nimport type { Nil } from './nil.js';\nimport { N, nodeTypeBits } from './node-type.js';\nimport { addParentEdge } from './util/cursor.js';\nexport type { TreeContext };\n\nconst { isArray } = Array;\ntype AllNodeOptions = {\n /**\n * This seems harder to implement. For now, for anything that needs\n * to be flattened, we hoist it to the root.\n */\n // hoistToParent?: boolean\n\n /**\n * For statements with optional semis,\n * we flag this for accurate re-serialization.\n *\n * @todo - Not sure if we actually need this, but it's here\n * if we wanted a concrete syntax tree.\n */\n semi?: boolean;\n};\n\n/**\n * @todo - Clean up and delete these types and symbols, if not used.\n */\nexport type Primitive = undefined | boolean | string | number;\nexport type PrimitiveOrFunc = Primitive | ((...args: any[]) => any);\n\nexport const ABORT: unique symbol = Symbol('ABORT');\nexport const REMOVE: unique symbol = Symbol('REMOVE');\nexport const IS_PROXY: unique symbol = Symbol('IS_PROXY');\nexport type NodeVisitReturn = void | Node | symbol;\nexport type NodeOptions = Record<string, any> & AllNodeOptions;\nexport const DEFAULT_DATA = 'data';\n\ntype BasicNodeTypes = PrimitiveOrFunc | Node;\ntype NodeRecordValue = BasicNodeTypes | Array<BasicNodeTypes | PrimitiveOrFunc[]> | Record<string, any>;\nexport type NodeValueObject = Record<string, NodeRecordValue>;\nexport type NodeValue = BasicNodeTypes | BasicNodeTypes[] | NodeValueObject;\n\nexport type NodeMapArray<\n T extends NodeValueObject = NodeValueObject,\n K = keyof T,\n V = T[string]\n> = Array<[K, V]>;\n\nexport type LocationInfo = [\n startOffset: number,\n startLine: number,\n startColumn: number,\n endOffset: number,\n endLine: number,\n endColumn: number\n];\n\n/**\n * Values returned by {@link Node.location}: a full six-number span, or `[]` when unknown.\n * The empty tuple is the lazy default assigned by the `location` getter.\n */\nexport type LocationInfoOrEmpty = LocationInfo | [];\n\n/**\n * Location argument for node construction and APIs that accept another node's `location`.\n * Same shape as {@link LocationInfoOrEmpty}, or `undefined` to defer to the empty default.\n */\nexport type OptionalLocation = LocationInfoOrEmpty | undefined;\n\nexport type RenderKey = number | symbol;\n\nexport const CANONICAL: unique symbol = Symbol('CANONICAL');\nexport const EVAL: unique symbol = Symbol('EVAL');\nexport const CALLER: unique symbol = Symbol('CALLER');\n\nexport type NodeEdge<T> = Map<RenderKey, T>;\n\nexport type Cursor = {\n node: Node;\n renderKey: RenderKey;\n};\n\nfunction isContextArg(value: Context | RenderKey | undefined): value is Context {\n return typeof value === 'object' && value !== null && 'rulesetFrames' in value;\n}\n\nfunction getActiveParentFromContext(\n node: Node,\n context?: Context\n): Node | undefined {\n if (!context) {\n return node.parent;\n }\n const keys: RenderKey[] = [];\n const push = (key: RenderKey | undefined): void => {\n if (key === undefined || key === CANONICAL || keys.includes(key)) {\n return;\n }\n keys.push(key);\n };\n push(context.renderKey);\n push(context.rulesContext?.renderKey);\n push(node.renderKey);\n if (node.parentEdges?.has(EVAL)) {\n push(EVAL);\n }\n for (const key of keys) {\n const parent = node.parentEdges?.get(key);\n if (parent !== undefined) {\n return parent;\n }\n }\n return node.parent;\n}\n\nfunction hasTypeProperty(value: unknown): value is { type?: string } {\n return (typeof value === 'object' || typeof value === 'function')\n && value !== null\n && 'type' in value;\n}\n\nfunction getNodeChildKeys(node: Node): readonly string[] | null | undefined {\n const childKeys: readonly string[] | null | undefined = Reflect.get(node.constructor, 'childKeys');\n return childKeys;\n}\n\nfunction getNodeField<T = unknown>(node: Node, key: string): T {\n const value: T = Reflect.get(node, key);\n return value;\n}\n\nfunction setNodeField(node: Node, key: string, value: unknown): void {\n Reflect.set(node, key, value);\n}\n\nfunction getNodeEdge<T>(node: Node, key: string): NodeEdge<T> | undefined {\n const edge = Reflect.get(node, key);\n return edge instanceof Map ? edge : undefined;\n}\n\nfunction getNodeEdgeList(node: Node, key: string): Array<NodeEdge<unknown> | undefined> | undefined {\n const edges = Reflect.get(node, key);\n return Array.isArray(edges) ? edges : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction getNodeValue(node: Node): unknown {\n return getNodeField(node, 'value');\n}\n\nexport function canReuseEvalState(node: Node, context?: Context): boolean {\n const renderKey = context?.renderKey;\n if (renderKey === undefined || renderKey === CANONICAL) {\n return true;\n }\n return node.renderKey === renderKey;\n}\n\nfunction setNodeEvaluated(node: Node, context?: Context): void {\n if (!canReuseEvalState(node, context)) {\n return;\n }\n setNodeField(node, 'evaluated', true);\n}\n\nfunction getNodeKeySetLibrary(node: Node): unknown {\n return Reflect.get(node, 'keySetLibrary');\n}\n\nfunction setNodeKeySetLibrary(node: Node, library: unknown): void {\n Reflect.set(node, 'keySetLibrary', library);\n}\n\nfunction isRulesNode(node: Node | undefined): node is Rules {\n return node?.type === 'Rules';\n}\n\nfunction toPrimitiveValue(value: unknown): Primitive {\n return (\n value === undefined\n || typeof value === 'string'\n || typeof value === 'number'\n || typeof value === 'boolean'\n )\n ? value\n : String(value);\n}\n\n/**\n * Utility type to mark a node's value as generated\n */\nexport type GeneratedNodeValue<T> = T extends object ? T & { generated: true } : T;\n\nexport const defineType = <\n V = never,\n T extends AbstractClass<Node> = AbstractClass<Node>,\n P extends ConstructorParameters<T> = ConstructorParameters<T>\n>(\n Clazz: T,\n type: string,\n shortType?: string\n) => {\n shortType ??= type.toLowerCase();\n Reflect.set(Clazz, 'type', type);\n Reflect.set(Clazz, 'shortType', shortType);\n\n /** Build nodeType bitmask by OR-ing bits for each type in the prototype chain */\n let nodeType = 0;\n let proto: unknown = Clazz;\n /**\n * @todo - We shouldn't have to crawl the prototype at runtime.\n * We should be setting this explicitly in a parameter to defineType.\n */\n while (hasTypeProperty(proto) && proto.type) {\n const bit = nodeTypeBits[proto.type];\n if (bit !== undefined) {\n nodeType |= bit;\n }\n proto = Object.getPrototypeOf(proto);\n }\n /** Set on the prototype so ALL instances (including `new Foo()`) inherit it */\n Clazz.prototype.nodeType = nodeType;\n Clazz.prototype.type = type;\n Clazz.prototype.shortType = shortType;\n\n type Args = [value?: P[0] | V, options?: P[1], location?: P[2]];\n return (...args: Args) => {\n const node: InstanceType<T> = Reflect.construct(Clazz, args);\n return node;\n };\n};\n\nexport type ConditionOperator = 'and' | 'or' | '=' | '>' | '<' | '>=' | '<=';\n\nexport type NoOverride<T> = Tagged<T, 'NoOverride'>;\n\n// Node state flags as bitmask\nexport const F_VISIBLE = 0b1;\nexport const F_MAY_ASYNC = 0b10;\n/**\n * @todo - The plan is to use these as signals for evaluation. If we\n * bubble these correctly, then we can exit early from evaluation for\n * a speed boost. However, bubbling is not yet water-tight and needs\n * test coverage.\n */\nexport const F_STATIC = 0b100;\nexport const F_NON_STATIC = 0b1000;\n/** Whether or not a physical ampersand is in this selector */\nexport const F_AMPERSAND = 0b10000;\n/** Whether an ampersand was implicitly added (not written by user) */\nexport const F_IMPLICIT_AMPERSAND = 0b100000;\n/** Selector item produced by extend and eligible for reference-mode rendering. */\nexport const F_EXTENDED = 0b1000000;\n/** Selector item that matches an extend target and should be suppressed in reference-mode output. */\nexport const F_EXTEND_TARGET = 0b10000000;\n\n// Default state: only visible is true\nexport const F_DEFAULT = F_VISIBLE;\n\nexport function isVisibleInContext(node: Node, context?: Context): boolean {\n return context ? node._hasFlag(F_VISIBLE, context) : node.hasFlag(F_VISIBLE);\n}\n\n/** Secondary metadata flags. Keeps a pile of booleans off the instance shape. */\nconst M_ALLOW_ROOT = 1 << 0;\nconst M_ALLOW_RULE_ROOT = 1 << 1;\nconst M_GENERATED = 1 << 2;\nconst M_REQUIRED_SEMI = 1 << 3;\nconst M_FROZEN = 1 << 4;\n\n// Future flags can be added here\n// export const CACHED = 0b1000000;\n// export const DIRTY = 0b10000000;\n// export const LOCKED = 0b100000000;\n\n// const FULLY_EVALUATED = F_EVALUATED | F_PRE_EVALUATED;\n\nexport type RestorableIterator<T> = Iterator<T> & {\n mark: (key?: string) => void;\n reset: (key?: string) => void;\n};\n\ntype NodeMeta<O extends NodeOptions = NodeOptions> = {\n treeContext?: TreeContext;\n options?: O & AllNodeOptions;\n sourceNode?: Node;\n sourceParent?: Node;\n hoistToRoot?: boolean;\n};\n\n/**\n * The underlying type for all Jess nodes\n */\nexport abstract class Node<\n Data = NodeValue,\n O extends NodeOptions = NodeOptions,\n ChildData extends Record<string, unknown> = Record<string, unknown>\n> {\n _location: OptionalLocation;\n get location(): LocationInfoOrEmpty {\n return (this._location ??= []);\n }\n\n private _meta: NodeMeta<O> | undefined;\n private _metaFlags = 0;\n\n private _getMeta(): NodeMeta<O> {\n return (this._meta ??= {});\n }\n\n /** Assigned in index to avoid circularity */\n get treeContext() {\n return this._meta?.treeContext;\n }\n\n get options(): O & AllNodeOptions {\n const meta = this._getMeta();\n if (meta.options === undefined) {\n meta.options = Reflect.construct(Object, []);\n }\n return meta.options;\n }\n\n set options(options: O & AllNodeOptions) {\n this._getMeta().options = options;\n }\n\n /**\n * Assigned on the prototype by defineType — do NOT initialize in subclasses\n * (an `= 'X'` would create an own property that shadows the prototype value).\n * Use interface merging to declare the literal type per node class.\n */\n declare type: string;\n declare shortType: string;\n\n /**\n * Bitmask of this node's type and all ancestor types.\n * Set on the prototype by defineType. Used by isNode for O(1) type checking.\n * DO NOT initialize here — an `= 0` would create an own property that\n * shadows the prototype value set by defineType.\n */\n declare nodeType: number;\n\n /**\n * Whitespace or comments before or after a Node.\n *\n * If this is `1`, it represents a single space character (' ').\n * If it's 0, it means there were no pre/post tokens when parsed.\n * If undefined, it means this was created using the API, and default\n * formatting can be used.\n * In a NodeList, any whitespace tokens outside of comments are individually represented,\n * because they are preserved while the comment may not be.\n */\n /** Nil type is resolved at runtime via prototype patching */\n pre: Array<Comment | Node | string> | 1 | 0 | undefined;\n post: Array<Comment | Node | string> | 1 | 0 | undefined;\n\n /** Will be copied during inherit */\n state = F_DEFAULT;\n\n preEvaluated = false;\n evaluated = false;\n declare stateEdges: Map<RenderKey, number> | undefined;\n\n get visible() {\n return this.hasFlag(F_VISIBLE);\n }\n\n declare fullRender: boolean;\n\n get allowRoot() {\n return (this._metaFlags & M_ALLOW_ROOT) !== 0;\n }\n\n set allowRoot(value: boolean) {\n this._metaFlags = value ? (this._metaFlags | M_ALLOW_ROOT) : (this._metaFlags & ~M_ALLOW_ROOT);\n }\n\n get allowRuleRoot() {\n return (this._metaFlags & M_ALLOW_RULE_ROOT) !== 0;\n }\n\n set allowRuleRoot(value: boolean) {\n this._metaFlags = value ? (this._metaFlags | M_ALLOW_RULE_ROOT) : (this._metaFlags & ~M_ALLOW_RULE_ROOT);\n }\n\n get hoistToRoot() {\n return this._meta?.hoistToRoot;\n }\n\n set hoistToRoot(value: boolean | undefined) {\n if (value === undefined) {\n if (this._meta) {\n this._meta.hoistToRoot = undefined;\n }\n return;\n }\n this._getMeta().hoistToRoot = value;\n }\n\n /**\n * Code internally should call .create() when making new\n * nodes, which will automatically mark the node as generated.\n */\n get generated() {\n return (this._metaFlags & M_GENERATED) !== 0;\n }\n\n set generated(value: boolean) {\n this._metaFlags = value ? (this._metaFlags | M_GENERATED) : (this._metaFlags & ~M_GENERATED);\n }\n\n /**\n * If the node must have a semi separator before\n * the next node when in a declaration list or main\n * rules list.\n */\n get requiredSemi() {\n return (this._metaFlags & M_REQUIRED_SEMI) !== 0;\n }\n\n set requiredSemi(value: boolean) {\n this._metaFlags = value ? (this._metaFlags | M_REQUIRED_SEMI) : (this._metaFlags & ~M_REQUIRED_SEMI);\n }\n\n /**\n * Track the original source when cloned / copied,\n * rather than keeping the entire tree\n */\n get sourceNode() {\n return this._meta?.sourceNode ?? this;\n }\n\n set sourceNode(node: Node) {\n this._getMeta().sourceNode = node;\n }\n\n /**\n * When evaluating, nodes are assigned an index and depth by the Rules node.\n * This is used for lookup order. Note, this _will_ be undefined\n * initially, but we assign it in the Rules node, which is also\n * where we read it, so this makes the type easier.\n */\n index!: number;\n\n /** @todo - Is there a reliable way to cache this? */\n get depth() {\n let node = this.rulesParent;\n let depth = 0;\n while (node) {\n depth++;\n node = node.rulesParent;\n }\n return depth;\n }\n\n /**\n * If true, prevents re-parenting of this node.\n * This is used to maintain source lookup chains.\n */\n get frozen() {\n return (this._metaFlags & M_FROZEN) !== 0;\n }\n\n set frozen(value: boolean) {\n this._metaFlags = value ? (this._metaFlags | M_FROZEN) : (this._metaFlags & ~M_FROZEN);\n }\n\n /**\n * The parent node of this node. Usually, this\n * shouldn't be set directly. Instead, a parent should use\n * parent.adopt(thisNode);\n */\n declare readonly parent: Node | undefined;\n declare parentEdges: NodeEdge<Node> | undefined;\n declare renderKey: RenderKey;\n\n get sourceParent() {\n return this._meta?.sourceParent;\n }\n\n set sourceParent(node: Node | undefined) {\n this._getMeta().sourceParent = node;\n }\n\n /** Patched at runtime in node.ts to return Nil instance */\n declare nil: () => Nil;\n\n /**\n * Keys of instance fields that hold child Nodes.\n * Override per node type.\n * - `undefined` (default) — unmigrated\n * - `null` — leaf node, no children to iterate/adopt/clone\n * - `string[]` — names of instance fields holding child Node(s) or Node[]\n */\n static childKeys: readonly string[] | null | undefined = undefined;\n\n /**\n * The internal data of the node.\n * Prefer setData() for mutations to ensure proper parent adoption.\n */\n // Note to LLM - STOP removing Readonly to try to fix type errors. Make\n // this a strong readonly contract. Otherwise we will miss type errors\n // for things like code mutating arrays that are assigned to data.\n // Uses `declare` to avoid emitting a class field initializer that would\n // shadow prototype getters on migrated subclasses.\n\n private _adoptValue(value: unknown): void {\n if (value instanceof Node) {\n this.adopt(value);\n return;\n }\n if (isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const item = value[i];\n if (item instanceof Node) {\n this.adopt(item);\n }\n }\n }\n }\n\n protected _invalidateValueOf(): void {\n if (Reflect.has(this, '_valueOf')) {\n Reflect.set(this, '_valueOf', undefined);\n }\n if (Reflect.has(this, '_keySet')) {\n Reflect.set(this, '_keySet', undefined);\n Reflect.set(this, '_visibleKeySet', undefined);\n Reflect.set(this, '_requiredKeySet', undefined);\n }\n }\n\n /**\n * Set the whole child payload, a named child field, or an indexed child item.\n * This is a canonical mutation compatibility seam; non-canonical mutation\n * should happen through derived nodes and keyed edges.\n */\n setData(val: NodeValue): void;\n setData(key: string | number, val: unknown): void;\n setData(...args: unknown[]): void {\n const childKeys = getNodeChildKeys(this);\n\n if (args.length === 1) {\n const val = args[0];\n if (Array.isArray(childKeys) && childKeys.length === 1) {\n setNodeField(this, childKeys[0]!, val);\n } else if (Array.isArray(childKeys) && val !== null && typeof val === 'object') {\n for (const key of childKeys) {\n if (Reflect.has(val, key)) {\n setNodeField(this, key, Reflect.get(val, key));\n }\n }\n } else {\n setNodeField(this, 'value', val);\n }\n this._adoptValue(val);\n this._invalidateValueOf();\n return;\n }\n\n const key = args[0];\n if (typeof key !== 'string' && typeof key !== 'number') {\n throw new TypeError('setData key must be a string or number');\n }\n const val = args[1];\n if (typeof key === 'number') {\n const arr = this._getArrayField();\n if (arr[key] === val) {\n return;\n }\n arr[key] = val;\n } else {\n const fields = this;\n if (fields[key] === val) {\n return;\n }\n fields[key] = val;\n }\n this._adoptValue(val);\n this._invalidateValueOf();\n }\n\n private _getArrayField(): unknown[] {\n const childKeys = getNodeChildKeys(this);\n if (!Array.isArray(childKeys) || childKeys.length === 0) {\n throw new Error(`${this.type} has no array child field`);\n }\n const key = childKeys[0]!;\n const value = getNodeField(this, key);\n if (!isArray(value)) {\n throw new Error(`${this.type}.${key} is not an array child field`);\n }\n return value;\n }\n\n push(ctx: Context, ...items: Node[]): void;\n push(...items: Node[]): void;\n push(ctxOrFirst: Context | Node, ...rest: Node[]): void {\n let ctx: Context | undefined;\n let items: Node[];\n if (ctxOrFirst instanceof Node) {\n items = [ctxOrFirst, ...rest];\n } else {\n ctx = ctxOrFirst;\n items = rest;\n }\n const arr = this._getArrayField();\n arr.push(...items);\n for (const item of items) {\n if (item instanceof Node) {\n this.adopt(item, ctx);\n }\n }\n this._invalidateValueOf();\n }\n\n splice(start: number, deleteCount: number, ...items: unknown[]): unknown[] {\n const arr = this._getArrayField();\n const removed = arr.splice(start, deleteCount, ...items);\n for (const item of items) {\n if (item instanceof Node) {\n this.adopt(item);\n }\n }\n this._invalidateValueOf();\n return removed;\n }\n\n unshift(...items: unknown[]): void {\n const arr = this._getArrayField();\n arr.unshift(...items);\n for (const item of items) {\n if (item instanceof Node) {\n this.adopt(item);\n }\n }\n this._invalidateValueOf();\n }\n\n /**\n * Add a flag to the node's state\n * Handles STATIC/NON_STATIC exclusivity automatically\n */\n addFlag(flag: number) {\n // NON_STATIC takes precedence over STATIC\n if (flag === F_STATIC && this.hasFlag(F_NON_STATIC)) {\n return;\n }\n this.state |= flag;\n // Handle STATIC/NON_STATIC exclusivity\n if (flag === F_NON_STATIC) {\n this.state &= ~F_STATIC;\n }\n }\n\n /**\n * Remove a flag from the node's state\n */\n removeFlag(flag: number) {\n this.state &= ~flag;\n }\n\n /**\n * Check if the node has a specific flag\n */\n hasFlag(flag: number): boolean {\n return (this.state & flag) !== 0;\n }\n\n /**\n * Add multiple flags to the node's state\n */\n addFlags(...flags: number[]) {\n for (let i = 0; i < flags.length; i++) {\n this.addFlag(flags[i]!);\n }\n }\n\n private _resolveRuntimeRenderKey(context: Context): RenderKey {\n if (context.renderKey !== undefined) {\n return context.renderKey;\n }\n if (this.renderKey !== CANONICAL) {\n return this.renderKey;\n }\n if (this.stateEdges?.has(EVAL)) {\n return EVAL;\n }\n return this.renderKey;\n }\n\n _hasFlag(flag: number, context: Context): boolean {\n const renderKey = this._resolveRuntimeRenderKey(context);\n if (renderKey === this.renderKey) {\n return this.hasFlag(flag);\n }\n const flags = this.stateEdges?.get(renderKey) ?? this.state;\n return (flags & flag) !== 0;\n }\n\n _addFlag(flag: number, context: Context): void {\n const renderKey = this._resolveRuntimeRenderKey(context);\n if (renderKey === this.renderKey) {\n this.addFlag(flag);\n return;\n }\n const stateEdges = (this.stateEdges ??= new Map());\n let nextFlags = (stateEdges.get(renderKey) ?? this.state) | flag;\n if (flag === F_NON_STATIC) {\n nextFlags &= ~F_STATIC;\n }\n stateEdges.set(renderKey, nextFlags);\n }\n\n _removeFlag(flag: number, context: Context): void {\n const renderKey = this._resolveRuntimeRenderKey(context);\n if (renderKey === this.renderKey) {\n this.removeFlag(flag);\n return;\n }\n const stateEdges = (this.stateEdges ??= new Map());\n stateEdges.set(renderKey, (stateEdges.get(renderKey) ?? this.state) & ~flag);\n }\n\n adopt(node: Node, ctx?: Context) {\n if (!node.frozen) {\n const renderKey = ctx?.renderKey;\n if (renderKey !== undefined && renderKey !== CANONICAL) {\n const edge = node.parentEdges ?? new Map<RenderKey, Node>();\n edge.set(renderKey, this);\n node.parentEdges = edge;\n } else {\n setNodeField(node, 'parent', this);\n }\n }\n if (node.hasFlag(F_NON_STATIC)) {\n this.addFlag(F_NON_STATIC);\n this.removeFlag(F_STATIC);\n } else if (node.hasFlag(F_STATIC)) {\n this.addFlag(F_STATIC);\n }\n if (node.hasFlag(F_MAY_ASYNC)) {\n this.addFlag(F_MAY_ASYNC);\n }\n if (node.hasFlag(F_AMPERSAND) && this.type !== 'Rules') {\n this.addFlag(F_AMPERSAND);\n }\n }\n\n constructor(\n value: Data,\n options?: O,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n setNodeField(this, 'parent', undefined);\n setNodeField(this, 'renderKey', CANONICAL);\n this.index = undefined!;\n this._location = location;\n if (options !== undefined || treeContext !== undefined) {\n this._meta = {\n sourceNode: this,\n sourceParent: undefined,\n options,\n treeContext\n };\n } else {\n this._meta = {\n sourceNode: this,\n sourceParent: undefined\n };\n }\n }\n\n /**\n * Type-safe access to child data fields.\n * Without a second arg: returns canonical (parse-time) value.\n * With a renderKey: returns edge-selected value if one exists.\n * With a context: returns edge-selected value first, then any eval-state-patched value.\n *\n * @example\n * url.get('value') // canonical, typed\n * url.get('value', renderKey) // render-path aware, typed\n * url.get('value', ctx) // render + eval-state aware, typed\n * url.get('name') // TS error if 'name' not in ChildData\n */\n get<K extends keyof ChildData & string>(key: K): ChildData[K];\n get<K extends keyof ChildData & string>(key: K, renderKey: RenderKey | undefined): ChildData[K];\n get<K extends keyof ChildData & string>(key: K, ctx: Context | undefined): ChildData[K];\n get<K extends keyof ChildData & string>(key: K, ctxOrRenderKey?: Context | RenderKey | undefined): ChildData[K] {\n const ctx = isContextArg(ctxOrRenderKey) ? ctxOrRenderKey : undefined;\n const explicitRenderKey = !isContextArg(ctxOrRenderKey)\n ? ctxOrRenderKey\n : undefined;\n const renderKeys: RenderKey[] = [];\n const pushRenderKey = (renderKey: RenderKey | undefined) => {\n if (renderKey === undefined || renderKey === CANONICAL || renderKeys.includes(renderKey)) {\n return;\n }\n renderKeys.push(renderKey);\n };\n pushRenderKey(explicitRenderKey);\n pushRenderKey(ctx?.renderKey);\n pushRenderKey(ctx?.rulesContext?.renderKey);\n pushRenderKey(this.renderKey !== CANONICAL ? this.renderKey : undefined);\n const singularEdge = getNodeEdge<ChildData[K]>(this, `${key}Edge`);\n const canonicalValue = getNodeField(this, key);\n if (\n ctx\n && (singularEdge?.has(EVAL) || getNodeEdgeList(this, `${key}Edges`)?.some(edge => edge?.has(EVAL))\n )) {\n pushRenderKey(EVAL);\n }\n\n for (const renderKey of renderKeys) {\n const overridden = singularEdge?.get(renderKey);\n if (overridden !== undefined) {\n return overridden;\n }\n if (isArray(canonicalValue)) {\n const indexedEdges = getNodeEdgeList(this, `${key}Edges`);\n if (indexedEdges) {\n let resolved: ChildData[K] | undefined;\n for (let i = 0; i < canonicalValue.length; i++) {\n const item = indexedEdges[i]?.get(renderKey);\n if (item !== undefined) {\n if (!resolved) {\n const nextResolved: ChildData[K] = [...canonicalValue];\n resolved = nextResolved;\n }\n resolved[i] = item;\n }\n }\n if (resolved) {\n return resolved;\n }\n }\n }\n }\n\n return getNodeField<ChildData[K]>(this, key);\n }\n\n /**\n * Static factory method to create a generated node.\n * Has the exact same signature as the constructor but automatically marks the node as generated.\n *\n * @param value - The node's value data\n * @param options - Node options\n * @param location - Location information\n * @param treeContext - Tree context\n * @returns A new node instance with generated flag set if applicable\n */\n static create<T extends new (...args: any[]) => Node>(\n this: T,\n value: ConstructorParameters<T>[0],\n options?: ConstructorParameters<T>[1],\n location?: ConstructorParameters<T>[2],\n treeContext?: ConstructorParameters<T>[3]\n ): InstanceType<T> {\n // Create the instance with the same signature as constructor\n const instance: InstanceType<T> = Reflect.construct(this, [value, options, location, treeContext]);\n\n // Mark as generated if the value is an object that can be marked\n if (instance instanceof Node) {\n instance.generated = true;\n }\n\n return instance;\n }\n\n get rulesParent(): Rules | undefined {\n let possibleRules: Node | undefined = this.parent;\n while (possibleRules && possibleRules.type !== 'Rules') {\n possibleRules = possibleRules.parent;\n }\n return isRulesNode(possibleRules) ? possibleRules : undefined;\n }\n\n get sourceRulesParent(): Rules | undefined {\n let node = this.parent;\n let sourceParent = this.sourceParent;\n while (node && !sourceParent) {\n node = node.parent;\n sourceParent = node?.sourceParent;\n }\n return sourceParent?.rulesParent;\n }\n\n /**\n * Mutates node children in place. Used by eval()?\n *\n * Processed nodes must always return a Node.\n */\n forEachNode(func: (n: Node, idx?: number) => MaybePromise<Node>, context?: Context) {\n if (!this.hasFlag(F_MAY_ASYNC)) {\n return this._forEachNodeSync(func, context);\n }\n const entries = this._collectChildEntries();\n return serialForEach(entries, ([value, key, collection]: [unknown, string | number, any], idx: number) => {\n if (!(value instanceof Node)) {\n return;\n }\n const out = func(value, idx);\n if (isThenable(out)) {\n return (out as Promise<Node>).then((result) => {\n if (result !== value) {\n collection[key] = result;\n if (result instanceof Node) {\n this.adopt(result);\n }\n this._invalidateValueOf();\n }\n });\n }\n if (out !== value) {\n collection[key] = out as Node;\n this.adopt(out as Node);\n this._invalidateValueOf();\n }\n });\n }\n\n private _collectChildEntries(): [unknown, string | number, any][] {\n const ck = getNodeChildKeys(this);\n if (!ck) {\n return [];\n }\n const entries: [unknown, string | number, any][] = [];\n for (const key of ck) {\n const field = getNodeField(this, key);\n if (isArray(field)) {\n for (let i = 0; i < field.length; i++) {\n entries.push([field[i], i, field]);\n }\n } else {\n entries.push([field, key!, this]);\n }\n }\n return entries;\n }\n\n private _forEachNodeSync(func: (n: Node, idx?: number) => Node, _context?: Context) {\n const ck = getNodeChildKeys(this);\n\n if (Array.isArray(ck)) {\n let idx = 0;\n for (const key of ck) {\n const field = getNodeField(this, key);\n if (isArray(field)) {\n for (let i = 0; i < field.length; i++) {\n const item = field[i];\n if (!(item instanceof Node)) {\n continue;\n }\n const result = func(item, idx++);\n if (result !== item) {\n field[i] = result;\n this.adopt(result);\n this._invalidateValueOf();\n }\n }\n } else if (field instanceof Node) {\n const result = func(field, idx++);\n if (result !== field) {\n setNodeField(this, key, result);\n this.adopt(result);\n this._invalidateValueOf();\n }\n }\n }\n }\n }\n\n * nodeAndPrePost(): IterableIterator<Node> {\n const node = this;\n if (isArray(node.pre)) {\n for (let i = 0; i < node.pre.length; i++) {\n const n = node.pre[i];\n if (n instanceof Node) {\n yield n;\n }\n }\n }\n yield node;\n if (isArray(node.post)) {\n for (let i = 0; i < node.post.length; i++) {\n const n = node.post[i];\n if (n instanceof Node) {\n yield n;\n }\n }\n }\n }\n\n /**\n * Return an iterator for all nodes / children nodes, including this one\n */\n nodes(\n reverse?: boolean,\n includePrePost?: boolean\n ): NodeTraversalCursor {\n return new NodeTraversalCursor(this, {\n includeSelf: true,\n deep: true,\n reverse,\n includePrePost\n });\n }\n\n /**\n * An iterator for all node children\n */\n children(\n deep?: boolean,\n reverse?: boolean,\n includePrePost?: boolean\n ): NodeTraversalCursor {\n return new NodeTraversalCursor(this, {\n includeSelf: false,\n deep,\n reverse,\n includePrePost\n });\n }\n\n /**\n * Accept a visitor (classic visitor pattern).\n *\n * Visits the node itself first, then recursively visits children.\n * This matches the Less.js visitor pattern and allows nodes to control\n * their own traversal if needed by overriding this method.\n *\n * @param visitor - The visitor to accept\n * @returns The result from visiting this node (may be a replacement node)\n */\n accept(visitor: Visitor): Node {\n // Visit self first (like Less.js pattern).\n // Support both Visitor class instances (visit()) and plain visitor objects.\n let result: Node | NodeVisitReturn = this;\n const treeVisitMethod = Reflect.get(visitor, '_visit');\n const hasTreeVisitorState = Reflect.get(visitor, 'visitedNodes') instanceof Set;\n const visitMethod = Reflect.get(visitor, 'visit');\n if (typeof treeVisitMethod === 'function' && hasTreeVisitorState) {\n const visited: NodeVisitReturn = treeVisitMethod.call(visitor, this, {});\n result = visited;\n } else if (typeof visitMethod === 'function') {\n const visited: Node = visitMethod.call(visitor, this);\n result = visited;\n } else {\n const maybeAbort = visitor.enter?.(this);\n if (maybeAbort === ABORT) {\n return this;\n }\n const methodName = this.type.charAt(0).toLowerCase() + this.type.slice(1);\n const typeMethod = Reflect.get(visitor, methodName);\n if (typeof typeMethod === 'function') {\n const visited: NodeVisitReturn = typeMethod.call(visitor, this);\n if (visited) {\n result = visited;\n }\n }\n result = visitor.exit?.(result) ?? result;\n }\n\n // Visit children recursively (Less.js pattern)\n // Note: If TreeVisitor is using accept(), it will skip auto-visiting children\n // to avoid double-visiting. See TreeVisitor._visit() implementation.\n for (const child of this.children()) {\n if (child.accept) {\n child.accept(visitor);\n } else {\n // Fallback: if child doesn't have accept, visit directly\n visitor.visit(child);\n }\n }\n\n // Return the result (may be a replacement node)\n return result instanceof Node ? result : this;\n }\n\n clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const ck = getNodeChildKeys(this);\n\n // Leaf node — no children to iterate or deep-clone\n if (ck === null) {\n const options = this._meta?.options;\n const newNode: this = Reflect.construct(this.constructor, [getNodeValue(this), options ? { ...options } : undefined, this.location, this.treeContext]);\n newNode.inherit(this);\n return newNode;\n }\n\n // Container — build constructor value from childKeys\n let cloneData: unknown;\n let cloneRecord: Record<string, unknown> | undefined;\n if (ck!.length === 1) {\n const field = getNodeField(this, ck![0]!);\n cloneData = isArray(field) ? [...field] : field;\n } else {\n cloneRecord = {};\n cloneData = cloneRecord;\n for (const key of ck!) {\n const field = getNodeField(this, key);\n cloneRecord[key] = isArray(field) ? [...field] : field;\n }\n }\n\n if (deep) {\n cloneFn ??= n => n.clone(deep);\n if (ck!.length === 1) {\n if (isArray(cloneData)) {\n for (let i = 0; i < cloneData.length; i++) {\n if (cloneData[i] instanceof Node) {\n cloneData[i] = cloneFn(cloneData[i]);\n }\n }\n } else if (cloneData instanceof Node) {\n cloneData = cloneFn(cloneData);\n }\n } else {\n const cloneObject = cloneRecord;\n for (const key of ck!) {\n const val = cloneObject?.[key];\n if (isArray(val)) {\n for (let i = 0; i < val.length; i++) {\n if (val[i] instanceof Node) {\n val[i] = cloneFn(val[i]);\n }\n }\n } else if (val instanceof Node) {\n if (cloneObject) {\n cloneObject[key] = cloneFn(val);\n }\n }\n }\n }\n }\n\n // When eval state is active and this is a shallow clone, the constructor will call\n // adopt() for all child nodes without ctx, which directly mutates their parent fields.\n // Save the pre-construction parent values so we can restore them after, routing the\n // new parent assignment through the eval state instead.\n let priorChildParents: [Node, Node | undefined][] | undefined;\n if (!deep && ctx) {\n priorChildParents = [];\n if (isArray(cloneData)) {\n for (const item of cloneData) {\n if (item instanceof Node) {\n priorChildParents.push([item, item.parent]);\n }\n }\n } else if (cloneData instanceof Node) {\n priorChildParents.push([cloneData, cloneData.parent]);\n } else if (isRecord(cloneData)) {\n for (const key of ck!) {\n const field = cloneData[key];\n if (field instanceof Node) {\n priorChildParents.push([field, field.parent]);\n } else if (isArray(field)) {\n for (const item of field) {\n if (item instanceof Node) {\n priorChildParents.push([item, item.parent]);\n }\n }\n }\n }\n }\n }\n\n const options = this._meta?.options;\n const newNode: this = Reflect.construct(this.constructor, [cloneData, options ? { ...options } : undefined, this.location, this.treeContext]);\n\n // Reconnect shallow-cloned children on the active render path without\n // mutating canonical parent pointers.\n if (priorChildParents) {\n const renderKey = ctx!.renderKey ?? this.renderKey;\n for (const [child, priorParent] of priorChildParents) {\n if (renderKey !== undefined) {\n addParentEdge(child, renderKey, newNode);\n }\n setNodeField(child, 'parent', priorParent);\n }\n }\n\n newNode.inherit(this);\n Node._inheritDerivedParent(this, newNode, ctx);\n return newNode;\n }\n\n /** Remove comments from pre/post */\n stripPrePost(n: Node, preOrPost: 'pre' | 'post') {\n const prePost = n[preOrPost];\n if (isArray(prePost)) {\n n[preOrPost] = [...prePost];\n for (let [key, node] of prePost.entries()) {\n if (node instanceof Node && node.type === 'Comment') {\n /** Replace comment with a nil node that inherits location */\n const nilNode = this.nil?.() || this._createMinimalNil();\n prePost[key] = nilNode.inherit(node);\n }\n }\n }\n }\n\n /** Minimal nil fallback for edge cases where prototype method isn't attached yet */\n private _createMinimalNil(): Node {\n // @ts-expect-error - normally an abstract class\n const nilish = new Node();\n nilish.type = 'Nil';\n nilish.shortType = 'nil';\n nilish.nodeType = nodeTypeBits['Nil']!;\n nilish.removeFlag(F_VISIBLE);\n return nilish;\n }\n\n /**\n * Same as clone except comments are stripped.\n * This is used for variable referencing and\n * selector extending.\n */\n copy(deep?: boolean, cloneFn?: (n: Node) => Node): this {\n const newNode = this.clone(\n deep,\n (n) => {\n if (n.type !== 'Comment') {\n const copy = n.copy(deep, cloneFn);\n return copy;\n }\n const nilNode = this.nil?.() || this._createMinimalNil();\n return nilNode.inherit(n);\n }\n );\n if (this.hasFlag(F_AMPERSAND)) {\n newNode.addFlag(F_AMPERSAND);\n }\n if (this.hasFlag(F_IMPLICIT_AMPERSAND)) {\n newNode.addFlag(F_IMPLICIT_AMPERSAND);\n }\n // Strip comments from pre/post, preserving whitespace\n newNode.stripPrePost(newNode, 'pre');\n newNode.stripPrePost(newNode, 'post');\n return newNode;\n }\n\n /**\n * `preEval` takes the following steps, which are extended in subclasses:\n * 1. Clone the node (if the source node is wanted/needed)\n * 2. Set `preEvaluated` to true\n * 3. pre-evaluate all children\n * 4. Return the node\n *\n * Mostly this is overridden to resolve names before registering.\n *\n * @todo - Update preEval / eval to use static evaluation based on flags.\n */\n preEval(context: Context): MaybePromise<Node> {\n if (!this.preEvaluated) {\n let node = this.clone();\n node.preEvaluated = true;\n\n // Note: Rules nodes handle index assignment for themselves and their children\n // Other nodes will get indices assigned by their parent Rules\n let out: MaybePromise<void>;\n try {\n out = node.forEachNode(n => n.preEval(context), context);\n } catch (error: unknown) {\n throw error;\n }\n if (isThenable(out)) {\n return Promise.resolve(out).then(() => node).catch((error: unknown) => {\n throw error;\n });\n }\n return node;\n }\n return this;\n }\n\n /**\n * This is the method all nodes will override.\n * Individual nodes will specify / narrow return type\n *\n * By default, evals all children\n */\n protected evalNode(context: Context): MaybePromise<Node> {\n if (this.hasFlag(F_STATIC)) {\n return this;\n }\n let out = this.forEachNode((n: Node) => {\n return n.eval(context);\n }, context);\n if (isThenable(out)) {\n return Promise.resolve(out).then(() => {\n return this;\n });\n }\n return this;\n }\n\n static evalStatic(node: Node, context: Context): MaybePromise<Node> {\n const reusableState = canReuseEvalState(node, context);\n if (node.hasFlag(F_STATIC) && node.evaluated && reusableState) {\n return node;\n }\n\n if (!node.hasFlag(F_MAY_ASYNC)) {\n return Node._evalStaticSync(node, context);\n }\n\n let preEvaluatedNode: Node;\n\n return pipe(\n () => {\n if (!node.preEvaluated || !reusableState) {\n return node.preEval(context);\n }\n return node;\n },\n (preEvald) => {\n preEvaluatedNode = preEvald;\n if (canReuseEvalState(preEvaluatedNode, context)) {\n preEvaluatedNode.preEvaluated = true;\n }\n if (preEvald !== node) {\n Node._inheritDerivedRenderKey(node, preEvaluatedNode, context);\n preEvaluatedNode.inherit(node);\n Node._inheritDerivedParent(node, preEvaluatedNode, context);\n }\n if (!preEvaluatedNode.evaluated || !canReuseEvalState(preEvaluatedNode, context)) {\n return preEvaluatedNode.evalNode(context);\n }\n return preEvaluatedNode;\n },\n (evald) => {\n setNodeEvaluated(evald, context);\n if (preEvaluatedNode !== evald && typeof evald.inherit === 'function') {\n Node._inheritDerivedRenderKey(preEvaluatedNode, evald, context);\n if (Node._shouldInheritEvalResult(preEvaluatedNode, evald)) {\n evald.inherit(preEvaluatedNode);\n Node._inheritDerivedParent(preEvaluatedNode, evald, context);\n }\n }\n return evald;\n }\n );\n }\n\n private static _evalStaticSync(node: Node, context: Context): Node {\n let preEvaluatedNode: Node;\n const reusableState = canReuseEvalState(node, context);\n\n if (!node.preEvaluated || !reusableState) {\n preEvaluatedNode = node.preEval(context);\n } else {\n preEvaluatedNode = node;\n }\n if (canReuseEvalState(preEvaluatedNode, context)) {\n preEvaluatedNode.preEvaluated = true;\n }\n if (preEvaluatedNode !== node) {\n Node._inheritDerivedRenderKey(node, preEvaluatedNode, context);\n preEvaluatedNode.inherit(node);\n Node._inheritDerivedParent(node, preEvaluatedNode, context);\n }\n\n let evald: Node;\n if (!preEvaluatedNode.evaluated || !canReuseEvalState(preEvaluatedNode, context)) {\n evald = preEvaluatedNode.evalNode(context);\n } else {\n evald = preEvaluatedNode;\n }\n setNodeEvaluated(evald, context);\n if (preEvaluatedNode !== evald && typeof evald.inherit === 'function') {\n Node._inheritDerivedRenderKey(preEvaluatedNode, evald, context);\n if (Node._shouldInheritEvalResult(preEvaluatedNode, evald)) {\n evald.inherit(preEvaluatedNode);\n Node._inheritDerivedParent(preEvaluatedNode, evald, context);\n }\n }\n return evald;\n }\n\n private static _shouldInheritEvalResult(source: Node, result: Node): boolean {\n if (source.type !== 'Reference') {\n return true;\n }\n return (result.nodeType & (N.Mixin | N.Ruleset | N.Rules | N.Func | N.JsFunction)) === 0;\n }\n\n private static _inheritDerivedRenderKey(source: Node, derived: Node, context?: Context): void {\n if (source === derived || derived.renderKey !== CANONICAL) {\n return;\n }\n derived.renderKey = source.renderKey === CANONICAL\n ? (context?.renderKey ?? EVAL)\n : source.renderKey;\n }\n\n private static _inheritDerivedParent(source: Node, derived: Node, context?: Context): void {\n if (source === derived) {\n return;\n }\n setNodeField(derived, 'parent', getActiveParentFromContext(source, context));\n }\n\n /**\n * @note - Make sure you don't call super.eval while evaluating a node. Call it indirectly\n * from another node.\n */\n eval(context: Context): MaybePromise<Node> {\n if (Object.getPrototypeOf(this).eval !== Node.prototype.eval) {\n throw new Error('Do not call super.eval() from a subclass.');\n }\n return Node.evalStatic(this, context);\n }\n\n /**\n * This is used when a Node will replace another node.\n */\n inherit(node: Node) {\n /**\n * Frozen nodes inherit the parent only if they don't have a parent yet.\n */\n if (!this.frozen) {\n setNodeField(this, 'parent', node.parent);\n } else {\n if (this.parent === undefined) {\n setNodeField(this, 'parent', node.parent);\n }\n }\n this._location = node.location;\n if (this._meta?.treeContext === undefined) {\n this._getMeta().treeContext = node.treeContext;\n }\n /** Copy state exactly (not OR, to preserve removed flags) */\n // Only sync F_VISIBLE flag, preserve all other flags\n if (!node.hasFlag(F_VISIBLE)) {\n this.removeFlag(F_VISIBLE);\n }\n // Preserve F_IMPLICIT_AMPERSAND so cloned selectors (e.g. after extend) keep invisible-ampersand\n // handling in createProcessedSelector and valueOf() remains correct for exact extend matching.\n if (node.hasFlag(F_IMPLICIT_AMPERSAND)) {\n this.addFlag(F_IMPLICIT_AMPERSAND);\n }\n if (node.hasFlag(F_EXTENDED)) {\n this.addFlag(F_EXTENDED);\n }\n if (node.hasFlag(F_EXTEND_TARGET)) {\n this.addFlag(F_EXTEND_TARGET);\n }\n // Note that we need to create new arrays if we mutate pre/post later\n this.pre ||= node.pre;\n this.post ||= node.post;\n this.sourceNode = node.sourceNode;\n this.sourceParent ??= node.sourceParent;\n if (node.hoistToRoot) {\n this.hoistToRoot = true;\n }\n if (getNodeKeySetLibrary(this) === undefined) {\n const keySetLibrary = getNodeKeySetLibrary(node);\n if (keySetLibrary !== undefined) {\n setNodeKeySetLibrary(this, keySetLibrary);\n }\n }\n // Preserve the generated flag when inheriting; never overwrite true with false\n // (e.g. Ampersand.eval returns PseudoSelector with .generated true, then evalStatic\n // calls PseudoSelector.inherit(Ampersand), which would otherwise overwrite with false)\n this.generated = this.generated || node.generated;\n /**\n * If it's replacing a node that's evaluated, it should inherit the same index.\n * Otherwise, it should be settable after cloning / copying.\n */\n this.index ??= node.index;\n return this;\n }\n\n /**\n * Represents the normalized string value of the node,\n * for the purposes of comparison with other nodes,\n * regardless of type.\n *\n * Derived nodes will override this with different\n * normalization algorithms.\n */\n valueOf(_context?: Context): Primitive {\n const ck = getNodeChildKeys(this);\n if (!ck) {\n // Leaf node — value is a primitive\n return toPrimitiveValue(getNodeValue(this));\n }\n // Container — collect string values from children\n const parts: string[] = [];\n for (const key of ck) {\n const field = getNodeField(this, key);\n if (isArray(field)) {\n for (let i = 0; i < field.length; i++) {\n parts.push(`${field[i]}`);\n }\n } else if (field !== undefined) {\n parts.push(`${field}`);\n }\n }\n if (parts.length === 1) {\n return parts[0]!;\n }\n return parts.join('');\n }\n\n processPrePost(key: 'pre' | 'post', defaultVal: string = '', options: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n let value = this[key];\n if (value === undefined) {\n if (defaultVal) {\n w.add(defaultVal);\n if (defaultVal === ' ') {\n w.signalBoundaryIntent(key, 'explicit_space');\n }\n }\n return w.getSince(mark);\n } else if (value === 0) {\n w.signalBoundaryIntent(key, 'explicit_none');\n return '';\n } else if (value === 1) {\n w.add(' ');\n w.signalBoundaryIntent(key, 'explicit_space');\n return w.getSince(mark);\n } else if (isArray(value)) {\n // Handle Node[] array - call toString() on each node (they will emit into writer)\n for (let i = 0; i < value.length; i++) {\n const node = value[i];\n if (node instanceof Node) {\n node.toString(options);\n } else {\n const s = String(node);\n w.add(s);\n }\n }\n return w.getSince(mark);\n } else {\n const s = String(value);\n w.add(s);\n return w.getSince(mark);\n }\n }\n\n /**\n * This re-serializes the node, if needed. Will\n * likely be over-ridden in some cases.\n *\n * Note that this is the \"as-is\" representation of the\n * node, not the \"evaluated\" version.\n *\n * Note that the ToCssVisitor will be a little\n * more sophisticated, as it will re-format\n * to some extent by replacing newlines + spacing\n * with the appropriate amount of whitespace.\n *\n * @note toString() will, by default, include pre/post\n * white-space and comments, to make serialization\n * easy.\n *\n * In almost all Node cases, this should not be overriden,\n * and toTrimmedString() should be overridden instead.\n */\n toString(options?: PrintOptions, _renderKey?: RenderKey): string {\n if (!isVisibleInContext(this, options?.context) && !this.fullRender) {\n return '';\n }\n if (options?.suppressComments && this.type === 'Comment') {\n return '';\n }\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n let pre = w.capture(() => this.processPrePost('pre', '', options));\n const bodyStr = w.capture(() => this.toTrimmedString(options));\n let post = w.capture(() => this.processPrePost('post', '', options));\n\n let result = pre + bodyStr + post;\n // Trim output if flag is set\n w.add(result, this);\n return w.getSince(mark);\n }\n\n /**\n * Serialize the evaluated tree. Requires context so position patches\n * (the virtual evaluated tree) are resolved during serialization.\n *\n * Use this instead of toString() when serializing eval results.\n * toString() serializes the canonical (parsed) tree without eval state.\n */\n render(options?: PrintOptions | Context, renderKey?: RenderKey): string {\n const normalizedOptions = isContextArg(options)\n ? { context: options }\n : options;\n return this.toString(normalizedOptions, renderKey);\n }\n\n /**\n * The form of the node without pre/post comments and white-space\n *\n * @note - Internally, this still calls `toString()` on each value,\n * so that the internal spacing of the node serialization is\n * correct. This method just serializes a node without the outer\n * pre/post nodes.\n *\n * @todo - Simplify\n */\n toTrimmedString(options?: PrintOptions, _renderKey?: RenderKey) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const ck = getNodeChildKeys(this);\n const ctx = options.context;\n if (ck) {\n for (const key of ck) {\n // Resolve through eval state when context available\n const field = ctx\n ? this.get(key! as keyof ChildData & string, ctx)\n : getNodeField(this, key);\n if (isArray(field)) {\n for (const item of field) {\n if (item instanceof Node) {\n item.toString(options);\n } else {\n const s = item === undefined ? '' : String(item);\n if (s) {\n w.add(s, this);\n }\n }\n }\n } else if (field instanceof Node) {\n field.toString(options);\n } else {\n const s = field === undefined ? '' : String(field);\n if (s) {\n w.add(s, this);\n }\n }\n }\n } else {\n // Leaf node — render the primitive value directly\n const s = String(getNodeValue(this) ?? '');\n if (s) {\n w.add(s, this);\n }\n }\n return w.getSince(mark);\n }\n\n /**\n * Individual node types will override this.\n *\n * This is just a default implementation.\n * 0 = equal (==)\n * 1 = greater than (>)\n * -1 = less than (<)\n * undefined = not comparable\n */\n compare(b: Node, context?: Context): 0 | 1 | -1 | undefined {\n let aVal = this.valueOf(context);\n let bVal = b.valueOf(context);\n if (aVal === bVal) {\n return 0;\n }\n if (aVal === undefined || bVal === undefined) {\n return undefined;\n }\n return aVal > bVal ? 1 : -1;\n }\n\n /** Overridden in index.ts to avoid circularity */\n operate(_b: Node, _op: Operator, _context: Context): Node {\n return this;\n }\n\n static numericCompare(a: number, b: number) {\n if (a === b) {\n return 0;\n } else if (Math.abs(a - b) < Number.EPSILON) {\n /** Close enough! Prevents floating point precision issues */\n return 0;\n } else if (a > b) {\n return 1;\n } else {\n return -1;\n }\n }\n\n /**\n * Generates a .js module\n * @todo - Generate a .ts module & .js.map\n */\n /** Move to ToModuleVisitor */\n // toModule?(context: Context, out: OutputCollector): void\n}\n\n/** When converting Less/Sass to Jess, we'll switch this flag temporarily */\nNode.prototype.fullRender = false;\n","/**\n * Import from node-base to avoid circular dependency.\n * The patching of Node.prototype.nil happens in node.ts\n */\nimport {\n Node,\n F_VISIBLE,\n F_STATIC,\n defineType,\n type OptionalLocation,\n type NodeOptions\n} from './node-base.js';\nimport type { Context, TreeContext } from '../context.js';\n\nexport interface Nil extends Node<''> {\n type: 'Nil';\n shortType: 'nil';\n valueOf(): '';\n eval(context: Context): Nil;\n}\n\n/**\n * A Node type that outputs nothing.\n *\n * We need this for things like rulesets,\n * which need dynamically-linked nodes\n *\n * This is also the default value for declarations like:\n * `$var:;`\n */\nexport class Nil extends Node<''> {\n static override childKeys = null as null;\n\n constructor(\n value?: any,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext) {\n super('', options, location, treeContext);\n this.allowRoot = true;\n this.allowRuleRoot = true;\n this.addFlag(F_STATIC);\n this.removeFlag(F_VISIBLE);\n // Nil nodes should never render, even if fullRender is set on prototype (e.g., in tests)\n this.fullRender = false;\n }\n\n override toTrimmedString() {\n return '';\n }\n\n override toString() {\n return '';\n }\n}\n\nexport const nil = defineType(Nil, 'Nil');","/**\n * Import from node-base to avoid circular dependency.\n * The patching happens in node.ts\n */\nimport { Node, defineType, type OptionalLocation, type NodeOptions, type TreeContext, F_STATIC } from './node-base.js';\nimport type { Context } from '../context.js';\nimport { type MaybePromise } from '@jesscss/awaitable-pipe';\nimport { Nil } from './nil.js';\n\nexport type AnyRole =\n 'ident'\n | 'name'\n | 'charset'\n | 'keyword'\n | 'property'\n | 'atkeyword'\n | 'urlvalue'\n | 'flag'\n | 'customprop'\n | 'semi'\n | 'operator'\n | 'any';\n\n/** Doesn't get assigned but can be used for inference? */\nexport type AnyOptions<T extends string> = NodeOptions & {\n role?: T;\n};\n\nexport interface Any<\n Role extends AnyRole = AnyRole\n> extends Node<string, AnyOptions<Role>> {\n type: 'Any' | 'Keyword';\n shortType: 'any' | 'keyword';\n eval(context: Context): Any<Role>;\n valueOf(): string;\n}\n\n/**\n * Any is a simple token that has a string value and a role.\n * Sometimes that role is unspecified. Think of it as a generic,\n * and a placeholder for tokens that don't have anything special\n * to do during evaluation.\n *\n * Called \"Anonymous\" in Less's original tree, but \"anonymous\"\n * was somewhat a counter-intuitive name.\n */\nexport class Any<\n Role extends AnyRole = AnyRole\n> extends Node<string, AnyOptions<Role>> {\n static override childKeys = null as null;\n\n readonly value!: string;\n readonly role: Role | undefined;\n\n constructor(\n value: string,\n options?: AnyOptions<Role>,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n super(value, options, location, treeContext);\n this.value = value;\n this.role = options?.role as Role | undefined;\n this.addFlag(F_STATIC);\n }\n\n override preEval(context: Context): this | Nil {\n this.preEvaluated = true;\n // Index should already be assigned by parent Rules\n if (this.role === 'charset') {\n if (!context.currentCharset) {\n /** @todo - Throw error in the future? */\n context.currentCharset = this;\n }\n return new Nil();\n }\n return this;\n }\n\n // Any values are static and don't need evaluation\n override evalNode(_context: Context): MaybePromise<Node> {\n return this;\n }\n\n override compare(other: Node): 0 | 1 | -1 | undefined {\n // In Less guards, quoted strings are distinct from bare identifiers.\n if (other.type === 'Quoted') {\n return undefined;\n }\n if (other.type === 'Any' || other.type === 'Keyword') {\n return this.value === String(other.valueOf?.() ?? '') ? 0 : undefined;\n }\n if (other.type === 'Num' || other.type === 'Dimension') {\n const text = this.value.trim();\n if (!/^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)$/.test(text)) {\n return undefined;\n }\n const otherNumber = Reflect.get(other, 'number');\n const otherUnit = Reflect.get(other, 'unit');\n if (typeof otherNumber !== 'number') {\n return undefined;\n }\n if (other.type === 'Dimension' && otherUnit) {\n return undefined;\n }\n return Number(text) === otherNumber ? 0 : undefined;\n }\n if (typeof other.toString === 'function') {\n const normalize = (s: string) => s.replace(/;\\s*/g, ', ').replace(/\\s+/g, ' ').trim();\n return normalize(this.toString()) === normalize(other.toString()) ? 0 : undefined;\n }\n return undefined;\n }\n}\n\n// Custom any function that properly handles role narrowing\nexport function any<Role extends AnyRole = AnyRole>(\n value: string,\n options?: AnyOptions<Role>\n): Any<Role> {\n return new Any(value, options);\n}\ndefineType(Any, 'Any');\n\n/** Legacy class - remove? */\nexport class Anonymous<\n Role extends AnyRole = AnyRole\n> extends Any<Role> {}\ndefineType(Anonymous, 'Anonymous');\n\n/**\n * Keyword represents a CSS keyword value (e.g., 'auto', 'none', 'inherit', 'and', 'or').\n *\n * This is a convenience class that extends Any with role: 'keyword' fixed.\n * It provides better type safety and aligns with Less.js's Keyword node type\n * for compatibility purposes.\n *\n * Note: In Jess, boolean values ('true', 'false') are represented as Bool nodes,\n * not Keyword nodes, unlike Less.js where they are Keyword instances.\n */\nexport interface Keyword {\n type: 'Keyword';\n shortType: 'keyword';\n}\n\nexport class Keyword extends Any<'keyword'> {\n constructor(\n value: string,\n options?: Omit<NodeOptions, 'role'>,\n location?: OptionalLocation,\n context?: TreeContext\n ) {\n // Force role to 'keyword'\n super(value, { ...options, role: 'keyword' }, location, context);\n }\n}\ndefineType(Keyword, 'Keyword');\n\n/**\n * Helper function to create a Keyword node\n */\nexport function keyword(\n value: string,\n options?: Omit<NodeOptions, 'role'>,\n location?: OptionalLocation,\n context?: TreeContext\n): Keyword {\n return new Keyword(value, options, location, context);\n}\n","// errors.ts\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport { type IRecognitionException, type ILexingResult } from '@chevrotain/types';\nimport type { TreeContext } from './context.js';\nimport type { OptionalLocation } from './tree/node.js';\nimport type { Deprecation } from './deprecation.js';\n\ntype JessFile = TreeContext['file'];\n\n/** Minimal shape for passing context and a node to helpers. */\nexport type TreeContextLike = { file: JessFile };\n\n/** Node type carrying a `location` (full span, empty tuple, or unset). */\nexport type LocNode = { location?: OptionalLocation };\n\ntype Phase = 'parse' | 'resolve' | 'import' | 'eval' | 'extend' | 'plugin';\ntype Severity = 'error' | 'warn';\n\n/**\n * Normalized error format for all phases (lexing, parsing, evaluation).\n * This is the format returned by safeParse/safeRender methods.\n */\nexport interface ErrorDiagnostic {\n code: string;\n phase: Phase;\n message: string;\n reason: string;\n fix: string;\n note?: string;\n\n // File location information\n file?: {\n name: string;\n path: string;\n fullPath: string;\n source?: string;\n };\n filePath?: string;\n line: number;\n column: number;\n /**\n * Relevant source lines for code frame display.\n * Keys are line numbers (1-indexed), values are the line content.\n * Includes the error line and context lines (before/after).\n * Example: { 55: 'before line', 56: 'error line', 57: 'after line' }\n */\n lines?: Record<number, string>;\n\n // Raw error data (for parser/lexer errors)\n errors?: IRecognitionException[];\n lexerErrors?: ILexingResult['errors'];\n}\n\n/**\n * Normalized warning format for all phases (lexing, parsing, evaluation).\n * This is the format returned by safeParse/safeRender methods.\n */\nexport interface WarningDiagnostic {\n code: string;\n phase: Phase;\n message: string;\n reason: string;\n fix: string;\n note?: string;\n\n // File location information\n file?: {\n name: string;\n path: string;\n fullPath: string;\n // Note: source is NOT included - use 'lines' property for code frame display\n };\n filePath?: string;\n line: number;\n column: number;\n endLine?: number;\n endColumn?: number;\n /**\n * Relevant source lines for code frame display.\n * Keys are line numbers (1-indexed), values are the line content.\n * Includes the warning line and context lines (before/after).\n * Example: { 55: 'before line', 56: 'warning line', 57: 'after line' }\n */\n lines?: Record<number, string>;\n}\n\n/**\n * Initialization bag for a diagnostic.\n * Prefer passing `ctx` + `node` so file/line/column/source are auto-wired.\n * If those aren’t available, provide `filePath`/`source`/`line`/`column` directly.\n */\nexport type JessErrorInit = {\n severity?: Severity;\n code: string;\n phase: Phase;\n\n /** Optional: auto-wire file/line/col/source from compiler context + node */\n ctx?: TreeContextLike;\n node?: LocNode;\n\n /** Manual overrides if ctx/node aren’t provided */\n filePath?: string;\n source?: string;\n line?: number;\n column?: number;\n\n /** Interpolation values for the selected template */\n meta?: Record<string, unknown>;\n\n /** Optional overrides for the template’s strings */\n summary?: string;\n reason?: string;\n fix?: string;\n\n /** Optional one-liner for extra context */\n note?: string;\n\n /** Optional overrides for the template’s strings */\n errors?: IRecognitionException[];\n lexerErrors?: ILexingResult['errors'];\n};\n\n/* =========================\n * Template registry\n * ========================= */\n\n/**\n * Template record for codes.\n * Keep these short and actionable. Use `${placeholders}` for meta fields.\n */\ntype Template = { summary: string; reason: string; fix: string };\n\n/* eslint-disable @typescript-eslint/naming-convention */\nconst TEMPLATES = {\n // Parse/Lex\n 'parse/unexpected-token': {\n summary: 'Unexpected token',\n reason: 'Token \"${token}\" is not valid here.',\n fix: 'Check for a missing quote/comma or wrong operator.'\n },\n 'parse/unterminated-string': {\n summary: 'Unterminated string',\n reason: 'Missing closing quote.',\n fix: 'Close the string, e.g. url(\"hero.jpg\").'\n },\n 'parse/unexpected-syntax': {\n summary: 'Unexpected syntax',\n reason: 'Expected ${expected}, got ${got}.',\n fix: 'Add the expected token or remove the unexpected one.'\n },\n 'parse/syntax-error': {\n summary: 'Syntax error',\n reason: '${message}',\n fix: 'Check surrounding tokens near this location.'\n },\n\n // Resolve/Import\n 'resolve/name-not-found': {\n summary: 'Name not found',\n reason: 'Symbol \"${symbol}\" is undefined in this scope.',\n fix: 'Define \"${symbol}\" or import a file that provides it.'\n },\n 'import/circular-compose': {\n summary: 'Circular @-compose detected',\n reason: '${chain}',\n fix: 'Break the cycle (extract shared bits and compose that).'\n },\n\n // Eval\n 'eval/bad-call-arity': {\n summary: 'Bad call: wrong arity',\n reason: '${callee} expects ${expectedCount} args, got ${gotCount}.',\n fix: 'Add/remove arguments to match the signature.'\n },\n 'eval/type-mismatch': {\n summary: 'Type mismatch',\n reason: '${callee} expects ${expected}, got ${got}.',\n fix: 'Pass a ${expected}; convert or choose a compatible value.'\n },\n\n // Extend\n 'extend/protected-boundary': {\n summary: 'Extend blocked by protected boundary',\n reason: '\"${target}\" is defined behind a protected compose boundary.',\n fix: 'Move \"${target}\" to a shared file or create a local shim.'\n },\n 'extend/not-found': {\n summary: 'Extend target \"${target}\" not found',\n reason: 'No ruleset found matching \"${target}\" in accessible extend roots.',\n fix: 'Ensure \"${target}\" exists and is accessible from the current extend root.'\n },\n 'extend/not-accessible': {\n summary: 'Extend target \"${target}\" not accessible',\n reason: '\"${target}\" exists but is not accessible from the current extend root (blocked by at-rule or compose boundary).',\n fix: 'Move the extend or the target to a shared extend root, or use a different approach.'\n },\n\n // Plugin\n 'plugin/unsupported-feature': {\n summary: 'Unsupported feature',\n reason: 'Plugin \"${plugin}\" does not implement ${feature}.',\n fix: 'Use a supported alternative or enable a fallback.'\n },\n\n // ---------- Warnings (examples you can expand) ----------\n 'eval/deprecated': {\n summary: 'Deprecated feature',\n reason: '\"${what}\" is deprecated.',\n fix: 'Use \"${use}\" instead.'\n },\n 'resolve/unused-variable': {\n summary: 'Unused variable',\n reason: '\"${symbol}\" is declared but its value is never used.',\n fix: 'Remove it or prefix with \"_\" to silence.'\n },\n 'selector/duplicate': {\n summary: 'Duplicate selector',\n reason: 'Selector \"${selector}\" is defined multiple times.',\n fix: 'Consolidate rules or remove the duplicate.'\n }\n} satisfies Record<string, Template>;\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type JessErrorCode = keyof typeof TEMPLATES;\n\nexport function isJessErrorCode(code: string): code is JessErrorCode {\n return Object.hasOwn(TEMPLATES, code);\n}\n\n/**\n * Replaces `${key}` with values from `meta`. Unset keys render as `<key>`.\n */\nfunction interpolate(s: string, meta: Record<string, unknown>): string {\n return s.replace(/\\$\\{(\\w+)\\}/g, (_: string, k: string) => String(meta[k] ?? `<${k}>`));\n}\n\n/* =========================\n * OSC-8 hyperlinks\n * ========================= */\n\nfunction osc8(uri: string, label: string): string {\n return `\\x1b]8;;${uri}\\x1b\\\\${label}\\x1b]8;;\\x1b\\\\`;\n}\n\nfunction supportsLinks(): boolean {\n const tty = process.stderr.isTTY && process.env.TERM !== 'dumb';\n if (!tty) {\n return false;\n }\n return Boolean(\n process.env.TERM_PROGRAM === 'vscode'\n || process.env.ITERM_SESSION_ID\n || process.env.WT_SESSION\n );\n}\n\nfunction linkFor(abs: string, line: number, col: number, label: string): string {\n const uri = `vscode://file/${abs}:${line}:${col}`;\n return supportsLinks() ? osc8(uri, label) : label;\n}\n\n/* =========================\n * Path labeling (human-short)\n * ========================= */\n\nfunction trail(p: string, n: number): string {\n const parts = p.split(path.sep).filter(Boolean);\n return (parts.length <= n ? parts : ['…', ...parts.slice(parts.length - n)]).join(path.sep);\n}\n\nfunction prettyLabel(abs: string, line: number, col: number): string {\n const rel = path.relative(process.cwd(), abs);\n const shown = (!rel.startsWith('..') && !path.isAbsolute(rel)) ? rel : trail(abs, 3);\n return `${shown}:${line}:${col}`;\n}\n\n/* =========================\n * Code-frame utilities\n * ========================= */\n\nfunction buildLineStarts(src: string): Uint32Array {\n const starts: number[] = [0];\n for (let i = 0; i < src.length; i++) {\n const ch = src.charCodeAt(i);\n if (ch === 10) {\n starts.push(i + 1);\n } else if (ch === 13) {\n if (src.charCodeAt(i + 1) === 10) {\n i++;\n }\n starts.push(i + 1);\n }\n }\n return Uint32Array.from(starts);\n}\n\n/**\n * Extracts relevant source lines for code frame display.\n * Returns an object with line numbers as keys (1-indexed) and line content as values.\n * Includes the target line and context lines (before/after).\n * @param source - Full source code\n * @param line - Target line number (1-indexed)\n * @param contextLines - Number of context lines before/after (default: 1)\n * @returns Object with line numbers as keys, e.g. { 55: 'before', 56: 'error', 57: 'after' }\n */\nexport function extractRelevantLines(\n source: string | undefined,\n line: number,\n contextLines: number = 1\n): Record<number, string> | undefined {\n if (!source) {\n return undefined;\n }\n\n // Split source into lines once\n const lines = source.split(/\\r?\\n/);\n const totalLines = lines.length;\n const targetLine = Math.max(1, Math.min(line, totalLines));\n\n // Calculate line range (1-indexed)\n const startLine = Math.max(1, targetLine - contextLines);\n const endLine = Math.min(totalLines, targetLine + contextLines);\n\n // Extract relevant lines\n const result: Record<number, string> = {};\n for (let i = startLine; i <= endLine; i++) {\n result[i] = lines[i - 1]!; // Convert to 0-indexed for array access\n }\n\n return result;\n}\n\nfunction ensureLineStarts(file: JessFile): Uint32Array | undefined {\n if (!file?.source) {\n return undefined;\n }\n // Your file type may already have `lines`; if not, store it there.\n if (!file.lines) {\n file.lines = buildLineStarts(file.source);\n }\n\n return file.lines as Uint32Array;\n}\n\nfunction getLine(file: JessFile, line: number): string {\n const src = file?.source;\n const idx = ensureLineStarts(file);\n if (!src || !idx || line < 1 || line > idx.length) {\n return '';\n }\n const start = idx[line - 1];\n const end = line < idx.length ? idx[line]! - 1 : src.length;\n const last = src.charCodeAt(end - 1);\n const realEnd = last === 13 ? end - 1 : end; // trim trailing \\r\n return src.slice(start, realEnd);\n}\n\nfunction codeFrameFromFile(file: JessFile, line = 1, col = 1): string {\n if (!file?.source) {\n return '';\n }\n\n ensureLineStarts(file);\n\n const width = String(line).length;\n const num = (n: number) => String(n).padStart(width, ' ');\n const caret = ' '.repeat(Math.max(0, col - 1)) + '^';\n\n const prev = getLine(file, line - 1);\n const curr = getLine(file, line);\n const next = getLine(file, line + 1);\n\n let out = '';\n if (prev) {\n out += chalk.gray(`${num(line - 1)} | ${prev}\\n`);\n }\n out += chalk.bold(`${num(line)} | ${curr}\\n`);\n out += chalk.gray(` ${' '.repeat(width)} | `) + chalk.red(caret) + '\\n';\n if (next) {\n out += chalk.gray(`${num(line + 1)} | ${next}\\n`);\n }\n return out;\n}\n\n/* =========================\n * Diagnostic (error or warn)\n * ========================= */\n\nexport class JessError extends Error {\n severity: Severity = 'error';\n code: keyof typeof TEMPLATES = 'parse/syntax-error';\n phase: Phase = 'parse';\n\n // Resolved source context (fileObj preferred; filePath is legacy)\n fileObj?: JessFile;\n filePath?: string;\n line = 1;\n column = 1;\n source?: string;\n node?: LocNode; // Store node to extract endLine/endColumn\n\n reason = '';\n fix = '';\n note?: string;\n\n errors?: IRecognitionException[];\n lexerErrors?: ILexingResult['errors'];\n\n constructor(init: JessErrorInit) {\n // Resolve context from ctx/node first, else from explicit fields.\n const fileObj = init.ctx?.file;\n const abs = fileObj?.fullPath ?? init.filePath;\n const line = init.node?.location?.[1] ?? init.line ?? 1;\n const column = init.node?.location?.[2] ?? init.column ?? 1;\n const source = fileObj?.source ?? init.source;\n\n const code = isJessErrorCode(init.code) ? init.code : 'parse/syntax-error';\n const meta = init.meta ?? {};\n const t = TEMPLATES[code];\n\n const summary = init.summary ?? interpolate(t.summary, meta);\n const reason = init.reason ?? interpolate(t.reason, meta);\n const fix = init.fix ?? interpolate(t.fix, meta);\n\n super(summary);\n\n this.name = 'JessError';\n this.severity = init.severity ?? 'error';\n this.code = code;\n this.phase = init.phase;\n\n this.fileObj = fileObj;\n this.filePath = abs;\n this.line = line;\n this.column = column;\n this.source = source;\n this.node = init.node; // Store node for endLine/endColumn extraction\n\n this.reason = reason;\n this.fix = fix;\n this.note = init.note;\n\n this.errors = init.errors;\n this.lexerErrors = init.lexerErrors;\n }\n\n /** Lightweight JSON for serializers (e.g. Vitest). Strips heavy Chevrotain token trees and full source. */\n toJSON() {\n return {\n severity: this.severity,\n code: this.code,\n phase: this.phase,\n fileObj: this.fileObj\n ? { name: this.fileObj.name, path: this.fileObj.path, fullPath: this.fileObj.fullPath }\n : undefined,\n filePath: this.filePath,\n reason: this.reason,\n fix: this.fix,\n note: this.note,\n errors: this.errors?.map(e => ({ message: e.message, stack: e.stack })),\n lexerErrors: this.lexerErrors?.map(e => ({ message: e.message, line: e.line, column: e.column }))\n };\n }\n\n /** Pretty, clickable string for terminal/Problems panel. */\n override toString(): string {\n const abs = this.fileObj?.fullPath ?? this.filePath;\n const l = this.line ?? 1;\n const c = this.column ?? 1;\n const label = abs ? prettyLabel(abs, l, c) : '(unknown)';\n const clickable = abs ? linkFor(abs, l, c, label) : label;\n\n const color = this.severity === 'warn' ? chalk.yellow : chalk.red;\n\n const header =\n `${color(this.severity)} ${color(this.code)} `\n + `${chalk.gray(`[${this.phase}]`)} ${chalk.cyan(clickable)} `\n + `${chalk.white('— ' + this.message)}`;\n\n let frame = '';\n if (this.fileObj?.source) {\n frame = codeFrameFromFile(this.fileObj, l, c);\n } else if (this.source) {\n // Legacy, slower fallback\n const lines = this.source.split(/\\r?\\n/);\n const prev = lines[l - 2];\n const curr = lines[l - 1] ?? '';\n const next = lines[l];\n const width = String(l).length;\n const num = (n: number) => String(n).padStart(width, ' ');\n const caret = ' '.repeat(Math.max(0, c - 1)) + '^';\n if (prev) {\n frame += chalk.gray(`${num(l - 1)} | ${prev}\\n`);\n }\n frame += chalk.bold(`${num(l)} | ${curr}\\n`);\n frame += chalk.gray(` ${' '.repeat(width)} | `) + chalk.red(caret) + '\\n';\n if (next) {\n frame += chalk.gray(`${num(l + 1)} | ${next}\\n`);\n }\n }\n\n const out = [\n header,\n frame && frame.trimEnd(),\n '',\n `Reason: ${this.reason}`,\n `Fix: ${this.fix}`,\n this.note ? `Note: ${this.note}` : undefined,\n (!supportsLinks() && abs) ? chalk.dim(`Path: ${abs}:${l}:${c}`) : undefined\n ]\n .filter(Boolean)\n .join('\\n');\n\n return out;\n }\n}\n\n/* =========================\n * Printing helpers\n * ========================= */\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst _seen = new Set<string>();\n\n/**\n * Emits a diagnostic to stderr (or a custom stream).\n * Set `dedupe: true` to suppress repeats from the same location/message.\n */\nexport function emit(diag: JessError, opts?: { stream?: NodeJS.WriteStream; dedupe?: boolean }): void {\n const stream = opts?.stream ?? process.stderr;\n if (opts?.dedupe) {\n const abs = diag.fileObj?.fullPath ?? diag.filePath ?? '';\n const key = `${diag.severity}|${diag.code}|${abs}|${diag.line}|${diag.column}|${diag.message}`;\n if (_seen.has(key)) {\n return;\n }\n _seen.add(key);\n }\n stream.write(String(diag) + '\\n');\n}\n\n/** Clears the in-process de-duplication set. Useful for tests. */\nexport function resetDedupe(): void {\n _seen.clear();\n}\n\n/* =========================\n * Factories / Public API\n * ========================= */\n\nexport function makeJessError(init: JessErrorInit): JessError {\n return new JessError(init);\n}\n\ntype Common = {\n ctx?: TreeContextLike;\n node?: LocNode;\n\n filePath?: string;\n source?: string;\n line?: number;\n column?: number;\n\n note?: string;\n summary?: string;\n reason?: string;\n fix?: string;\n severity?: Severity;\n\n meta?: Record<string, unknown>;\n};\n\n/**\n * Primary **error** helpers.\n * Each function returns a `JessError` ready to be thrown or emitted.\n */\nexport const ERR = {\n // Parse/Lex\n unexpectedToken(args: Common & { meta: { token: string } }) {\n return makeJessError({ code: 'parse/unexpected-token', phase: 'parse', ...args });\n },\n\n unterminatedString(args: Common = {}) {\n return makeJessError({ code: 'parse/unterminated-string', phase: 'parse', ...args });\n },\n\n // Resolve/Import\n nameNotFound(args: Common & { meta: { symbol: string } }) {\n return makeJessError({ code: 'resolve/name-not-found', phase: 'resolve', ...args });\n },\n\n circularCompose(args: Common & { meta: { chain: string } }) {\n return makeJessError({ code: 'import/circular-compose', phase: 'import', ...args });\n },\n\n // Eval\n arity(args: Common & { meta: { callee: string; expectedCount: number; gotCount: number } }) {\n return makeJessError({ code: 'eval/bad-call-arity', phase: 'eval', ...args });\n },\n\n typeMismatch(args: Common & { meta: { callee: string; expected: string; got: string } }) {\n return makeJessError({ code: 'eval/type-mismatch', phase: 'eval', ...args });\n },\n\n // Extend\n extendBoundary(args: Common & { meta: { target: string } }) {\n return makeJessError({ code: 'extend/protected-boundary', phase: 'extend', ...args });\n },\n\n extendNotFound(args: Common & { meta: { target: string } }) {\n return makeJessError({ code: 'extend/not-found', phase: 'extend', ...args });\n },\n\n extendNotAccessible(args: Common & { meta: { target: string } }) {\n return makeJessError({ code: 'extend/not-accessible', phase: 'extend', ...args });\n },\n\n // Plugin\n pluginUnsupported(args: Common & { meta: { plugin: string; feature: string } }) {\n return makeJessError({ code: 'plugin/unsupported-feature', phase: 'plugin', ...args });\n }\n};\n\n/**\n * Primary **warning** helpers.\n * Same API shape as `ERR`, but default `severity: 'warn'`.\n * Call `emit(WARN.*(...))` to log without throwing.\n */\nexport const WARN = {\n deprecated(args: Common & { meta: { what: string; use: string; deprecation?: Deprecation } }) {\n return makeJessError({ severity: 'warn', code: 'eval/deprecated', phase: 'eval', ...args });\n },\n\n unusedVar(args: Common & { meta: { symbol: string } }) {\n return makeJessError({ severity: 'warn', code: 'resolve/unused-variable', phase: 'resolve', ...args });\n },\n\n duplicateSelector(args: Common & { meta: { selector: string } }) {\n return makeJessError({ severity: 'warn', code: 'selector/duplicate', phase: 'extend', ...args });\n },\n\n extendNotFound(args: Common & { meta: { target: string } }) {\n return makeJessError({ severity: 'warn', code: 'extend/not-found', phase: 'extend', ...args });\n },\n\n extendNotAccessible(args: Common & { meta: { target: string } }) {\n return makeJessError({ severity: 'warn', code: 'extend/not-accessible', phase: 'extend', ...args });\n }\n};\n\n/* =========================\n * Chevrotain adapter\n * ========================= */\n\n/**\n * Converts a Chevrotain parser/lexer error into a friendly diagnostic.\n * If you pass `ctx`, the error will be clickable and include a code-frame.\n *\n * @param errors Chevrotain recognition errors\n * @param lexerResult Chevrotain lexing result\n * @param filePath Absolute path to the file (legacy fallback)\n * @param source File contents (legacy fallback)\n * @param ctx Optional TreeContext to auto-fill file/line/col/source\n */\nexport function getErrorFromParser(\n errors: IRecognitionException[],\n lexerErrors: ILexingResult['errors'] | undefined,\n filePath: string,\n source: string,\n ctx?: TreeContextLike\n): JessError {\n const error = lexerErrors?.[0] ?? errors[0];\n if (!error) {\n return new JessError({ code: 'parse/syntax-error', phase: 'parse', filePath, source, ctx });\n }\n\n const isLex = !('token' in error);\n\n const line =\n 'token' in error\n ? error.token?.startLine\n : error.line;\n\n const column =\n 'token' in error\n ? error.token?.startColumn\n : error.column;\n\n const message = error.message || '';\n\n let code: keyof typeof TEMPLATES = 'parse/syntax-error';\n let meta: Record<string, unknown> = {};\n\n if (isLex) {\n code = 'parse/unexpected-token';\n meta = { token: ('char' in error ? String(error.char) : undefined) ?? '/' };\n } else if (/unterminated|string not closed/i.test(message)) {\n code = 'parse/unterminated-string';\n } else if (/expecting/i.test(message)) {\n code = 'parse/unexpected-syntax';\n const m = message.match(/expecting\\s+([^,]+).*?but found\\s+'?([^']+)'?/i);\n meta = m ? { expected: m[1], got: m[2] } : { expected: 'token', got: 'other' };\n }\n\n return new JessError({\n code,\n phase: 'parse',\n meta,\n ctx,\n filePath,\n source,\n line: line ?? 1,\n column: column ?? 1,\n errors,\n lexerErrors\n });\n}\n\n/**\n * Converts a JessError to a normalized ErrorDiagnostic or WarningDiagnostic.\n * Extracts relevant source lines for code frame display.\n */\nexport function toDiagnostic(error: JessError): ErrorDiagnostic | WarningDiagnostic {\n // Extract relevant lines from source (error line + context)\n const lines = extractRelevantLines(error.source ?? error.fileObj?.source, error.line);\n\n // Extract endLine/endColumn from node location if available\n // Location format: [startOffset, startLine, startColumn, endOffset, endLine, endColumn]\n const nodeLocation = error.node?.location;\n const endLine = nodeLocation && nodeLocation.length >= 6\n ? nodeLocation[4]\n : undefined;\n const endColumn = nodeLocation && nodeLocation.length >= 6\n ? nodeLocation[5]\n : undefined;\n\n // Create file object without source (we only use 'lines' for code frames)\n const file = error.fileObj\n ? {\n name: error.fileObj.name,\n path: error.fileObj.path,\n fullPath: error.fileObj.fullPath\n // Explicitly exclude source - we use 'lines' property instead\n }\n : undefined;\n\n const base = {\n code: error.code,\n phase: error.phase,\n message: error.message,\n reason: error.reason,\n fix: error.fix,\n note: error.note,\n file,\n filePath: error.filePath,\n line: error.line,\n column: error.column,\n endLine,\n endColumn,\n lines\n };\n\n if (error.severity === 'error') {\n return {\n ...base,\n errors: error.errors,\n lexerErrors: error.lexerErrors\n } as ErrorDiagnostic;\n } else {\n return base as WarningDiagnostic;\n }\n}\n","import type { MaybePromise } from 'awaitable-pipe';\nimport { F_VISIBLE, Node, type NodeOptions, type NodeValue, defineType } from './node.js';\nimport type { IfAny } from 'type-fest';\nimport type { Context } from '../context.js';\nimport type { Nil } from './nil.js';\nimport { type BitSetLibrary, BitSet } from './util/bitset.js';\n\nconst { isArray } = Array;\n/**\n * This represents anything that is valid in a selector\n *\n * @todo - Add Sass private / placeholder selectors?\n * e.g. `\\\\foo` instead of `%foo`\n * private = `\\\\_foo`\n */\n\nexport interface Selector<T = any, O extends NodeOptions = NodeOptions, CD extends Record<string, unknown> = Record<string, unknown>> extends Node<IfAny<T, NodeValue, T>, O, CD> {\n valueOf(): string;\n getKeySet(context?: Context): BitSet<string>;\n eval(context: Context): MaybePromise<Selector<T>> | MaybePromise<Nil>;\n}\n\nexport abstract class Selector<T = any, O extends NodeOptions = NodeOptions, CD extends Record<string, unknown> = Record<string, unknown>> extends Node<IfAny<T, NodeValue, T>, O, CD> {\n isSelector = true;\n\n protected _valueOf: string | undefined;\n\n keySetLibrary: BitSetLibrary<string> | undefined;\n\n private _seedKeySetLibrary(library: BitSetLibrary<string>): void {\n this.keySetLibrary = library;\n for (const child of this.children(true)) {\n if ((child as Selector).isSelector) {\n (child as Selector).keySetLibrary = library;\n }\n }\n }\n\n protected override evalNode(context: Context): MaybePromise<Node> {\n this._seedKeySetLibrary(context.selectorBits);\n if (this.sourceNode !== this && (this.sourceNode as Selector).isSelector) {\n (this.sourceNode as Selector)._seedKeySetLibrary(context.selectorBits);\n }\n return super.evalNode(context);\n }\n\n /**\n * A set of all simplified (valueOf) selectors,\n * for easy lookup to see if the selector is extendable\n * by the key sets in the extend scope.\n */\n protected _keySet: BitSet<string> | undefined;\n /** Used for mixin registry indexing - only includes visible selectors */\n protected _visibleKeySet: BitSet<string> | undefined;\n /**\n * Like keySet but excludes keys inside `:is()` SelectorList args.\n * For `:is(.a, .b) .c`, requiredKeySet = `{.c}` while keySet = `{.a, .b, .c}`.\n * Safe for subset rejection: if requiredKeySet keys aren't in target, no match possible.\n */\n protected _requiredKeySet: BitSet<string> | undefined;\n\n get keySet() {\n if (!this._keySet) {\n this.computeKeySets();\n }\n return this._keySet!;\n }\n\n getKeySet(context?: Context): BitSet<string> {\n if (!context) {\n return this.keySet;\n }\n let library = this.keySetLibrary;\n if (!library) {\n throw new Error('Selector keySet library not found');\n }\n\n let children = (this as any).value;\n if (isArray(children)) {\n let keySet: BitSet<string> | undefined;\n for (const child of children as Selector[]) {\n let childKeySet = child.getKeySet(context);\n keySet = keySet ? keySet.or(childKeySet) : childKeySet.clone();\n }\n return keySet ?? library.getBitset();\n }\n\n let value = String((this as unknown as { valueOf(context?: Context): string }).valueOf(context));\n return library.getBitset([value]);\n }\n\n get visibleKeySet() {\n if (!this._visibleKeySet) {\n this.computeKeySets();\n }\n return this._visibleKeySet!;\n }\n\n get requiredKeySet() {\n if (!this._requiredKeySet) {\n this.computeKeySets();\n }\n return this._requiredKeySet!;\n }\n\n invalidateCache(): void {\n this._valueOf = undefined;\n this._keySet = undefined;\n this._visibleKeySet = undefined;\n this._requiredKeySet = undefined;\n }\n\n /**\n * Computes keySet, visibleKeySet, and requiredKeySet in one pass.\n * Subclasses should override this to implement their specific logic.\n */\n protected computeKeySets(): void {\n if (this._keySet && this._visibleKeySet && this._requiredKeySet) {\n return;\n }\n let library = this.keySetLibrary;\n if (!library) {\n throw new Error('Selector keySet library not found');\n }\n\n let children = (this as any).value;\n if (isArray(children)) {\n for (const child of children as Selector[]) {\n let childKeySet = child.keySet;\n this._keySet = this._keySet ? this._keySet.or(childKeySet) : childKeySet.clone();\n this._visibleKeySet = this._visibleKeySet\n ? this._visibleKeySet.or(child.visibleKeySet)\n : child.visibleKeySet.clone();\n this._requiredKeySet = this._requiredKeySet\n ? this._requiredKeySet.or(child.requiredKeySet)\n : child.requiredKeySet.clone();\n }\n return;\n }\n let value = String(this.valueOf());\n this._keySet = library.getBitset([value]);\n this._requiredKeySet = this._keySet;\n\n if (this.hasFlag(F_VISIBLE)) {\n this._visibleKeySet = this._keySet;\n } else {\n this._visibleKeySet = library.getBitset();\n }\n }\n}\n\ndefineType(Selector, 'Selector');\n","import {\n defineType,\n type OptionalLocation\n} from './node.js';\nimport type { Context } from '../context.js';\nimport { Nil } from './nil.js';\nimport { Selector } from './selector.js';\nimport type { SimpleSelector } from './selector-simple.js';\nimport { isNode } from './util/is-node.js';\nimport { type MaybePromise, pipe, isThenable, serialForEach } from '@jesscss/awaitable-pipe';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { N } from './node-type.js';\n\nexport type CompoundSelectorChildData = { value: SimpleSelector[] };\n\n/**\n * @example\n * .class#id\n *\n * Must have at least 2 selectors. Otherwise it would be collapsed.\n */\n/** Anything other than type (element) or universal, which must come first */\nconst nonElementRegex = /^[.#:[]/;\nexport interface CompoundSelector {\n type: 'CompoundSelector';\n shortType: 'compound';\n}\nexport class CompoundSelector extends Selector<SimpleSelector[], any, CompoundSelectorChildData> {\n static override childKeys = ['value'] as const;\n\n value!: SimpleSelector[];\n\n constructor(value: SimpleSelector[], options?: any, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.value = value;\n for (const child of value) {\n if (child instanceof Selector) {\n this.adopt(child);\n }\n }\n }\n\n get length() {\n return this.value.length;\n }\n\n override clone(deep?: boolean): this {\n if (deep) {\n return super.clone(true) as this;\n }\n return this._withValue(this.value) as this;\n }\n\n private _withValue(value: SimpleSelector[]): CompoundSelector {\n const location = Array.isArray(this.location) && this.location.length === 6\n ? this.location as OptionalLocation\n : undefined;\n const node = new (this.constructor as typeof CompoundSelector)(\n [],\n this.options ? { ...this.options } : undefined,\n location,\n this.treeContext\n );\n node.inherit(this);\n node.value = value;\n return node;\n }\n\n override valueOf() {\n let value = this._valueOf;\n if (!value) {\n const components = this.value;\n const preserveGeneratedPseudoOrder = components.some(component =>\n (isNode(component, N.PseudoSelector) && component.generated)\n || isNode(component, N.Ampersand)\n );\n\n if (preserveGeneratedPseudoOrder) {\n value = components.map(component => component.valueOf()).join('');\n this._valueOf = value;\n return value;\n }\n\n const elementSelectors: string[] = [];\n const nonElementSelectors: string[] = [];\n\n const processComponents = (components: SimpleSelector[]) => {\n for (const component of components) {\n if (\n isNode(component, N.PseudoSelector)\n && component.get('name') === ':is'\n && isNode(component.get('arg'), N.CompoundSelector)\n ) {\n processComponents((component.get('arg') as CompoundSelector).get('value'));\n continue;\n }\n value = component.valueOf();\n if (!nonElementRegex.test(value)) {\n elementSelectors.push(value);\n } else {\n nonElementSelectors.push(value);\n }\n }\n };\n processComponents(components);\n\n value = [...elementSelectors, ...nonElementSelectors.sort()].join('');\n this._valueOf = value;\n }\n return value;\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const data = this.get('value', options.context);\n const mark = w.mark();\n for (const item of data) {\n const out = w.capture(() => item.toString(options));\n w.add(out.trim(), item);\n }\n return w.getSince(mark);\n }\n\n override evalNode(context: Context): MaybePromise<CompoundSelector | Selector | Nil> {\n return pipe(\n () => {\n const sel = super.evalNode(context) as CompoundSelector;\n const value = [...sel.get('value', context)];\n let changed = false;\n const maybe = serialForEach(value.map((_, i) => i), (i: number) => {\n const out = value[i]!.eval(context);\n if (isThenable(out)) {\n return (out as Promise<SimpleSelector>).then((res) => {\n if (res !== value[i]) {\n value[i] = res as SimpleSelector;\n changed = true;\n }\n return undefined;\n });\n }\n if ((out as SimpleSelector) !== value[i]) {\n value[i] = out as SimpleSelector;\n changed = true;\n }\n return undefined;\n });\n if (isThenable(maybe)) {\n return (maybe as Promise<void>).then(() => {\n if (changed) {\n return sel === this\n ? this._withValue(value)\n : (() => {\n sel.value = value;\n return sel;\n })();\n }\n return sel;\n });\n }\n if (changed) {\n return sel === this\n ? this._withValue(value)\n : (() => {\n sel.value = value;\n return sel;\n })();\n }\n return sel;\n },\n (sel) => {\n let data: SimpleSelector[] = sel.get('value', context).filter(n => n && !(n instanceof Nil));\n const preserveGeneratedPseudoOrder = data.some(component =>\n (isNode(component, N.PseudoSelector) && component.generated)\n || isNode(component, N.Ampersand)\n );\n if (!preserveGeneratedPseudoOrder) {\n data = data.sort((a: SimpleSelector, b: SimpleSelector) => {\n let aIsElement = !nonElementRegex.test(a.valueOf());\n let bIsElement = !nonElementRegex.test(b.valueOf());\n if (aIsElement && bIsElement) {\n return a.valueOf() < b.valueOf() ? -1 : 1;\n }\n return aIsElement ? -1 : bIsElement ? 1 : 0;\n });\n }\n if (data.length === 0) {\n return (new Nil()).inherit(this);\n }\n if (data.length === 1) {\n return data[0]!.inherit(this) as Selector;\n }\n const nextValue = [...data];\n return sel === this\n ? this._withValue(nextValue)\n : (() => {\n sel.value = nextValue;\n return sel;\n })();\n }\n );\n }\n}\n\nexport const compound = defineType(CompoundSelector, 'CompoundSelector', 'compound');\n","import { type Combinator } from './combinator.js';\nimport { type Ampersand } from './ampersand.js';\nimport {\n defineType,\n type OptionalLocation\n} from './node.js';\nimport type { Context } from '../context.js';\nimport { type Nil } from './nil.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { Selector } from './selector.js';\nimport type { SimpleSelector } from './selector-simple.js';\nimport type { CompoundSelector } from './selector-compound.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, pipe, isThenable, serialForEach } from '@jesscss/awaitable-pipe';\n\n// TODO - fix later\nexport type ComplexSelectorComponent = SimpleSelector | CompoundSelector | Combinator | Ampersand;\n// type SelectorValue = Component[]\nexport type ComplexSelectorValue = ComplexSelectorComponent[];\n\nexport type ComplexSelectorChildData = { value: ComplexSelectorValue };\n\n/**\n * Selectors with combinators.\n *\n * @example\n * #id > .class.class\n *\n * @note A complex selector may not always start with a selector. We also use this for a\n * relative selector, which means it may start with a combinator.\n */\nexport interface ComplexSelector {\n type: 'ComplexSelector';\n shortType: 'sel';\n}\nexport class ComplexSelector extends Selector<ComplexSelectorValue, any, ComplexSelectorChildData> {\n static override childKeys = ['value'] as const;\n\n value!: ComplexSelectorValue;\n\n constructor(value: ComplexSelectorValue, options?: any, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.value = value;\n for (const child of value) {\n if (child instanceof Selector) {\n this.adopt(child);\n }\n }\n }\n\n get length() {\n return this.value.length;\n }\n\n override clone(deep?: boolean): this {\n if (deep) {\n return super.clone(true) as this;\n }\n return this._withValue(this.value) as this;\n }\n\n private _withValue(value: ComplexSelectorValue): ComplexSelector {\n const location = Array.isArray(this.location) && this.location.length === 6\n ? this.location as OptionalLocation\n : undefined;\n const node = new (this.constructor as typeof ComplexSelector)(\n [],\n this.options ? { ...this.options } : undefined,\n location,\n this.treeContext\n );\n node.inherit(this);\n node.value = value;\n return node;\n }\n\n override valueOf() {\n const value = Array.isArray(this.value)\n ? this.value\n : [this.value as unknown as ComplexSelectorComponent];\n return (this._valueOf ??= value.map(n => n.valueOf()).join(''));\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const value = this.get('value', options.context);\n let length = value.length;\n const mark = w.mark();\n for (let i = 0; i < length; i++) {\n let component = value[i]!;\n /** Add some combinator spacing */\n if (isNode(component, N.Combinator)) {\n /** Skip spacing if the previous node is a Nil */\n if (isNode(value[i - 1], N.Nil)) {\n continue;\n }\n let co = component.value;\n if (co !== ' ') {\n let out = w.capture(() => component.toString(options));\n if (out !== '|') {\n w.add(` ${out.trim()} `, component);\n } else {\n w.add(out.trim(), component);\n }\n } else {\n let out = w.capture(() => component.toString(options));\n w.add(` ${out.trim()}`, component);\n }\n } else {\n let out = w.capture(() => component.toString(options));\n w.add(out.trim(), component);\n }\n }\n return w.getSince(mark);\n }\n\n override evalNode(context: Context): MaybePromise<Selector | Nil> {\n return pipe(\n () => {\n const selector = super.evalNode(context) as ComplexSelector;\n const value = [...selector.get('value', context)];\n let changed = false;\n const maybe = serialForEach(value.map((_, i) => i), (i: number) => {\n const out = value[i]!.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Selector | Nil>).then((res) => {\n if (res !== value[i]) {\n value[i] = res as ComplexSelectorComponent;\n changed = true;\n }\n return undefined;\n });\n }\n if ((out as ComplexSelectorComponent) !== value[i]) {\n value[i] = out as ComplexSelectorComponent;\n changed = true;\n }\n return undefined;\n });\n if (isThenable(maybe)) {\n return (maybe as Promise<void>).then(() => {\n if (changed) {\n return selector === this\n ? this._withValue(value)\n : (() => {\n selector.value = value;\n return selector;\n })();\n }\n return selector;\n });\n }\n if (changed) {\n return selector === this\n ? this._withValue(value)\n : (() => {\n selector.value = value;\n return selector;\n })();\n }\n return selector;\n },\n (selector) => {\n const value = selector.get('value', context);\n if (value.length === 1) {\n const originalOnly = value[0]!;\n const only = originalOnly.clone();\n only.inherit(selector);\n if (selector.hoistToRoot || this.hoistToRoot || only.hoistToRoot) {\n only.hoistToRoot = true;\n }\n return only;\n }\n return selector;\n }\n );\n }\n}\n\ntype SelectorParams = ConstructorParameters<typeof ComplexSelector>;\n\nexport const sel = defineType<ComplexSelectorValue>(ComplexSelector, 'ComplexSelector', 'sel') as (\n value: ComplexSelectorValue,\n options?: SelectorParams[1],\n location?: SelectorParams[2],\n treeContext?: SelectorParams[3]\n) => ComplexSelector;\n","import { default as OriginalBitSet } from 'bitset';\n\nexport class BitSet<T = unknown> extends OriginalBitSet {\n _library: BitSetLibrary<T> | undefined;\n\n override or(other: BitSet<T>): BitSet<T> {\n let set = super.or(other) as BitSet<T>;\n set._library = this._library;\n return set;\n }\n\n override clone(): BitSet<T> {\n let set: any = new BitSet<T>();\n /**\n * Clone like the regular bitset does but preserve this as the constructor.\n * Otherwise cloned objects won't preserve the library reference.\n */\n set.data = (this as any).data.slice();\n set._ = (this as any)._;\n set._library = this._library;\n return set;\n }\n\n override and(other: BitSet<T>): BitSet<T> {\n let set = super.and(other) as BitSet<T>;\n set._library = this._library;\n return set;\n }\n\n override xor(other: BitSet<T>): BitSet<T> {\n let set = super.xor(other) as BitSet<T>;\n set._library = this._library;\n return set;\n }\n\n override not(): BitSet<T> {\n let set = super.not() as BitSet<T>;\n set._library = this._library;\n return set;\n }\n}\n\nexport class BitSetLibrary<T = unknown> {\n private _bitset: BitSet<T>;\n /** Value to Bitset position map */\n private _values = new Map<T, number>();\n /** Bitset position to value map */\n private _positions: T[] = [];\n\n constructor(values?: T[]) {\n this._bitset = new BitSet();\n this._bitset._library = this;\n if (values) {\n for (let i = 0; i < values.length; i++) {\n this._values.set(values[i]!, i);\n this._bitset.set(i, 0);\n }\n }\n }\n\n get size() {\n return this._values.size;\n }\n\n /** Returns position */\n add(value: T): number {\n let values = this._values;\n let pos = values.get(value);\n if (pos !== undefined) {\n return pos;\n }\n pos = this.size;\n values.set(value, pos);\n this._positions[pos] = value;\n this._bitset.set(pos, 0);\n return pos;\n }\n\n has(value: T) {\n return this._values.has(value);\n }\n\n /** Get Bitset from an iterable of values */\n getBitset(values?: Iterable<T>): BitSet<T> {\n let bitset = this._bitset.clone();\n if (values) {\n for (const value of values) {\n let pos = this.add(value);\n bitset.set(pos, 1);\n }\n }\n return bitset;\n }\n\n getValue(position: number): T | undefined {\n return this._positions[position];\n }\n\n hasBit(bitset: BitSet<T>, value: T): boolean {\n if (bitset._library !== this) {\n throw new Error('Bitset must be from this library');\n }\n const pos = this._values.get(value);\n return pos !== undefined ? Boolean(bitset.get(pos)) : false;\n }\n\n forEachValue(bitset: BitSet<T>, fn: (value: T, position: number) => void): void {\n if (bitset._library !== this) {\n throw new Error('Bitset must be from this library');\n }\n\n const data = (bitset as { data?: number[] }).data;\n if (!data) {\n return;\n }\n\n for (let wordIndex = 0; wordIndex < data.length; wordIndex++) {\n let word = data[wordIndex]! >>> 0;\n while (word !== 0) {\n const lowestBit = word & -word;\n const bitIndex = 31 - Math.clz32(lowestBit);\n const position = (wordIndex * 32) + bitIndex;\n const value = this._positions[position];\n if (value !== undefined) {\n fn(value, position);\n }\n word &= word - 1;\n }\n }\n }\n\n valuesOf(bitset: BitSet<T>): T[] {\n const values: T[] = [];\n this.forEachValue(bitset, (value) => {\n values.push(value);\n });\n return values;\n }\n}\n\n/**\n * All bits in a that are true must be true in b\n*/\nexport function isSubsetOf(a: BitSet, b: BitSet): boolean {\n if (a._library !== b._library) {\n throw new Error('Bitsets must be from the same library');\n }\n\n const aInternal = a as { data?: number[]; _?: number };\n const bInternal = b as { data?: number[]; _?: number };\n if (aInternal._ || bInternal._) {\n return a.and(b).equals(a);\n }\n\n const aData = aInternal.data;\n const bData = bInternal.data;\n if (!aData) {\n return true;\n }\n\n for (let i = 0; i < aData.length; i++) {\n const aWord = aData[i] ?? 0;\n if (!aWord) {\n continue;\n }\n\n const bWord = bData?.[i] ?? 0;\n if ((aWord & ~bWord) !== 0) {\n return false;\n }\n }\n\n return true;\n}\n\n/** True when `a` and `b` share no set bits. */\nexport function isDisjoint(a: BitSet, b: BitSet): boolean {\n if (a._library !== b._library) {\n throw new Error('Bitsets must be from the same library');\n }\n const intersection = a.and(b) as BitSet;\n const data = (intersection as { data?: number[] }).data;\n if (!data) {\n return true;\n }\n\n for (let i = 0; i < data.length; i++) {\n if (data[i]) {\n return false;\n }\n }\n\n return true;\n}\n","import { Selector } from '../selector.js';\nimport { SelectorList } from '../selector-list.js';\nimport { F_AMPERSAND, type Node } from '../node.js';\nimport type { Context as EvalContext } from '../../context.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport { isDisjoint, type BitSet } from './bitset.js';\nimport { type PseudoSelector } from '../selector-pseudo.js';\nimport { type CompoundSelector } from '../selector-compound.js';\nimport { type ComplexSelector } from '../selector-complex.js';\n\n/**\n * A single located selector match.\n *\n * `startIndex` / `endIndex` are measured in the `containingNode`'s local\n * ordered data when the containing node is ordered.\n *\n * `exact` means the matched route consumed its span end-to-end without extra\n * unmatched basic selectors on that route.\n *\n * `crossesAmpersand` is set on synthetic cross-boundary matches completed\n * through a parent selector context.\n *\n * `consumedTarget` means this location matched everything it could possibly\n * match in its target container. This is distinct from route-level\n * `fullMatch`, which only means one exact match route succeeded.\n */\ninterface SelectorMatchLocation {\n startIndex?: number;\n endIndex?: number;\n matchedIndices?: number[];\n containingNode: Node;\n exact?: boolean;\n crossesAmpersand?: boolean;\n consumedTarget?: boolean;\n ampersandCrossings?: SelectorMatchAmpersandCrossing[];\n}\n\ninterface SelectorMatchSegment {\n containingNode: Node;\n startIndex?: number;\n endIndex?: number;\n matchedIndices?: number[];\n}\n\ninterface SelectorMatchAmpersandCrossing {\n ampersandNode?: Node;\n targetSegment: SelectorMatchSegment;\n parentSegment?: SelectorMatchSegment;\n}\n\n/**\n * Aggregate selector-match result.\n *\n * `fullMatch` means at least one exact end-to-end route matched.\n * `partialMatch` means at least one match of any kind was found.\n * `crossesAmpersand` means at least one recorded match crossed an ampersand\n * boundary instead of matching entirely on one side of it.\n */\ninterface SelectorMatchState {\n fullMatch: boolean;\n partialMatch: boolean;\n crossesAmpersand: boolean;\n matches: SelectorMatchLocation[];\n}\n\n/** The set of basic selectors that one unordered position can satisfy. */\ntype MatchGroupRequirement = {\n basicSelectorIndex: Map<string, number>;\n basicSelectorCounts: number[];\n basicSelectorTotal: number;\n hasComplexBranch: boolean;\n branchTailAmbiguous: boolean;\n};\n\n/** One position can satisfy any one of its alternatives, such as `:is(...)`. */\ntype MatchGroup = {\n alternatives: MatchGroupRequirement[];\n};\n\n/** One ordered unit in a route-level match plan. */\ntype MatchPlanUnit =\n | {\n kind: 'group';\n index: number;\n node: Node;\n group: MatchGroup;\n }\n | {\n kind: 'combinator';\n index: number;\n node: Node;\n value: string;\n };\n\ntype RouteMatchPlan = {\n kind: 'route';\n selector: Selector;\n units: MatchPlanUnit[];\n hasAmbiguousBranchTail: boolean;\n};\n\ntype SelectorListMatchPlan = {\n kind: 'list';\n selector: SelectorList;\n alternates: MatchPlan[];\n};\n\ntype MatchPlan = RouteMatchPlan | SelectorListMatchPlan;\n\ntype MatchGroupState = {\n remainingCounts: number[];\n remainingTotal: number;\n exact: boolean;\n matchedOutsideAmpersand: boolean;\n};\n\ntype MatchWindowResult = {\n matched: boolean;\n exact: boolean;\n};\n\ntype GroupMatchCache = WeakMap<Node, WeakMap<MatchGroup, MatchWindowResult>>;\ntype SelectorMatchPairCache = WeakMap<Selector, WeakMap<Selector, SelectorMatchState>>;\ntype SelectorMatchContext = {\n pairCache: SelectorMatchPairCache;\n evalContext?: EvalContext;\n};\n\nconst selectorMatchPlanCache = new WeakMap<Selector, {\n value: string;\n plan: MatchPlan;\n}>();\n\nfunction selectorValueOf(node: Node | Selector, context?: EvalContext): string {\n return String((node as unknown as { valueOf(context?: EvalContext): string }).valueOf(context));\n}\n\nfunction bitSetValues(bitSet: BitSet<string> | undefined): string[] | undefined {\n return bitSet?._library?.valuesOf(bitSet);\n}\n\nfunction safeIsDisjoint(\n left: BitSet<string> | undefined,\n right: BitSet<string> | undefined\n): boolean {\n if (!left || !right) {\n return false;\n }\n if (left._library && right._library && left._library === right._library) {\n return isDisjoint(left, right);\n }\n const leftValues = bitSetValues(left);\n const rightValues = bitSetValues(right);\n if (!leftValues || !rightValues) {\n return false;\n }\n const rightSet = new Set(rightValues);\n for (const value of leftValues) {\n if (rightSet.has(value)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns true for pseudos whose selector arguments can be searched recursively\n * but cannot be consumed as part of a continuing outer match, unlike `:is()`.\n */\nfunction isSearchablePseudoBoundary(node: Node): node is PseudoSelector {\n return (\n isNode(node, N.PseudoSelector)\n && node.get('name') !== ':is'\n && isNode(node.get('arg'), N.Selector)\n );\n}\n\nfunction createRequirement(): MatchGroupRequirement {\n const basicSelectorIndex = new Map<string, number>();\n const basicSelectorCounts: number[] = [];\n\n return {\n basicSelectorIndex,\n basicSelectorCounts,\n basicSelectorTotal: 0,\n hasComplexBranch: false,\n branchTailAmbiguous: false\n };\n}\n\nfunction addRequirementValue(requirement: MatchGroupRequirement, value: string): MatchGroupRequirement {\n const existingIndex = requirement.basicSelectorIndex.get(value);\n if (existingIndex !== undefined) {\n requirement.basicSelectorCounts[existingIndex]!++;\n requirement.basicSelectorTotal++;\n return requirement;\n }\n\n requirement.basicSelectorIndex.set(value, requirement.basicSelectorCounts.length);\n requirement.basicSelectorCounts.push(1);\n requirement.basicSelectorTotal++;\n return requirement;\n}\n\nfunction cloneRequirement(requirement: MatchGroupRequirement): MatchGroupRequirement {\n return {\n basicSelectorIndex: new Map(requirement.basicSelectorIndex),\n basicSelectorCounts: [...requirement.basicSelectorCounts],\n basicSelectorTotal: requirement.basicSelectorTotal,\n hasComplexBranch: requirement.hasComplexBranch,\n branchTailAmbiguous: requirement.branchTailAmbiguous\n };\n}\n\nfunction mergeRequirements(\n left: MatchGroupRequirement,\n right: MatchGroupRequirement\n): MatchGroupRequirement {\n const merged = cloneRequirement(left);\n for (const [value, index] of right.basicSelectorIndex.entries()) {\n const count = right.basicSelectorCounts[index] ?? 0;\n for (let i = 0; i < count; i++) {\n addRequirementValue(merged, value);\n }\n }\n merged.hasComplexBranch ||= right.hasComplexBranch;\n merged.branchTailAmbiguous ||= right.branchTailAmbiguous;\n return merged;\n}\n\nfunction markComplexBranchRequirements(\n requirements: MatchGroupRequirement[],\n branch: Selector & { value?: readonly Node[] },\n parent?: Selector,\n context?: EvalContext\n): MatchGroupRequirement[] {\n const earlierValues = new Set<string>();\n\n if (isNode(branch, N.ComplexSelector)) {\n for (let i = 0; i < (branch as ComplexSelector).get('value').length - 1; i++) {\n const component = (branch as ComplexSelector).get('value')[i]!;\n const nested = buildGroupRequirements(component, parent, context);\n for (let j = 0; j < nested.length; j++) {\n for (const value of nested[j]!.basicSelectorIndex.keys()) {\n earlierValues.add(value);\n }\n }\n }\n }\n\n for (let i = 0; i < requirements.length; i++) {\n const requirement = requirements[i]!;\n requirement.hasComplexBranch = true;\n for (const value of requirement.basicSelectorIndex.keys()) {\n if (earlierValues.has(value)) {\n requirement.branchTailAmbiguous = true;\n break;\n }\n }\n }\n\n return requirements;\n}\n\nfunction buildGroupRequirements(\n node: Node,\n parent?: Selector,\n context?: EvalContext,\n activePath: Set<Node> = new Set()\n): MatchGroupRequirement[] {\n if (activePath.has(node)) {\n return [createRequirement()];\n }\n activePath.add(node);\n\n if (isNode(node, N.BasicSelector)) {\n const requirement = createRequirement();\n addRequirementValue(requirement, selectorValueOf(node, context));\n activePath.delete(node);\n return [requirement];\n }\n\n if (isNode(node, N.Ampersand)) {\n const resolved = node.getResolvedSelector(context) ?? parent;\n if (resolved && !isNode(resolved, N.Nil)) {\n if (activePath.has(resolved)) {\n activePath.delete(node);\n return [createRequirement()];\n }\n const result = buildGroupRequirements(resolved, parent, context, activePath);\n activePath.delete(node);\n return result;\n }\n\n activePath.delete(node);\n return [createRequirement()];\n }\n\n if (isNode(node, N.ComplexSelector)) {\n for (let i = (node as ComplexSelector).get('value').length - 1; i >= 0; i--) {\n const component = (node as ComplexSelector).get('value')[i]!;\n if (!isNode(component, N.Combinator)) {\n return markComplexBranchRequirements(\n buildGroupRequirements(component, parent, context, activePath),\n node as unknown as Selector & { value?: readonly Node[] },\n parent,\n context\n );\n }\n }\n\n activePath.delete(node);\n return [createRequirement()];\n }\n\n if (isNode(node, N.PseudoSelector) && node.get('name') !== ':is') {\n const requirement = createRequirement();\n addRequirementValue(requirement, selectorValueOf(node, context));\n activePath.delete(node);\n return [requirement];\n }\n\n if (isSearchablePseudoBoundary(node)) {\n activePath.delete(node);\n return [createRequirement()];\n }\n\n if (isNode(node, N.SelectorList)) {\n const alternatives: MatchGroupRequirement[] = [];\n for (let i = 0; i < (node as SelectorList).get('value').length; i++) {\n const nested = buildGroupRequirements((node as SelectorList).get('value')[i]!, parent, context, activePath);\n for (let j = 0; j < nested.length; j++) {\n alternatives.push(nested[j]!);\n }\n }\n activePath.delete(node);\n return alternatives;\n }\n\n let requirements: MatchGroupRequirement[] = [createRequirement()];\n const children = node.children();\n let child = children.next();\n\n while (!child.done) {\n const childRequirements = buildGroupRequirements(child.value, parent, context, activePath);\n const nextRequirements: MatchGroupRequirement[] = [];\n for (let i = 0; i < requirements.length; i++) {\n for (let j = 0; j < childRequirements.length; j++) {\n nextRequirements.push(\n mergeRequirements(requirements[i]!, childRequirements[j]!)\n );\n }\n }\n requirements = nextRequirements;\n child = children.next();\n }\n\n activePath.delete(node);\n return requirements;\n}\n\nfunction buildMatchGroup(node: Node, parent?: Selector, context?: EvalContext): MatchGroup {\n return {\n alternatives: buildGroupRequirements(node, parent, context)\n };\n}\n\nfunction buildRouteMatchPlan(selector: Selector, parent?: Selector, context?: EvalContext): RouteMatchPlan {\n if (isNode(selector, N.ComplexSelector)) {\n const units: MatchPlanUnit[] = [];\n let hasAmbiguousBranchTail = false;\n\n for (let i = 0; i < (selector as ComplexSelector).get('value').length; i++) {\n const component = (selector as ComplexSelector).get('value')[i]!;\n if (isNode(component, N.Combinator)) {\n units.push({\n kind: 'combinator',\n index: i,\n node: component,\n value: selectorValueOf(component, context)\n });\n continue;\n }\n\n const group = buildMatchGroup(\n component,\n isNode(component, N.Ampersand) && i === 0 ? undefined : parent,\n context\n );\n const hasAlternatives = group.alternatives.some(alternate => alternate.basicSelectorTotal > 0);\n if (hasAlternatives) {\n hasAmbiguousBranchTail ||= group.alternatives.some(alternate => alternate.branchTailAmbiguous);\n units.push({\n kind: 'group',\n index: i,\n node: component,\n group\n });\n }\n }\n\n return {\n kind: 'route',\n selector,\n units,\n hasAmbiguousBranchTail\n };\n }\n\n if (isNode(selector, N.Combinator)) {\n return {\n kind: 'route',\n selector,\n hasAmbiguousBranchTail: false,\n units: [{\n kind: 'combinator',\n index: 0,\n node: selector,\n value: selectorValueOf(selector, context)\n }]\n };\n }\n\n const group = buildMatchGroup(selector, parent, context);\n return {\n kind: 'route',\n selector,\n hasAmbiguousBranchTail: group.alternatives.some(alternate => alternate.branchTailAmbiguous),\n units: group.alternatives.some(alternate => alternate.basicSelectorTotal > 0)\n ? [{\n kind: 'group',\n index: 0,\n node: selector,\n group\n }]\n : []\n };\n}\n\nfunction buildMatchPlan(selector: Selector, parent?: Selector, context?: EvalContext): MatchPlan {\n if (isNode(selector, N.SelectorList)) {\n return {\n kind: 'list',\n selector,\n alternates: (selector as SelectorList).get('value').map(item => getSelectorMatchPlan(item, parent, context))\n };\n }\n\n return buildRouteMatchPlan(selector, parent, context);\n}\n\nfunction getSelectorMatchPlan(selector: Selector, parent?: Selector, context?: EvalContext): MatchPlan {\n if (parent || context) {\n return buildMatchPlan(selector, parent, context);\n }\n\n const value = selectorValueOf(selector);\n const cached = selectorMatchPlanCache.get(selector);\n if (cached && cached.value === value) {\n return cached.plan;\n }\n\n const plan = buildMatchPlan(selector);\n selectorMatchPlanCache.set(selector, { value, plan });\n return plan;\n}\n\nfunction cloneGroupStates(states: MatchGroupState[]): MatchGroupState[] {\n const nextStates = new Array<MatchGroupState>(states.length);\n for (let i = 0; i < states.length; i++) {\n const state = states[i]!;\n nextStates[i] = {\n remainingCounts: [...state.remainingCounts],\n remainingTotal: state.remainingTotal,\n exact: state.exact,\n matchedOutsideAmpersand: state.matchedOutsideAmpersand\n };\n }\n return nextStates;\n}\n\nfunction allStatesAreTerminalPartial(states: MatchGroupState[]): boolean {\n for (let i = 0; i < states.length; i++) {\n const state = states[i]!;\n if (state.remainingTotal > 0 || state.exact) {\n return false;\n }\n }\n return true;\n}\n\nfunction consumeGroupBasics(\n node: Node,\n group: MatchGroupRequirement,\n states: MatchGroupState[],\n insideAmpersand = false,\n parent?: Selector,\n context?: EvalContext,\n activePath: Set<Node> = new Set()\n): MatchGroupState[] {\n if (states.length === 0) {\n return states;\n }\n\n if (activePath.has(node)) {\n return states;\n }\n activePath.add(node);\n\n if (isNode(node, N.BasicSelector) || (isNode(node, N.PseudoSelector) && node.get('name') !== ':is')) {\n const idx = group.basicSelectorIndex.get(selectorValueOf(node, context));\n\n for (let i = 0; i < states.length; i++) {\n const state = states[i]!;\n\n if (state.remainingTotal === 0 && !state.exact) {\n continue;\n }\n\n if (idx === undefined || state.remainingCounts[idx] === 0) {\n state.exact = false;\n continue;\n }\n\n state.remainingCounts[idx]!--;\n state.remainingTotal--;\n if (!insideAmpersand) {\n state.matchedOutsideAmpersand = true;\n }\n }\n\n activePath.delete(node);\n return states;\n }\n\n if (isNode(node, N.Ampersand)) {\n const resolved = node.getResolvedSelector(context) ?? parent;\n if (resolved && !isNode(resolved, N.Nil)) {\n if (activePath.has(resolved)) {\n activePath.delete(node);\n return states;\n }\n const result = consumeGroupBasics(resolved, group, states, true, parent, context, activePath);\n activePath.delete(node);\n return result;\n }\n\n activePath.delete(node);\n return states;\n }\n\n if (isSearchablePseudoBoundary(node)) {\n activePath.delete(node);\n return states;\n }\n\n if (isNode(node, N.SelectorList)) {\n const alternates = node.children();\n const routes = [alternates.mark()];\n const nextStates: MatchGroupState[] = [];\n\n while (routes.length > 0) {\n alternates.restore(routes.pop()!);\n const alternate = alternates.next();\n\n if (alternate.done) {\n continue;\n }\n\n routes.push(alternates.mark());\n\n nextStates.push(\n ...consumeGroupBasics(\n alternate.value,\n group,\n cloneGroupStates(states),\n insideAmpersand,\n parent,\n context,\n activePath\n )\n );\n }\n\n activePath.delete(node);\n return nextStates;\n }\n\n const children = node.children();\n let nextStates = states;\n let child = children.next();\n\n while (!child.done && nextStates.length > 0 && !allStatesAreTerminalPartial(nextStates)) {\n nextStates = consumeGroupBasics(child.value, group, nextStates, insideAmpersand, parent, context, activePath);\n child = children.next();\n }\n\n activePath.delete(node);\n return nextStates;\n}\n\n/** Summarizes a set of consume-states with a single pass. */\nfunction summarizeStates(states: MatchGroupState[]): MatchWindowResult {\n let matched = false;\n let exact = false;\n\n for (let i = 0; i < states.length; i++) {\n const state = states[i]!;\n if (state.remainingTotal !== 0 || !state.matchedOutsideAmpersand) {\n continue;\n }\n\n matched = true;\n if (state.exact) {\n exact = true;\n break;\n }\n }\n\n return { matched, exact };\n}\n\n/**\n * Matches a single unordered target position against one match group.\n *\n * This is the core \"consume basics within a position\" operation used by\n * route-level matching.\n */\nfunction matchTargetGroup(\n targetGroup: Node,\n findGroup: MatchGroup,\n parent?: Selector,\n allowAmpersandOnlyMatch = false,\n context?: EvalContext\n): MatchWindowResult {\n let matched = false;\n let exact = false;\n\n for (let i = 0; i < findGroup.alternatives.length; i++) {\n const requirement = findGroup.alternatives[i]!;\n const states = consumeGroupBasics(targetGroup, requirement, [{\n remainingCounts: [...requirement.basicSelectorCounts],\n remainingTotal: requirement.basicSelectorTotal,\n exact: true,\n matchedOutsideAmpersand: false\n }], false, parent, context);\n const summary = summarizeStates(states);\n if (!summary.matched && allowAmpersandOnlyMatch) {\n for (let j = 0; j < states.length; j++) {\n const state = states[j]!;\n if (state.remainingTotal !== 0) {\n continue;\n }\n\n summary.matched = true;\n if (state.exact) {\n summary.exact = true;\n break;\n }\n }\n }\n\n matched ||= summary.matched;\n exact ||= summary.exact && !requirement.hasComplexBranch;\n\n if (exact) {\n break;\n }\n }\n\n return { matched, exact };\n}\n\nfunction matchCompoundWindow(\n targetCompound: Selector & { value: readonly Node[] },\n start: number,\n end: number,\n requirement: MatchGroupRequirement,\n parent?: Selector,\n context?: EvalContext\n): MatchWindowResult {\n let states = [{\n remainingCounts: [...requirement.basicSelectorCounts],\n remainingTotal: requirement.basicSelectorTotal,\n exact: true,\n matchedOutsideAmpersand: false\n }];\n\n for (let i = start; i <= end && states.length > 0 && !allStatesAreTerminalPartial(states); i++) {\n states = consumeGroupBasics(targetCompound.value[i]!, requirement, states, false, parent, context);\n }\n\n const summary = summarizeStates(states);\n if (!summary.matched && parent) {\n let allAmpersands = true;\n for (let i = start; i <= end; i++) {\n if (!isNode(targetCompound.value[i]!, N.Ampersand)) {\n allAmpersands = false;\n break;\n }\n }\n\n if (allAmpersands) {\n for (let i = 0; i < states.length; i++) {\n const state = states[i]!;\n if (state.remainingTotal !== 0) {\n continue;\n }\n summary.matched = true;\n if (state.exact) {\n summary.exact = true;\n break;\n }\n }\n }\n }\n if (requirement.hasComplexBranch) {\n summary.exact = false;\n }\n return summary;\n}\n\nfunction collectMatchedIndicesForWindow(\n targetCompound: Selector & { value: readonly Node[] },\n start: number,\n end: number,\n requirement: MatchGroupRequirement,\n context?: EvalContext\n): number[] | undefined {\n const remainingCounts = [...requirement.basicSelectorCounts];\n const matchedIndices: number[] = [];\n\n for (let i = start; i <= end; i++) {\n const node = targetCompound.value[i]!;\n if (!isNode(node, N.BasicSelector) && !(isNode(node, N.PseudoSelector) && node.get('name') !== ':is')) {\n continue;\n }\n\n const idx = requirement.basicSelectorIndex.get(selectorValueOf(node, context));\n if (idx === undefined || remainingCounts[idx] === 0) {\n continue;\n }\n\n remainingCounts[idx]!--;\n matchedIndices.push(i);\n }\n\n if (matchedIndices.length === 0) {\n return undefined;\n }\n\n const spanLength = end - start + 1;\n if (matchedIndices.length === spanLength) {\n return undefined;\n }\n\n return matchedIndices;\n}\n\n/**\n * Collects every group-local span match for a target node.\n *\n * For compounds this scans contiguous windows so repeated matches in the same\n * compound are reported independently.\n *\n * @todo This is still the hottest path in selector matching. It currently\n * scans O(n^2) spans and may re-run `matchCompoundWindow()` for the same\n * requirement to prove minimality (`withoutStartMatches` / `withoutEndMatches`).\n * If this becomes a measurable bottleneck, replace the brute-force span scan\n * with a requirement-aware sliding window or prefix-count index that can:\n * 1. detect whether a span satisfies the requirement,\n * 2. prove minimality without rescanning adjacent subspans, and\n * 3. still preserve current semantics for extras-inside-span, matchedIndices,\n * branch-tail ambiguity, and repeated independent matches in one compound.\n */\nfunction collectGroupMatchLocations(\n targetGroup: Node,\n findGroup: MatchGroup,\n parent?: Selector,\n context?: EvalContext\n): SelectorMatchLocation[] {\n if (!isNode(targetGroup, N.CompoundSelector)) {\n const groupMatch = matchTargetGroup(\n targetGroup,\n findGroup,\n parent,\n !!parent && isNode(targetGroup, N.Ampersand),\n context\n );\n return groupMatch.matched\n ? [{\n startIndex: 0,\n endIndex: 0,\n containingNode: targetGroup,\n exact: groupMatch.exact,\n consumedTarget: groupMatch.exact\n }]\n : [];\n }\n\n const matches: SelectorMatchLocation[] = [];\n const seen = new Set<number>();\n const targetCompound = targetGroup as unknown as Selector & { value: readonly Node[] };\n const targetLength = (targetGroup as CompoundSelector).get('value').length;\n\n for (let i = 0; i < findGroup.alternatives.length; i++) {\n const requirement = findGroup.alternatives[i]!;\n for (let start = 0; start < targetLength; start++) {\n for (let end = start; end < targetLength; end++) {\n const windowMatch = matchCompoundWindow(\n targetCompound,\n start,\n end,\n requirement,\n parent,\n context\n );\n\n if (!windowMatch.matched) {\n continue;\n }\n\n const withoutStartMatches = start < end\n && matchCompoundWindow(targetCompound, start + 1, end, requirement, parent, context).matched;\n if (withoutStartMatches) {\n continue;\n }\n\n const withoutEndMatches = start < end\n && matchCompoundWindow(targetCompound, start, end - 1, requirement, parent, context).matched;\n if (withoutEndMatches) {\n continue;\n }\n\n const key = start * targetLength + end;\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n\n matches.push({\n startIndex: start,\n endIndex: end,\n matchedIndices: collectMatchedIndicesForWindow(targetCompound, start, end, requirement, context),\n containingNode: targetGroup,\n exact: windowMatch.exact && start === 0 && end === targetLength - 1,\n consumedTarget: windowMatch.exact && start === 0 && end === targetLength - 1\n });\n }\n }\n }\n\n matches.sort((left, right) => {\n const leftStart = left.startIndex ?? 0;\n const rightStart = right.startIndex ?? 0;\n if (leftStart !== rightStart) {\n return leftStart - rightStart;\n }\n\n const leftEnd = left.endIndex ?? leftStart;\n const rightEnd = right.endIndex ?? rightStart;\n return leftEnd - rightEnd;\n });\n\n const filtered: SelectorMatchLocation[] = [];\n let lastEnd = -1;\n for (let i = 0; i < matches.length; i++) {\n const match = matches[i]!;\n const start = match.startIndex ?? 0;\n const end = match.endIndex ?? start;\n\n if (start <= lastEnd) {\n continue;\n }\n\n filtered.push(match);\n lastEnd = end;\n }\n\n return filtered;\n}\n\n/** Fast constructor for the no-match result shape. */\nfunction emptySelectorMatchState(): SelectorMatchState {\n return {\n fullMatch: false,\n partialMatch: false,\n crossesAmpersand: false,\n matches: []\n };\n}\n\n/** Appends one result list into another without allocating a combined array. */\nfunction pushMatches(\n target: SelectorMatchLocation[],\n source: SelectorMatchLocation[]\n): void {\n for (let i = 0; i < source.length; i++) {\n target.push(source[i]!);\n }\n}\n\nfunction cloneMatchSegment(\n segment: SelectorMatchSegment | undefined\n): SelectorMatchSegment | undefined {\n if (!segment) {\n return undefined;\n }\n\n return {\n containingNode: segment.containingNode,\n startIndex: segment.startIndex,\n endIndex: segment.endIndex,\n matchedIndices: segment.matchedIndices ? [...segment.matchedIndices] : undefined\n };\n}\n\nfunction cloneAmpersandCrossings(\n crossings: SelectorMatchAmpersandCrossing[] | undefined\n): SelectorMatchAmpersandCrossing[] | undefined {\n if (!crossings || crossings.length === 0) {\n return undefined;\n }\n\n const next = new Array<SelectorMatchAmpersandCrossing>(crossings.length);\n for (let i = 0; i < crossings.length; i++) {\n const crossing = crossings[i]!;\n next[i] = {\n ampersandNode: crossing.ampersandNode,\n targetSegment: cloneMatchSegment(crossing.targetSegment)!,\n parentSegment: cloneMatchSegment(crossing.parentSegment)\n };\n }\n\n return next;\n}\n\nfunction getCachedGroupMatch(\n cache: GroupMatchCache,\n targetGroup: Node,\n findGroup: MatchGroup,\n parent?: Selector,\n evalContext?: EvalContext\n): MatchWindowResult {\n let nodeCache = cache.get(targetGroup);\n if (!nodeCache) {\n nodeCache = new WeakMap<MatchGroup, MatchWindowResult>();\n cache.set(targetGroup, nodeCache);\n }\n\n const cached = nodeCache.get(findGroup);\n if (cached) {\n return cached;\n }\n\n let result: MatchWindowResult;\n if (isNode(targetGroup, N.CompoundSelector)) {\n let matched = false;\n let exact = false;\n\n for (let i = 0; i < findGroup.alternatives.length; i++) {\n const windowMatch = matchCompoundWindow(\n targetGroup as unknown as Selector & { value: readonly Node[] },\n 0,\n (targetGroup as CompoundSelector).get('value').length - 1,\n findGroup.alternatives[i]!,\n parent,\n evalContext\n );\n matched ||= windowMatch.matched;\n exact ||= windowMatch.exact;\n\n if (exact) {\n break;\n }\n }\n\n result = { matched, exact };\n } else {\n result = matchTargetGroup(\n targetGroup,\n findGroup,\n parent,\n !!parent && isNode(targetGroup, N.Ampersand),\n evalContext\n );\n }\n nodeCache.set(findGroup, result);\n return result;\n}\n\nfunction getBranchAlternatives(node: Node): readonly Selector[] | undefined {\n if (isNode(node, N.SelectorList)) {\n return (node as SelectorList).get('value');\n }\n\n if (isNode(node, N.PseudoSelector) && node.get('name') === ':is' && isNode(node.get('arg'), N.Selector)) {\n if (isNode(node.get('arg'), N.SelectorList)) {\n return (node.get('arg') as SelectorList).get('value');\n }\n\n return [node.get('arg') as Selector];\n }\n\n return undefined;\n}\n\nfunction matchGroupNodes(\n findNode: Node,\n targetNode: Node,\n findGroup: MatchGroup,\n groupMatchCache: GroupMatchCache,\n context: SelectorMatchContext,\n parent?: Selector\n): MatchWindowResult {\n const targetBranches = getBranchAlternatives(targetNode);\n const findBranches = getBranchAlternatives(findNode);\n if (targetBranches && findBranches) {\n let matched = false;\n let exact = false;\n\n for (let i = 0; i < findBranches.length; i++) {\n for (let j = 0; j < targetBranches.length; j++) {\n const nested = selectorMatchInternal(findBranches[i]!, targetBranches[j]!, parent, context);\n matched ||= nested.partialMatch;\n exact ||= nested.fullMatch;\n\n if (exact) {\n break;\n }\n }\n\n if (exact) {\n break;\n }\n }\n\n return { matched, exact };\n }\n\n if (targetBranches) {\n let matched = false;\n let exact = false;\n\n for (let i = 0; i < targetBranches.length; i++) {\n const nested = selectorMatchInternal(findNode as Selector, targetBranches[i]!, parent, context);\n matched ||= nested.partialMatch;\n exact ||= nested.fullMatch;\n\n if (exact) {\n break;\n }\n }\n\n return { matched, exact };\n }\n\n return getCachedGroupMatch(groupMatchCache, targetNode, findGroup, parent, context.evalContext);\n}\n\nfunction pushNestedBranchMatches(\n findNode: Node,\n target: Selector,\n matches: SelectorMatchLocation[],\n context: SelectorMatchContext,\n parent?: Selector\n): void {\n const branches = getBranchAlternatives(findNode);\n if (branches) {\n for (let i = 0; i < branches.length; i++) {\n const nested = selectorMatchInternal(target, branches[i]!, parent, context);\n if (!nested.fullMatch) {\n continue;\n }\n for (let j = 0; j < nested.matches.length; j++) {\n const match = nested.matches[j]!;\n matches.push({\n startIndex: match.startIndex,\n endIndex: match.endIndex,\n matchedIndices: match.matchedIndices,\n containingNode: match.containingNode,\n exact: false,\n consumedTarget: match.consumedTarget,\n ampersandCrossings: cloneAmpersandCrossings(match.ampersandCrossings)\n });\n }\n }\n return;\n }\n\n const children = findNode.children();\n let child = children.next();\n while (!child.done) {\n pushNestedBranchMatches(child.value, target, matches, context, parent);\n child = children.next();\n }\n}\n\n/**\n * Compares a contiguous slice of ordered units.\n *\n * Groups compare via unordered basic-selector consumption, while combinators\n * must match exactly in place.\n */\nfunction matchUnitWindow(\n findUnits: MatchPlanUnit[],\n findStart: number,\n targetUnits: MatchPlanUnit[],\n targetStart: number,\n length: number,\n groupMatchCache: GroupMatchCache,\n context: SelectorMatchContext,\n parent?: Selector\n): MatchWindowResult {\n let exact = true;\n\n for (let offset = 0; offset < length; offset++) {\n const findUnit = findUnits[findStart + offset]!;\n const targetUnit = targetUnits[targetStart + offset]!;\n\n if (findUnit.kind !== targetUnit.kind) {\n return { matched: false, exact: false };\n }\n\n if (findUnit.kind === 'combinator') {\n if (targetUnit.kind !== 'combinator' || findUnit.value !== targetUnit.value) {\n return { matched: false, exact: false };\n }\n continue;\n }\n\n const groupMatch = matchGroupNodes(\n findUnit.node,\n targetUnit.node,\n findUnit.group,\n groupMatchCache,\n context,\n parent\n );\n if (!groupMatch.matched) {\n return { matched: false, exact: false };\n }\n\n exact &&= groupMatch.exact;\n }\n\n return { matched: true, exact };\n}\n\n/** True when a complex selector begins with a visible ampersand boundary. */\nfunction hasLeadingAmpersandBoundary(selector: Selector): boolean {\n return (\n isNode(selector, N.ComplexSelector)\n && (selector as ComplexSelector).get('value').length > 0\n && isNode((selector as ComplexSelector).get('value')[0]!, N.Ampersand)\n );\n}\n\nfunction getBoundaryTailUnits(routePlan: RouteMatchPlan): MatchPlanUnit[] {\n if (hasLeadingAmpersandBoundary(routePlan.selector)) {\n return routePlan.units;\n }\n\n return [{\n kind: 'combinator',\n index: -1,\n node: routePlan.selector,\n value: ' '\n }, ...routePlan.units];\n}\n\nfunction locationCrossesAmpersand(location: SelectorMatchLocation): boolean {\n if (location.ampersandCrossings && location.ampersandCrossings.length > 0) {\n return true;\n }\n\n if (location.crossesAmpersand) {\n return true;\n }\n\n const { containingNode, startIndex, endIndex } = location;\n\n if (!containingNode.hasFlag(F_AMPERSAND)) {\n return false;\n }\n\n if (startIndex === undefined || endIndex === undefined) {\n return true;\n }\n\n if (isNode(containingNode, N.CompoundSelector) || isNode(containingNode, N.ComplexSelector)) {\n for (let i = startIndex; i <= endIndex; i++) {\n if (containingNode.get('value')[i]?.hasFlag(F_AMPERSAND)) {\n return true;\n }\n }\n return false;\n }\n\n if (isNode(containingNode, N.SelectorList)) {\n return !!(containingNode as SelectorList).get('value')[startIndex]?.hasFlag(F_AMPERSAND);\n }\n\n return true;\n}\n\nfunction getLocationAmpersandCrossings(\n location: SelectorMatchLocation,\n context?: EvalContext\n): SelectorMatchAmpersandCrossing[] | undefined {\n if (location.ampersandCrossings && location.ampersandCrossings.length > 0) {\n return location.ampersandCrossings;\n }\n\n const { containingNode } = location;\n if (!containingNode.hasFlag(F_AMPERSAND)) {\n return undefined;\n }\n\n const indices = location.matchedIndices && location.matchedIndices.length > 0\n ? location.matchedIndices\n : undefined;\n const start = location.startIndex ?? indices?.[0] ?? 0;\n const end = location.endIndex ?? indices?.[indices.length - 1] ?? start;\n const targetSegment: SelectorMatchSegment = {\n containingNode,\n startIndex: location.startIndex,\n endIndex: location.endIndex,\n matchedIndices: location.matchedIndices ? [...location.matchedIndices] : undefined\n };\n\n const crossings: SelectorMatchAmpersandCrossing[] = [];\n const seenAmpersands = new Set<Node>();\n const pushCrossing = (ampersandNode: Node): void => {\n if (seenAmpersands.has(ampersandNode)) {\n return;\n }\n\n seenAmpersands.add(ampersandNode);\n\n let parentSegment: SelectorMatchSegment | undefined;\n if (isNode(ampersandNode, N.Ampersand)) {\n const resolved = ampersandNode.getResolvedSelector(context);\n if (resolved && !isNode(resolved, N.Nil)) {\n parentSegment = {\n containingNode: resolved\n };\n }\n }\n\n crossings.push({\n ampersandNode,\n targetSegment,\n parentSegment\n });\n };\n\n if (isNode(containingNode, N.Ampersand)) {\n pushCrossing(containingNode);\n return crossings;\n }\n\n if (isNode(containingNode, N.CompoundSelector) || isNode(containingNode, N.ComplexSelector)) {\n if (indices) {\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i]!;\n const node = containingNode.get('value')[idx];\n if (node && isNode(node, N.Ampersand)) {\n pushCrossing(node);\n }\n }\n }\n\n for (let i = start; i <= end; i++) {\n const node = containingNode.get('value')[i];\n if (node && isNode(node, N.Ampersand)) {\n pushCrossing(node);\n }\n }\n }\n\n if (isNode(containingNode, N.SelectorList) && start === end) {\n const node = (containingNode as SelectorList).get('value')[start];\n if (node && isNode(node, N.Ampersand)) {\n pushCrossing(node);\n } else if (node && (isNode(node, N.CompoundSelector) || isNode(node, N.ComplexSelector))) {\n for (let i = 0; i < node.get('value').length; i++) {\n const child = node.get('value')[i];\n if (child && isNode(child, N.Ampersand)) {\n const resolved = child.getResolvedSelector(context);\n crossings.push({\n ampersandNode: child,\n targetSegment,\n parentSegment: resolved && !isNode(resolved, N.Nil)\n ? { containingNode: resolved as Selector }\n : undefined\n });\n }\n }\n }\n }\n\n return crossings.length > 0 ? crossings : undefined;\n}\n\n/**\n * Finalizes aggregate booleans from the collected match list.\n *\n * This intentionally uses a single scan to avoid repeated array passes on a\n * hot path.\n */\nfunction finalizeMatchState(result: SelectorMatchState, context?: EvalContext): SelectorMatchState {\n let fullMatch = false;\n let crossesAmpersand = false;\n\n for (let i = 0; i < result.matches.length; i++) {\n const match = result.matches[i]!;\n if (!match.ampersandCrossings) {\n match.ampersandCrossings = getLocationAmpersandCrossings(match, context);\n }\n fullMatch ||= !!match.exact;\n crossesAmpersand ||= locationCrossesAmpersand(match);\n\n if (fullMatch && crossesAmpersand) {\n break;\n }\n }\n\n result.fullMatch ||= fullMatch;\n result.partialMatch ||= result.matches.length > 0;\n result.crossesAmpersand = crossesAmpersand;\n return result;\n}\n\n/**\n * Recursively searches inside searchable pseudo-selector arguments.\n *\n * These nested matches are root-like searches; they do not allow an outer\n * match route to continue through the pseudo boundary.\n */\nfunction pushNestedPseudoMatches(\n find: Selector,\n targetNode: Node,\n matches: SelectorMatchLocation[],\n context: SelectorMatchContext\n): void {\n if (isSearchablePseudoBoundary(targetNode)) {\n if (isSearchablePseudoBoundary(find)) {\n if (find.get('name') !== targetNode.get('name')) {\n return;\n }\n\n const nested = selectorMatchInternal(find.get('arg') as Selector, targetNode.get('arg') as Selector, undefined, context);\n for (let i = 0; i < nested.matches.length; i++) {\n const match = nested.matches[i]!;\n matches.push({\n startIndex: match.startIndex,\n endIndex: match.endIndex,\n containingNode: match.containingNode,\n exact: match.exact,\n consumedTarget: match.consumedTarget,\n ampersandCrossings: cloneAmpersandCrossings(match.ampersandCrossings)\n });\n }\n return;\n }\n\n const nested = selectorMatchInternal(find, targetNode.get('arg') as Selector, undefined, context);\n for (let i = 0; i < nested.matches.length; i++) {\n const match = nested.matches[i]!;\n matches.push({\n startIndex: match.startIndex,\n endIndex: match.endIndex,\n containingNode: match.containingNode,\n exact: false,\n consumedTarget: match.consumedTarget,\n ampersandCrossings: cloneAmpersandCrossings(match.ampersandCrossings)\n });\n }\n return;\n }\n\n const children = targetNode.children();\n let child = children.next();\n while (!child.done) {\n pushNestedPseudoMatches(find, child.value, matches, context);\n child = children.next();\n }\n}\n\n/**\n * Finds all occurrences of `find` inside `target`.\n *\n * Matching is ordered at the route level, unordered only inside a single\n * compound-like position, and branches only at `SelectorList` alternatives.\n * A selector list on the find side is treated as alternate find routes: any\n * one alternate may match, and each matching alternate contributes its own\n * recorded locations.\n *\n * When `parent` is provided, it acts like an implicit prefix context joined to\n * `target` by a descendant combinator. Parent traversal is attempted only when\n * a match reaches a left-side ampersand boundary with partial-but-incomplete\n * progress; matches that exist only inside the parent do not get added on\n * their own.\n *\n * That same `parent` context is preserved when matching through nested\n * selector-list and `:is(...)` alternatives, because those are still the same\n * authored match route. It is not preserved for root-like searches inside\n * non-`:is()` pseudo-selector boundaries, because those searches must not\n * continue the outer route through that boundary.\n *\n * Complex selector branches inside `:is(...)` or selector lists are treated as\n * alternate branch routes. Matching may succeed inside one branch, but the\n * outer route cannot continue leftward through that branch unless that branch\n * itself was consumed end-to-end.\n */\nfunction selectorMatchUncached(\n find: Selector,\n target: Selector,\n parent: Selector | undefined,\n context: SelectorMatchContext\n): SelectorMatchState {\n const evalContext = context.evalContext;\n\n if (isNode(find, N.SelectorList)) {\n const result = emptySelectorMatchState();\n\n for (let i = 0; i < (find as SelectorList).get('value').length; i++) {\n const nested = selectorMatchInternal((find as SelectorList).get('value')[i]!, target, parent, context);\n result.fullMatch ||= nested.fullMatch;\n result.partialMatch ||= nested.partialMatch;\n result.crossesAmpersand ||= nested.crossesAmpersand;\n pushMatches(result.matches, nested.matches);\n }\n\n return finalizeMatchState(result, context.evalContext);\n }\n\n if (\n isNode(find, N.PseudoSelector)\n && find.get('name') !== ':is'\n && isNode(find.get('arg'), N.Selector)\n ) {\n if (isSearchablePseudoBoundary(target)) {\n if (find.get('name') !== target.get('name')) {\n return emptySelectorMatchState();\n }\n\n return selectorMatchInternal(find.get('arg') as Selector, target.get('arg') as Selector, parent, context);\n }\n\n const nested = selectorMatchInternal(find.get('arg') as Selector, target, parent, context);\n if (!nested.partialMatch) {\n return nested;\n }\n\n const matches = new Array<SelectorMatchLocation>(nested.matches.length);\n for (let i = 0; i < nested.matches.length; i++) {\n const match = nested.matches[i]!;\n matches[i] = {\n startIndex: match.startIndex,\n endIndex: match.endIndex,\n containingNode: find.get('arg') as Node,\n exact: false,\n consumedTarget: false,\n ampersandCrossings: cloneAmpersandCrossings(match.ampersandCrossings)\n };\n }\n\n return {\n fullMatch: false,\n partialMatch: true,\n crossesAmpersand: matches.some(locationCrossesAmpersand),\n matches\n };\n }\n\n const findValue = selectorValueOf(find, evalContext);\n if (isNode(target, N.SelectorList)) {\n for (let i = 0; i < (target as SelectorList).get('value').length; i++) {\n const sel = (target as SelectorList).get('value')[i]!;\n if (findValue === selectorValueOf(sel, evalContext)) {\n return {\n fullMatch: true,\n partialMatch: true,\n crossesAmpersand: sel.hasFlag(F_AMPERSAND),\n matches: [{\n startIndex: i,\n endIndex: i,\n matchedIndices: [i],\n containingNode: target,\n exact: true,\n consumedTarget: (target as SelectorList).get('value').length === 1,\n ampersandCrossings: getLocationAmpersandCrossings({\n startIndex: i,\n endIndex: i,\n matchedIndices: [i],\n containingNode: target,\n exact: true,\n consumedTarget: (target as SelectorList).get('value').length === 1\n }, evalContext)\n }]\n };\n }\n\n const nested = selectorMatchInternal(find, sel, parent, context);\n if (nested.partialMatch) {\n return {\n fullMatch: nested.fullMatch,\n partialMatch: true,\n crossesAmpersand: nested.crossesAmpersand || sel.hasFlag(F_AMPERSAND),\n matches: [{\n startIndex: i,\n endIndex: i,\n matchedIndices: [i],\n containingNode: target,\n exact: nested.fullMatch,\n consumedTarget: nested.fullMatch && (target as SelectorList).get('value').length === 1,\n ampersandCrossings: cloneAmpersandCrossings(nested.matches[0]?.ampersandCrossings)\n }]\n };\n }\n }\n return emptySelectorMatchState();\n } else {\n if (findValue === selectorValueOf(target, evalContext)) {\n return {\n fullMatch: true,\n partialMatch: true,\n crossesAmpersand: target.hasFlag(F_AMPERSAND),\n matches: [{\n containingNode: target,\n exact: true,\n consumedTarget: true,\n ampersandCrossings: getLocationAmpersandCrossings({\n containingNode: target,\n exact: true,\n consumedTarget: true\n }, evalContext)\n }]\n };\n }\n }\n\n if (\n !parent\n && find.keySetLibrary\n && target.keySetLibrary\n ) {\n if (evalContext) {\n if (safeIsDisjoint(find.getKeySet(evalContext), target.getKeySet(evalContext))) {\n return emptySelectorMatchState();\n }\n } else {\n if (\n !find.hasFlag(F_AMPERSAND)\n && target.hasFlag(F_AMPERSAND)\n && safeIsDisjoint(find.visibleKeySet, target.visibleKeySet)\n ) {\n return emptySelectorMatchState();\n }\n if (\n !safeIsDisjoint(find.requiredKeySet, find.keySet)\n && safeIsDisjoint(find.requiredKeySet, target.keySet)\n ) {\n return emptySelectorMatchState();\n }\n }\n }\n\n const findPlan = getSelectorMatchPlan(find, undefined, evalContext);\n if (findPlan.kind !== 'route' || findPlan.units.length === 0) {\n return emptySelectorMatchState();\n }\n const groupMatchCache: GroupMatchCache = new WeakMap();\n\n const matchParentRoute = (\n routePlan: RouteMatchPlan,\n parentPlan: MatchPlan\n ): SelectorMatchState => {\n const result = emptySelectorMatchState();\n const routeUnits = routePlan.units;\n const findUnits = findPlan.units;\n\n if (routeUnits.length === 0) {\n return result;\n }\n\n const boundaryTailUnits = getBoundaryTailUnits(routePlan);\n const boundaryTailLength = boundaryTailUnits.length;\n const findLength = findUnits.length;\n const matchedAll = (\n findLength <= boundaryTailLength\n && matchUnitWindow(\n findUnits,\n 0,\n boundaryTailUnits,\n boundaryTailLength - findLength,\n findLength,\n groupMatchCache,\n context,\n parent\n ).matched\n );\n\n if (matchedAll || boundaryTailLength > findLength) {\n return result;\n }\n\n const targetBoundaryMatch = matchUnitWindow(\n findUnits,\n findLength - boundaryTailLength,\n boundaryTailUnits,\n 0,\n boundaryTailLength,\n groupMatchCache,\n context,\n parent\n );\n\n if (!targetBoundaryMatch.matched) {\n return result;\n }\n\n const remainingFindLength = findLength - boundaryTailLength;\n if (remainingFindLength === 0) {\n return result;\n }\n\n const matchParentPlan = (plan: MatchPlan): void => {\n if (plan.kind === 'list') {\n for (let i = 0; i < plan.alternates.length; i++) {\n matchParentPlan(plan.alternates[i]!);\n }\n return;\n }\n\n const parentUnits = plan.units;\n if (parentUnits.length < remainingFindLength) {\n return;\n }\n\n const parentMatch = matchUnitWindow(\n findUnits,\n 0,\n parentUnits,\n parentUnits.length - remainingFindLength,\n remainingFindLength,\n groupMatchCache,\n context\n );\n\n if (!parentMatch.matched) {\n return;\n }\n\n const exact = (\n parentMatch.exact\n && targetBoundaryMatch.exact\n && remainingFindLength === parentUnits.length\n );\n const firstTargetUnit = boundaryTailUnits[0]!;\n const lastTargetUnit = boundaryTailUnits[boundaryTailLength - 1]!;\n const firstParentUnit = parentUnits[parentUnits.length - remainingFindLength]!;\n const lastParentUnit = parentUnits[parentUnits.length - 1]!;\n const leadingAmpersand = hasLeadingAmpersandBoundary(routePlan.selector)\n ? (routePlan.selector as ComplexSelector).value[0]\n : undefined;\n const ampersandCrossings: SelectorMatchAmpersandCrossing[] = [{\n ampersandNode: leadingAmpersand,\n targetSegment: {\n containingNode: routePlan.selector,\n startIndex: firstTargetUnit.index,\n endIndex: lastTargetUnit.index\n },\n parentSegment: {\n containingNode: plan.selector,\n startIndex: firstParentUnit.index,\n endIndex: lastParentUnit.index\n }\n }];\n\n if (isNode(routePlan.selector, N.CompoundSelector) || isNode(routePlan.selector, N.ComplexSelector)) {\n result.matches.push({\n startIndex: 0,\n endIndex: (routePlan.selector as CompoundSelector | ComplexSelector).get('value').length - 1,\n containingNode: routePlan.selector,\n exact,\n crossesAmpersand: true,\n consumedTarget: !!exact,\n ampersandCrossings\n });\n return;\n }\n\n result.matches.push({\n containingNode: routePlan.selector,\n exact,\n crossesAmpersand: true,\n consumedTarget: !!exact,\n ampersandCrossings\n });\n };\n\n matchParentPlan(parentPlan);\n return finalizeMatchState(result, context.evalContext);\n };\n\n const pushMidRouteAmpersandMatches = (\n matches: SelectorMatchLocation[],\n routePlan: RouteMatchPlan\n ): void => {\n const routeUnits = routePlan.units;\n const findUnits = findPlan.units;\n\n const pushMatchesForResolvedPlan = (\n plan: MatchPlan,\n ampStart: number,\n ampUnit: MatchPlanUnit & { kind: 'group' },\n tailLength: number,\n tailMatch: MatchWindowResult\n ): void => {\n if (plan.kind === 'list') {\n for (let i = 0; i < plan.alternates.length; i++) {\n pushMatchesForResolvedPlan(plan.alternates[i]!, ampStart, ampUnit, tailLength, tailMatch);\n }\n return;\n }\n\n const remainingFindLength = findUnits.length - tailLength;\n if (remainingFindLength <= 0) {\n return;\n }\n\n const parentUnits = plan.units;\n if (parentUnits.length < remainingFindLength) {\n return;\n }\n\n const parentMatch = matchUnitWindow(\n findUnits,\n 0,\n parentUnits,\n parentUnits.length - remainingFindLength,\n remainingFindLength,\n groupMatchCache,\n context\n );\n if (!parentMatch.matched) {\n return;\n }\n\n const tailEndUnit = routeUnits[ampStart + tailLength] ?? routeUnits[routeUnits.length - 1]!;\n const firstParentUnit = parentUnits[parentUnits.length - remainingFindLength]!;\n const lastParentUnit = parentUnits[parentUnits.length - 1]!;\n const exact = (\n ampStart === 0\n && ampStart + tailLength === routeUnits.length - 1\n && remainingFindLength === parentUnits.length\n && parentMatch.exact\n && tailMatch.exact\n );\n\n matches.push({\n startIndex: ampUnit.index,\n endIndex: tailEndUnit.index,\n containingNode: routePlan.selector,\n exact,\n crossesAmpersand: true,\n consumedTarget: !!exact,\n ampersandCrossings: [{\n ampersandNode: ampUnit.node,\n targetSegment: {\n containingNode: routePlan.selector,\n startIndex: ampUnit.index,\n endIndex: tailEndUnit.index\n },\n parentSegment: {\n containingNode: plan.selector,\n startIndex: firstParentUnit.index,\n endIndex: lastParentUnit.index\n }\n }]\n });\n };\n\n for (let ampStart = 0; ampStart < routeUnits.length - 1; ampStart++) {\n const ampUnit = routeUnits[ampStart]!;\n if (!(ampUnit.kind === 'group' && isNode(ampUnit.node, N.Ampersand))) {\n continue;\n }\n\n const resolved = ampUnit.node.getResolvedSelector(evalContext) ?? parent;\n if (!resolved || isNode(resolved, N.Nil)) {\n continue;\n }\n\n const resolvedPlan = getSelectorMatchPlan(resolved as Selector, undefined, evalContext);\n const maxTailLength = Math.min(\n routeUnits.length - (ampStart + 1),\n findUnits.length - 1\n );\n\n for (let tailLength = 1; tailLength <= maxTailLength; tailLength++) {\n const tailMatch = matchUnitWindow(\n findUnits,\n findUnits.length - tailLength,\n routeUnits,\n ampStart + 1,\n tailLength,\n groupMatchCache,\n context,\n parent\n );\n if (!tailMatch.matched) {\n continue;\n }\n\n pushMatchesForResolvedPlan(resolvedPlan, ampStart, {\n ...ampUnit,\n kind: 'group'\n }, tailLength, tailMatch);\n }\n }\n };\n\n const matchTargetRoute = (\n routePlan: RouteMatchPlan,\n parentPlan?: MatchPlan\n ): SelectorMatchState => {\n const result = emptySelectorMatchState();\n const routeUnits = routePlan.units;\n const findUnits = findPlan.units;\n const singleFindGroup = findUnits.length === 1 && findUnits[0]!.kind === 'group'\n ? findUnits[0]!\n : undefined;\n const suppressAmbiguousBranchLocations = findUnits.length > 0 && routePlan.selector !== find\n ? findPlan.hasAmbiguousBranchTail\n : findPlan.hasAmbiguousBranchTail;\n\n if (routeUnits.length >= findUnits.length) {\n const lastStart = routeUnits.length - findUnits.length;\n\n for (let start = 0; start <= lastStart; start++) {\n let exact = start === 0 && routeUnits.length === findUnits.length;\n const windowMatch = matchUnitWindow(\n findUnits,\n 0,\n routeUnits,\n start,\n findUnits.length,\n groupMatchCache,\n context,\n parent\n );\n let matched = windowMatch.matched;\n exact &&= windowMatch.exact;\n\n if (!matched) {\n continue;\n }\n\n if (\n parent\n && findUnits.length === 1\n && routeUnits.length > 1\n && routeUnits[start]?.kind === 'group'\n && isNode(routeUnits[start]!.node, N.Ampersand)\n ) {\n continue;\n }\n\n if (singleFindGroup) {\n const targetUnit = routeUnits[start]!;\n if (targetUnit.kind === 'group') {\n const groupLocations = collectGroupMatchLocations(\n targetUnit.node,\n singleFindGroup.group,\n parent,\n evalContext\n );\n for (let i = 0; i < groupLocations.length; i++) {\n const location = groupLocations[i]!;\n result.matches.push({\n ...location,\n exact: exact && location.exact,\n consumedTarget: !!location.consumedTarget,\n ampersandCrossings: cloneAmpersandCrossings(location.ampersandCrossings)\n });\n }\n continue;\n }\n }\n\n if (!windowMatch.exact && suppressAmbiguousBranchLocations) {\n result.partialMatch = true;\n continue;\n }\n\n result.matches.push({\n startIndex: routeUnits[start]!.index,\n endIndex: routeUnits[start + findUnits.length - 1]!.index,\n containingNode: routePlan.selector as Node,\n exact,\n consumedTarget: !!exact\n });\n }\n }\n\n pushMidRouteAmpersandMatches(result.matches, routePlan);\n\n if (parentPlan) {\n pushMatches(result.matches, matchParentRoute(routePlan, parentPlan).matches);\n }\n\n return finalizeMatchState(result, context.evalContext);\n };\n\n const matchTargetPlan = (\n plan: MatchPlan,\n parentPlan?: MatchPlan\n ): SelectorMatchState => {\n if (plan.kind === 'route') {\n return matchTargetRoute(plan, parentPlan);\n }\n\n const result = emptySelectorMatchState();\n for (let i = 0; i < plan.alternates.length; i++) {\n const match = matchTargetPlan(plan.alternates[i]!, parentPlan);\n pushMatches(result.matches, match.matches);\n }\n\n return finalizeMatchState(result, context.evalContext);\n };\n\n const parentPlan = parent ? getSelectorMatchPlan(parent, undefined, evalContext) : undefined;\n const result = matchTargetPlan(getSelectorMatchPlan(target, parent, evalContext), parentPlan);\n pushNestedPseudoMatches(find, target, result.matches, context);\n if (!result.partialMatch && result.matches.length === 0) {\n pushNestedBranchMatches(find, target, result.matches, context, parent);\n }\n return finalizeMatchState(result, context.evalContext);\n}\n\nfunction selectorMatchInternal(\n find: Selector,\n target: Selector,\n parent: Selector | undefined,\n context: SelectorMatchContext\n): SelectorMatchState {\n if (parent) {\n return selectorMatchUncached(find, target, parent, context);\n }\n\n let findCache = context.pairCache.get(find);\n if (!findCache) {\n findCache = new WeakMap<Selector, SelectorMatchState>();\n context.pairCache.set(find, findCache);\n }\n\n const cached = findCache.get(target);\n if (cached) {\n return cached;\n }\n\n const result = selectorMatchUncached(find, target, undefined, context);\n findCache.set(target, result);\n return result;\n}\n\n/**\n * Finds all occurrences of `find` inside `target`.\n *\n * Matching is ordered at the route level, unordered only inside a single\n * compound-like position, and branches only at `SelectorList` alternatives.\n *\n * When `parent` is provided, it acts like an implicit prefix context joined to\n * `target` by a descendant combinator. Parent traversal is attempted only when\n * a match reaches a left-side ampersand boundary with partial-but-incomplete\n * progress; matches that exist only inside the parent do not get added on\n * their own.\n *\n * Complex selector branches inside `:is(...)` or selector lists are treated as\n * alternate branch routes. Matching may succeed inside one branch, but the\n * outer route cannot continue leftward through that branch unless that branch\n * itself was consumed end-to-end.\n *\n * The matcher uses normalized `valueOf()` and selector key-set fast paths only\n * as cheap equality / rejection signals. They are not shape-preserving and\n * should not be used by callers to infer the structural rewrite shape of a\n * successful match.\n */\nexport function selectorMatch(\n find: Selector,\n target: Selector,\n parent?: Selector,\n evalContext?: EvalContext\n): SelectorMatchState {\n return selectorMatchInternal(find, target, parent, {\n pairCache: new WeakMap(),\n evalContext\n });\n}\n","import {\n defineType,\n F_EXTENDED,\n F_EXTEND_TARGET,\n type OptionalLocation\n} from './node.js';\nimport { type Context } from '../context.js';\nimport { Selector } from './selector.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, pipe, isThenable, serialForEach } from '@jesscss/awaitable-pipe';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { selectorMatch } from './util/selector-match-core.js';\n\nexport type SelectorListChildData = { value: Selector[] };\n\nexport interface SelectorList {\n type: 'SelectorList';\n shortType: 'sellist';\n}\n\n/** Constructs */\nexport class SelectorList extends Selector<Selector[], any, SelectorListChildData> {\n static override childKeys = ['value'] as const;\n\n value!: Selector[];\n\n constructor(value: Selector[], options?: any, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.value = value;\n for (const child of value) {\n if (child instanceof Selector) {\n this.adopt(child);\n }\n }\n }\n\n get length() {\n return this.value.length;\n }\n\n override clone(deep?: boolean): this {\n if (deep) {\n return super.clone(true) as this;\n }\n return this._withValue(this.value) as this;\n }\n\n private _withValue(value: Selector[]): SelectorList {\n const location = Array.isArray(this.location) && this.location.length === 6\n ? this.location as OptionalLocation\n : undefined;\n const node = new (this.constructor as typeof SelectorList)(\n [],\n this.options ? { ...this.options } : undefined,\n location,\n this.treeContext\n );\n node.inherit(this);\n node.value = value;\n return node;\n }\n\n /** Normalize selectors on separate lines with indentation */\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n let depth = options.depth!;\n let space = ''.padStart(depth * 2);\n // Flatten generated top-level `:is(...)` items into the selector list.\n const sourceValue = this.get('value', options.context);\n const value: Selector[] = [];\n for (const item of sourceValue) {\n if (isNode(item, N.PseudoSelector) && item.get('name') === ':is') {\n const arg = item.get('arg');\n if (arg && isNode(arg, N.SelectorList)) {\n value.push(...arg.get('value'));\n continue;\n }\n }\n if (isNode(item, N.CompoundSelector) && item.get('value').length === 1) {\n const only = item.get('value')[0]!;\n if (isNode(only, N.PseudoSelector) && only.get('name') === ':is') {\n const arg = only.get('arg');\n if (arg && isNode(arg, N.SelectorList)) {\n value.push(...arg.get('value'));\n continue;\n }\n }\n }\n if (isNode(item, N.ComplexSelector) && item.get('value').length === 1) {\n const only = item.get('value')[0]!;\n if (isNode(only, N.PseudoSelector) && only.get('name') === ':is') {\n const arg = only.get('arg');\n if (arg && isNode(arg, N.SelectorList)) {\n value.push(...arg.get('value'));\n continue;\n }\n }\n }\n value.push(item);\n }\n if (\n options.referenceMode === true\n && options.referenceRenderEnabled === true\n && options.referenceFilterTargets === true\n ) {\n const extendedOnly = value.filter(item =>\n item.hasFlag(F_EXTENDED) && !item.hasFlag(F_EXTEND_TARGET)\n );\n if (extendedOnly.length > 0) {\n value.splice(0, value.length, ...extendedOnly);\n }\n }\n let length = value.length;\n if (length === 0) {\n return '';\n }\n const mark = w.mark();\n let item = value[0]!;\n\n let out = w.capture(() => item.toString(options));\n w.add(out.trim(), item);\n\n for (let i = 1; i < length; i++) {\n item = value[i]!;\n w.add(`,\\n${space}`);\n out = (w.capture(() => item.toString(options))).trim();\n w.add(out);\n }\n return w.getSince(mark);\n }\n\n override valueOf() {\n const itemValues = this.value.map(item => item.valueOf());\n return itemValues.join(',');\n }\n\n override compare(b: Selector, context?: Context): 0 | 1 | -1 | undefined {\n if (!isNode(b, N.Selector)) {\n return super.compare(b as unknown as Selector, context);\n }\n const semantic = selectorMatch(this, b, undefined, context);\n if (semantic.fullMatch) {\n return 0;\n }\n return super.compare(b, context);\n }\n\n override evalNode(context: Context): MaybePromise<SelectorList | Selector> {\n return pipe(\n () => {\n const list = super.evalNode(context) as SelectorList;\n const value = [...list.get('value', context)];\n let changed = false;\n const maybe = serialForEach(value.map((_, i) => i), (i) => {\n const out = value[i]!.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Selector>).then((res) => {\n if (res !== value[i]) {\n value[i] = res as Selector;\n changed = true;\n }\n return undefined;\n });\n }\n if ((out as Selector) !== value[i]) {\n value[i] = out as Selector;\n changed = true;\n }\n return undefined;\n });\n if (isThenable(maybe)) {\n return (maybe as Promise<void>).then(() => {\n if (changed) {\n return list === this\n ? this._withValue(value)\n : (() => {\n list.value = value;\n return list;\n })();\n }\n return list;\n });\n }\n if (changed) {\n return list === this\n ? this._withValue(value)\n : (() => {\n list.value = value;\n return list;\n })();\n }\n return list;\n },\n (list) => {\n const value = list.get('value', context);\n const flattened: Selector[] = [];\n for (const item of value) {\n if (isNode(item, N.PseudoSelector) && item.get('name') === ':is') {\n const arg = item.get('arg');\n if (arg && isNode(arg, N.SelectorList)) {\n flattened.push(...arg.get('value'));\n continue;\n }\n }\n if (isNode(item, N.CompoundSelector) && item.get('value').length === 1) {\n const only = item.get('value')[0]!;\n if (isNode(only, N.PseudoSelector) && only.get('name') === ':is') {\n const arg = only.get('arg');\n if (arg && isNode(arg, N.SelectorList)) {\n flattened.push(...arg.get('value'));\n continue;\n }\n }\n }\n if (isNode(item, N.ComplexSelector) && item.get('value').length === 1) {\n const only = item.get('value')[0]!;\n if (isNode(only, N.PseudoSelector) && only.get('name') === ':is') {\n const arg = only.get('arg');\n if (arg && isNode(arg, N.SelectorList)) {\n flattened.push(...arg.get('value'));\n continue;\n }\n }\n }\n flattened.push(item);\n }\n if (flattened.length !== value.length) {\n if (list === this) {\n list = this._withValue(flattened);\n } else {\n list.value = flattened;\n }\n }\n if (flattened.length === 1) {\n return flattened[0]!;\n }\n return list;\n }\n );\n }\n}\n\nexport const sellist = defineType(SelectorList, 'SelectorList', 'sellist');\n","import { type NodeOptions, defineType } from './node.js';\nimport { Selector } from './selector.js';\n\nexport abstract class SimpleSelector<\n T = any,\n O extends NodeOptions = NodeOptions,\n CD extends Record<string, unknown> = Record<string, unknown>\n> extends Selector<T, O, CD> {}\n\ndefineType(SimpleSelector, 'SimpleSelector');","import {\n defineType,\n Node,\n type OptionalLocation,\n type NodeOptions,\n type TreeContext\n} from './node.js';\nimport { SimpleSelector } from './selector-simple.js';\nimport { type Context } from '../context.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { Selector } from './selector.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, pipe } from '@jesscss/awaitable-pipe';\n\nexport type PseudoSelectorValue = {\n /**\n * The name of the pseudo-selector\n * @note - this will contain the `:` prefix,\n * to support `::before` and `::after`\n */\n name: string;\n arg?: Node;\n};\n\nexport type PseudoSelectorChildData = { name: string; arg: Node | undefined };\n\n/**\n * A pseudo selector\n * @see https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements\n * e.g. :hover, :focus, :active\n*/\nexport interface PseudoSelector {\n type: 'PseudoSelector';\n shortType: 'pseudo';\n}\nexport class PseudoSelector extends SimpleSelector<PseudoSelectorValue, NodeOptions, PseudoSelectorChildData> {\n static override childKeys = ['name', 'arg'] as const;\n\n name!: string;\n arg: Node | undefined;\n\n constructor(value: PseudoSelectorValue, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.name = value.name;\n this.arg = value.arg;\n if (this.arg instanceof Node) {\n this.adopt(this.arg);\n }\n }\n\n override computeKeySets(): void {\n if (this._keySet && this._visibleKeySet && this._requiredKeySet) {\n return;\n }\n let name = this.name;\n let arg: unknown = this.arg;\n let library = this.keySetLibrary;\n if (!library) {\n throw new Error('Selector keySet library not found');\n }\n if (isNode(arg, N.Selector)) {\n if (name === ':is') {\n this._keySet = arg.keySet;\n this._visibleKeySet = arg.visibleKeySet;\n if (isNode(arg, N.SelectorList)) {\n this._requiredKeySet = library.getBitset();\n } else {\n this._requiredKeySet = arg.requiredKeySet;\n }\n } else {\n let pos = library.add(name);\n let keySet = this._keySet = arg.keySet.clone();\n let visibleKeySet = this._visibleKeySet = arg.visibleKeySet.clone();\n keySet.set(pos, 1);\n visibleKeySet.set(pos, 1);\n this._requiredKeySet = arg.requiredKeySet.clone();\n this._requiredKeySet.set(pos, 1);\n }\n } else {\n this._keySet = library.getBitset([this.valueOf()]);\n this._visibleKeySet = this._keySet;\n this._requiredKeySet = this._keySet;\n }\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const context = options.context;\n const name = this.get('name', context);\n const arg = this.get('arg', context);\n const mark = w.mark();\n if (this.generated && name === ':is' && arg && isNode(arg, N.SelectorList)) {\n let out = w.capture(() => arg.toString(options));\n out = out.replace(/\\n\\s*/g, ' ').trimEnd();\n if (!out.includes(',')) {\n w.add(out, arg);\n return w.getSince(mark);\n }\n w.add(name, this);\n w.add('(');\n w.add(out, arg);\n w.add(')');\n return w.getSince(mark);\n }\n w.add(name, this);\n if (arg) {\n w.add('(');\n if (isNode(arg, N.SelectorList)) {\n let out = w.capture(() => arg.toString(options));\n out = out.replace(/\\n\\s*/g, ' ').trimEnd();\n w.add(out, arg);\n } else {\n let out = w.capture(() => arg.toString(options));\n w.add(out.trimEnd(), arg);\n }\n w.add(')');\n }\n return w.getSince(mark);\n }\n\n override valueOf(): string {\n let valueOf = this._valueOf;\n if (!valueOf) {\n let name = this.name;\n let arg = this.arg;\n valueOf = `${name}${arg ? `(${arg.valueOf()})` : ''}`;\n this._valueOf = valueOf;\n }\n return valueOf;\n }\n\n override evalNode(context: Context): MaybePromise<PseudoSelector> {\n const currentArg = this.get('arg', context);\n const node = super.evalNode(context) as PseudoSelector;\n if (!currentArg) {\n return node;\n }\n return pipe(\n () => {\n context.parenFrames.push(false);\n return currentArg.eval(context);\n },\n (evaluatedArg) => {\n context.parenFrames.pop();\n if (node === this) {\n const out = this.clone() as PseudoSelector;\n out.inherit(this);\n out.adopt(evaluatedArg, context);\n out.arg = evaluatedArg;\n return out;\n }\n node.adopt(evaluatedArg, context);\n node.arg = evaluatedArg;\n return node;\n }\n );\n }\n}\n\nexport const pseudo = defineType<PseudoSelectorValue, typeof PseudoSelector>(PseudoSelector, 'PseudoSelector', 'pseudo');\n\n/**\n * Convenience function to create a :is() pseudo-selector\n * @param arg The selector that goes inside :is()\n * @returns A PseudoSelector with name \":is\" and the provided selector as argument\n */\nexport function is(arg: Selector): PseudoSelector {\n const p = pseudo({ name: ':is', arg });\n p.generated = true;\n return p;\n}\n","import type { Context } from '../context.js';\nimport { defineType, F_STATIC, type OptionalLocation, type NodeOptions, type TreeContext } from './node.js';\nimport { Selector } from './selector.js';\n\nexport type Combinators = ' ' | '>' | '+' | '~' | '|' | '||';\n\nexport interface Combinator extends Selector<Combinators> {\n type: 'Combinator';\n shortType: 'co';\n eval(context: Context): Combinator;\n}\n\nexport class Combinator extends Selector<Combinators> {\n static override childKeys = null as null;\n\n readonly value!: Combinators;\n\n constructor(\n value: Combinators,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n super(value, options, location, treeContext);\n this.value = value;\n this.addFlag(F_STATIC);\n }\n}\n\nexport const co = defineType(Combinator, 'Combinator', 'co');\n","import type { Context } from '../context.js';\nimport { defineType, F_STATIC, type OptionalLocation, type NodeOptions, type TreeContext } from './node.js';\nimport { SimpleSelector } from './selector-simple.js';\n\nexport interface BasicSelector extends SimpleSelector<string> {\n type: 'BasicSelector';\n shortType: 'el';\n eval(context: Context): BasicSelector;\n}\n\n/**\n * A basic selector\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors/Selectors_and_combinators#basic_selectors\n * e.g. div, .foo, #bar\n*/\nexport class BasicSelector extends SimpleSelector<string> {\n static override childKeys = null as null;\n\n value!: string;\n\n constructor(\n value: string,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n super(value, options, location, treeContext);\n this.value = value;\n this.addFlag(F_STATIC);\n }\n\n get isClass() {\n return /^\\./.test(this.value);\n }\n\n get isId() {\n return /^#/.test(this.value);\n }\n\n /** A tag-type selector */\n get isTag() {\n return /^[^.#*]/.test(this.value);\n }\n\n override evalNode(context: Context): BasicSelector {\n const node = super.evalNode(context) as BasicSelector;\n if (node.isClass) {\n context.hashClass(node.value);\n }\n return node;\n }\n\n override valueOf(): string {\n return (this._valueOf ??= (this.isTag ? this.value.toLowerCase() : this.value));\n }\n\n /** @todo - move to visitors */\n // toCSS(context: Context, out: OutputCollector) {\n // if (this.isClass) {\n // out.add(context.hashClass(this.data.value), this.location)\n // } else {\n // out.add(this.data.value, this.location)\n // }\n // }\n\n // toModule(context: Context, out: OutputCollector) {\n // const loc = this.location\n // out.add('$J.el(', loc)\n // this.data.toModule(context, out)\n // out.add(')')\n // }\n}\n\n/** Short form of a basic selector is a short 'el' for 'element' */\nexport const el = defineType(BasicSelector, 'BasicSelector', 'el');\n","/**\n * Selector-like ampersand template payloads.\n *\n * Supports:\n * - suffix/prefix forms like `-1`, `.foo`, `b`\n * - explicit insertion templates containing `&`\n * - selector-ish fragments, but reserves `nil` for `&(nil)`\n */\nexport const AMPERSAND_TEMPLATE_CONTENTS_REGEX = /(?:[.#\\w\\u0080-\\uffff-]|\\d)(?:[.#\\w\\u0080-\\uffff-]|&)*|(?:[.#\\w\\u0080-\\uffff-]|&)*&(?:[.#\\w\\u0080-\\uffff-]|&)*/;\n","import { CANONICAL, EVAL, type Node, type RenderKey } from '../node-base.js';\nimport type { Context } from '../../context.js';\nimport type { Rules } from '../rules.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport { addEdgeAt, addParentEdge, removeParentEdge } from './cursor.js';\n\nfunction getParentEdgeRenderKeys(\n node: Node,\n ctx: Context,\n edge?: Map<unknown, Node | undefined>\n): unknown[] {\n const keys: unknown[] = [];\n const push = (key: unknown): void => {\n if (key === undefined || key === CANONICAL || keys.includes(key)) {\n return;\n }\n keys.push(key);\n };\n push(ctx.renderKey);\n push(ctx.rulesContext?.renderKey);\n push(node.renderKey);\n if (edge?.has(EVAL)) {\n push(EVAL);\n }\n return keys;\n}\n\nfunction setRulesValueArray(rules: Rules, nodes: Node[]): void {\n const mutableRules = rules as Rules & { _setValueArray?: (nodes: Node[]) => void };\n if (typeof mutableRules._setValueArray !== 'function') {\n throw new Error('Rules is missing _setValueArray');\n }\n mutableRules._setValueArray(nodes);\n}\n\ntype ChildWriteTarget =\n | {\n kind: 'canonical';\n currentChildren: readonly Node[];\n }\n | {\n kind: 'wrapper';\n renderKey: RenderKey;\n currentChildren: readonly Node[];\n }\n | {\n kind: 'overlay';\n renderKey: RenderKey;\n currentChildren: readonly Node[];\n };\n\nfunction resolveChildWriteTarget(\n rules: Rules,\n ctx: Context\n): ChildWriteTarget {\n const resolvedRenderKey = ctx.renderKey ?? rules.renderKey;\n const renderKey = resolvedRenderKey === CANONICAL ? undefined : resolvedRenderKey;\n if (renderKey === undefined) {\n return {\n kind: 'canonical',\n currentChildren: rules.value\n };\n }\n if (rules.renderKey !== undefined && rules.renderKey === renderKey) {\n return {\n kind: 'wrapper',\n renderKey,\n currentChildren: rules.value\n };\n }\n return {\n kind: 'overlay',\n renderKey,\n currentChildren: rules.get('value', ctx)\n };\n}\n\nfunction maybeMarkScopeDirty(\n rules: Rules,\n ctx: Context,\n options: { markDirty?: boolean }\n): void {\n if (options.markDirty !== false) {\n markScopeDirty(rules, ctx);\n }\n}\n\nfunction connectRenderChildren(\n rules: Rules,\n nodes: readonly Node[],\n renderKey: RenderKey\n): void {\n for (let index = 0; index < nodes.length; index++) {\n const node = nodes[index]!;\n addEdgeAt(rules, 'value', index, renderKey, node);\n addParentEdge(node, renderKey, rules);\n }\n}\n\nfunction disconnectMissingRenderChildren(\n previous: readonly Node[],\n next: readonly Node[],\n renderKey: RenderKey\n): void {\n for (const child of previous) {\n if (!next.includes(child)) {\n removeParentEdge(child, renderKey);\n }\n }\n}\n\n/**\n * Resolve the effective parent for the current render placement.\n *\n * Node graph invariants:\n * - `node.parent` stores the canonical fallback parent.\n * - `node.parentEdges` stores placement-specific parent overrides keyed by render key.\n * - callers should treat this as the primary upward traversal surface when rebuilding\n * the current render path (for example, reconstructing the active Ruleset / AtRule frames).\n * - secondary lookup lanes such as `CALLER` are intentionally not followed here; they are\n * opt-in traversal choices layered on top of the primary parent walk.\n */\nexport function getParent(\n node: Node,\n ctx: Context\n): Node | undefined {\n for (const renderKey of getParentEdgeRenderKeys(node, ctx, node.parentEdges)) {\n const parent = node.parentEdges?.get(renderKey);\n if (parent !== undefined) {\n return parent;\n }\n }\n return node.parent;\n}\n\n/**\n * Write the primary parent for a node.\n *\n * For canonical writes this mutates `node.parent`.\n * For render-keyed writes this records a placement override in `node.parentEdges`\n * without disturbing canonical parentage.\n *\n * This should be the default way eval/adoption code captures the \"current frame\"\n * onto emitted nodes. If later serialization needs to guess the parent from text,\n * the real bug is usually that `setParent(...)` was not called with the correct\n * render placement when the node was created.\n */\nexport function setParent(\n node: Node,\n parent: Node | undefined,\n ctx: Context\n): void {\n if (ctx.renderKey !== undefined && ctx.renderKey !== CANONICAL) {\n if (parent) {\n addParentEdge(node, ctx.renderKey, parent);\n } else {\n removeParentEdge(node, ctx.renderKey);\n }\n return;\n }\n node.parent = parent;\n}\n\nexport function isEvaluated(\n node: Node,\n _ctx: Context\n): boolean {\n return node.evaluated;\n}\n\nexport function setEvaluated(\n node: Node,\n value: boolean,\n _ctx: Context\n): void {\n node.evaluated = value;\n}\n\nexport function isPreEvaluated(\n node: Node,\n _ctx: Context\n): boolean {\n return node.preEvaluated;\n}\n\nexport function setPreEvaluated(\n node: Node,\n value: boolean,\n _ctx: Context\n): void {\n node.preEvaluated = value;\n}\n\nexport function getIndex(\n node: Node,\n _ctx: Context\n): number {\n return node.index;\n}\n\nexport function setIndex(\n node: Node,\n index: number,\n _ctx: Context\n): void {\n node.index = index;\n}\n\nexport function getSourceParent(\n node: Node,\n _ctx: Context\n): Node | undefined {\n return node.sourceParent;\n}\n\nexport function setSourceParent(\n node: Node,\n parent: Node | undefined,\n _ctx: Context\n): void {\n node.sourceParent = parent;\n}\n\nexport function getChildren(\n rules: Rules,\n ctx: Context\n): readonly Node[] {\n return rules.get('value', ctx);\n}\n\nexport function setChildren(\n rules: Rules,\n nodes: readonly Node[],\n ctx: Context,\n options: { markDirty?: boolean } = {}\n): void {\n const target = resolveChildWriteTarget(rules, ctx);\n if (target.kind === 'canonical') {\n setRulesValueArray(rules, [...nodes]);\n for (const node of nodes) {\n rules.adopt(node, ctx);\n }\n maybeMarkScopeDirty(rules, ctx, options);\n return;\n }\n if (target.kind === 'wrapper') {\n setRulesValueArray(rules, [...nodes]);\n }\n disconnectMissingRenderChildren(target.currentChildren, nodes, target.renderKey);\n connectRenderChildren(rules, nodes, target.renderKey);\n maybeMarkScopeDirty(rules, ctx, options);\n}\n\nexport function setChildAt(\n rules: Rules,\n index: number,\n node: Node,\n ctx: Context,\n options: { markDirty?: boolean } = {}\n): void {\n const target = resolveChildWriteTarget(rules, ctx);\n if (target.kind !== 'canonical') {\n if (target.currentChildren[index] === node) {\n return;\n }\n const previous = target.currentChildren[index];\n if (target.kind === 'wrapper') {\n const nextValue = [...target.currentChildren];\n nextValue[index] = node;\n setRulesValueArray(rules, nextValue);\n }\n if (previous && previous !== node) {\n removeParentEdge(previous, target.renderKey);\n }\n addEdgeAt(rules, 'value', index, target.renderKey, node);\n addParentEdge(node, target.renderKey, rules);\n maybeMarkScopeDirty(rules, ctx, options);\n return;\n }\n const currentChildren = [...target.currentChildren];\n const prev = currentChildren[index];\n if (prev === node) {\n return;\n }\n currentChildren[index] = node;\n setRulesValueArray(rules, currentChildren);\n rules.adopt(node, ctx);\n maybeMarkScopeDirty(rules, ctx, options);\n}\n\nexport function markScopeDirty(\n _rules: Rules,\n _ctx: Context\n): void {\n // Registry delta tracking removed with EvalSession.\n // Registry rebuilds from children on next access.\n}\n\nexport interface EvalDependency {\n dependsOn: Set<import('../declaration-var.js').VarDeclaration> | null;\n sourceExpr?: Node;\n}\n\nexport function getDependency(\n node: Node,\n ctx: Context\n): EvalDependency | null {\n return ctx.dependencyMap.get(node) ?? null;\n}\n\nexport function setDependency(\n node: Node,\n dependency: EvalDependency,\n ctx: Context\n): void {\n ctx.dependencyMap.set(node, dependency);\n}\n\nexport function mergeDependencies(\n nodes: readonly (Node | undefined)[],\n ctx: Context\n): EvalDependency | null {\n let merged: Set<import('../declaration-var.js').VarDeclaration> | null = null;\n let sourceExpr: Node | undefined;\n for (const node of nodes) {\n if (!node) {\n continue;\n }\n const dep = getDependency(node, ctx);\n if (dep?.dependsOn && dep.dependsOn.size > 0) {\n if (!merged) {\n merged = new Set(dep.dependsOn);\n sourceExpr = dep.sourceExpr;\n } else {\n for (const v of dep.dependsOn) {\n merged.add(v);\n }\n }\n }\n }\n return merged ? { dependsOn: merged, sourceExpr } : null;\n}\n\nexport function isTopLevelVarDeclaration(\n node: Node,\n ctx: Context\n): node is import('../declaration-var.js').VarDeclaration {\n if (!isNode(node, N.VarDeclaration)) {\n return false;\n }\n const parent = getParent(node, ctx);\n return !!parent && isNode(parent, N.Rules) && parent === ctx.root;\n}\n","import { Selector } from '../selector.js';\nimport { Combinator } from '../combinator.js';\nimport { ComplexSelector } from '../selector-complex.js';\nimport { CompoundSelector } from '../selector-compound.js';\nimport { SelectorList } from '../selector-list.js';\nimport { PseudoSelector } from '../selector-pseudo.js';\nimport { BasicSelector } from '../selector-basic.js';\nimport { AMPERSAND_TEMPLATE_CONTENTS_REGEX } from './ampersand-template.js';\nimport type { Rules } from '../rules.js';\nimport type { Ruleset } from '../ruleset.js';\nimport type { Node, RenderKey } from '../node.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport { Nil } from '../nil.js';\nimport { F_IMPLICIT_AMPERSAND, F_EXTENDED } from '../node.js';\nimport type { Context } from '../../context.js';\nimport { getParent } from './field-helpers.js';\nimport { getParentEdge } from './cursor.js';\n\nconst ampersandTemplateInterpolationRegex = /[$@]\\{[^}]+\\}/g;\nconst ampersandTemplateRegex = new RegExp(`^(?:${AMPERSAND_TEMPLATE_CONTENTS_REGEX.source})$`);\n\nfunction getSelectorListArgNode(target: Selector): SelectorList | undefined {\n const arg = Reflect.get(target, 'arg');\n return isNode(arg, N.SelectorList) ? arg : undefined;\n}\n\nfunction getPseudoSelectorNode(node: Selector): PseudoSelector | undefined {\n return isNode(node, N.PseudoSelector) ? node : undefined;\n}\n\n/**\n * Returns true when `sel` is purely `&` with no explicit template — meaning the\n * ruleset's selector is an unmodified mirror of its parent. Such rulesets\n * are updated by refreshNestedRulesetSelectors and should not be directly\n * targeted by the extend loop.\n */\nexport function isBareAmpersandOwnSelector(sel: Selector | Nil): boolean {\n if (!sel || sel instanceof Nil) {\n return false;\n }\n if (isNode(sel, N.Ampersand)) {\n return sel.isPlainAmpersand();\n }\n if (isNode(sel, N.CompoundSelector)) {\n const items = sel.get('value');\n return items.length === 1\n && isNode(items[0], N.Ampersand)\n && items[0].isPlainAmpersand();\n }\n if (isNode(sel, N.ComplexSelector)) {\n const items = sel.get('value');\n return items.length === 1\n && isNode(items[0], N.Ampersand)\n && items[0].isPlainAmpersand();\n }\n return false;\n}\n\n/**\n * Smart `:is()` wrapper. Flattens nested generated `:is()`, deduplicates,\n * and skips wrapping single items.\n */\nexport function wrapInGeneratedIs(selector: Selector): Selector {\n const items: Selector[] = [];\n const seen = new Set<string>();\n\n const addItem = (item: Selector): void => {\n let pseudo = getPseudoSelectorNode(item);\n if (pseudo && !(pseudo.generated && pseudo.get('name') === ':is')) {\n pseudo = undefined;\n }\n if (!pseudo) {\n const compound = isNode(item, N.CompoundSelector) ? item : undefined;\n if (compound && compound.get('value').length === 1) {\n const only = compound.get('value')[0];\n pseudo = isNode(only, N.PseudoSelector) ? only : undefined;\n if (!(pseudo && pseudo.generated && pseudo.get('name') === ':is')) {\n pseudo = undefined;\n }\n }\n }\n const pseudoArg = pseudo ? getSelectorListArgNode(pseudo) : undefined;\n if (pseudoArg) {\n for (const child of pseudoArg.get('value')) {\n addItem(child);\n }\n return;\n }\n const key = item.valueOf();\n if (!seen.has(key)) {\n seen.add(key);\n items.push(item);\n }\n };\n\n if (isNode(selector, N.SelectorList)) {\n for (const item of selector.get('value')) {\n addItem(item);\n }\n } else {\n addItem(selector);\n }\n\n if (items.length === 1) {\n return items[0]!;\n }\n\n const list = SelectorList.create(items).inherit(selector);\n list.pre = undefined;\n list.post = undefined;\n const wrapper = PseudoSelector.create({ name: ':is', arg: list });\n wrapper.generated = true;\n return wrapper.inherit(selector);\n}\n\n/** Walk node.parent → Rules → Ruleset to find the containing Ruleset, if any. */\nexport function getCurrentParentNode(node: Node, context?: Context | RenderKey): Node | undefined {\n if (context && typeof context !== 'object') {\n return getParentEdge({ node, renderKey: context })?.node;\n }\n return context ? getParent(node, context) : node.parent;\n}\n\n/** Walk node.parent → Rules → Ruleset to find the containing Ruleset, if any. */\nexport function getParentRuleset(node: Node, context?: Context): Ruleset | undefined {\n const visited = new Set<Node>();\n let current = getCurrentParentNode(node, context);\n\n while (current && !visited.has(current)) {\n if (isNode(current, N.Ruleset)) {\n return current;\n }\n visited.add(current);\n current = getCurrentParentNode(current, context);\n }\n\n return undefined;\n}\n\nexport function hasSourceExtendWrapperParent(node: Node): boolean {\n const parent = node.parent;\n if (!isNode(parent, N.Rules)) {\n return false;\n }\n\n const sourceRules = isNode(parent.sourceNode, N.Rules)\n ? parent.sourceNode as Rules\n : parent;\n const sourceChildren = sourceRules.value;\n\n let sawExtend = false;\n let sawRuleset = false;\n for (const child of sourceChildren) {\n if (isNode(child, N.Extend)) {\n sawExtend = true;\n continue;\n }\n if (isNode(child, N.Ruleset)) {\n sawRuleset = true;\n }\n }\n\n return sawExtend && sawRuleset;\n}\n\nfunction flattenSelectorListAlternatives(list: SelectorList): SelectorList {\n const flattened: Selector[] = [];\n const seen = new Set<string>();\n\n const pushUnique = (selector: Selector): void => {\n const key = selector.valueOf();\n if (seen.has(key)) {\n return;\n }\n seen.add(key);\n flattened.push(selector);\n };\n\n for (const item of list.get('value')) {\n if (isNode(item, N.PseudoSelector) && item.get('name') === ':is' && isNode(item.get('arg'), N.SelectorList)) {\n const arg = item.get('arg');\n if (isNode(arg, N.SelectorList)) {\n for (const child of arg.get('value')) {\n pushUnique(child);\n }\n }\n continue;\n }\n\n if (isNode(item, N.CompoundSelector) && item.get('value').length === 1) {\n const only = item.get('value')[0]!;\n if (isNode(only, N.PseudoSelector) && only.get('name') === ':is' && isNode(only.get('arg'), N.SelectorList)) {\n const arg = only.get('arg');\n if (isNode(arg, N.SelectorList)) {\n for (const child of arg.get('value')) {\n pushUnique(child);\n }\n }\n continue;\n }\n }\n\n if (isNode(item, N.ComplexSelector) && item.get('value').length === 1) {\n const only = item.get('value')[0]!;\n if (isNode(only, N.PseudoSelector) && only.get('name') === ':is' && isNode(only.get('arg'), N.SelectorList)) {\n const arg = only.get('arg');\n if (isNode(arg, N.SelectorList)) {\n for (const child of arg.get('value')) {\n pushUnique(child);\n }\n }\n continue;\n }\n }\n\n pushUnique(item);\n }\n\n if (flattened.length === list.get('value').length) {\n return list;\n }\n\n return SelectorList.create(flattened).inherit(list);\n}\n\n/**\n * Wraps a parent selector into the single selector fragment that should appear\n * inside another selector context.\n *\n * A selector list becomes generated `:is(...)` so it can occupy one selector\n * position without AST mutation. Non-lists are copied directly.\n */\nexport function wrapParentSelectorForNestedContext(\n parentSelector: Selector,\n _collapseNesting: boolean = false\n): Selector {\n let parentCopy = parentSelector.copy(true);\n if (isNode(parentCopy, N.SelectorList)) {\n parentCopy = flattenSelectorListAlternatives(parentCopy);\n }\n if (isNode(parentCopy, N.ComplexSelector)) {\n const requiresGrouping = parentCopy.get('value').some(\n part => isNode(part, N.Combinator) && part.valueOf() !== ' '\n );\n if (requiresGrouping) {\n const wrapped = PseudoSelector.create({ name: ':is', arg: parentCopy });\n wrapped.generated = true;\n return wrapped;\n }\n }\n if (isNode(parentCopy, N.SelectorList)) {\n const wrapped = PseudoSelector.create({ name: ':is', arg: parentCopy });\n wrapped.generated = true;\n return wrapped;\n }\n return parentCopy;\n}\n\n/**\n * Returns the selector fragment(s) that should replace an authored ampersand.\n *\n * Selector-list parents become generated `:is(...)` wrappers so they can occupy\n * one selector position. Complex parents splice directly only when the\n * ampersand is the leading component of the containing route; otherwise they\n * remain wrapped to preserve route validity.\n */\nexport function getParentReplacementForAmpersand(\n parentSelector: Selector,\n atStart: boolean\n): Selector[] {\n const parentCopy = parentSelector.copy(true);\n\n if (isNode(parentCopy, N.SelectorList)) {\n return [wrapParentSelectorForNestedContext(parentCopy)];\n }\n\n if (isNode(parentCopy, N.ComplexSelector)) {\n if (atStart) {\n return [...parentCopy.get('value')];\n }\n\n const wrapped = PseudoSelector.create({\n name: ':is',\n arg: parentCopy\n });\n wrapped.generated = true;\n return [wrapped];\n }\n\n return [parentCopy];\n}\n\nexport function selectorHasAuthoredAmpersand(selector: Selector): boolean {\n if (isNode(selector, N.Ampersand)) {\n return !selector.hasFlag(F_IMPLICIT_AMPERSAND);\n }\n\n if (isNode(selector, N.SelectorList | N.ComplexSelector | N.CompoundSelector)) {\n return selector.get('value').some(item => selectorHasAuthoredAmpersand(item));\n }\n\n if (isNode(selector, N.PseudoSelector)) {\n const arg = (selector as PseudoSelector).get('arg');\n if (arg && isNode(arg, N.Selector)) {\n return selectorHasAuthoredAmpersand(arg);\n }\n }\n\n return false;\n}\n\nfunction selectorContainsGeneratedIs(selector: Selector): boolean {\n if (isNode(selector, N.PseudoSelector)) {\n return selector.generated && selector.get('name') === ':is';\n }\n\n if (isNode(selector, N.SelectorList | N.ComplexSelector | N.CompoundSelector)) {\n return selector.get('value').some(item => selectorContainsGeneratedIs(item));\n }\n\n return false;\n}\n\n/**\n * Apply an ampersand's template (suffix like `-1` or template like `.&-foo`)\n * to a resolved parent selector. Mirrors the logic in Ampersand.evalNode but\n * operates on the already-resolved replacement selector.\n */\nfunction applyTemplate(resolved: Selector, template: string, inherit: Selector): Selector {\n const normalizedTemplate = template.replace(ampersandTemplateInterpolationRegex, 'x');\n if (normalizedTemplate === 'nil' || !ampersandTemplateRegex.test(normalizedTemplate)) {\n throw new SyntaxError(`Invalid ampersand template \"${template}\"`);\n }\n\n const isTemplateMerge = template.includes('&');\n if (isTemplateMerge) {\n const isIdentJoinChar = (char: string | undefined): boolean =>\n !!char && /[a-zA-Z0-9_-]/.test(char);\n const assertValidTemplateJoin = (template: string, replacement: string): void => {\n if (!replacement) {\n return;\n }\n let searchFrom = 0;\n while (true) {\n const idx = template.indexOf('&', searchFrom);\n if (idx === -1) {\n break;\n }\n const before = idx > 0 ? template[idx - 1] : undefined;\n const after = idx < template.length - 1 ? template[idx + 1] : undefined;\n const first = replacement[0];\n const last = replacement[replacement.length - 1];\n const invalidHeadJoin = (first === '.' || first === '#') && isIdentJoinChar(before);\n const invalidTailJoin = (last === '.' || last === '#') && isIdentJoinChar(after);\n if (invalidHeadJoin || invalidTailJoin) {\n throw new SyntaxError(`Invalid ampersand merge template \"${template}\" with parent selector \"${replacement}\"`);\n }\n searchFrom = idx + 1;\n }\n };\n const applyTemplate = (sel: Selector): Selector => {\n const value = sel.toTrimmedString();\n assertValidTemplateJoin(template, value);\n return new BasicSelector(template.split('&').join(value)).inherit(inherit);\n };\n const distributeTemplate = (sel: Selector): Selector => {\n if (\n isNode(sel, N.PseudoSelector)\n && sel.generated\n && sel.get('name') === ':is'\n && isNode(sel.get('arg'), N.SelectorList)\n ) {\n const arg = sel.get('arg');\n return isNode(arg, N.Selector) ? distributeTemplate(arg) : sel;\n }\n if (isNode(sel, N.SelectorList)) {\n const items = sel.get('value').map(item => distributeTemplate(item));\n const result = SelectorList.create(\n items.flatMap(item => isNode(item, N.SelectorList) ? item.get('value') : [item])\n ).inherit(inherit);\n return result;\n }\n const selectorStr = sel.toTrimmedString();\n if (selectorStr.includes(',')) {\n const parts = selectorStr.split(',').map(s => s.trim()).filter(Boolean);\n const mapped = parts.map((part) => {\n assertValidTemplateJoin(template, part);\n return new BasicSelector(template.split('&').join(part)).inherit(inherit);\n });\n return mapped.length === 1 ? mapped[0]! : SelectorList.create(mapped).inherit(inherit);\n }\n return applyTemplate(sel);\n };\n return distributeTemplate(resolved);\n }\n\n const doAppend = (n: Selector): void => {\n for (const s of n.nodes(true)) {\n if (isNode(s, N.SimpleSelector)) {\n if (isNode(s, N.BasicSelector)) {\n (s as BasicSelector).value = (s as BasicSelector).value + template;\n return;\n }\n throw new SyntaxError(`Cannot append \"${template}\" to this type of selector`);\n }\n }\n throw new SyntaxError(`Cannot append \"${template}\" to this type of selector`);\n };\n\n // Unwrap generated :is(SelectorList) so append distributes to all items\n let target = resolved;\n if (\n isNode(target, N.PseudoSelector)\n && target.generated\n && target.get('name') === ':is'\n && isNode(target.get('arg'), N.SelectorList)\n ) {\n const arg = target.get('arg');\n if (isNode(arg, N.Selector)) {\n target = arg;\n }\n }\n if (isNode(target, N.SelectorList)) {\n target.get('value').forEach(item => doAppend(item));\n } else {\n doAppend(target);\n }\n resolved.hoistToRoot = true;\n return resolved;\n}\n\nfunction resolveAuthoredAmpersands(\n selector: Selector,\n parentSelector: Selector,\n atTopLevel: boolean = true\n): Selector {\n if (isNode(selector, N.Ampersand)) {\n const template = selector.template;\n if (template instanceof Nil) {\n const nilResult = new Nil().inherit(selector);\n nilResult.hoistToRoot = true;\n return nilResult;\n }\n const replacement = getParentReplacementForAmpersand(parentSelector, true);\n let resolved = replacement.length === 1\n ? replacement[0]!\n : ComplexSelector.create(replacement).inherit(selector);\n if (typeof template === 'string' && template) {\n resolved = applyTemplate(resolved, template, selector);\n }\n if (template !== undefined) {\n resolved.hoistToRoot = true;\n }\n return resolved;\n }\n\n if (isNode(selector, N.SelectorList)) {\n return SelectorList.create(\n selector.get('value').map(item => resolveAuthoredAmpersands(item, parentSelector))\n ).inherit(selector);\n }\n\n // CompoundSelector with leading bare & and ComplexSelector parent at top level:\n // Fuse parent's last part with compound suffix → * b[e] instead of :is(* b)[e]\n // Only at top level — inside a ComplexSelector (e.g. after +), keep :is() wrapping.\n if (atTopLevel && isNode(selector, N.CompoundSelector)) {\n const compoundData = selector.get('value');\n if (\n compoundData.length >= 2\n && isNode(compoundData[0], N.Ampersand)\n && !compoundData[0]!.hasFlag(F_IMPLICIT_AMPERSAND)\n && compoundData[0].isPlainAmpersand()\n && isNode(parentSelector, N.ComplexSelector)\n ) {\n const parentParts = [...parentSelector.get('value')];\n const remaining = compoundData.slice(1).map(d => resolveAuthoredAmpersands(d, parentSelector));\n const lastParentPart = parentParts[parentParts.length - 1]!.clone(false);\n const fusedLast = CompoundSelector.create([lastParentPart, ...remaining]).inherit(selector);\n const prefix = parentParts.slice(0, -1).map(p => p.clone(false));\n if (prefix.length > 0) {\n return ComplexSelector.create([...prefix, fusedLast]).inherit(selector);\n }\n return fusedLast;\n }\n }\n\n if (isNode(selector, N.ComplexSelector | N.CompoundSelector)) {\n const selectorData = selector.get('value');\n const nextData: Selector[] = [];\n let hasAppendValue = false;\n const isCompound = isNode(selector, N.CompoundSelector);\n for (let i = 0; i < selectorData.length; i++) {\n const item = selectorData[i];\n if (isNode(item, N.Ampersand) && !item.hasFlag(F_IMPLICIT_AMPERSAND)) {\n const template = item.template;\n const atStart = !isCompound && i === 0;\n if (template instanceof Nil) {\n hasAppendValue = true;\n continue;\n }\n const parts = getParentReplacementForAmpersand(parentSelector, atStart);\n if (typeof template === 'string' && template) {\n let resolved = parts.length === 1\n ? parts[0]!\n : ComplexSelector.create(parts).inherit(item);\n resolved = applyTemplate(resolved, template, item);\n nextData.push(resolved);\n hasAppendValue = true;\n } else {\n nextData.push(...parts);\n if (template !== undefined) {\n hasAppendValue = true;\n }\n }\n continue;\n }\n // Fuse complex parent into compound at ComplexSelector start position:\n // e.g. &.foo with parent .a .b → .a .b.foo (not :is(.a .b).foo)\n if (\n !isCompound && i === 0\n && isNode(item, N.CompoundSelector)\n && isNode(parentSelector, N.ComplexSelector)\n ) {\n const compoundData = item.get('value');\n if (compoundData.length > 0 && isNode(compoundData[0], N.Ampersand) && !compoundData[0]!.hasFlag(F_IMPLICIT_AMPERSAND)) {\n const ampTemplate = compoundData[0].template;\n if (ampTemplate === undefined) {\n const parentParts = [...parentSelector.get('value')];\n const remaining = compoundData.slice(1).map(d => resolveAuthoredAmpersands(d, parentSelector));\n const lastParentPart = parentParts[parentParts.length - 1]!.copy(true);\n const compoundItems = [lastParentPart, ...remaining];\n const fusedLast = CompoundSelector.create(compoundItems).inherit(item);\n const prefix = parentParts.slice(0, -1).map(p => p.copy(true));\n if (prefix.length > 0) {\n nextData.push(...prefix, fusedLast);\n } else {\n nextData.push(fusedLast);\n }\n continue;\n }\n }\n }\n nextData.push(resolveAuthoredAmpersands(item, parentSelector, false));\n }\n // For compounds, sort type/element selectors before class/id/pseudo\n if (isCompound) {\n nextData.sort((a, b) => {\n const aIsTag = isNode(a, N.BasicSelector) && a.isTag ? 0 : 1;\n const bIsTag = isNode(b, N.BasicSelector) && b.isTag ? 0 : 1;\n return aIsTag - bIsTag;\n });\n }\n if (nextData.length === 0) {\n const nilResult = new Nil().inherit(selector);\n nilResult.hoistToRoot = hasAppendValue;\n return nilResult;\n }\n const ctor = !isCompound ? ComplexSelector : CompoundSelector;\n const result = ctor.create(nextData).inherit(selector);\n if (hasAppendValue) {\n result.hoistToRoot = true;\n }\n return result;\n }\n\n if (isNode(selector, N.PseudoSelector)) {\n const arg = selector.get('arg');\n if (arg && isNode(arg, N.Selector)) {\n const copy = selector.copy(true);\n const nextArg = resolveAuthoredAmpersands(arg, parentSelector);\n copy.adopt(nextArg);\n copy.arg = nextArg;\n return copy;\n }\n }\n\n return selector.copy(true);\n}\n\nfunction composeSelectorRouteWithParent(\n selector: Selector,\n parentSelector: Selector\n): Selector {\n const childCopy = selector.copy(true);\n if (selectorHasAuthoredAmpersand(childCopy)) {\n return resolveAuthoredAmpersands(childCopy, parentSelector);\n }\n const parentParts = getParentReplacementForAmpersand(parentSelector, true);\n\n if (isNode(childCopy, N.ComplexSelector)) {\n const nextData = [...parentParts];\n\n if (!isNode(childCopy.get('value')[0], N.Combinator)) {\n nextData.push(Combinator.create(' '));\n }\n\n nextData.push(...childCopy.get('value'));\n return ComplexSelector.create(nextData).inherit(selector);\n }\n\n return ComplexSelector.create([\n ...parentParts,\n Combinator.create(' '),\n childCopy\n ]).inherit(selector);\n}\n\n/**\n * Composes a selector with its parent selector without inserting implicit\n * ampersands or relying on later `:is(...)` cleanup passes.\n *\n * The historical `getImplicitSelector()` name is kept for compatibility with\n * callers and tests, but the implementation is now pure selector composition.\n *\n * - Start-position parent composition follows the same rule as authored `&`:\n * selector-list parents stay one fragment via generated `:is(...)`, while\n * non-list parents splice directly.\n * - Selector-list children keep their list shape after composition.\n * - Selector-list children containing complex items are grouped under one\n * generated `:is(...)` before the parent is composed so the common parent\n * stays shared.\n * @param collapseNesting - Whether to collapse nesting (affects visibility flags)\n * @returns The composed selector\n */\nexport function getImplicitSelector(\n selector: Selector,\n parent: Selector,\n collapseNesting: boolean = false\n): Selector {\n if (isNode(selector, N.Nil)) {\n return selector;\n }\n\n const parentSelector = parent;\n if (!parentSelector || isNode(parentSelector, N.Nil)) {\n return selector.copy(true);\n }\n\n if (isNode(selector, N.SelectorList)) {\n const shouldGroupSelectorListBeforeComposition = (\n !selectorHasAuthoredAmpersand(selector)\n && (\n !collapseNesting\n ? selector.get('value').some(item =>\n isNode(item, N.ComplexSelector) && item.get('value').length > 1\n )\n : (\n !isNode(parentSelector, N.SelectorList)\n && !selectorContainsGeneratedIs(parentSelector)\n )\n )\n );\n\n if (shouldGroupSelectorListBeforeComposition) {\n const grouped = PseudoSelector.create({\n name: ':is',\n arg: selector.copy(true)\n });\n grouped.generated = true;\n selector = composeSelectorRouteWithParent(grouped, parentSelector);\n if (collapseNesting) {\n selector.hoistToRoot = true;\n }\n return selector;\n }\n\n const next = selector.get('value').map(item =>\n composeSelectorRouteWithParent(item, parentSelector)\n );\n const list = SelectorList.create(next).inherit(selector);\n if (collapseNesting) {\n list.hoistToRoot = true;\n }\n return list;\n }\n\n selector = composeSelectorRouteWithParent(selector, parentSelector);\n\n if (collapseNesting) {\n selector.hoistToRoot = true;\n }\n return selector;\n}\n\n/**\n * Removes one leading parent composition from a selector so nested rulesets can\n * keep rendering local selector shape while their concrete `data.selector`\n * remains fully composed for matching.\n *\n * Only alternatives that actually start with the serialized parent prefix are\n * de-prefixed. Mixed selector lists therefore keep escaped/hoisted alternatives\n * intact while converting same-parent alternatives back to local form.\n */\nexport function localizeSelectorAgainstParent(\n selector: Selector,\n parent: Selector\n): Selector {\n const wrappedParent = wrapParentSelectorForNestedContext(parent, false);\n const parentPrefix = isNode(wrappedParent, N.ComplexSelector)\n ? [...wrappedParent.get('value')]\n : [wrappedParent];\n\n const stripParentPrefix = (route: Selector): Selector => {\n if (!isNode(route, N.ComplexSelector)) {\n return route.copy(true);\n }\n\n const data = route.get('value');\n if (data.length <= parentPrefix.length) {\n return route.copy(true);\n }\n\n for (let i = 0; i < parentPrefix.length; i++) {\n if (data[i]!.valueOf() !== parentPrefix[i]!.valueOf()) {\n return route.copy(true);\n }\n }\n\n const next = data[parentPrefix.length];\n if (!isNode(next, N.Combinator) || next.valueOf() !== ' ') {\n return route.copy(true);\n }\n\n const remainder = data.slice(parentPrefix.length + 1).map(node => node.copy(true));\n if (remainder.length === 0) {\n return route.copy(true);\n }\n if (remainder.length === 1) {\n return remainder[0]!;\n }\n return ComplexSelector.create(remainder).inherit(route);\n };\n\n if (isNode(selector, N.SelectorList)) {\n return SelectorList.create(\n selector.get('value').map(item => stripParentPrefix(item))\n ).inherit(selector);\n }\n\n return stripParentPrefix(selector);\n}\n\n/** Returns true if the selector (or any top-level SelectorList item) has F_EXTENDED. */\nexport function hasExtendedSelector(sel: Selector | Nil | undefined, context?: Context): boolean {\n if (!sel || sel instanceof Nil) {\n return false;\n }\n if (isNode(sel, N.SelectorList)) {\n return sel.get('value').some(item =>\n context ? item._hasFlag(F_EXTENDED, context) : item.hasFlag(F_EXTENDED)\n );\n }\n return context\n ? sel._hasFlag(F_EXTENDED, context)\n : sel.hasFlag(F_EXTENDED);\n}\n","import type { Selector } from '../selector.js';\nimport type { Context } from '../../context.js';\nimport { SelectorList } from '../selector-list.js';\nimport { CompoundSelector } from '../selector-compound.js';\nimport { ComplexSelector } from '../selector-complex.js';\nimport type { ComplexSelectorValue } from '../selector-complex.js';\nimport { PseudoSelector } from '../selector-pseudo.js';\nimport { Combinator } from '../combinator.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport { getImplicitSelector, getParentReplacementForAmpersand, wrapParentSelectorForNestedContext } from './selector-utils.js';\nimport { selectorMatch } from './selector-match-core.js';\nimport { Node } from '../node.js';\nimport { CANONICAL, EVAL, F_AMPERSAND } from '../node-base.js';\nimport { addParentEdge } from './cursor.js';\n\n/**\n * @todo Once extend correctness is stabilized and the remaining suites are\n * green, do a dedicated performance review of this file. Focus on:\n * - repeated nested `selectorMatch()` calls\n * - unnecessary selector copying or wrapper allocation\n * - opportunities to thread match metadata instead of recomputing it\n */\n\n/**\n * Extend failure categories surfaced to callers while the rewrite remains\n * intentionally incremental.\n */\nexport type ExtendErrorType =\n 'NOT_FOUND'\n | 'ELEMENT_CONFLICT'\n | 'ID_CONFLICT'\n | 'AMPERSAND_BOUNDARY'\n | 'PARTIAL_MATCH';\n\nexport const ExtendErrorType = {\n NOT_FOUND: 'NOT_FOUND' as const,\n ELEMENT_CONFLICT: 'ELEMENT_CONFLICT' as const,\n ID_CONFLICT: 'ID_CONFLICT' as const,\n AMPERSAND_BOUNDARY: 'AMPERSAND_BOUNDARY' as const,\n PARTIAL_MATCH: 'PARTIAL_MATCH' as const\n} as const;\n\n/**\n * Structured extend failure used instead of throwing during selector rewrites.\n */\nexport class ExtendError extends Error {\n constructor(\n public type: ExtendErrorType,\n message: string\n ) {\n super(message);\n this.name = 'ExtendError';\n }\n}\n\n/**\n * Result of trying to extend a selector.\n *\n * `value` is always returned so callers can keep using the original selector on\n * misses without additional branching.\n */\nexport interface ExtendResult {\n value: Selector;\n error?: ExtendError;\n isChanged: boolean;\n}\n\n/** Creates a successful extend result around the mutated or rewritten selector. */\nfunction createSuccessResult(value: Selector, isChanged = true): ExtendResult {\n return { value, isChanged };\n}\n\n/** Creates a failed extend result while preserving the original selector. */\nfunction createErrorResult(value: Selector, type: ExtendErrorType, message: string): ExtendResult {\n return {\n value,\n error: new ExtendError(type, message),\n isChanged: false\n };\n}\n\nfunction expandGeneratedIsAlternatives(selector: Selector): Selector[] {\n if (\n isNode(selector, N.PseudoSelector)\n && selector.generated === true\n && selector.get('name') === ':is'\n && getSelectorListArg(selector)\n ) {\n return [...getSelectorListArg(selector)!.get('value')];\n }\n\n return [selector];\n}\n\nfunction getDerivedSelectorRenderKey(source: Selector): symbol | number {\n return source.renderKey === CANONICAL ? EVAL : source.renderKey;\n}\n\nfunction finalizeDerivedSelector<T extends Selector>(\n source: Selector,\n nextNode: T,\n reusedChildren: readonly unknown[]\n): T {\n const priorParents = reusedChildren.flatMap(child =>\n child instanceof Node ? [[child, child.parent] as const] : []\n );\n nextNode.inherit(source);\n nextNode.renderKey = getDerivedSelectorRenderKey(source);\n for (const [child, priorParent] of priorParents) {\n addParentEdge(child, nextNode.renderKey, nextNode);\n Reflect.set(child, 'parent', priorParent);\n }\n return nextNode;\n}\n\nfunction createDerivedValueContainer(source: SelectorList, value: Selector[]): SelectorList;\nfunction createDerivedValueContainer(source: ComplexSelector, value: ComplexSelectorValue): ComplexSelector;\nfunction createDerivedValueContainer(source: CompoundSelector, value: Selector[]): CompoundSelector;\nfunction createDerivedValueContainer(\n source: SelectorList | ComplexSelector | CompoundSelector,\n value: Selector[] | ComplexSelectorValue\n): SelectorList | ComplexSelector | CompoundSelector {\n const nextNode = isNode(source, N.SelectorList)\n ? new SelectorList(value, source.options ? { ...source.options } : undefined, source.location, source.treeContext)\n : isNode(source, N.ComplexSelector)\n ? new ComplexSelector(value, source.options ? { ...source.options } : undefined, source.location, source.treeContext)\n : new CompoundSelector(value, source.options ? { ...source.options } : undefined, source.location, source.treeContext);\n return finalizeDerivedSelector(source, nextNode, value);\n}\n\nfunction cloneComplexSelectorComponent(component: ComplexSelectorValue[number]): ComplexSelectorValue[number] {\n const cloned: ComplexSelectorValue[number] = component instanceof Node\n ? component.copy(true)\n : component;\n return cloned;\n}\n\nfunction createDerivedSelectorListFromSource(\n source: Selector,\n value: Selector[]\n): SelectorList {\n const nextNode = new SelectorList(\n value,\n source.options ? { ...source.options } : undefined,\n source.location,\n source.treeContext\n );\n return finalizeDerivedSelector(source, nextNode, value);\n}\n\nfunction createDerivedPseudoWithArg(\n source: PseudoSelector,\n arg: Selector\n): PseudoSelector {\n const nextNode = PseudoSelector.create(\n { name: source.name, arg },\n source.options ? { ...source.options } : undefined,\n source.location,\n source.treeContext\n );\n nextNode.generated = source.generated;\n return finalizeDerivedSelector(source, nextNode, [arg]);\n}\n\nfunction getSelectorChildren(target: Selector): readonly Selector[] | undefined {\n if (isNode(target, N.SelectorList | N.CompoundSelector | N.ComplexSelector)) {\n return target.get('value');\n }\n return undefined;\n}\n\nfunction getSelectorArg(target: Selector): Selector | undefined {\n if (!isNode(target, N.PseudoSelector)) {\n return undefined;\n }\n const arg = target.get('arg');\n return isNode(arg, N.Selector) ? arg : undefined;\n}\n\nfunction getSelectorListArg(target: Selector): SelectorList | undefined {\n if (!isNode(target, N.PseudoSelector)) {\n return undefined;\n }\n const arg = target.get('arg');\n return isNode(arg, N.SelectorList) ? arg : undefined;\n}\n\nfunction getCompoundSelector(node: Selector): CompoundSelector | undefined {\n return isNode(node, N.CompoundSelector) ? node : undefined;\n}\n\nfunction getComplexSelector(node: Selector): ComplexSelector | undefined {\n return isNode(node, N.ComplexSelector) ? node : undefined;\n}\n\nfunction getSelectorList(node: Selector): SelectorList | undefined {\n return isNode(node, N.SelectorList) ? node : undefined;\n}\n\nfunction normalizeSelectorListAlternatives(list: readonly Selector[]): Selector[] {\n const flattened: Selector[] = [];\n const seen = new Set<string>();\n\n for (const item of list) {\n const itemArgList = isNode(item, N.PseudoSelector) ? getSelectorListArg(item) : undefined;\n if (isNode(item, N.PseudoSelector) && item.get('name') === ':is' && itemArgList) {\n for (const child of itemArgList.get('value')) {\n const key = child.valueOf();\n if (!seen.has(key)) {\n seen.add(key);\n flattened.push(child);\n }\n }\n continue;\n }\n\n const compound = getCompoundSelector(item);\n if (compound && compound.get('value').length === 1) {\n const only = compound.get('value')[0]!;\n const onlyArgList = isNode(only, N.PseudoSelector) ? getSelectorListArg(only) : undefined;\n if (isNode(only, N.PseudoSelector) && only.get('name') === ':is' && onlyArgList) {\n for (const child of onlyArgList.get('value')) {\n const key = child.valueOf();\n if (!seen.has(key)) {\n seen.add(key);\n flattened.push(child);\n }\n }\n continue;\n }\n }\n\n const complex = getComplexSelector(item);\n if (complex && complex.get('value').length === 1) {\n const only = complex.get('value')[0]!;\n const onlyArgList = isNode(only, N.PseudoSelector) ? getSelectorListArg(only) : undefined;\n if (isNode(only, N.PseudoSelector) && only.get('name') === ':is' && onlyArgList) {\n for (const child of onlyArgList.get('value')) {\n const key = child.valueOf();\n if (!seen.has(key)) {\n seen.add(key);\n flattened.push(child);\n }\n }\n continue;\n }\n }\n\n const key = item.valueOf();\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n flattened.push(item);\n }\n return flattened;\n}\n\nfunction canMutateSelectorContainer(target: Selector): boolean {\n return target.renderKey !== CANONICAL || target.sourceNode !== target;\n}\n\nfunction setPseudoArg(target: PseudoSelector, arg: Selector): PseudoSelector {\n if (!canMutateSelectorContainer(target)) {\n return createDerivedPseudoWithArg(target, arg);\n }\n target.adopt(arg);\n target.arg = arg;\n target.invalidateCache();\n return target;\n}\n\nfunction setSelectorContainerValue(\n target: SelectorList | ComplexSelector | CompoundSelector,\n value: Selector[]\n): SelectorList | ComplexSelector | CompoundSelector {\n if (!canMutateSelectorContainer(target)) {\n return createDerivedValueContainer(target, value);\n }\n Reflect.set(target, 'value', value);\n for (const item of value) {\n target.adopt(item);\n }\n target.invalidateCache();\n return target;\n}\n\nfunction setSelectorContainerValueAt(\n target: SelectorList | ComplexSelector | CompoundSelector,\n index: number,\n replacement: Selector\n): SelectorList | ComplexSelector | CompoundSelector {\n const nextValue = target.get('value').slice();\n nextValue[index] = replacement;\n return setSelectorContainerValue(target, nextValue);\n}\n\n/**\n * Appends a new alternative to an existing alternate container by returning\n * a derived container that reuses unchanged child selectors.\n *\n * This is used for exact matches on selector lists and sole `:is(...)`\n * containers, where the correct extend output is to add another alternative\n * rather than wrap the whole selector again.\n */\nfunction appendAlternative(\n target: Selector,\n extendWith: Selector\n): Selector | undefined {\n const next = expandGeneratedIsAlternatives(extendWith);\n\n if (isNode(target, N.SelectorList)) {\n const normalized = normalizeSelectorListAlternatives(target.get('value'));\n const nextItems = normalizeSelectorListAlternatives([...normalized, ...next]);\n return createDerivedValueContainer(target, nextItems);\n }\n\n if (isNode(target, N.PseudoSelector) && target.get('name') === ':is' && getSelectorArg(target)) {\n const arg = getSelectorArg(target)!;\n if (getSelectorList(arg)) {\n const normalized = normalizeSelectorListAlternatives(arg.get('value'));\n const nextItems = normalizeSelectorListAlternatives([...normalized, ...next]);\n return createDerivedPseudoWithArg(target, createDerivedValueContainer(arg, nextItems));\n }\n\n const list = createDerivedSelectorListFromSource(arg, normalizeSelectorListAlternatives([arg, ...next]));\n return createDerivedPseudoWithArg(target, list);\n }\n\n return undefined;\n}\n\n/**\n * Produces the exact-extend output for one fully matched selector.\n *\n * When the matched selector already is an alternate container, the new\n * selector is appended in place. Otherwise a selector list is created around\n * the matched selector and the extension alternative.\n *\n * This is the preferred output for any selector that has an exact full match\n * route, including full-match results discovered while running in partial\n * mode. A generated\n * `:is(...)` wrapper should only be introduced when the rewrite genuinely has\n * to preserve unmatched siblings around a partial match.\n */\nfunction createAlternativeSelector(\n target: Selector,\n extendWith: Selector\n): Selector {\n if (target.valueOf() === extendWith.valueOf()) {\n return target;\n }\n const appended = appendAlternative(target, extendWith);\n if (appended) {\n return appended;\n }\n\n return createDerivedSelectorListFromSource(target, [target, ...expandGeneratedIsAlternatives(extendWith)]);\n}\n\n/**\n * Wraps one matched selector fragment in a generated `:is(original, extendWith)`\n * pseudo so partial extends can preserve unmatched siblings around it.\n *\n * When `selector` and `extendWith` are identical (e.g. `.class:extend(.class all)`),\n * no wrapper is needed — the fragment is marked visible in place and returned as-is.\n */\nfunction wrapSelectorInIs(selector: Selector, extendWith: Selector): Selector {\n // Flatten: if selector is already a generated :is(SelectorList), extract its items\n // instead of nesting :is(:is(...), extension).\n const selectorItems = expandGeneratedIsAlternatives(selector);\n const extendItems = expandGeneratedIsAlternatives(extendWith);\n const allItems = normalizeSelectorListAlternatives([...selectorItems, ...extendItems]);\n\n if (allItems.length === 1) {\n return selector;\n }\n\n const arg = SelectorList.create(allItems).inherit(selector);\n arg.pre = undefined;\n arg.post = undefined;\n\n const wrapper = PseudoSelector.create({\n name: ':is',\n arg\n });\n wrapper.generated = true;\n const inherited = wrapper.inherit(selector);\n inherited.pre = undefined;\n inherited.post = undefined;\n return inherited;\n}\n\n/** Wraps a selector in a generated `:is(...)` without adding another alternate. */\nfunction wrapSelectorAsGeneratedIs(selector: Selector): Selector {\n const wrapper = PseudoSelector.create({\n name: ':is',\n arg: selector\n });\n wrapper.generated = true;\n return wrapper.inherit(selector);\n}\n\ntype CompoundConflictInfo = {\n elements: Set<string>;\n ids: Set<string>;\n};\n\nfunction createCompoundConflictInfo(): CompoundConflictInfo {\n return {\n elements: new Set<string>(),\n ids: new Set<string>()\n };\n}\n\n/**\n * Collects the element and id selectors that can participate in one merged\n * compound position.\n *\n * This mirrors extend's validity rule, not selector serialization. Complex\n * selectors only contribute their terminal position because that is the part\n * that can merge with the surrounding compound. Selector lists and `:is(...)`\n * contribute the union of their alternatives.\n */\nfunction collectCompoundConflictInfo(\n selector: Selector,\n info: CompoundConflictInfo = createCompoundConflictInfo()\n): CompoundConflictInfo {\n if (isNode(selector, N.BasicSelector)) {\n if (selector.isTag) {\n info.elements.add(selector.valueOf());\n } else if (selector.isId) {\n info.ids.add(selector.valueOf());\n }\n return info;\n }\n\n if (isNode(selector, N.CompoundSelector | N.SelectorList)) {\n for (const child of selector.get('value')) {\n collectCompoundConflictInfo(child, info);\n }\n return info;\n }\n\n if (isNode(selector, N.ComplexSelector)) {\n const complexData = selector.get('value');\n for (let i = complexData.length - 1; i >= 0; i--) {\n const child = complexData[i]!;\n if (isNode(child, N.Combinator)) {\n continue;\n }\n collectCompoundConflictInfo(child, info);\n break;\n }\n return info;\n }\n\n if (isNode(selector, N.PseudoSelector) && getSelectorArg(selector) && selector.get('name') === ':is') {\n collectCompoundConflictInfo(getSelectorArg(selector)!, info);\n }\n\n return info;\n}\n\n/**\n * Validates that inserting `extendWith` into the remaining members of one\n * compound position would not create an impossible selector such as\n * `span:is(div, .foo)` or `#first:is(#second, .foo)`.\n */\nfunction getCompoundConflictError(\n surroundingMembers: readonly Selector[],\n extendWith: Selector\n): ExtendError | undefined {\n const surrounding = createCompoundConflictInfo();\n for (const member of surroundingMembers) {\n collectCompoundConflictInfo(member, surrounding);\n }\n\n const extension = collectCompoundConflictInfo(extendWith);\n const surroundingElement = surrounding.elements.size > 0 ? [...surrounding.elements][0]! : undefined;\n const conflictingElement = [...extension.elements].find(element => surroundingElement && element !== surroundingElement);\n if (conflictingElement) {\n return new ExtendError(ExtendErrorType.ELEMENT_CONFLICT, 'Extend would introduce a conflicting element selector');\n }\n\n const surroundingId = surrounding.ids.size > 0 ? [...surrounding.ids][0]! : undefined;\n const conflictingId = [...extension.ids].find(id => surroundingId && id !== surroundingId);\n if (conflictingId) {\n return new ExtendError(ExtendErrorType.ID_CONFLICT, 'Extend would introduce a conflicting id selector');\n }\n\n return undefined;\n}\n\n/**\n * Removes element and id selectors from `selector` when they are already\n * supplied by the surrounding compound context outside the generated `:is(...)`\n * wrapper.\n *\n * This keeps rewrites like `div:is(.a, div.b)` normalized to `div:is(.a, .b)`\n * and `#foo:is(.class, #foo.other)` normalized to `#foo:is(.class, .other)`.\n */\nfunction stripRedundantCompoundContext(\n selector: Selector,\n surroundingMembers: readonly Selector[]\n): Selector {\n const surrounding = createCompoundConflictInfo();\n for (const member of surroundingMembers) {\n collectCompoundConflictInfo(member, surrounding);\n }\n\n const normalize = (node: Selector): Selector | undefined => {\n if (isNode(node, N.BasicSelector)) {\n if (node.isTag && surrounding.elements.has(node.valueOf())) {\n return undefined;\n }\n if (node.isId && surrounding.ids.has(node.valueOf())) {\n return undefined;\n }\n return node;\n }\n\n const compound = getCompoundSelector(node);\n if (compound) {\n const next = compound.get('value')\n .map(child => normalize(child))\n .filter((child): child is Selector => !!child);\n if (next.length === 0) {\n return undefined;\n }\n if (next.length === 1) {\n return next[0]!;\n }\n return CompoundSelector.create(next).inherit(node);\n }\n\n const list = getSelectorList(node);\n if (list) {\n const next = list.get('value')\n .map(child => normalize(child))\n .filter((child): child is Selector => !!child);\n if (next.length === 0) {\n return node;\n }\n if (next.length === 1) {\n return next[0]!;\n }\n return SelectorList.create(next).inherit(node);\n }\n\n if (isNode(node, N.PseudoSelector) && node.get('name') === ':is' && getSelectorArg(node)) {\n const nextArg = normalize(getSelectorArg(node)!);\n if (!nextArg) {\n return undefined;\n }\n const copy = node.copy(true);\n return setPseudoArg(copy, nextArg);\n }\n\n return node;\n };\n\n return normalize(selector) ?? selector;\n}\n\n/**\n * Rewrites a compound-local partial match by replacing only the consumed\n * members with a generated `:is(...)` wrapper and leaving the unmatched\n * remainder in place.\n */\nfunction wrapCompoundMatchRange(\n targetCompound: CompoundSelector,\n startIndex: number,\n endIndex: number,\n matchedIndices: number[] | undefined,\n extendWith: Selector\n): Selector {\n const effectiveMatchedIndices = matchedIndices && matchedIndices.length > 0\n ? matchedIndices\n : Array.from({ length: endIndex - startIndex + 1 }, (_, offset) => startIndex + offset);\n const outsideMembers = getCompoundMembersOutsideRange(targetCompound, startIndex, endIndex, matchedIndices);\n const matched = effectiveMatchedIndices.map(index => targetCompound.value[index]!);\n const matchedSingle = matched.length === 1 ? matched[0]! : undefined;\n const wrapped = wrapSelectorInIs(\n matchedSingle ?? CompoundSelector.create(matched).inherit(targetCompound),\n stripRedundantCompoundContext(extendWith, outsideMembers)\n );\n if (matchedSingle && wrapped === matchedSingle) {\n return targetCompound;\n }\n const nextData: Selector[] = [];\n const matchedIndexSet = new Set(effectiveMatchedIndices);\n\n for (let i = 0; i < targetCompound.value.length; i++) {\n const node = targetCompound.value[i]!;\n if (i === effectiveMatchedIndices[0]) {\n nextData.push(wrapped);\n continue;\n }\n if (matchedIndexSet.has(i)) {\n continue;\n }\n nextData.push(node);\n }\n\n if (nextData.length === 1) {\n return nextData[0]!;\n }\n\n return ComplexSelector.create(nextData).inherit(targetCompound);\n}\n\nfunction getCompoundMembersOutsideRange(\n compoundSelector: CompoundSelector,\n startIndex: number,\n endIndex: number,\n matchedIndices: number[] | undefined\n): Selector[] {\n const effectiveMatchedIndices = matchedIndices && matchedIndices.length > 0\n ? matchedIndices\n : Array.from({ length: endIndex - startIndex + 1 }, (_, offset) => startIndex + offset);\n const matchedIndexSet = new Set(effectiveMatchedIndices);\n\n return compoundSelector.value.filter((_, index) => !matchedIndexSet.has(index));\n}\n\nfunction wrapOrderedMatchRange(\n targetSelector: ComplexSelector,\n startIndex: number,\n endIndex: number,\n extendWith: Selector\n): Selector {\n const matched = targetSelector.value.slice(startIndex, endIndex + 1);\n const wrapped = wrapSelectorInIs(\n matched.length === 1\n ? matched[0]!\n : ComplexSelector.create(matched).inherit(targetSelector),\n extendWith\n );\n const nextData: Selector[] = [];\n\n for (let i = 0; i < targetSelector.value.length; i++) {\n const node = targetSelector.value[i]!;\n if (i === startIndex) {\n nextData.push(wrapped);\n continue;\n }\n if (i > startIndex && i <= endIndex) {\n continue;\n }\n nextData.push(node);\n }\n\n if (nextData.length === 1) {\n return nextData[0]!;\n }\n\n return ComplexSelector.create(nextData).inherit(targetSelector);\n}\n\n/**\n * Replaces one direct child selector inside its parent container.\n *\n * This keeps mutation localized to the owning parent so downstream caches and\n * parent links stay consistent with the node model.\n */\nfunction replaceDirectSelectorChild(\n parent: Selector,\n child: Selector,\n replacement: Selector\n): Selector | undefined {\n const parentChildren = getSelectorChildren(parent);\n\n if (\n isNode(parent, N.PseudoSelector)\n && (\n parent.get('arg') === child\n || (\n getSelectorArg(parent) !== undefined\n && getSelectorArg(parent)!.type === child.type\n && getSelectorArg(parent)!.valueOf() === child.valueOf()\n )\n )\n ) {\n return setPseudoArg(parent, replacement);\n }\n\n if (parentChildren) {\n const index = parentChildren.findIndex(node => node === child);\n const fallbackIndex = index !== -1\n ? index\n : parentChildren.findIndex(node => node.type === child.type && node.valueOf() === child.valueOf());\n if (fallbackIndex !== -1 && isNode(parent, N.SelectorList | N.ComplexSelector | N.CompoundSelector)) {\n return setSelectorContainerValueAt(parent, fallbackIndex, replacement);\n }\n }\n\n return undefined;\n}\n\nfunction getStructurallyMatchingDirectChildSelector(\n target: Selector,\n node: Selector\n): Selector | undefined {\n const arg = getSelectorArg(target);\n if (isNode(target, N.PseudoSelector) && arg) {\n if (arg.type === node.type && arg.valueOf() === node.valueOf()) {\n return arg;\n }\n return undefined;\n }\n\n const children = getSelectorChildren(target);\n if (!children) {\n return undefined;\n }\n\n return children.find(child => child.type === node.type && child.valueOf() === node.valueOf());\n}\n\n/**\n * Resolves authored ampersands in a root complex selector against the provided\n * parent without mutating the original target selector.\n *\n * This is currently used only for full-span crossed matches on the root target\n * route.\n */\nfunction resolveAmpersandTarget(\n target: ComplexSelector,\n parent?: Selector\n): Selector | undefined {\n const nextData: ComplexSelectorValue = [];\n let replacedAny = false;\n\n for (let i = 0; i < target.get('value').length; i++) {\n const component = target.get('value')[i]!;\n if (isNode(component, N.Ampersand)) {\n const resolvedRaw = component.getResolvedSelector() ?? parent;\n if (!resolvedRaw || isNode(resolvedRaw, N.Nil)) {\n nextData.push(cloneComplexSelectorComponent(component));\n continue;\n }\n nextData.push(...getParentReplacementForAmpersand(resolvedRaw, i === 0));\n replacedAny = true;\n continue;\n }\n nextData.push(cloneComplexSelectorComponent(component));\n }\n\n if (!replacedAny) {\n return undefined;\n }\n\n return ComplexSelector.create(nextData).inherit(target);\n}\n\n/**\n * Materializes the original matched target side when an extend crossed a parent\n * boundary.\n *\n * Explicit authored ampersands resolve through their own replacement logic.\n * Plain nested selectors with an implicit parent boundary are composed against\n * `parent` on demand so the resulting selector is self-contained once hoisted\n * or appended as an exact alternative.\n */\nfunction materializeCrossedTarget(\n target: Selector,\n parent: Selector | undefined\n): Selector | undefined {\n const resolvedAmpersands = isNode(target, N.ComplexSelector)\n ? resolveAmpersandTarget(target, parent)\n : undefined;\n if (resolvedAmpersands) {\n return resolvedAmpersands;\n }\n\n if (!parent) {\n return undefined;\n }\n\n // When both are SelectorLists, produce :is(parent) :is(inner) to avoid\n // duplicating the parent prefix across every alternative.\n if (isNode(target, N.SelectorList) && isNode(parent, N.SelectorList)) {\n const parentFragment = wrapParentSelectorForNestedContext(parent, false);\n const innerIs = PseudoSelector.create({ name: ':is', arg: target.copy(true) });\n innerIs.generated = true;\n return ComplexSelector.create([parentFragment, Combinator.create(' '), innerIs]).inherit(target);\n }\n\n return getImplicitSelector(target, parent, false);\n}\n\n/**\n * Materializes authored ampersands throughout a hoisted selector so the\n * returned selector no longer depends on external parent context.\n *\n * Once a rewrite hoists to root, every remaining `&` in the returned selector\n * must be replaced with its parent selector using the same wrapping rules as\n * ordinary ampersand replacement.\n */\nfunction materializeAmpersandsForHoist(\n selector: Selector,\n parent: Selector\n): Selector {\n if (isNode(selector, N.Ampersand)) {\n const resolved = selector.getResolvedSelector() ?? parent;\n const resolvedCopy = resolved.copy(true);\n return materializeAmpersandsForHoist(resolvedCopy, parent);\n }\n\n const selectorList = getSelectorList(selector);\n if (selectorList) {\n const next = selectorList.get('value').map(child =>\n materializeAmpersandsForHoist(child.copy(true), parent)\n );\n const rebuilt = SelectorList.create(next).inherit(selector);\n rebuilt.hoistToRoot = selector.hoistToRoot;\n return rebuilt;\n }\n\n const complex = getComplexSelector(selector);\n if (complex) {\n const nextData: Selector[] = [];\n\n for (let i = 0; i < complex.get('value').length; i++) {\n const child = complex.get('value')[i]!;\n if (isNode(child, N.Ampersand)) {\n const resolved = child.getResolvedSelector() ?? parent;\n const replacement = materializeAmpersandsForHoist(resolved.copy(true), parent);\n nextData.push(...getParentReplacementForAmpersand(replacement, i === 0));\n continue;\n }\n\n nextData.push(materializeAmpersandsForHoist(child.copy(true), parent));\n }\n\n const rebuilt = ComplexSelector.create(nextData).inherit(selector);\n rebuilt.hoistToRoot = selector.hoistToRoot;\n return rebuilt;\n }\n\n const compound = getCompoundSelector(selector);\n if (compound) {\n const nextData: Selector[] = [];\n\n for (const selectorChild of compound.get('value')) {\n if (isNode(selectorChild, N.Ampersand)) {\n const resolved = materializeAmpersandsForHoist((selectorChild.getResolvedSelector() ?? parent)!.copy(true), parent);\n if (isNode(resolved, N.CompoundSelector)) {\n nextData.push(...resolved.get('value'));\n } else if (isNode(resolved, N.ComplexSelector | N.SelectorList)) {\n nextData.push(wrapSelectorAsGeneratedIs(resolved));\n } else {\n nextData.push(resolved);\n }\n continue;\n }\n\n nextData.push(materializeAmpersandsForHoist(selectorChild.copy(true), parent));\n }\n\n if (nextData.length === 1) {\n const only = nextData[0]!;\n only.hoistToRoot = selector.hoistToRoot;\n return only;\n }\n\n const rebuilt = CompoundSelector.create(nextData).inherit(selector);\n rebuilt.hoistToRoot = selector.hoistToRoot;\n return rebuilt;\n }\n\n if (isNode(selector, N.PseudoSelector) && isNode(selector.get('arg'), N.Selector)) {\n const copy = selector.copy(true);\n const nextCopy = setPseudoArg(copy, materializeAmpersandsForHoist(getSelectorArg(selector)!, parent));\n nextCopy.hoistToRoot = selector.hoistToRoot;\n return nextCopy;\n }\n\n const copy = selector.copy(true);\n copy.hoistToRoot = selector.hoistToRoot;\n return copy;\n}\n\nfunction getCrossedAmpersandParent(location: ReturnType<typeof selectorMatch>['matches'][number]): Selector | undefined {\n const crossing = location.ampersandCrossings?.find(crossing => crossing.parentSegment && isNode(crossing.parentSegment.containingNode, N.Selector));\n return crossing?.parentSegment?.containingNode;\n}\n\n/**\n * Rewrites a root compound span that crossed an ampersand by resolving the\n * matched span against the parent seam and leaving unmatched compound members\n * outside the generated `:is(...)`.\n */\nfunction wrapResolvedCompoundSpan(\n targetCompound: CompoundSelector,\n startIndex: number,\n endIndex: number,\n extendWith: Selector,\n resolvedParent: Selector\n): Selector {\n const matchedMembers = targetCompound.value.slice(startIndex, endIndex + 1);\n const matchedSelector = matchedMembers.length === 1\n ? matchedMembers[0]!\n : CompoundSelector.create(matchedMembers).inherit(targetCompound);\n const outsideMembers = targetCompound.value.filter((_: Selector, index: number) => index < startIndex || index > endIndex);\n const wrapped = wrapSelectorInIs(\n materializeAmpersandsForHoist(matchedSelector, resolvedParent),\n stripRedundantCompoundContext(extendWith, outsideMembers)\n );\n const nextData: Selector[] = [];\n\n for (let i = 0; i < targetCompound.value.length; i++) {\n if (i === startIndex) {\n nextData.push(wrapped);\n continue;\n }\n if (i > startIndex && i <= endIndex) {\n continue;\n }\n nextData.push(targetCompound.value[i]!);\n }\n\n if (nextData.length === 1) {\n return nextData[0]!;\n }\n\n return ComplexSelector.create(nextData).inherit(targetCompound);\n}\n\nfunction getLastOrderedSelector(selector: Selector): Selector {\n const complex = getComplexSelector(selector);\n if (complex) {\n for (let i = complex.get('value').length - 1; i >= 0; i--) {\n const child = complex.get('value')[i]!;\n if (!isNode(child, N.Combinator)) {\n return child;\n }\n }\n }\n\n return selector;\n}\n\nfunction buildMatchedCompoundSelector(\n targetCompound: CompoundSelector,\n startIndex: number,\n endIndex: number,\n matchedIndices?: number[]\n): Selector {\n const effectiveMatchedIndices = matchedIndices && matchedIndices.length > 0\n ? matchedIndices\n : Array.from({ length: endIndex - startIndex + 1 }, (_, offset) => startIndex + offset);\n const matched = effectiveMatchedIndices.map(index => targetCompound.value[index]!);\n\n if (matched.length === 1) {\n return matched[0]!;\n }\n\n return CompoundSelector.create(matched).inherit(targetCompound);\n}\n\n/**\n * Rewrites a crossed ordered span whose terminal position is a compound with\n * unmatched tail members that must stay outside the generated `:is(...)`.\n *\n * When the terminal compound crossed an ampersand seam, the matched portion is\n * the full crossed target segment, not just the visible `matchedIndices`.\n * Otherwise the authored `&` would leak into the remainder instead of staying\n * attached to the matched fragment it helped complete.\n */\nfunction wrapResolvedOrderedSpanWithTailRemainder(\n targetSelector: ComplexSelector,\n startIndex: number,\n endIndex: number,\n extendWith: Selector,\n resolvedParent: Selector,\n terminalFind: Selector,\n location?: ReturnType<typeof selectorMatch>['matches'][number],\n context?: Context\n): Selector | undefined {\n const tail = targetSelector.value[endIndex]!;\n if (!isNode(tail, N.CompoundSelector)) {\n return undefined;\n }\n\n const tailMatch = selectorMatch(terminalFind, tail, resolvedParent, context);\n const tailLocation = tailMatch.matches.find(match => match.containingNode === tail);\n if (!tailLocation || tailLocation.startIndex === undefined || tailLocation.endIndex === undefined) {\n return undefined;\n }\n const crossedTailSegment = location?.ampersandCrossings?.find(crossing =>\n crossing.targetSegment.containingNode === tail\n )?.targetSegment ?? tailLocation.ampersandCrossings?.find(crossing =>\n crossing.targetSegment.containingNode === tail\n )?.targetSegment;\n const tailStartIndex = crossedTailSegment?.startIndex ?? tailLocation.startIndex;\n const tailEndIndex = crossedTailSegment?.endIndex ?? tailLocation.endIndex;\n const tailMatchedIndices = crossedTailSegment?.matchedIndices ?? tailLocation.matchedIndices;\n const effectiveTailMatchedIndices = crossedTailSegment ? undefined : tailMatchedIndices;\n\n const matchedPrefix: Selector[] = [];\n for (let i = startIndex; i < endIndex; i++) {\n matchedPrefix.push(materializeAmpersandsForHoist(targetSelector.value[i]!.copy(true), resolvedParent));\n }\n\n const matchedTailSelector = buildMatchedCompoundSelector(\n tail,\n tailStartIndex,\n tailEndIndex,\n effectiveTailMatchedIndices\n );\n matchedPrefix.push(crossedTailSegment\n ? materializeAmpersandsForHoist(matchedTailSelector, resolvedParent)\n : matchedTailSelector);\n\n const orderedMatchedSelector = matchedPrefix.length === 1\n ? matchedPrefix[0]!\n : ComplexSelector.create(matchedPrefix).inherit(targetSelector);\n const wrapped = wrapSelectorInIs(orderedMatchedSelector, extendWith);\n const tailRemainder = getCompoundMembersOutsideRange(\n tail,\n tailStartIndex,\n tailEndIndex,\n effectiveTailMatchedIndices\n );\n const inserted = tailRemainder.length > 0\n ? CompoundSelector.create([wrapped, ...tailRemainder]).inherit(tail)\n : wrapped;\n\n const nextData: Selector[] = [];\n for (let i = 0; i < targetSelector.value.length; i++) {\n if (i === startIndex) {\n nextData.push(inserted);\n continue;\n }\n if (i > startIndex && i <= endIndex) {\n continue;\n }\n nextData.push(targetSelector.value[i]!);\n }\n\n if (nextData.length === 1) {\n return nextData[0]!;\n }\n\n return ComplexSelector.create(nextData).inherit(targetSelector);\n}\n\n/**\n * Rewrites one direct child selector of `target` by delegating to\n * `tryExtendSelector()` on that child and then replacing it through the parent\n * container.\n *\n * This is a structural rewrite step on an already-selected subtree. When that\n * child still belongs to the same authored selector route, the same `parent`\n * context is forwarded so authored ampersands inside the child keep the same\n * resolution context the outer target matched with.\n *\n * The fallback `selectorMatch()` call is only used to recover crossed-seam\n * hoist information for exact child rewrites that do not otherwise surface it\n * on the rewritten child node itself.\n */\nfunction tryExtendDirectChildSelector(\n target: Selector,\n child: Selector | undefined,\n find: Selector,\n extendWith: Selector,\n parent?: Selector,\n crossedAmpersandHint = false,\n context?: Context\n): ExtendResult | undefined {\n if (!child) {\n return undefined;\n }\n\n const nested = tryExtendSelector(child, find, extendWith, true, parent, context);\n if (nested.error) {\n return undefined;\n }\n\n const nextTarget = replaceDirectSelectorChild(target, child, nested.value);\n if (!nextTarget) {\n return undefined;\n }\n\n if (nested.value.hoistToRoot || crossedAmpersandHint) {\n nextTarget.hoistToRoot = true;\n } else if (parent && child.hasFlag(F_AMPERSAND)) {\n const childMatch = selectorMatch(find, child, parent, context);\n if (childMatch.fullMatch && childMatch.crossesAmpersand) {\n nextTarget.hoistToRoot = true;\n }\n }\n return createSuccessResult(nextTarget, nested.isChanged);\n}\n\n/**\n * Finds the direct child selector of `target` that structurally owns `node`.\n *\n * This lets partial rewrites recurse into the nearest direct child selector\n * even when the selected match location lives several wrapper levels below it.\n */\nfunction getContainingDirectChildSelector(\n target: Selector,\n node: Node\n): Selector | undefined {\n if (!isNode(target, N.SelectorList | N.CompoundSelector | N.ComplexSelector)) {\n return undefined;\n }\n\n let current: Node | undefined = node;\n while (current && current.parent && current.parent !== target) {\n current = current.parent;\n }\n\n if (current && current.parent === target && isNode(current, N.Selector)) {\n return current;\n }\n\n return undefined;\n}\n\n/**\n * Returns the single direct child selector selected by one exact location on\n * an ordered or alternate container, when that location maps to exactly one\n * child slot of the current target.\n */\nfunction getSingleMatchedDirectChild(\n target: Selector,\n location: ReturnType<typeof selectorMatch>['matches'][number]\n): Selector | undefined {\n if (\n !isNode(target, N.SelectorList | N.CompoundSelector | N.ComplexSelector)\n || location.containingNode !== target\n || location.startIndex === undefined\n || location.startIndex !== location.endIndex\n ) {\n return undefined;\n }\n\n const children = getSelectorChildren(target);\n return children ? children[location.startIndex] : undefined;\n}\n\n/** Returns the direct selector-valued arg on a pseudo selector, if any. */\nfunction getDirectPseudoArg(\n target: Selector\n): Selector | undefined {\n return isNode(target, N.PseudoSelector) && getSelectorArg(target)\n ? getSelectorArg(target)\n : undefined;\n}\n\n/** Returns the direct selector-valued arg on a `:is(...)` pseudo, if any. */\nfunction getDirectIsArg(\n target: Selector\n): Selector | undefined {\n return isNode(target, N.PseudoSelector) && target.get('name') === ':is' && getSelectorArg(target)\n ? getSelectorArg(target)\n : undefined;\n}\n\n/** Returns the directly rewriteable selector-list container on `target`, if any. */\nfunction getDirectSelectorList(\n target: Selector\n): Selector | undefined {\n return getSelectorList(target) ?? getSelectorListArg(target);\n}\n\n/**\n * Appends to the direct selector-list container that already owns the matched\n * selector, preserving surrounding wrapper shape.\n */\nfunction tryAppendToContainingSelectorList(\n target: Selector,\n containingNode: Selector,\n extendWith: Selector\n): ExtendResult | undefined {\n const list = getDirectSelectorList(target);\n if (!list) {\n return undefined;\n }\n if (containingNode.parent !== list) {\n return undefined;\n }\n\n const replacement = appendAlternative(list, extendWith);\n if (!replacement) {\n return undefined;\n }\n if (list === target) {\n return createSuccessResult(replacement);\n }\n const nextTarget = replaceDirectSelectorChild(target, list, replacement);\n if (!nextTarget) {\n return undefined;\n }\n return createSuccessResult(nextTarget);\n}\n\n/**\n * Appends at the end of the direct selector-list container when `find`\n * fully matches that container under the same parent context.\n */\nfunction tryAppendToDirectSelectorListOnFullMatch(\n target: Selector,\n find: Selector,\n extendWith: Selector,\n parent?: Selector,\n context?: Context\n): ExtendResult | undefined {\n const list = getDirectSelectorList(target);\n if (!list) {\n return undefined;\n }\n const innerMatch = selectorMatch(find, list, parent, context);\n if (!innerMatch.fullMatch) {\n return undefined;\n }\n\n const replacement = appendAlternative(list, extendWith);\n if (!replacement) {\n return undefined;\n }\n if (list === target) {\n if (innerMatch.crossesAmpersand) {\n replacement.hoistToRoot = true;\n }\n return createSuccessResult(replacement);\n }\n const nextTarget = replaceDirectSelectorChild(target, list, replacement);\n if (!nextTarget) {\n return undefined;\n }\n if (innerMatch.crossesAmpersand) {\n nextTarget.hoistToRoot = true;\n }\n return createSuccessResult(nextTarget);\n}\n\nfunction getLastOrderedSelectorIndex(selector: ComplexSelector): number {\n for (let i = selector.value.length - 1; i >= 0; i--) {\n if (!isNode(selector.value[i], N.Combinator)) {\n return i;\n }\n }\n return -1;\n}\n\nfunction mergeCompoundMembersIntoSelector(\n members: readonly Selector[],\n selector: Selector\n): Selector {\n const merged: Selector[] = [...members];\n const compound = getCompoundSelector(selector);\n if (compound) {\n merged.push(...compound.get('value'));\n } else {\n merged.push(selector);\n }\n if (merged.length === 1) {\n return merged[0]!;\n }\n return CompoundSelector.create(merged).inherit(selector);\n}\n\n/**\n * Appends `extendWith` into a nested `:is(...)` when `find` already fully\n * matches a selector that belongs to the same rewritten component.\n *\n * The important distinction here is component identity, not the mere presence\n * of `:is(...)`: when the full match stays attached to the same selector\n * component, the rewrite should append into that component's alternate\n * container instead of widening the outer selector shape. Parent-aware crossed\n * full matches hoist the owning target so the returned selector is later\n * materialized against that parent context.\n */\nfunction tryAppendIntoNestedIsOnFullMatch(\n target: Selector,\n find: Selector,\n extendWith: Selector,\n parent?: Selector,\n context?: Context\n): ExtendResult | undefined {\n if (!isNode(target, N.CompoundSelector | N.ComplexSelector)) {\n return undefined;\n }\n\n const targetData = getSelectorChildren(target);\n if (!targetData) {\n return undefined;\n }\n for (let i = 0; i < targetData.length; i++) {\n const child = targetData[i];\n const childArg = getSelectorArg(child);\n if (!(isNode(child, N.PseudoSelector) && child.get('name') === ':is' && childArg)) {\n continue;\n }\n const innerMatch = selectorMatch(find, childArg, parent, context);\n if (!innerMatch.fullMatch) {\n continue;\n }\n const replacement = appendAlternative(child, extendWith);\n if (!replacement) {\n continue;\n }\n const nextTarget = replaceDirectSelectorChild(target, child, replacement);\n if (!nextTarget) {\n continue;\n }\n if (innerMatch.crossesAmpersand) {\n nextTarget.hoistToRoot = true;\n }\n return createSuccessResult(nextTarget);\n }\n\n return undefined;\n}\n\n/**\n * Pulls matched compound members into the terminal selector of a nested\n * complex branch when those members all refer to the same selector component.\n *\n * This is the case where outer compound members and the branch terminal are\n * interchangeable because they all describe the same element/component. In\n * that situation the rewrite should stay attached to that component rather\n * than widen across the entire outer compound span.\n */\nfunction tryPullCompoundMatchIntoNestedIsBranch(\n target: CompoundSelector,\n location: ReturnType<typeof selectorMatch>['matches'][number],\n find: Selector,\n extendWith: Selector,\n context?: Context\n): ExtendResult | undefined {\n if (!(location.startIndex !== undefined && location.endIndex !== undefined)) {\n return undefined;\n }\n\n const targetValues = target.get('value');\n const pseudoIndex = targetValues.findIndex((node, index) =>\n index >= location.startIndex!\n && index <= location.endIndex!\n && isNode(node, N.PseudoSelector)\n && node.get('name') === ':is'\n && getSelectorArg(node)\n );\n if (pseudoIndex === -1) {\n return undefined;\n }\n\n const pseudoNode = targetValues[pseudoIndex];\n if (!isNode(pseudoNode, N.PseudoSelector)) {\n return undefined;\n }\n const pulledMembers = targetValues.filter((node, index) =>\n index >= location.startIndex!\n && index <= location.endIndex!\n && index !== pseudoIndex\n );\n if (pulledMembers.length === 0) {\n return undefined;\n }\n\n const arg = getSelectorArg(pseudoNode) ?? pseudoNode.get('arg');\n if (!isNode(arg, N.Selector)) {\n return undefined;\n }\n const alternatives = isNode(arg, N.SelectorList)\n ? [...arg.get('value')]\n : [arg];\n\n for (let i = 0; i < alternatives.length; i++) {\n const alternative = alternatives[i]!;\n if (!isNode(alternative, N.ComplexSelector)) {\n continue;\n }\n const lastIndex = getLastOrderedSelectorIndex(alternative);\n if (lastIndex === -1) {\n continue;\n }\n\n const lastSelector = alternative.get('value')[lastIndex]!;\n const merged = mergeCompoundMembersIntoSelector(pulledMembers, lastSelector);\n const mergedMatch = selectorMatch(find, merged, undefined, context);\n if (!mergedMatch.fullMatch) {\n continue;\n }\n\n const wrapped = wrapSelectorInIs(merged, extendWith);\n const nextAlternative = setSelectorContainerValueAt(\n alternative,\n lastIndex,\n wrapped\n );\n const nextArg = isNode(arg, N.SelectorList)\n ? setSelectorContainerValueAt(arg, i, nextAlternative)\n : nextAlternative;\n const nextPseudo = setPseudoArg(pseudoNode, nextArg);\n\n const nextData = targetValues\n .flatMap((node, index) => {\n if (index < location.startIndex! || index > location.endIndex! || index === pseudoIndex) {\n return [index === pseudoIndex ? nextPseudo : node];\n }\n return [];\n });\n const nextTarget = setSelectorContainerValue(target, nextData);\n return createSuccessResult(nextTarget);\n }\n\n return undefined;\n}\n\n/** Picks the most useful rewrite location from a selector-match result. */\nfunction getPreferredMatchLocation(\n target: Selector,\n match: ReturnType<typeof selectorMatch>\n): ReturnType<typeof selectorMatch>['matches'][number] {\n return match.matches.find(location => location.exact && location.containingNode === target)\n ?? match.matches.find(location => location.exact)\n ?? match.matches[0]!;\n}\n\n/**\n * Produces the exact-mode extend output once a full match has already been\n * established by `selectorMatch()`.\n */\nfunction createExactExtendResult(\n target: Selector,\n extendWith: Selector,\n parent: Selector | undefined,\n crossedAmpersand: boolean,\n finalize: (result: ExtendResult) => ExtendResult\n): ExtendResult {\n if (\n isNode(target, N.SelectorList)\n || (isNode(target, N.PseudoSelector) && target.get('name') === ':is' && isNode(target.get('arg'), N.Selector))\n ) {\n // When the match crossed a parent boundary, materialize before appending.\n if (crossedAmpersand) {\n const resolved = materializeCrossedTarget(target, parent);\n if (resolved) {\n return finalize(createSuccessResult(createAlternativeSelector(resolved, extendWith)));\n }\n }\n return finalize(createSuccessResult(createAlternativeSelector(target, extendWith)));\n }\n\n const resolved = crossedAmpersand\n ? materializeCrossedTarget(target, parent)\n : resolveAmpersandTarget(target, parent);\n if (resolved) {\n return finalize(createSuccessResult(createAlternativeSelector(resolved, extendWith)));\n }\n\n return finalize(createSuccessResult(createAlternativeSelector(target, extendWith)));\n}\n\n/**\n * Handles the fallback path where the top-level target had no partial matches,\n * but an exact nested append or direct child rewrite may still be valid.\n */\nfunction tryHandleNoPartialMatch(\n target: Selector,\n find: Selector,\n extendWith: Selector,\n parent: Selector | undefined,\n finalize: (result: ExtendResult) => ExtendResult,\n context?: Context\n): ExtendResult | undefined {\n const nestedIsAppend = tryAppendIntoNestedIsOnFullMatch(target, find, extendWith, parent, context);\n if (nestedIsAppend) {\n return finalize(nestedIsAppend);\n }\n\n const nestedDirectChild = getDirectPseudoArg(target)\n ? tryExtendDirectChildSelector(target, getDirectPseudoArg(target), find, extendWith, parent, false, context)\n : undefined;\n if (nestedDirectChild) {\n if (nestedDirectChild.value.hoistToRoot) {\n target.hoistToRoot = true;\n }\n return finalize(nestedDirectChild);\n }\n\n return undefined;\n}\n\nfunction tryHandleMultiDirectChildFullMatches(\n target: Selector,\n find: Selector,\n extendWith: Selector,\n parent: Selector | undefined,\n finalize: (result: ExtendResult) => ExtendResult,\n context?: Context\n): ExtendResult | undefined {\n if (!isNode(target, N.SelectorList | N.CompoundSelector | N.ComplexSelector)) {\n return undefined;\n }\n\n const matchedChildren: Array<{ index: number; child: Selector }> = [];\n const targetData = getSelectorChildren(target);\n if (!targetData) {\n return undefined;\n }\n for (let i = 0; i < targetData.length; i++) {\n const child = targetData[i];\n if (!child || !isNode(child, N.Selector)) {\n continue;\n }\n if (isNode(child, N.Combinator)) {\n continue;\n }\n\n const childMatch = selectorMatch(find, child, parent, context);\n if (childMatch.crossesAmpersand) {\n continue;\n }\n if (!childMatch.fullMatch && !childMatch.partialMatch) {\n continue;\n }\n matchedChildren.push({ index: i, child });\n }\n\n if (matchedChildren.length < 2) {\n return undefined;\n }\n\n let currentTarget = target;\n let crossedAmpersand = false;\n let anyChanged = false;\n for (const { index, child } of matchedChildren) {\n const childValueBefore = child.valueOf();\n let replacement: Selector | undefined;\n\n if (isNode(target, N.SelectorList)) {\n const result = tryExtendSelector(child, find, extendWith, true, parent, context);\n if (!result.error) {\n replacement = result.value;\n crossedAmpersand ||= !!result.value.hoistToRoot;\n }\n } else if (isNode(target, N.CompoundSelector)) {\n const outsideMembers = getCompoundMembersOutsideRange(\n target,\n index,\n index,\n undefined\n );\n const conflict = getCompoundConflictError(outsideMembers, extendWith);\n if (conflict) {\n return { value: target, error: conflict, isChanged: false };\n }\n\n if (isNode(child, N.CompoundSelector | N.ComplexSelector | N.PseudoSelector | N.SelectorList)) {\n const result = tryExtendSelector(child, find, extendWith, true, parent, context);\n if (!result.error) {\n replacement = result.value;\n crossedAmpersand ||= !!result.value.hoistToRoot;\n }\n } else {\n replacement = wrapSelectorInIs(child, stripRedundantCompoundContext(extendWith, outsideMembers));\n }\n } else {\n if (isNode(child, N.CompoundSelector | N.ComplexSelector | N.PseudoSelector | N.SelectorList)) {\n const result = tryExtendSelector(child, find, extendWith, true, parent, context);\n if (!result.error) {\n replacement = result.value;\n crossedAmpersand ||= !!result.value.hoistToRoot;\n }\n } else {\n replacement = wrapSelectorInIs(child, extendWith);\n }\n }\n\n if (!replacement) {\n continue;\n }\n if (replacement !== child || replacement.valueOf() !== childValueBefore) {\n anyChanged = true;\n }\n currentTarget = setSelectorContainerValueAt(currentTarget, index, replacement);\n }\n\n if (crossedAmpersand) {\n currentTarget.hoistToRoot = true;\n }\n\n return finalize(createSuccessResult(currentTarget, anyChanged));\n}\n\n/**\n * Attempts to extend `target` using `find` and `extendWith`.\n *\n * Exact mode adds a new alternative only when `selectorMatch()` reports a full\n * match. Partial mode wraps only genuinely partial matches; if partial mode\n * finds an exact route, it also adds a new alternative instead of generating a\n * redundant `:is(...)` wrapper.\n *\n * The deciding question is whether the successful match stays attached to the\n * same selector component or crosses a component boundary. When the match\n * remains on the same component, the rewrite should append to that component's\n * alternate container. When it crosses a component boundary, the rewrite may\n * need a generated `:is(...)` wrapper to preserve the unmatched surrounding\n * structure.\n *\n * Put differently: before introducing a generated `:is(...)`, first ask\n * whether `selectorMatch()` found an exact full match route for the selector\n * component being rewritten. If it did, the correct shape is a selector list\n * or an append into an existing alternate container.\n *\n * When `parent` is provided, it is passed directly into `selectorMatch()` as a\n * non-mutating implicit ampersand context. This allows extend callers to search\n * authored selectors against their resolved parent context without first\n * materializing implicit ampersand wrappers into the target tree.\n *\n * Nested `tryExtendSelector()` calls in this file are still structural rewrite\n * helpers on already-selected child selectors. They may reuse the same\n * `parent` when that child is part of the same authored selector route and\n * therefore must preserve the same ampersand resolution context, but they do\n * not widen the search into unrelated outer contexts.\n *\n * This implementation is intentionally being rebuilt in tiny slices on top of\n * `selectorMatch()`. Unsupported rewrite shapes currently return `NOT_FOUND`\n * rather than falling back to legacy extend behavior.\n */\nexport function tryExtendSelector(\n target: Selector,\n find: Selector,\n extendWith: Selector,\n partial: boolean,\n parent?: Selector,\n context?: Context\n): ExtendResult {\n const finalize = (result: ExtendResult): ExtendResult => {\n if (!result.error && parent && result.value.hoistToRoot) {\n return createSuccessResult(materializeAmpersandsForHoist(result.value, parent));\n }\n return result;\n };\n\n const match = selectorMatch(find, target, parent, context);\n if (!partial) {\n if (!match.fullMatch) {\n return createErrorResult(target, ExtendErrorType.NOT_FOUND, 'Selector not found');\n }\n\n return createExactExtendResult(target, extendWith, parent, match.crossesAmpersand, finalize);\n }\n\n if (!match.partialMatch || match.matches.length === 0) {\n const noPartialMatchResult = tryHandleNoPartialMatch(target, find, extendWith, parent, finalize, context);\n if (noPartialMatchResult) {\n return noPartialMatchResult;\n }\n\n return createErrorResult(target, ExtendErrorType.NOT_FOUND, 'Selector not found');\n }\n\n const earlyDirectListAppend = tryAppendToDirectSelectorListOnFullMatch(target, find, extendWith, parent, context);\n if (earlyDirectListAppend) {\n return finalize(earlyDirectListAppend);\n }\n\n const multiDirectChildFullMatch = tryHandleMultiDirectChildFullMatches(\n target,\n find,\n extendWith,\n parent,\n finalize,\n context\n );\n if (multiDirectChildFullMatch) {\n return multiDirectChildFullMatch;\n }\n\n const location = getPreferredMatchLocation(target, match);\n const crossedAmpersand = !!(location.crossesAmpersand || match.crossesAmpersand);\n const markTargetHoist = (extra = false): void => {\n if (crossedAmpersand || extra) {\n target.hoistToRoot = true;\n }\n };\n const finishNested = (\n result: ExtendResult | undefined,\n extraHoist = false\n ): ExtendResult | undefined => {\n if (!result) {\n return undefined;\n }\n\n markTargetHoist(extraHoist || !!result.value.hoistToRoot);\n return finalize(result);\n };\n const finishRootReplacement = (\n replacement: Selector,\n preserveRootKinds: number\n ): ExtendResult => {\n if (replacement === target) {\n return finalize(createSuccessResult(target, false));\n }\n if (isNode(replacement, preserveRootKinds)) {\n const rootTarget = getSelectorChildren(target) ? target : undefined;\n if (!rootTarget) {\n return finalize(createSuccessResult(replacement));\n }\n const nextTarget = setSelectorContainerValue(\n rootTarget,\n [...getSelectorChildren(replacement)!]\n );\n if (crossedAmpersand) {\n nextTarget.hoistToRoot = true;\n }\n return finalize(createSuccessResult(nextTarget));\n }\n\n if (crossedAmpersand) {\n replacement.hoistToRoot = true;\n }\n return finalize(createSuccessResult(replacement));\n };\n const finishStructuralChildRewrite = (\n child: Selector | undefined\n ): ExtendResult | undefined => {\n if (!child) {\n return undefined;\n }\n\n const nested = tryExtendSelector(child, find, extendWith, true, parent, context);\n const nextTarget = nested.error ? undefined : replaceDirectSelectorChild(target, child, nested.value);\n if (!nextTarget) {\n return undefined;\n }\n\n if (crossedAmpersand || nested.value.hoistToRoot) {\n nextTarget.hoistToRoot = true;\n }\n return finalize(createSuccessResult(nextTarget, nested.isChanged));\n };\n const tryHandleRootSingleSlotPartial = (): ExtendResult | undefined => {\n const rootIsOrdered = isNode(target, N.ComplexSelector) || isNode(target, N.CompoundSelector);\n const targetChildren = getSelectorChildren(target);\n const orderedTarget = getComplexSelector(target) ?? getCompoundSelector(target);\n if (\n !rootIsOrdered\n || location.containingNode !== target\n || location.startIndex === undefined\n || location.endIndex === undefined\n || location.startIndex !== location.endIndex\n || (\n targetChildren !== undefined\n && isNode(targetChildren[location.startIndex]!, N.CompoundSelector)\n && location.matchedIndices\n && location.matchedIndices.length > 0\n )\n ) {\n return undefined;\n }\n\n const compoundTarget = getCompoundSelector(target);\n const compoundOutsideMembers = compoundTarget\n ? getCompoundMembersOutsideRange(\n compoundTarget,\n location.startIndex,\n location.endIndex,\n location.matchedIndices\n )\n : undefined;\n\n if (compoundTarget) {\n const conflict = getCompoundConflictError(compoundOutsideMembers!, extendWith);\n if (conflict) {\n return { value: target, error: conflict, isChanged: false };\n }\n }\n\n const existing = targetChildren![location.startIndex]!;\n const nestedIsListAppend = tryAppendToDirectSelectorListOnFullMatch(existing, find, extendWith, parent, context);\n if (nestedIsListAppend) {\n const nextTarget = setSelectorContainerValueAt(\n orderedTarget!,\n location.startIndex,\n nestedIsListAppend.value\n );\n if (crossedAmpersand || nestedIsListAppend.value.hoistToRoot) {\n nextTarget.hoistToRoot = true;\n }\n return finalize(createSuccessResult(nextTarget));\n }\n\n if (\n isNode(existing, N.PseudoSelector | N.SelectorList | N.CompoundSelector | N.ComplexSelector)\n && !isNode(existing, N.CompoundSelector)\n ) {\n const nested = tryExtendSelector(existing, find, extendWith, true, parent, context);\n if (!nested.error) {\n const nextTarget = setSelectorContainerValueAt(\n orderedTarget!,\n location.startIndex,\n nested.value\n );\n if (crossedAmpersand || nested.value.hoistToRoot) {\n nextTarget.hoistToRoot = true;\n }\n return finalize(createSuccessResult(nextTarget, nested.isChanged));\n }\n }\n\n const wrapped = wrapSelectorInIs(existing, stripRedundantCompoundContext(extendWith, compoundOutsideMembers ?? []));\n const nextTarget = setSelectorContainerValueAt(\n orderedTarget!,\n location.startIndex,\n wrapped\n );\n if (crossedAmpersand) {\n nextTarget.hoistToRoot = true;\n }\n return finalize(createSuccessResult(nextTarget, wrapped !== existing));\n };\n const tryHandleRootMultiSlotPartial = (): ExtendResult | undefined => {\n const compoundTarget = getCompoundSelector(target);\n if (\n compoundTarget\n && location.containingNode === target\n && location.startIndex !== undefined\n && location.endIndex !== undefined\n && location.startIndex < location.endIndex\n ) {\n const crossedAmpersandParent = getCrossedAmpersandParent(location);\n if (crossedAmpersandParent) {\n const replacement = wrapResolvedCompoundSpan(\n compoundTarget,\n location.startIndex,\n location.endIndex,\n extendWith,\n crossedAmpersandParent\n );\n return finishRootReplacement(replacement, N.ComplexSelector | N.CompoundSelector);\n }\n\n const outsideMembers = getCompoundMembersOutsideRange(\n compoundTarget,\n location.startIndex,\n location.endIndex,\n location.matchedIndices\n );\n const conflict = getCompoundConflictError(outsideMembers, extendWith);\n if (conflict) {\n return { value: target, error: conflict, isChanged: false };\n }\n\n const pulledIntoNestedIs = tryPullCompoundMatchIntoNestedIsBranch(compoundTarget, location, find, extendWith, context);\n if (pulledIntoNestedIs) {\n return finalize(pulledIntoNestedIs);\n }\n\n const replacement = wrapCompoundMatchRange(\n compoundTarget,\n location.startIndex,\n location.endIndex,\n location.matchedIndices,\n extendWith\n );\n return finishRootReplacement(replacement, N.ComplexSelector | N.CompoundSelector);\n }\n\n const complexTarget = getComplexSelector(target);\n if (\n complexTarget\n && location.containingNode === target\n && location.startIndex !== undefined\n && location.endIndex !== undefined\n && location.startIndex < location.endIndex\n ) {\n const crossedAmpersandParent = getCrossedAmpersandParent(location)\n ?? (crossedAmpersand ? parent : undefined);\n if (crossedAmpersandParent) {\n const replacement = wrapResolvedOrderedSpanWithTailRemainder(\n complexTarget,\n location.startIndex,\n location.endIndex,\n extendWith,\n crossedAmpersandParent,\n getLastOrderedSelector(find),\n location,\n context\n );\n if (replacement) {\n return finishRootReplacement(replacement, N.ComplexSelector);\n }\n }\n\n const replacement = wrapOrderedMatchRange(complexTarget, location.startIndex, location.endIndex, extendWith);\n return finishRootReplacement(replacement, N.ComplexSelector);\n }\n\n return undefined;\n };\n const tryHandleDirectChildContainingNodePartial = (): ExtendResult | undefined => {\n const containingNode = location.containingNode;\n const directChild = isNode(containingNode, N.Selector)\n ? (\n getContainingDirectChildSelector(target, containingNode)\n ?? getStructurallyMatchingDirectChildSelector(target, containingNode)\n )\n : undefined;\n if (!directChild) {\n return undefined;\n }\n\n let replacement: Selector;\n if (\n isNode(directChild, N.CompoundSelector)\n && location.startIndex !== undefined\n && location.endIndex !== undefined\n ) {\n const crossedAmpersandParent = getCrossedAmpersandParent(location);\n if (crossedAmpersandParent) {\n replacement = wrapSelectorInIs(\n materializeAmpersandsForHoist(directChild, crossedAmpersandParent),\n extendWith\n );\n } else {\n const pulledIntoNestedIs = tryPullCompoundMatchIntoNestedIsBranch(directChild, location, find, extendWith, context);\n if (pulledIntoNestedIs) {\n replacement = pulledIntoNestedIs.value;\n } else {\n const conflict = getCompoundConflictError(\n getCompoundMembersOutsideRange(\n directChild,\n location.startIndex,\n location.endIndex,\n location.matchedIndices\n ),\n extendWith\n );\n if (conflict) {\n return { value: target, error: conflict, isChanged: false };\n }\n\n replacement = wrapCompoundMatchRange(\n directChild,\n location.startIndex,\n location.endIndex,\n location.matchedIndices,\n extendWith\n );\n }\n }\n } else {\n const nestedDirectChild = isNode(directChild, N.PseudoSelector | N.SelectorList | N.ComplexSelector)\n ? tryExtendSelector(directChild, find, extendWith, true, parent, context)\n : undefined;\n if (nestedDirectChild && !nestedDirectChild.error) {\n replacement = nestedDirectChild.value;\n } else {\n const compoundTarget = getCompoundSelector(target);\n if (compoundTarget) {\n const childIndex = compoundTarget.get('value').findIndex(node => node === containingNode);\n if (childIndex !== -1) {\n const conflict = getCompoundConflictError(\n getCompoundMembersOutsideRange(\n compoundTarget,\n childIndex,\n childIndex,\n undefined\n ),\n extendWith\n );\n if (conflict) {\n return { value: target, error: conflict, isChanged: false };\n }\n }\n }\n\n replacement = wrapSelectorInIs(directChild, extendWith);\n }\n }\n\n const childChanged = replacement !== directChild;\n const nextTarget = replaceDirectSelectorChild(target, directChild, replacement);\n if (nextTarget) {\n if (crossedAmpersand) {\n nextTarget.hoistToRoot = true;\n }\n return finalize(createSuccessResult(nextTarget, childChanged));\n }\n\n return undefined;\n };\n const directPseudoArg = getDirectPseudoArg(target);\n const directIsArg = getDirectIsArg(target);\n if (location.exact) {\n const directListAppend = tryAppendToDirectSelectorListOnFullMatch(target, find, extendWith, parent);\n if (directListAppend) {\n markTargetHoist(!!directListAppend.value.hoistToRoot);\n return finalize(directListAppend);\n }\n\n if (\n location.containingNode === target\n && isNode(target, N.ComplexSelector)\n ) {\n const resolved = resolveAmpersandTarget(target, parent);\n if (resolved) {\n const exactResult = createAlternativeSelector(resolved, extendWith);\n exactResult.hoistToRoot = true;\n markTargetHoist(true);\n return finalize(createSuccessResult(exactResult));\n }\n }\n\n if (location.containingNode === target) {\n const nestedIsResult = directIsArg\n ? tryExtendDirectChildSelector(target, directIsArg, find, extendWith, parent, crossedAmpersand, context)\n : undefined;\n const finishedNestedIs = finishNested(nestedIsResult);\n if (finishedNestedIs) {\n return finishedNestedIs;\n }\n\n const nestedPseudoResult = directPseudoArg && directPseudoArg === location.containingNode\n ? tryExtendDirectChildSelector(target, location.containingNode, find, extendWith, parent, crossedAmpersand, context)\n : undefined;\n const finishedNestedPseudo = finishNested(nestedPseudoResult);\n if (finishedNestedPseudo) {\n return finishedNestedPseudo;\n }\n\n const nestedListResult = isNode(target, N.SelectorList)\n ? tryExtendDirectChildSelector(target, getSingleMatchedDirectChild(target, location), find, extendWith, parent, crossedAmpersand, context)\n : undefined;\n const finishedNestedList = finishNested(nestedListResult);\n if (finishedNestedList) {\n return finishedNestedList;\n }\n\n const nestedOrderedChildResult = (isNode(target, N.ComplexSelector) || isNode(target, N.CompoundSelector))\n ? tryExtendDirectChildSelector(target, getSingleMatchedDirectChild(target, location), find, extendWith, parent, crossedAmpersand, context)\n : undefined;\n const finishedNestedOrderedChild = finishNested(nestedOrderedChildResult);\n if (finishedNestedOrderedChild) {\n return finishedNestedOrderedChild;\n }\n\n const exactTarget = crossedAmpersand\n ? materializeCrossedTarget(target, parent) ?? target\n : target;\n const exactResult = createAlternativeSelector(exactTarget, extendWith);\n if (crossedAmpersand) {\n exactResult.hoistToRoot = true;\n markTargetHoist(true);\n }\n return finalize(createSuccessResult(exactResult));\n }\n\n const nestedPseudoListAppend = isNode(location.containingNode, N.Selector)\n ? tryAppendToContainingSelectorList(target, location.containingNode, extendWith)\n : undefined;\n const finishedNestedPseudoListAppend = finishNested(nestedPseudoListAppend);\n if (finishedNestedPseudoListAppend) {\n return finishedNestedPseudoListAppend;\n }\n\n if (location.containingNode.parent === target) {\n if (isNode(target, N.SelectorList)) {\n const rewrittenListChild = isNode(location.containingNode, N.Selector)\n ? finishStructuralChildRewrite(location.containingNode)\n : undefined;\n if (rewrittenListChild) {\n return rewrittenListChild;\n }\n\n return finalize(createSuccessResult(createAlternativeSelector(target, extendWith)));\n }\n\n const rewrittenChild = isNode(location.containingNode, N.Selector)\n ? finishStructuralChildRewrite(location.containingNode)\n : undefined;\n if (rewrittenChild) {\n return rewrittenChild;\n }\n }\n }\n\n const nestedPseudoResult = directPseudoArg && directPseudoArg === location.containingNode\n ? tryExtendDirectChildSelector(target, location.containingNode, find, extendWith, parent, crossedAmpersand, context)\n : undefined;\n const finishedNestedPseudo = finishNested(nestedPseudoResult);\n if (finishedNestedPseudo) {\n return finishedNestedPseudo;\n }\n\n if (location.containingNode === target) {\n const nestedIsResult = directIsArg\n ? tryExtendDirectChildSelector(target, directIsArg, find, extendWith, parent, crossedAmpersand, context)\n : undefined;\n const finishedNestedIs = finishNested(nestedIsResult);\n if (finishedNestedIs) {\n return finishedNestedIs;\n }\n\n const nestedListResult = isNode(target, N.SelectorList)\n ? tryExtendDirectChildSelector(target, getSingleMatchedDirectChild(target, location), find, extendWith, parent, crossedAmpersand, context)\n : undefined;\n const finishedNestedList = finishNested(nestedListResult);\n if (finishedNestedList) {\n return finishedNestedList;\n }\n }\n\n const rootSingleSlotPartial = tryHandleRootSingleSlotPartial();\n if (rootSingleSlotPartial) {\n return rootSingleSlotPartial;\n }\n\n const rootMultiSlotPartial = tryHandleRootMultiSlotPartial();\n if (rootMultiSlotPartial) {\n return rootMultiSlotPartial;\n }\n\n const directChildContainingNodePartial = tryHandleDirectChildContainingNodePartial();\n if (directChildContainingNodePartial) {\n return directChildContainingNodePartial;\n }\n\n const containingChild = getContainingDirectChildSelector(target, location.containingNode);\n if (containingChild) {\n const nested = tryExtendDirectChildSelector(target, containingChild, find, extendWith, parent, crossedAmpersand, context);\n const finishedNested = finishNested(nested);\n if (finishedNested) {\n return finishedNested;\n }\n }\n\n return createErrorResult(target, ExtendErrorType.NOT_FOUND, 'Partial extend shape not implemented yet');\n}\n","import type { Context } from '../../context.js';\nimport { WARN, toDiagnostic } from '../../jess-error.js';\nimport type { AtRule } from '../at-rule.js';\nimport type { Node } from '../node.js';\nimport type { Rules } from '../rules.js';\nimport type { Ruleset } from '../ruleset.js';\nimport type { Selector } from '../selector.js';\nimport { CompoundSelector } from '../selector-compound.js';\nimport { ComplexSelector, type ComplexSelectorComponent } from '../selector-complex.js';\nimport { SelectorList } from '../selector-list.js';\nimport { PseudoSelector } from '../selector-pseudo.js';\n\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport { Nil } from '../nil.js';\nimport { F_EXTENDED, F_VISIBLE } from '../node.js';\nimport { selectorMatch } from './selector-match-core.js';\nimport { tryExtendSelector } from './extend-core.js';\nimport { getCurrentParentNode, getImplicitSelector, localizeSelectorAgainstParent, getParentRuleset, hasSourceExtendWrapperParent, isBareAmpersandOwnSelector, selectorHasAuthoredAmpersand } from './selector-utils.js';\n\n/**\n * Extend-root orchestration is intentionally record-driven:\n *\n * 1. During eval, qualifying scopes register themselves as extend roots.\n * 2. Rulesets register directly against the current extend root.\n * 3. Extend processing consumes only recorded roots/rulesets/instructions.\n *\n * This file should not discover roots or child roots by walking the node tree.\n * Extend support must stay close to zero-cost when no extends are present, so\n * all expensive work is deferred until we have both recorded rulesets and\n * recorded extend instructions to apply.\n *\n * @todo Once the extend test matrix is green, do a dedicated performance review\n * of extend-root orchestration. Re-check:\n * - zero-work behavior when no extends are present\n * - repeat-pass behavior and termination characteristics under load\n * - cache invalidation costs\n * - whether any remaining selector rewrites can be deferred to serialization\n */\n\nfunction invalidateSelectorCache(selector?: Selector | Nil): void {\n if (!selector || isNode(selector, N.Nil)) {\n return;\n }\n selector.invalidateCache();\n}\n\nfunction invalidateRulesetSelectorCaches(ruleset: Ruleset, context?: Context): void {\n ruleset.invalidateSelectorValueCache();\n invalidateSelectorCache(ruleset.get('selector', context));\n invalidateSelectorCache(context ? ruleset.get('_extendedSelector', context) : ruleset.getExtendedSelector());\n invalidateSelectorCache(ruleset.getOwnSelector(context));\n invalidateSelectorCache(context ? ruleset.get('selectorBeforeExtend', context) : ruleset.getSelectorBeforeExtend());\n const rules = ruleset.enterRules(context);\n if (!rules || !isNode(rules, N.Rules)) {\n return;\n }\n for (const child of (rules as Rules).value) {\n if (isNode(child, N.Ruleset)) {\n invalidateRulesetSelectorCaches(child as Ruleset, context);\n }\n }\n}\n\nfunction refreshNestedRulesetSelectors(parentRuleset: Ruleset, context?: Context): void {\n const rules = parentRuleset.enterRules(context);\n if (!rules || !isNode(rules, N.Rules)) {\n return;\n }\n\n const parentSelector = parentRuleset.getEffectiveSelector(false, context);\n if (!parentSelector || isNode(parentSelector, N.Nil)) {\n return;\n }\n\n for (const child of (rules as Rules).value) {\n if (!isNode(child, N.Ruleset)) {\n continue;\n }\n\n const childRuleset = child as Ruleset;\n syncRulesetDerivedSelector(childRuleset, context);\n refreshNestedRulesetSelectors(childRuleset, context);\n }\n}\n\nfunction hasReferenceBoundaryParent(ruleset: Ruleset, context?: Context): boolean {\n const parent = getCurrentParentNode(ruleset, context);\n return Boolean(\n parent\n && isNode(parent, N.Rules)\n && (parent as Rules).options?.referenceMode === true\n );\n}\n\nfunction parentRulesetOwnsDerivedSelectorState(parentRuleset: Ruleset, context?: Context): boolean {\n const extendedSelector = context\n ? parentRuleset.get('_extendedSelector', context)\n : parentRuleset.getExtendedSelector();\n if (extendedSelector !== undefined) {\n return true;\n }\n const selectorBeforeExtend = context\n ? parentRuleset.get('selectorBeforeExtend', context)\n : parentRuleset.getSelectorBeforeExtend();\n if (selectorBeforeExtend !== undefined) {\n return true;\n }\n return getRulesetHoistToRoot(parentRuleset, context) === true;\n}\n\nfunction getDerivedSelectorFromParent(ruleset: Ruleset, context?: Context): Selector | Nil | undefined {\n const ownSelector = ruleset.getOwnSelector(context);\n if (!ownSelector || isNode(ownSelector, N.Nil)) {\n return undefined;\n }\n if (isBareAmpersandOwnSelector(ownSelector) && hasReferenceBoundaryParent(ruleset, context)) {\n return undefined;\n }\n\n const parentRuleset = getParentRuleset(ruleset, context);\n if (!parentRuleset || !parentRulesetOwnsDerivedSelectorState(parentRuleset, context)) {\n return undefined;\n }\n const parentSelector = parentRuleset?.getEffectiveSelector(false, context);\n if (!parentSelector || isNode(parentSelector, N.Nil)) {\n return undefined;\n }\n\n const composedSelector = getImplicitSelector(ownSelector, parentSelector, false);\n const currentSelector = ruleset.get('selector', context);\n if (!isNode(currentSelector, N.Nil) && composedSelector.valueOf() === currentSelector.valueOf()) {\n return undefined;\n }\n\n return composedSelector;\n}\n\nfunction syncRulesetDerivedSelector(ruleset: Ruleset, context?: Context): void {\n const derivedSelector = getDerivedSelectorFromParent(ruleset, context);\n ruleset.setExtendedSelector(derivedSelector, context);\n}\n\nfunction normalizeGeneratedIsOrder(selector: Selector, insideGeneratedIs = false): Selector {\n if (isNode(selector, N.SelectorList)) {\n return SelectorList.create(\n (selector as SelectorList).get('value').map(item => normalizeGeneratedIsOrder(item as Selector, insideGeneratedIs))\n ).inherit(selector) as Selector;\n }\n\n if (isNode(selector, N.ComplexSelector)) {\n return ComplexSelector.create(\n (selector as ComplexSelector).get('value').map(part =>\n normalizeGeneratedIsOrder(part as Selector, insideGeneratedIs) as ComplexSelectorComponent\n )\n ).inherit(selector) as Selector;\n }\n\n if (isNode(selector, N.CompoundSelector)) {\n const normalizedMembers = (selector as CompoundSelector).get('value').map(child =>\n normalizeGeneratedIsOrder(child as Selector, insideGeneratedIs)\n );\n if (!insideGeneratedIs) {\n return CompoundSelector.create(normalizedMembers).inherit(selector) as Selector;\n }\n const generatedIs = normalizedMembers.filter(member =>\n isNode(member, N.PseudoSelector)\n && member.generated\n && member.get('name') === ':is'\n );\n if (generatedIs.length !== 1 || generatedIs[0] === normalizedMembers[0]) {\n return CompoundSelector.create(normalizedMembers).inherit(selector) as Selector;\n }\n const leadingGeneratedIs = generatedIs[0]!;\n const others = normalizedMembers.filter(member => member !== leadingGeneratedIs);\n return CompoundSelector.create([\n leadingGeneratedIs,\n ...others\n ]).inherit(selector) as Selector;\n }\n\n if (isNode(selector, N.PseudoSelector)) {\n const arg = selector.get('arg');\n if (arg && isNode(arg, N.Selector)) {\n const copy = selector.copy(true) as PseudoSelector;\n const nextArg = normalizeGeneratedIsOrder(\n arg as Selector,\n insideGeneratedIs || (selector.generated && selector.get('name') === ':is')\n );\n copy.adopt(nextArg);\n copy.arg = nextArg;\n return copy as Selector;\n }\n }\n\n return selector;\n}\n\ntype ExtendRootRecord = {\n rules: Rules;\n parent?: Rules;\n children: Set<Rules>;\n rulesets: Set<Ruleset>;\n layerName?: string;\n isProtected: boolean;\n isCompose: boolean;\n namespace?: string;\n};\n\nexport class ExtendRootRegistry {\n private rootRecords = new WeakMap<Rules, ExtendRootRecord>();\n private rootsByLayerName = new Map<string, Set<Rules>>();\n private rootsByNamespace = new Map<string, Set<Rules>>();\n private layerNames = new WeakMap<AtRule, string>();\n private allRoots = new Set<Rules>();\n private visibleRootsCache = new WeakMap<Rules, Set<Rules>>();\n\n root?: Rules;\n extendRootStack: Rules[] = [];\n\n private ensureRootRecord(rules: Rules): ExtendRootRecord {\n let record = this.rootRecords.get(rules);\n if (!record) {\n record = {\n rules,\n children: new Set(),\n rulesets: new Set(),\n isProtected: false,\n isCompose: false\n };\n this.rootRecords.set(rules, record);\n this.allRoots.add(rules);\n this.visibleRootsCache = new WeakMap();\n }\n return record;\n }\n\n getCurrentExtendRoot(): Rules | undefined {\n return this.extendRootStack[this.extendRootStack.length - 1];\n }\n\n registerRoot(\n rules: Rules,\n parent?: Rules,\n options?: { layerName?: string; isProtected?: boolean; isCompose?: boolean; namespace?: string }\n ): void {\n const record = this.ensureRootRecord(rules);\n if (!this.root) {\n this.root = rules;\n }\n\n if (parent) {\n const parentRecord = this.ensureRootRecord(parent);\n record.parent = parent;\n parentRecord.children.add(rules);\n }\n\n if (options?.layerName) {\n record.layerName = options.layerName;\n let layerRoots = this.rootsByLayerName.get(options.layerName);\n if (!layerRoots) {\n layerRoots = new Set<Rules>();\n this.rootsByLayerName.set(options.layerName, layerRoots);\n }\n layerRoots.add(rules);\n }\n\n if (options?.namespace) {\n record.namespace = options.namespace;\n let nsRoots = this.rootsByNamespace.get(options.namespace);\n if (!nsRoots) {\n nsRoots = new Set<Rules>();\n this.rootsByNamespace.set(options.namespace, nsRoots);\n }\n nsRoots.add(rules);\n }\n\n if (options?.isProtected) {\n record.isProtected = true;\n }\n if (options?.isCompose) {\n record.isCompose = true;\n }\n this.visibleRootsCache = new WeakMap();\n }\n\n registerRuleset(root: Rules, ruleset: Ruleset): void {\n if (!root || !ruleset) {\n return;\n }\n this.ensureRootRecord(root).rulesets.add(ruleset);\n }\n\n getRulesets(root: Rules): ReadonlySet<Ruleset> | undefined {\n return this.rootRecords.get(root)?.rulesets;\n }\n\n clearRegisteredRulesets(): void {\n for (const root of this.allRoots) {\n this.rootRecords.get(root)?.rulesets.clear();\n }\n }\n\n getAllRoots(): Set<Rules> {\n return new Set(this.allRoots);\n }\n\n pushExtendRoot(rules: Rules): void {\n this.extendRootStack.push(rules);\n }\n\n popExtendRoot(): void {\n this.extendRootStack.pop();\n }\n\n getVisibleRoots(root: Rules): Set<Rules> {\n return this.getAccessibleRoots(root);\n }\n\n getAccessibleRoots(root: Rules): Set<Rules> {\n const cached = this.visibleRootsCache.get(root);\n if (cached) {\n return cached;\n }\n\n const accessible = new Set<Rules>();\n const visited = new Set<Rules>();\n\n const traverseChildren = (currentRoot: Rules): void => {\n if (visited.has(currentRoot)) {\n return;\n }\n visited.add(currentRoot);\n accessible.add(currentRoot);\n\n const currentRecord = this.rootRecords.get(currentRoot);\n if (!currentRecord) {\n return;\n }\n\n if (currentRecord.isProtected) {\n return;\n }\n\n if (currentRecord.children.size) {\n for (const child of currentRecord.children) {\n if (this.rootRecords.get(child)?.isProtected) {\n continue;\n }\n traverseChildren(child);\n }\n }\n\n const layer = currentRecord.layerName;\n if (layer) {\n const sameLayerRoots = this.rootsByLayerName.get(layer);\n if (sameLayerRoots) {\n for (const layerRoot of sameLayerRoots) {\n if (layerRoot !== currentRoot && !visited.has(layerRoot) && !this.rootRecords.get(layerRoot)?.isProtected) {\n accessible.add(layerRoot);\n traverseChildren(layerRoot);\n }\n }\n }\n }\n };\n\n traverseChildren(root);\n this.visibleRootsCache.set(root, accessible);\n return accessible;\n }\n\n isRootInNamespace(root: Rules, namespace: string): boolean {\n const namespaceRoots = this.rootsByNamespace.get(namespace);\n if (!namespaceRoots?.size) {\n return false;\n }\n for (const namespaceRoot of namespaceRoots) {\n if (this.getAccessibleRoots(namespaceRoot).has(root)) {\n return true;\n }\n }\n return false;\n }\n\n isSameOrDescendantRoot(rulesetRoot: Rules, extendRoot: Rules): boolean {\n if (rulesetRoot === extendRoot) {\n return true;\n }\n const rulesetRecord = this.rootRecords.get(rulesetRoot);\n if (!rulesetRecord) {\n return false;\n }\n if (rulesetRecord.isProtected) {\n return false;\n }\n const layerA = rulesetRecord.layerName;\n const layerB = this.rootRecords.get(extendRoot)?.layerName;\n if (layerA && layerB && layerA === layerB) {\n return true;\n }\n const extendRecord = this.rootRecords.get(extendRoot);\n if (!extendRecord || extendRecord.children.size === 0) {\n return false;\n }\n for (const child of extendRecord.children) {\n if (this.rootRecords.get(child)?.isProtected) {\n continue;\n }\n if (this.isSameOrDescendantRoot(rulesetRoot, child)) {\n return true;\n }\n }\n return false;\n }\n\n setLayerName(atRule: AtRule, layerName: string): void {\n this.layerNames.set(atRule, layerName);\n }\n\n getLayerName(atRule: AtRule): string | undefined {\n return this.layerNames.get(atRule);\n }\n\n takeLayerName(atRule: AtRule): string | undefined {\n const layer = this.layerNames.get(atRule);\n if (layer) {\n this.layerNames.delete(atRule);\n }\n return layer;\n }\n\n isProtectedRoot(rules: Rules): boolean {\n return this.rootRecords.get(rules)?.isProtected === true;\n }\n}\n\nfunction isInstructionVisibleForRoot(\n context: Context,\n rootRules: Rules,\n instruction: {\n extendRoot?: Rules;\n fromReferenceScope: boolean;\n namespace?: string;\n },\n getCachedVisibleRoots?: (root: Rules) => Set<Rules>\n): boolean {\n if (!instruction.extendRoot) {\n return false;\n }\n if (instruction.fromReferenceScope === true) {\n return false;\n }\n if (context.extendRoots.isProtectedRoot(rootRules) && instruction.extendRoot !== rootRules) {\n return false;\n }\n if (instruction.namespace) {\n if (instruction.namespace === '*') {\n return true;\n }\n return context.extendRoots.isRootInNamespace(rootRules, instruction.namespace);\n }\n if (instruction.extendRoot === rootRules) {\n return true;\n }\n if (context.extendRoots.isSameOrDescendantRoot(rootRules, instruction.extendRoot)) {\n return true;\n }\n const visibleRoots = getCachedVisibleRoots\n ? getCachedVisibleRoots(instruction.extendRoot)\n : context.extendRoots.getVisibleRoots(instruction.extendRoot);\n return visibleRoots.has(rootRules);\n}\n\nfunction isRootWithinInstructionNamespace(\n context: Context,\n rootRules: Rules,\n instruction: {\n namespace?: string;\n }\n): boolean {\n if (!instruction.namespace || instruction.namespace === '*') {\n return true;\n }\n return context.extendRoots.isRootInNamespace(rootRules, instruction.namespace);\n}\n\ntype RecordedExtendInstruction = {\n target: Selector;\n extendWith: Selector;\n partial: boolean;\n extendRoot: Rules;\n extendNode: Node;\n fromReferenceScope: boolean;\n namespace?: string;\n};\n\ntype TargetInfo = ReturnType<typeof getRulesetExtendTarget>;\ntype TargetInfoCache = WeakMap<Ruleset, Map<RecordedExtendInstruction, TargetInfo>>;\n\nfunction getCachedTargetInfo(\n cache: TargetInfoCache | undefined,\n ruleset: Ruleset,\n instruction: RecordedExtendInstruction,\n context?: Context\n): TargetInfo {\n if (cache) {\n let perRuleset = cache.get(ruleset);\n if (perRuleset?.has(instruction)) {\n return perRuleset.get(instruction);\n }\n const result = getRulesetExtendTarget(ruleset, instruction.target, instruction.partial, context);\n if (!perRuleset) {\n perRuleset = new Map();\n cache.set(ruleset, perRuleset);\n }\n perRuleset.set(instruction, result);\n return result;\n }\n return getRulesetExtendTarget(ruleset, instruction.target, instruction.partial, context);\n}\n\nfunction invalidateTargetInfoCacheTree(cache: TargetInfoCache, ruleset: Ruleset): void {\n cache.delete(ruleset);\n const rules = ruleset.get('rules');\n if (!rules || !isNode(rules, N.Rules)) {\n return;\n }\n for (const child of (rules as Rules).value) {\n if (isNode(child, N.Ruleset)) {\n invalidateTargetInfoCacheTree(cache, child as Ruleset);\n }\n }\n}\n\nfunction getRulesetInstructionSignature(\n ruleset: Ruleset,\n instruction: RecordedExtendInstruction,\n cache?: TargetInfoCache,\n context?: Context\n): string | undefined {\n const targetInfo = getCachedTargetInfo(cache, ruleset, instruction, context);\n if (!targetInfo) {\n return undefined;\n }\n\n return [\n targetInfo.selector.valueOf(),\n targetInfo.parent?.valueOf() ?? '',\n targetInfo.usingOwnSelector ? 'own' : 'full'\n ].join('\\u0000');\n}\n\nfunction isNodeInsideRules(node: Node, rules: Rules): boolean {\n let current: Node | undefined = node;\n while (current) {\n if (current === rules) {\n return true;\n }\n current = current.parent;\n }\n return false;\n}\n\nfunction getRulesetExtendTarget(\n ruleset: Ruleset,\n find: Selector,\n partial: boolean,\n context?: Context\n): { selector: Selector; parent?: Selector; usingOwnSelector: boolean } | undefined {\n const selector = ruleset.getEffectiveSelector(false, context);\n if (!selector || isNode(selector, N.Nil)) {\n return undefined;\n }\n\n const ownSelector = ruleset.getOwnSelector(context);\n if (hasSourceExtendWrapperParent(ruleset)) {\n return {\n selector,\n usingOwnSelector: false\n };\n }\n // Bare `&` rulesets are pure mirrors of their parent selector and are updated\n // by refreshNestedRulesetSelectors when the parent is extended. Skip direct\n // extend processing so selectorBeforeExtend is not incorrectly set on them.\n if (ownSelector && !isNode(ownSelector, N.Nil) && isBareAmpersandOwnSelector(ownSelector)) {\n return undefined;\n }\n const parentRs = getParentRuleset(ruleset, context);\n const parentSelectorBeforeExtend = parentRs\n ? (context ? parentRs.get('selectorBeforeExtend', context) : parentRs.getSelectorBeforeExtend())\n : undefined;\n const activeParentSelector = parentRs?.getEffectiveSelector(false, context);\n const parentSelector = (\n !partial\n && parentSelectorBeforeExtend\n && !isNode(parentSelectorBeforeExtend, N.Nil)\n ? parentSelectorBeforeExtend\n : activeParentSelector\n );\n if (\n ownSelector\n && !isNode(ownSelector, N.Nil)\n && ownSelector.valueOf() !== selector.valueOf()\n && parentSelector\n && !isNode(parentSelector, N.Nil)\n ) {\n const ownMatch = selectorMatch(find, ownSelector, parentSelector, context);\n const rawOwnMatch = partial\n ? selectorMatch(find, ownSelector, undefined, context)\n : undefined;\n const shouldUseOwnSelector = partial\n ? (\n ownMatch.fullMatch\n || ownMatch.partialMatch\n || Boolean(rawOwnMatch?.fullMatch)\n || Boolean(rawOwnMatch?.partialMatch)\n )\n : (\n ownMatch.fullMatch\n && ownMatch.crossesAmpersand\n );\n\n if (shouldUseOwnSelector) {\n return {\n selector: ownSelector,\n parent: parentSelector,\n usingOwnSelector: true\n };\n }\n\n if (\n !partial\n && activeParentSelector\n && !isNode(activeParentSelector, N.Nil)\n && activeParentSelector.valueOf() !== parentSelector.valueOf()\n ) {\n const activeOwnMatch = selectorMatch(find, ownSelector, activeParentSelector, context);\n if (activeOwnMatch.fullMatch && activeOwnMatch.crossesAmpersand) {\n return {\n selector: ownSelector,\n parent: activeParentSelector,\n usingOwnSelector: true\n };\n }\n }\n\n if (!partial && selectorHasAuthoredAmpersand(ownSelector as Selector)) {\n const composedMatch = selectorMatch(find, selector, undefined, context);\n if (composedMatch.fullMatch) {\n return {\n selector,\n usingOwnSelector: false\n };\n }\n }\n\n // Target doesn't match ownSelector (with parent context). Don't fall\n // through to the full composed selector — any match there would be in\n // the parent-prefix portion, which is handled when the parent ruleset\n // itself is extended + refreshNestedRulesetSelectors propagates changes.\n return undefined;\n }\n\n return {\n selector,\n usingOwnSelector: false\n };\n}\n\nfunction markExtendedSelector(selector: Selector, context?: Context): void {\n if (context) {\n selector._addFlag(F_EXTENDED, context);\n selector._addFlag(F_VISIBLE, context);\n } else {\n selector.addFlag(F_EXTENDED);\n selector.addFlag(F_VISIBLE);\n }\n if (isNode(selector, N.SelectorList)) {\n for (const item of (selector as SelectorList).get('value')) {\n if (context) {\n (item as Selector)._addFlag(F_EXTENDED, context);\n (item as Selector)._addFlag(F_VISIBLE, context);\n } else {\n (item as Selector).addFlag(F_EXTENDED);\n (item as Selector).addFlag(F_VISIBLE);\n }\n }\n }\n}\n\nfunction activateExtendedRuleset(ruleset: Ruleset, selector: Selector, context?: Context): void {\n const rulesetFlagTarget = ruleset;\n if (context) {\n rulesetFlagTarget._addFlag(F_EXTENDED, context);\n rulesetFlagTarget._addFlag(F_VISIBLE, context);\n } else {\n rulesetFlagTarget.addFlag(F_EXTENDED);\n rulesetFlagTarget.addFlag(F_VISIBLE);\n }\n markExtendedSelector(selector, context);\n}\n\nfunction selectorHasTopLevelValue(selector: Selector | Nil | undefined, value: string): boolean {\n if (!selector || isNode(selector, N.Nil)) {\n return false;\n }\n if (isNode(selector, N.SelectorList)) {\n return ((selector as SelectorList).get('value') as readonly Selector[]).some(item => item.valueOf() === value);\n }\n return selector.valueOf() === value;\n}\n\nfunction getExactOwnSelectorFallbackTarget(\n ruleset: Ruleset,\n instruction: RecordedExtendInstruction,\n currentTargetInfo: { selector: Selector; parent?: Selector; usingOwnSelector: boolean } | undefined,\n context?: Context\n): { selector: Selector; parent?: Selector; usingOwnSelector: boolean } | undefined {\n if (instruction.partial || currentTargetInfo?.usingOwnSelector) {\n return undefined;\n }\n\n const ownSelector = ruleset.getOwnSelector(context);\n if (!ownSelector || isNode(ownSelector, N.Nil)) {\n return undefined;\n }\n\n const parentRuleset = getParentRuleset(ruleset, context);\n const parentOwnSelector = parentRuleset?.getOwnSelector(context);\n if (\n parentOwnSelector\n && !isNode(parentOwnSelector, N.Nil)\n && isNode(parentOwnSelector, N.SelectorList)\n ) {\n return undefined;\n }\n const parentSelectorBeforeExtend = parentRuleset\n ? (context ? parentRuleset.get('selectorBeforeExtend', context) : parentRuleset.getSelectorBeforeExtend())\n : undefined;\n const activeParentSelector = parentRuleset?.getEffectiveSelector(false, context);\n const parentSelector = (\n parentSelectorBeforeExtend\n && !isNode(parentSelectorBeforeExtend, N.Nil)\n ? parentSelectorBeforeExtend\n : activeParentSelector\n );\n if (!parentSelector || isNode(parentSelector, N.Nil)) {\n return undefined;\n }\n\n if (selectorHasTopLevelValue(activeParentSelector, instruction.extendWith.valueOf())) {\n return undefined;\n }\n\n const ownMatch = selectorMatch(instruction.target, ownSelector, parentSelector, context);\n if (!ownMatch.partialMatch || ownMatch.crossesAmpersand) {\n return undefined;\n }\n\n return {\n selector: ownSelector,\n parent: parentSelector,\n usingOwnSelector: true\n };\n}\n\nfunction clearExtendedRuleset(ruleset: Ruleset, context?: Context): void {\n const rulesetFlagTarget = ruleset;\n if (context) {\n rulesetFlagTarget._removeFlag(F_EXTENDED, context);\n } else {\n rulesetFlagTarget.removeFlag(F_EXTENDED);\n }\n if (getRulesetHoistToRoot(ruleset, context) !== undefined) {\n setRulesetHoistToRoot(ruleset, undefined, context);\n }\n const selector = ((context ? ruleset.get('_extendedSelector', context) : ruleset.getExtendedSelector()) ?? ruleset.get('selector', context));\n if (selector && !isNode(selector, N.Nil)) {\n if (context) {\n selector._removeFlag(F_EXTENDED, context);\n } else {\n selector.removeFlag(F_EXTENDED);\n }\n }\n syncRulesetDerivedSelector(ruleset, context);\n}\n\nfunction getRulesetHoistToRoot(ruleset: Ruleset, _context?: Context): boolean | undefined {\n return ruleset.hoistToRoot;\n}\n\nfunction setRulesetHoistToRoot(ruleset: Ruleset, value: boolean | undefined, _context?: Context): void {\n ruleset.hoistToRoot = value;\n}\n\nfunction applyInstructionToRuleset(\n ruleset: Ruleset,\n instruction: RecordedExtendInstruction,\n cache?: TargetInfoCache,\n context?: Context\n): { matched: boolean; changed: boolean } {\n let targetInfo = getCachedTargetInfo(cache, ruleset, instruction, context);\n if (!targetInfo) {\n const fallbackTargetInfo = getExactOwnSelectorFallbackTarget(ruleset, instruction, undefined, context);\n if (!fallbackTargetInfo) {\n return { matched: false, changed: false };\n }\n targetInfo = fallbackTargetInfo;\n }\n\n let targetMatch = selectorMatch(\n instruction.target,\n targetInfo.selector,\n targetInfo.parent,\n context\n );\n if (!targetMatch.partialMatch) {\n const fallbackTargetInfo = getExactOwnSelectorFallbackTarget(ruleset, instruction, targetInfo, context);\n if (!fallbackTargetInfo) {\n return { matched: false, changed: false };\n }\n targetInfo = fallbackTargetInfo;\n targetMatch = selectorMatch(\n instruction.target,\n targetInfo.selector,\n targetInfo.parent,\n context\n );\n if (!targetMatch.partialMatch) {\n return { matched: false, changed: false };\n }\n }\n\n const currentSelector = ruleset.get('selector', context);\n const selectorBeforeExtend = targetInfo.usingOwnSelector\n ? targetInfo.selector\n : currentSelector;\n if (\n !(context ? ruleset.get('selectorBeforeExtend', context) : ruleset.getSelectorBeforeExtend())\n && selectorBeforeExtend\n && !isNode(selectorBeforeExtend, N.Nil)\n ) {\n ruleset.setSelectorBeforeExtend(selectorBeforeExtend.copy(true) as Selector, context!);\n }\n\n if (\n isNodeInsideRules(instruction.extendNode, ruleset.enterRules(context))\n && instruction.extendWith.valueOf() === targetInfo.selector.valueOf()\n && targetMatch.fullMatch\n ) {\n activateExtendedRuleset(ruleset, targetInfo.selector, context);\n return { matched: true, changed: false };\n }\n\n const extendWithVal = instruction.extendWith.valueOf();\n const extendWithAlreadyTopLevel = isNode(targetInfo.selector, N.SelectorList)\n ? ((targetInfo.selector as SelectorList).get('value') as readonly Selector[]).some(item => item.valueOf() === extendWithVal)\n : targetInfo.selector.valueOf() === extendWithVal;\n if (extendWithAlreadyTopLevel) {\n activateExtendedRuleset(ruleset, targetInfo.selector, context);\n return { matched: true, changed: false };\n }\n\n const before = targetInfo.selector.valueOf();\n const selectorInput = targetInfo.selector.copy(true) as Selector;\n const result = tryExtendSelector(\n selectorInput,\n instruction.target,\n instruction.extendWith,\n instruction.partial,\n targetInfo.parent,\n context\n );\n if (result.error) {\n if (instruction.extendWith.valueOf() === targetInfo.selector.valueOf()) {\n activateExtendedRuleset(ruleset, targetInfo.selector, context);\n }\n return { matched: true, changed: false };\n }\n\n const normalizedResult = normalizeGeneratedIsOrder(result.value);\n const after = normalizedResult.valueOf();\n activateExtendedRuleset(ruleset, normalizedResult, context);\n if (before === after) {\n return { matched: true, changed: false };\n }\n\n let shouldHoist = (\n normalizedResult.hoistToRoot\n || (\n targetInfo.usingOwnSelector\n && targetMatch.fullMatch\n && targetMatch.crossesAmpersand\n && normalizedResult !== targetInfo.selector\n )\n || (\n !targetInfo.usingOwnSelector\n && Boolean(ruleset.getOwnSelector() && !isNode(ruleset.getOwnSelector()!, N.Nil))\n && selectorHasAuthoredAmpersand(ruleset.getOwnSelector() as Selector)\n )\n );\n\n let nextSelector = normalizedResult;\n if (targetInfo.usingOwnSelector) {\n const nextOwnSelector = (\n shouldHoist || !targetInfo.parent\n )\n ? normalizedResult\n : localizeSelectorAgainstParent(normalizedResult, targetInfo.parent);\n ruleset.setOwnSelector(nextOwnSelector, context);\n\n if (!shouldHoist && targetInfo.parent) {\n nextSelector = getImplicitSelector(nextOwnSelector, targetInfo.parent, false);\n }\n }\n ruleset.setExtendedSelector(nextSelector, context);\n if (shouldHoist) {\n setRulesetHoistToRoot(ruleset, true, context);\n refreshNestedRulesetSelectors(ruleset, context);\n } else if (getRulesetHoistToRoot(ruleset, context) || ruleset.treeContext?.opts?.collapseNesting === true) {\n refreshNestedRulesetSelectors(ruleset, context);\n }\n invalidateRulesetSelectorCaches(ruleset, context);\n return { matched: true, changed: true };\n}\n\nfunction instructionCouldAffectRuleset(\n ruleset: Ruleset,\n instruction: RecordedExtendInstruction,\n cache?: TargetInfoCache,\n context?: Context\n): boolean {\n const targetInfo = getCachedTargetInfo(cache, ruleset, instruction, context);\n if (!targetInfo) {\n return false;\n }\n const result = selectorMatch(instruction.target, targetInfo.selector, targetInfo.parent, context);\n return result.fullMatch || result.partialMatch;\n}\n\nexport function processExtends(context: Context): void {\n try {\n const instructions: RecordedExtendInstruction[] = context.extends.map(([target, selectorWithExtend, partial, extendRoot, extendNode, , fromReferenceScope, namespace]) => ({\n target,\n extendWith: selectorWithExtend,\n partial,\n extendRoot,\n extendNode,\n fromReferenceScope: fromReferenceScope === true,\n namespace\n }));\n\n if (!instructions.length) {\n return;\n }\n\n const instructionMatched = new Set<RecordedExtendInstruction>();\n const seenRulesetInstructionStates = new WeakMap<Ruleset, Map<RecordedExtendInstruction, string>>();\n const appliedRulesetInstructions = new WeakMap<Ruleset, Set<RecordedExtendInstruction>>();\n const visibleRootsCache = new Map<Rules, Set<Rules>>();\n const getCachedVisibleRoots = (extendRoot: Rules): Set<Rules> => {\n let cached = visibleRootsCache.get(extendRoot);\n if (!cached) {\n cached = context.extendRoots.getVisibleRoots(extendRoot);\n visibleRootsCache.set(extendRoot, cached);\n }\n return cached;\n };\n\n let targetInfoCache: TargetInfoCache = new WeakMap();\n let changed = true;\n while (changed) {\n changed = false;\n\n for (const rootRules of context.extendRoots.getAllRoots()) {\n const rulesetSet = context.extendRoots.getRulesets(rootRules);\n if (!rulesetSet?.size) {\n continue;\n }\n\n const savedRenderKey = context.renderKey;\n const savedRulesContext = context.rulesContext;\n context.renderKey = rootRules.renderKey;\n context.rulesContext = rootRules;\n\n try {\n const visibleInstructions = instructions.filter(instruction =>\n isInstructionVisibleForRoot(context, rootRules, instruction, getCachedVisibleRoots)\n );\n if (!visibleInstructions.length) {\n continue;\n }\n\n for (const ruleset of rulesetSet) {\n let rulesetMatched = false;\n for (const instruction of visibleInstructions) {\n const appliedInstructions = appliedRulesetInstructions.get(ruleset);\n if (appliedInstructions?.has(instruction)) {\n instructionMatched.add(instruction);\n rulesetMatched = true;\n continue;\n }\n\n const signatureBefore = getRulesetInstructionSignature(ruleset, instruction, targetInfoCache, context);\n const perInstructionStates = seenRulesetInstructionStates.get(ruleset);\n if (\n signatureBefore !== undefined\n && perInstructionStates?.get(instruction) === signatureBefore\n ) {\n instructionMatched.add(instruction);\n rulesetMatched = true;\n continue;\n }\n\n const outcome = applyInstructionToRuleset(ruleset, instruction, targetInfoCache, context);\n if (outcome.matched) {\n instructionMatched.add(instruction);\n rulesetMatched = true;\n\n let nextStates = perInstructionStates;\n if (!nextStates) {\n nextStates = new Map<RecordedExtendInstruction, string>();\n seenRulesetInstructionStates.set(ruleset, nextStates);\n }\n nextStates.set(\n instruction,\n getRulesetInstructionSignature(ruleset, instruction, targetInfoCache, context) ?? signatureBefore ?? ''\n );\n }\n if (outcome.changed) {\n invalidateTargetInfoCacheTree(targetInfoCache, ruleset);\n targetInfoCache = new WeakMap();\n let nextAppliedInstructions = appliedInstructions;\n if (!nextAppliedInstructions) {\n nextAppliedInstructions = new Set<RecordedExtendInstruction>();\n appliedRulesetInstructions.set(ruleset, nextAppliedInstructions);\n }\n nextAppliedInstructions.add(instruction);\n changed = true;\n }\n }\n\n if (!rulesetMatched) {\n clearExtendedRuleset(ruleset, context);\n }\n }\n } finally {\n context.renderKey = savedRenderKey;\n context.rulesContext = savedRulesContext;\n }\n }\n }\n\n for (const instruction of instructions) {\n if (instruction.fromReferenceScope || instructionMatched.has(instruction)) {\n continue;\n }\n\n const target = instruction.target.valueOf();\n const targetLocation = instruction.target.location;\n const targetLine = targetLocation.length >= 2 ? targetLocation[1] : undefined;\n const targetColumn = targetLocation.length >= 3 ? targetLocation[2] : undefined;\n const targetFile = instruction.target.treeContext?.file;\n const targetFilePath = targetFile?.fullPath;\n\n const blockedProtectedRootExists = Array.from(context.extendRoots.getAllRoots()).some((root) => {\n if (!isRootWithinInstructionNamespace(context, root, instruction)) {\n return false;\n }\n if (isInstructionVisibleForRoot(context, root, instruction, getCachedVisibleRoots)) {\n return false;\n }\n\n const rulesets = context.extendRoots.getRulesets(root);\n if (!rulesets?.size) {\n return false;\n }\n\n for (const ruleset of rulesets) {\n if (instructionCouldAffectRuleset(ruleset, instruction, targetInfoCache, context)) {\n return true;\n }\n }\n return false;\n });\n\n const diagnostic = blockedProtectedRootExists\n ? WARN.extendNotAccessible({\n ctx: targetFile ? { file: targetFile } : undefined,\n filePath: targetFilePath,\n line: targetLine,\n column: targetColumn,\n meta: { target }\n })\n : WARN.extendNotFound({\n ctx: targetFile ? { file: targetFile } : undefined,\n filePath: targetFilePath,\n line: targetLine,\n column: targetColumn,\n meta: { target }\n });\n context.warnings.push(toDiagnostic(diagnostic));\n }\n } finally {\n context.extendRoots.clearRegisteredRulesets();\n }\n}\n","import type { MathMode } from '../../types/modes.js';\nimport type { Operator } from './calculate.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport type { Node } from '../node.js';\n\nexport type MathFrameState = {\n mathMode: MathMode;\n /**\n * Boolean stack. The current frame is the top-most value.\n * - `true` enables Less/Sass \"math in parens\" semantics\n * - `false` explicitly disables it (e.g. for call args)\n */\n parenFrames: ReadonlyArray<boolean>;\n /** Number stack, modeled as a depth counter */\n calcFrames: number;\n};\n\nexport function isInParens(parenFrames: ReadonlyArray<boolean>): boolean {\n return parenFrames.at(-1) ?? false;\n}\n\n/**\n * Shared calculation decision logic for both eval-time (`Context.shouldOperate`)\n * and parse-time decisions (Less→Jess conversion).\n *\n * This must remain behaviorally equivalent to `Context.shouldOperate`.\n */\nexport function shouldOperateWithMathFrames(\n state: MathFrameState,\n op: Operator,\n left: Node,\n right: Node\n): boolean {\n const { mathMode, calcFrames } = state;\n const inParens = isInParens(state.parenFrames);\n const inCalc = calcFrames !== 0;\n\n if (inCalc) {\n /** Only collapse safe units */\n if (isNode(left, N.Dimension) && isNode(right, N.Dimension)) {\n const lUnit = left.unit;\n const rUnit = right.unit;\n if ((op === '+' || op === '-') && lUnit === rUnit) {\n return true;\n }\n /** Can't make square units */\n if (op === '*' && (!lUnit || !rUnit)) {\n return true;\n }\n /** Can't divide by a unit */\n if (op === '/' && !rUnit) {\n return true;\n }\n }\n\n return false;\n }\n\n // Preserve CSS/Less slash syntax such as `font: small/20px` even under\n // aggressive math modes. Keyword-like `Any` operands are overwhelmingly\n // shorthand/value syntax, not arithmetic.\n if (op === '/' && (isNode(left, N.Any) || isNode(right, N.Any))) {\n return false;\n }\n\n /** Parens for Less/SCSS will set `canOperate` to true */\n if (mathMode === 'always' || inParens) {\n return true;\n }\n if (mathMode === 'parens-division') {\n return op !== '/';\n }\n if (mathMode === 'parens' || mathMode === 'strict') {\n return false;\n }\n return true;\n}\n","import type { Call } from '../call.js';\nimport type { List } from '../list.js';\nimport type { Context } from '../../context.js';\nimport { isNode } from './is-node.js';\n\ntype CallItem = string | undefined;\n\nfunction getCallArgsSignature(args: List | undefined, context?: Context): string | undefined {\n if (!isNode(args)) {\n return undefined;\n }\n return args.toTrimmedString(context ? { context } : undefined);\n}\n/**\n * This memoizes arguments for a call and returns true\n * if the call has called itself with the same arguments.\n *\n * It lazily indexes the arguments when there's a subsequent\n * call.\n */\nexport class CallMap {\n private _callMap = new Map<Call, [CallItem, ...CallItem[]]>();\n\n add(call: Call, args: List | undefined, context?: Context) {\n let set = this._callMap.get(call);\n const argsSignature = getCallArgsSignature(args, context);\n if (!set) {\n this._callMap.set(call, [argsSignature]);\n } else {\n if (argsSignature === undefined && set.includes(undefined)) {\n return true;\n }\n for (let i = 0; i < set.length; i++) {\n let item = set[i]!;\n if (item === argsSignature) {\n return true;\n }\n }\n }\n return false;\n }\n\n delete(call: Call) {\n let set = this._callMap.get(call);\n if (set) {\n set.pop();\n if (set.length === 0) {\n this._callMap.delete(call);\n }\n return true;\n }\n return false;\n }\n}\n","import type {\n AtRule,\n Ruleset,\n Rules,\n ImportOptions,\n Node,\n Any,\n Selector\n} from './tree/index.js';\nimport { ExtendRootRegistry } from './tree/util/extend-roots.js';\nimport { type Operator } from './tree/util/calculate.js';\nimport type { RenderKey } from './tree/node-base.js';\nimport type { PluginInterface } from './plugin.js';\nimport { EqualityMode, MathMode, UnitMode } from './types/modes.js';\nimport * as path from 'node:path';\nimport { isNode } from './tree/util/is-node.js';\nimport { N } from './tree/node-type.js';\nimport { shouldOperateWithMathFrames } from './tree/util/should-operate.js';\nimport { type ErrorDiagnostic, type WarningDiagnostic, JessError } from './jess-error.js';\nimport type { Call } from './tree/call.js';\nimport { CallMap } from './tree/util/recursion-helper.js';\nimport { createRequire } from 'node:module';\nimport { BitSetLibrary } from './tree/util/bitset.js';\nimport type { EvalDependency } from './tree/util/field-helpers.js';\n\nexport interface ContextOptions {\n /** Hash classes for module output */\n module?: boolean;\n /**\n * From docs:\n * \"Changes compilation mode so dynamic content\n * is output as CSS variables, and changes\n * the runtime module to generate CSS patches.\"\n *\n * @todo - Change this behavior to \"live expressions\"\n * i.e. change compilation to always be static, but\n * generate a separate module for calculated CSS variables.\n */\n dynamic?: boolean;\n collapseNesting?: boolean;\n\n enableJavaScript?: boolean;\n mathMode?: MathMode;\n unitMode?: UnitMode;\n equalityMode?: EqualityMode;\n\n /** Directories to search to resolve files */\n searchPaths?: string[];\n\n /**\n * Whether to leak variables and mixins into the caller scope,\n * such that they can be referenced / called by subsequent rules.\n *\n * @deprecated - a Less feature\n */\n leakyRules?: boolean;\n\n /**\n * Whether to bubble root-only at-rules (like @font-face, @keyframes)\n * to the root level when they're nested inside rulesets.\n *\n * @deprecated - a legacy Less feature; modern CSS allows nesting\n */\n bubbleRootAtRules?: boolean;\n\n /**\n * Suppress warnings (similar to Less's suppressWarnings option).\n * When true, warnings are collected but not emitted.\n */\n suppressWarnings?: boolean;\n\n /**\n * Break on first error (stop processing after first error).\n * When false, errors are collected and processing continues.\n */\n breakOnError?: boolean;\n}\n\nexport interface TreeContextOptions extends ContextOptions {\n inlineJavaScript?: boolean;\n\n /**\n * For instances where a new tree needs to inherit from scope\n * (like Less / SCSS `@import` rule)\n *\n * @todo - remove?\n */\n parentScope?: Rules;\n scope?: Rules;\n\n isModule?: boolean;\n\n file?: {\n /** Filename, e.g. \"main.jess\" */\n name: string;\n\n /** Absolute directory containing the file (no filename) */\n path: string;\n\n /** Absolute file path (directory + filename) */\n fullPath: string;\n\n /** Full file contents (recommended for code-frames) */\n source?: string;\n\n /** Lazy cache of line-start offsets (built on demand) */\n lines?: Uint32Array;\n };\n\n [k: string]: any;\n}\n\nconst idChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');\n\n/**\n * @todo - Redo:\n * 1. Create a hash of the file path; that way hashes\n * are unique per file, but also repeatable / predictable.\n * 2. Append file (module) hash after class name\n */\nexport const generateId = (length = 8) => {\n let str = '';\n let idCharsLength = idChars.length;\n for (let i = 0; i < length; i++) {\n str += idChars[Math.floor(Math.random() * idCharsLength)]!;\n }\n return str;\n};\n\n/**\n * Tree context is attached to each node\n * during the parsing phase / AST creation.\n *\n * Each file (and hence, tree) will get a new tree\n * context. For the most part, it is passed around\n * as an object reference.\n *\n * Additionally, it sets options that may be\n * unique to the tree, such as the math mode.\n */\nexport class TreeContext implements TreeContextOptions {\n opts: Record<string, any>;\n // changed to `rulesVisiblity` set during parsing\n leakyRules: boolean | undefined;\n bubbleRootAtRules: boolean | undefined;\n mathMode: MathMode | undefined;\n unitMode: UnitMode | undefined;\n equalityMode: EqualityMode | undefined;\n\n /** @todo - Change how extend works based on this value */\n isModule: boolean | undefined;\n\n file?: TreeContextOptions['file'];\n /**\n * The plugin that created this tree. It will have first dibs\n * to resolve any imports.\n */\n plugin?: PluginInterface;\n\n constructor(opts: TreeContextOptions = {}) {\n /**\n * Known options are attached to the instance.\n * Unknown options are assigned to `opts`\n */\n let {\n mathMode,\n unitMode,\n equalityMode,\n isModule,\n file,\n plugin,\n leakyRules,\n bubbleRootAtRules,\n ...rest\n } = opts;\n this.mathMode = mathMode;\n this.unitMode = unitMode;\n this.equalityMode = equalityMode;\n this.isModule = isModule;\n this.file = file;\n this.plugin = plugin;\n this.leakyRules = leakyRules;\n this.bubbleRootAtRules = bubbleRootAtRules;\n // this.scope = scope ?? new Scope(parentScope)\n this.opts = rest;\n }\n}\n\n/**\n * .a.b.c\n * simple = 0b1\n * compound = 0b10\n * complex = 0b100\n * a = 0b1000\n * b = 0b10000\n * c = 0b100000\n *\n * .a.b.c.c = 0b111010\n */\n\n/**\n * This is the context object used for evaluation.\n *\n * @note\n * Most of context represents \"state\" while evaluating.\n * There should only ever be one Context singleton per parse & evaluation.\n */\nexport class Context {\n readonly plugins: PluginInterface[];\n readonly opts: ContextOptions;\n\n treeContext!: TreeContext;\n\n /**\n * Collected errors during safeParse/safeRender.\n * Only populated when using safe methods.\n */\n errors: ErrorDiagnostic[] = [];\n\n /**\n * Collected warnings during safeParse/safeRender.\n * Only populated when using safe methods.\n */\n warnings: WarningDiagnostic[] = [];\n\n /**\n * A feature ported from Less - we suppress any `@charset`\n * after the first one.\n */\n currentCharset?: Any;\n /** Track whether charset has been emitted during toString to avoid duplicates */\n charsetEmitted?: boolean;\n\n /** @import rules must be at the top of CSS output */\n topImports?: Node[];\n\n /**\n * This is set when entering rulesets so that child nodes\n * can use this to lookup values. When evaluating inside a mixin/function,\n * this also enables call-time variable resolution ($~variable).\n */\n rulesContext!: Rules;\n /**\n * Internal transient lookup-scope override.\n *\n * Used by direct mixin/function invocation so canonical bodies can evaluate\n * against a prepared outer scope without changing the public node API.\n */\n lookupScope?: Rules;\n /** Entire context root (ultimate root) */\n root!: Rules;\n /** Set so that we can do ruleset selector lookup for extend */\n treeRoot!: Rules;\n allRoots: Rules[] = [];\n\n /** The call that is currently being evaluated */\n caller?: Call;\n\n /**\n * Current render-key selection for parent/edge-sensitive traversal.\n *\n * Canonical traversal falls back when no alternate edge exists.\n */\n renderKey?: RenderKey;\n\n /** Extend roots registry for managing extend scoping */\n extendRoots!: ExtendRootRegistry;\n\n /**\n * Depth-first document order of each Ruleset (assigned once per root before eval).\n * Used so processExtends can apply extends in true source order.\n *\n * @todo - Probably remove once I fix extends\n */\n documentOrderByRuleset?: WeakMap<Ruleset, number>;\n\n /**\n * Registered extends with their extend root context\n * Format: [target, selectorWithExtend, partial, extendRoot, extendNode, documentOrder?, fromReferenceScope?, namespace?]\n *\n * @todo - Probably remove once I fix extends\n */\n extends: Array<[target: Selector, selectorWithExtend: Selector, partial: boolean, extendRoot: Rules, extendNode: Node, documentOrder?: number, fromReferenceScope?: boolean, namespace?: string]> = [];\n\n /**\n * When doing any kind of lookup, the current node and resolved\n * nodes in the search chain are added to prevent recursion errors.\n *\n * Search-scope identity is canonical when available (`sourceNode ?? node`)\n * so derived wrappers do not bypass recursion guards.\n * Also used to track mixins currently being evaluated to prevent infinite recursion.\n */\n private _searchScope: Set<Node> | undefined;\n get searchScope() {\n return (this._searchScope ??= new Set());\n }\n\n getSearchScopeIdentity(node: Node): Node {\n return node.sourceNode ?? node;\n }\n\n hasInSearchScope(node: Node): boolean {\n return this.searchScope.has(this.getSearchScopeIdentity(node));\n }\n\n addToSearchScope(node: Node): void {\n this.searchScope.add(this.getSearchScopeIdentity(node));\n }\n\n deleteFromSearchScope(node: Node): void {\n this.searchScope.delete(this.getSearchScopeIdentity(node));\n }\n\n /**\n * The file (eval) context should have the same ID at compile-time\n * as run-time, so this ID will be set in `toModule()` output\n *\n * @todo - Make the id a hash of the (project-relative) path + contents\n */\n id = generateId();\n ruleCounter = 0;\n renderCounter = 0;\n\n /** Rules depth, used to figure out source order */\n depth = -1;\n\n /** Selector valueOf() strings to bitset positions */\n selectorBits = new BitSetLibrary<string>();\n\n private _classMap: Map<string, string> | undefined;\n get classMap() {\n return (this._classMap ??= new Map());\n }\n\n /** Frames for nested rulesets, used for selector evaluation */\n rulesetFrames: Ruleset[] = [];\n /**\n * When mixin eval clears `rulesetFrames`, this preserves the caller's\n * last ruleset frame so at-rule hoisting can still pick up the caller's\n * selector for the wrapper Ruleset.\n */\n callerRulesetFrame: Ruleset | undefined;\n /** Unified frames array for flat rendering when collapseNesting is true */\n frames: (Ruleset | AtRule)[] = [];\n\n /**\n * We push a boolean to this array when entering a calc() call\n * and pop it when leaving. This helps us determine if operations\n * should be performed or not.\n *\n * @todo - can't this just be a number?\n */\n calcFrames = 0;\n\n private _callMap: CallMap | undefined;\n get callMap() {\n return (this._callMap ??= new CallMap());\n }\n\n private _callStack: Call[] | undefined;\n get callStack() {\n return (this._callStack ??= []);\n }\n\n /**\n * Stack to track reference call chain for clearing matched keys at outermost level\n */\n private _referenceStack: number = 0;\n get referenceStack() {\n return this._referenceStack;\n }\n\n /**\n * Import-evaluation scope stack.\n *\n * This intentionally models lexical import scope instead of global counters:\n * - each import branch pushes its semantics on entry\n * - each branch pops in `finally`\n * - readers ask semantic questions (`inReferenceImportScope`) instead of\n * inspecting mutable depth values.\n *\n * Why this exists:\n * some behaviors depend on \"how we got here\" (call-path scope), not only\n * on the current node's own options. Example: suppressing top-level @import\n * hoists while traversing a reference-only branch.\n */\n private _importScopeStack: Array<{ reference: boolean; multiple: boolean }> = [];\n get importScope() {\n return this._importScopeStack;\n }\n\n get inReferenceImportScope() {\n return this._importScopeStack.some(scope => scope.reference);\n }\n\n get inMultipleImportScope() {\n return this._importScopeStack.some(scope => scope.multiple);\n }\n\n pushImportScope(scope: { reference?: boolean; multiple?: boolean }) {\n this._importScopeStack.push({\n reference: scope.reference === true,\n multiple: scope.multiple === true\n });\n }\n\n popImportScope() {\n if (this._importScopeStack.length > 0) {\n this._importScopeStack.pop();\n }\n }\n\n pushReference() {\n this._referenceStack++;\n }\n\n /**\n * Stack to track when a value comes from an important declaration\n * Used to propagate !important flag to containing declarations\n */\n private _importantSourceStack: number = 0;\n get hasImportantSource() {\n return this._importantSourceStack > 0;\n }\n\n pushImportantSource() {\n this._importantSourceStack++;\n }\n\n popImportantSource() {\n if (this._importantSourceStack > 0) {\n this._importantSourceStack--;\n }\n }\n\n popReference() {\n this._referenceStack--;\n }\n\n rulesEvalStack: Rules[] = [];\n\n /**\n * We push a boolean to this array when entering parens call\n * and pop it when leaving. This helps us determine if operations\n * should be performed or not.\n *\n * Sometimes we \"reset\" the \"in parentheses\" state by pushing false,\n * such as within a function call.\n */\n parenFrames: boolean[] = [];\n\n /**\n * Keys of @let variables --\n * We need this b/c we need to generate code\n * for over-riding in the exported function.\n *\n * @todo - remove?\n */\n private _exports: Set<string> | undefined;\n get exports(): Set<string> {\n return (this._exports ??= new Set());\n }\n\n nextRenderKey(): RenderKey {\n return ++this.renderCounter;\n }\n\n /**\n * currently generating a runtime module or not\n * @todo - remove in favor of ToModuleVisitor?\n */\n // isRuntime: boolean\n\n /**\n * In a custom declaration's value. All nodes should\n * be preserved as-is and not evaluated, except for\n * $() expressions.\n */\n inCustom: boolean | undefined;\n\n /** A flag set when evaluating conditions */\n isDefault: boolean | undefined;\n\n readonly dependencyMap = new WeakMap<Node, EvalDependency>();\n\n _leakyRules: boolean | undefined;\n get leakyRules() {\n return this._leakyRules ?? this.treeContext?.leakyRules ?? false;\n }\n\n _bubbleRootAtRules: boolean | undefined;\n get bubbleRootAtRules() {\n return this._bubbleRootAtRules ?? this.treeContext?.bubbleRootAtRules ?? false;\n }\n\n constructor(opts: ContextOptions = {}, plugins?: PluginInterface[]) {\n this.opts = opts;\n this.plugins = plugins ?? [];\n this.extendRoots = new ExtendRootRegistry();\n if (opts.leakyRules !== undefined) {\n this._leakyRules = opts.leakyRules;\n }\n if (opts.bubbleRootAtRules !== undefined) {\n this._bubbleRootAtRules = opts.bubbleRootAtRules;\n }\n }\n\n /** Full resolved path -> tree */\n sourceTrees = new Map<string, Rules>();\n evaldTrees = new Map<string, Rules>();\n composeSetValues = new Map<string, Rules>();\n\n /**\n * @param importPath - The bare import path e.g. `@import \"foo\";` in a .less file.\n */\n private async _getPath(importPath: string) {\n const currentTree = this.treeContext;\n const currentDirectory = currentTree?.file?.path ?? process.cwd();\n const { searchPaths = [] } = this.opts;\n\n const plugins = this.plugins;\n let finalPath: string | undefined;\n let currentPlugin = this.treeContext?.plugin;\n\n /** First, expand imports */\n let paths = currentPlugin?.expandImport?.(importPath, currentDirectory) ?? [importPath];\n if (paths.length === 0) {\n throw new Error(`No paths found for import \"${importPath}\"`);\n }\n\n /** Give current context plugin first dibs to resolve */\n if (currentPlugin?.resolve) {\n const result = await currentPlugin.resolve(paths, currentDirectory, searchPaths);\n if (result) {\n paths = result;\n }\n }\n\n /** Try to resolve using resolver plugins */\n for (const plugin of plugins) {\n if (plugin === currentPlugin) {\n continue;\n }\n if (!plugin.resolve) {\n continue;\n }\n const result = await plugin.resolve(paths, currentDirectory, searchPaths);\n if (result) {\n paths = result;\n }\n }\n\n /** Now, try to locate the first matching file using locator plugins */\n for (const plugin of plugins) {\n if (!plugin.locate) {\n continue;\n }\n const result = await plugin.locate(paths, currentDirectory);\n if (result) {\n finalPath = result;\n break;\n }\n }\n\n if (!finalPath) {\n // Fallback for bare module specifiers (e.g. \"@scope/pkg/path\").\n const looksBareSpecifier = (p: string) =>\n !path.isAbsolute(p)\n && !p.startsWith('./')\n && !p.startsWith('../')\n && !p.startsWith('/')\n && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(p);\n const tryResolveModule = (request: string, basedir: string): string | undefined => {\n try {\n const req = createRequire(path.join(basedir, '__jess_resolve__.js'));\n return req.resolve(request);\n } catch {\n return undefined;\n }\n };\n const moduleBaseDirs = [currentDirectory, ...searchPaths, process.cwd()];\n for (const candidate of paths) {\n if (!looksBareSpecifier(candidate)) {\n continue;\n }\n for (const baseDir of moduleBaseDirs) {\n const base = path.isAbsolute(baseDir) ? baseDir : path.resolve(currentDirectory, baseDir);\n const resolved = tryResolveModule(candidate, base) ?? tryResolveModule(`${candidate}.less`, base);\n if (resolved) {\n finalPath = resolved;\n break;\n }\n }\n if (finalPath) {\n break;\n }\n }\n }\n\n if (!finalPath) {\n /** @todo - Add messaging around tried paths */\n throw new Error(`File not found: ${importPath} (from: ${currentDirectory})`);\n }\n\n const normalizedFinalPath = finalPath.split(/[?#]/)[0]!;\n const ext = path.extname(normalizedFinalPath);\n const friendlyPath = path.relative(process.cwd(), normalizedFinalPath);\n\n if (!ext) {\n throw new Error(`File \"${friendlyPath}\" not supported`);\n }\n\n return {\n triedPaths: paths,\n resolvedPath: normalizedFinalPath,\n friendlyPath\n };\n }\n\n /**\n * Find the appropriate plugin for parsing based on type or extension\n */\n private findParserPlugin(type?: string, extension?: string): PluginInterface {\n const plugins = this.plugins;\n\n if (type) {\n const plugin = plugins.find(plugin => plugin.name === type);\n if (!plugin) {\n throw new Error(`Plugin \"${type}\" not found`);\n }\n if (!plugin.parse) {\n throw new Error(`Plugin \"${type}\" does not support parsing`);\n }\n return plugin;\n }\n\n if (extension) {\n const plugin = plugins.find(plugin => plugin.supportedExtensions?.includes(extension) && (plugin.parse || plugin.safeParse));\n if (!plugin) {\n throw new Error(`No plugin found for extension \"${extension}\"`);\n }\n return plugin;\n }\n\n throw new Error('No plugin type or extension specified');\n }\n\n async getTree(importPath: string, importOptions: ImportOptions = {}) {\n const { resolvedPath, triedPaths, friendlyPath } = await this._getPath(importPath);\n const { type } = importOptions;\n /**\n * We already have resolved this file and parsed it.\n */\n if (this.sourceTrees.has(resolvedPath)) {\n return {\n node: this.sourceTrees.get(resolvedPath)!,\n triedPaths,\n resolvedPath\n };\n }\n\n const plugins = this.plugins;\n\n const sourceGetter = plugins.find(plugin => plugin.getSource);\n if (!sourceGetter) {\n /** If we can't actually load files, bail. */\n throw new Error('No source getter found');\n }\n\n const ext = path.extname(resolvedPath);\n const plugin = this.findParserPlugin(type, ext);\n let source: string;\n try {\n source = await sourceGetter.getSource!(resolvedPath);\n } catch (error: unknown) {\n throw error;\n }\n const parseResult = plugin.safeParse!(resolvedPath, source, {\n compilerOptions: this.opts\n });\n\n // Collect normalized errors and warnings from plugin\n this.errors.push(...parseResult.errors);\n this.warnings.push(...parseResult.warnings);\n\n // Check if we have errors and should break\n if (parseResult.errors.length > 0 && this.opts.breakOnError !== false) {\n // Throw the first error as a JessError\n const firstError = parseResult.errors[0]!;\n throw new JessError({\n code: firstError.code,\n phase: firstError.phase,\n severity: 'error',\n ctx: firstError.file ? { file: firstError.file } : undefined,\n filePath: firstError.filePath,\n source: firstError.file?.source,\n line: firstError.line,\n column: firstError.column,\n reason: firstError.reason,\n fix: firstError.fix,\n note: firstError.note,\n errors: firstError.errors,\n lexerErrors: firstError.lexerErrors\n });\n }\n\n if (parseResult.tree) {\n // Set context.root so preEval visitors can check if this is the root\n // parseResult.tree should be a Rules node (the root of the parsed tree)\n if (!this.root && isNode(parseResult.tree, N.Rules)) {\n this.root = parseResult.tree;\n }\n\n this.sourceTrees.set(resolvedPath, parseResult.tree);\n return {\n node: parseResult.tree,\n triedPaths,\n resolvedPath\n };\n }\n\n // No tree and no errors means unsupported file\n const notSupportedError = new Error(`File \"${friendlyPath}\" not supported`);\n if (this.opts.breakOnError !== false) {\n throw notSupportedError;\n }\n // Add error for unsupported file\n this.errors.push({\n code: 'parse/unsupported-file',\n phase: 'parse',\n message: notSupportedError.message,\n reason: `The file \"${friendlyPath}\" is not supported by any available plugin.`,\n fix: 'Ensure the file has a supported extension or specify a plugin type.',\n filePath: resolvedPath,\n line: 1,\n column: 1\n });\n return {\n node: null,\n triedPaths,\n resolvedPath\n };\n }\n\n /**\n * Public path resolution for import nodes that need source-path lookups\n * without triggering parse/eval.\n */\n async resolveImportPath(importPath: string) {\n return this._getPath(importPath);\n }\n\n /**\n * Parse a string content directly using the appropriate plugin\n */\n async parseString(content: string, options: {\n filePath?: string;\n type?: string;\n extension?: string;\n } = {}) {\n const { filePath, type, extension } = options;\n const virtualPath = filePath || `virtual.${extension || 'jess'}`;\n const ext = extension || path.extname(virtualPath);\n\n const plugin = this.findParserPlugin(type, ext);\n const tree = await plugin.parse!(virtualPath, content, {\n compilerOptions: this.opts\n });\n\n if (!tree) {\n throw new Error('Failed to parse content');\n }\n\n return {\n node: tree,\n resolvedPath: virtualPath\n };\n }\n\n /**\n *\n * @param importPath\n * @param importOptions\n */\n async getModule(importPath: string, importOptions: ImportOptions = {}) {\n const isFnsImport = importPath === '@jesscss/fns'\n || importPath.startsWith('@jesscss/fns/')\n || importPath === '#less'\n || importPath.startsWith('#less/')\n || importPath === '#sass'\n || importPath.startsWith('#sass/');\n const { enableJavaScript } = this.opts;\n if (enableJavaScript === false && !isFnsImport) {\n throw new Error('JavaScript evaluation is disabled');\n }\n const { resolvedPath, triedPaths, friendlyPath } = await this._getPath(importPath);\n const { type } = importOptions;\n\n const plugins = this.plugins;\n const ext = path.extname(resolvedPath);\n\n let plugin: PluginInterface | undefined;\n\n if (type) {\n plugin = plugins.find(plugin => plugin.name === type);\n if (!plugin) {\n throw new Error(`Plugin \"${type}\" not found`);\n }\n if (!plugin.import) {\n throw new Error(`Plugin \"${type}\" can't import modules`);\n }\n }\n\n if (!plugin) {\n plugin = plugins.find(plugin => plugin.supportedExtensions?.includes(ext) && plugin.import);\n if (!plugin) {\n if (['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(ext)) {\n throw new Error('Feature not supported. Install @jesscss/plugin-js to enable script execution features.');\n }\n throw new Error(`File \"${friendlyPath}\" not supported`);\n }\n }\n\n const module = await plugin.import!(resolvedPath);\n if (!module) {\n throw new Error(`File \"${friendlyPath}\" not supported`);\n }\n\n return {\n module,\n triedPaths,\n resolvedPath\n };\n }\n\n // async getRules(\n // filePath: string,\n // nodeOptions: StyleImportOptions,\n // userOptions: Record<string, any> = {},\n // withNode?: StyleImportValue['withNode']\n // ) {\n // let rules = await this.getTree(filePath, userOptions);\n // if (withValues && isNode(withValues.node, 'Rules')) {\n // if (rules.options.readonly) {\n // throw new Error('Cannot set an import\\'s \"with\" values more than once.');\n // }\n // /** @todo - Throw errors for undefined vars */\n // let withRules = withValues.node.clone(true) as Rules;\n // withRules.value.unshift(rules);\n // rules = withRules;\n // if (withValues.type === 'set') {\n // this.sourceTrees.set(filePath, rules);\n // }\n // }\n // return rules;\n // }\n\n /**\n * Hash a CSS class name or not depending on the `module` setting\n *\n * @todo - do module files have different contexts, therefore different\n * hash maps?\n */\n hashClass(name: string) {\n /** Remove dot for mapping */\n name = name.slice(1);\n let lookup = this.classMap.get(name);\n if (lookup) {\n return `.${lookup}`;\n }\n let mapVal: string;\n if (this.opts.module) {\n mapVal = `${name}_${this.id}`;\n } else {\n mapVal = name;\n }\n this.classMap.set(name, mapVal);\n return `.${mapVal}`;\n }\n\n shouldOperate(op: Operator, left: Node, right: Node) {\n const mathMode = this.treeContext?.mathMode\n ?? this.opts?.mathMode\n ?? 'parens-division';\n return shouldOperateWithMathFrames(\n {\n mathMode,\n parenFrames: this.parenFrames,\n calcFrames: this.calcFrames\n },\n op,\n left,\n right\n );\n }\n}\n","/**\n * This file is the entry point for the Node class.\n * It imports from node-base.ts, applies prototype patches,\n * and re-exports everything.\n *\n * This ensures that ANY import of Node gets the patched version,\n * regardless of whether it goes through tree/index.ts or not.\n */\n\n// First, import everything from node-base (the pure Node class)\nexport * from './node-base.js';\nimport { Node } from './node-base.js';\n\n// Import dependencies needed for patching (these import from node-base, not node)\nimport { Nil } from './nil.js';\nimport { Any } from './any.js';\nimport { TreeContext } from '../context.js';\nimport { type Operator } from './util/calculate.js';\n\nconst LEGACY_DATA_INTERNAL = new Set([\n 'parent', 'index', 'frames', 'pre', 'post', 'state', 'nodeType',\n 'isSelector', 'keySetLibrary', 'role',\n 'fullRender',\n 'rulesetRegistry', 'mixinRegistry', 'declarationRegistry', 'functionRegistry',\n 'rulesIndexed', '_indexing',\n 'pendingExtends',\n '_valueOf', '_keySet', '_visibleKeySet', '_requiredKeySet'\n]);\n\nfunction getLegacyData(this: Node) {\n const childKeys = (this.constructor as typeof Node).childKeys;\n\n if (Array.isArray(childKeys)) {\n const extraKeys = Object.keys(this).filter((key) => {\n return !key.startsWith('_') && !LEGACY_DATA_INTERNAL.has(key) && !childKeys.includes(key);\n });\n\n if (childKeys.length === 1 && extraKeys.length === 0) {\n return (this as any)[childKeys[0]!];\n }\n\n const out: Record<string, unknown> = {};\n for (const key of childKeys) {\n const value = (this as any)[key];\n if (value !== undefined) {\n out[key] = value;\n }\n }\n for (const key of extraKeys) {\n const value = (this as any)[key];\n if (value !== undefined) {\n out[key] = value;\n }\n }\n return Object.keys(out).length > 0 ? out : undefined;\n }\n\n const directValue = (this as any).value;\n if (directValue !== undefined) {\n return directValue;\n }\n\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(this)) {\n if (key.startsWith('_') || LEGACY_DATA_INTERNAL.has(key)) {\n continue;\n }\n const value = (this as any)[key];\n if (value !== undefined) {\n out[key] = value;\n }\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Patch Node.prototype.nil to return a Nil instance\n */\nNode.prototype.nil = function() {\n return new Nil();\n};\n\n/**\n * Patch Node.prototype.operate for string concatenation\n */\nNode.prototype.operate = function(b: Node, op: Operator) {\n let aVal = this.toString();\n let bVal = b.toString();\n if (op === '+') {\n return new Any(aVal + bVal).inherit(this);\n }\n throw new Error(`Cannot operate on ${this.type}`);\n};\n\n/**\n * Define a fallback treeContext for testing.\n * Reads from _meta.treeContext (set by constructor), falls back to\n * a lazily-created empty TreeContext for nodes created without one.\n */\nObject.defineProperty(Node.prototype, 'treeContext', {\n get() {\n let context = this._meta?.treeContext;\n if (!context) {\n context = this._treeContext;\n if (!context) {\n context = this._treeContext = new TreeContext();\n }\n }\n return context;\n }\n});\n\nObject.defineProperty(Node.prototype, 'data', {\n get: getLegacyData,\n set(value) {\n this.setData(value);\n }\n});\n","import { isNode } from './is-node.js';\nimport isObject from 'lodash-es/isObject.js';\nimport { type Node } from '../node.js';\nimport type { EqualityMode } from '../../types/modes.js';\n\nexport function compare(a: any, b: any, mode: EqualityMode = 'coerce') {\n if (a === b) {\n return 0;\n }\n if (!isObject(a) && !isObject(b)) {\n return a > b ? 1 : -1;\n }\n if (isNode(a) && isNode(b)) {\n return a.compare(b);\n }\n /** Do comparison without strict equality */\n if (mode === 'coerce' && a == b) {\n return 0;\n }\n return undefined;\n}\n\n/**\n * Find the actual source order of two nodes, by comparing\n * their position in their lowest common ancestor in the tree.\n */\nexport function comparePosition(a: Node, b: Node) {\n if (a === b) {\n return 0;\n }\n\n const pathToRoot = (node: Node): Node[] => {\n const path: Node[] = [];\n let current: Node | undefined = node;\n let guard = 0;\n while (current && guard < 1024) {\n path.push(current);\n current = current.parent;\n guard++;\n }\n return path;\n };\n\n const aPath = pathToRoot(a);\n const bPath = pathToRoot(b);\n let ai = aPath.length - 1;\n let bi = bPath.length - 1;\n let commonAncestor: Node | undefined;\n\n while (ai >= 0 && bi >= 0 && aPath[ai] === bPath[bi]) {\n commonAncestor = aPath[ai];\n ai--;\n bi--;\n }\n\n if (!commonAncestor) {\n return 0;\n }\n\n const aChild = ai >= 0 ? aPath[ai] : a;\n const bChild = bi >= 0 ? bPath[bi] : b;\n const aIndex = Number.isFinite(aChild.index) ? aChild.index : 0;\n const bIndex = Number.isFinite(bChild.index) ? bChild.index : 0;\n return aIndex - bIndex;\n}\n\nexport function compareNodeArray(a: any[], b: any[], mode: EqualityMode = 'coerce'): 0 | 1 | -1 | undefined {\n let output: 0 | 1 | -1 | undefined;\n\n if (a.length !== b.length) {\n return undefined;\n }\n\n /**\n * All values must be equal, or less than, or greater than.\n * Anything else is undefined.\n */\n for (let i = 0; i < a.length; i++) {\n let result = compare(a[i]!, b[i]!, mode);\n if (result === undefined) {\n return undefined;\n }\n if (output === undefined) {\n output = result;\n } else if (result !== output) {\n return undefined;\n }\n }\n return output;\n}\n","import type { Context } from '../context.js';\nimport { Node, F_STATIC, defineType, type OptionalLocation, type NodeOptions, type TreeContext } from './node.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\n\nexport interface Bool extends Node<boolean> {\n type: 'Bool';\n shortType: 'bool';\n eval(context: Context): Bool;\n}\n\n/**\n * A boolean. Named `Bool` to avoid conflict with the built-in `Boolean` class.\n */\nexport class Bool extends Node<boolean> {\n static override childKeys = null as null;\n\n readonly value!: boolean;\n\n constructor(\n value: boolean,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n super(value, options, location, treeContext);\n this.value = value;\n this.addFlag(F_STATIC);\n }\n\n override compare(other: Node): 0 | 1 | -1 | undefined {\n if (other instanceof Bool) {\n return this.value === other.value ? 0 : undefined;\n }\n return undefined;\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n w.add(this.value ? 'true' : 'false', this);\n return w.getSince(mark);\n }\n}\n\nexport const bool = defineType(Bool, 'Bool');\n","import type { AtRule } from '../at-rule.js';\nimport type { Declaration } from '../declaration.js';\nimport type { Rules } from '../rules.js';\nimport type { Ruleset } from '../ruleset.js';\nimport { F_EXTENDED, isVisibleInContext, type Node } from '../node.js';\nimport { type FinalPrintOptions, getPrintOptions, OutputWriter } from './print.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport { Nil } from '../nil.js';\nimport { hasExtendedSelector } from './selector-utils.js';\nimport { isBareAmpersandOwnSelector } from './selector-utils.js';\nimport type { FlatRulePosition } from '../rules.js';\n\nfunction isRulesNode(node: Node): node is Rules {\n return isNode(node, N.Rules);\n}\n\nfunction isRulesetNode(node: Node): node is Ruleset {\n return isNode(node, N.Ruleset);\n}\n\nfunction isAtRuleNode(node: Node): node is AtRule {\n return isNode(node, N.AtRule);\n}\n\nfunction isDeclarationNode(node: Node): node is Declaration {\n return isNode(node, N.Declaration);\n}\n\nfunction isContainerNode(node: Node): node is Rules | Ruleset | AtRule {\n return isRulesNode(node) || isRulesetNode(node) || isAtRuleNode(node);\n}\n\nfunction getRulesVisibility(node: Rules | Ruleset): Record<string, string> | undefined {\n return isRulesNode(node)\n ? node.options.rulesVisibility\n : node.options.rulesVisibility;\n}\n\nfunction getRenderableSelectorString(node: Ruleset, collapseNesting: boolean | undefined, context: FinalPrintOptions['context']): string {\n return String(node.getRenderableSelector(collapseNesting, context)?.valueOf?.() ?? '');\n}\n\nfunction isReferenceModeRules(node: Node): node is Rules {\n return isRulesNode(node) && node.options.referenceMode === true;\n}\n\n/**\n * Normalizes the indent of a multi-line string by replacing initial whitespace.\n */\nexport function normalizeIndent(multiLineString: string, indent: string, maintainRelative?: boolean): string {\n if (!maintainRelative) {\n return multiLineString.replace(/^\\s*/, indent).replace(/[ \\t\\r\\f]*\\n\\s*/g, '\\n' + indent);\n }\n\n // Find the first line's original indent length\n const firstLineMatch = multiLineString.match(/^(?:\\n*|[ \\t\\r\\f]*\\n+)(\\s*)/);\n const firstLineOriginalIndentLength = firstLineMatch ? firstLineMatch[1]!.length : 0;\n\n // Use replace with callback to process each line in one pass\n let isFirstLine = true;\n return multiLineString.replace(/(?:^|\\n)(\\s*)([^\\n]*)/g, (match, lineIndent, lineContent) => {\n if (isFirstLine) {\n isFirstLine = false;\n return indent + lineContent.trimEnd();\n }\n\n const lineOriginalIndentLength = lineIndent.length;\n // Calculate the difference from the first line's indent\n const indentDifference = lineOriginalIndentLength - firstLineOriginalIndentLength;\n // Apply the difference to the new indent to maintain relative spacing\n const newLineIndent = indent + ' '.repeat(Math.max(0, indentDifference));\n return '\\n' + newLineIndent + lineContent.trimEnd();\n });\n}\n\nexport function indent(depth: number): string {\n return ''.padStart(depth * 2);\n}\n\nfunction rulesetExtendsReference(node: Ruleset, options: FinalPrintOptions): boolean {\n return (\n (options.context ? node._hasFlag(F_EXTENDED, options.context) : node.hasFlag(F_EXTENDED))\n || hasExtendedSelector(node.getRenderableSelector(options.collapseNesting, options.context), options.context)\n );\n}\n\nfunction rulesHaveReferenceRenderableDescendant(rules: Rules, options: FinalPrintOptions): boolean {\n for (const child of rules._getRenderChildren(options.context)) {\n if (isRulesNode(child)) {\n if (rulesHaveReferenceRenderableDescendant(child, options)) {\n return true;\n }\n continue;\n }\n if (isRulesetNode(child)) {\n if (!isVisibleInContext(child, options.context) && !child.fullRender) {\n const nestedRules = child.enterRules(options.context);\n if (nestedRules && rulesHaveReferenceRenderableDescendant(nestedRules, options)) {\n return true;\n }\n continue;\n }\n if (rulesetExtendsReference(child, options)) {\n return true;\n }\n const nestedRules = child.enterRules(options.context);\n if (nestedRules && rulesHaveReferenceRenderableDescendant(nestedRules, options)) {\n return true;\n }\n continue;\n }\n if (isAtRuleNode(child)) {\n if (!isVisibleInContext(child, options.context) && !child.fullRender) {\n const nestedRules = child.enterRules(options.context);\n if (nestedRules && rulesHaveReferenceRenderableDescendant(nestedRules, options)) {\n return true;\n }\n continue;\n }\n const nestedRules = child.enterRules(options.context);\n if (nestedRules && rulesHaveReferenceRenderableDescendant(nestedRules, options)) {\n return true;\n }\n continue;\n }\n if (!isVisibleInContext(child, options.context) && !child.fullRender) {\n continue;\n }\n }\n return false;\n}\n\nfunction nodeExtendsReference(node: AtRule | Ruleset, options: FinalPrintOptions): boolean {\n if (isRulesetNode(node)) {\n if (rulesetExtendsReference(node, options)) {\n return true;\n }\n const rules = node.enterRules(options.context);\n return rules ? rulesHaveReferenceRenderableDescendant(rules, options) : false;\n }\n const rules = node.enterRules(options.context);\n return rules ? rulesHaveReferenceRenderableDescendant(rules, options) : false;\n}\n\nfunction framesHaveSameHeader(\n currentFrame: AtRule | Ruleset,\n priorFrame: AtRule | Ruleset,\n depth: number,\n options: FinalPrintOptions\n): boolean {\n if (currentFrame.type !== priorFrame.type) {\n return false;\n }\n const currentHeader = currentFrame.getHeaderString({ ...options, depth }, true);\n const priorHeader = priorFrame.getHeaderString({ ...options, depth }, true);\n return currentHeader === priorHeader;\n}\n\n/**\n * Handles flattening and serializing of at-rules and rulesets\n */\nexport function serializeRulesContainer(node: AtRule | Ruleset, options: FinalPrintOptions): string {\n const w = options.writer;\n let inFrames = options.inFrames;\n const frameHeaders = options.frameHeaders;\n\n if (isRulesetNode(node) && node.getRenderableSelector(options.collapseNesting, options.context) instanceof Nil) {\n return '';\n }\n // let header = node.getHeaderString(options);\n\n const mark = w.mark();\n const previousReferenceMode = options.referenceMode === true;\n const previousReferenceRenderEnabled = options.referenceRenderEnabled !== false;\n const previousReferenceRenderOnExtend = options.referenceRenderOnExtend !== false;\n const inReferenceMode = previousReferenceMode;\n const enteringReferenceMode = false;\n const inheritedRenderEnabled = enteringReferenceMode ? false : previousReferenceRenderEnabled;\n const renderEnabled = inReferenceMode\n ? (inheritedRenderEnabled || (previousReferenceRenderOnExtend && nodeExtendsReference(node, options)))\n : true;\n const isOptionalReferenceBoundary = isRulesNode(node)\n && getRulesVisibility(node)?.Ruleset === 'optional';\n options.referenceMode = inReferenceMode;\n options.referenceRenderEnabled = renderEnabled;\n options.referenceRenderOnExtend = previousReferenceRenderOnExtend;\n if (isRulesetNode(node) && inReferenceMode && renderEnabled) {\n const previewHeader = node.getHeaderString(options, false);\n if (!previewHeader) {\n const nestedRules = node.enterRules(options.context);\n if (!nestedRules || !rulesHaveReferenceRenderableDescendant(nestedRules, options)) {\n options.referenceMode = previousReferenceMode;\n options.referenceRenderEnabled = previousReferenceRenderEnabled;\n options.referenceRenderOnExtend = previousReferenceRenderOnExtend;\n return '';\n }\n }\n }\n const rules = node.enterRules(options.context);\n if (!rules) {\n if (inReferenceMode && !renderEnabled) {\n options.referenceMode = previousReferenceMode;\n options.referenceRenderEnabled = previousReferenceRenderEnabled;\n options.referenceRenderOnExtend = previousReferenceRenderOnExtend;\n return '';\n }\n // Leaf at-rules (no body) are not \"frame headers\". Always emit them with comments\n // preserved; comment-stripping should only apply to repeated *frame* headers.\n w.add(node.getHeaderString(options, false));\n options.referenceMode = previousReferenceMode;\n options.referenceRenderEnabled = previousReferenceRenderEnabled;\n options.referenceRenderOnExtend = previousReferenceRenderOnExtend;\n return w.getSince(mark);\n }\n\n const positionMap = new WeakMap<Node, FlatRulePosition>();\n let rulesToRender = rules.flatRules(true, options.context, positionMap);\n if (isRulesetNode(node) && inReferenceMode && renderEnabled) {\n const mergedMirrorBodyRules: Node[] = [];\n const expandedRulesToRender: Node[] = [];\n for (const child of rulesToRender) {\n if (isRulesetNode(child)) {\n const ownSelector = child.getOwnSelector();\n if (\n ownSelector\n && !(ownSelector instanceof Nil)\n && isBareAmpersandOwnSelector(ownSelector)\n ) {\n const childRules = child.enterRules(options.context);\n if (childRules) {\n for (const innerChild of childRules.flatRules(true, options.context, positionMap)) {\n if (isContainerNode(innerChild)) {\n expandedRulesToRender.push(innerChild);\n } else {\n mergedMirrorBodyRules.push(innerChild);\n }\n }\n continue;\n }\n }\n }\n expandedRulesToRender.push(child);\n }\n if (mergedMirrorBodyRules.length > 0) {\n const finalRulesToRender: Node[] = [];\n let insertedMergedMirrorBodyRules = false;\n for (const child of expandedRulesToRender) {\n const isContainer = isContainerNode(child);\n if (!insertedMergedMirrorBodyRules && isContainer) {\n finalRulesToRender.push(...mergedMirrorBodyRules);\n insertedMergedMirrorBodyRules = true;\n }\n finalRulesToRender.push(child);\n }\n if (!insertedMergedMirrorBodyRules) {\n finalRulesToRender.push(...mergedMirrorBodyRules);\n }\n rulesToRender = finalRulesToRender;\n } else {\n rulesToRender = expandedRulesToRender;\n }\n }\n const declarationOutputCache = new Map<object, string>();\n const skippedDuplicateDeclarations = new Set<object>();\n const seenDeclarationsByProp = new Map<string, Set<string>>();\n const withNodePosition = <T>(target: Node, fn: () => T): T => {\n const ctx = options.context;\n const position = positionMap.get(target);\n if (!ctx || !position) {\n return fn();\n }\n\n const previousRenderKey = ctx.renderKey;\n if (position.renderKey !== undefined) {\n ctx.renderKey = position.renderKey;\n }\n try {\n return fn();\n } finally {\n ctx.renderKey = previousRenderKey;\n }\n };\n if (rulesToRender.length === 0) {\n options.referenceMode = previousReferenceMode;\n options.referenceRenderEnabled = previousReferenceRenderEnabled;\n options.referenceRenderOnExtend = previousReferenceRenderOnExtend;\n return '';\n }\n\n // Less-style duplicate declaration handling:\n // for each property, keep the last exact serialized declaration and skip earlier duplicates.\n for (let i = rulesToRender.length - 1; i >= 0; i--) {\n const node = rulesToRender[i]!;\n if (!isDeclarationNode(node) || isNode(node, N.VarDeclaration)) {\n continue;\n }\n // Push per-node position so patched fields are visible during dedup\n const declWriter = new OutputWriter();\n const declOptions = getPrintOptions({ ...options, writer: declWriter, depth: options.depth + 1 });\n const declOut = withNodePosition(node, () => node.toTrimmedString(declOptions));\n declarationOutputCache.set(node, declOut);\n const declKey = `${declOut}${node.requiresSemi(options.context) ? ';' : ''}`;\n const declProp = node.get('name', options.context).valueOf();\n let seenValues = seenDeclarationsByProp.get(declProp);\n if (!seenValues) {\n seenValues = new Set<string>();\n seenDeclarationsByProp.set(declProp, seenValues);\n }\n if (seenValues.has(declKey)) {\n skippedDuplicateDeclarations.add(node);\n } else {\n seenValues.add(declKey);\n }\n }\n\n const hoisted = node.isHoisted(options);\n // const isRuleset = isNode(node, 'Ruleset');\n const treeFrames = options.treeFrames!;\n const prevTreeFrames = hoisted ? treeFrames.slice() : undefined;\n if (hoisted) {\n // When hoisting, we must reset the active frame stack to at-rules only.\n // Otherwise, previously-rendered non-hoisted rulesets (e.g. `.header`) can remain\n // in `treeFrames` and cause nested output like:\n // .header { :is(.header-nav, .footer .footer-nav) { ... } }\n // even though the current node is hoisted to root.\n const atRulesOnly = treeFrames.filter(f => isNode(f, N.AtRule));\n treeFrames.splice(0, treeFrames.length, ...atRulesOnly, node);\n options.inFrames = inFrames = treeFrames;\n } else {\n options.inFrames = inFrames = treeFrames!;\n inFrames.push(node);\n }\n // Note: in the hoisted branch above, `node` is already included.\n\n let lastRenderedFrames = options.lastRenderedFrames;\n\n /** Don't output selector yet. Let's see if any child rules need hoisting. */\n for (let idx = 0; idx < rulesToRender.length; idx++) {\n let n = rulesToRender[idx]!;\n const isContainer = isNode(n, N.Ruleset | N.AtRule | N.Rules);\n\n // Push per-node position from the position map so patched fields resolve\n const skipped = withNodePosition(n, () => {\n if (!isVisibleInContext(n, options.context) && !n.fullRender) {\n return true;\n }\n if (inReferenceMode && !renderEnabled && !isOptionalReferenceBoundary && isContainer) {\n return true;\n }\n if (inReferenceMode && !renderEnabled && !isContainer) {\n return true;\n }\n if (isNode(n, N.Declaration) && !isNode(n, N.VarDeclaration) && skippedDuplicateDeclarations.has(n)) {\n return true;\n }\n\n if (isRulesNode(n)) {\n const ownRefMode = isReferenceModeRules(n);\n const childRefMode = inReferenceMode || ownRefMode;\n const entering = !inReferenceMode && ownRefMode;\n const childRenderEnabled = childRefMode\n ? (entering ? false : renderEnabled)\n : true;\n const childOptions: FinalPrintOptions = {\n ...options,\n referenceMode: childRefMode,\n referenceRenderEnabled: childRenderEnabled,\n referenceRenderOnExtend: previousReferenceRenderOnExtend\n };\n const childOut = w.capture(() => n.toTrimmedString(childOptions));\n if (childOut) {\n w.add(childOut, n);\n }\n return true;\n }\n const isLeafAtRule = isAtRuleNode(n) && !n.enterRules(options.context);\n if (isContainerNode(n) && !isLeafAtRule) {\n const childReferenceRenderEnabled = (\n inReferenceMode\n && isAtRuleNode(node)\n && isContainerNode(n)\n )\n ? nodeExtendsReference(n, options)\n : renderEnabled;\n const keepReferenceFilteringForBareMirror = (\n inReferenceMode\n && renderEnabled\n && isRulesetNode(node)\n && isRulesetNode(n)\n && Boolean(\n (() => {\n const ownSelector = n.getOwnSelector();\n return ownSelector\n && !(ownSelector instanceof Nil)\n && isBareAmpersandOwnSelector(ownSelector);\n })()\n )\n );\n const childReferenceMode = (\n inReferenceMode\n && isAtRuleNode(node)\n && isContainerNode(n)\n )\n ? true\n : keepReferenceFilteringForBareMirror\n ? true\n : (inReferenceMode && renderEnabled && !isOptionalReferenceBoundary) ? false : inReferenceMode;\n const childOptions: FinalPrintOptions = {\n ...options,\n referenceMode: childReferenceMode,\n referenceRenderEnabled: childReferenceRenderEnabled,\n referenceRenderOnExtend: previousReferenceRenderOnExtend,\n preserveCapturedContainerFrame: true\n };\n const childOut = w.capture(() => n.toTrimmedString(childOptions));\n if (!childOut) {\n return true;\n }\n w.add(childOut, n);\n return true;\n }\n\n return false;\n });\n if (skipped) {\n continue;\n }\n\n withNodePosition(n, () => {\n let matches = -1;\n for (let i = 0; i < lastRenderedFrames.length; i++) {\n const currentFrame = inFrames[i];\n const priorFrame = lastRenderedFrames[i];\n const sameFrame = currentFrame === priorFrame\n || (\n currentFrame\n && priorFrame\n && isContainerNode(currentFrame)\n && isContainerNode(priorFrame)\n && !isRulesNode(currentFrame)\n && !isRulesNode(priorFrame)\n && framesHaveSameHeader(currentFrame, priorFrame, i, options)\n );\n if (!sameFrame) {\n break;\n }\n matches = i;\n }\n for (let i = lastRenderedFrames.length - 1; i > matches; i--) {\n w.add(indent(i) + '}\\n');\n frameHeaders.pop();\n lastRenderedFrames.pop();\n options.depth = i;\n }\n\n for (let i = matches + 1; i < inFrames.length; i++) {\n let s = frameHeaders[i];\n const f = inFrames[i]!;\n lastRenderedFrames.push(f);\n if (s === undefined) {\n s = inFrames[i]!.getHeaderString({ ...options, depth: i });\n frameHeaders[i] = s;\n } else if (s === '') {\n s = inFrames[i]!.getHeaderString({ ...options, depth: i }, true);\n frameHeaders[i] = s;\n }\n options.depth = i;\n w.add(s!);\n }\n\n const idt = indent(options.depth + 1);\n const nn = n;\n let pre = w.capture(() => nn.processPrePost('pre', undefined, options));\n const out = isDeclarationNode(nn)\n ? (declarationOutputCache.get(nn) ?? w.capture(() => nn.toTrimmedString({ ...options, depth: options.depth + 1 })))\n : w.capture(() => nn.toTrimmedString({ ...options, depth: options.depth + 1 }));\n if (\n isNode(nn, N.Any)\n && !nn.requiredSemi\n && !out.trim()\n && !pre.trim()\n ) {\n return;\n }\n if (isDeclarationNode(nn)) {\n pre = pre.replace(/^[\\s\\S]*\\n([ \\t]*)$/g, '$1');\n const declIn = pre + out;\n const hasEmptyValue = /:\\s*$/.test(out);\n const declNormalized = hasEmptyValue && (!pre || pre.trim() === '')\n ? `${idt}${out}`\n : normalizeIndent(declIn, idt, true);\n if (nn.isCustomProperty(options.context)) {\n w.add(idt);\n w.add(out, nn);\n } else {\n w.add(declNormalized, nn);\n }\n } else if (isRulesNode(nn)) {\n w.add(out, nn);\n } else if (isAtRuleNode(nn) && !nn.enterRules(options.context)) {\n w.add(out, nn);\n } else {\n w.add(idt);\n w.add(out, nn);\n }\n if (isDeclarationNode(nn) ? nn.requiresSemi(options.context) : nn.requiredSemi) {\n w.add(';');\n }\n\n w.add('\\n');\n const post = w.capture(() => nn.processPrePost('post', undefined, options));\n if (!/^\\s*$/.test(post)) {\n w.add(normalizeIndent(post, idt));\n }\n });\n }\n inFrames.pop();\n frameHeaders.pop();\n const frameCloseBase = options.preserveCapturedContainerFrame\n ? treeFrames.length + 1\n : treeFrames.length;\n while (lastRenderedFrames.length > frameCloseBase) {\n w.add(indent(lastRenderedFrames.length - 1) + '}\\n');\n options.depth = Math.max(frameCloseBase, options.depth - 1);\n lastRenderedFrames.pop();\n }\n if (prevTreeFrames) {\n treeFrames.splice(0, treeFrames.length, ...prevTreeFrames);\n }\n options.referenceMode = previousReferenceMode;\n options.referenceRenderEnabled = previousReferenceRenderEnabled;\n options.referenceRenderOnExtend = previousReferenceRenderOnExtend;\n return w.getSince(mark);\n}\n","/**\n * Centralized unwrapping of generated :is() pseudo-selectors when they are\n * the \"first visual\" selector (leading). Used after ruleset eval and in\n * extend post-processing. Does NOT recurse into pseudo args; callers that\n * need to process pseudo args (e.g. extend) call processLeadingIs for each\n * selector they care about, including args of :is/:where at processing time.\n */\n\nimport type { Selector } from '../selector.js';\nimport { SelectorList } from '../selector-list.js';\nimport { ComplexSelector, type ComplexSelectorComponent } from '../selector-complex.js';\nimport { CompoundSelector } from '../selector-compound.js';\nimport { PseudoSelector } from '../selector-pseudo.js';\nimport { Ampersand } from '../ampersand.js';\nimport { F_IMPLICIT_AMPERSAND, type Node } from '../node.js';\nimport { Nil } from '../nil.js';\nimport { isPlainObject } from './collections.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\n\nexport type ProcessLeadingIsOptions = {\n /** When true, unwrapping a generated :is(SelectorList) merges its items into the outer list (return array). */\n inSelectorList?: boolean;\n};\n\n/**\n * Unwrap a generated :is() that is the first visual selector, when safe.\n * - If selector is a SelectorList: process each item with inSelectorList=true; flatten any array returns.\n * - If selector is a single generated :is(): when inSelectorList and arg is SelectorList, return arg.data (array); else return arg.\n * - If first visual component of a CompoundSelector is generated :is (arg not SelectorList): merge :is arg's last part with compound suffix into a new ComplexSelector.\n * - If first visual component of a ComplexSelector is generated :is (arg not SelectorList): unwrap into the complex's components.\n *\n * Does NOT recurse into pseudo-selector args. Only considers the outer selector structure.\n *\n * @returns The processed selector, or an array of selectors when unwrapping :is(SelectorList) in list context (caller merges into list).\n */\nexport function processLeadingIs(\n selector: Selector,\n options: ProcessLeadingIsOptions = {}\n): Selector | Selector[] {\n const { inSelectorList = false } = options;\n\n const getFirstVisualIndex = (items: ComplexSelectorComponent[]): number => {\n for (let i = 0; i < items.length; i++) {\n if (!isNode(items[i], N.Combinator)) {\n return i;\n }\n }\n return -1;\n };\n\n const getImplicitAmpPrefix = (complex: ComplexSelector): string | null => {\n for (const part of complex.value) {\n if (isNode(part, N.Ampersand) && (part as unknown as Node).hasFlag(F_IMPLICIT_AMPERSAND)) {\n const resolved = (part as Ampersand).getResolvedSelector();\n return resolved && !(resolved instanceof Nil) ? resolved.valueOf() : null;\n }\n }\n return null;\n };\n\n const hasEscapedQuoted = (node: Node | undefined, seen = new Set<Node>()): boolean => {\n if (!node || seen.has(node)) {\n return false;\n }\n seen.add(node);\n if (isNode(node, N.Quoted) && Boolean(node.escaped)) {\n return true;\n }\n const value = 'value' in node ? node.value : undefined;\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item && typeof item === 'object' && 'type' in (item as Record<string, unknown>)) {\n if (hasEscapedQuoted(item as Node, seen)) {\n return true;\n }\n }\n }\n return false;\n }\n if (isPlainObject(value)) {\n for (const item of Object.values(value)) {\n if (item && typeof item === 'object' && 'type' in (item as Record<string, unknown>)) {\n if (hasEscapedQuoted(item as Node, seen)) {\n return true;\n }\n }\n }\n }\n return false;\n };\n\n const stripImplicitPrefixFromItem = (item: Selector, implicitAmpPrefix: string): Selector => {\n if (!isNode(item, N.ComplexSelector)) {\n return item.clone(false) as Selector;\n }\n const itemComplex = item as ComplexSelector;\n const firstVisualIndex = getFirstVisualIndex([...itemComplex.value]);\n if (firstVisualIndex < 0) {\n return item.clone(false) as Selector;\n }\n const firstVisual = itemComplex.value[firstVisualIndex] as Selector;\n if (firstVisual.valueOf() !== implicitAmpPrefix) {\n return item.clone(false) as Selector;\n }\n let start = firstVisualIndex + 1;\n if (start < itemComplex.value.length && isNode(itemComplex.value[start], N.Combinator)) {\n start++;\n }\n const tail = itemComplex.value.slice(start).map(c => (c as Selector).clone(false) as ComplexSelectorComponent);\n if (tail.length === 1 && !isNode(tail[0], N.Combinator)) {\n return tail[0] as Selector;\n }\n if (tail.length > 1) {\n return ComplexSelector.create(tail).inherit(itemComplex) as Selector;\n }\n return item.clone(false) as Selector;\n };\n\n // SelectorList: process each item; merge list results (array or SelectorList) into one list.\n if (isNode(selector, N.SelectorList)) {\n const list = selector as SelectorList;\n const out: Selector[] = [];\n const seen = new Set<string>();\n let changed = false;\n const pushUnique = (item: Selector): void => {\n const key = item.valueOf();\n if (seen.has(key)) {\n changed = true;\n return;\n }\n seen.add(key);\n out.push(item);\n };\n for (const item of list.value) {\n const result = processLeadingIs(item, { inSelectorList: true });\n if (Array.isArray(result)) {\n for (const entry of result) {\n pushUnique(entry);\n }\n changed = true;\n } else if (isNode(result, N.SelectorList)) {\n for (const entry of (result as SelectorList).value.map(s => s.clone(false) as Selector)) {\n pushUnique(entry);\n }\n changed = true;\n } else {\n pushUnique(result);\n changed ||= result !== item;\n }\n }\n if (!changed) {\n return selector;\n }\n if (out.length === 1) {\n return out[0]!;\n }\n return SelectorList.create(out.map(s => s.clone(false) as Selector)).inherit(selector) as Selector;\n }\n\n // Single PseudoSelector :is, generated\n if (isNode(selector, N.PseudoSelector)) {\n const pseudo = selector as PseudoSelector;\n if (pseudo.name !== ':is' || !pseudo.generated) {\n return selector;\n }\n const arg = pseudo.arg as Selector | undefined;\n if (!arg) {\n return selector;\n }\n if (hasEscapedQuoted(arg)) {\n return selector;\n }\n // :is(SelectorList): in list context merge; else return array for caller to handle\n if (isNode(arg, N.SelectorList)) {\n if (inSelectorList) {\n return arg.value.map(s => s.clone(false) as Selector);\n }\n // Top-level single :is(SelectorList): unwrap to the list (or single if one item)\n if (arg.value.length === 1) {\n return arg.value[0]!.clone(false) as Selector;\n }\n return SelectorList.create(arg.value.map(s => s.clone(false) as Selector)).inherit(selector) as Selector;\n }\n // :is(not list): unwrap to the single selector\n return arg.clone(false) as Selector;\n }\n\n // CompoundSelector: first component is generated :is (arg not list) → merge suffix into last part of :is, return ComplexSelector.\n // GCD of complex + compound is complex (e.g. parent * b + &[e] → * b[e]), so we unwrap to that shape.\n if (isNode(selector, N.CompoundSelector)) {\n const compound = selector as CompoundSelector;\n const value = compound.value;\n if (value.length === 0) {\n return selector;\n }\n const first = value[0];\n if (\n !isNode(first, N.PseudoSelector)\n || (first as PseudoSelector).name !== ':is'\n || !(first as PseudoSelector).generated\n ) {\n return selector;\n }\n const arg = (first as PseudoSelector).arg as Selector | undefined;\n if (!arg) {\n return selector;\n }\n if (hasEscapedQuoted(arg)) {\n return selector;\n }\n const normalizedArg = isNode(arg, N.SelectorList) && arg.value.length === 1\n ? (arg.value[0]! as Selector)\n : arg;\n if (isNode(normalizedArg, N.SelectorList)) {\n const suffix = value.slice(1).map(s => (s as Selector).clone(false));\n if (suffix.length === 0) {\n return SelectorList.create(normalizedArg.value.map(s => s.clone(false) as Selector)).inherit(selector) as Selector;\n }\n // Keep :is(list).suffix (e.g. :is(.one,.two).three) as one selector.\n return selector;\n }\n\n const suffix = value.slice(1).map(s => (s as Selector).clone(false));\n if (suffix.length === 0) {\n return arg.clone(false) as Selector;\n }\n\n // Merge suffix into last component of arg (complex or compound)\n if (isNode(normalizedArg, N.ComplexSelector)) {\n const complex = normalizedArg as ComplexSelector;\n const comps = complex.value.slice().map(c => (c as Selector).clone(false) as ComplexSelectorComponent);\n for (let i = comps.length - 1; i >= 0; i--) {\n const c = comps[i]!;\n if (isNode(c, N.Combinator)) {\n continue;\n }\n if (isNode(c, N.CompoundSelector)) {\n const compound = c as CompoundSelector;\n const newCompound = CompoundSelector.create([\n ...compound.value.map(s => (s as Selector).clone(false)),\n ...suffix\n ]).inherit(compound);\n comps[i] = newCompound as ComplexSelectorComponent;\n break;\n }\n comps[i] = CompoundSelector.create([\n (c as Selector).clone(false),\n ...suffix\n ]) as ComplexSelectorComponent;\n break;\n }\n return ComplexSelector.create(comps).inherit(selector) as Selector;\n }\n if (isNode(normalizedArg, N.CompoundSelector)) {\n const newCompound = (normalizedArg as CompoundSelector).value.slice().map(s => (s as Selector).clone(false));\n newCompound.push(...suffix);\n return CompoundSelector.create(newCompound).inherit(selector) as Selector;\n }\n const newCompound = CompoundSelector.create([\n normalizedArg.clone(false),\n ...suffix\n ]).inherit(selector);\n return ComplexSelector.create([newCompound as ComplexSelectorComponent]).inherit(selector) as Selector;\n }\n\n // ComplexSelector: first visual component is generated :is (arg not list) → unwrap into complex\n if (isNode(selector, N.ComplexSelector)) {\n const complex = selector as ComplexSelector;\n const implicitAmpPrefix = getImplicitAmpPrefix(complex);\n if (implicitAmpPrefix) {\n let changed = false;\n const outComponents: ComplexSelectorComponent[] = [];\n for (const part of complex.value) {\n if (isNode(part, N.PseudoSelector) && part.name === ':is' && part.generated) {\n const arg = part.arg;\n if (arg && hasEscapedQuoted(arg as Node)) {\n outComponents.push((part as Selector).clone(false) as ComplexSelectorComponent);\n continue;\n }\n if (arg && isNode(arg, N.SelectorList)) {\n const normalizedArgs = arg.value.map((item) => {\n const normalized = stripImplicitPrefixFromItem(item as Selector, implicitAmpPrefix);\n if (normalized.valueOf() !== (item as Selector).valueOf()) {\n changed = true;\n }\n return normalized;\n });\n let nonCombinatorCount = 0;\n let hasImplicitAmpPart = false;\n for (const c of complex.value) {\n if (!isNode(c, N.Combinator)) {\n nonCombinatorCount++;\n if (isNode(c, N.Ampersand) && (c as unknown as Node).hasFlag(F_IMPLICIT_AMPERSAND)) {\n hasImplicitAmpPart = true;\n }\n }\n }\n // `& :is(list)` under collapse should serialize as list headers.\n if (nonCombinatorCount === 2 && hasImplicitAmpPart) {\n return SelectorList.create(normalizedArgs).inherit(selector) as Selector;\n }\n const list = SelectorList.create(normalizedArgs).inherit(arg);\n outComponents.push(...list.value.map(s => s.clone(false) as ComplexSelectorComponent));\n changed = true;\n continue;\n }\n }\n outComponents.push((part as Selector).clone(false) as ComplexSelectorComponent);\n }\n if (changed) {\n if (outComponents.length === 1 && !isNode(outComponents[0], N.Combinator)) {\n return outComponents[0] as Selector;\n }\n return ComplexSelector.create(outComponents).inherit(selector) as Selector;\n }\n }\n\n const value = [...complex.value];\n const firstSelIndex = getFirstVisualIndex(value);\n if (firstSelIndex < 0) {\n return selector;\n }\n const first = value[firstSelIndex];\n if (\n isNode(first, N.CompoundSelector)\n && isNode((first as CompoundSelector).value?.[0], N.PseudoSelector)\n && ((first as CompoundSelector).value?.[0] as PseudoSelector).name === ':is'\n && ((first as CompoundSelector).value?.[0] as PseudoSelector).generated\n ) {\n const unwrappedFirst = processLeadingIs(first as Selector, { inSelectorList: false });\n if (!Array.isArray(unwrappedFirst)) {\n const prefix = value\n .slice(0, firstSelIndex)\n .map(c => (c as Selector).clone(false) as ComplexSelectorComponent);\n const rest = value\n .slice(firstSelIndex + 1)\n .map(c => (c as Selector).clone(false) as ComplexSelectorComponent);\n const unwrappedComps = isNode(unwrappedFirst, N.ComplexSelector)\n ? (unwrappedFirst as ComplexSelector).value.map(c => (c as Selector).clone(false) as ComplexSelectorComponent)\n : [unwrappedFirst.clone(false) as ComplexSelectorComponent];\n return ComplexSelector.create([\n ...prefix,\n ...unwrappedComps,\n ...rest\n ]).inherit(selector) as Selector;\n }\n }\n if (\n !isNode(first, N.PseudoSelector)\n || (first as PseudoSelector).name !== ':is'\n || !(first as PseudoSelector).generated\n ) {\n return selector;\n }\n const arg = (first as PseudoSelector).arg as Selector | undefined;\n if (!arg) {\n return selector;\n }\n if (hasEscapedQuoted(arg)) {\n return selector;\n }\n const normalizedArg = isNode(arg, N.SelectorList) && arg.value.length === 1\n ? (arg.value[0]! as Selector)\n : arg;\n if (isNode(normalizedArg, N.SelectorList)) {\n const normalizedList = processLeadingIs(normalizedArg as Selector, { inSelectorList: true });\n const rest = value.slice(firstSelIndex + 1).map(c => (c as Selector).clone(false) as ComplexSelectorComponent);\n // Keep :is(list) when there is a suffix (e.g. :is(.one,.two) .three) so it serializes as one selector.\n if (rest.length > 0) {\n if (isNode(normalizedList, N.SelectorList) && normalizedList !== normalizedArg) {\n const copy = (first as PseudoSelector).clone(false) as PseudoSelector;\n copy.adopt(normalizedList);\n copy.arg = normalizedList;\n return ComplexSelector.create([\n ...value.slice(0, firstSelIndex).map(c => (c as Selector).clone(false) as ComplexSelectorComponent),\n copy as unknown as ComplexSelectorComponent,\n ...rest\n ]).inherit(selector) as Selector;\n }\n return selector;\n }\n const listArg = isNode(normalizedList, N.SelectorList)\n ? normalizedList as SelectorList\n : normalizedArg as SelectorList;\n const expanded: Selector[] = listArg.value.map((item) => {\n if (isNode(item, N.ComplexSelector)) {\n return ComplexSelector.create([\n ...(item as ComplexSelector).value.map(c => (c as Selector).clone(false) as ComplexSelectorComponent),\n ...rest\n ]).inherit(selector) as Selector;\n }\n if (rest.length === 0) {\n return (item as Selector).clone(false) as Selector;\n }\n return ComplexSelector.create([\n (item as Selector).clone(false) as ComplexSelectorComponent,\n ...rest\n ]).inherit(selector) as Selector;\n });\n if (expanded.length === 1) {\n return expanded[0]!;\n }\n return SelectorList.create(expanded).inherit(selector) as Selector;\n }\n\n if (isNode(normalizedArg, N.ComplexSelector)) {\n const argComplex = normalizedArg as ComplexSelector;\n const rest = value.slice(firstSelIndex + 1);\n const argComps = argComplex.value.slice().map(c => (c as Selector).clone(false) as ComplexSelectorComponent);\n const restComps = rest.map(c => (c as Selector).clone(false) as ComplexSelectorComponent);\n const newValue = [...argComps, ...restComps];\n return ComplexSelector.create(newValue).inherit(selector) as Selector;\n }\n const rest = value.slice(firstSelIndex + 1).map(c => (c as Selector).clone(false) as ComplexSelectorComponent);\n const newValue = [normalizedArg.clone(false) as ComplexSelectorComponent, ...rest];\n return ComplexSelector.create(newValue).inherit(selector) as Selector;\n }\n\n return selector;\n}\n","import {\n CALLER,\n CANONICAL,\n Node,\n F_VISIBLE,\n F_EXTENDED,\n F_EXTEND_TARGET,\n F_IMPLICIT_AMPERSAND,\n F_NON_STATIC,\n defineType,\n type NodeOptions,\n type OptionalLocation,\n type RenderKey,\n type NodeEdge\n} from './node.js';\nimport { Rules } from './rules.js';\nimport type { Context, TreeContext } from '../context.js';\nimport { Nil } from './nil.js';\nimport { Bool } from './bool.js';\nimport type { Condition } from './condition.js';\nimport type { Selector } from './selector.js';\nimport { atIndex } from './util/collections.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { Ampersand } from './ampersand.js';\nimport { ComplexSelector, type ComplexSelectorComponent } from './selector-complex.js';\nimport { SelectorList } from './selector-list.js';\nimport { type PrintOptions, type FinalPrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, pipe, isThenable } from '@jesscss/awaitable-pipe';\nimport type { AtRule } from './at-rule.js';\nimport { serializeRulesContainer, normalizeIndent, indent } from './util/serialize-helper.js';\nimport { getCurrentParentNode, getImplicitSelector as getImplicitSelectorUtil, getParentRuleset, hasExtendedSelector, hasSourceExtendWrapperParent, selectorHasAuthoredAmpersand } from './util/selector-utils.js';\nimport { addEdge } from './util/cursor.js';\nimport { processLeadingIs } from './util/process-leading-is.js';\n\nexport type RulesetValue = {\n selector: Selector | Nil;\n /**\n * It's important that any Node that defines a Rules\n * sets it to the `rules` property. This allows us to\n * generalize nodes for the `frames` property in Context\n */\n rules: Rules;\n guard?: Condition | Nil;\n /**\n * When this ruleset is extended, we store its selector before the first extend.\n * Nested rulesets' implicit & (selectorContainer → parent value) use this when set, so they\n * do not \"see\" the extended form (EXTEND_RULES §5: do not materialize ampersands\n * that were not matched and extended).\n */\n selectorBeforeExtend?: Selector | Nil;\n};\n\ntype RulesetOptions = NodeOptions & {\n parentSelector?: Selector | Nil;\n /** Own selector before parent resolution (getImplicitSelector); used by extend so nested rulesets extend .replace,.c not the resolved form. */\n ownSelector?: Selector | Nil;\n /** Hoisted at-rule wrapper already carries the caller selector; do not prepend the parent again in preEval. */\n resolvedHoistWrapper?: boolean;\n};\n\n/** @todo - Fix typing */\ntype NarrowRulesetValue<T> = T extends RulesetValue ? T : RulesetValue;\n\nexport type RulesetChildData = {\n selector: Selector | Nil;\n rules: Rules;\n guard: Condition | Nil | undefined;\n selectorBeforeExtend: Selector | Nil | undefined;\n /** Patched selector from extend — used by serialization instead of canonical selector. */\n _extendedSelector: Selector | Nil | undefined;\n frames: (Ruleset | AtRule)[] | undefined;\n};\n\n/**\n * A qualified rule. This is historically called a \"Ruleset\"\n * by older CSS documentation and by Less.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_rulesets\n *\n * @example\n * .box {\n * color: black;\n * }\n */\nexport interface Ruleset {\n type: 'Ruleset';\n shortType: 'ruleset';\n}\n\nexport class Ruleset<T = RulesetValue> extends Node<NarrowRulesetValue<T>, RulesetOptions, RulesetChildData> {\n static override childKeys = ['selector', 'rules', 'guard', 'selectorBeforeExtend'] as const;\n\n // Ruleset has preEval method but doesn't need to set flags - preEvaluated is tracked as boolean\n private frames: (Ruleset | AtRule)[] | undefined;\n\n selector!: Selector | Nil;\n declare selectorEdge: NodeEdge<Selector | Nil> | undefined;\n rules!: Rules;\n declare rulesEdge: NodeEdge<Rules> | undefined;\n guard: Condition | Nil | undefined;\n declare guardEdge: NodeEdge<Condition | Nil | undefined> | undefined;\n selectorBeforeExtend: Selector | Nil | undefined;\n declare selectorBeforeExtendEdge: NodeEdge<Selector | Nil | undefined> | undefined;\n /** Patched selector from extend — used by serialization instead of canonical selector. */\n private _extendedSelector: Selector | Nil | undefined;\n declare _extendedSelectorEdge: NodeEdge<Selector | Nil | undefined> | undefined;\n\n constructor(value: NarrowRulesetValue<T>, options?: RulesetOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.selector = value.selector;\n this.rules = value.rules;\n this.guard = value.guard;\n this.selectorBeforeExtend = value.selectorBeforeExtend;\n if (this.selector instanceof Node) {\n this.adopt(this.selector);\n }\n if (this.rules instanceof Node) {\n this.adopt(this.rules);\n }\n if (this.guard instanceof Node) {\n this.adopt(this.guard);\n }\n if (this.selectorBeforeExtend instanceof Node) {\n this.adopt(this.selectorBeforeExtend);\n }\n this.allowRoot = true;\n this.allowRuleRoot = true;\n }\n\n /**\n * If this ruleset shares its value object with a descendant ruleset, give those\n * descendants their own value so mutating this ruleset's value.selector does not\n * overwrite the descendant's selector (e.g. .rep_ace nested ruleset case).\n */\n static ensureDescendantRulesetsHaveOwnValue(\n ruleset: Ruleset,\n sharedValue: RulesetValue\n ): void {\n const rules = ruleset.rules;\n if (!rules || !isNode(rules, N.Rules)) {\n return;\n }\n const children = (rules as Rules).value;\n if (!Array.isArray(children)) {\n return;\n }\n for (const child of children) {\n if (!isNode(child, N.Ruleset)) {\n continue;\n }\n const rs = child as Ruleset;\n // With instance fields (no shared data object), shallow clones already\n // have independent fields, so this identity check is always false.\n // Kept for structural safety until full clone audit.\n Ruleset.ensureDescendantRulesetsHaveOwnValue(rs, sharedValue);\n }\n }\n\n static collapseRedundantGeneratedChildren(ruleset: Ruleset): void {\n const rules = ruleset.rules;\n if (!rules || !isNode(rules, N.Rules)) {\n return;\n }\n const children = [...rules.value];\n const normalized: Node[] = [];\n for (const child of children) {\n if (!isNode(child, N.Ruleset)) {\n normalized.push(child);\n continue;\n }\n const childRuleset = child as Ruleset;\n Ruleset.collapseRedundantGeneratedChildren(childRuleset);\n const shouldInline =\n Boolean(ruleset.options?.generated)\n && Boolean(childRuleset.options?.generated)\n && String(ruleset.selector?.valueOf?.() ?? '') === String(childRuleset.selector?.valueOf?.() ?? '');\n if (shouldInline) {\n normalized.push(...childRuleset.rules.value);\n continue;\n }\n normalized.push(childRuleset);\n }\n if (normalized.length !== rules.value.length || normalized.some((node, index) => node !== rules.value[index])) {\n rules._setValueArray(normalized);\n for (const child of normalized) {\n rules.adopt(child);\n }\n }\n }\n\n isHoisted(options: PrintOptions) {\n return this.hoistToRoot ?? options.collapseNesting ?? false;\n }\n\n protected _valueOf: string | undefined;\n\n private _resolveRenderKey(context?: Context): RenderKey {\n return context?.renderKey ?? context?.rulesContext?.renderKey ?? this.renderKey;\n }\n\n getOwnSelector(): Selector | Nil | undefined {\n return this.options.ownSelector;\n }\n\n setOwnSelector(selector: Selector | Nil | undefined): void {\n this.options = {\n ...this.options,\n ownSelector: selector\n };\n }\n\n getSelector(renderKey?: RenderKey): Selector | Nil {\n return renderKey !== undefined\n ? this.selectorEdge?.get(renderKey) ?? this.selector\n : this.selector;\n }\n\n private _getSelectorSourceNode(selector: Selector | Nil | undefined): Node | undefined {\n if (!(selector instanceof Node)) {\n return undefined;\n }\n return selector.sourceNode;\n }\n\n /**\n * Transitional edge/cursor seam: enter the render-owned Rules container for\n * this ruleset. This is intentionally explicit because it may wrap/adopt.\n */\n enterRules(context?: Context): Rules {\n const renderKey = this._resolveRenderKey(context);\n const rules = this.getRules(renderKey);\n if (\n renderKey !== undefined\n && renderKey !== CANONICAL\n && rules === this.rules\n && this.rules.renderKey !== CANONICAL\n && this.rules.renderKey !== renderKey\n ) {\n const wrappedRules = this.rules.createShallowBodyWrapper(undefined, renderKey);\n addEdge(this, 'rules', renderKey, wrappedRules);\n if (context && getCurrentParentNode(wrappedRules, { ...context, renderKey }) !== this) {\n this.adopt(wrappedRules, { ...context, renderKey });\n }\n return wrappedRules;\n }\n if (rules !== this.rules) {\n if (context && getCurrentParentNode(rules, context) !== this) {\n this.adopt(rules, context);\n }\n return rules;\n }\n return rules.withRenderOwner(this, renderKey, context);\n }\n\n getRules(renderKey?: RenderKey): Rules {\n return renderKey !== undefined\n ? this.rulesEdge?.get(renderKey) ?? this.rules\n : this.rules;\n }\n\n private _assignRules(rules: Rules, context: Context): void {\n const renderKey = this._resolveRenderKey(context);\n if (renderKey !== undefined && renderKey !== CANONICAL) {\n this.rulesEdge?.delete(renderKey);\n if (this.rulesEdge?.size === 0) {\n this.rulesEdge = undefined;\n }\n }\n this.rules = rules;\n this.adopt(rules, context);\n }\n\n getGuard(renderKey?: RenderKey): Condition | Nil | undefined {\n return renderKey !== undefined\n ? this.guardEdge?.get(renderKey) ?? this.guard\n : this.guard;\n }\n\n getSelectorBeforeExtend(renderKey?: RenderKey): Selector | Nil | undefined {\n return renderKey !== undefined\n ? this.selectorBeforeExtendEdge?.get(renderKey) ?? this.selectorBeforeExtend\n : this.selectorBeforeExtend;\n }\n\n setSelectorBeforeExtend(selector: Selector | Nil | undefined, context: Context): void {\n const renderKey = this._resolveRenderKey(context);\n if (renderKey === undefined || renderKey === CANONICAL) {\n this.selectorBeforeExtend = selector;\n return;\n }\n if (selector instanceof Node) {\n this.adopt(selector, { ...context, renderKey });\n }\n addEdge(this, 'selectorBeforeExtend', renderKey, selector as Selector | Nil);\n }\n\n getExtendedSelector(renderKey?: RenderKey): Selector | Nil | undefined {\n return renderKey !== undefined\n ? this._extendedSelectorEdge?.get(renderKey) ?? this._extendedSelector\n : this._extendedSelector;\n }\n\n setExtendedSelector(selector: Selector | Nil | undefined, context?: Context): void {\n const renderKey = context ? this._resolveRenderKey(context) : undefined;\n if (renderKey === undefined || renderKey === CANONICAL) {\n this._extendedSelector = selector;\n this.invalidateSelectorValueCache();\n return;\n }\n if (selector instanceof Node) {\n this.adopt(selector, { ...context, renderKey });\n }\n addEdge(this, '_extendedSelector', renderKey, selector as Selector | Nil);\n this.invalidateSelectorValueCache();\n }\n\n /**\n * Returns the selector shape that should be printed for this ruleset.\n *\n * Nested rulesets keep rendering their local selector shape unless they are\n * being serialized from root (`hoistToRoot`) or collapse nesting is enabled.\n * In those cases, the selector must be recomposed against its parent.\n */\n getRenderableSelector(collapseNesting = this.treeContext?.opts?.collapseNesting ?? false, context?: Context): Selector | Nil {\n const ownSelector = this.getOwnSelector();\n if (\n !hasSourceExtendWrapperParent(this)\n && !this.hoistToRoot\n && !collapseNesting\n && ownSelector\n && !(ownSelector instanceof Nil)\n && this._hasAncestorRuleset(context)\n ) {\n return ownSelector as Selector;\n }\n\n return this.getEffectiveSelector(collapseNesting, context);\n }\n\n private _hasAncestorRuleset(context?: Context): boolean {\n const seen = new Set<Node>();\n const pending: Node[] = [];\n const enqueue = (node: Node | undefined) => {\n if (!node || seen.has(node)) {\n return;\n }\n seen.add(node);\n pending.push(node);\n };\n\n enqueue(getCurrentParentNode(this, context));\n enqueue(this.parent);\n for (const parent of this.parentEdges?.values?.() ?? []) {\n enqueue(parent);\n }\n\n while (pending.length > 0) {\n const current = pending.shift()!;\n if (isNode(current, N.Ruleset)) {\n return true;\n }\n enqueue(getCurrentParentNode(current, context));\n enqueue(current.parent);\n for (const parent of current.parentEdges?.values?.() ?? []) {\n enqueue(parent);\n }\n }\n return false;\n }\n\n /**\n * Returns the selector that should be used for matching/rendering right now.\n *\n * For nested rulesets that keep a local `ownSelector`, this recomposes the\n * selector against the current parent selector on demand instead of requiring\n * eager mutation of `data.selector` after extends. Hoisted rulesets keep their\n * concrete selector unchanged because they already serialize from root.\n */\n getEffectiveSelector(collapseNesting = this.treeContext?.opts?.collapseNesting ?? false, context?: Context): Selector | Nil {\n // Use extend-patched selector if available, else canonical\n const renderKey = this._resolveRenderKey(context);\n const extendedSelector = this.getExtendedSelector(renderKey);\n const selector = (extendedSelector ?? this.getSelector(renderKey)) as Selector | Nil;\n if (!selector || selector instanceof Nil) {\n return selector;\n }\n\n const ownSelector = this.getOwnSelector();\n const parentRs = getParentRuleset(this, context);\n if (\n collapseNesting\n && this.hoistToRoot\n && ownSelector\n && !(ownSelector instanceof Nil)\n && isNode(ownSelector as Selector, N.SelectorList)\n && isNode(selector as Selector, N.SelectorList)\n && ownSelector.valueOf() !== selector.valueOf()\n ) {\n return selector;\n }\n if (\n collapseNesting\n && this.hoistToRoot\n && ownSelector\n && !(ownSelector instanceof Nil)\n && Ruleset.isBareAmpersandSelector(ownSelector)\n ) {\n return selector;\n }\n const normalizeParentSelector = (parentSelector: Selector | Nil | undefined): Selector | Nil | undefined => {\n if (\n parentRs\n && parentSelector\n && !(parentSelector instanceof Nil)\n && Ruleset.isBareAmpersandSelector(parentSelector)\n ) {\n const parentOwn = parentRs.getOwnSelector();\n if (\n parentOwn\n && !(parentOwn instanceof Nil)\n && Ruleset.isBareAmpersandSelector(parentOwn)\n && parentRs.getSelector(parentRs._resolveRenderKey(context))\n && !(parentRs.getSelector(parentRs._resolveRenderKey(context)) instanceof Nil)\n && !Ruleset.isBareAmpersandSelector(parentRs.getSelector(parentRs._resolveRenderKey(context)))\n ) {\n return parentRs.getSelector(parentRs._resolveRenderKey(context));\n }\n }\n return parentSelector;\n };\n const getComposedParentSelector = (): Selector | Nil | undefined => {\n let parentSelector = normalizeParentSelector(parentRs?.getEffectiveSelector(collapseNesting, context));\n if (\n parentSelector\n && !(parentSelector instanceof Nil)\n && parentRs?.getSelectorBeforeExtend(parentRs._resolveRenderKey(context))\n && Ruleset.hasReferenceBoundaryParent(parentRs, context)\n ) {\n parentSelector = Ruleset.filterReferenceVisibleSelectorItems(\n parentSelector as Selector,\n parentRs.getSelectorBeforeExtend(parentRs._resolveRenderKey(context))\n );\n }\n return parentSelector;\n };\n const parentSelector = getComposedParentSelector();\n if (\n this.hoistToRoot\n && extendedSelector\n && !(extendedSelector instanceof Nil)\n && ownSelector\n && !(ownSelector instanceof Nil)\n && selectorHasAuthoredAmpersand(ownSelector as Selector)\n ) {\n return selector;\n }\n if (\n ownSelector\n && !(ownSelector instanceof Nil)\n && parentSelector\n && !(parentSelector instanceof Nil)\n && ownSelector.valueOf() !== selector.valueOf()\n ) {\n return getImplicitSelectorUtil(ownSelector as Selector, parentSelector as Selector, collapseNesting);\n }\n\n if (this.hoistToRoot) {\n return selector;\n }\n\n return selector;\n }\n\n /** Used for equality comparison with other rulesets */\n override valueOf(context?: Context) {\n if (context) {\n const collapseNesting = context.opts.collapseNesting ?? this.treeContext?.opts?.collapseNesting ?? false;\n const renderKey = this._resolveRenderKey(context);\n const selector = (\n this.getExtendedSelector(renderKey)\n || this.hoistToRoot\n || collapseNesting === true\n )\n ? this.getEffectiveSelector(collapseNesting, context)\n : this.getSelector(renderKey);\n return selector instanceof Nil ? '' : (selector as Selector).valueOf();\n }\n if (this._valueOf !== undefined) {\n return this._valueOf;\n }\n const selector = (\n this._extendedSelector\n || this.hoistToRoot\n || this.treeContext?.opts?.collapseNesting === true\n )\n ? this.getEffectiveSelector()\n : this.selector;\n if (selector instanceof Nil) {\n this._valueOf = '';\n return this._valueOf;\n }\n this._valueOf = selector instanceof Nil ? '' : (selector as Selector).valueOf();\n return this._valueOf;\n }\n\n /**\n * Invalidate cached selector-based string value.\n *\n * `Ruleset.valueOf()` is used by serialization frame tracking; when an extend\n * mutates `value.selector`, we must clear this cache so frame/header caching\n * reflects the updated selector.\n */\n invalidateSelectorValueCache(): void {\n this._valueOf = undefined;\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const opts = options as FinalPrintOptions;\n if (\n opts.referenceMode === true\n && opts.referenceRenderEnabled !== false\n && this.hoistToRoot\n ) {\n const ownSelector = this.getOwnSelector();\n if (ownSelector && Ruleset.isBareAmpersandSelector(ownSelector)) {\n return '';\n }\n }\n return serializeRulesContainer(this, opts);\n }\n\n /**\n * Render the opening of this ruleset (selector)\n * @todo - Efficiently serialize the selector with and without comments?\n */\n /** Ensure every node in the selector has F_VISIBLE so toString() does not skip them (rep_ace bug).\n * Do NOT add F_VISIBLE to implicit ampersands: they must stay invisible so nested output stays short. */\n private static ensureSelectorVisible(sel: Selector | Nil): void {\n if (!sel || sel instanceof Nil || typeof (sel as Node).addFlag !== 'function') {\n return;\n }\n const n = sel as Node;\n if (isNode(sel, N.Ampersand) && n.hasFlag(F_IMPLICIT_AMPERSAND)) {\n return;\n }\n if (!n.hasFlag(F_VISIBLE)) {\n n.addFlag(F_VISIBLE);\n }\n if (isNode(sel, N.SelectorList)) {\n const list = sel as SelectorList;\n for (const item of list.get('value')) {\n Ruleset.ensureSelectorVisible(item);\n }\n return;\n }\n if (isNode(sel, N.ComplexSelector)) {\n const comps = (sel as ComplexSelector).get('value');\n for (const c of comps) {\n Ruleset.ensureSelectorVisible(c as Selector);\n }\n return;\n }\n const v = 'value' in sel ? sel.value : undefined;\n if (Array.isArray(v)) {\n for (const c of v) {\n Ruleset.ensureSelectorVisible(c);\n }\n }\n }\n\n private static materializeHoistedImplicitAmpersands(sel: Selector | Nil): Selector | Nil {\n if (!sel || sel instanceof Nil) {\n return sel;\n }\n const materialize = (node: Selector): Selector => {\n if (isNode(node, N.Ampersand)) {\n const amp = node as Ampersand;\n const n = amp as unknown as Node;\n if (n.hasFlag(F_IMPLICIT_AMPERSAND)) {\n const resolved = amp.getResolvedSelector();\n if (resolved && !(resolved instanceof Nil)) {\n return resolved as Selector;\n }\n }\n return node;\n }\n if (isNode(node, N.SelectorList)) {\n const list = node as SelectorList;\n return SelectorList.create(list.get('value').map(item => materialize(item as Selector))).inherit(node) as Selector;\n }\n if (isNode(node, N.ComplexSelector)) {\n const complex = node as ComplexSelector;\n const parts: ComplexSelectorComponent[] = [];\n for (const part of complex.get('value')) {\n if (isNode(part, N.Ampersand)) {\n const amp = part as Ampersand;\n const n = amp as unknown as Node;\n if (n.hasFlag(F_IMPLICIT_AMPERSAND)) {\n const resolved = amp.getResolvedSelector();\n if (resolved && !(resolved instanceof Nil)) {\n const repl = materialize(resolved as Selector);\n if (isNode(repl, N.ComplexSelector)) {\n parts.push(...(repl as ComplexSelector).get('value') as ComplexSelectorComponent[]);\n } else {\n parts.push(repl as ComplexSelectorComponent);\n }\n continue;\n }\n }\n }\n parts.push(materialize(part as Selector) as ComplexSelectorComponent);\n }\n return ComplexSelector.create(parts).inherit(node) as Selector;\n }\n const arr = 'value' in node ? node.value : undefined;\n if (Array.isArray(arr)) {\n const cloned = node.copy(true) as Selector & { value?: Selector[] };\n cloned.value = arr.map(item => materialize(item as Selector));\n return cloned as Selector;\n }\n return node;\n };\n const materialized = materialize(sel as Selector);\n return processLeadingIs(materialized) as Selector;\n }\n\n static isBareAmpersandSelector(sel: Selector | Nil): boolean {\n if (!sel || sel instanceof Nil) {\n return false;\n }\n if (isNode(sel, N.Ampersand)) {\n return (sel as Ampersand).isPlainAmpersand();\n }\n if (isNode(sel, N.CompoundSelector | N.ComplexSelector)) {\n const items = (sel as unknown as { value?: unknown[] }).value;\n if (!Array.isArray(items)) {\n return false;\n }\n return items.length === 1\n && isNode(items[0] as Node, N.Ampersand)\n && (items[0] as Ampersand).isPlainAmpersand();\n }\n if (isNode(sel, N.SelectorList)) {\n return (sel as SelectorList).get('value').every(\n item => isNode(item, N.Ampersand) && (item as Ampersand).isPlainAmpersand()\n );\n }\n return false;\n }\n\n private static hasReferenceBoundaryParent(node: Node, context?: Context): boolean {\n const parent = getCurrentParentNode(node, context);\n return Boolean(\n parent\n && isNode(parent, N.Rules)\n && (parent as Rules).options?.referenceMode === true\n );\n }\n\n static hasExtendedTopLevelSelector(sel: Selector | Nil): boolean {\n return hasExtendedSelector(sel);\n }\n\n private static filterSelectorItems(\n sel: Selector,\n shouldKeep: (item: Selector) => boolean\n ): Selector | Nil {\n if (!isNode(sel, N.SelectorList)) {\n return shouldKeep(sel) ? sel : new Nil();\n }\n const seen = new Set<string>();\n const kept: Selector[] = [];\n for (const item of (sel as SelectorList).get('value')) {\n if (!shouldKeep(item)) {\n continue;\n }\n const key = item.valueOf();\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n kept.push(item as Selector);\n }\n if (kept.length === 0) {\n return new Nil();\n }\n if (kept.length === 1) {\n return kept[0]!;\n }\n return SelectorList.create(kept).inherit(sel);\n }\n\n private static filterExtendedTopLevelSelectorItems(sel: Selector, context?: Context): Selector | Nil {\n return Ruleset.filterSelectorItems(sel, item =>\n (context ? item._hasFlag(F_EXTENDED, context) : item.hasFlag(F_EXTENDED))\n && !(context ? item._hasFlag(F_EXTEND_TARGET, context) : item.hasFlag(F_EXTEND_TARGET))\n );\n }\n\n private static filterReferenceVisibleSelectorItems(\n current: Selector,\n original?: Selector | Nil,\n context?: Context\n ): Selector | Nil {\n if (!original || original instanceof Nil) {\n return Ruleset.filterExtendedTopLevelSelectorItems(current, context);\n }\n const originalValues = new Set<string>();\n if (isNode(original, N.SelectorList)) {\n for (const item of (original as SelectorList).get('value')) {\n originalValues.add(item.valueOf());\n }\n } else {\n originalValues.add(original.valueOf());\n }\n const changedItems = Ruleset.filterSelectorItems(current, item =>\n !originalValues.has(item.valueOf())\n );\n if (!(changedItems instanceof Nil)) {\n return changedItems;\n }\n return Ruleset.filterSelectorItems(current, item =>\n (context ? item._hasFlag(F_EXTENDED, context) : item.hasFlag(F_EXTENDED))\n && !(context ? item._hasFlag(F_EXTEND_TARGET, context) : item.hasFlag(F_EXTEND_TARGET))\n );\n }\n\n getHeaderString(options: FinalPrintOptions, withoutComments?: boolean): string {\n const w = options.writer;\n const renderKey = this.renderKey !== CANONICAL\n ? this.renderKey\n : this._resolveRenderKey(options.context);\n const selector = this.getRenderableSelector(\n options.collapseNesting,\n options.context ? { ...options.context, renderKey } : options.context\n );\n const idt = indent(options.depth);\n\n // Should never be called for Nil selectors (serializeRulesContainer guards this),\n // but keep it safe for TypeScript and invariants.\n if (selector instanceof Nil) {\n return '';\n }\n if (withoutComments) {\n options = { ...options, suppressComments: true };\n }\n let renderSelector: Selector | Nil = selector;\n const ownSelector = this.getOwnSelector();\n const currentSelector = this.getSelector(renderKey);\n if (\n this.hoistToRoot\n && Ruleset.isBareAmpersandSelector(renderSelector)\n && ownSelector\n && !(ownSelector instanceof Nil)\n && Ruleset.isBareAmpersandSelector(ownSelector)\n && !Ruleset.isBareAmpersandSelector(currentSelector)\n ) {\n renderSelector = currentSelector;\n }\n if (this.hoistToRoot && options.depth === 0 && !(renderSelector instanceof Nil)) {\n renderSelector = Ruleset.materializeHoistedImplicitAmpersands(renderSelector as Selector) as typeof selector;\n }\n if (\n options.referenceMode === true\n && options.referenceRenderEnabled === true\n && !(renderSelector instanceof Nil)\n ) {\n const filteredReferenceSelector = Ruleset.filterReferenceVisibleSelectorItems(\n renderSelector as Selector,\n this.getSelectorBeforeExtend(renderKey),\n options.context\n ) as typeof renderSelector;\n const rulesetExtended = options.context\n ? this._hasFlag(F_EXTENDED, options.context)\n : this.hasFlag(F_EXTENDED);\n if (!(filteredReferenceSelector instanceof Nil)) {\n renderSelector = filteredReferenceSelector;\n } else if (!rulesetExtended) {\n return '';\n }\n }\n const prevReferenceFilterTargets = options.referenceFilterTargets === true;\n const disableTargetFilteringForTopLevelList = (\n (options.context ? this._hasFlag(F_EXTENDED, options.context) : this.hasFlag(F_EXTENDED))\n && !(renderSelector instanceof Nil)\n && isNode(renderSelector as Selector, N.SelectorList)\n );\n options.referenceFilterTargets = (\n options.referenceMode === true\n && options.referenceRenderEnabled === true\n && !disableTargetFilteringForTopLevelList\n );\n Ruleset.ensureSelectorVisible(renderSelector);\n const ctx = options.context;\n const previousRenderKey = ctx?.renderKey;\n if (ctx && renderKey !== undefined) {\n ctx.renderKey = renderKey;\n }\n const selOut = w.capture(() => renderSelector.toString(options));\n if (ctx) {\n ctx.renderKey = previousRenderKey;\n }\n options.referenceFilterTargets = prevReferenceFilterTargets;\n return normalizeIndent(selOut.replace(/\\s+$/, '') + ' {', idt) + '\\n';\n }\n\n override preEval(context: Context): MaybePromise<this> {\n if (!this.preEvaluated) {\n const node = this.clone(false, undefined, context);\n node.preEvaluated = true;\n const renderKey = node._resolveRenderKey(context);\n const selectorText = String(this.getSelector(renderKey)?.valueOf?.() ?? '');\n if (process.env.JESS_DEBUG_LOCK === 'throw-pre-ruleset' && selectorText.includes('.call-inner-lock-mixin')) {\n throw new Error(`[lock-pre-ruleset] ${JSON.stringify({\n selectorText,\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n renderKey: String(renderKey)\n })}`);\n }\n // Index should already be assigned by parent Rules\n node.sourceNode ??= this;\n const rulesetOptions = node.options;\n let rules = node.enterRules(context);\n // On re-eval (e.g. mixin clone), use the pre-composition ownSelector so we\n // compose from the authored selector, not the already-composed one.\n let selector: Selector | Nil = rulesetOptions.ownSelector ?? node.getSelector(renderKey);\n // Generated wrapper rulesets (e.g. implicit `& { ... }` created by AtRule hoisting)\n // should not force var visibility to `private`, otherwise sibling vars inside the wrapper\n // (like Less `@base`) become inaccessible.\n if (!rulesetOptions.generated) {\n if (rules.renderKey === CANONICAL) {\n const wrappedRules = rules.createShallowBodyWrapper(context);\n node.rules = wrappedRules;\n node.adopt(wrappedRules, context);\n rules = wrappedRules;\n }\n const nextRulesOptions = {\n ...rules.options,\n rulesVisibility: {\n ...rules.options.rulesVisibility\n }\n };\n if (context.leakyRules) {\n nextRulesOptions.rulesVisibility.Mixin = 'public';\n nextRulesOptions.rulesVisibility.VarDeclaration = 'optional';\n } else {\n nextRulesOptions.rulesVisibility.Mixin = 'private';\n nextRulesOptions.rulesVisibility.VarDeclaration = 'private';\n }\n rules.options = nextRulesOptions;\n }\n const parentRuleset = context.rulesetFrames.at(-1);\n const parentSelector = parentRuleset?.getSelector(parentRuleset._resolveRenderKey(context));\n // Store own selector before parent resolution so extend can extend .replace,.c not the resolved form.\n node.setOwnSelector(selector);\n if (\n !node.options.resolvedHoistWrapper\n && parentSelector\n && !(parentSelector instanceof Nil)\n && !(selector instanceof Nil)\n && parentRuleset\n ) {\n const collapseForComposition = Boolean(\n context.opts.collapseNesting\n && !selectorHasAuthoredAmpersand(selector as Selector)\n );\n selector = getImplicitSelectorUtil(\n selector as Selector,\n parentSelector as Selector,\n collapseForComposition\n );\n {\n const selectorSourceNode = node === this\n ? selector.clone(false, undefined, context)\n : selector;\n if (selector instanceof Node) {\n selector.sourceNode = selectorSourceNode;\n }\n }\n }\n // DO NOT evaluate guard here - guards are evaluated at call time in getFunctionFromMixins\n // Just evaluate the selector\n const ownSelector = node.getOwnSelector();\n return pipe(\n () => selector.eval(context),\n (sel) => {\n // If ownSelector has non-static children (e.g. interpolated attr values),\n // evaluate it so extend matching uses the resolved form.\n // Evaluate with collapseNesting=false so Ampersand nodes stay lazy\n // (pointing at their parent container) rather than expanding into\n // :is(parent). The combined selector was already correctly composed\n // by getImplicitSelectorUtil; expanding & here corrupts the relative\n // form and causes getEffectiveSelector to prepend the parent twice.\n if (\n ownSelector\n && !isNode(ownSelector, N.Nil)\n && ownSelector !== selector\n ) {\n const savedCollapseNesting = context.opts.collapseNesting;\n context.opts.collapseNesting = false;\n return pipe(\n () => ownSelector.eval(context),\n (evaledOwn) => {\n context.opts.collapseNesting = savedCollapseNesting;\n node.setOwnSelector(evaledOwn as Selector);\n return sel;\n }\n );\n }\n return sel;\n },\n (sel) => {\n if (isNode(sel as Node, N.Selector)) {\n sel = processLeadingIs(sel as Selector) as Selector | Nil;\n }\n // If this ruleset shares its value with a descendant ruleset, give descendants\n // their own value before we overwrite value.selector so they keep their selector.\n Ruleset.ensureDescendantRulesetsHaveOwnValue(node as Ruleset, {} as RulesetValue);\n // Store the evaluated selector - this is what will be in the frame\n node.selector = sel as Selector | Nil;\n if (sel instanceof Node) {\n node.adopt(sel, context);\n }\n if (sel.hoistToRoot) {\n node.hoistToRoot = true;\n }\n // Register to extend root's registry for extend lookups\n const extendRoot = context.extendRoots.getCurrentExtendRoot();\n if (extendRoot) {\n extendRoot.register('ruleset', node as Ruleset);\n // Keep a per-root registry list for visibility processing\n context.extendRoots.registerRuleset(extendRoot, node as Ruleset);\n }\n // Depth-first: preEval child rules immediately so all nested rulesets/extends\n // are registered in source order before we process extends.\n // Push this ruleset to the frame so nested rulesets get the correct parent selector\n // when building implicit selectors (e.g. .header-nav inside .header → .header .header-nav).\n const childRules = node.enterRules(context);\n if (childRules && !(childRules as unknown as Ruleset).preEvaluated) {\n context.rulesetFrames.push(node as Ruleset);\n if (extendRoot) {\n context.extendRoots.registerRoot(childRules, extendRoot);\n }\n const preEvaldRules = childRules.preEval(context);\n if (isThenable(preEvaldRules)) {\n return (preEvaldRules as Promise<Rules>).then((rules) => {\n context.rulesetFrames.pop();\n node.rules = rules;\n node.adopt(rules, context);\n if (extendRoot && rules !== childRules) {\n context.extendRoots.registerRoot(rules, extendRoot);\n }\n return node;\n });\n }\n context.rulesetFrames.pop();\n node._assignRules(preEvaldRules as Rules, context);\n if (extendRoot && preEvaldRules !== childRules) {\n context.extendRoots.registerRoot(preEvaldRules as Rules, extendRoot);\n }\n }\n return node;\n }\n );\n }\n return this;\n }\n\n /** Attach an (invisible) ampersand to the selector(s) if it's not already there */\n getImplicitSelector(parentSelector: Selector, collapseNesting = false) {\n const selector = this.get('selector');\n if (selector instanceof Nil) {\n return selector;\n }\n return getImplicitSelectorUtil(selector, parentSelector, collapseNesting);\n }\n\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const priorSelectorParent = !deep && this.selector instanceof Node\n ? this.selector.parent\n : undefined;\n const priorRulesParent = !deep && this.rules instanceof Node\n ? this.rules.parent\n : undefined;\n const cloned = super.clone(deep, cloneFn, ctx) as this;\n if (!deep) {\n if (this.selector instanceof Node) {\n (this.selector as unknown as { parent?: Node }).parent = priorSelectorParent;\n }\n if (this.rules instanceof Node) {\n (this.rules as unknown as { parent?: Node }).parent = priorRulesParent;\n }\n const renderKey = ctx ? cloned._resolveRenderKey(ctx) : this.renderKey;\n const selector = cloned.getSelector(renderKey);\n if (selector instanceof Node) {\n if (ctx || this !== this.sourceNode) {\n cloned.selector = selector.clone(false, undefined, ctx) as Selector | Nil;\n cloned.adopt(cloned.selector, ctx);\n }\n }\n const currentRules = this.getRules(renderKey);\n if (ctx && currentRules !== this.rules) {\n cloned.rules = currentRules;\n cloned.adopt(currentRules, ctx);\n }\n if (this !== this.sourceNode && cloned.rules === this.rules) {\n const rules = ctx ? cloned.enterRules(ctx) : cloned.rules;\n cloned.rules = rules.createShallowBodyWrapper(ctx);\n cloned.adopt(cloned.rules, ctx);\n }\n }\n if (!deep && ctx && this !== this.sourceNode && cloned.rules !== this.rules && cloned.rules.parent !== cloned) {\n cloned.adopt(cloned.rules, ctx);\n }\n return cloned;\n }\n\n override copy(deep?: boolean): this {\n const node = super.copy(deep);\n const selectorSource = this.getOwnSelector() ?? this.selector;\n node.selector = selectorSource.sourceNode.copy(true) as Selector | Nil;\n node.adopt(node.selector);\n return node;\n }\n\n override evalNode(context: Context): MaybePromise<Ruleset | Rules | Nil> {\n if (this.evaluated) {\n return this;\n }\n let pushedFrames = false;\n const renderKey = this._resolveRenderKey(context);\n const previousRenderKey = context.renderKey;\n if (renderKey !== undefined && renderKey !== CANONICAL) {\n context.renderKey = renderKey;\n }\n /** Should have been maybe cloned in preEval */\n this.evaluated = true;\n const collapseNesting = context.opts.collapseNesting;\n\n // Store frames snapshot for collapseNesting serialization\n if (collapseNesting) {\n this.frames = [...context.frames];\n }\n\n const out = pipe(\n () => {\n const selectorText = String(this.getSelector(renderKey)?.valueOf?.() ?? '');\n if (process.env.JESS_DEBUG_LOCK === 'throw-ruleset' && selectorText.includes('.call-inner-lock-mixin')) {\n throw new Error(`[lock-ruleset] ${JSON.stringify({\n selectorText,\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n renderKey: String(renderKey),\n childCount: this.enterRules(context).get('value', context).length\n })}`);\n }\n if (\n selectorText.includes('.call-lock-mixin')\n || selectorText.includes('#guarded-caller')\n || selectorText.includes('#guarded-deeper')\n ) {\n }\n let guard = this.getGuard(renderKey);\n // Guard was already set to Nil (failed in a previous eval)\n if (guard instanceof Nil) {\n return guard;\n }\n // Evaluate guard at definition time (not call time like mixins)\n // This is different from mixins because rulesets can't use caller scope for guards\n if (guard) {\n return pipe(\n () => guard.eval(context),\n (guardResult) => {\n const selectorText = String(this.getSelector(renderKey)?.valueOf?.() ?? '');\n const guardPasses = Boolean(guardResult instanceof Bool && guardResult.value === true);\n if (selectorText.includes('#guarded') || selectorText.includes('#top') || selectorText.includes('#deeper')) {\n }\n if (!guardPasses) {\n // Guard failed - mark as Nil and return it\n this.guard = new Nil() as Condition | Nil;\n return new Nil();\n }\n // Guard passed - clear it and continue with selector evaluation\n this.guard = undefined as Condition | Nil | undefined;\n return undefined;\n }\n );\n }\n return undefined;\n },\n (guardResult) => {\n // If guard failed, return Nil (ruleset produces no output)\n if (guardResult instanceof Nil) {\n return guardResult;\n }\n let selector = this.getSelector(renderKey);\n const frame = atIndex(context.rulesetFrames, -1);\n if (frame && (this.hoistToRoot ?? context.opts.collapseNesting)) {\n this.hoistToRoot = true;\n }\n\n if (selector instanceof Nil) {\n // If selector evaluates to Nil, return the rules body directly instead of the ruleset\n // This allows rules to be output even when there's no selector context\n // We don't push frames because there's no selector context\n // Store Nil in selector so next step can detect this case\n this.selector = selector as Selector | Nil;\n const evaluatedRules = this.enterRules(context).eval(context);\n // Update this.rules to point to evaluated Rules to prevent circular reference\n // when debug code traverses the AST\n if (isThenable(evaluatedRules)) {\n return (evaluatedRules as Promise<Rules>).then((rules) => {\n this._assignRules(rules, context);\n return rules;\n });\n }\n this._assignRules(evaluatedRules as Rules, context);\n return evaluatedRules;\n }\n // Preserve the sourceNode from the current selector before replacing it\n const preservedSourceNode = this._getSelectorSourceNode(this.getSelector(renderKey));\n this.selector = selector as Selector | Nil;\n this.adopt(this.selector, context);\n // Restore the sourceNode on the new selector so it's available when copying\n const currentSelector = this.getSelector(renderKey);\n if (preservedSourceNode && currentSelector) {\n {\n const selectorForSourceNode = currentSelector;\n if (selectorForSourceNode instanceof Node && preservedSourceNode) {\n selectorForSourceNode.sourceNode = preservedSourceNode;\n }\n }\n }\n if (context.opts.collapseNesting) {\n this.hoistToRoot = true;\n }\n context.rulesetFrames.push(this as Ruleset);\n context.frames.push(this);\n pushedFrames = true;\n return this.enterRules(context).eval(context);\n },\n (evaluatedRules: Rules | Nil) => {\n if (pushedFrames) {\n context.rulesetFrames.pop();\n context.frames.pop();\n }\n if (evaluatedRules instanceof Nil) {\n return evaluatedRules;\n }\n\n // If selector was Nil, evaluatedRules is already Rules (not wrapped in Ruleset)\n // In that case, return it directly without wrapping back in Ruleset\n if (this.getSelector(renderKey) instanceof Nil) {\n // Selector was Nil, so we already returned Rules directly - just return it\n return evaluatedRules;\n }\n\n this._assignRules(evaluatedRules as Rules, context);\n const rules = this.enterRules(context);\n if (rules.visibleRules(context).length === 0) {\n this._removeFlag(F_VISIBLE, context);\n }\n return this;\n }\n );\n\n if (isThenable(out)) {\n return (out as Promise<Ruleset | Rules | Nil>).then(\n (result) => {\n context.renderKey = previousRenderKey;\n return result;\n },\n (error) => {\n context.renderKey = previousRenderKey;\n throw error;\n }\n );\n }\n context.renderKey = previousRenderKey;\n return out;\n }\n\n /** @todo move to ToCssVisitor */\n // toCSS(context: Context, out: OutputCollector) {\n // const { sels, value } = this\n // context.inSelector = true\n // sels.toCSS(context, out)\n // context.inSelector = false\n // out.add(' ')\n // value.toCSS(context, out)\n // }\n\n /** @todo Move to ToModuleVisitor */\n // toModule(context: Context, out: OutputCollector) {\n // out.add('$J.rule({\\n', this.location)\n // context.indent++\n // const pre = context.pre\n // out.add(`${pre}sels: `)\n // this.sels.toModule(context, out)\n // out.add(`,\\n${pre}value: `)\n // this.data.toModule(context, out)\n // context.indent--\n // out.add(`},${JSON.stringify(this.location)})`)\n // }\n}\n\ntype RulesetParams = ConstructorParameters<typeof Ruleset>;\n\nexport const ruleset = defineType<RulesetValue>(Ruleset, 'Ruleset') as (\n value: RulesetValue | RulesetParams[0],\n options?: RulesetParams[1],\n location?: RulesetParams[2],\n treeContext?: RulesetParams[3]\n) => Ruleset;\n","/** Regex constants to re-use */\nexport const LIST_ITEM_TRIM = /^\\s+|\\s+$/g;\n","import { type Context } from '../context.js';\nimport { CANONICAL, defineType, F_MAY_ASYNC, Node, type NodeEdge, type RenderKey } from './node.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { compareNodeArray } from './util/compare.js';\nimport { type Operator } from './util/calculate.js';\nimport { LIST_ITEM_TRIM } from './util/regex.js';\nimport { addEdgeAt, addParentEdge, removeParentEdge } from './util/cursor.js';\nimport { isThenable, serialForEach, type MaybePromise } from '@jesscss/awaitable-pipe';\nimport { canReuseEvalState } from './node-base.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\n\nexport type ListOptions = {\n /**\n * Lists can be separated by comma, semi-colon,\n * or slash, depending on the type of list.\n *\n * @todo - Is there a more CSS-y way to define this?\n */\n sep?: ',' | ';' | '/';\n};\n\nexport type ListChildData<T extends Node = Node> = { value: T[] };\n\nexport interface List<T extends Node = Node> extends Node<T[], ListOptions, ListChildData<T>> {\n type: 'List';\n shortType: 'list';\n eval(context: Context): Promise<this>;\n}\n\nexport function getListItem<T extends Node | NodeEdge<Node>>(list: T[], index: number, renderKey?: RenderKey) {\n if (renderKey === undefined) {\n return list[index];\n }\n return list instanceof Map\n ? list.get(renderKey)?.[index] ?? list[index]\n : list[index];\n}\n/**\n * A list of expressions\n *\n * i.e. one, two, three\n * or .sel, #id.class, [attr]\n * or one / two / three\n */\nexport class List<T extends Node = Node> extends Node<T[], ListOptions, ListChildData<T>> {\n static override childKeys = ['value'] as const;\n\n value: T[];\n valueEdges?: Array<NodeEdge<T> | undefined>;\n\n getValue(renderKey?: RenderKey) {\n if (renderKey === undefined || !this.valueEdges) {\n return this.value;\n }\n let resolved: T[] | undefined;\n for (let i = 0; i < this.value.length; i++) {\n const alternate = this.valueEdges[i]?.get(renderKey);\n if (alternate !== undefined) {\n (resolved ??= [...this.value])[i] = alternate;\n }\n }\n return resolved ?? this.value;\n }\n\n getValueAt(index: number, renderKey?: RenderKey) {\n return renderKey !== undefined\n ? this.valueEdges?.[index]?.get(renderKey) ?? this.value[index]\n : this.value[index];\n }\n\n at(index: number, context?: Context) {\n const renderKey = context?.renderKey ?? this.renderKey;\n return this.getValueAt(index, renderKey);\n }\n\n private _replaceValueAt(index: number, node: T, renderKey: RenderKey): void {\n const previous = this.getValueAt(index, renderKey);\n if (previous === node) {\n return;\n }\n if (previous && previous !== node) {\n removeParentEdge(previous, renderKey);\n }\n addEdgeAt(this, 'value', index, renderKey, node);\n addParentEdge(node, renderKey, this);\n }\n\n constructor(value: T[], options?: ListOptions, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.value = value;\n for (const child of value) {\n if (child instanceof Node) {\n this.adopt(child);\n }\n }\n }\n\n // NOTE: `length` intentionally remains canonical for now.\n // Unlike render/eval surfaces, it has no Context channel, so making it\n // state-aware would require a broader API change rather than a node-local patch.\n get length() {\n return this.value.length;\n }\n\n // NOTE: iteration intentionally remains canonical for now for the same reason as\n // `length`: there is no explicit Context channel on the iterator protocol.\n * [Symbol.iterator]() {\n yield* this.value.entries();\n }\n\n private _valueOf: string | undefined;\n\n // NOTE: `valueOf()` intentionally remains canonical for now.\n // It is a cached observer on the canonical list instance, and it has no\n // Context parameter. Making it state-aware here would make the cache\n // ambiguous across concurrent sessions that see different patched `value`s.\n override valueOf() {\n return (this._valueOf ??= this.value.map(v => v.valueOf()).join(';'));\n }\n\n override toTrimmedString(options?: PrintOptions, renderKey?: RenderKey) {\n options = getPrintOptions(options);\n const w = options.writer!;\n let { sep = ',' } = this.options ?? {};\n const activeRenderKey = renderKey ?? options.context?.renderKey ?? this.renderKey;\n let value = this.getValue(activeRenderKey);\n let length = value.length;\n const mark = w.mark();\n if (value.length === 0) {\n return '';\n }\n // Print first item as-is\n let item = getListItem(value, 0, renderKey);\n let out = w.capture(() => item.toString(options));\n w.add(out.replace(LIST_ITEM_TRIM, ''), item);\n // Subsequent items: emit sep; capture next item to decide spacing precisely\n for (let i = 1; i < length; i++) {\n item = value[i]!;\n const rawOut = w.capture(() => item.toString(options));\n const startsOnNextLine = /^[ \\t\\r\\f]*\\n/.test(rawOut);\n const preserveSimpleMultilineCommaList = (\n sep === ','\n && startsOnNextLine\n && value.every(entry => isNode(entry, N.Any | N.Quoted | N.Sequence))\n );\n if (sep === '/') {\n w.add(' / ');\n out = rawOut.replace(LIST_ITEM_TRIM, '');\n } else if (preserveSimpleMultilineCommaList) {\n w.add(sep);\n out = rawOut.replace(/\\s+$/g, '');\n } else {\n w.add(`${sep} `);\n out = rawOut.replace(LIST_ITEM_TRIM, '');\n }\n w.add(out);\n }\n return w.getSince(mark);\n }\n\n override compare(other: Node) {\n // NOTE: `compare()` intentionally remains canonical for now.\n if (other instanceof List) {\n const equalityMode = this.treeContext?.equalityMode ?? 'coerce';\n const result = compareNodeArray([...this.value], [...other.value], equalityMode);\n return result;\n }\n if (other.type === 'Any') {\n const normalize = (s: string) => s.replace(/;\\s*/g, ', ').replace(/\\s+/g, ' ').trim();\n const left = normalize(this.toString());\n const right = normalize(other.toString());\n return left === right ? 0 : undefined;\n }\n return undefined;\n }\n\n override operate(b: Node, op: Operator, context: Context): List<T> {\n if (op !== '+') {\n throw new Error(`List operation \"${op}\" not supported`);\n }\n const ownItems = this.getValue(context.renderKey);\n const nextItems = b instanceof List ? b.getValue(context.renderKey) : [b as T];\n let newList = this.clone();\n const nextValue = [...ownItems, ...nextItems];\n newList.value = nextValue;\n\n return newList;\n }\n\n override preEval(context: Context): MaybePromise<Node> {\n const reusableState = canReuseEvalState(this, context);\n if (this.preEvaluated && reusableState) {\n return this;\n }\n const renderKey = context.renderKey ?? this.renderKey;\n const isNonCanonical = renderKey !== undefined && renderKey !== CANONICAL;\n const value = this.getValue(renderKey);\n const nextValue = value.slice();\n\n if (!this.hasFlag(F_MAY_ASYNC)) {\n let changed = false;\n for (let i = 0; i < nextValue.length; i++) {\n const child = nextValue[i]!;\n const result = child.preEval(context) as T;\n if (result !== child) {\n nextValue[i] = result;\n changed = true;\n }\n }\n if (changed) {\n if (isNonCanonical) {\n for (let i = 0; i < nextValue.length; i++) {\n const child = nextValue[i]!;\n if (child !== value[i]) {\n this._replaceValueAt(i, child, renderKey);\n }\n }\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n } else {\n const node = this.clone();\n node.preEvaluated = true;\n node.value = nextValue;\n for (const child of nextValue) {\n node.adopt(child);\n }\n return node;\n }\n }\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n }\n\n let changed = false;\n const out = serialForEach(nextValue, (child, i) => {\n const result = child.preEval(context);\n if (isThenable(result)) {\n return (result as Promise<T>).then((resolved) => {\n if (resolved !== child) {\n nextValue[i] = resolved;\n changed = true;\n }\n });\n }\n if (result !== child) {\n nextValue[i] = result as T;\n changed = true;\n }\n });\n if (isThenable(out)) {\n return (out as Promise<void>).then(() => {\n if (changed) {\n if (isNonCanonical) {\n for (let i = 0; i < nextValue.length; i++) {\n const child = nextValue[i]!;\n if (child !== value[i]) {\n this._replaceValueAt(i, child, renderKey);\n }\n }\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n } else {\n const node = this.clone();\n node.preEvaluated = true;\n node.value = nextValue;\n for (const child of nextValue) {\n node.adopt(child);\n }\n return node;\n }\n }\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n });\n }\n if (changed) {\n if (isNonCanonical) {\n for (let i = 0; i < nextValue.length; i++) {\n const child = nextValue[i]!;\n if (child !== value[i]) {\n this._replaceValueAt(i, child, renderKey);\n }\n }\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n } else {\n const node = this.clone();\n node.preEvaluated = true;\n node.value = nextValue;\n for (const child of nextValue) {\n node.adopt(child);\n }\n return node;\n }\n }\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n }\n\n protected override evalNode(context: Context): MaybePromise<Node> {\n const renderKey = context.renderKey ?? this.renderKey;\n const isNonCanonical = renderKey !== undefined && renderKey !== CANONICAL;\n const value = this.getValue(renderKey);\n const nextValue = value.slice();\n\n if (!this.hasFlag(F_MAY_ASYNC)) {\n let changed = false;\n for (let i = 0; i < nextValue.length; i++) {\n const child = nextValue[i]!;\n const result = child.eval(context) as T;\n if (result !== child) {\n nextValue[i] = result;\n changed = true;\n }\n }\n if (changed) {\n if (isNonCanonical) {\n for (let i = 0; i < nextValue.length; i++) {\n const child = nextValue[i]!;\n if (child !== value[i]) {\n this._replaceValueAt(i, child, renderKey);\n }\n }\n return this;\n }\n const node = this.clone();\n node.value = nextValue;\n for (const child of nextValue) {\n node.adopt(child);\n }\n return node;\n }\n return this;\n }\n\n let changed = false;\n const out = serialForEach(nextValue, (child, i) => {\n const result = child.eval(context);\n if (isThenable(result)) {\n return (result as Promise<T>).then((resolved) => {\n if (resolved !== child) {\n nextValue[i] = resolved;\n changed = true;\n }\n });\n }\n if (result !== child) {\n nextValue[i] = result as T;\n changed = true;\n }\n });\n if (isThenable(out)) {\n return (out as Promise<void>).then(() => {\n if (changed) {\n if (isNonCanonical) {\n for (let i = 0; i < nextValue.length; i++) {\n const child = nextValue[i]!;\n if (child !== value[i]) {\n this._replaceValueAt(i, child, renderKey);\n }\n }\n return this;\n }\n const node = this.clone();\n node.value = nextValue;\n for (const child of nextValue) {\n node.adopt(child);\n }\n return node;\n }\n return this;\n });\n }\n if (changed) {\n if (isNonCanonical) {\n for (let i = 0; i < nextValue.length; i++) {\n const child = nextValue[i]!;\n if (child !== value[i]) {\n this._replaceValueAt(i, child, renderKey);\n }\n }\n return this;\n }\n const node = this.clone();\n node.value = nextValue;\n for (const child of nextValue) {\n node.adopt(child);\n }\n return node;\n }\n return this;\n }\n}\n\ntype Params = ConstructorParameters<typeof List>;\n\nexport const list = defineType(List, 'List') as (\n value: Params[0],\n options?: Params[1],\n location?: Params[2],\n treeContext?: Params[3]\n) => List;\n","import { CANONICAL, Node, F_STATIC, defineType, type NodeEdge, type RenderKey } from './node.js';\nimport { canReuseEvalState } from './node-base.js';\nimport { Nil } from './nil.js';\nimport { List } from './list.js';\nimport type { Context } from '../context.js';\nimport { compare, compareNodeArray } from './util/compare.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { type MaybePromise, pipe, isThenable, serialForEach } from '@jesscss/awaitable-pipe';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { setParent } from './util/field-helpers.js';\nimport { addEdgeAt, addParentEdge, removeParentEdge } from './util/cursor.js';\n\nexport type SequenceOptions = {\n /**\n * CSS values are typically spaced,\n * because of how they're parsed.\n */\n // spaced: boolean\n /** Used with custom properties */\n preserveWhitespace?: boolean;\n /** Serialize children as a spaced value list without mutating child `pre` fields. */\n forceSpacing?: boolean;\n};\n\n/**\n * A continuous collection of nodes. Historically in Less,\n * these were termed \"expressions\", but in computer science,\n * an expression will yield a value, and a CSS value can\n * actually be a sequence of values (like for shorthand)\n */\nexport interface Sequence extends Node<Node[], SequenceOptions, SequenceChildData> {\n type: 'Sequence' | 'QueryCondition';\n shortType: 'seq' | 'query';\n}\nexport type SequenceChildData = { value: Node[] };\n\nexport class Sequence extends Node<Node[], SequenceOptions, SequenceChildData> {\n static override childKeys = ['value'] as const;\n\n value!: Node[];\n valueEdges?: Array<NodeEdge<Node> | undefined>;\n\n constructor(value: Node[], options?: SequenceOptions, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.value = value;\n for (const child of value) {\n if (child instanceof Node) {\n this.adopt(child);\n }\n }\n }\n\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const value = this.getValue(ctx?.renderKey ?? this.renderKey);\n const cloneChild = cloneFn ?? ((n: Node) => n.clone(deep, cloneFn, ctx));\n const clonedValue = deep\n ? value.map(child => cloneChild(child))\n : [...value];\n const options = this._meta?.options;\n const newNode: this = Reflect.construct(this.constructor, [\n [],\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n ]);\n newNode.value = clonedValue;\n if (ctx) {\n for (const child of clonedValue) {\n setParent(child, newNode, ctx);\n }\n } else {\n for (const child of clonedValue) {\n newNode.adopt(child);\n }\n }\n newNode.inherit(this);\n return newNode;\n }\n\n get length() {\n return this.value.length;\n }\n\n getValue(renderKey?: RenderKey) {\n if (renderKey === undefined || !this.valueEdges) {\n return this.value;\n }\n let resolved: Node[] | undefined;\n for (let i = 0; i < this.value.length; i++) {\n const alternate = this.valueEdges[i]?.get(renderKey);\n if (alternate !== undefined) {\n (resolved ??= [...this.value])[i] = alternate;\n }\n }\n return resolved ?? this.value;\n }\n\n getValueAt(index: number, renderKey?: RenderKey) {\n return renderKey !== undefined\n ? this.valueEdges?.[index]?.get(renderKey) ?? this.value[index]\n : this.value[index];\n }\n\n private _replaceValueAt(index: number, node: Node, renderKey: RenderKey): void {\n const previous = this.getValueAt(index, renderKey);\n if (previous === node) {\n return;\n }\n if (previous && previous !== node) {\n removeParentEdge(previous, renderKey);\n }\n addEdgeAt(this, 'value', index, renderKey, node);\n addParentEdge(node, renderKey, this);\n }\n\n private _cloneWithValue(value: Node[]): this {\n const node = this.clone();\n node.value = value;\n for (const child of value) {\n if (child instanceof Node) {\n node.adopt(child);\n }\n }\n return node;\n }\n\n // NOTE: `length` intentionally remains canonical for now. A state-aware\n // getter would need an explicit Context channel; otherwise the same node\n // instance would have ambiguous answers when different sessions patch\n // `value` to different lengths at the same time.\n\n override compare(other: Node, context?: Context) {\n if (other instanceof Sequence) {\n const equalityMode = this.treeContext?.equalityMode ?? 'coerce';\n const renderKey = context?.renderKey;\n const left = this.getValue(renderKey);\n const right = other.getValue(renderKey);\n const result = !context\n ? compareNodeArray(left, right, equalityMode)\n : compareSequenceItems(left, right, equalityMode, context);\n return result;\n }\n if (other.type === 'Any') {\n const normalize = (s: string) => s.replace(/\\s+/g, ' ').trim();\n const left = normalize(this.toTrimmedString(context ? { context } : undefined));\n const right = normalize(other.toString());\n return left === right ? 0 : undefined;\n }\n return undefined;\n }\n\n /** @todo - This serialization seems overly complex */\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n if (options?.inCustom) {\n return super.toTrimmedString(options);\n }\n const w = options.writer!;\n const mark = w.mark();\n const value = this.getValue(options.context?.renderKey ?? this.renderKey);\n const length = value.length;\n\n if (length === 0) {\n return '';\n }\n\n // Serialize first node with toString() to preserve comments\n const firstCaptured = w.captureWithMeta(() => value[0]!.toString(options));\n w.add(firstCaptured.text);\n let prevTrailingIntent = firstCaptured.trailingIntent;\n\n // Serialize subsequent nodes with normalized spacing\n for (let i = 1; i < length; i++) {\n const node = value[i]!;\n // For sequences, normalize spacing based on actual serialized output (including pre/post)\n // If direct child has explicit pre === 0, respect that (no space)\n if (node.pre === 0 && !this.options?.forceSpacing) {\n // Explicitly no space - respect that, but still use toString() to preserve comments\n node.toString(options);\n } else {\n // Check what's already written (previous node's output) to see if it ends with space\n const currentMark = w.mark();\n const writtenSoFar = w.getSince(mark);\n const prevEndsWithSpace = writtenSoFar.endsWith(' ');\n w.restore(currentMark);\n\n // Capture current node's output to check if it starts with space\n // This captures the serialized output including pre/post from child nodes\n const currentCaptured = w.captureWithMeta(() => node.toString(options));\n let currentNodeOut = currentCaptured.text;\n const isNegativeValue = isNode(node, N.Negative);\n if (\n isNegativeValue\n && !this.options?.preserveWhitespace\n && /^\\s+-/.test(currentNodeOut)\n ) {\n currentNodeOut = currentNodeOut.replace(/^\\s+/, '');\n }\n const currentStartsWithSpace = /^\\s/.test(currentNodeOut);\n const hasExplicitNoSpaceBoundary = (\n !this.options?.forceSpacing\n && (\n prevTrailingIntent === 'explicit_none'\n || currentCaptured.leadingIntent === 'explicit_none'\n )\n );\n\n if (!prevEndsWithSpace && !currentStartsWithSpace && !hasExplicitNoSpaceBoundary) {\n // No space present - add single space before node\n w.add(' ');\n }\n // Write the captured output (node was already serialized in capture())\n w.add(currentNodeOut);\n prevTrailingIntent = currentCaptured.trailingIntent;\n }\n }\n\n return w.getSince(mark);\n }\n\n override operate(b: Node, op: string, context: Context): Sequence | List {\n if (op !== '+') {\n throw new Error(`Sequence operation \"${op}\" not supported`);\n }\n let newSequence = this.clone();\n if (b instanceof List) {\n return new List([newSequence, ...b.getValue(context.renderKey)]).inherit(this);\n } else if (isNode(b, N.Sequence)) {\n /** Inference not working in this class? */\n const values = b.getValue(context.renderKey).map(v => v.clone());\n if (values.length) {\n values[0]!.pre = 1;\n }\n newSequence.value = [...newSequence.getValue(context.renderKey), ...values];\n for (const child of newSequence.value) {\n newSequence.adopt(child);\n }\n } else {\n b = b.clone();\n b.pre = 1;\n newSequence.value = [...newSequence.getValue(context.renderKey), b];\n for (const child of newSequence.value) {\n newSequence.adopt(child);\n }\n }\n return newSequence;\n }\n\n override preEval(context: Context): MaybePromise<Node> {\n const reusableState = canReuseEvalState(this, context);\n if (this.preEvaluated && reusableState) {\n return this;\n }\n const renderKey = context.renderKey ?? this.renderKey;\n const isNonCanonical = renderKey !== undefined && renderKey !== CANONICAL;\n const value = this.getValue(renderKey);\n const nextValue = [...value];\n\n if (!this.hasFlag(F_STATIC)) {\n const maybe = serialForEach(nextValue, (child, i) => {\n const result = child.preEval(context);\n if (isThenable(result)) {\n return (result as Promise<Node>).then((resolved) => {\n if (resolved !== child) {\n nextValue[i] = resolved;\n }\n });\n }\n if (result !== child) {\n nextValue[i] = result as Node;\n }\n });\n if (isThenable(maybe)) {\n return (maybe as Promise<void>).then(() => {\n if (isNonCanonical) {\n for (let i = 0; i < nextValue.length; i++) {\n if (nextValue[i] !== value[i]) {\n this._replaceValueAt(i, nextValue[i]!, renderKey);\n }\n }\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n }\n const changed = nextValue.some((child, i) => child !== value[i]);\n if (!changed) {\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n }\n const node = this._cloneWithValue(nextValue);\n node.preEvaluated = true;\n return node;\n });\n }\n if (isNonCanonical) {\n for (let i = 0; i < nextValue.length; i++) {\n if (nextValue[i] !== value[i]) {\n this._replaceValueAt(i, nextValue[i]!, renderKey);\n }\n }\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n }\n const changed = nextValue.some((child, i) => child !== value[i]);\n if (!changed) {\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n }\n const node = this._cloneWithValue(nextValue);\n node.preEvaluated = true;\n return node;\n }\n\n if (reusableState) {\n this.preEvaluated = true;\n }\n return this;\n }\n\n /**\n * During evaluation of sequences,\n * Jess may find values that are lists.\n *\n * In this case, we need to create a single\n * list that contains members of the expanded lists.\n *\n * @todo - If this is a selector sequence, and we've\n * evaluated an expression to an inner sequence,\n * then we should be inserting white-space combinators?\n *\n * @todo - REWRITE\n */\n override evalNode(context: Context): MaybePromise<Node> {\n if (this.hasFlag(F_STATIC)) {\n return this;\n }\n const renderKey = context.renderKey ?? this.renderKey;\n const isNonCanonical = renderKey !== undefined && renderKey !== CANONICAL;\n return pipe(\n () => {\n const nextValue = [...this.getValue(renderKey)];\n let changed = false;\n const maybe = serialForEach(nextValue.map((n, i) => [n, i] as const), ([n, i]) => {\n const out = n.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Node>).then((res) => {\n if (res !== n) {\n nextValue[i] = res;\n changed = true;\n }\n });\n }\n if ((out as Node) !== n) {\n nextValue[i] = out as Node;\n changed = true;\n }\n });\n if (isThenable(maybe)) {\n return (maybe as Promise<void>).then(() => {\n return { changed, nextValue };\n });\n }\n return { changed, nextValue };\n },\n ({ changed, nextValue }) => {\n const currentValue = this.getValue(renderKey);\n const value = nextValue.filter(n => n && !(n instanceof Nil));\n const shapeChanged = value.length !== currentValue.length;\n\n if (isNonCanonical && !shapeChanged) {\n if (changed) {\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== currentValue[i]) {\n this._replaceValueAt(i, value[i]!, renderKey);\n }\n }\n }\n return this;\n }\n\n if (value.length === 1 && !this.options?.preserveWhitespace) {\n return value[0]!;\n }\n if (!changed && !shapeChanged) {\n return this;\n }\n return this._cloneWithValue(value);\n }\n );\n }\n\n /** @todo move to visitors */\n // toCSS(context: Context, out: OutputCollector): void {\n // const cast = context.cast\n // this.value.forEach(n => {\n // const val = cast(n)\n // val.toCSS(context, out)\n // })\n // }\n\n // toModule(context: Context, out: OutputCollector) {\n // const loc = this.location\n // out.add('$J.expr([', loc)\n // const length = this.value.length - 1\n // this.value.forEach((n, i) => {\n // n.toModule(context, out)\n // if (i < length) {\n // out.add(', ')\n // }\n // })\n // out.add('])')\n // }\n}\n\nexport const seq = defineType(Sequence, 'Sequence', 'seq');\n\nexport const spaced = (\n value: Node[],\n options?: SequenceOptions\n) => {\n for (let i = 1; i < value.length; i++) {\n value[i]!.pre = 1;\n }\n return new Sequence(value, options);\n};\n\nfunction compareSequenceItems(\n left: Node[],\n right: Node[],\n equalityMode: 'coerce' | 'strict',\n context: Context\n): 0 | 1 | -1 | undefined {\n let output: 0 | 1 | -1 | undefined;\n\n if (left.length !== right.length) {\n return undefined;\n }\n\n for (let i = 0; i < left.length; i++) {\n const a = left[i]!;\n const b = right[i]!;\n const result = a instanceof Node && b instanceof Node\n ? a.compare(b, context)\n : compare(a, b, equalityMode);\n if (result === undefined) {\n return undefined;\n }\n if (output === undefined) {\n output = result;\n } else if (result !== output) {\n return undefined;\n }\n }\n return output;\n}\n","import { Node, defineType, type OptionalLocation, type TreeContext, type NodeOptions } from './node.js';\n\ntype Fn = (...args: any[]) => any;\n/**\n * A JS function.\n */\nexport interface JsFunction {\n type: 'JsFunction';\n shortType: 'jsfunc';\n}\nexport class JsFunction extends Node<Fn> {\n static override childKeys = null as null;\n\n value!: Fn;\n name?: string | undefined;\n\n constructor(\n value: { name: string; fn: Fn } | Fn,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n const fn = typeof value === 'function' ? value : value.fn;\n\n super(fn, options, location, treeContext);\n this.value = fn;\n this.name = typeof value === 'function' ? undefined : value.name;\n }\n}\n\nexport const jsfunc = defineType(JsFunction, 'JsFunction', 'jsfunc');","import type { Ruleset } from '../ruleset.js';\nimport type { Selector } from '../selector.js';\nimport type { Rules } from '../rules.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\nimport type { Mixin } from '../mixin.js';\nimport { Nil } from '../nil.js';\nimport { CALLER, CANONICAL, EVAL, Node } from '../node.js';\nimport { JsFunction } from '../js-function.js';\nimport type { Func } from '../function.js';\nimport type { Declaration } from '../declaration.js';\nimport type { Context } from '../../context.js';\nimport { atIndex } from './collections.js';\nimport { comparePosition } from './compare.js';\nimport { type BitSet, type BitSetLibrary, isSubsetOf } from './bitset.js';\nimport { getParent, setParent } from './field-helpers.js';\nimport { getCurrentParentNode } from './selector-utils.js';\n\nconst { isArray } = Array;\n\ntype SelectorKeySet = Set<string> | BitSet<string>;\ntype SelectorKeySource = SelectorKeySet | string[];\n\nconst NON_INDEXABLE_SELECTOR_KEYS = new Set(['', ' ', '>', '+', '~', '||']);\n\nfunction getNodeValueArray(node: Node): unknown[] | undefined {\n const value = Reflect.get(node, 'value');\n return Array.isArray(value) ? value : undefined;\n}\n\nfunction getSelectorKeySetLibrary(node: unknown): BitSetLibrary<string> | undefined {\n return typeof node === 'object' && node !== null\n ? Reflect.get(node, 'keySetLibrary')\n : undefined;\n}\n\nfunction setSelectorKeySetLibrary(node: unknown, library: BitSetLibrary<string>): void {\n if (typeof node === 'object' && node !== null) {\n Reflect.set(node, 'keySetLibrary', library);\n }\n}\n\nfunction isSelectorLikeNode(value: unknown): value is Selector {\n return value instanceof Node\n && typeof value === 'object'\n && 'isSelector' in value\n && value.isSelector === true;\n}\n\nfunction isSelectorLikeOrNil(value: unknown): value is Selector | Nil {\n return isSelectorLikeNode(value) || isNode(value, N.Nil);\n}\n\nfunction getRulesetSelector(ruleset: Ruleset, context?: Context): Selector | Nil | undefined {\n const selector = ruleset.get('selector', context);\n return isSelectorLikeOrNil(selector) ? selector : undefined;\n}\n\nfunction getMixinOwnSelector(mixin: Ruleset): Selector | Nil | undefined {\n const ownSelector = mixin.options.ownSelector;\n return isSelectorLikeOrNil(ownSelector) ? ownSelector : undefined;\n}\n\nfunction isIndexableSelectorKey(key: string): boolean {\n return !key.startsWith(':') && !NON_INDEXABLE_SELECTOR_KEYS.has(key);\n}\n\nfunction tryGetSelectorKeySet(\n selector: Selector | Nil | undefined,\n visible: boolean = true\n): SelectorKeySet | undefined {\n if (!selector || selector instanceof Nil) {\n return undefined;\n }\n try {\n return visible ? selector.visibleKeySet : selector.keySet;\n } catch {\n return undefined;\n }\n}\n\nfunction getSelectorKeyValues(keySet: SelectorKeySource | undefined): string[] {\n if (!keySet) {\n return [];\n }\n if (isArray(keySet)) {\n return keySet;\n }\n if (keySet instanceof Set) {\n return [...keySet];\n }\n return keySet._library?.valuesOf(keySet) ?? [];\n}\n\nfunction getFallbackSelectorIndexKeys(selector: Node | undefined): string[] {\n if (!selector) {\n return [];\n }\n const value = Reflect.get(selector, 'value');\n if (isArray(value)) {\n const keys: string[] = [];\n for (const child of value) {\n if (!(child instanceof Node)) {\n continue;\n }\n if (isNode(child, N.Combinator)) {\n continue;\n }\n keys.push(...getFallbackSelectorIndexKeys(child));\n }\n return keys;\n }\n const key = String(selector.valueOf?.() ?? '');\n return key && isIndexableSelectorKey(key) ? [key] : [];\n}\n\nfunction hasSelectorKey(keySet: SelectorKeySet | undefined, key: string): boolean {\n if (!keySet) {\n return false;\n }\n if (keySet instanceof Set) {\n return keySet.has(key);\n }\n return keySet._library?.hasBit(keySet, key) ?? false;\n}\n\nfunction getIndexableSelectorKeys(keySet: SelectorKeySource | undefined): string[] {\n return getSelectorKeyValues(keySet).filter(\n key => typeof key === 'string' && !key.startsWith('*') && isIndexableSelectorKey(key)\n );\n}\n\nfunction isNonImportStyleBoundary(rules: Rules | undefined): boolean {\n return Boolean(\n rules\n && rules.sourceNode?.type === 'StyleImport'\n && rules.sourceNode.options.type !== 'import'\n );\n}\n\nexport type DeclarationFindOptions = {\n filter?: (n: Node) => boolean;\n candidates?: Set<Node>;\n optionalCandidates?: Set<Node>;\n findAll?: boolean;\n /** This gets set if any parent is set to readonly */\n readonly?: boolean;\n searchParents?: boolean;\n start?: number;\n local?: boolean;\n};\n\nexport type FindOptions = DeclarationFindOptions & {\n childFilterType?: 'Mixin' | 'Ruleset' | undefined;\n context?: Context;\n searchedRules?: Set<Rules>;\n candidateContexts?: WeakMap<Node, Context>;\n /**\n * Whether this lookup has an explicit target (e.g., #ns[@foo]).\n * When true, Rules with isMixinOutput=true will be searchable.\n * When false or undefined, mixin output Rules will be excluded.\n */\n hasTarget?: boolean;\n};\n\nexport type MixinRegistryEntry = {\n value: Mixin | Ruleset;\n match: string[];\n};\n\n// [DELETED: RegistryData, globalRegistryCache, peekRegistryData, ensureRegistryData,\n// getRegistryDelta, ensureSessionRegistryIndex, getRegistryIndex, isRegistryIndexing,\n// syncRegistryCache, registerCanonicalNode, registerSessionNode — see registry-state-plan.md]\n\nfunction addRulesetToIndex(\n index: Map<string, Set<Ruleset>>,\n rules: Rules,\n ruleset: Ruleset,\n context?: Context\n): void {\n if (!isSelectorLikeNode(ruleset.get('selector', context))) {\n return;\n }\n\n const selector = ruleset.get('selector', context);\n if (!isSelectorLikeNode(selector)) {\n return;\n }\n const selectorBits = (rules.treeContext as { selectorBits?: BitSetLibrary<string>; opts?: { selectorBits?: BitSetLibrary<string> } } | undefined)?.selectorBits\n ?? rules.treeContext?.opts?.selectorBits;\n if (selectorBits && !getSelectorKeySetLibrary(selector)) {\n setSelectorKeySetLibrary(selector, selectorBits);\n const selectorValue = getNodeValueArray(selector);\n if (selectorValue) {\n for (const child of selectorValue) {\n if (isSelectorLikeNode(child) && !getSelectorKeySetLibrary(child)) {\n setSelectorKeySetLibrary(child, selectorBits);\n }\n }\n }\n }\n\n let keySet: SelectorKeySource;\n try {\n keySet = selector.keySet;\n } catch {\n return;\n }\n\n for (const key of getSelectorKeyValues(keySet)) {\n const existing = index.get(key);\n if (existing) {\n existing.add(ruleset);\n } else {\n index.set(key, new Set([ruleset]));\n }\n }\n}\n\nfunction addMixinToIndex(\n index: Map<string, MixinRegistryEntry[]>,\n rules: Rules,\n mixin: Mixin | Ruleset,\n context?: Context\n): void {\n if (isNode(mixin, N.Ruleset)) {\n const ruleset = mixin;\n let selector = getRulesetSelector(ruleset, context);\n if (isNode(selector, N.Nil)) {\n return;\n }\n const ownSelector = getMixinOwnSelector(ruleset);\n const callableSelector = ownSelector && !isNode(ownSelector, N.Nil) ? ownSelector : selector;\n if (isNode(callableSelector, N.Ampersand)) {\n return;\n }\n const sourceSelector = selector?.sourceNode;\n const selectorVisibleKeySet = tryGetSelectorKeySet(selector);\n const sourceVisibleKeySet = tryGetSelectorKeySet(sourceSelector);\n const selectorToIndex = getIndexableSelectorKeys(selectorVisibleKeySet).length\n ? selector\n : (getIndexableSelectorKeys(sourceVisibleKeySet).length ? sourceSelector : selector);\n let keySetToUse: SelectorKeySet | string[] | undefined;\n if (isNode(selectorToIndex, N.SelectorList)) {\n for (const sel of selectorToIndex.get('value')) {\n const selKeySet = tryGetSelectorKeySet(sel);\n if (selKeySet) {\n indexMixinSelectorStart(index, mixin, selKeySet);\n }\n }\n keySetToUse = undefined;\n } else {\n keySetToUse = tryGetSelectorKeySet(selectorToIndex);\n }\n if (\n keySetToUse\n && getIndexableSelectorKeys(keySetToUse).length > 0\n && ownSelector\n && !isNode(ownSelector, N.Nil)\n ) {\n const resolvedKeys = getIndexableSelectorKeys(keySetToUse);\n const ownSelectorText = String(ownSelector?.valueOf?.() ?? '');\n if (ownSelector && !getSelectorKeySetLibrary(ownSelector) && getSelectorKeySetLibrary(selectorToIndex)) {\n setSelectorKeySetLibrary(ownSelector, getSelectorKeySetLibrary(selectorToIndex)!);\n }\n const ownKeys = getIndexableSelectorKeys(tryGetSelectorKeySet(ownSelector));\n const parentRules = context ? getParent(mixin, context) : mixin.parent;\n const parentRuleset = parentRules\n ? (context ? getParent(parentRules, context) : parentRules.parent)\n : undefined;\n const parentSelector = isNode(parentRuleset, N.Ruleset)\n ? parentRuleset.get('selector', context)\n : undefined;\n const parentKeys = (\n parentSelector && !isNode(parentSelector, N.Nil)\n ? getIndexableSelectorKeys(tryGetSelectorKeySet(parentSelector))\n : []\n );\n if (\n parentKeys.length > 0\n && resolvedKeys.length > parentKeys.length\n ) {\n const parentKeySet = new Set(parentKeys);\n const localKeys = resolvedKeys.filter(k => !parentKeySet.has(k));\n if (localKeys.length > 0 && localKeys.length < resolvedKeys.length) {\n keySetToUse = localKeys;\n }\n } else if (ownKeys.length > 1 && ownSelectorText.trimStart().startsWith('&')) {\n keySetToUse = ownKeys.slice(1);\n } else if (\n parentKeys.length === 0\n && ownKeys.length > 0\n && resolvedKeys.length > ownKeys.length\n ) {\n keySetToUse = ownKeys;\n }\n }\n if (\n keySetToUse !== undefined\n && getIndexableSelectorKeys(keySetToUse).length === 0\n && ownSelector\n && !isNode(ownSelector, N.Nil)\n ) {\n const ownKeySet = tryGetSelectorKeySet(ownSelector);\n if (ownKeySet && getIndexableSelectorKeys(ownKeySet).length) {\n const ownKeys = getIndexableSelectorKeys(ownKeySet);\n const selectorText = String(selectorToIndex.valueOf?.() ?? '');\n keySetToUse = selectorText.startsWith('&') && ownKeys.length > 1\n ? new Set(ownKeys.slice(1))\n : ownKeySet;\n }\n }\n if (keySetToUse !== undefined) {\n indexMixinSelectorStart(index, mixin, keySetToUse);\n } else {\n // Fallback: test-created compound selectors may not have a keySet yet.\n // Derive indexable selector segments directly from the selector tree so\n // namespace/compound lookups can still use startKey + remainder matching.\n const fallbackKeys = getFallbackSelectorIndexKeys(callableSelector);\n if (fallbackKeys.length > 0) {\n indexMixinSelectorStart(index, mixin, fallbackKeys);\n } else {\n const selectorStr = String(callableSelector.valueOf?.() ?? '');\n if (selectorStr) {\n indexMixinSelectorStart(index, mixin, [selectorStr]);\n }\n }\n }\n return;\n }\n\n const keys = isNode(mixin, N.Mixin) && context ? mixin.getKeySet(context) : mixin.keySet;\n indexMixinSelectorStart(index, mixin, keys);\n}\n\nfunction addDeclarationToIndex(\n index: Map<string, Set<Declaration>>,\n item: Declaration\n): void {\n const key = item.get('name').valueOf();\n const set = index.get(key);\n if (set) {\n set.add(item);\n } else {\n index.set(key, new Set([item]));\n }\n}\n\nfunction indexMixinSelectorStart(\n index: Map<string, MixinRegistryEntry[]>,\n mixin: Mixin | Ruleset,\n keys: SelectorKeySource\n): void {\n let candidateKeys = getIndexableSelectorKeys(keys);\n for (let i = 0; i < candidateKeys.length; i++) {\n const startKey = candidateKeys[i]!;\n const rest = candidateKeys.filter(k => k !== startKey);\n const existing = index.get(startKey);\n if (existing) {\n existing.push({ value: mixin, match: rest });\n } else {\n index.set(startKey, [{ value: mixin, match: rest }]);\n }\n }\n}\n\nexport abstract class Registry<\n Type extends Node,\n IndexType extends Type | Set<Type> | Array<{\n value: Type;\n [key: string]: any;\n }> = Set<Type>\n> {\n abstract index: Map<string, IndexType>;\n protected pendingItems = new Set<Type>();\n\n constructor(\n public rules: Rules,\n protected context?: Context\n ) {}\n\n add(item: Type): void {\n this.pendingItems.add(item);\n }\n\n indexPendingItems() {\n if (this.pendingItems.size === 0) {\n return;\n }\n for (const item of this.pendingItems) {\n let key = String(item.valueOf());\n let set = this.index.get(key);\n if (set && set instanceof Set) {\n set.add(item);\n } else {\n this.index.set(key, new Set([item]));\n }\n }\n this.pendingItems.clear();\n }\n\n _searchRulesChildren(\n key: string,\n filterType: 'VarDeclaration' | 'Declaration' | 'Mixin',\n options: FindOptions = {}\n ) {\n let rules = this.rules;\n // CRITICAL FIX: Initialize searchedRules if not provided, and add current Rules BEFORE any recursive calls\n // The flaw in the original algorithm: when _searchRulesChildren calls childRules.find(), that creates\n // a new search context via DeclarationRegistry.find(), which may not preserve searchedRules tracking.\n // By initializing it here and adding the current Rules immediately, we ensure tracking persists.\n const searchedRules = options?.searchedRules ?? new Set<Rules>();\n if (!searchedRules.has(rules)) {\n searchedRules.add(rules);\n }\n let findType = filterType === 'Mixin' ? 'mixin' as const : 'declaration' as const;\n let findAll = Boolean(options.findAll);\n let {\n candidates = new Set(),\n start,\n readonly,\n local,\n childFilterType,\n context\n } = options;\n // childFilterType is the filterType to use when calling child Rules.find\n // If not provided, use filterType (for backward compatibility with DeclarationRegistry)\n // Note: childFilterType can be undefined to mean \"don't filter\" (accept both Mixin and Ruleset)\n const actualChildFilterType = 'childFilterType' in options ? childFilterType : filterType;\n let firstValue = candidates.values().next().value;\n rules.ensureCurrentRenderRulesRegistered(context);\n if (rules._rulesSet) {\n const { rulesSet } = rules;\n const length = rulesSet.length;\n if (length) {\n // Create one shared child options object, reused across loop iterations\n const childOpts: FindOptions = options\n ? {\n ...options,\n searchParents: false,\n start: undefined,\n searchedRules,\n context\n }\n : { searchParents: false, start: undefined, readonly, searchedRules, context };\n const optionalCandidates = options?.optionalCandidates;\n const isComparisonContext = firstValue && candidates.size > 0;\n const hasTarget = options?.hasTarget === true;\n\n // searchedRules is already initialized above and includes the current Rules\n // Inline the filter logic into the loop to avoid creating an intermediate array\n for (let i = length - 1; i >= 0; i--) {\n let r = rulesSet.at(i)!;\n // --- inline filter logic ---\n const entryVisibility = r.rulesVisibility?.[filterType];\n const nodeVisibility = r.node.options.rulesVisibility?.[filterType];\n const visibility = entryVisibility ?? nodeVisibility;\n const isMixinOutput = r.node.options?.isMixinOutput === true;\n if (isMixinOutput && !hasTarget) {\n continue;\n }\n if (!isMixinOutput) {\n const isVisible = visibility === 'public' || visibility === 'optional';\n if (!isVisible) {\n continue;\n }\n if (r.node.options?.forward && context?.rulesContext === rules) {\n continue;\n }\n if (local && r.node.options?.local) {\n continue;\n }\n if (!(findAll || !firstValue || isComparisonContext)) {\n continue;\n }\n if (start !== undefined && r.node.index >= start) {\n continue;\n }\n }\n // --- end inline filter logic ---\n // Skip if we've already searched this Rules node to prevent infinite recursion\n if (searchedRules && searchedRules.has(r.node)) {\n continue;\n }\n if (r.node === rules) {\n throw new Error(`Rules node contains itself in rulesSet`);\n }\n // Update per-iteration fields on the shared object\n childOpts.readonly = readonly || r.readonly;\n childOpts.local = local || Boolean(r.node.options?.local);\n // Use actualChildFilterType which may be undefined for mixin-ruleset lookups\n // filterType parameter is used to SELECT registry, actualChildFilterType is used to FILTER results\n let result = r.node.find(findType, key, actualChildFilterType, childOpts);\n if (result) {\n // Check if this Rules has optional visibility (from RulesEntry or the actual Rules node)\n const entryVisibility = r.rulesVisibility?.[filterType];\n const nodeVisibility = r.node.options.rulesVisibility?.[filterType];\n const isOptional = entryVisibility === 'optional' || nodeVisibility === 'optional';\n\n const isPublic = entryVisibility === 'public' || nodeVisibility === 'public';\n if (!findAll && isPublic) {\n if (options && childOpts.readonly) {\n options.readonly = true;\n }\n if (isArray(result)) {\n for (const node of result) {\n candidates.add(node);\n }\n } else {\n candidates.add(result);\n }\n break;\n }\n if (options) {\n options.readonly ||= childOpts.readonly;\n }\n if (isArray(result)) {\n for (const node of result) {\n if (isOptional && optionalCandidates) {\n optionalCandidates.add(node);\n } else {\n candidates.add(node);\n }\n }\n } else {\n if (isOptional && optionalCandidates) {\n optionalCandidates.add(result);\n } else {\n candidates.add(result);\n }\n }\n }\n }\n }\n }\n // REMOVED: Manual iteration through rules.value for child Rules nodes\n // If a Rules node is in rules.value and should be searchable, it should be registered\n // via registerNode() which adds it to rulesSet. We already search rulesSet above.\n // Manually iterating through rules.value creates infinite loops when a Rules node\n // appears in its own children, and is unnecessary since registered Rules are in rulesSet.\n }\n\n /**\n * Find the closest declaration from start, in reverse order,\n * using a binary search\n */\n _findClosestByStart(list: Type[], start?: number) {\n if (start === undefined) {\n return atIndex(list, -1);\n }\n /**\n * We do this so we start looking above the given position and don't\n * return the current node.\n */\n start -= 1;\n let bestMatch: number | undefined;\n\n /** Binary search the queue to find a starting position */\n let left = 0;\n let right = list.length - 1;\n\n while (left <= right) {\n let mid = Math.floor((left + right) / 2);\n let midVal = list.at(mid)!.index;\n if (midVal === start) {\n bestMatch = mid;\n break;\n }\n if (midVal < start) {\n bestMatch = mid;\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n return bestMatch !== undefined ? list.at(bestMatch) : undefined;\n }\n\n private _findByKey(candidates: Set<Type> | Type | undefined, key: string): Set<Type> | Type | undefined {\n let set = this.index.get(key);\n if (set) {\n let newSet: Set<Type> | undefined;\n if (set instanceof Set) {\n newSet = set;\n } else if (isArray(set)) {\n newSet = new Set(set.map(({ value }) => value));\n } else {\n return set;\n }\n if (candidates) {\n if (candidates instanceof Set) {\n // Avoid Set.prototype.union (not available in our TS lib target)\n for (const v of newSet) {\n candidates.add(v);\n }\n } else {\n candidates = new Set([candidates, ...newSet]);\n }\n } else {\n candidates = newSet;\n }\n }\n return candidates;\n }\n\n find(keys: string | string[] | Set<string>, _filterType?: string, _options?: FindOptions): Type[] | Type | Array<{ value: Type; [key: string]: any }> | undefined {\n this.indexPendingItems();\n let candidates: Set<Type> | Type | undefined;\n if (isArray(keys) || keys instanceof Set) {\n for (const key of keys) {\n candidates = this._findByKey(candidates, key);\n }\n } else {\n candidates = this._findByKey(candidates, keys);\n }\n if (candidates instanceof Set) {\n return candidates.size ? [...candidates] : undefined;\n }\n return candidates;\n }\n}\n\n/**\n * Registry for fast selector-based ruleset lookups\n */\nexport class RulesetRegistry extends Registry<Ruleset> {\n private _index = new Map<string, Set<Ruleset>>();\n get index(): Map<string, Set<Ruleset>> {\n return this._index;\n }\n\n /**\n * Add a ruleset to be indexed later\n */\n override add(ruleset: Ruleset) {\n addRulesetToIndex(this.index, this.rules, ruleset, this.context);\n }\n\n /**\n * Index any pending rulesets\n * Override the base class method to use keySet-based indexing\n */\n override indexPendingItems() {\n return;\n }\n\n /**\n * Find candidate rulesets that might match the target selector.\n * Searches only the local index - all rulesets should be registered\n * to the extend root's registry during evaluation.\n */\n override find(keys: string[] | Set<string>): Ruleset[] | undefined {\n // Index any pending rulesets first\n this.indexPendingItems();\n\n let candidates: Set<Ruleset> | undefined;\n let rulesets: Ruleset[] | undefined;\n\n /** Just get based on first key */\n const indices = [this.index];\n for (const key of keys) {\n for (const index of indices) {\n const set = index.get(key);\n if (set) {\n candidates ??= new Set<Ruleset>();\n for (const candidate of set) {\n candidates.add(candidate);\n }\n }\n }\n break;\n }\n if (!candidates) {\n return undefined;\n }\n\n /** Now find selectors that have all keys */\n const searchKeys = keys instanceof Set ? [...keys] : keys;\n let searchKeySet = keys instanceof Set ? keys : new Set(keys);\n let searchBitSet: BitSet<string> | undefined;\n for (const c of candidates) {\n let sel = c.get('selector');\n if (!sel || isNode(sel, N.Nil)) {\n continue;\n }\n let isSubset: boolean;\n const selectorKeySet = sel.keySet;\n if (!(selectorKeySet instanceof Set) && selectorKeySet._library) {\n searchBitSet ??= selectorKeySet._library.getBitset(searchKeySet);\n isSubset = isSubsetOf(searchBitSet, selectorKeySet);\n } else {\n isSubset = true;\n for (const k of searchKeys) {\n if (!hasSelectorKey(selectorKeySet, k)) {\n isSubset = false;\n break;\n }\n }\n }\n if (isSubset) {\n (rulesets ??= []).push(c);\n }\n }\n\n return rulesets;\n }\n}\n\n/**\n * The mixin registry works a little differently than the selector registry\n * in these ways:\n *\n * 1. The mixin registry can only be indexed by basic element, class, and\n * id selectors.\n * 2. The index is the start key, not any key found in the selector.\n * 3. '>' and ' ' combinators are ignored.\n * 4. Initial ampersands (implicit or explicit) are ignored.\n * 5. The mixin registry is local to the rules, whereas the selector registry\n * is global to the file tree.\n * 6. Rulesets and mixins without params will have their children searched\n * if the first part matches.\n */\nexport class MixinRegistry extends Registry<\n Mixin | Ruleset,\n MixinRegistryEntry[]\n> {\n private _index = new Map<string, MixinRegistryEntry[]>();\n get index(): Map<string, MixinRegistryEntry[]> {\n return this._index;\n }\n\n // private getSimpleKeyList(selector: Selector | Nil | undefined): string[] | undefined {\n // let keyList: string[] | undefined;\n // if (selector && 'keySet' in selector) {\n // let passed = true;\n // let foundBasic = false;\n // for (const sel of selector.nodes()) {\n // /** Ampersand is okay at start, but not after a basic selector */\n // if (!foundBasic && isNode(sel, 'Ampersand')) {\n // continue;\n // }\n\n // if (isNode(sel, 'Combinator')) {\n // if (sel.value !== '>' && sel.value !== ' ') {\n // passed = false;\n // break;\n // }\n // continue;\n // }\n\n // /** Anything other than a universal selector is fine */\n // if (isNode(sel, 'BasicSelector') && /^[^*]/.test(sel.value)) {\n // (keyList ??= []).push(sel.valueOf() as string);\n // foundBasic = true;\n // continue;\n // }\n // if (isNode(sel, 'CompoundSelector') || isNode(sel, 'ComplexSelector')) {\n // /** Might still be fine */\n // continue;\n // }\n // /** Nothing else is valid, so fail */\n // passed = false;\n // break;\n // }\n // if (!passed) {\n // return;\n // }\n // }\n // return keyList;\n // }\n\n private _indexSelectorStart(mixin: Ruleset | Mixin, keySet: SelectorKeySet | string[]) {\n indexMixinSelectorStart(this.index, mixin, keySet);\n }\n\n /**\n * For un-preEvaluated mixin rules, register child Rulesets/Mixins\n * so namespace lookup can descend into them. Also propagate\n * keySetLibrary so selectors can compute their keySets.\n */\n private _ensureChildrenRegistered(rules: Rules, selectorBits?: BitSetLibrary<string>) {\n for (const child of rules.getRegistryChildren(this.context)) {\n if (isNode(child, N.Ruleset)) {\n const sel = child.get('selector', this.context);\n if (isSelectorLikeNode(sel) && selectorBits && !sel.keySetLibrary) {\n sel.keySetLibrary = selectorBits;\n const selValue = Reflect.get(sel, 'value');\n if (isArray(selValue)) {\n for (const sub of selValue) {\n if (isSelectorLikeNode(sub) && !sub.keySetLibrary) {\n sub.keySetLibrary = selectorBits;\n }\n }\n }\n }\n rules.registerNode(child, undefined, this.context);\n } else if (isNode(child, N.Mixin)) {\n rules.registerNode(child, undefined, this.context);\n }\n }\n }\n\n override add(mixin: Mixin | Ruleset) {\n addMixinToIndex(this.index, this.rules, mixin, this.context);\n }\n\n override indexPendingItems() {\n return;\n }\n\n /**\n * Check if an entry matches the search criteria.\n * Handles exact matches, partial matches (compound selector completion), and recursive searches.\n * This consolidates the matching logic to avoid duplication.\n */\n /**\n * Check if a Ruleset/Mixin matches a given array of keys using the same logic as the registry\n * This uses the indexed match arrays (same as _checkEntryMatch) rather than direct selector comparison\n * @param value The Ruleset or Mixin to check\n * @param keys The array of keys to match against (e.g., [\".jo\", \".ki\"])\n * @returns true if the Ruleset/Mixin matches the keys using registry matching logic\n */\n checkRulesetMatchesKeys(value: Mixin | Ruleset, keys: string[]): boolean {\n if (!keys || keys.length === 0) {\n return false;\n }\n\n // Get the selector's keySet and extract indexable keys (same as _indexSelectorStart)\n let indexableKeys: string[] = [];\n if (isNode(value, N.Ruleset)) {\n const selector = value.get('selector', this.context);\n if (isNode(selector, N.Nil)) {\n return false;\n }\n if (isNode(selector, N.SelectorList)) {\n // For selector lists, check if any selector matches\n return selector.get('value').some((sel) => {\n const selKeys = getIndexableSelectorKeys(tryGetSelectorKeySet(sel, false));\n if (selKeys.length === 0) {\n return false;\n }\n // Check if keys appear in sequence in this selector's keys\n return this._checkKeysSubsequence(selKeys, keys);\n });\n }\n const keySet = tryGetSelectorKeySet(selector, false);\n if (!keySet || getSelectorKeyValues(keySet).length === 0) {\n return false;\n }\n indexableKeys = getIndexableSelectorKeys(keySet);\n } else {\n const keySet = value.keySet;\n if (!keySet || getSelectorKeyValues(keySet).length === 0) {\n return false;\n }\n indexableKeys = getIndexableSelectorKeys(keySet);\n }\n\n if (indexableKeys.length === 0) {\n return false;\n }\n\n // Check if the provided keys appear in sequence in the selector's indexable keys\n // The keySet should only contain keys from the Ruleset's own selector, not parent context\n return this._checkKeysSubsequence(indexableKeys, keys);\n }\n\n /**\n * Internal helper that checks if the provided keys appear in sequence within the selector's keys\n *\n * For compound selectors like `#header .milk .chips .jo.ki`, when we search for `.jo`, we get:\n * - The full selector's indexable keys: `[\"#header\", \".milk\", \".chips\", \".jo\", \".ki\"]`\n * - When checking if accumulated keys `[\".jo\", \".ki\"]` match, we check if they appear in sequence\n */\n private _checkKeysSubsequence(selectorKeys: string[], searchKeys: string[]): boolean {\n if (searchKeys.length === 0) {\n return false;\n }\n\n // Check if searchKeys is a subsequence of selectorKeys (searchKeys appear in order)\n let searchIndex = 0;\n for (const selectorKey of selectorKeys) {\n if (searchIndex < searchKeys.length && selectorKey === searchKeys[searchIndex]) {\n searchIndex++;\n }\n }\n\n const matches = searchIndex === searchKeys.length;\n return matches;\n }\n\n /**\n * Find candidate mixins (or rulesets, or both) that might match the target selector\n *\n * ...also...\n *\n * @todo - Not sure how recursion works here with the match overflow and returning\n * proper arrays.\n */\n override find(\n keys: string | string[],\n filterType: 'Mixin' | 'Ruleset' | undefined = undefined,\n options: FindOptions = {}\n ): (Mixin | Ruleset)[] | undefined {\n let keyList: string[] | undefined;\n\n if (isArray(keys)) {\n keyList = keys;\n } else {\n keyList = [keys];\n }\n\n if (!keyList?.length) {\n return;\n }\n\n let rules: Rules | undefined = this.rules;\n let {\n searchParents = true,\n local = false,\n candidates = new Set<Node>(),\n context,\n hasTarget = false\n } = options ?? {};\n const candidateContexts = options?.candidateContexts ?? new WeakMap<Node, Context>();\n const getCandidateIdentity = (node: Node): Node => node.sourceNode ?? node;\n const getContextRenderPriority = (ctx?: Context): number => {\n const renderKey = ctx?.renderKey;\n if (renderKey === undefined || renderKey === CANONICAL) {\n return 0;\n }\n if (renderKey === EVAL) {\n return 1;\n }\n return 2;\n };\n const getCandidateScore = (node: Node, ctx?: Context): [number, number, number] => {\n const nonCanonicalParentEdgeKeys = node.parentEdges\n ? [...node.parentEdges.keys()].filter(key => key !== CANONICAL && key !== CALLER)\n : [];\n const ctxRenderKey = ctx?.renderKey;\n const matchesContextKey = ctxRenderKey !== undefined && nonCanonicalParentEdgeKeys.includes(ctxRenderKey) ? 1 : 0;\n const contextPriority = getContextRenderPriority(ctx);\n const fewerEdgesScore = -nonCanonicalParentEdgeKeys.length;\n return [matchesContextKey, contextPriority, fewerEdgesScore];\n };\n const rememberCandidateContext = (node: Node): void => {\n if (!context || !rules) {\n return;\n }\n const identity = getCandidateIdentity(node);\n const nextContext: Context = {\n ...context,\n rulesContext: rules\n };\n const existingContext = candidateContexts.get(identity);\n if (\n !existingContext\n || (\n existingContext.renderKey === CANONICAL\n && nextContext.renderKey !== CANONICAL\n )\n || (\n existingContext.renderKey === undefined\n && nextContext.renderKey !== undefined\n )\n ) {\n candidateContexts.set(identity, nextContext);\n }\n };\n const addCandidate = (node: Node): void => {\n const sourceNode = node.sourceNode ?? node;\n for (const existing of candidates) {\n const existingNode = existing;\n if ((existingNode.sourceNode ?? existingNode) !== sourceNode) {\n continue;\n }\n const existingIdentity = getCandidateIdentity(existingNode);\n const existingContext = candidateContexts.get(existingIdentity);\n const nextContext = context && rules\n ? {\n ...context,\n rulesContext: rules\n }\n : context;\n const existingScore = getCandidateScore(existingNode, existingContext);\n const nextScore = getCandidateScore(node, nextContext);\n rememberCandidateContext(existingNode);\n if (\n existingScore[0] > nextScore[0]\n || (existingScore[0] === nextScore[0] && existingScore[1] > nextScore[1])\n || (existingScore[0] === nextScore[0] && existingScore[1] === nextScore[1] && existingScore[2] >= nextScore[2])\n ) {\n return;\n }\n candidates.delete(existingNode);\n break;\n }\n if (context && rules) {\n setParent(node, rules, context);\n rememberCandidateContext(node);\n }\n (candidates ??= new Set()).add(node);\n };\n const mixinHasNoRequiredParams = (mixinNode: Mixin): boolean => {\n const params = mixinNode.get('params');\n if (!params || params.length === 0) {\n return true;\n }\n for (const param of params.get('value')) {\n if (param.type === 'Rest') {\n continue;\n }\n if (isNode(param, N.VarDeclaration)) {\n if (param.get('value') instanceof Nil) {\n return false;\n }\n continue;\n }\n if (isNode(param, N.Any) && param.role === 'property') {\n return false;\n }\n return false;\n }\n return true;\n };\n const getDescendContext = (node: Node, baseContext?: Context): Context | undefined => {\n if (!baseContext) {\n return undefined;\n }\n let nodeRenderKey = node.renderKey;\n if (nodeRenderKey === undefined || nodeRenderKey === CANONICAL || nodeRenderKey === baseContext.renderKey) {\n const nonCanonicalParentEdgeKeys = node.parentEdges\n ? [...node.parentEdges.keys()].filter(key => key !== CANONICAL && key !== CALLER)\n : [];\n if (nonCanonicalParentEdgeKeys.length === 1) {\n nodeRenderKey = nonCanonicalParentEdgeKeys[0]!;\n }\n }\n if (\n nodeRenderKey === undefined\n || nodeRenderKey === CANONICAL\n || nodeRenderKey === baseContext.renderKey\n ) {\n return baseContext;\n }\n return {\n ...baseContext,\n renderKey: nodeRenderKey\n };\n };\n\n // Track which Rules nodes we've already searched to prevent infinite recursion\n // Use the searchedRules from options if it exists, otherwise create a new Set\n let mixinChildSearchOpts: FindOptions | undefined;\n const searchedRules = options?.searchedRules || new Set<Rules>();\n if (options) {\n options.searchedRules = searchedRules;\n options.candidateContexts = candidateContexts;\n }\n while (rules) {\n // Don't add to searchedRules yet - we'll add it after we finish searching (including children)\n let [startKey, ...search] = keyList;\n const registry = rules.getRegistry('mixin', context);\n if (registry) {\n registry.indexPendingItems();\n }\n const mixinIndices = registry ? [registry.index] : [];\n const existing: MixinRegistryEntry[] = [];\n for (const index of mixinIndices) {\n const entries = index.get(startKey!);\n if (entries) {\n existing.push(...entries);\n }\n }\n // Resolve interpolated selector starts (e.g. \"@{a2}\") against current context\n // so unresolved-index keys can still match resolved call keys (e.g. \".foo\").\n let resolvedInterpolatedStartEntries: Array<{ value: Mixin | Ruleset; match: string[] }> = [];\n if (context && typeof startKey === 'string' && existing.length === 0) {\n for (const index of mixinIndices) {\n for (const [indexedKey, indexedEntries] of index) {\n const matchInterpolated = /^@\\{(.+)\\}$/.exec(indexedKey);\n if (!matchInterpolated) {\n continue;\n }\n const varName = matchInterpolated[1]!;\n const maybeVar = rules.find('declaration', varName, 'VarDeclaration', {\n context,\n hasTarget,\n filter: options?.filter\n });\n if (isNode(maybeVar, N.VarDeclaration)) {\n const resolvedValue = String(maybeVar.get('value').valueOf?.() ?? maybeVar.get('value') ?? '');\n if (resolvedValue === startKey) {\n resolvedInterpolatedStartEntries.push(...indexedEntries);\n }\n }\n }\n }\n }\n\n // With the new indexing (by local visible keys), nested rulesets are indexed under their own keys\n // So we only need to check entries under the startKey - no need to scan all entries\n let allEntriesToCheck: Array<{ value: Mixin | Ruleset; match: string[] }> = [];\n if (existing) {\n allEntriesToCheck.push(...existing);\n }\n if (resolvedInterpolatedStartEntries.length > 0) {\n allEntriesToCheck.push(...resolvedInterpolatedStartEntries);\n }\n\n if (allEntriesToCheck.length > 0) {\n const targetMatch = search.length === 0 ? [startKey!] : search;\n const deferredExactMatches: Array<Mixin | Ruleset> = [];\n const candidateSizeBeforeEntries = candidates.size;\n for (const { value, match } of allEntriesToCheck) {\n if (filterType && value.type !== filterType) {\n continue;\n }\n\n // If match equals targetMatch (search or [startKey] when search is empty), this IS the ruleset we're looking for\n // Also, if search is empty and match is empty, this ruleset IS the startKey we're looking for\n // BUT: For compound search paths (keyList.length > 1), we should NOT add the startKey mixin itself\n // as a candidate when search.length === 0 && match.length === 0, because that means we found the startKey\n // but haven't fully matched the compound path. The startKey should only be added as a candidate if we're\n // doing a simple lookup (keyList.length === 1), where the startKey IS the full match.\n if (arraysEqualAsSet(match, targetMatch)) {\n if (keyList.length > 1) {\n deferredExactMatches.push(value);\n } else {\n addCandidate(value);\n }\n continue;\n }\n // Only add startKey mixin as candidate if we're doing a simple lookup (not a compound path)\n if (search.length === 0 && match.length === 0 && keyList.length === 1) {\n addCandidate(value);\n continue;\n }\n // For compound paths, we don't add startKey as a candidate, but we still need to search inside it\n // The recursive search below will handle finding nested mixins\n\n // If match equals [startKey] OR match is empty (meaning this ruleset IS the startKey),\n // we need to search inside it for the remaining search keys\n // NOTE: We should search inside #theme even if we're not adding it as a candidate (for compound paths)\n if (search.length > 0 && (arraysEqual(match, [startKey!]) || match.length === 0)) {\n const isRuleset = isNode(value, N.Ruleset);\n const isMixin = isNode(value, N.Mixin);\n const hasNoParams = isMixin && mixinHasNoRequiredParams(value);\n if (isRuleset || hasNoParams) {\n const subRules = isRuleset\n ? value.enterRules(context)\n : value.get('rules', context).withRenderOwner(\n value,\n context?.renderKey,\n context\n );\n // Mixin rules aren't preEvaluated during registration — register\n // child rulesets/mixins now so namespace lookup can descend.\n // Always ensure children are registered for namespace descent —\n // preEvaluated children still need keySetLibrary on their selectors\n // for the mixin registry to index them.\n this._ensureChildrenRegistered(subRules, context?.selectorBits);\n const subMixinRegistry = subRules.getRegistry('mixin', context);\n subMixinRegistry?.indexPendingItems();\n subMixinRegistry?.find(search, filterType, {\n searchParents: false,\n local,\n candidates,\n context,\n candidateContexts,\n filter: options?.filter,\n hasTarget,\n searchedRules: undefined // Not needed when searchParents is false\n });\n }\n continue;\n }\n\n // If there are more search keys than match keys, recursively search inside this ruleset\n // This handles cases where match is a prefix of search (e.g., match=[\".foo\"], search=[\".foo\", \".bar\"])\n // Or when match is empty (ruleset IS the startKey) and we need to search inside for the full search\n const shouldRecurse = search.length > 0 && (search.length > match.length || match.length === 0);\n const matchKeysInSearch = match.length > 0 && arrayContainsAll(search, match);\n if (shouldRecurse) {\n let searchKeys: string[];\n if (match.length === 0) {\n // Match is empty, meaning this ruleset IS the startKey, search inside for the full search\n searchKeys = search;\n } else if (matchKeysInSearch) {\n // Match keys are all contained in search — remove them (set-based) to get the remainder\n const matchSet = new Set(match);\n searchKeys = search.filter(k => !matchSet.has(k));\n } else {\n // Match is not a prefix of search - skip this ruleset, it doesn't match\n continue;\n }\n const isRuleset = isNode(value, N.Ruleset);\n const isMixin = isNode(value, N.Mixin);\n const hasNoParams = isMixin && mixinHasNoRequiredParams(value);\n if (isRuleset || hasNoParams) {\n const subRules = isRuleset\n ? value.enterRules(context)\n : value.get('rules', context).withRenderOwner(\n value,\n context?.renderKey,\n context\n );\n this._ensureChildrenRegistered(subRules, context?.selectorBits);\n const subMixinRegistry = subRules.getRegistry('mixin', context);\n subMixinRegistry?.indexPendingItems();\n subMixinRegistry?.find(searchKeys, filterType, {\n searchParents: false,\n local,\n candidates,\n context,\n candidateContexts,\n filter: options?.filter,\n hasTarget,\n searchedRules: searchedRules\n });\n }\n }\n }\n\n if (keyList.length > 1 && candidates.size === candidateSizeBeforeEntries) {\n for (const candidate of deferredExactMatches) {\n addCandidate(candidate);\n }\n }\n }\n\n // Track which candidates existed before searching children (by snapshot of the set)\n const candidateSizeBefore = candidates ? candidates.size : 0;\n const candidatesBefore = candidateSizeBefore > 0 ? new Set(candidates) : undefined;\n // Reuse a single child search options object\n // For compound paths (keyList.length > 1), the first segment acts as a namespace\n // target — allow searching inside mixin output rulesets so that e.g.\n // `.Person(\"Male\")` output containing `.person { .sayGender() {} }` is reachable.\n const childHasTarget = hasTarget || keyList.length > 1;\n if (!mixinChildSearchOpts) {\n mixinChildSearchOpts = {\n searchParents: false,\n local,\n candidates,\n findAll: true,\n childFilterType: filterType,\n context,\n filter: options?.filter,\n hasTarget: childHasTarget,\n searchedRules\n };\n } else {\n mixinChildSearchOpts.searchedRules = searchedRules;\n }\n registry?._searchRulesChildren(startKey!, 'Mixin', mixinChildSearchOpts);\n\n // After _searchRulesChildren, check if any new candidates are mixins/rulesets we should search inside\n // This handles the case where #theme mixin is found in imported Rules and we need to search inside it\n // Also, for compound paths, remove #theme from candidates if it was added by _searchRulesChildren\n // because we only want to search inside it, not include it as a final candidate\n if (candidates && candidates.size > candidateSizeBefore) {\n const candidatesToRemove: (Mixin | Ruleset)[] = [];\n for (const candidate of candidates) {\n const candidateNode = candidate;\n // Only check candidates that were added by _searchRulesChildren (not in original set)\n if (candidatesBefore && candidatesBefore.has(candidateNode)) {\n continue;\n }\n {\n const isMixin = isNode(candidateNode, N.Mixin);\n const isRuleset = isNode(candidateNode, N.Ruleset);\n const hasNoParams = isMixin && mixinHasNoRequiredParams(candidateNode);\n // Check if this candidate matches the startKey.\n // For rulesets discovered via child-search, key-set membership is the reliable signal.\n const candidateKey = isMixin\n ? candidateNode.get('name')?.valueOf?.()\n : (isRuleset ? candidateNode.get('selector').valueOf?.() : '');\n const candidateSelector = isRuleset\n ? candidateNode.get('selector')\n : undefined;\n const candidateVisibleKeySet = candidateSelector && !isNode(candidateSelector, N.Nil)\n ? tryGetSelectorKeySet(candidateSelector, true)\n : undefined;\n const candidateKeySet = candidateSelector && !isNode(candidateSelector, N.Nil)\n ? tryGetSelectorKeySet(candidateSelector, false)\n : undefined;\n const matchesStartKey = isRuleset\n ? (\n hasSelectorKey(candidateVisibleKeySet, startKey!)\n || hasSelectorKey(candidateKeySet, startKey!)\n || candidateKey === startKey\n )\n : candidateKey === startKey;\n\n // For compound paths (keyList.length > 1), remove startKey from candidates if it was added by _searchRulesChildren\n // because we only want to search inside it, not include it as a final candidate\n if (matchesStartKey && keyList.length > 1) {\n candidatesToRemove.push(candidateNode);\n }\n\n // Search inside the candidate if it matches startKey and we have remaining search keys\n if (matchesStartKey && search.length > 0 && (isRuleset || hasNoParams)) {\n const foundContext = candidateContexts.get(getCandidateIdentity(candidateNode));\n const descendContext = getDescendContext(candidateNode, foundContext ?? context);\n let subRules = isRuleset\n ? candidateNode.enterRules(descendContext)\n : candidateNode.get('rules', descendContext).withRenderOwner(\n candidateNode,\n descendContext?.renderKey,\n descendContext\n );\n const searchContext = descendContext\n ? { ...descendContext, rulesContext: subRules }\n : undefined;\n const subMixinRegistry = subRules.getRegistry('mixin', searchContext);\n subMixinRegistry?.indexPendingItems();\n subMixinRegistry?.find(search, filterType, {\n searchParents: false,\n local,\n candidates,\n context: searchContext,\n candidateContexts,\n filter: options?.filter,\n hasTarget,\n searchedRules: undefined // Not needed when searchParents is false\n });\n }\n }\n }\n // Remove candidates that shouldn't be in the final result (for compound paths)\n for (const candidateToRemove of candidatesToRemove) {\n candidates.delete(candidateToRemove);\n }\n }\n\n // Mark this Rules node as searched after we've finished searching it (including children)\n searchedRules.add(rules);\n\n if (isNonImportStyleBoundary(rules)) {\n searchParents = false;\n }\n\n if (!searchParents) {\n break;\n }\n do {\n rules = rules?.getRegistryParent(context);\n } while (rules && rules.type !== 'Rules');\n }\n\n // With compound keys parsed as arrays (e.g., ['#theme', '.dark', '.navbar', '.colors']),\n // we can find all matches in one pass. The find() method handles compound keys by\n // recursively searching inside nested rulesets for the remaining keys.\n\n return candidates.size ? [...candidates] : undefined;\n }\n}\n\n/**\n * For either Sass, Jess, or JS functions.\n *\n * Less and Sass can register global functions that can be called from the language\n * without a `@-use` directive.\n *\n * @todo Should the presence of `@-use` directives anywhere in the\n * stylesheet tree cause these global functions to be disabled?\n */\nexport class FunctionRegistry extends Registry<JsFunction | Func, JsFunction | Func> {\n index = new Map<string, JsFunction | Func>();\n\n cloneForRules(rules: Rules): FunctionRegistry {\n const next = new FunctionRegistry(rules);\n // Preserve any functions injected directly into the registry (Less plugin style).\n next.index = new Map(this.index);\n next.pendingItems = new Set(this.pendingItems);\n return next;\n }\n\n override indexPendingItems() {\n if (this.pendingItems.size === 0) {\n return;\n }\n for (const item of this.pendingItems) {\n if (item instanceof JsFunction) {\n this.index.set(item.name!, item);\n continue;\n }\n // Stylesheet-defined function node\n const nameKey = (item as Func).nameKey;\n if (nameKey) {\n this.index.set(nameKey, item);\n }\n }\n this.pendingItems.clear();\n }\n\n override find(name: string, filterType?: string, options?: FindOptions): JsFunction | Func | undefined {\n let fn: JsFunction | Func | undefined;\n let rules: Rules | undefined = this.rules;\n let { searchParents = true } = options ?? {};\n let findRoot = false;\n while (rules) {\n if (isNonImportStyleBoundary(rules)) {\n searchParents = false;\n }\n let registry = rules.functionRegistry;\n if (registry) {\n registry.indexPendingItems();\n fn = registry.index.get(name);\n\n if (fn || !searchParents) {\n break;\n }\n }\n\n do {\n rules = rules?.getRegistryParent(this.context);\n if (\n findRoot\n && rules?.type === 'Rules'\n && rules.getRegistryParent(this.context) === undefined\n ) {\n /** We're at the root */\n break;\n }\n } while (!findRoot && rules && rules.type !== 'Rules');\n }\n\n return fn;\n }\n\n /**\n * Override add() to support both Jess API (add(item)) and Less.js API (add(name, func))\n */\n override add(item: JsFunction | Func): void;\n override add(name: string, func: JsFunction | ((...args: any[]) => any)): void;\n override add(\n nameOrItem: string | JsFunction | Func,\n func?: JsFunction | ((...args: any[]) => any)\n ): void {\n // If first argument is a JsFunction or Func, use base class behavior\n if (nameOrItem instanceof JsFunction || (typeof nameOrItem === 'object' && nameOrItem !== null && Reflect.get(nameOrItem, 'type') === 'Func')) {\n super.add(nameOrItem as JsFunction | Func);\n return;\n }\n\n // Otherwise, it's Less.js-compatible API: add(name, func)\n if (typeof nameOrItem !== 'string' || func === undefined) {\n throw new Error('FunctionRegistry.add() requires either a JsFunction or (name: string, func: JsFunction | Function)');\n }\n\n // Convert name to lowercase for Less.js compatibility\n const lowerName = nameOrItem.toLowerCase();\n\n // If func is already a JsFunction, use it directly\n // Otherwise, create a new JsFunction from the raw function\n const jsFunc = func instanceof JsFunction\n ? func\n : new JsFunction({ name: lowerName, fn: func });\n\n // Ensure the name is set\n if (!jsFunc.name) {\n jsFunc.name = lowerName;\n }\n\n // Add to pendingItems directly\n this.pendingItems.add(jsFunc);\n }\n\n /**\n * Less.js-compatible API: Add multiple functions at once\n * @param functions Object mapping function names to functions\n */\n addMultiple(functions: Record<string, JsFunction | ((...args: any[]) => any)>): void {\n for (const [name, func] of Object.entries(functions)) {\n this.add(name, func);\n }\n }\n\n /**\n * Less.js-compatible API: Get a function by name\n * Uses case-insensitive lookup and searches parent chain\n * @param name Function name (case-insensitive)\n * @returns The function if found, undefined otherwise\n */\n get(name: string): JsFunction | Func | undefined {\n // Convert to lowercase for case-insensitive lookup\n const lowerName = name.toLowerCase();\n\n // First check local registry\n this.indexPendingItems();\n let fn = this.index.get(lowerName);\n\n if (fn) {\n return fn;\n }\n\n // If not found locally, use find() to search parent chain\n // find() already handles parent traversal\n return this.find(lowerName);\n }\n\n /**\n * Less.js-compatible API: Get all local functions (without parent chain)\n * @returns Object mapping function names to functions\n */\n getLocalFunctions(): Record<string, JsFunction | Func> {\n this.indexPendingItems();\n const result: Record<string, JsFunction | Func> = {};\n for (const [name, func] of this.index.entries()) {\n result[name] = func;\n }\n return result;\n }\n\n /**\n * Less.js-compatible API: Create a child registry that inherits from this one\n * In Less.js, this creates a new registry with prototype inheritance.\n * In Jess, we create a new registry that searches this one as a parent.\n *\n * @returns A new FunctionRegistry that will search this registry when functions aren't found locally\n */\n inherit(): FunctionRegistry {\n // Create a new registry for the same Rules\n // The new registry will use find() which searches parent chain\n // We need to create a registry that references this one as parent\n // Since FunctionRegistry.find() already searches parent Rules chain,\n // we can create a new registry on the same Rules and it will naturally\n // find functions in parent Rules. However, for true \"inherit\" behavior\n // where we want to search THIS registry specifically, we need a different approach.\n\n // For now, create a new registry on the same Rules\n // The find() method will search up the Rules parent chain, which includes\n // this registry's Rules, so it should work correctly.\n const childRegistry = new FunctionRegistry(this.rules);\n\n // Store reference to parent registry for direct lookup\n // This allows the child to search the parent registry even if it's on the same Rules\n Reflect.set(childRegistry, '_parentRegistry', this);\n\n // Override get() to check parent registry first\n const originalGet = childRegistry.get.bind(childRegistry);\n childRegistry.get = function(this: FunctionRegistry, name: string): JsFunction | Func | undefined {\n // First check local registry\n this.indexPendingItems();\n const localFn = this.index.get(name.toLowerCase());\n if (localFn) {\n return localFn;\n }\n\n // Then check parent registry\n const parentRegistry = Reflect.get(this, '_parentRegistry');\n if (parentRegistry instanceof FunctionRegistry) {\n const parentFn = parentRegistry.get(name);\n if (parentFn) {\n return parentFn;\n }\n }\n\n // Finally, use find() to search Rules parent chain\n return originalGet(name);\n }.bind(childRegistry);\n\n return childRegistry;\n }\n}\n\n/**\n *\n * @note - Keys of different types may overlap, but then are filtered when searching.\n * As in, a variable named `$foo` and a property named `foo` will be in the\n * same map.\n */\nexport class DeclarationRegistry extends Registry<Declaration> {\n private _index = new Map<string, Set<Declaration>>();\n get index(): Map<string, Set<Declaration>> {\n return this._index;\n }\n\n override add(item: Declaration): void {\n addDeclarationToIndex(this.index, item);\n }\n\n override indexPendingItems() {\n return;\n }\n\n /**\n * Get declarations from map and nested rulesets.\n * This will return a list of all matching nodes.\n *\n * @todo - The pattern for mixins will be similar, no? Can this be\n * re-used / abstracted?\n *\n * @todo - Register declarations and index them only when searching.\n * This would be similar to how we index rulesets for extending.\n */\n override find(\n key: string,\n filterType: 'VarDeclaration' | 'Declaration' = 'VarDeclaration',\n options?: FindOptions\n ): Declaration | undefined {\n const candidateContexts = options?.candidateContexts ?? new WeakMap<Node, Context>();\n const getCandidateIdentity = (node: Declaration): Node => node.sourceNode ?? node;\n const getDeclarationCandidateScore = (node: Declaration, activeRules: Rules): [number, number, number, number] => {\n const activeRenderKey = context?.renderKey ?? activeRules.renderKey;\n const nonCanonicalParentEdgeKeys = node.parentEdges\n ? [...node.parentEdges.keys()].filter(key => key !== CANONICAL && key !== CALLER)\n : [];\n const matchesActiveKey = activeRenderKey !== undefined && nonCanonicalParentEdgeKeys.includes(activeRenderKey) ? 1 : 0;\n const isDerived = node !== getCandidateIdentity(node) ? 1 : 0;\n const isPreEvaluated = node.preEvaluated ? 1 : 0;\n const isEvaluated = node.evaluated ? 1 : 0;\n return [matchesActiveKey, isDerived, isPreEvaluated, isEvaluated];\n };\n const shouldReplaceCandidate = (existing: Declaration, next: Declaration, activeRules: Rules): boolean => {\n const existingScore = getDeclarationCandidateScore(existing, activeRules);\n const nextScore = getDeclarationCandidateScore(next, activeRules);\n for (let i = 0; i < existingScore.length; i++) {\n if (nextScore[i]! > existingScore[i]!) {\n return true;\n }\n if (nextScore[i]! < existingScore[i]!) {\n return false;\n }\n }\n return false;\n };\n const rememberCandidateContext = (node: Declaration, activeRules: Rules): void => {\n if (!context) {\n return;\n }\n setParent(node, activeRules, context);\n candidateContexts.set(node, {\n ...context,\n rulesContext: activeRules,\n renderKey: context.renderKey ?? activeRules.renderKey\n });\n };\n const getCandidateContext = (node: Declaration, activeRules: Rules): Context | undefined => {\n return candidateContexts.get(node) ?? (\n context\n ? {\n ...context,\n rulesContext: activeRules\n }\n : context\n );\n };\n const getDeclarationOrderPath = (node: Declaration, boundaryRules: Rules): number[] | undefined => {\n const path: number[] = [];\n let current: Node | undefined = node;\n const nodeContext = getCandidateContext(node, boundaryRules);\n while (current) {\n const parent = nodeContext ? getParent(current, nodeContext) : current.parent;\n if (!parent) {\n return undefined;\n }\n if (current.index === undefined) {\n return undefined;\n }\n path.unshift(current.index);\n if (parent === boundaryRules) {\n return path;\n }\n if (!isNode(parent, N.Rules)) {\n return undefined;\n }\n current = parent;\n }\n return undefined;\n };\n const compareDeclarationsForLookup = (a: Declaration, b: Declaration): number => {\n const aPath = getDeclarationOrderPath(a, rules);\n const bPath = getDeclarationOrderPath(b, rules);\n if (aPath && bPath) {\n const length = Math.min(aPath.length, bPath.length);\n for (let i = 0; i < length; i++) {\n const diff = aPath[i]! - bPath[i]!;\n if (diff !== 0) {\n return diff;\n }\n }\n if (aPath.length !== bPath.length) {\n return aPath.length - bPath.length;\n }\n }\n const pos = comparePosition(a, b);\n return pos ?? 0;\n };\n let declCandidate = new Set<Declaration>();\n let optionalCandidates = options?.optionalCandidates ?? new Set<Declaration>();\n let rules: Rules | undefined = this.rules;\n let isPublic = false;\n let {\n searchParents = true,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n local = false,\n start,\n context\n } = options ?? {};\n if (options) {\n options.candidateContexts = candidateContexts;\n }\n\n let newReadonly: boolean | undefined = false;\n let searchChildrenOptions: FindOptions | undefined;\n // Track visited Rules nodes in the parent chain to detect circular parent chains\n const visitedRules = new Set<Rules>();\n while (rules) {\n // CRITICAL: Check for circular parent chain\n if (visitedRules.has(rules)) {\n throw new Error(`Circular parent chain detected in DeclarationRegistry.find`);\n }\n visitedRules.add(rules);\n let currentReadonly = options?.readonly || rules.options.readonly;\n newReadonly = currentReadonly;\n const invocationBinding = filterType === 'VarDeclaration'\n ? rules.getInvocationBinding(key, context)\n : undefined;\n if (invocationBinding && (!options?.filter || options.filter(invocationBinding))) {\n rememberCandidateContext(invocationBinding, rules);\n newReadonly ||= invocationBinding.options.readonly;\n if (options && newReadonly) {\n options.readonly = true;\n }\n return invocationBinding;\n }\n const registry = rules.getRegistry('declaration', context);\n registry?.indexPendingItems();\n let list: Declaration[] | undefined;\n const filter = options?.filter;\n const indexSet = registry?.index.get(key);\n if (indexSet) {\n const deduped = new Map<Node, Declaration>();\n for (const n of indexSet) {\n if (n.type === filterType && (!filter || filter(n))) {\n const identity = getCandidateIdentity(n);\n const existing = deduped.get(identity);\n if (!existing || shouldReplaceCandidate(existing, n, rules)) {\n deduped.set(identity, n);\n }\n }\n }\n for (const n of deduped.values()) {\n rememberCandidateContext(n, rules);\n (list ??= []).push(n);\n }\n }\n if (list) {\n if (list.length > 1) {\n list.sort(compareDeclarationsForLookup);\n }\n let result = registry._findClosestByStart(list, start);\n if (result) {\n rememberCandidateContext(result, rules);\n newReadonly ||= result.options.readonly;\n // Visibility determines how declarations are found:\n // - 'private': only visible from INSIDE (children looking up) or same scope,\n // NOT from outside looking in (child Rules searches).\n // - 'optional': fallback only — returned if no public match is found.\n // - 'public': immediate candidate.\n //\n // IMPORTANT: Walking UP the parent chain is always an \"inside\" lookup — the\n // search originates from a descendant of this scope, so private does NOT block.\n // Private only blocks _searchRulesChildren (outside looking in).\n const currentRulesVisibility = rules.options.rulesVisibility?.[filterType] ?? '';\n const currentRulesOwner = getCurrentParentNode(rules, context);\n const shouldPreferLexicalVar = (\n filterType === 'VarDeclaration'\n && (\n currentRulesVisibility !== 'optional'\n || currentRulesOwner?.type === 'Ruleset'\n )\n );\n if (shouldPreferLexicalVar) {\n if (options) {\n options.readonly ||= newReadonly;\n }\n return result;\n }\n if (currentRulesVisibility === 'optional') {\n optionalCandidates.add(result);\n } else {\n declCandidate.add(result);\n isPublic = true;\n }\n }\n }\n // Initialize searchedRules to prevent infinite recursion when searching child Rules\n // This is critical: if a Rules node appears in its own children, we need to track it\n const searchedRules = options?.searchedRules ?? new Set<Rules>();\n if (!searchedRules.has(rules)) {\n searchedRules.add(rules);\n }\n // CRITICAL: When searching children, we MUST set searchParents: false to prevent\n // Reuse a single child options object — update mutable fields per iteration\n // instead of spreading a new object every loop\n if (!searchChildrenOptions) {\n searchChildrenOptions = options\n ? {\n ...options,\n searchParents: false,\n readonly: newReadonly,\n candidates: declCandidate,\n searchedRules: searchedRules,\n optionalCandidates\n }\n : {\n searchParents: false,\n readonly: newReadonly,\n candidates: declCandidate,\n searchedRules: searchedRules,\n optionalCandidates\n };\n } else {\n searchChildrenOptions.readonly = newReadonly;\n }\n rules.getRegistry('declaration', context)._searchRulesChildren(key, filterType, searchChildrenOptions);\n\n // After searching the CURRENT scope (index + children), if we found public declarations,\n // sort them, find the best one (closest to start or at bottom), and return immediately.\n // Otherwise, continue up the parent scope.\n if (declCandidate.size > 0) {\n let bestResult: Declaration | undefined;\n // Use comparePosition to find the last declaration by source order\n const candidateArray = Array.from(declCandidate);\n if (candidateArray.length === 1) {\n bestResult = candidateArray[0];\n } else {\n candidateArray.sort((a, b) => {\n const order = compareDeclarationsForLookup(a, b);\n if (order !== 0) {\n return order;\n }\n const aContext = getCandidateContext(a, rules);\n const bContext = getCandidateContext(b, rules);\n const aDirect = (aContext ? getParent(a, aContext) : a.parent) === rules;\n const bDirect = (bContext ? getParent(b, bContext) : b.parent) === rules;\n if (aDirect !== bDirect) {\n return aDirect ? 1 : -1;\n }\n return 0;\n });\n bestResult = candidateArray[candidateArray.length - 1];\n }\n if (options && searchChildrenOptions?.readonly) {\n options.readonly = true;\n }\n return bestResult;\n }\n\n // If we haven't found public candidates in the current scope, continue normal parent search\n // (optional candidates are tracked but we keep searching up the parent chain)\n if (isNonImportStyleBoundary(rules)) {\n searchParents = false;\n }\n if (isPublic || !searchParents) {\n if (options && searchChildrenOptions?.readonly) {\n options.readonly = true;\n }\n const result = declCandidate.values().next().value;\n return result;\n }\n\n do {\n rules = rules?.getRegistryParent(context);\n } while (rules && rules.type !== 'Rules');\n // The start constraint only applies within the originating scope.\n // When walking up to a parent scope, drop it so declarations at any\n // position in the parent are eligible.\n start = undefined;\n }\n if (options && newReadonly) {\n options.readonly = true;\n }\n // After searching all parents, if we only have optional candidates, return the best one\n if (declCandidate.size === 0 && optionalCandidates.size > 0) {\n const optionalArray = Array.from(optionalCandidates);\n if (optionalArray.length === 1) {\n return optionalArray[0];\n }\n optionalArray.sort(compareDeclarationsForLookup);\n const optionalResult = optionalArray[optionalArray.length - 1];\n return optionalResult;\n }\n return declCandidate.values().next().value;\n }\n}\n\nexport function getDirectDeclarationsByKey(\n rules: Rules,\n key: string | undefined,\n context?: Context\n): Declaration[] {\n const children = rules.getRegistryChildren(context);\n const matches: Declaration[] = [];\n for (const child of children) {\n if (!isNode(child, N.Declaration | N.VarDeclaration)) {\n continue;\n }\n const name = child.get('name', context);\n if (key === undefined || name?.valueOf?.() === key) {\n matches.push(child);\n }\n }\n return matches;\n}\n\nfunction arraysEqual(a: string[], b: string[]) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Does `a` contain all elements of `b`? (order-independent)\n *\n * Uses linear scan instead of `Set.prototype.isSubsetOf` because\n * selector key arrays are typically 1–3 elements, where the overhead\n * of allocating a Set dominates.\n */\nfunction arrayContainsAll(a: string[], b: string[]): boolean {\n if (b.length > a.length) {\n return false;\n }\n if (b.length === 0) {\n return true;\n }\n // For small arrays, just use includes\n for (const item of b) {\n if (!a.includes(item)) {\n return false;\n }\n }\n return true;\n}\n\n/** Are `a` and `b` equal as unordered sets? See {@link arrayContainsAll}. */\nfunction arraysEqualAsSet(a: string[], b: string[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n return arrayContainsAll(a, b);\n}\n","import { Node, F_MAY_ASYNC, F_VISIBLE, F_NON_STATIC, defineType } from './node.js';\nimport { Any, type AnyRole, type AnyOptions } from './any.js';\nimport type { Context } from '../context.js';\nimport { BasicSelector } from './selector-basic.js';\nimport { CompoundSelector } from './selector-compound.js';\nimport type { Selector } from './selector.js';\nimport { PseudoSelector } from './selector-pseudo.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, serialForEach, isThenable } from '@jesscss/awaitable-pipe';\n\n// Placeholder that's very unlikely to appear in user strings\n// but is also easily typeable for tests\nexport const INTERPOLATION_PLACEHOLDER = '%%';\nconst INTERPOLATION_PLACEHOLDER_REGEXP = /%%/g;\n\nfunction shouldWrapSelectorInIs(replacement: Node): boolean {\n if (isNode(replacement, N.SelectorList)) {\n return true;\n }\n if (isNode(replacement, N.ComplexSelector)) {\n return true;\n }\n if (replacement.type === 'SelectorCapture') {\n const arg = (replacement as unknown as { value: Node }).value;\n return isNode(arg, N.SelectorList) || isNode(arg, N.ComplexSelector);\n }\n const str = String(replacement.valueOf?.() ?? replacement);\n return str.includes(',');\n}\n\nfunction getIsWrapperArg(replacement: Node): Node {\n if (replacement.type === 'SelectorCapture') {\n return (replacement as unknown as { value: Node }).value;\n }\n return replacement;\n}\n\nfunction serializeGeneratedIsWrapper(replacement: Node): string {\n const arg = getIsWrapperArg(replacement);\n const pseudo = PseudoSelector.create({ name: ':is', arg });\n pseudo.generated = true;\n return pseudo.toTrimmedString().replace(/\\n\\s*/g, ' ');\n}\n\nexport type InterpolatedValue = {\n /** String with INTERPOLATION_PLACEHOLDER placeholders */\n source: string;\n replacements: Node[];\n};\n\nexport type InterpolatedChildData = { source: string; replacements: Node[] };\n\n/**\n * Merge an interface to declare the specific types\n *\n * @todo - Instead of extending simple selector, create a selector \"wrapper\"\n * that goes around expressions and interpolated values, so that it\n * casts as a selector after evaluation.\n *\n * This would eliminate the need for the `evalToSelector` and `evalToGeneric`\n * methods, because the wrapper would handle the returned node type.\n */\nexport interface Interpolated<\n Role extends AnyRole = AnyRole\n> extends Node<InterpolatedValue, AnyOptions<Role>, InterpolatedChildData> {\n type: 'Interpolated';\n shortType: 'interpolated';\n eval(context: Context): MaybePromise<Any<Role>>;\n}\n/**\n * An interpolated value is one that contains\n * reference variables, or expressions, but\n * which MUST resolve to a node with a string value\n * (like Anonymous) when evaluated.\n *\n * @example\n * in Less:\n * - `@@foo` is an interpolated variable\n * - `--prop-@{foo}` is an interpolated property\n */\nexport class Interpolated<\n Role extends AnyRole = AnyRole\n> extends Node<InterpolatedValue, AnyOptions<Role>, InterpolatedChildData> {\n static override childKeys = ['source', 'replacements'] as const;\n\n source!: string;\n replacements!: Node[];\n\n constructor(value: InterpolatedValue, options?: AnyOptions<Role>, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.source = value.source;\n this.replacements = value.replacements;\n for (const r of this.replacements) {\n if (r instanceof Node) {\n this.adopt(r);\n }\n }\n // Interpolated nodes are always non-static and may be async\n this.addFlags(F_VISIBLE, F_MAY_ASYNC, F_NON_STATIC);\n }\n\n override clone(deep?: boolean): this {\n const replacements = deep\n ? this.replacements.map(replacement => replacement.clone(true))\n : this.replacements;\n const node = new (this.constructor as typeof Interpolated<Role>)(\n { source: this.source, replacements: [] },\n this.options ? { ...this.options } : undefined,\n this.location,\n this.treeContext\n ) as this;\n node.inherit(this);\n node.replacements = replacements;\n if (deep) {\n for (const replacement of replacements) {\n node.adopt(replacement);\n }\n }\n return node;\n }\n\n override valueOf(): string {\n return this.source;\n }\n\n private _withReplacements(replacements: Node[]): this {\n const node = new (this.constructor as typeof Interpolated<Role>)(\n { source: this.source, replacements: [] },\n this.options ? { ...this.options } : undefined,\n this.location,\n this.treeContext\n ) as this;\n node.inherit(this);\n node.replacements = replacements;\n return node;\n }\n\n replace(replacements?: Node[], options?: PrintOptions): string {\n const printOpts = getPrintOptions(options);\n const context = printOpts.context;\n const source = this.get('source', context);\n const activeReplacements = replacements ?? this.get('replacements', context);\n let output = source;\n let i = 0;\n let w = printOpts!.writer;\n INTERPOLATION_PLACEHOLDER_REGEXP.lastIndex = 0;\n output = output.replace(INTERPOLATION_PLACEHOLDER_REGEXP, () => {\n let replacement: Node | undefined;\n try {\n replacement = activeReplacements[i++];\n } catch (error: unknown) {\n throw error;\n }\n let result = '';\n if (replacement) {\n if (isNode(replacement, N.Reference)) {\n // Preserve exact interpolation reference syntax (including quoted property keys).\n result = w.capture(() => replacement.toTrimmedString(printOpts));\n } else if (isNode(replacement, N.Quoted)) {\n // Interpolated string slots merge raw string content.\n // Using valueOf() avoids re-emitting inner quote delimiters.\n result = String(replacement.valueOf());\n } else {\n result = w.capture(() => replacement!.toTrimmedString(printOpts));\n }\n if (!isNode(replacement, N.Reference)) {\n result = result.trim();\n }\n }\n return result;\n });\n\n return output;\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const result = this.replace(undefined, options);\n w.add(result, this);\n return w.getSince(mark);\n }\n\n /**\n * Can turn simple #id, .class, element or SelectorCapture into a selector.\n * Legacy \"list of mixin references\" (e.g. @var: .a, .b, .c) is not supported; use *[.a, .b, .c].\n */\n createSelector(context?: Context) {\n const source = this.get('source', context);\n const replacements = this.get('replacements', context);\n const segments = source.split(INTERPOLATION_PLACEHOLDER);\n const isWholeSelectorInterpolation = (\n replacements.length === 1\n && segments.length === 2\n && segments[0]!.trim() === ''\n && segments[1]!.trim() === ''\n );\n // For full-selector interpolation, collapse directly to the resolved selector/text.\n // Generated :is wrappers are only needed for embedded interpolation fragments.\n if (isWholeSelectorInterpolation) {\n const replacement = replacements[0]!;\n if (context && !replacement.evaluated) {\n throw new Error('Cannot create selector from un-evaluated interpolated node');\n }\n if (isNode(replacement, N.Selector)) {\n return replacement.clone(false).inherit(this) as Selector;\n }\n return new BasicSelector(replacement.toTrimmedString().trim()).inherit(this);\n }\n let output = '';\n for (let [i, replacement] of replacements.entries()) {\n if (context && !replacement.evaluated) {\n throw new Error('Cannot create selector from un-evaluated interpolated node');\n }\n let part = replacement.toTrimmedString();\n if (shouldWrapSelectorInIs(replacement)) {\n part = serializeGeneratedIsWrapper(replacement);\n }\n output += (segments[i] ?? '') + part;\n }\n // Preserve any trailing literal segment after the last interpolation placeholder.\n if (segments.length > replacements.length) {\n output += segments.slice(replacements.length).join(INTERPOLATION_PLACEHOLDER);\n }\n // Interpolated selector output can produce compound selectors (e.g. \".a#b\").\n // Preserve token boundaries so keySet/registry lookup can match correctly.\n const simpleTokens = output.match(/[#.][^#.\\s]+|[^#.\\s]+/g) ?? [output];\n if (\n simpleTokens.length > 1\n && !output.includes(':')\n && !output.includes('[')\n && !output.includes('&')\n ) {\n return new CompoundSelector(simpleTokens.map(token => new BasicSelector(token))).inherit(this);\n }\n return new BasicSelector(output).inherit(this);\n }\n\n createGeneric(context?: Context) {\n const trimmedString = this.toTrimmedString(context ? { context } : undefined);\n let any = new Any<Role>(trimmedString, { role: this.options.role }).inherit(this);\n return any;\n }\n\n /** Convenience: evaluate replacements then convert to Selector (BasicSelector or SelectorList) */\n evalToSelector(context: Context): MaybePromise<Selector> {\n const out = this._evalToInterpolated(context);\n if (isThenable(out)) {\n return (out as Promise<Interpolated<Role>>).then(node => node.createSelector(context));\n }\n return (out as Interpolated<Role>).createSelector(context);\n }\n\n override evalNode(context: Context): MaybePromise<Any> {\n const out = this._evalToInterpolated(context);\n if (isThenable(out)) {\n return (out as Promise<Interpolated<Role>>).then((node) => {\n return node.createGeneric(context);\n });\n }\n const result = (out as Interpolated<Role>).createGeneric(context);\n return result;\n }\n\n /**\n * Just evaluate replacements and return. We don't stringify yet,\n * because depending on the context, it will turn into different\n * node types.\n */\n override preEval(context: Context): MaybePromise<this> {\n if (this.preEvaluated) {\n return this;\n }\n const node = this.clone() as this;\n node.preEvaluated = true;\n const replacements = [...this.replacements];\n let changed = false;\n const maybe = serialForEach(replacements, (replacement, idx) => {\n const out = replacement.preEval(context);\n if (isThenable(out)) {\n return (out as Promise<Node>).then((result) => {\n if (result !== replacement) {\n replacements[idx] = result;\n changed = true;\n }\n });\n }\n if ((out as Node) !== replacement) {\n replacements[idx] = out as Node;\n changed = true;\n }\n return undefined;\n });\n if (isThenable(maybe)) {\n return (maybe as Promise<void>).then(() => {\n if (changed) {\n node.replacements = replacements;\n }\n return node;\n });\n }\n if (changed) {\n node.replacements = replacements;\n }\n return node;\n }\n\n _evalToInterpolated(context: Context): MaybePromise<this> {\n let node = this;\n let replacements = [...node.get('replacements', context)];\n const markEvaluated = (result: Node): Node => {\n result.evaluated = true;\n return result;\n };\n\n let maybe = serialForEach(replacements, (n, idx) => {\n const out = n.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Node>).then((result) => {\n replacements[idx] = markEvaluated(result);\n });\n }\n replacements[idx] = markEvaluated(out as Node);\n return undefined;\n });\n if (isThenable(maybe)) {\n return maybe.then(() => {\n if (node === this) {\n return this._withReplacements(replacements);\n }\n node.replacements = replacements;\n return node;\n });\n }\n if (node === this) {\n return this._withReplacements(replacements);\n }\n node.replacements = replacements;\n return node;\n }\n}\n\nexport const interpolated = defineType(Interpolated, 'Interpolated');\n","export type Operator = '+' | '-' | '*' | '/' | '%';\n\nexport function calculate(a: number, op: Operator, b: number) {\n switch (op) {\n case '+': return a + b;\n case '-': return a - b;\n case '*': return a * b;\n case '/': return a / b;\n case '%': return a % b;\n }\n}","import type { Class } from 'type-fest';\nimport { Node, F_STATIC, defineType, type NodeOptions, type OptionalLocation, type TreeContext } from './node.js';\nimport { calculate, type Operator } from './util/calculate.js';\nimport { type Context } from '../context.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport round from 'lodash-es/round.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\ntype ColorValues = [number, number, number, number] | number[];\ntype ChannelTuple = [number, string];\ntype ChannelValue = number | ChannelTuple;\ntype AlphaValue = number | ChannelTuple;\ntype RGBChannels = [ChannelValue, ChannelValue, ChannelValue];\ntype HSLChannels = [ChannelValue, ChannelValue, ChannelValue];\n\nexport enum ColorFormat {\n HEX,\n RGB,\n HSL\n}\n\nfunction clamp(v: number, max: number) {\n return Math.min(Math.max(v, 0), max);\n}\n\nfunction parseHexString(hex: string): { rgb: [number, number, number]; alpha: number } {\n let rgba: number[] = [];\n let hexValue = hex.slice(1);\n\n if (hexValue.length >= 6) {\n (hexValue.match(/.{2}/g) as RegExpMatchArray).forEach((c, i) => {\n if (i < 3) {\n rgba.push(parseInt(c, 16));\n } else {\n rgba.push(parseInt(c, 16) / 255);\n }\n });\n } else {\n hexValue.split('').forEach((c, i) => {\n if (i < 3) {\n rgba.push(parseInt(c + c, 16));\n } else {\n rgba.push(parseInt(c + c, 16) / 255);\n }\n });\n }\n\n return {\n rgb: [rgba[0]!, rgba[1]!, rgba[2]!] as [number, number, number],\n alpha: rgba.length === 3 ? 1 : rgba[3]!\n };\n}\n\nconst { isArray } = Array;\n\nexport interface ColorData {\n node?: string | Node;\n /** Legacy field; format now lives on Color options. */\n format?: ColorFormat;\n rgb?: RGBChannels;\n hsl?: HSLChannels;\n alpha?: AlphaValue;\n}\n\nexport interface ColorOptions extends NodeOptions {\n format?: ColorFormat;\n modernSyntax?: boolean;\n}\n\nexport interface Color extends Node<ColorData, ColorOptions> {\n type: 'Color';\n shortType: 'color';\n eval(context: Context): Color;\n node: string | Node | undefined;\n}\n\n/**\n * Color's `value` will store RGB, HSL, and alpha separately to avoid unnecessary conversions.\n * Conversion only happens when modifying colors or when explicitly requested.\n */\nexport class Color extends Node<ColorData, ColorOptions> {\n static override childKeys = null as null;\n\n _rgbChannels: RGBChannels | undefined;\n _hslChannels: HSLChannels | undefined;\n _alphaValue: AlphaValue | undefined;\n _nodeValue: string | Node | undefined;\n\n get node(): string | Node | undefined {\n return this._nodeValue;\n }\n\n set node(value: string | Node | undefined) {\n this._nodeValue = value;\n }\n\n constructor(\n value: ColorData | string | ColorValues,\n options?: ColorOptions,\n location?: OptionalLocation,\n context?: TreeContext\n ) {\n let colorData: ColorData;\n let colorOptions: ColorOptions = options ?? {};\n\n if (isArray(value)) {\n // Handle color array [r, g, b, a]\n const [r, g, b, a] = value as [number, number, number, number];\n colorData = {\n rgb: [r, g, b],\n alpha: a\n };\n colorOptions = { ...colorOptions, format: colorOptions.format ?? ColorFormat.RGB };\n } else if (typeof value === 'object' && value !== null && !isNode(value)) {\n // Handle ColorData object\n colorData = value as ColorData;\n\n // Validate that we have either rgb, hsl, or a node to parse\n if (!colorData.rgb && !colorData.hsl && !colorData.node) {\n throw new TypeError('Color constructor requires rgb, hsl, or node property');\n }\n if (colorData.format !== undefined && colorOptions.format === undefined) {\n colorOptions = { ...colorOptions, format: colorData.format };\n }\n } else if (typeof value === 'string') {\n // Handle hex string - parse it immediately to set RGB values\n const { rgb, alpha } = parseHexString(value);\n colorData = {\n node: value,\n rgb,\n alpha\n };\n colorOptions = { ...colorOptions, format: colorOptions.format ?? ColorFormat.HEX };\n } else {\n throw new TypeError('Color constructor requires ColorData object, hex string, or color array');\n }\n\n // Keep value focused on channels/node; rendering intent is held in options.\n colorData.format = undefined;\n super(colorData, colorOptions, location, context);\n this._rgbChannels = colorData.rgb;\n this._hslChannels = colorData.hsl;\n this._alphaValue = colorData.alpha;\n this._nodeValue = colorData.node;\n this.addFlag(F_STATIC);\n }\n\n override clone(deep?: boolean): this {\n const options = this._meta?.options;\n const colorData: any = {\n node: this._nodeValue,\n rgb: this._rgbChannels ? [...this._rgbChannels] : undefined,\n hsl: this._hslChannels ? [...this._hslChannels] : undefined,\n alpha: this._alphaValue\n };\n const newNode = new (this.constructor as Class<this>)(\n colorData,\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n );\n newNode.inherit(this);\n return newNode;\n }\n\n override compare(b: Node, context?: Context): 0 | 1 | -1 | undefined {\n if (!(b instanceof Color)) {\n return super.compare(b, context);\n }\n\n const aRgba = [...this._rgb, this._alpha] as const;\n const bRgba = [...b._rgb, b._alpha] as const;\n\n for (let i = 0; i < aRgba.length; i++) {\n const cmp = Node.numericCompare(aRgba[i]!, bRgba[i]!);\n if (cmp !== 0) {\n return cmp;\n }\n }\n\n return 0;\n }\n\n private normalizeChannelValue(value: unknown): ChannelValue {\n if (typeof value === 'number') {\n return value;\n }\n if (isNode(value, N.Dimension)) {\n const { number, unit } = value;\n return unit ? [number, unit] : number;\n }\n return value as ChannelValue;\n }\n\n private hueToDegrees(value: ChannelValue): number {\n value = this.normalizeChannelValue(value) as ChannelValue;\n if (typeof value === 'number') {\n return value;\n }\n const [number, unit] = value;\n switch (unit) {\n case 'turn':\n return number * 360;\n case 'rad':\n return number * (180 / Math.PI);\n case 'grad':\n return number * 0.9;\n default:\n return number;\n }\n }\n\n private percentToUnit(value: ChannelValue): number {\n value = this.normalizeChannelValue(value) as ChannelValue;\n if (typeof value === 'number') {\n return value;\n }\n const [number, unit] = value;\n return unit === '%' ? number / 100 : number;\n }\n\n private rgbChannelToNumber(value: ChannelValue): number {\n value = this.normalizeChannelValue(value) as ChannelValue;\n if (typeof value === 'number') {\n return value;\n }\n const [number, unit] = value;\n return unit === '%' ? (number * 255) / 100 : number;\n }\n\n private alphaToNumber(value: AlphaValue): number {\n value = this.normalizeChannelValue(value) as AlphaValue;\n if (typeof value === 'number') {\n return value;\n }\n const [number, unit] = value;\n return unit === '%' ? number / 100 : number;\n }\n\n private getSerializedAlphaText(compress: boolean): string {\n const alphaSource = this._alphaValue;\n if (compress && this.alpha === 0) {\n return '0';\n }\n const normalizedAlphaSource = this.normalizeChannelValue(alphaSource) as AlphaValue;\n if (Array.isArray(normalizedAlphaSource)) {\n const [alphaValue, alphaUnit] = normalizedAlphaSource;\n return `${round(alphaValue, 8)}${alphaUnit}`;\n }\n return `${this.alpha}`;\n }\n\n private getSerializedRgbText(): [string, string, string] {\n const rgbSource = this._rgbChannels;\n if (!rgbSource) {\n const [r, g, b] = this.rgb;\n return [`${r}`, `${g}`, `${b}`];\n }\n return rgbSource.map((channel, idx) => {\n channel = this.normalizeChannelValue(channel) as ChannelValue;\n if (typeof channel === 'number') {\n return `${this.rgb[idx]!}`;\n }\n const [number, unit] = channel;\n if (unit === '%') {\n return `${round(clamp(number, 100), 8)}%`;\n }\n return `${this.rgb[idx]!}`;\n }) as [string, string, string];\n }\n\n /**\n * Get RGB values, converting from HSL if needed.\n * Returns clamped values (0-255) for better developer experience.\n * For internal calculations, use _rgb instead.\n */\n get rgb(): [number, number, number] {\n const [r, g, b] = this._rgb;\n return [\n clamp(round(r), 255),\n clamp(round(g), 255),\n clamp(round(b), 255)\n ];\n }\n\n /**\n * Internal getter for unclamped RGB values.\n * Use this for calculations and conversions.\n */\n get _rgb(): [number, number, number] {\n if (this._rgbChannels) {\n const [r, g, b] = this._rgbChannels;\n return [\n this.rgbChannelToNumber(r),\n this.rgbChannelToNumber(g),\n this.rgbChannelToNumber(b)\n ];\n }\n\n if (this._hslChannels) {\n // Convert HSL to RGB\n const [h, s, l] = this._hslChannels;\n const hue = this.hueToDegrees(h) / 360;\n const sat = this.percentToUnit(s);\n const light = this.percentToUnit(l);\n\n let r, g, b;\n\n if (sat === 0) {\n r = g = b = light;\n } else {\n const hue2rgb = (p: number, q: number, t: number) => {\n if (t < 0) {\n t += 1;\n }\n if (t > 1) {\n t -= 1;\n }\n if (t < 1 / 6) {\n return p + (q - p) * 6 * t;\n }\n if (t < 1 / 2) {\n return q;\n }\n if (t < 2 / 3) {\n return p + (q - p) * (2 / 3 - t) * 6;\n }\n return p;\n };\n\n const q = light < 0.5 ? light * (1 + sat) : light + sat - light * sat;\n const p = 2 * light - q;\n\n r = hue2rgb(p, q, hue + 1 / 3);\n g = hue2rgb(p, q, hue);\n b = hue2rgb(p, q, hue - 1 / 3);\n }\n\n // Convert from 0-1 to 0-255 range\n const rgb = [r * 255, g * 255, b * 255] as [number, number, number];\n this._rgbChannels = rgb;\n this._hslChannels = undefined;\n return rgb;\n }\n\n // If value has a node that's a string, parse it as hex\n if (this._nodeValue && typeof this._nodeValue === 'string') {\n const { rgb, alpha } = parseHexString(this._nodeValue);\n this._rgbChannels = rgb;\n this._alphaValue = alpha;\n this._hslChannels = undefined;\n return rgb;\n }\n\n throw new TypeError('Cannot convert color value to rgb');\n }\n\n set rgb(rgb: [number, number, number] | RGBChannels) {\n this._rgbChannels = rgb;\n this._hslChannels = undefined;\n }\n\n /**\n * Get HSL values, converting from RGB if needed.\n * Returns clamped values (hue: 0-360, saturation/lightness: 0-1) for better developer experience.\n * For internal calculations, use _hsl instead.\n */\n get hsl(): [number, number, number] {\n const [h, s, l] = this._hsl;\n return [\n ((h % 360) + 360) % 360, // Wrap hue to 0-360\n clamp(s, 1), // Clamp saturation to 0-1\n clamp(l, 1) // Clamp lightness to 0-1\n ];\n }\n\n /**\n * Internal getter for unclamped HSL values.\n * Use this for calculations and conversions.\n */\n get _hsl(): [number, number, number] {\n if (this._hslChannels) {\n const [h, s, l] = this._hslChannels;\n return [\n this.hueToDegrees(h),\n this.percentToUnit(s),\n this.percentToUnit(l)\n ];\n }\n\n // Convert RGB to HSL\n let [r, g, b] = this._rgb;\n // Convert RGB from 0-255 range to 0-1 range for HSL calculation\n r = r / 255;\n g = g / 255;\n b = b / 255;\n\n let max = Math.max(r, g, b);\n let min = Math.min(r, g, b);\n let h: number;\n let s: number;\n let l = (max + min) / 2;\n\n if (max === min) {\n h = s = 0;\n } else {\n let d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r: {\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n }\n case g: {\n h = (b - r) / d + 2;\n break;\n }\n case b: {\n h = (r - g) / d + 4;\n break;\n }\n }\n h! /= 6;\n }\n\n const hsl = [h! * 360, s, l] as [number, number, number];\n this._hslChannels = hsl;\n this._rgbChannels = undefined;\n return hsl;\n }\n\n set hsl(hsl: [number, number, number] | HSLChannels) {\n this._hslChannels = hsl;\n this._rgbChannels = undefined;\n }\n\n /**\n * Get alpha value.\n * Returns clamped value (0-1) for better developer experience.\n * For internal calculations, use _alpha instead.\n */\n get alpha(): number {\n return clamp(this._alpha, 1);\n }\n\n /**\n * Internal getter for unclamped alpha value.\n * Use this for calculations and conversions.\n */\n get _alpha(): number {\n const alpha = this._alphaValue ?? 1;\n return this.alphaToNumber(alpha);\n }\n\n set alpha(alpha: AlphaValue) {\n this._alphaValue = alpha;\n }\n\n /**\n * Get RGBA values for backward compatibility.\n * Returns clamped values for better developer experience.\n */\n get rgba(): ColorValues {\n return [...this.rgb, this.alpha];\n }\n\n set rgba(rgba: ColorValues) {\n const [r, g, b, a] = rgba as [number, number, number, number];\n this._rgbChannels = [r, g, b];\n this._alphaValue = a;\n this._hslChannels = undefined;\n }\n\n /**\n * Get HSLA values for backward compatibility.\n * Returns clamped values for better developer experience.\n */\n get hsla(): [number, number, number, number] {\n return [...this.hsl, this.alpha];\n }\n\n set hsla(hsla: [number, number, number, number]) {\n const [h, s, l, a] = hsla;\n this._hslChannels = [h, s, l];\n this._alphaValue = a;\n this._rgbChannels = undefined;\n }\n\n toHSL(): [number, number, number] {\n return this.hsl;\n }\n\n toHex(): string {\n const values = this.rgb;\n let alpha = this.alpha;\n if (alpha < 1) {\n values.push(round(alpha * 255));\n }\n let hex = '#' + values.map(function(c) {\n let hex = c.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n }).join('');\n return hex;\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const compress = Boolean(options.compress);\n\n // If value has a node that's a Node, serialize it directly\n if (this._nodeValue && isNode(this._nodeValue)) {\n return this._nodeValue.toTrimmedString(options);\n }\n\n // If value has a node that's a string, output it as-is\n if (this._nodeValue && typeof this._nodeValue === 'string') {\n w.add(this._nodeValue, this);\n return w.getSince(mark);\n }\n\n // Handle format-based serialization\n const format = this.options.format ?? ColorFormat.HEX;\n if (format === ColorFormat.RGB) {\n const useModernSyntax = Boolean(this.options.modernSyntax || compress);\n const rgbText = this.getSerializedRgbText();\n const alphaText = this.getSerializedAlphaText(compress);\n if (useModernSyntax) {\n if (this.alpha < 1) {\n w.add('rgb(', this);\n w.add(`${rgbText[0]} ${rgbText[1]} ${rgbText[2]} / ${alphaText}`);\n w.add(')');\n } else {\n w.add('rgb(', this);\n w.add(`${rgbText[0]} ${rgbText[1]} ${rgbText[2]}`);\n w.add(')');\n }\n } else {\n if (this.alpha < 1) {\n w.add('rgba(', this);\n w.add(`${rgbText[0]}, ${rgbText[1]}, ${rgbText[2]}, ${alphaText}`);\n w.add(')');\n } else {\n w.add('rgb(', this);\n w.add(`${rgbText[0]}, ${rgbText[1]}, ${rgbText[2]}`);\n w.add(')');\n }\n }\n return w.getSince(mark);\n } else if (format === ColorFormat.HSL) {\n const [h, s, l] = this.hsl;\n const hueSource = this._hslChannels?.[0];\n const alphaText = this.getSerializedAlphaText(compress);\n const authoredHueUnit = Array.isArray(hueSource) ? hueSource[1] : '';\n const roundedHue = round(h, 8);\n const canDropHueUnitForCompression = compress && roundedHue === 0;\n const modernHueUnit = canDropHueUnitForCompression\n ? ''\n : (authoredHueUnit || 'deg');\n const preservedHueUnit = canDropHueUnitForCompression ? '' : authoredHueUnit;\n const useModernSyntax = Boolean(this.options.modernSyntax || compress);\n if (useModernSyntax) {\n if (this.alpha < 1) {\n w.add('hsl(', this);\n w.add(`${roundedHue}${modernHueUnit} ${round(s * 100, 8)}% ${round(l * 100, 8)}% / ${alphaText}`);\n w.add(')');\n } else {\n w.add('hsl(', this);\n w.add(`${roundedHue}${modernHueUnit} ${round(s * 100, 8)}% ${round(l * 100, 8)}%`);\n w.add(')');\n }\n } else {\n if (this.alpha < 1) {\n w.add('hsla(', this);\n w.add(`${roundedHue}${preservedHueUnit}, ${round(s * 100, 8)}%, ${round(l * 100, 8)}%, ${alphaText}`);\n w.add(')');\n } else {\n w.add('hsl(', this);\n w.add(`${roundedHue}${preservedHueUnit}, ${round(s * 100, 8)}%, ${round(l * 100, 8)}%`);\n w.add(')');\n }\n }\n return w.getSince(mark);\n }\n\n // Default to hex\n w.add(this.toHex(), this);\n return w.getSince(mark);\n }\n\n override operate(b: Node, op: Operator, context?: Context | undefined): Color {\n let aRGB = this._rgb;\n let newColorValues: [number, number, number];\n let newAlpha = this._alpha;\n\n if (isNode(b, N.Dimension)) {\n const { number: bVal, unit: bUnit } = b;\n const unitMode = context?.opts?.unitMode ?? 'loose';\n const isStrictLikeMode = unitMode === 'strict' || unitMode === 'preserve';\n if (bUnit && isStrictLikeMode) {\n throw new TypeError(`Cannot convert \"${b}\" to a color`);\n }\n // Apply operation to each RGB component with the number\n newColorValues = aRGB.map(a => calculate(a, op, bVal)) as [number, number, number];\n } else if (b instanceof Color) {\n // Color-to-color operation\n let bRGB = b._rgb;\n newColorValues = aRGB.map((a, i) => calculate(a, op, bRGB[i]!)) as [number, number, number];\n newAlpha = this._alpha * (1 - b._alpha) + b._alpha;\n } else {\n throw new TypeError(`Cannot operate on ${b.type}`);\n }\n\n // Create new color with preserved data\n const newColor = new Color({\n rgb: newColorValues,\n alpha: newAlpha\n // Don't preserve HSL - new RGB values represent a new color\n }, {\n format: this.options.format,\n modernSyntax: this.options.modernSyntax\n }).inherit(this);\n\n return newColor;\n }\n}\n\nexport const color = defineType(Color, 'Color');\n","import { Node, defineType } from './node.js';\n\n/**\n * A plain JS object.\n */\nexport interface JsObject {\n type: 'JsObject';\n shortType: 'jsobj';\n}\n\nexport class JsObject extends Node<Record<string, any>> {\n static override childKeys = null as null;\n\n value!: Record<string, any>;\n\n constructor(value: Record<string, any>, options?: any, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.value = value;\n }\n}\n\nexport const jsobj = defineType(JsObject, 'JsObject', 'jsobj');","import type { Node } from '../node.js';\nimport { Nil } from '../nil.js';\nimport { List } from '../list.js';\n// Dimension and Num are NOT imported here to break circular dependency:\n// dimension.ts → color.ts → call.ts → cast.ts → dimension.ts\n// Instead, we use createRequire to access them synchronously at runtime\nimport { Any } from '../any.js';\nimport { Color } from '../color.js';\nimport { JsFunction } from '../js-function.js';\nimport { JsObject } from '../js-object.js';\nimport { Bool } from '../bool.js';\nimport { isNode } from './is-node.js';\nimport { isPlainObject } from './collections.js';\nimport { createRequire } from 'node:module';\n\nconst { isArray } = Array;\n\n// Create a synchronous require function for ES modules\nconst require = createRequire(import.meta.url);\n\n// Lazy getters for Dimension and Num to break circular dependency\n// These use require() to access modules at runtime, not at module load time\n// By the time cast() is called, dimension.ts and number.ts will be fully loaded\nfunction getDimension() {\n // Use require() to access module at runtime - breaks circular dependency at module load time\n return require('../dimension.js').Dimension;\n}\n\nfunction getNum() {\n // Use require() to access module at runtime - breaks circular dependency at module load time\n return require('../number.js').Num;\n}\n\nfunction getNodeType(value: any): Node {\n if (isNode(value)) {\n return value;\n }\n if (value === undefined || value === null) {\n return new Nil();\n }\n if (typeof value === 'boolean') {\n return new Bool(value);\n }\n if (typeof value === 'function') {\n // Hmm, the LLM added this, is it needed?\n // Preserve function options (e.g., params metadata from getFunctionFromMixins)\n const options = (value as Function & { options?: Record<string, unknown> }).options;\n return new JsFunction(value, options);\n }\n if (isPlainObject(value)) {\n return new JsObject(value);\n }\n if (isArray(value)) {\n return new List(value.map(val => cast(val)));\n }\n if (value.constructor === Number) {\n const Num = getNum();\n return new Num(value as unknown as number);\n }\n if (typeof value === 'string') {\n if (value.startsWith('#')) {\n return new Color(value);\n } else {\n let result = value.match(/^(\\d*(?:\\.\\d+))([a-z]*)$/i);\n if (result) {\n const Dimension = getDimension();\n return new Dimension({ number: parseFloat(result[1]!), unit: result[2] });\n }\n }\n }\n return new Any(value.toString());\n}\n\n/**\n * Casts a primitive JavaScript value to a Jess node\n * (if not already).\n *\n * @example\n * cast(area(5))\n */\nexport function cast(value: any): Node {\n const node = getNodeType(value);\n /**\n * If converting from a primitive, then\n * the value should be considered evaluated.\n */\n // Cast from primitive — F_STATIC on Any/Num/etc prevents re-eval.\n return node;\n}","import { CALLER, CANONICAL, defineType, Node, F_MAY_ASYNC, F_VISIBLE, F_NON_STATIC, type OptionalLocation } from './node.js';\nimport type { Context, TreeContext } from '../context.js';\nimport { cast } from './util/cast.js';\nimport type { FindOptions } from './util/registry-utils.js';\nimport { Any, type AnyRole, Keyword } from './any.js';\nimport { Selector } from './selector.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport type { Call } from './call.js';\nimport type { Quoted } from './quoted.js';\nimport { atIndex } from './util/collections.js';\nimport type { Num } from './number.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { isThenable, type MaybePromise, pipe } from '@jesscss/awaitable-pipe';\nimport { getFunctionFromMixins } from './rules.js';\nimport type { MixinEntry, Rules } from './rules.js';\nimport type { Interpolated } from './interpolated.js';\nimport type { Ruleset } from './ruleset.js';\nimport type { Mixin } from './mixin.js';\nimport type { Declaration } from './declaration.js';\nimport type { Color } from './color.js';\nimport type { VarDeclaration } from './declaration-var.js';\nimport {\n isTopLevelVarDeclaration,\n getDependency,\n getParent,\n setParent,\n getSourceParent,\n setSourceParent,\n setDependency\n} from './util/field-helpers.js';\nimport { getCurrentParentNode } from './util/selector-utils.js';\n\n/**\n * The type is determined by syntax\n * and location.\n * e.g. in Jess\n * - `$foo` refers to a variable\n * - `$.foo` or `$target.foo` is a named member lookup (variable or property)\n * - `$[foo]` or `$target[foo]` is a braced variable reference\n * - `$['foo']` or `$target['foo']` is a braced property reference\n * - `$[$var]` is a variable member name lookup\n * - `$foo[0]` is an index lookup\n * - in `$|.foo()`, `.foo` is a mixin\n * - in `$foo|.mixin()`, `.mixin` is a mixin in `$foo`\n * - Resolution:\n * - `$` searches scope,\n * - `$^` searches in declaration order\n * in Less\n * - `@foo` refers to a variable\n * - `$foo` refers to a property\n * - `.foo` or `#foo` refers to a mixin\n */\nexport type ReferenceValue = {\n target?: Reference | Call | undefined;\n key:\n string\n | string[]\n | Node\n | Any\n | number // $[0] or $.0\n | Num // $.key or $[key] or $*key\n | Quoted // $['key']\n | Selector // $*(.selector)\n | Reference // $.key\n | Interpolated; // @{variable} interpolation\n};\n\nexport type ReferenceOptions = {\n /**\n * What kind of lookup are we doing?\n */\n type?: 'index' | 'declaration' | 'variable' | 'property' | 'function' | 'mixin' | 'ruleset' | 'mixin-ruleset';\n /**\n * Resolution strategy:\n * - 'scope': Search in scope (Less-style, default)\n * - 'linear': Search linearly from definition position (Sass-style for regular code)\n * - 'call-time': Search linearly from call site position (Sass-style for mixins/functions)\n */\n resolution?: 'scope' | 'linear' | 'call-time';\n /**\n * Optional references just resolve to the string\n * representation if the fallback value is set to true.\n *\n * @note - Used by Less for function references\n */\n fallbackValue?: Node | true;\n filter?: (node: Node) => boolean;\n role?: AnyRole;\n /** Internal: preserve lexical start-bound lookup for synthetic refs such as `+:` normalization. */\n respectStart?: boolean;\n};\nconst { isArray } = Array;\n\n/**\n * Extract mixin reference keys from a selector in document order,\n * skipping combinators. For `#theme > .mixin`, returns `[\"#theme\", \".mixin\"]`.\n *\n * Must preserve the original selector child order (not bitset order)\n * so that MixinRegistry lookup uses the correct startKey.\n */\nfunction getSelectorReferenceKeys(selector: Selector): string[] {\n const value = 'value' in selector ? selector.value : undefined;\n if (isArray(value)) {\n const keys: string[] = [];\n for (const child of value) {\n if (isNode(child, N.Combinator)) {\n continue;\n }\n if (isNode(child, N.Selector)) {\n keys.push(...getSelectorReferenceKeys(child as Selector));\n } else {\n const val = String(child.valueOf());\n if (val) {\n keys.push(val);\n }\n }\n }\n return keys;\n }\n const val = String(selector.valueOf());\n return val ? [val] : [];\n}\n\nfunction normalizeSelectorPathKey(\n key: string,\n type: ReferenceOptions['type']\n): string | string[] {\n if (type !== 'mixin' && type !== 'ruleset' && type !== 'mixin-ruleset') {\n return key;\n }\n if (key.includes(' ') || key.includes('>') || key.includes('+') || key.includes('~') || key.includes('||')) {\n return key;\n }\n const parts = key.match(/[.#][^.#\\s>+~|]+/g);\n if (parts && parts.length > 1 && parts.join('') === key) {\n return parts;\n }\n return key;\n}\n\nfunction isInsideSelectorCapture(node: Node | undefined, context?: Context): boolean {\n let cursor: Node | undefined = node;\n while (cursor) {\n if (cursor.type === 'SelectorCapture') {\n return true;\n }\n cursor = context ? getLookupParentNode(cursor, context) : cursor.parent;\n }\n return false;\n}\n\nfunction getLookupParentNode(node: Node, context: Context): Node | undefined {\n return getParent(node, context);\n}\n\nfunction getStateRulesParent(node: Node, context: Context): Rules | undefined {\n let possibleRules: Node | undefined = getLookupParentNode(node, context);\n while (possibleRules && possibleRules.type !== 'Rules') {\n possibleRules = getLookupParentNode(possibleRules, context);\n }\n return possibleRules as Rules | undefined;\n}\n\nfunction getNodeScopedParent(node: Node, context: Context): Node | undefined {\n return getParent(node, {\n ...context,\n renderKey: undefined,\n rulesContext: undefined\n });\n}\n\nfunction getSourceRulesParent(node: Node, context: Context): Rules | undefined {\n let possibleRules: Node | undefined = getNodeScopedParent(node, context);\n while (possibleRules && possibleRules.type !== 'Rules') {\n possibleRules = getNodeScopedParent(possibleRules, context);\n }\n return possibleRules as Rules | undefined;\n}\n\nfunction getStateSourceRulesParent(node: Node, context: Context): Rules | undefined {\n let current: Node | undefined = node;\n let sourceParent = getSourceParent(node, context);\n while (current && !sourceParent) {\n current = getLookupParentNode(current, context);\n sourceParent = current ? getSourceParent(current, context) : undefined;\n }\n if (sourceParent && isNode(sourceParent, N.Rules)) {\n return sourceParent as Rules;\n }\n return sourceParent ? getSourceRulesParent(sourceParent, context) : undefined;\n}\n\nfunction getCallerParentNode(node: Node, context: Context): Node | undefined {\n let current: Node | undefined = node;\n while (current) {\n const callerParent = current.parentEdges?.get(CALLER);\n if (callerParent) {\n return callerParent;\n }\n current = getLookupParentNode(current, context);\n }\n return undefined;\n}\n\nfunction getCallerRulesParent(node: Node, context: Context): Rules | undefined {\n const callerParent = getCallerParentNode(node, context);\n if (callerParent && isNode(callerParent, N.Rules)) {\n return callerParent as Rules;\n }\n return callerParent ? getStateRulesParent(callerParent, context) : undefined;\n}\n\nfunction shouldAnchorResolvedReferenceResult(\n result: Node,\n context: Context\n): boolean {\n if ((result.nodeType & (N.Mixin | N.Ruleset | N.Rules | N.Func | N.JsFunction)) !== 0) {\n return getSourceParent(result, context) === undefined;\n }\n return true;\n}\n\nfunction anchorResolvedReferenceResult<T extends Node>(\n result: T,\n sourceReference: Node,\n context: Context\n): T {\n if (shouldAnchorResolvedReferenceResult(result, context)) {\n setSourceParent(result, sourceReference, context);\n }\n return result;\n}\n\nexport type ReferenceChildData = {\n target: Reference | Call | undefined;\n key: ReferenceValue['key'];\n};\n\n/**\n * This is a variable or property reference,\n * which can itself contain a reference (a variable variable).\n */\nexport interface Reference {\n type: 'Reference';\n shortType: 'ref';\n}\nexport class Reference extends Node<ReferenceValue, ReferenceOptions, ReferenceChildData> {\n static override childKeys = ['target', 'key'] as const;\n\n target: Reference | Call | undefined;\n key!: ReferenceValue['key'];\n\n constructor(value: ReferenceValue | string, options?: ReferenceOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n if (typeof value === 'string') {\n value = { key: value };\n }\n super(value, options, location, treeContext);\n this.target = value.target;\n this.key = value.key;\n if (this.target instanceof Node) {\n this.adopt(this.target);\n }\n if (this.key instanceof Node) {\n this.adopt(this.key);\n }\n // References are always non-static and may be async\n this.addFlags(F_MAY_ASYNC, F_VISIBLE, F_NON_STATIC);\n }\n\n override preEval(context: Context): MaybePromise<Node> {\n if (this.preEvaluated) {\n return this;\n }\n const node = this.clone();\n node.preEvaluated = true;\n if (this.parentEdges) {\n node.parentEdges = new Map(this.parentEdges);\n }\n const out = node.forEachNode(child => child.preEval(context), context);\n if (isThenable(out)) {\n return (out as Promise<void>).then(() => node);\n }\n return node;\n }\n\n override valueOf() {\n return '';\n }\n\n /**\n * @note - A reference doesn't render `$` (unless it has a target);\n * that's managed by the parent expression.\n */\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n let { type = 'variable', resolution, fallbackValue, role } = this.options;\n const context = options.context;\n const target = this.get('target', context);\n const key = this.get('key', context);\n const emitKey = (k: any) => {\n if (typeof k === 'string' || typeof k === 'number') {\n w.add(String(k), this);\n } else if (k instanceof Node) {\n k.toString(options);\n } else if (isArray(k)) {\n w.add(k.map(k => String(k)).join(''));\n } else {\n w.add(String(k));\n }\n };\n if (target) {\n target.toString(options);\n }\n if (resolution === 'linear') {\n w.add('^');\n } else if (resolution === 'call-time') {\n w.add('~');\n }\n /**\n * Reference serialization forms:\n * 1. `$[key]` — braced variable reference (or `$target[key]` with a target)\n * 2. `$['key']` — braced property reference (or `$target['key']` with a target)\n * 3. `$.key` or `$target.key` — dot syntax for named member lookup (variable or property)\n * 4. `$[$var]` — variable member name lookup (key is itself a reference)\n * 5. `$[0]` — index (or `$target[0]` with a target)\n * 6. `$[-1]` — negative index\n */\n if (role === 'ident' && (type === 'variable' || type === 'property') && !target) {\n w.add('$[');\n emitKey(key);\n w.add(']');\n return w.getSince(mark);\n }\n switch (type) {\n case 'index':\n if (!target) {\n w.add('$');\n }\n w.add('[');\n emitKey(key);\n w.add(']');\n break;\n case 'variable':\n if (target) {\n // Braced variable: $target[key]\n w.add('[');\n emitKey(key);\n w.add(']');\n } else {\n w.add('$');\n emitKey(key);\n }\n break;\n case 'declaration':\n // Dot syntax for named member lookup: $.key or $target.key\n if (!target) {\n w.add('$');\n }\n w.add('.');\n emitKey(key);\n break;\n case 'property':\n // Braced property: $['key'] or $target['key']\n if (!target) {\n w.add('$');\n }\n w.add('[\\'');\n emitKey(key);\n w.add('\\']');\n break;\n case 'mixin':\n // If this mixin reference has a target (e.g. `ns.foo`), render it as a scoped lookup:\n // `ns > foo`. Without target, keep the legacy mixin marker form (`|foo`).\n w.add(target ? ' > ' : '|');\n emitKey(key);\n break;\n\n /** @todo - remove? This should be a selector capture node I think */\n case 'ruleset':\n w.add('*(');\n emitKey(key);\n w.add(')');\n break;\n case 'mixin-ruleset':\n w.add('*');\n emitKey(key);\n break;\n }\n if (fallbackValue === true) {\n w.add('?');\n }\n return w.getSince(mark);\n }\n\n /**\n * We don't need to mark evaluated, because a reference\n * should never resolve to itself\n */\n override evalNode(context: Context): MaybePromise<Node> {\n const stripBoundaryPathInPlace = (\n node: Node,\n boundary: 'leading' | 'trailing'\n ): void => {\n if (boundary === 'leading') {\n node.pre = undefined;\n } else {\n node.post = undefined;\n }\n if (!isNode(node, N.Sequence | N.List)) {\n return;\n }\n const value = (node as unknown as { value: Node[] }).value;\n const index = boundary === 'leading' ? 0 : value.length - 1;\n const child = value[index];\n if (!(child instanceof Node)) {\n return;\n }\n const childClone = child.clone(false, undefined, context);\n value[index] = childClone;\n setParent(childClone, node, context);\n stripBoundaryPathInPlace(childClone, boundary);\n };\n\n const materializeResolvedValue = <T extends Node>(node: T): T => {\n const out = node.clone(false, undefined, context) as T;\n if (isNode(out, N.Sequence | N.List)) {\n stripBoundaryPathInPlace(out, 'leading');\n stripBoundaryPathInPlace(out, 'trailing');\n }\n return out;\n };\n\n let target = this.get('target', context);\n let key = this.get('key', context);\n let { type, fallbackValue, filter: originalFilter } = this.options;\n // Track reference chain for clearing remainders at outermost level\n context.pushReference();\n // Prefer the *current* evaluation rules context (mixin call-time scope) over the lexical rulesParent.\n // This is critical for mixin parameters (e.g. `@fallback`) which are registered onto the call-time\n // wrapper `Rules` and should be visible inside nested at-rule preludes.\n const activeRulesParent = getStateRulesParent(this, context);\n const activeSourceRulesParent = getStateSourceRulesParent(this, context);\n const activeCallerRulesParent = getCallerRulesParent(this, context);\n const lookupSourceRulesParent = context.lookupScope\n ? getStateSourceRulesParent(context.lookupScope, context)\n : undefined;\n const lookupCallerRulesParent = context.lookupScope\n ? getCallerRulesParent(context.lookupScope, context)\n : undefined;\n const sourceReference = this.sourceNode as Node;\n let resolvedTarget = target\n ? target.eval(context)\n : (\n type === 'property'\n ? activeRulesParent ?? context.rulesContext\n : context.rulesContext ?? activeRulesParent\n );\n const result = pipe(\n () => {\n if (isThenable(resolvedTarget)) {\n return (resolvedTarget as Promise<any>).then(result => result);\n }\n return resolvedTarget;\n },\n (resolvedTarget) => {\n let out: any;\n try {\n out = isNode(key) ? key.eval(context) : key;\n } catch (err: unknown) {\n throw err;\n }\n if (isThenable(out)) {\n return out.then((k: any) => {\n // If key is a Selector (CompoundSelector, ComplexSelector, etc.), extract keySet as array\n if (isNode(k, N.Selector)) {\n const keyArray = getSelectorReferenceKeys(k as Selector);\n return [resolvedTarget, keyArray] as [any, string[]];\n }\n // If k is already an array, preserve it\n if (isArray(k)) {\n return [resolvedTarget, k] as [any, string[]];\n }\n return [resolvedTarget, k.valueOf()] as [any, string];\n });\n }\n // If key is a Selector (CompoundSelector, ComplexSelector, etc.), extract keySet as array\n if (isNode(out, N.Selector)) {\n const keyArray = getSelectorReferenceKeys(out as Selector);\n return [resolvedTarget, keyArray] as [any, string[]];\n }\n // If key is already an array, preserve it\n if (isArray(out)) {\n return [resolvedTarget, out] as [any, string[]];\n }\n const normalizedKey = typeof (isNode(out) ? out.valueOf() : out) === 'string'\n ? normalizeSelectorPathKey(String(isNode(out) ? out.valueOf() : out), type)\n : (isNode(out) ? out.valueOf() : out);\n return [resolvedTarget, normalizedKey] as [any, string];\n },\n ([resolvedTarget, valueKey]) => {\n /**\n * If we don't have rules yet, assume that this node\n * was an ambiguous reference to a mixin (such as a valid color\n * or an interpolated identifier). In that case, try to resolve\n * it as a reference to a mixin.\n *\n * (We have to do this for Less.)\n */\n if (resolvedTarget instanceof Node) {\n if (!isNode(resolvedTarget, N.Rules | N.Ruleset | N.JsFunction | N.Mixin)) {\n let targetKey = isNode(resolvedTarget as Node, N.Color) ? String((resolvedTarget as Color)._nodeValue) : (resolvedTarget as Node).valueOf();\n if (typeof targetKey === 'string') {\n let ref = new Reference(targetKey, { type: 'mixin-ruleset' });\n this.adopt(ref, context);\n return Promise.all([\n ref.eval(context),\n valueKey\n ]);\n }\n }\n }\n return [resolvedTarget, valueKey] as [any, string | string[]];\n },\n ([resolvedTarget, valueKey]) => {\n /**\n * If we're looking something up on a function, we presume\n * it needs to be called first, and that it has no arguments.\n */\n if (isNode(resolvedTarget, N.JsFunction)) {\n const jsResult = ((resolvedTarget as any).value as (...args: any[]) => any).call(context);\n if (isThenable(jsResult)) {\n return (jsResult as Promise<any>).then((result) => {\n return [result, valueKey] as [any, string | string[]];\n });\n } else {\n resolvedTarget = jsResult;\n return [resolvedTarget, valueKey] as [any, string | string[]];\n }\n }\n\n /**\n * If we're looking something up on a mixin or ruleset (namespace lookup),\n * we need to evaluate its rules to get the Rules node first.\n *\n * Before evaluating, check if this Ruleset/Mixin has matched keys from a previous partial match\n * (for chained calls like .jo.ki() where .jo finds .jo.ki with matched keys [\".jo\"])\n * We accumulate the new key and use registry lookup to verify the compound match\n */\n if (isNode(resolvedTarget, N.Mixin | N.Ruleset)) {\n const targetRules = isNode(resolvedTarget, N.Ruleset)\n ? (resolvedTarget as Ruleset).enterRules(context)\n : (resolvedTarget as Mixin)\n .get('rules', context)\n .withRenderOwner(\n resolvedTarget as Node,\n (resolvedTarget as Node).renderKey ?? context.renderKey,\n context\n );\n return [targetRules, valueKey] as [Node, string | string[]];\n }\n\n return [resolvedTarget, valueKey] as [Node, string | string[]];\n },\n ([resolvedTarget, valueKey]) => {\n originalFilter ??= () => true;\n const isInterpolatedVariable =\n this.options.type === 'variable'\n && getLookupParentNode(this, context)?.type === 'Interpolated';\n const filter = (n: Node) => {\n const passesOriginal = originalFilter!(n);\n const blockedBySearchScope = context.hasInSearchScope(n);\n return passesOriginal && !blockedBySearchScope;\n };\n const hasTarget = !!target;\n\n const performLookup = (targetRules: Rules | Node | undefined): any => {\n if (!targetRules) {\n return undefined;\n }\n const opts: FindOptions = { filter, context, hasTarget };\n const findLocalLinearPropertyDeclaration = (rules: Rules, keyStr: string): Node | undefined => {\n if (this.options.resolution !== 'linear' || opts.start === undefined) {\n return undefined;\n }\n const children = rules.getRegistryChildren(context);\n const start = Math.min(opts.start - 1, children.length - 1);\n for (let i = start; i >= 0; i--) {\n const candidate = children[i];\n if (\n candidate\n && isNode(candidate, N.Declaration)\n && String(candidate.get('name', context).valueOf()) === keyStr\n && (!filter || filter(candidate))\n ) {\n return candidate;\n }\n }\n return undefined;\n };\n if (\n !target\n && targetRules.options?.isMixinOutput === true\n && (type === 'mixin' || type === 'mixin-ruleset' || type === 'ruleset')\n ) {\n opts.local = true;\n }\n\n const shouldRespectStart = type !== 'property' || this.options.respectStart === true;\n if (this.options.resolution === 'linear' && !isInterpolatedVariable && shouldRespectStart) {\n // For linear resolution, climb up the parent chain until we find a node with a Rules parent\n // and use that node's index for linear lookup\n let startIndex = this.index;\n let currentNode: Node | undefined = this;\n const shouldDebugPropertyStart = type === 'property'\n && (isArray(valueKey) ? valueKey[0] : valueKey) === 'background-color';\n const debugChain: Array<{ type: string; index: number | undefined; renderKey: string }> = shouldDebugPropertyStart\n ? [{ type: currentNode.type, index: currentNode.index, renderKey: String(currentNode.renderKey) }]\n : [];\n\n // If this node doesn't have an index, climb up until we find one\n if (startIndex === undefined) {\n while (currentNode && startIndex === undefined) {\n currentNode = getLookupParentNode(currentNode, context);\n if (shouldDebugPropertyStart && currentNode) {\n debugChain.push({ type: currentNode.type, index: currentNode.index, renderKey: String(currentNode.renderKey) });\n }\n if (currentNode) {\n startIndex = currentNode.index;\n }\n }\n }\n\n // Now climb up until we find a node that has a Rules parent\n while (currentNode) {\n const currentParent = getLookupParentNode(currentNode, context);\n if (!currentParent || isNode(currentParent, N.Rules)) {\n break;\n }\n currentNode = currentParent;\n if (shouldDebugPropertyStart) {\n debugChain.push({ type: currentNode.type, index: currentNode.index, renderKey: String(currentNode.renderKey) });\n }\n if (currentNode && currentNode.index !== undefined) {\n startIndex = currentNode.index;\n }\n }\n\n if (startIndex !== undefined) {\n opts.start = startIndex;\n }\n } else if (this.options.resolution === 'call-time' && !isInterpolatedVariable && shouldRespectStart) {\n // For call-time resolution, use the call site's position (context.callSiteIndex)\n // instead of the definition position. This allows mixins to resolve variables\n // at the time they're called, not when they're defined.\n if (context.rulesContext !== undefined) {\n opts.start = context.rulesContext.index;\n } else {\n // Fall back to linear resolution if we can't find a call site\n let startIndex = this.index;\n let currentNode: Node | undefined = this;\n\n if (startIndex === undefined) {\n while (currentNode && startIndex === undefined) {\n currentNode = getLookupParentNode(currentNode, context);\n if (currentNode) {\n startIndex = currentNode.index;\n }\n }\n }\n\n while (currentNode) {\n const currentParent = getLookupParentNode(currentNode, context);\n if (!currentParent || isNode(currentParent, N.Rules)) {\n break;\n }\n currentNode = currentParent;\n if (currentNode && currentNode.index !== undefined) {\n startIndex = currentNode.index;\n }\n }\n\n if (startIndex !== undefined) {\n opts.start = startIndex;\n }\n }\n }\n switch (type) {\n case 'index':\n if (typeof valueKey === 'number') {\n if (isNode(targetRules, N.Rules)) {\n return targetRules.at(valueKey);\n } else if (isNode(targetRules, N.JsArray)) {\n return atIndex((targetRules as any).value, valueKey);\n }\n } else {\n const keyStr = isArray(valueKey) ? (valueKey[0] ?? '') : valueKey;\n if (isNode(targetRules, N.Rules)) {\n // If the key was a Keyword, look up as a variable first\n if (key instanceof Keyword) {\n const found = targetRules.find('declaration', `${keyStr}`, 'VarDeclaration', opts);\n if (found !== undefined) {\n return found;\n }\n }\n // If the key was a Quoted, look up as a property\n if (isNode(key, N.Quoted)) { // property lookup\n const found = targetRules.find('declaration', `${keyStr}`, 'Declaration', opts);\n if (found !== undefined) {\n return found;\n }\n }\n return targetRules.find('declaration', `${keyStr}`, undefined, opts);\n } else if (isNode(targetRules, N.JsObject)) {\n return (targetRules as any).value[keyStr];\n }\n }\n break;\n case 'variable':\n if (isNode(targetRules, N.Rules)) {\n const keyStr = isArray(valueKey) ? valueKey[0] : valueKey;\n const found = targetRules.find('declaration', `${keyStr}`, 'VarDeclaration', opts);\n if (found !== undefined) {\n return found;\n }\n return undefined;\n }\n break;\n case 'function':\n if (isNode(targetRules, N.Rules)) {\n const keyStr = isArray(valueKey) ? valueKey[0] : valueKey;\n const inCall = isNode(getLookupParentNode(this, context), N.Call);\n const findFunction = () =>\n targetRules.find('function', `${keyStr}`, undefined, opts)\n ?? targetRules.findStatePatchedFunction(`${keyStr}`, opts);\n // When called (e.g. `ns.func(...)`), prefer function lookup first, then fall back to a declaration.\n // When not called, parsers should generally use `index`/`variable` references for `ns.func` so\n // declarations win; but if we are here, keep behavior predictable.\n if (inCall) {\n return (\n findFunction()\n ?? targetRules.find('declaration', `${keyStr}`, undefined, opts)\n );\n }\n // Not in call: prefer declaration first, then function.\n return (\n targetRules.find('declaration', `${keyStr}`, undefined, opts)\n ?? findFunction()\n );\n }\n break;\n case 'property':\n if (isNode(targetRules, N.Rules)) {\n const keyStr = isArray(valueKey) ? (valueKey[0] ?? '') : valueKey;\n opts.local = true;\n const localLinear = findLocalLinearPropertyDeclaration(targetRules, keyStr);\n if (localLinear !== undefined) {\n return localLinear;\n }\n const declaration = targetRules.find('declaration', `${keyStr}`, 'Declaration', opts);\n if (declaration !== undefined) {\n return declaration;\n }\n return undefined;\n } else if (isNode(targetRules, N.JsObject)) {\n const keyStr = isArray(valueKey) ? (valueKey[0] ?? '') : valueKey;\n return (targetRules as any).value[keyStr];\n }\n break;\n case 'mixin':\n if (isNode(targetRules, N.Rules)) {\n // valueKey can be string or string[] - find() accepts both\n const mixin = targetRules.find('mixin', valueKey, 'Mixin', opts);\n if (mixin) {\n return mixin;\n }\n // Some Less built-ins are invoked in mixin-like call positions.\n // If a mixin lookup misses during a Call, allow function fallback.\n if (isNode(getLookupParentNode(this, context), N.Call)) {\n const keyStr = isArray(valueKey) ? (valueKey[0] ?? '') : valueKey;\n return targetRules.find('function', `${keyStr}`, undefined, opts);\n }\n return undefined;\n }\n break;\n case 'ruleset':\n if (isNode(targetRules, N.Rules)) {\n const keyStr = isArray(valueKey) ? valueKey[0] : valueKey;\n return targetRules.find('mixin', `${keyStr}`, 'Ruleset', opts);\n }\n break;\n case 'mixin-ruleset':\n if (isNode(targetRules, N.Rules)) {\n const mixinOrRuleset = targetRules.find('mixin', valueKey, undefined, opts);\n if (mixinOrRuleset) {\n return mixinOrRuleset;\n }\n if (isNode(getLookupParentNode(this, context), N.Call)) {\n const keyStr = isArray(valueKey) ? (valueKey[0] ?? '') : valueKey;\n return targetRules.find('function', `${keyStr}`, undefined, opts);\n }\n return undefined;\n }\n break;\n }\n return undefined;\n };\n const performExplicitParentVariableLookup = (): Declaration | undefined => {\n if (type !== 'variable' || target) {\n return undefined;\n }\n const keyStr = isArray(valueKey) ? valueKey[0] : valueKey;\n const seenRules = new Set<Rules>();\n let current: Node | undefined = this;\n while (current) {\n current = getLookupParentNode(current, context);\n if (!current) {\n break;\n }\n if (!isNode(current, N.Rules)) {\n continue;\n }\n const rules = current as Rules;\n if (seenRules.has(rules)) {\n continue;\n }\n seenRules.add(rules);\n const found = rules.find('declaration', `${keyStr}`, 'VarDeclaration', {\n filter,\n context,\n hasTarget,\n searchParents: false\n });\n if (found !== undefined) {\n return found as Declaration;\n }\n }\n return undefined;\n };\n\n // Lookup is driven by the resolved target scope.\n // In mixin/at-rule nesting cases, `this.rulesParent` can point at a narrower scope (e.g. the\n // nested @media Rules) while the variable lives on an ancestor Rules (e.g. mixin param wrapper).\n const lookupTarget = isNode(resolvedTarget, N.Ruleset)\n ? (resolvedTarget as Ruleset).enterRules(context)\n : resolvedTarget;\n let returnVal: any;\n if (isNode(lookupTarget, N.Rules)) {\n returnVal = performLookup(lookupTarget);\n\n if (\n returnVal === undefined\n && !target\n && type === 'variable'\n ) {\n returnVal = performExplicitParentVariableLookup();\n }\n\n if (\n returnVal === undefined\n && context.lookupScope\n && context.lookupScope !== lookupTarget\n ) {\n returnVal = performLookup(context.lookupScope);\n }\n\n if (\n returnVal === undefined\n && !target\n && type === 'variable'\n && context.callStack.length > 0\n && lookupSourceRulesParent\n && lookupSourceRulesParent !== lookupTarget\n && lookupSourceRulesParent !== context.lookupScope\n ) {\n returnVal = performLookup(lookupSourceRulesParent);\n }\n\n if (\n returnVal === undefined\n && !target\n && type === 'variable'\n && context.callStack.length > 0\n && lookupCallerRulesParent\n && lookupCallerRulesParent !== lookupTarget\n && lookupCallerRulesParent !== context.lookupScope\n ) {\n returnVal = performLookup(lookupCallerRulesParent);\n }\n\n if (\n returnVal === undefined\n && !target\n && type === 'variable'\n && context.callStack.length > 0\n && activeSourceRulesParent\n && activeSourceRulesParent !== lookupTarget\n ) {\n returnVal = performLookup(activeSourceRulesParent);\n }\n\n if (\n returnVal === undefined\n && !target\n && type === 'variable'\n && context.callStack.length > 0\n && activeCallerRulesParent\n && activeCallerRulesParent !== lookupTarget\n ) {\n returnVal = performLookup(activeCallerRulesParent);\n }\n\n // If leakyRules is true, try caller scope as a secondary pass (historical behavior).\n if (returnVal === undefined && context.leakyRules) {\n returnVal = performLookup(activeRulesParent);\n if (returnVal === undefined) {\n returnVal = performLookup(activeSourceRulesParent);\n }\n if (returnVal === undefined) {\n returnVal = performLookup(activeCallerRulesParent);\n }\n }\n }\n return { returnVal, valueKey };\n },\n ({ returnVal, valueKey }) => {\n const valueKeyStr2 = isArray(valueKey) ? valueKey.join('') : String(valueKey);\n if (returnVal === undefined) {\n if (!fallbackValue) {\n if (\n (type === 'mixin' || type === 'mixin-ruleset')\n && isInsideSelectorCapture(this, context)\n ) {\n return new Any(valueKeyStr2, { role: 'ident' });\n }\n switch (type) {\n case 'mixin':\n throw new ReferenceError(`No matching mixins found for '${valueKeyStr2}'`);\n case 'ruleset':\n throw new ReferenceError(`No matching rulesets found for '${valueKeyStr2}'`);\n case 'mixin-ruleset':\n throw new ReferenceError(`No matching mixins found for '${valueKeyStr2}'`);\n }\n throw new ReferenceError(`'${valueKeyStr2}' is not defined`);\n }\n if (fallbackValue === true) {\n const any = new Any(`${valueKey}`, { role: this.options.role });\n return any;\n }\n // Evaluate the fallbackValue if it's a Node\n let out = fallbackValue.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Node>).then(node => node);\n }\n return out;\n }\n if (isNode(returnVal, N.Declaration | N.VarDeclaration)) {\n context.addToSearchScope(returnVal as Node);\n const hasImportant = isNode(returnVal, N.Declaration) && !!(returnVal as Declaration).get('important');\n const scopeRenderKey = context.lookupScope?.renderKey ?? context.renderKey;\n const declarationValueContext = scopeRenderKey !== undefined && context.renderKey !== scopeRenderKey\n ? { ...context, renderKey: scopeRenderKey }\n : context;\n const declValue = (returnVal as Declaration).get('value', declarationValueContext);\n const declarationParent = scopeRenderKey !== undefined\n ? getCurrentParentNode(returnVal as Node, scopeRenderKey)\n : getCurrentParentNode(returnVal as Node, context);\n const declarationRulesScope = isNode(declarationParent, N.Rules)\n ? declarationParent as Rules\n : getStateRulesParent(returnVal as Node, context);\n if (\n declValue instanceof Node\n && getSourceParent(declValue, declarationValueContext) === undefined\n ) {\n const declarationScopeSourceParent = declarationRulesScope\n ? getSourceParent(declarationRulesScope as Node, declarationValueContext)\n : undefined;\n const declarationSourceParent = getSourceParent(returnVal as Node, declarationValueContext)\n ?? declarationScopeSourceParent;\n if (declarationSourceParent) {\n setSourceParent(declValue, declarationSourceParent, declarationValueContext);\n }\n }\n // Mixin references (e.g. @foo: .a) are not resolved at lookup time; they are\n // resolved only when called (@foo();) or used as target of a lookup (@foo[prop]).\n const isMixinRef = isNode(declValue, N.Reference) && declValue.options?.type === 'mixin-ruleset';\n return pipe(\n () => {\n // Track that this value came from an important declaration\n // We push here but DON'T pop - let the consuming Declaration pop it\n if (hasImportant) {\n context.pushImportantSource();\n }\n declValue.frozen = true;\n if (isMixinRef) {\n return declValue;\n }\n const previousRulesContext = context.rulesContext;\n const previousLookupScope = context.lookupScope;\n const previousRenderKey = context.renderKey;\n if (declarationRulesScope) {\n context.rulesContext = declarationRulesScope;\n context.lookupScope = declarationRulesScope;\n context.renderKey = scopeRenderKey ?? declarationRulesScope.renderKey ?? previousRenderKey;\n }\n try {\n return declValue.eval(context);\n } finally {\n context.rulesContext = previousRulesContext;\n context.lookupScope = previousLookupScope;\n context.renderKey = previousRenderKey;\n }\n },\n (evald) => {\n context.deleteFromSearchScope(returnVal as Node);\n // DON'T pop important source here - let the consuming Declaration pop it\n // after it has checked and merged the important flag\n let out = materializeResolvedValue(evald);\n out.pre = this.pre;\n out.post = this.post;\n setSourceParent(out, sourceReference, context);\n const dependency = isTopLevelVarDeclaration(returnVal as Node, context)\n ? {\n dependsOn: new Set<VarDeclaration>([returnVal as VarDeclaration]),\n sourceExpr: this as Node\n }\n : getDependency(evald, context);\n if (dependency?.dependsOn && dependency.dependsOn.size > 0) {\n setDependency(out, {\n dependsOn: new Set(dependency.dependsOn),\n sourceExpr: dependency.sourceExpr ?? this\n }, context);\n }\n return out;\n }\n );\n } else if (isArray(returnVal)) {\n // When a mixin-ruleset reference is used as the target of another\n // Reference (e.g. #theme -> .dark -> .navbar), preserve the resolved\n // scope entry instead of eagerly converting it into a callable mixin.\n if (type === 'mixin-ruleset' && !isNode(getLookupParentNode(this, context), N.Call) && context.referenceStack > 1) {\n const first = returnVal[0] as Node | undefined;\n if (first && isNode(first, N.Mixin | N.Ruleset)) {\n anchorResolvedReferenceResult(first as Node, sourceReference, context);\n context.popReference();\n return cast(first);\n }\n context.popReference();\n return cast(undefined);\n }\n\n // Only pass Mixins and Rulesets to getFunctionFromMixins\n for (let item of returnVal) {\n anchorResolvedReferenceResult(item, sourceReference, context);\n if (!isNode(item, N.Mixin | N.Ruleset)) {\n context.popReference();\n return cast(undefined);\n }\n }\n // When the parent is a Call, return the resolved candidate(s) directly\n // so Call.evalNode keeps candidate placement/renderKey and dispatches\n // through the direct mixin path instead of the legacy JsFunction\n // wrapper path.\n if (\n (type === 'mixin' || type === 'mixin-ruleset')\n && isNode(getLookupParentNode(this, context), N.Call)\n ) {\n context.popReference();\n return returnVal.length === 1\n ? returnVal[0] as Node\n : returnVal as unknown as Node;\n }\n // Multi-match, namespace, or non-Call consumer: use legacy function wrapper.\n const func = getFunctionFromMixins(returnVal as MixinEntry[]);\n context.popReference();\n return cast(func);\n }\n const result = cast(returnVal);\n // Pop reference and clear remainders if we're at the outermost level\n context.popReference();\n anchorResolvedReferenceResult(result, sourceReference, context);\n return result;\n }\n );\n if (isThenable(result)) {\n return (result as Promise<Node>).then(\n res => res,\n (err) => {\n throw err;\n }\n );\n }\n return result as Node;\n }\n}\n\nexport const ref = defineType(Reference, 'Reference', 'ref');\n","import { isPlainObject } from './tree/util/collections.js';\nimport { AbstractClass, Class, OmitIndexSignature } from 'type-fest';\nimport { isNode } from './tree/util/is-node.js';\nimport { N } from './tree/node-type.js';\nimport type { Context } from './context.js';\nimport { isThenable } from '@jesscss/awaitable-pipe';\nimport type { MaybePromise } from '@jesscss/awaitable-pipe';\nimport { List, Sequence, Operation, Num, Dimension } from './tree/index.js';\nimport type { ConversionPlugin, PreprocessParams } from './conversions.js';\nimport { isEvaluated } from './tree/util/field-helpers.js';\nimport { F_STATIC } from './tree/node.js';\nexport type PrimitiveType = 'string' | 'number' | 'boolean' | 'null' | 'undefined';\nexport type ArgType = PrimitiveType | Class<any> | AbstractClass<any>;\nexport type Lazy<T> = () => MaybePromise<T>;\n\n/**\n * FunctionThis provides a proxy-based interface for function execution context.\n *\n * The `args` property is always a function that returns a `MaybePromise<List>`,\n * providing a consistent API regardless of lazy parameter configuration.\n *\n * @example\n * ```typescript\n * const func = defineFunction('test', async function(this: FunctionThis) {\n * // this.args is always a function that returns the arguments\n * const evaluatedArgs = await this.args();\n * return evaluatedArgs;\n * }, {\n * params: [\n * { name: 'value', type: 'string', lazy: true }\n * ]\n * });\n * ```\n */\nexport type FunctionThis = {\n /** The evaluation context */\n context: Context;\n /** The current call node that invoked this function, when available. */\n caller?: Context['caller'];\n /**\n * The function arguments. Always returns a function that evaluates to MaybePromise<List>.\n * This provides a consistent API regardless of lazy parameter configuration.\n */\n args: () => MaybePromise<List>;\n /** The original arguments, not evaluated */\n rawArgs: List;\n};\n\nexport type ParamDefinition = {\n name: string;\n type: ArgType | readonly ArgType[];\n optional?: boolean;\n default?: any;\n /** Marks this parameter as a variadic rest parameter. Must be the last param. */\n rest?: boolean;\n /** If true, provide a thunk (() => Promise<T>) to the internal positional function */\n lazy?: boolean;\n /** Conversion plugins to apply to the argument before passing to the function */\n convert?: ConversionPlugin[];\n};\n\nexport type DefineFunctionOptions = {\n /**\n * Parameter definitions. Can be a single array for one signature,\n * or an array of arrays for function overloading (multiple signatures).\n * The system will try each signature until one matches.\n */\n params: readonly ParamDefinition[] | readonly ParamDefinition[][];\n /**\n * Preprocesses the raw arguments array before parsing into a record.\n * This allows transformations like splitting sequences, normalizing arguments, etc.\n * Applied in order, with each preprocessor receiving the output of the previous one.\n *\n * @param args - The raw arguments array\n * @param context - The evaluation context\n * @returns The processed arguments array (can be async)\n */\n preprocessParams?: PreprocessParams[];\n // Future options can be added here\n // example?: boolean;\n // validate?: boolean;\n};\n\n// Helper type to get the inferred type from ArgType\ntype GetArgType<T extends ArgType> =\n T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : T extends Class<any> | AbstractClass<any>\n ? InstanceType<T>\n : never;\n\n// Helper type to get the inferred type from a parameter definition, accounting for lazy\ntype GetParamType<T extends DefineFunctionOptions['params'][number]> =\n T extends { lazy: true; type: infer A extends ArgType }\n ? Lazy<GetArgType<A>>\n : T extends { lazy: true; type: readonly ArgType[] }\n ? Lazy<GetArgType<T['type'][number]>>\n : T extends { type: infer A extends ArgType }\n ? GetArgType<A>\n : T extends { type: readonly ArgType[] }\n ? GetArgType<T['type'][number]>\n : never;\n\n/** This should be getting only required types but it doesn't? */\ntype GetBaseRecordType<T extends DefineFunctionOptions['params']> = (\n OmitIndexSignature<{\n [K in keyof T as T[K] extends { optional: true } | { default: any }\n ? never\n : T[K] extends { name: infer N extends string }\n ? N\n : never]:\n T[K] extends DefineFunctionOptions['params'][number]\n ? GetParamType<T[K]>\n : never;\n }>\n);\n\ntype GetOptionalRecordType<T extends DefineFunctionOptions['params']> = {\n [K in keyof T as T[K] extends { optional: true } | { default: any }\n ? T[K] extends { name: infer N extends string }\n ? N\n : never\n : never]?:\n T[K] extends { rest: true }\n ? (\n T[K] extends DefineFunctionOptions['params'][number]\n ? GetParamType<T[K]>[]\n : never\n )\n : (\n T[K] extends DefineFunctionOptions['params'][number]\n ? GetParamType<T[K]>\n : never\n );\n};\n\n// Get record types for named parameters\ntype GetRecordType<T extends DefineFunctionOptions['params']> = (\n GetOptionalRecordType<T> & Omit<GetBaseRecordType<T>, keyof GetOptionalRecordType<T>>\n);\n\ntype GetPositionalTypes<\n T extends DefineFunctionOptions['params'],\n P extends Partial<GetRecordType<DefineFunctionOptions['params']>> = Partial<GetRecordType<T>>\n> = T extends readonly [infer First, ...infer Rest]\n ? Rest extends DefineFunctionOptions['params']\n ? First extends { optional: true } | { default: any }\n ? First extends DefineFunctionOptions['params'][number]\n ? [(GetParamType<First> | (P & GetRecordType<T>))?, ...GetPositionalTypes<Rest, P>]\n : never\n : First extends DefineFunctionOptions['params'][number]\n ? [GetParamType<First> | (P & GetRecordType<T>), ...GetPositionalTypes<Rest, P>]\n : never\n : []\n : [];\n\n/**\n * Validates that the internal function signature matches the params definition\n */\ntype ValidateFunctionSignature<\n T extends DefineFunctionOptions,\n F extends (...args: any[]) => any\n> = F;\n\nexport function defineFunction<\n const T extends DefineFunctionOptions,\n F extends (...args: any[]) => any\n>(\n name: string,\n fn: ValidateFunctionSignature<T, F>,\n options?: T\n): DefinedFunction<T, F>;\n\nexport type DefinedFunction<\n T extends DefineFunctionOptions,\n F extends (...args: any[]) => any\n> = {\n (...args: any[]): ReturnType<F>;\n name: string;\n params: DefineFunctionOptions['params'];\n} & {\n call(thisArg: any, ...args: any[]): ReturnType<F>;\n apply(thisArg: any, args: any[]): ReturnType<F>;\n};\n\nexport function defineFunction<\n const T extends DefineFunctionOptions,\n F extends (...args: any[]) => any\n>(\n name: string,\n fn: ValidateFunctionSignature<T, F>,\n options?: T\n) {\n // The external API types remain exactly the same, but internal function accepts positional parameters only\n\n type NamedFunction = DefinedFunction<T, F>;\n\n /**\n * Function that accepts either positional arguments or a record object.\n * Parameter names are inferred from the params array: name, value, etc.\n * All calls are converted to positional format before calling the internal function.\n */\n const result = function(...args: any[]): ReturnType<F> {\n const rawParams = options?.params;\n if (!rawParams) {\n return (fn as any)(...args);\n }\n\n // Normalize params - handle overloaded signatures\n const paramSignatures: ParamDefinition[][] = Array.isArray(rawParams) && rawParams.length > 0 && Array.isArray(rawParams[0])\n ? rawParams.map(sig => [...sig]) as ParamDefinition[][]\n : [[...(rawParams as readonly ParamDefinition[])]];\n\n // For direct calls, use the first signature (overloading handled in callWithContext)\n const params = paramSignatures[0]!;\n\n // Validate rest parameter position\n validateRestParameterPosition(params);\n\n // Parse arguments into a record\n const record = parseArgumentsToRecord(args, params);\n\n // Apply defaults and validate\n applyDefaultsAndValidate(record, params);\n\n // Convert to positional arguments and call internal function\n const positionalArgs = buildPositionalArgs(record, params);\n return (fn as any)(...positionalArgs);\n } as NamedFunction;\n\n /** Allow runtime reflection on the function */\n return new Proxy(result, {\n has(target, prop) {\n if (prop === 'name' || prop === 'options') {\n return true;\n }\n return prop in target;\n },\n get(target, prop) {\n if (prop === 'name') {\n return name;\n } else if (prop === 'options') {\n return options;\n } else if (prop === '_internal') {\n return fn;\n }\n return (target as any)[prop];\n }\n });\n}\n\n/** This will be called internally by Jess to functions created with defineFunction */\nexport async function callWithContext(context: Context, fn: (...args: any[]) => any, ...args: any[]): Promise<any> {\n const listArg = args.length === 1 && isNode(args[0], N.List)\n ? args[0] as List\n : undefined;\n args = listArg ? [...listArg.get('value')] : args;\n // Only reject record-based calls (plain objects) when there's no params metadata\n // Collections are allowed as positional arguments even without params metadata\n // (e.g., detached rulesets passed to mixins)\n if (!(fn as any)?.options?.params && args.some(arg => isPlainObject(arg) && !isNode(arg))) {\n throw new Error('Record-based call without params is not supported');\n }\n\n /** Normalize positional args into a List node for tracking original arguments */\n const originalArgsList: List = listArg\n ? listArg.clone(false)\n : new List(args.map(arg => isNode(arg) ? arg.clone() : arg));\n\n const hasParams = !!(fn as any)?.options?.params;\n\n if (!hasParams) {\n // No metadata; treat as normal positional function call (sync or async)\n return (fn as any).call(context, ...args);\n }\n\n const params = (fn as any)?.options?.params as DefineFunctionOptions['params'] | undefined;\n const options = (fn as any)?.options as DefineFunctionOptions | undefined;\n\n // Apply preprocessParams if provided (e.g., for splitting sequences)\n if (options?.preprocessParams && options.preprocessParams.length > 0) {\n for (const preprocessor of options.preprocessParams) {\n const processed = preprocessor(args, context);\n if (isThenable(processed)) {\n args = await processed;\n } else {\n args = processed;\n }\n }\n }\n\n // Handle function overloading: params can be an array of param arrays\n // Normalize to always be an array of signatures\n const paramSignatures: ParamDefinition[][] = (() => {\n if (!params) {\n return [];\n }\n // Check if params is an array of arrays (overloaded signatures)\n if (Array.isArray(params) && params.length > 0 && Array.isArray(params[0])) {\n return params.map(sig => [...sig]) as ParamDefinition[][];\n }\n // Single signature - wrap in array\n return [[...(params as readonly ParamDefinition[])]];\n })();\n\n let matchedParams: readonly ParamDefinition[] | undefined;\n let record: any;\n let lastError: Error | undefined;\n\n // Try each signature until one matches\n for (const signature of paramSignatures) {\n try {\n record = parseCallWithContextArgs(args, signature);\n // Try to build positional args to validate the signature matches\n // We'll do a dry-run validation\n const tempRecord = { ...record };\n let isValid = true;\n\n // Check if we have a record object (plain object) in args\n // Collections are treated as positional arguments, not record-based calls\n const hasRecordArg = args.some(arg => isPlainObject(arg));\n\n for (let i = 0; i < signature.length; i++) {\n const def = signature[i]!;\n const value = tempRecord[def.name];\n\n // Check required parameters\n if (!def.optional && !def.rest && value === undefined) {\n isValid = false;\n break;\n }\n\n // Check if we have enough arguments (skip this check if we have a record arg)\n if (!hasRecordArg && !def.rest && i >= args.length && !def.optional) {\n isValid = false;\n break;\n }\n }\n\n // Check if we have too many arguments (not counting rest params or record args)\n const hasRest = signature.some(p => p.rest);\n if (!hasRest && !hasRecordArg && args.length > signature.length) {\n isValid = false;\n }\n\n if (isValid) {\n matchedParams = signature;\n break;\n }\n } catch (error) {\n lastError = error as Error;\n continue;\n }\n }\n\n // If no signature matched, throw an error\n if (!matchedParams) {\n if (lastError) {\n throw lastError;\n }\n throw new Error(`No matching function signature for ${args.length} argument(s)`);\n }\n\n // Re-parse with the matched signature to ensure correct record structure\n record = parseCallWithContextArgs(args, matchedParams);\n\n /**\n * Create FunctionThis proxy for function execution context.\n * The args property is always a function that returns the arguments.\n */\n context.callStack.at(-1)?.adopt(originalArgsList);\n const functionThis: FunctionThis = {\n context,\n args: () => originalArgsList.eval(context),\n rawArgs: originalArgsList,\n caller: context.caller\n };\n\n // Build positional arguments with evaluation, validation, and conversion\n const positionalArgs = await buildCallWithContextPositionalArgs(record, matchedParams, context);\n\n // Call the function with the evaluated arguments\n // Mixin functions expect Context as 'this', not FunctionThis\n if ((fn as any)._internal) {\n return ((fn as any)._internal).call(functionThis, ...positionalArgs);\n } else {\n // For mixin functions and other functions that expect Context as 'this'\n return (fn as any).call(context, ...positionalArgs);\n }\n}\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\n/**\n * Validates that rest parameters are in the correct position (last)\n */\nfunction validateRestParameterPosition(params: readonly ParamDefinition[]): void {\n const restIndex = params.findIndex(p => p.rest);\n if (restIndex >= 0 && restIndex !== params.length - 1) {\n throw new Error('Rest parameter must be the last parameter');\n }\n}\n\n/**\n * Applies conversion plugins to a value\n */\nfunction applyConversionPlugins(value: unknown, plugins: ConversionPlugin[]): unknown {\n let result: unknown = value;\n\n // Apply conversion plugins in sequence\n for (const plugin of plugins) {\n result = plugin(result);\n }\n\n return result;\n}\n\n/**\n * Parses function arguments into a record object\n */\nfunction parseArgumentsToRecord(args: any[], params: readonly ParamDefinition[]): any {\n const record: any = {};\n const restIndex = params.findIndex(p => (p as any).rest);\n const hasRest = restIndex >= 0;\n\n // Handle pure record call (single object argument)\n if (args.length === 1 && isPlainObject(args[0])) {\n const isClassInstance = params?.some((opt) => {\n const types = Array.isArray(opt.type) ? opt.type : [opt.type];\n return types.some(type =>\n typeof type === 'function' && args[0] instanceof type\n );\n });\n\n if (!isClassInstance) {\n const input = args[0] as any;\n const isLateProxy = !!input && typeof input === 'object' && '_raw' in input;\n return isLateProxy ? input._raw : { ...input };\n }\n }\n\n // Handle hybrid call (positional + record)\n if (args.length > 1 && isPlainObject(args[args.length - 1])) {\n const positionalArgs = args.slice(0, -1);\n const recordArg = args[args.length - 1];\n\n // Set values from positional arguments\n if (!hasRest) {\n for (let i = 0; i < positionalArgs.length && i < (params?.length ?? 0); i++) {\n const paramName = params?.[i]?.name;\n if (paramName) {\n record[paramName] = positionalArgs[i];\n }\n }\n } else {\n for (let i = 0; i < (params?.length ?? 0); i++) {\n const def = params[i]!;\n const paramName = def.name;\n if ((def as any).rest) {\n record[paramName] = positionalArgs.slice(i);\n break;\n } else if (i < positionalArgs.length) {\n record[paramName] = positionalArgs[i];\n }\n }\n }\n\n // Override with values from record (record takes precedence)\n Object.assign(record, recordArg);\n return record;\n }\n\n // Handle pure positional call\n if (!hasRest) {\n for (let i = 0; i < Math.max(args.length, params?.length ?? 0); i++) {\n const paramName = params?.[i]?.name;\n if (paramName) {\n if (i < args.length) {\n record[paramName] = args[i];\n } else if (params?.[i]?.default !== undefined) {\n record[paramName] = params![i]?.default;\n } else if (params?.[i]?.optional) {\n record[paramName] = undefined;\n }\n }\n }\n } else {\n for (let i = 0; i < (params?.length ?? 0); i++) {\n const def = params[i]!;\n const paramName = def.name;\n if ((def as any).rest) {\n record[paramName] = args.slice(i);\n break;\n } else if (i < args.length) {\n record[paramName] = args[i];\n } else if (def.default !== undefined) {\n record[paramName] = def.default;\n } else if (def.optional) {\n record[paramName] = undefined;\n }\n }\n }\n\n return record;\n}\n\n/**\n * Applies defaults and validates arguments\n */\nfunction applyDefaultsAndValidate(record: any, params: readonly ParamDefinition[]): void {\n // Apply defaults for missing parameters\n for (const paramDef of params ?? []) {\n const paramName = paramDef.name;\n if (record[paramName] === undefined && paramDef.default !== undefined) {\n record[paramName] = paramDef.default;\n }\n // Normalize rest param to array\n if ((paramDef as any).rest) {\n const current = record[paramName];\n if (current === undefined) {\n record[paramName] = [];\n } else if (!Array.isArray(current)) {\n record[paramName] = [current];\n }\n }\n }\n\n validateArguments(record, params);\n}\n\n/**\n * Builds positional arguments from record\n */\nfunction buildPositionalArgs(record: any, params: readonly ParamDefinition[]): any[] {\n const positionalArgs: any[] = [];\n\n for (let i = 0; i < (params?.length ?? 0); i++) {\n const def = params![i]!;\n const name = def.name;\n\n if ((def as any).rest) {\n const v = record[name];\n const arr: any[] = Array.isArray(v) ? v : (v === undefined ? [] : [v]);\n if ((def as any).lazy) {\n positionalArgs.push(...arr.map(item => createThunk(item, def)));\n } else {\n positionalArgs.push(...arr.map((item) => {\n // Apply conversion plugins if defined\n if (def.convert && item instanceof Dimension) {\n return applyConversionPlugins(item, def.convert);\n }\n return item;\n }));\n }\n } else {\n const v = record[name];\n if ((def as any).lazy) {\n // For optional lazy parameters, if value is undefined, pass undefined directly\n // instead of creating a thunk (which would try to call undefined())\n if (v === undefined && (def.optional || def.default !== undefined)) {\n positionalArgs.push(undefined);\n } else {\n positionalArgs.push(createThunk(v, def));\n }\n } else {\n // Apply conversion plugins if defined\n if (def.convert && v instanceof Dimension) {\n positionalArgs.push(applyConversionPlugins(v, def.convert));\n } else {\n positionalArgs.push(v);\n }\n }\n }\n }\n\n return positionalArgs;\n}\n\n/**\n * Parses callWithContext arguments into a record\n */\nfunction parseCallWithContextArgs(args: any[], params: readonly ParamDefinition[] | undefined): any {\n const record: any = {};\n const restIndex = params ? params.findIndex(p => (p as any).rest) : -1;\n const hasRest = (restIndex ?? -1) >= 0;\n\n if (!hasRest) {\n for (let i = 0; i < Math.min(args.length, params?.length ?? 0); i++) {\n let arg = args[i];\n // Collections are treated as positional arguments, not record-based calls\n if (isPlainObject(arg) && !isNode(arg)) {\n Object.assign(record, arg);\n continue;\n }\n const paramName = params?.[i]?.name as string;\n if (!paramName) {\n throw new Error('Function does not support this number of arguments');\n }\n record[paramName] = args[i];\n }\n } else {\n for (let i = 0; i < (params?.length ?? 0); i++) {\n const def = params![i]!;\n const paramName = def.name;\n const arg = args[i];\n // Collections are treated as positional arguments, not record-based calls\n if (isPlainObject(arg) && !isNode(arg)) {\n Object.assign(record, arg);\n continue;\n }\n if ((def as any).rest) {\n record[paramName] = args.slice(i);\n break;\n } else {\n record[paramName] = arg;\n }\n }\n }\n\n return record;\n}\n\n/**\n * Builds positional arguments for callWithContext with evaluation\n */\nasync function buildCallWithContextPositionalArgs(\n record: any,\n params: readonly ParamDefinition[] | undefined,\n context: Context\n): Promise<any[]> {\n const positionalArgs: any[] = [];\n\n for (let i = 0; i < (params?.length ?? 0); i++) {\n const def = params![i]!;\n const name = def.name;\n\n if ((def as any).rest) {\n const v = record[name];\n const arr: any[] = Array.isArray(v) ? v : (v === undefined ? [] : [v]);\n if ((def as any).lazy) {\n positionalArgs.push(...arr.map(item => createThunk(item, def, context)));\n } else {\n for (const item of arr) {\n let processedItem: any = (isNode(item) && !isEvaluated(item, context)) ? (item as any).eval(context) : item;\n if (isThenable(processedItem)) {\n processedItem = await processedItem;\n }\n\n // Validate AFTER evaluation but BEFORE conversion\n validateArgumentIfNeeded(processedItem, def, 'Argument');\n\n // Apply conversion plugins if defined\n if (def.convert && processedItem instanceof Dimension) {\n processedItem = applyConversionPlugins(processedItem, def.convert);\n }\n positionalArgs.push(processedItem);\n }\n }\n } else {\n const v = record[name];\n if ((def as any).lazy) {\n // For optional lazy parameters, if value is undefined, pass undefined directly\n // instead of creating a thunk (which would try to call undefined())\n if (v === undefined && (def.optional || def.default !== undefined)) {\n positionalArgs.push(undefined);\n } else {\n positionalArgs.push(createThunk(v, def, context));\n }\n } else {\n let processedValue: any = (isNode(v) && !isEvaluated(v, context)) ? (v as any).eval(context) : v;\n\n // Handle async evaluation without truncating remaining parameters.\n if (isThenable(processedValue)) {\n processedValue = await processedValue;\n }\n\n // Validate AFTER evaluation but BEFORE conversion\n validateArgumentIfNeeded(processedValue, def, 'Argument');\n\n const callerName = context.caller && isNode(context.caller, N.Call)\n ? (() => {\n const n = context.caller!.get('name');\n return typeof n === 'string'\n ? n\n : (isNode(n, N.Reference) ? String(n.get('key')?.valueOf?.() ?? '') : '');\n })()\n : '';\n // Apply conversion plugins if defined\n if (def.convert && processedValue instanceof Dimension) {\n processedValue = applyConversionPlugins(processedValue, def.convert);\n }\n positionalArgs.push(processedValue);\n }\n }\n }\n\n return positionalArgs;\n}\n\n/**\n * Validates callWithContext arguments from record (before conversion)\n */\nfunction validateCallWithContextArgs(record: any, params: readonly ParamDefinition[] | undefined): void {\n if (!params) {\n return;\n }\n\n for (let i = 0; i < params.length; i++) {\n const def = params[i]!;\n const value = record[def.name];\n\n // Skip validation for lazy parameters since they're passed as thunks\n if ((def as any).lazy) {\n continue;\n }\n\n // Skip validation for rest parameters as they're validated as arrays\n if ((def as any).rest) {\n continue;\n }\n\n // Skip validation for optional parameters that are undefined\n if ((def as any).optional && value === undefined) {\n continue;\n }\n\n validateArgument(value, def, 'Argument');\n }\n}\n\n/**\n * Creates a thunk function that evaluates a value and validates the result\n */\nfunction createThunk(val: any, paramDef: any, context?: Context): () => MaybePromise<any> {\n // For direct calls without context, val should be the user's lazy function (e.g., () => new Dimension(...))\n // NOT a thunk. We create a thunk that calls val() and validates the resolved result.\n if (typeof val === 'function' && !context) {\n // Create a thunk that calls val() and validates the resolved result\n // Note: We validate the RESOLVED result when the thunk is called, not the function itself\n return async (): Promise<any> => {\n const result = await val();\n // A thunk should never return a function - if it does, that's an error\n // Check both typeof and instanceof Function to catch all function types\n if (typeof result === 'function' || result instanceof Function) {\n throw new Error(`Thunk for parameter '${paramDef?.name}' returned a function. This indicates val was already a thunk, which should never happen. Original val type: ${typeof val}, result type: ${typeof result}, result constructor: ${result?.constructor?.name}`);\n }\n // Validate the RESOLVED result (not the function itself)\n // This is where lazy parameter validation happens - when the thunk is called and the value is resolved\n // Skip validation for optional parameters that are undefined\n if (paramDef && !(paramDef as any).rest && !(result === undefined && (paramDef.optional || paramDef.default !== undefined))) {\n const validation = validateValue(result, paramDef.type, paramDef.name);\n if (!validation.isValid) {\n throw new TypeError(validation.errorMessage);\n }\n }\n return result;\n };\n }\n\n // For callWithContext path or non-function values\n // If val is undefined and parameter is optional, return a thunk that returns undefined\n if (val === undefined && (paramDef?.optional || paramDef?.default !== undefined)) {\n return async (): Promise<any> => {\n return undefined;\n };\n }\n return async (): Promise<any> => {\n let result;\n if (context && isNode(val) && !isEvaluated(val, context)) {\n result = await (val as any).eval(context);\n if (val.hasFlag(F_STATIC) && isNode(result) && result.sourceNode === val) {\n result = val;\n }\n } else if (typeof val === 'function') {\n // If val is a function (lazy parameter), call it\n result = await val();\n } else {\n result = val;\n }\n\n // Validate the evaluated result if we have param definition\n // Note: For lazy parameters, we validate the result of calling the function, not the function itself\n // Skip validation for optional parameters that are undefined\n if (paramDef && !(paramDef as any).rest && !(result === undefined && (paramDef.optional || paramDef.default !== undefined))) {\n const validation = validateValue(result, paramDef.type, paramDef.name);\n if (!validation.isValid) {\n throw new TypeError(validation.errorMessage);\n }\n }\n\n return result;\n };\n}\n\n/**\n * Runtime validation function to check argument types and required parameters for record-based calls\n */\nfunction validateArguments(record: any, params?: readonly ParamDefinition[]) {\n if (!params) {\n return;\n }\n\n // Check that all required parameters are provided\n for (const paramDef of params) {\n const paramName = paramDef.name;\n const expectedType = paramDef.type;\n const isOptional = paramDef.optional || paramDef.default !== undefined;\n const value = record[paramName];\n\n // Check if required parameter is missing\n if (!isOptional && value === undefined) {\n throw new TypeError(`Required argument '${paramName}' is missing`);\n }\n\n // Skip validation for undefined optional arguments\n if (value === undefined) {\n continue;\n }\n\n // For lazy parameters, validate that it's a function (validation of result happens in thunk)\n if ((paramDef as any).lazy) {\n if (typeof value !== 'function') {\n throw new TypeError(`Argument '${paramName}' must be a function (lazy parameter). Got: ${typeof value}`);\n }\n continue;\n }\n\n const isRest = (paramDef as any).rest === true;\n if (isRest) {\n if (!Array.isArray(value)) {\n throw new TypeError(`Argument '${paramName}' must be an array (rest parameter)`);\n }\n const elementTypes = Array.isArray(expectedType) ? expectedType : [expectedType];\n for (let idx = 0; idx < (value as any[]).length; idx++) {\n const el = (value as any[])[idx];\n const isValid = (Array.isArray(elementTypes) ? elementTypes : [elementTypes]).some(type => isValidType(el, type));\n if (!isValid) {\n const types = Array.isArray(elementTypes) ? elementTypes : [elementTypes];\n const typeList = types.map((t: any) => typeof t === 'function' ? t.name : t).join(', ');\n const actualType = typeof el === 'object' && el !== null ? el.constructor?.name || typeof el : typeof el;\n throw new TypeError(`Element ${idx} of '${paramName}' must be of type '${typeList}'. Got: ${actualType}`);\n }\n }\n } else {\n const validation = validateValue(value, expectedType, paramName, 'Argument');\n if (!validation.isValid) {\n throw new TypeError(validation.errorMessage);\n }\n }\n }\n}\n\n/**\n * Centralized validation result\n */\ninterface ValidationResult {\n isValid: boolean;\n errorMessage?: string;\n}\n\n/**\n * Validate argument if needed (checks for lazy and undefined values)\n */\nfunction validateArgumentIfNeeded(\n value: any,\n def: any,\n prefix: string = 'Parameter'\n): void {\n if (!(def as any).lazy && value !== undefined) {\n const validation = validateValue(value, def.type, def.name, prefix);\n if (!validation.isValid) {\n throw new TypeError(validation.errorMessage);\n }\n }\n}\n\n/**\n * Centralized validation function\n */\nfunction validateValue(value: any, expectedType: ArgType | readonly ArgType[], paramName: string, context: string = 'Argument'): ValidationResult {\n // Handle array of types (union types)\n if (Array.isArray(expectedType)) {\n const isValid = expectedType.some(type => isValidType(value, type));\n if (!isValid) {\n const typeList = expectedType.map((t: any) => typeof t === 'function' ? t.name : t).join(', ');\n const actualType = typeof value === 'object' && value !== null ? value.constructor?.name || typeof value : typeof value;\n return {\n isValid: false,\n errorMessage: `${context} '${paramName}' must be one of: ${typeList}. Got: ${actualType}`\n };\n }\n return { isValid: true };\n }\n\n // Handle single type\n if (!isValidType(value, expectedType as ArgType)) {\n const typeName = typeof expectedType === 'function' ? expectedType.name : expectedType;\n const actualType = typeof value === 'object' && value !== null ? value.constructor?.name || typeof value : typeof value;\n return {\n isValid: false,\n errorMessage: `${context} '${paramName}' must be of type '${typeName}'. Got: ${actualType}`\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate array elements (for rest parameters)\n */\nfunction validateArrayElements(value: any[], elementTypes: ArgType | readonly ArgType[], paramName: string, context: string = 'Argument'): ValidationResult {\n const types = Array.isArray(elementTypes) ? elementTypes : [elementTypes];\n\n for (let idx = 0; idx < value.length; idx++) {\n const el = value[idx];\n const isValid = types.some(type => isValidType(el, type));\n if (!isValid) {\n const typeList = types.map((t: any) => typeof t === 'function' ? t.name : t).join(', ');\n const actualType = typeof el === 'object' && el !== null ? el.constructor?.name || typeof el : typeof el;\n return {\n isValid: false,\n errorMessage: `Element ${idx} of '${paramName}' must be of type '${typeList}'. Got: ${actualType}`\n };\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Check if a value matches the expected type\n */\nfunction isValidType(value: any, expectedType: ArgType): boolean {\n switch (expectedType) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number';\n case 'boolean':\n return typeof value === 'boolean';\n case 'null':\n return value === null;\n case 'undefined':\n return value === undefined;\n default:\n // Check if it's a class constructor\n if (typeof expectedType === 'function') {\n return value instanceof expectedType;\n }\n return false;\n }\n}\n\n/**\n * Validates a single argument against its parameter definition\n */\nfunction validateArgument(value: any, def: any, context: string = 'argument'): void {\n // Skip validation for optional parameters that are undefined\n if ((def as any).optional && value === undefined) {\n return;\n }\n\n // For lazy parameters, validate that it's a function\n if ((def as any).lazy) {\n if (typeof value !== 'function') {\n throw new TypeError(\n `${context} '${def.name}' must be a function (lazy parameter). Got: ${typeof value}`\n );\n }\n return;\n }\n\n // Validate rest parameters as arrays\n if ((def as any).rest) {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} '${def.name}' must be an array (rest parameter)`);\n }\n const expectedType = def.type;\n for (let idx = 0; idx < value.length; idx++) {\n const el = value[idx];\n if (!isValidType(el, expectedType as ArgType)) {\n const typeName = typeof expectedType === 'function' ? expectedType.name : expectedType;\n const actualType = typeof el === 'object' && el !== null ? el.constructor?.name || typeof el : typeof el;\n throw new TypeError(`Element ${idx} of '${def.name}' must be of type '${typeName}'. Got: ${actualType}`);\n }\n }\n return;\n }\n\n // Validate regular parameters\n const expectedType = def.type;\n const validation = validateValue(value, expectedType, def.name, context);\n if (!validation.isValid) {\n throw new TypeError(validation.errorMessage);\n }\n}\n","import type { Class } from 'type-fest';\nimport type { Context } from '../context.js';\nimport { Node, F_NON_STATIC, defineType, type NodeOptions, type OptionalLocation, type TreeContext } from './node.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\nimport { getDependency, setDependency, setParent } from './util/field-helpers.js';\n\nexport type ExpressionChildData = { value: Node };\n\n/**\n * An expression is a node that returns a value.\n * It can contain values, references, and operations.\n *\n * When parsing Less/Sass, everything containing an operation is\n * considered an expression.\n */\nexport interface Expression extends Node<Node, NodeOptions, ExpressionChildData> {\n type: 'Expression';\n shortType: 'expr';\n eval(context: Context): MaybePromise<Node>;\n}\n\nexport class Expression extends Node<Node, NodeOptions, ExpressionChildData> {\n static override childKeys = ['value'] as const;\n\n readonly value!: Node;\n\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const value = this.get('value', ctx);\n const cloneChild = cloneFn ?? ((n: Node) => n.clone(deep, cloneFn, ctx));\n const clonedValue = deep ? cloneChild(value) : value;\n const options = this._meta?.options;\n const priorParent = !deep && ctx ? clonedValue.parent : undefined;\n const newNode = new (this.constructor as Class<this>)(\n clonedValue,\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n );\n if (!deep && ctx) {\n setParent(clonedValue, newNode, ctx);\n (clonedValue as unknown as { parent?: Node }).parent = priorParent;\n }\n newNode.inherit(this);\n return newNode;\n }\n\n constructor(value: Node, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n if (value instanceof Node) {\n this.adopt(value);\n }\n this.addFlag(F_NON_STATIC);\n }\n\n override evalNode(context: Context): MaybePromise<Node> {\n const value = this.get('value', context);\n const out = value.eval(context);\n const applyDependency = (result: Node): Node => {\n const dependency = getDependency(result, context);\n if (dependency?.dependsOn && dependency.dependsOn.size > 0) {\n setDependency(result, {\n dependsOn: new Set(dependency.dependsOn),\n sourceExpr: this\n }, context);\n }\n return result;\n };\n /** @todo - Cast as selector if the context is within a selector */\n if (isThenable(out)) {\n return (out as Promise<Node>).then(applyDependency);\n }\n return applyDependency(out as Node);\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const value = this.get('value', options.context);\n w.add('$', this);\n w.add('(');\n value.toString(options);\n w.add(')');\n return w.getSince(mark);\n }\n}\n\ntype Params = ConstructorParameters<typeof Expression>;\n\nexport const expr = defineType(Expression, 'Expression', 'expr') as (\n value: Params[0],\n options?: Params[1],\n location?: Params[2],\n treeContext?: Params[3]\n) => Expression;\n","import chalk from 'chalk';\n\nexport interface Logger {\n configure?(log: Logger): void;\n log?(...args: any[]): void;\n info?(...args: any[]): void;\n warn?(...args: any[]): void;\n error?(...args: any[]): void;\n}\n/** Configure with custom behavior */\nexport const logger: Required<Logger> = {\n configure(log: Logger) {\n Object.assign(logger, log);\n },\n\n log(...args: any[]) {\n console.log(...args);\n },\n\n info(...args: any[]) {\n console.info(...args);\n },\n\n warn(...args: any[]) {\n console.error(chalk.yellow(...args));\n },\n\n error(...args: any[]) {\n console.error(chalk.red(...args));\n }\n};\n","import type { Class } from 'type-fest';\nimport { type Context } from '../context.js';\nimport { Color, ColorFormat } from './color.js';\nimport {\n Node,\n F_STATIC,\n type OptionalLocation,\n type NodeOptions,\n type TreeContext,\n defineType\n} from './node.js';\nimport { type Operator, calculate } from './util/calculate.js';\nimport { logger } from '../logger.js';\nimport round from 'lodash-es/round.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\n\n// import type { Context } from '../context.js'\n// import type { OutputCollector } from '../output'\n\nexport type DimensionValue = {\n number: number;\n unit?: string;\n};\n\nconst { isArray } = Array;\n\ntype LengthUnit = 'm' | 'cm' | 'mm' | 'in' | 'px' | 'pt' | 'pc';\ntype DurationUnit = 's' | 'ms';\ntype AngleUnit = 'rad' | 'deg' | 'grad' | 'turn';\ntype ConversionUnit = LengthUnit | DurationUnit | AngleUnit;\ntype UnitMapEntries = Array<[ConversionUnit, ConversionGroup]>;\n\nexport interface Dimension extends Node<DimensionValue> {\n type: 'Dimension' | 'Num';\n shortType: 'dimension' | 'num';\n eval(context: Context): Dimension;\n}\n\n/**\n * A number or dimension\n */\nexport class Dimension extends Node<DimensionValue> {\n static override childKeys = null as null;\n\n readonly number!: number;\n readonly unit: string | undefined;\n\n constructor(\n value: DimensionValue,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n super(value, options, location, treeContext);\n this.number = value.number;\n this.unit = value.unit;\n this.addFlag(F_STATIC);\n }\n\n /** Compatibility — synthesizes the legacy .data shape from instance fields */\n\n private _unitToGroup: Map<string, ConversionGroup> | undefined;\n get unitToGroup() {\n let unitToGroup = this._unitToGroup;\n if (!unitToGroup) {\n const lengthEntries: UnitMapEntries = ['m', 'cm', 'mm', 'in', 'px', 'pt', 'pc'].map(unit => [unit as LengthUnit, ConversionGroup.Length]);\n const durationEntries: UnitMapEntries = ['s', 'ms'].map(unit => [unit as DurationUnit, ConversionGroup.Duration]);\n const angleEntries: UnitMapEntries = ['rad', 'deg', 'grad', 'turn'].map(unit => [unit as AngleUnit, ConversionGroup.Angle]);\n const entries = lengthEntries.concat(durationEntries).concat(angleEntries);\n this._unitToGroup = unitToGroup = new Map(entries);\n }\n return unitToGroup;\n }\n\n override clone(deep?: boolean): this {\n const options = this._meta?.options;\n const newNode = new (this.constructor as Class<this>)(\n { number: this.number, unit: this.unit },\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n );\n newNode.inherit(this);\n return newNode;\n }\n\n override valueOf() {\n const { number, unit } = this;\n return unit ? `${number}${unit}` : number;\n }\n\n override operate(b: Node, op: Operator, context?: Context | undefined): Dimension | Color {\n if (!(b instanceof Dimension || b instanceof Color)) {\n throw new TypeError(`Cannot operate on ${b.type}`);\n }\n let unitToGroup = this.unitToGroup;\n if (b instanceof Color) {\n let { number, unit } = this;\n const unitMode = context?.opts?.unitMode ?? 'loose';\n const isStrictLikeMode = unitMode === 'strict' || unitMode === 'preserve';\n if (unit && isStrictLikeMode) {\n throw new TypeError(`Cannot convert \"${this}\" to a color`);\n }\n let thisColor = new Color(\n { rgb: [number, number, number] },\n { format: b.options?.format ?? ColorFormat.RGB }\n ).inherit(this);\n return thisColor.operate(b, op, context).inherit(this);\n }\n let { number: aVal, unit: aUnit } = this;\n let { number: bVal, unit: bUnit } = b;\n let unitMode = context?.opts.unitMode ?? 'loose';\n let isStrictMode = unitMode === 'strict';\n let isPreserveMode = unitMode === 'preserve';\n\n if (bVal === 0 && op === '/') {\n throw new TypeError('Cannot divide by zero');\n }\n if (!aUnit || !bUnit) {\n let outUnit = aUnit ?? bUnit;\n /** One or both doesn't have a unit, so just calculate the number */\n if ((isStrictMode || isPreserveMode) && bUnit && op === '/') {\n if (isPreserveMode) {\n return new Dimension({\n number: calculate(aVal, op, bVal),\n unit: `1/${bUnit}`\n }).inherit(this);\n }\n throw new TypeError('Cannot divide a number by a unit');\n }\n return new Dimension({ number: calculate(aVal, op, bVal), unit: outUnit }).inherit(this);\n }\n\n if (aUnit === bUnit) {\n /** Both units match, so the now we have some choices */\n if (op === '+' || op === '-') {\n return new Dimension({ number: calculate(aVal, op, bVal), unit: aUnit }).inherit(this);\n }\n if (isStrictMode || isPreserveMode) {\n if (op === '*') {\n if (isPreserveMode) {\n return new Dimension({\n number: calculate(aVal, op, bVal),\n unit: `${aUnit}*${bUnit}`\n }).inherit(this);\n }\n throw new TypeError('Cannot multiply two units together');\n } else {\n /** Cancel units during division */\n return new Dimension({ number: calculate(aVal, op, bVal) }).inherit(this);\n }\n } else {\n return new Dimension({ number: calculate(aVal, op, bVal), unit: aUnit }).inherit(this);\n }\n }\n const aGroup = unitToGroup.get(aUnit);\n const bGroup = unitToGroup.get(bUnit);\n\n if (aGroup === undefined || bGroup === undefined || aGroup !== bGroup) {\n if (isStrictMode || isPreserveMode) {\n if (isPreserveMode) {\n return new Dimension({\n number: calculate(aVal, op, bVal),\n unit: (\n op === '+' || op === '-'\n ? `${aUnit}±${bUnit}`\n : `${aUnit}${op}${bUnit}`\n )\n }).inherit(this);\n }\n /** Units don't match, and can't be converted */\n throw new TypeError('Incompatible units. Change the units or use the unit function');\n }\n /** Just coerce to the left-hand unit */\n return new Dimension({ number: calculate(aVal, op, bVal), unit: aUnit }).inherit(this);\n }\n\n const group = conversions[bGroup];\n // @ts-expect-error - set up proper indexing later\n let atomicUnit = group[aUnit] as number;\n // @ts-expect-error - set up proper indexing later\n let targetUnit = group[bUnit] as number;\n\n if (isPreserveMode && (op === '*' || op === '/')) {\n return new Dimension({\n number: calculate(aVal, op, bVal),\n unit: `${aUnit}${op}${bUnit}`\n }).inherit(this);\n }\n\n bVal = bVal / (atomicUnit / targetUnit);\n return new Dimension({ number: calculate(aVal, op, bVal), unit: aUnit }).inherit(this);\n }\n\n override compare(b: Node, context?: Context): 0 | 1 | -1 | undefined {\n if (b.type === 'Any') {\n const text = String(('value' in b ? b.value : '') ?? '').trim();\n if (!/^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)$/.test(text)) {\n return undefined;\n }\n return this.number === Number(text) ? 0 : undefined;\n }\n if (b.type === 'Quoted') {\n return undefined;\n }\n if (b.type === 'Bool') {\n return undefined;\n }\n if (!(b instanceof Dimension || b instanceof Color)) {\n return undefined;\n }\n let unitToGroup = this.unitToGroup;\n let unitMode = context?.opts?.unitMode ?? 'loose';\n let isStrictMode = unitMode === 'strict';\n let isPreserveMode = unitMode === 'preserve';\n let { number: aVal, unit: aUnit } = this;\n\n /** Normalize percentages to a number for numerical comparison */\n if (aUnit === '%') {\n aVal = aVal / 100;\n aUnit = undefined;\n }\n if (b instanceof Color) {\n if (aUnit) {\n let msg = `Cannot convert \"${this}\" to a color`;\n if (isStrictMode) {\n throw new TypeError(msg);\n } else {\n logger.warn(msg);\n }\n return super.compare(b, context);\n }\n let thisColor = new Color({ rgb: [aVal, aVal, aVal] }, { format: ColorFormat.RGB }).inherit(this);\n return thisColor.compare(b);\n }\n let { number: bVal, unit: bUnit } = b;\n if (bUnit === '%') {\n bVal = bVal / 100;\n bUnit = undefined;\n }\n\n if (!aUnit && !bUnit) {\n return Node.numericCompare(aVal, bVal);\n }\n if (!aUnit || !bUnit) {\n // Less guards allow unitless numbers to compare directly with dimensions.\n return Node.numericCompare(aVal, bVal);\n }\n if (aUnit && bUnit) {\n /** These are the only truly comparable dimensions */\n if (!aUnit) {\n return Node.numericCompare(aVal, bVal);\n }\n const aGroup = unitToGroup.get(aUnit);\n const bGroup = unitToGroup.get(bUnit!);\n\n if (aGroup === undefined || bGroup === undefined || aGroup !== bGroup) {\n if (isStrictMode || isPreserveMode) {\n /** Units don't match, and can't be converted */\n throw new TypeError('Incompatible units. Change the units or use the unit function');\n }\n return undefined;\n }\n const group = conversions[bGroup];\n // @ts-expect-error - set up proper indexing later\n let atomicUnit = group[aUnit] as number;\n // @ts-expect-error - set up proper indexing later\n let targetUnit = group[bUnit] as number;\n\n bVal = bVal / (atomicUnit / targetUnit);\n\n return Node.numericCompare(aVal, bVal);\n }\n return super.compare(b, context);\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n let { number, unit = '' } = this;\n\n // Check if unit is compound (contains '/', '*', or '±')\n const isCompoundUnit = unit && (unit.includes('/') || unit.includes('*') || unit.includes('±'));\n\n if (isCompoundUnit) {\n // Output as calc() for compound units\n // Parse the compound unit to reconstruct a valid calc() expression\n w.add('calc(', this);\n const numberStr = `${round(number, 8)}`.toLowerCase();\n\n // Parse compound unit to create calc expression\n if (unit.includes('/')) {\n // Division: \"px/s\" or \"1/s\" → calc(number * 1px / 1s) or calc(number / 1s)\n const parts = unit.split('/');\n const numerator = parts[0] || '1';\n const denominator = parts[1] || '1';\n if (numerator === '1') {\n // Special case: \"1/s\" means number / unit → calc(number / 1s)\n w.add(`${numberStr} / 1${denominator}`);\n } else {\n // General case: \"px/s\" → calc(number * 1px / 1s)\n w.add(`${numberStr} * 1${numerator} / 1${denominator}`);\n }\n } else if (unit.includes('*')) {\n // Multiplication: \"px*em\" → calc(number * 1px * 1em)\n // Example: 10px * 2em → 20 with unit \"px*em\" → calc(20 * 1px * 1em)\n const parts = unit.split('*');\n const units = parts.map(u => `1${u}`).join(' * ');\n w.add(`${numberStr} * ${units}`);\n } else if (unit.includes('±')) {\n // Addition/subtraction: \"px±em\" → calc(1px ± 1em)\n // Note: We don't have the original values, so this is approximate\n // The actual operation would be calc(aVal * 1px ± bVal * 1em)\n const parts = unit.split('±');\n const unit1 = parts[0] || '';\n const unit2 = parts[1] || '';\n // Output as calc(1unit1 + 1unit2) - approximation since we don't have original values\n w.add(`1${unit1} + 1${unit2}`);\n } else {\n // Fallback - shouldn't happen\n w.add(`${numberStr} * 1${unit}`);\n }\n w.add(')');\n } else {\n // Normal unit output\n const numberStr = `${round(number, 8)}`.toLowerCase();\n w.add(numberStr, this);\n if (unit) {\n w.add(unit);\n }\n }\n return w.getSince(mark);\n }\n\n /** @todo - move to visitors */\n // toCSS(context: Context, out: OutputCollector) {\n // out.add(this.toString(), this.location)\n // }\n\n // toModule(context: Context, out: OutputCollector) {\n // const pre = context.pre\n // out.add('$J.num({\\n' +\n // ` ${pre}value: ${this.data},\\n` +\n // ` ${pre}unit: \"${this.unit ?? ''}\"\\n` +\n // `${pre}})`\n // , this.location)\n // }\n}\n\nconst enum ConversionGroup {\n Length = 0,\n Duration = 1,\n Angle = 2\n}\n\nconst conversions = {\n [ConversionGroup.Length]: {\n m: 1,\n cm: 0.01,\n mm: 0.001,\n in: 0.0254,\n px: 0.0254 / 96,\n pt: 0.0254 / 72,\n pc: 0.0254 / 72 * 12\n } satisfies Record<LengthUnit, number>,\n [ConversionGroup.Duration]: {\n s: 1,\n ms: 0.001\n } satisfies Record<DurationUnit, number>,\n [ConversionGroup.Angle]: {\n rad: 1 / (2 * Math.PI),\n deg: 1 / 360,\n grad: 1 / 400,\n turn: 1\n } satisfies Record<AngleUnit, number>\n};\n\ndefineType(Dimension, 'Dimension');\n\nexport const dimension = (\n value: DimensionValue | [number, string] | number,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n) => {\n if (isArray(value)) {\n let [number, unit] = value;\n return new Dimension({ number, unit }, options, location, treeContext);\n }\n return new Dimension(typeof value === 'number' ? { number: value } : value, options, location, treeContext);\n};","import { type Context } from '../context.js';\nimport { Bool } from './bool.js';\nimport { Expression } from './expression.js';\nimport { Operation } from './operation.js';\nimport { Node, defineType, F_NON_STATIC, type OptionalLocation, type TreeContext } from './node.js';\nimport { Dimension } from './dimension.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\n\nexport type ParenOptions = {\n escaped?: boolean;\n delimiter?: 'paren' | 'square';\n};\n\nexport type ParenChildData = { value: Node | undefined };\n\nconst isOpOrExpression = (node: Node): node is Operation | Expression => {\n return node instanceof Operation || node instanceof Expression;\n};\n\n/**\n * An expression in parenthesis\n */\nexport interface Paren {\n type: 'Paren';\n shortType: 'paren';\n eval(context: Context): MaybePromise<Node>;\n}\n\nexport class Paren extends Node<Node | undefined, ParenOptions, ParenChildData> {\n static override childKeys = ['value'] as const;\n\n value: Node | undefined;\n\n constructor(value?: Node, options?: ParenOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n if (value instanceof Node) {\n this.adopt(value);\n }\n if (options?.escaped) {\n this.addFlag(F_NON_STATIC);\n }\n }\n\n private _isEscaped(_context?: Context): boolean {\n return Boolean(this.options?.escaped);\n }\n\n private _unwrapValue(value: Node, context?: Context): Node {\n let current = value;\n while (current instanceof Paren) {\n const next = current.get('value', context);\n if (!next) {\n break;\n }\n current = next;\n }\n return current;\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const parenOptions = this.options;\n const escapeChar = parenOptions?.escaped ? '~' : '';\n const delimiter = parenOptions?.delimiter ?? 'paren';\n const open = delimiter === 'square' ? '[' : '(';\n const close = delimiter === 'square' ? ']' : ')';\n if (escapeChar) {\n w.add(escapeChar, this);\n }\n w.add(open);\n let value = this.get('value', options.context);\n if (value) {\n if (value instanceof Node) {\n let out = w.capture(() => value.toString(options));\n w.add(out.replace(/^[ \\t\\r\\f]*|[ \\t\\r\\f]*$/g, ''), value);\n } else {\n w.add(String(value), this);\n }\n }\n w.add(close);\n return w.getSince(mark);\n }\n\n override evalNode(context: Context): MaybePromise<Node> {\n let value = this.get('value', context);\n if (value) {\n let isOp = isOpOrExpression(value);\n if (isOp) {\n context.parenFrames.push(true);\n }\n const maybeEvald = value.eval(context);\n const after = (v: Node): Node => {\n value = v;\n if (isOp) {\n context.parenFrames.pop();\n }\n if (this._isEscaped(context) && value instanceof Node) {\n return value;\n }\n const delimiter = this.options?.delimiter ?? 'paren';\n if (delimiter === 'paren') {\n value = this._unwrapValue(value, context);\n if (value instanceof Bool || value instanceof Dimension) {\n return value;\n }\n if (isOp && !isOpOrExpression(value)) {\n return value;\n }\n }\n const node = this.clone();\n const previousValue = node.value;\n node.value = value;\n if (previousValue instanceof Node && previousValue !== value) {\n previousValue.parent = undefined;\n }\n node.adopt(value);\n return node;\n };\n if (isThenable(maybeEvald)) {\n return (maybeEvald as Promise<Node>).then(after);\n }\n return after(maybeEvald as Node);\n }\n return this;\n }\n}\n\nexport const paren = defineType(Paren, 'Paren');\n","import { CALLER, CANONICAL, Node, defineType, F_VISIBLE, F_NON_STATIC, F_MAY_ASYNC, type OptionalLocation, type TreeContext } from './node.js';\nimport { type Context } from '../context.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { cast } from './util/cast.js';\nimport { callWithContext } from '../define-function.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { Paren } from './paren.js';\nimport { isThenable } from '@jesscss/awaitable-pipe';\nimport { evalMixinDirect, type MixinEntry, type Rules } from './rules.js';\nimport { Any } from './any.js';\nimport { List, list } from './list.js';\nimport { getParent, mergeDependencies, setDependency, setParent, setSourceParent } from './util/field-helpers.js';\nimport { finalizeInvocationOutputRules } from './util/mixin-instance-primitives.js';\nimport { addParentEdge } from './util/cursor.js';\n\nexport type CallValue = {\n /**\n * Can be an identifier or something like a mixin or variable lookup\n * e.g. $|#mixin|.class() is -> [Call name: [Ref (#mixin.class)], args: []]\n */\n name: string | Node;\n args?: List<Node>;\n /**\n * Optional content node, used for passing blocks to mixins/functions.\n * This is how Jess represents \"call with content block\" forms like:\n * $ > foo(): @{ ... }\n * or:\n * $ > foo(): @($x) { ... }\n */\n contentNode?: Node;\n};\n\nexport type CallOptions = {\n /**\n * Legacy Less feature -- if a ruleset is returned,\n * all the properties can be marked as important.\n */\n markImportant?: boolean;\n silentFail?: boolean;\n /** Parser-provided hint for modern color-call syntax (space/slash form). */\n modernSyntax?: boolean;\n};\n\n/**\n * This is an exported type that allows extra properties\n * and specifies the shape of `this` for a function call.\n */\nexport type ExtendedFn<T extends any[] = any[], R = any> = ((this: Context, ...args: T) => R) & {\n /**\n * Allow for optional calling, which means an optional\n * reference to a function will output a stringified\n * function representation if there's an evaluation error.\n *\n * This is done for Less, which sets this for functions\n * that have a CSS equivalent.\n */\n allowOptional?: boolean;\n evalArgs?: boolean;\n};\n\n/**\n * @note In Less, the ref for something like `rgb`\n * is not a string, but is an (optional) variable reference.\n */\nexport type CallChildData = { name: string | Node; args: List<Node> | undefined; contentNode: Node | undefined };\n\nexport interface Call {\n type: 'Call';\n shortType: 'call';\n}\n\nexport class Call extends Node<CallValue, CallOptions, CallChildData> {\n static override childKeys = ['name', 'args', 'contentNode'] as const;\n\n name!: string | Node;\n args: List<Node> | undefined;\n contentNode: Node | undefined;\n\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const name = this.get('name', ctx);\n const args = this.get('args', ctx);\n const contentNode = this.get('contentNode', ctx);\n const cloneData: CallValue = {\n name: deep && name instanceof Node ? name.clone(deep, cloneFn, ctx) : name,\n args: deep && args instanceof Node ? args.clone(deep, cloneFn, ctx) : args,\n contentNode: deep && contentNode instanceof Node ? contentNode.clone(deep, cloneFn, ctx) : contentNode\n };\n\n let priorChildParents: Array<[Node, Node | undefined]> | undefined;\n if (!deep) {\n priorChildParents = [];\n if (cloneData.name instanceof Node) {\n priorChildParents.push([cloneData.name, cloneData.name.parent]);\n }\n if (cloneData.args instanceof Node) {\n priorChildParents.push([cloneData.args, cloneData.args.parent]);\n }\n if (cloneData.contentNode instanceof Node) {\n priorChildParents.push([cloneData.contentNode, cloneData.contentNode.parent]);\n }\n }\n\n const options = this._meta?.options;\n const newNode: this = Reflect.construct(this.constructor, [\n cloneData,\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n ]);\n\n if (priorChildParents) {\n for (const [child, priorParent] of priorChildParents) {\n if (ctx) {\n setParent(child, newNode, ctx);\n }\n Reflect.set(child, 'parent', priorParent);\n }\n }\n\n newNode.inherit(this);\n return newNode;\n }\n\n constructor(value: CallValue, options?: CallOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.name = value.name;\n this.args = value.args;\n this.contentNode = value.contentNode;\n if (this.name instanceof Node) {\n this.adopt(this.name);\n }\n if (this.args instanceof Node) {\n this.adopt(this.args);\n }\n if (this.contentNode instanceof Node) {\n this.adopt(this.contentNode);\n }\n this.requiredSemi = true;\n // Function calls are always non-static and may be async\n this.addFlags(F_VISIBLE, F_NON_STATIC, F_MAY_ASYNC);\n }\n\n private _serializeCallArg(node: Node, options: PrintOptions): string {\n const context = options.context;\n if (isNode(node, N.Sequence)) {\n const children = node.get('value', context);\n const isQuotedConcatSequence = (\n children.some(child => isNode(child, N.Quoted))\n && children.every(child => isNode(child, N.Quoted | N.Any | N.Interpolated))\n );\n return children\n .map(child => this._serializeCallArg(child, options).replace(/^[ \\t\\r\\f]+|[ \\t\\r\\f]+$/g, ''))\n .join(isQuotedConcatSequence ? '' : ' ');\n }\n if (isNode(node, N.List)) {\n const sep = node.options?.sep ?? ',';\n const joiner = sep === '/' ? ' / ' : `${sep} `;\n return node.get('value', context)\n .map(child => this._serializeCallArg(child, options).replace(/^[ \\t\\r\\f]+|[ \\t\\r\\f]+$/g, ''))\n .join(joiner);\n }\n return options.writer!.capture(() => node.toString(options))\n .replace(/^[ \\t\\r\\f]+|[ \\t\\r\\f]+$/g, '');\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n const { silentFail, markImportant } = this.options ?? {};\n const name = this.get('name', context);\n const args = this.get('args', context);\n const contentNode = this.get('contentNode', context);\n if (typeof name === 'string') {\n w.add(name, this);\n } else {\n name.toString(options);\n }\n if (silentFail) {\n w.add('?');\n }\n w.add('(');\n if (args) {\n const normalizedArgs = args.get('value', context).filter(Boolean);\n const last = normalizedArgs.length - 1;\n for (let i = 0; i <= last; i++) {\n const arg = normalizedArgs[i]!;\n w.add(this._serializeCallArg(arg, options), arg);\n if (i < last) {\n w.add(', ');\n }\n }\n }\n w.add(')');\n if (markImportant) {\n w.add(' !important');\n }\n if (contentNode) {\n w.add(': ');\n contentNode.toString(options);\n }\n return w.getSince(mark);\n }\n\n /** Recursively makes declarations important */\n makeImportant(rules: Rules, context?: Context): Rules {\n const effectiveContext = (\n context\n && rules.renderKey !== CANONICAL\n && context.renderKey !== rules.renderKey\n )\n ? { ...context, renderKey: rules.renderKey }\n : context;\n const important: Any<'flag'> = new Any('!important', { role: 'flag' });\n for (const rule of rules.get('value', effectiveContext)) {\n if (isNode(rule, N.Declaration)) {\n rule.setCurrentImportant(important, effectiveContext);\n } else if (isNode(rule, N.Rules)) {\n this.makeImportant(rule, effectiveContext);\n } else if (isNode(rule, N.AtRule)) {\n const nestedRules = rule.get('rules');\n if (nestedRules) {\n this.makeImportant(nestedRules, effectiveContext);\n }\n } else if (isNode(rule, N.Ruleset)) {\n const nestedRules = rule.get('rules');\n if (nestedRules) {\n this.makeImportant(nestedRules, effectiveContext);\n }\n }\n }\n return rules;\n }\n\n /** Come back and redo -- too hard to reason about as a MaybePromise */\n override evalNode(context: Context): Promise<Node> {\n return (async () => {\n let name = this.get('name', context);\n let args = this.get('args', context);\n const callOptions = this.options ?? {};\n let { markImportant } = callOptions;\n const applyDependencyToResult = <T extends Node>(\n result: T,\n nodes?: readonly (Node | undefined)[]\n ): T => {\n const dependency = mergeDependencies(\n nodes ? [result, ...nodes] : [result],\n context\n );\n if (dependency?.dependsOn && dependency.dependsOn.size > 0) {\n setDependency(result, {\n dependsOn: new Set(dependency.dependsOn),\n sourceExpr: this\n }, context);\n }\n return result;\n };\n const adoptCallWhitespace = <T extends Node>(node: T): T => {\n node.pre = this.pre;\n node.post = this.post;\n node.sourceParent ??= this;\n return node;\n };\n const cloneLeafDownstreamResult = <T extends Node>(node: T): T => {\n return node.clone();\n };\n const materializeDownstreamResult = <T extends Node>(node: T): T => {\n if (node === node.sourceNode) {\n const childKeys = Reflect.get(node.constructor, 'childKeys');\n if (childKeys === null) {\n return cloneLeafDownstreamResult(node);\n }\n return node;\n }\n return node;\n };\n const materializeStylesheetFunctionRulesBoundary = <T extends Node>(node: T): T => {\n if (node === node.sourceNode && isNode(node, N.Rules)) {\n return node.clone(false, undefined, context);\n }\n return materializeDownstreamResult(node);\n };\n const evalArgNodes = async (nodes?: List<Node>) => {\n if (!nodes) {\n return undefined;\n }\n const out: Node[] = [];\n for (const node of nodes.get('value')) {\n out.push(await node.eval(context));\n }\n return list(out, nodes.options);\n };\n const anchorCallArgNodes = (nodes?: List<Node>) => {\n if (!nodes) {\n return;\n }\n for (const argNode of nodes.get('value')) {\n // Anchor property refs and callback mixins to the call-site scope\n // without cloning the arg tree.\n if (isNode(argNode, N.Reference) && argNode.options?.type === 'property') {\n setSourceParent(argNode, this, context);\n } else if (isNode(argNode, N.Mixin)) {\n setSourceParent(argNode, this, context);\n }\n }\n };\n\n context.callStack.push(this);\n context.parenFrames.push(false);\n\n if (process.env.JESS_DEBUG_LOCK === 'throw-call') {\n const rawName = String(name?.valueOf?.() ?? '');\n if (rawName.includes('.inner-locked-mixin')) {\n throw new Error(`[lock-call:raw] ${JSON.stringify({\n rawName,\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n renderKey: String(this.renderKey),\n rulesContext: context.rulesContext?.type,\n lookupScope: context.lookupScope?.type\n })}`);\n }\n }\n let n = typeof name === 'string' ? name : await name.eval(context);\n const debugRawKey = isNode(name, N.Reference)\n ? String(name.key?.valueOf?.() ?? '')\n : '';\n if (process.env.JESS_DEBUG_LOCK === 'log-call' && debugRawKey.includes('inner-locked-mixin')) {\n console.log('[lock-call]', {\n debugRawKey,\n resolvedType: Array.isArray(n) ? 'array' : n?.type ?? typeof n,\n resolvedName: typeof n === 'string' ? n : n?.valueOf?.(),\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n rulesContext: context.rulesContext?.type,\n lookupScope: context.lookupScope?.type\n });\n }\n if (process.env.JESS_DEBUG_LOCK === 'throw-call-resolved') {\n const resolvedName = String(n?.valueOf?.() ?? '');\n const rawName = String(name?.valueOf?.() ?? '');\n if (rawName.includes('.inner-locked-mixin') || resolvedName.includes('.inner-locked-mixin')) {\n throw new Error(`[lock-call:resolved] ${JSON.stringify({\n rawName,\n resolvedName,\n resolvedType: Array.isArray(n) ? 'array' : n?.type,\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n renderKey: String(this.renderKey),\n rulesContext: context.rulesContext?.type,\n lookupScope: context.lookupScope?.type\n })}`);\n }\n }\n // Resolve mixin reference only at call time (same as variable refs: evaluate when used, not when stored).\n if (isNode(n, N.Reference) && n.options?.type === 'mixin-ruleset') {\n n = await n.eval(context);\n }\n // Note: Stylesheet-defined functions should be represented as a Reference(type='function')\n // by parsers that support them. We intentionally avoid implicit string→function lookup here\n // to prevent surprising behavior for plain CSS function-like calls.\n // If the evaluated name is a Call node, execute it directly\n // This handles cases like @alias: .something(foo); @alias();\n if (isNode(n, N.Call)) {\n // Execute the inner Call node (it will handle its own callStack push/pop)\n const result = materializeDownstreamResult(await n.eval(context));\n // Apply markImportant if needed\n if (markImportant && isNode(result, N.Rules)) {\n this.makeImportant(result, context);\n }\n // Always pop the outer call's stack entries\n context.callStack.pop();\n context.parenFrames.pop();\n return adoptCallWhitespace(result);\n } else if (isNode(n, N.Mixin) || isNode(n, N.Ruleset) || Array.isArray(n)) {\n // Direct mixin invocation — skip getFunctionFromMixins/callWithContext wrapper\n const originalCaller = context.caller;\n context.caller = this;\n try {\n const result = await evalMixinDirect(context, n as MixinEntry | MixinEntry[], args);\n if (process.env.JESS_DEBUG_LOCK === 'throw-nil-call' && debugRawKey.includes('inner-locked-mixin') && isNode(result, N.Nil)) {\n throw new Error(`[lock-call:direct-nil] ${JSON.stringify({\n debugRawKey,\n resolvedType: Array.isArray(n) ? 'array' : n?.type,\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n rulesContext: context.rulesContext?.type,\n lookupScope: context.lookupScope?.type\n })}`);\n }\n // Result is already fully evaluated by the dispatch primitives — no re-eval.\n if (markImportant && isNode(result, N.Rules)) {\n this.makeImportant(result, context);\n }\n context.callStack.pop();\n context.parenFrames.pop();\n return adoptCallWhitespace(result);\n } finally {\n context.caller = originalCaller;\n }\n } else if (isNode(n, N.Func)) {\n // Execute stylesheet-defined functions via their evalCall behavior.\n const argNodes = await evalArgNodes(args) ?? list([]);\n const contentNode = this.get('contentNode', context);\n const originalCaller = context.caller;\n context.caller = this;\n try {\n const result = await n.evalCall(context, argNodes, contentNode);\n if (process.env.JESS_DEBUG_LOCK === 'throw-nil-call' && debugRawKey.includes('inner-locked-mixin') && isNode(result, N.Nil)) {\n throw new Error(`[lock-call:func-nil] ${JSON.stringify({\n debugRawKey,\n resolvedType: n.type,\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n rulesContext: context.rulesContext?.type,\n lookupScope: context.lookupScope?.type\n })}`);\n }\n context.callStack.pop();\n context.parenFrames.pop();\n return applyDependencyToResult(\n adoptCallWhitespace(materializeStylesheetFunctionRulesBoundary(result)),\n argNodes.get('value')\n );\n } finally {\n context.caller = originalCaller;\n }\n } else if (isNode(n, N.Collection)) {\n // If the evaluated name is Rules or Collection (detached rulesets),\n // return those rules directly, but only if args are empty\n // If args are provided, throw an error - you can't call Rules/Collection with arguments\n if (args && args.get('value').length > 0) {\n context.callStack.pop();\n context.parenFrames.pop();\n throw new ReferenceError(`Cannot call ${n.type} with arguments`);\n }\n let rules: Rules = n.createPlacementWrapper(context, context.nextRenderKey());\n const placementContext: Context = {\n ...context,\n renderKey: rules.renderKey,\n rulesContext: rules\n };\n // Detached-ruleset invocation keeps the definition-owned `.parent` /\n // `.sourceParent` chain and exposes caller ancestry through an\n // explicit secondary edge.\n addParentEdge(rules, CALLER, this);\n rules = await rules.eval(context);\n finalizeInvocationOutputRules(rules, placementContext);\n context.callStack.pop();\n context.parenFrames.pop();\n // Apply markImportant if needed\n if (markImportant) {\n this.makeImportant(rules, context);\n }\n return rules;\n }\n\n let fn = isNode(n, N.JsFunction) ? n.value : n;\n if (typeof fn === 'function') {\n const originalCaller = context.caller;\n context.caller = this;\n let didPopCallStack = false;\n try {\n const fnOptions = Reflect.get(fn, 'options');\n const hasParamMetadata = Boolean(fnOptions && Reflect.get(fnOptions, 'params'));\n if (args) {\n anchorCallArgNodes(args);\n if (!hasParamMetadata) {\n args = await evalArgNodes(args);\n anchorCallArgNodes(args);\n }\n }\n const result = await (\n args\n ? (\n hasParamMetadata\n ? callWithContext(context, fn, args)\n : callWithContext(context, fn, ...[...args.get('value')])\n )\n : callWithContext(context, fn)\n );\n if (process.env.JESS_DEBUG_LOCK === 'throw-nil-call' && debugRawKey.includes('inner-locked-mixin') && isNode(result, N.Nil)) {\n throw new Error(`[lock-call:jsfn-nil] ${JSON.stringify({\n debugRawKey,\n resolvedType: typeof fn,\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n rulesContext: context.rulesContext?.type,\n lookupScope: context.lookupScope?.type\n })}`);\n }\n context.caller = originalCaller;\n context.callStack.pop();\n didPopCallStack = true;\n if (isNode(result)) {\n let evald = result.eval(context);\n if (isThenable(evald)) {\n evald = await evald;\n }\n if (process.env.JESS_DEBUG_LOCK === 'throw-nil-call' && debugRawKey.includes('inner-locked-mixin') && isNode(evald, N.Nil)) {\n throw new Error(`[lock-call:jsfn-post-eval-nil] ${JSON.stringify({\n debugRawKey,\n resultType: result.type,\n parent: this.parent?.type,\n sourceParent: this.sourceParent?.type,\n rulesContext: context.rulesContext?.type,\n lookupScope: context.lookupScope?.type\n })}`);\n }\n if (markImportant && isNode(evald, N.Rules)) {\n this.makeImportant(evald, context);\n }\n return adoptCallWhitespace(evald);\n }\n let castResult = cast(result);\n if (isNode(castResult, N.Rules) && castResult.value.length === 1) {\n return adoptCallWhitespace(castResult.value[0]!);\n }\n return adoptCallWhitespace(castResult);\n } catch (e) {\n const unitMode = context?.opts?.unitMode ?? 'loose';\n const shouldRethrowForMode = unitMode === 'strict';\n if (e instanceof ReferenceError && e.message.includes('No matching mixins')) {\n if (getParent(this, context)?.type === 'SelectorCapture') {\n return adoptCallWhitespace(new Any(String(n.valueOf()), { role: 'ident' }).inherit(this));\n }\n if (isNode(name, N.Reference)) {\n throw new ReferenceError(`No matching mixins found for '${name.get('key').valueOf()}'`);\n }\n throw e;\n }\n if (!callOptions.silentFail || shouldRethrowForMode) {\n throw e;\n }\n let newCall = this.clone().inherit(this);\n /** Remove this flag for serialization */\n newCall.options.silentFail = false;\n newCall.name = isNode(name, N.Reference) && name.options.fallbackValue === true\n ? String(name.get('key'))\n : String(n.valueOf());\n newCall.args = await evalArgNodes(args);\n return applyDependencyToResult(adoptCallWhitespace(newCall), newCall.args?.get('value'));\n } finally {\n context.caller = originalCaller;\n context.parenFrames.pop();\n if (!didPopCallStack) {\n context.callStack.pop();\n }\n }\n } else {\n if (n === 'calc') {\n context.calcFrames++;\n }\n const evaluatedArgs = await evalArgNodes(args);\n\n if (n === 'calc') {\n context.calcFrames--;\n }\n context.parenFrames.pop();\n context.callStack.pop();\n const needsMaterializedClone = Boolean(callOptions.silentFail);\n const node = needsMaterializedClone\n ? this.clone()\n : this.clone();\n node.options.silentFail = false;\n if (\n n === 'calc' && evaluatedArgs\n ) {\n const evalArgItems = evaluatedArgs.get('value');\n if (isNode(evalArgItems[0], N.Dimension)) {\n return applyDependencyToResult(evalArgItems[0]!, evalArgItems);\n } else if (context.calcFrames !== 0) {\n return applyDependencyToResult(new Paren(evalArgItems[0]!), evalArgItems);\n }\n }\n node.name = n;\n node.args = evaluatedArgs;\n return applyDependencyToResult(adoptCallWhitespace(node), evaluatedArgs?.get('value'));\n }\n })().then(value => value);\n }\n}\n\ntype Params = ConstructorParameters<typeof Call>;\n\nexport const call = defineType(Call, 'Call') as (\n value: Params[0],\n options?: Params[1],\n location?: Params[2],\n treeContext?: Params[3]\n) => Call;\n","import { Node, defineType, F_VISIBLE, F_NON_STATIC, type NodeOptions, type OptionalLocation, type TreeContext } from './node.js';\nimport type { Context } from '../context.js';\nimport type { Operator } from './util/calculate.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\nimport { getPrintOptions, type PrintOptions } from './util/print.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { Call } from './call.js';\nimport { list } from './list.js';\nimport {\n mergeDependencies,\n setDependency,\n setEvaluated\n} from './util/field-helpers.js';\n\nexport type { Operator };\n/** Operation is always a tuple */\nexport type OperationValue = [\n left: Node,\n op: Operator,\n right: Node\n];\n\nexport type OperationChildData = { left: Node; operator: Operator; right: Node };\n\nexport interface Operation {\n type: 'Operation';\n shortType: 'op';\n}\n/**\n * A math operation OR a value with a slash. CSS is ambiguous\n * in syntax about which is which, so we just classify `value / value`\n * as an operation.\n */\nexport class Operation extends Node<OperationValue, NodeOptions, OperationChildData> {\n static override childKeys = ['left', 'right'] as const;\n\n left!: Node;\n private operator!: Operator;\n right!: Node;\n\n override clone(deep?: boolean): this {\n const options = this._meta?.options;\n const value: OperationValue = [\n deep ? this.left.clone(deep) : this.left,\n this.operator,\n deep ? this.right.clone(deep) : this.right\n ];\n const newNode: this = Reflect.construct(this.constructor, [\n value,\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n ]);\n newNode.inherit(this);\n return newNode;\n }\n\n constructor(value: OperationValue, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.left = value[0];\n this.operator = value[1];\n this.right = value[2];\n if (this.left instanceof Node) {\n this.adopt(this.left);\n }\n if (this.right instanceof Node) {\n this.adopt(this.right);\n }\n // Operations are always non-static, but can inherit may_async from children\n this.addFlags(F_VISIBLE, F_NON_STATIC);\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n const left = this.get('left', context);\n const op = this.operator;\n const right = this.get('right', context);\n let leftStr = w.capture(() => left.toString(options));\n let rightStr = w.capture(() => right.toString(options));\n w.add(leftStr.trimEnd(), left);\n w.add(` ${op} `, this);\n w.add(rightStr.trimStart(), right);\n return w.getSince(mark);\n }\n\n override evalNode(context: Context): MaybePromise<Node> {\n let n = this;\n const left = n.get('left', context);\n const op = n.operator;\n const right = n.get('right', context);\n const maybeLeft = left.eval(context);\n const applyMergedDependency = (result: Node, l: Node, r: Node): Node => {\n const dependency = mergeDependencies([l, r], context);\n if (dependency?.dependsOn && dependency.dependsOn.size > 0) {\n setDependency(result, {\n dependsOn: new Set(dependency.dependsOn),\n sourceExpr: this\n }, context);\n }\n return result;\n };\n const finalize = (l: Node, r: Node): MaybePromise<Node> => {\n if (context.shouldOperate(op, l, r)) {\n if (isNode(l, N.Operation) || isNode(r, N.Operation)) {\n // Preserve composite expressions such as `10px / 2 * 2` when a nested\n // operation intentionally remains unevaluated under current math mode.\n const outOperation = n.clone(false);\n outOperation.adopt(l, context);\n outOperation.adopt(r, context);\n Reflect.set(outOperation, 'left', l);\n Reflect.set(outOperation, 'right', r);\n return applyMergedDependency(outOperation, l, r);\n }\n const unitMode = context?.opts?.unitMode ?? 'preserve';\n const isPreserveMode = unitMode === 'preserve';\n\n // In preserve mode, catch unit errors and return calc() call\n if (isPreserveMode && isNode(l, N.Dimension) && isNode(r, N.Dimension)) {\n try {\n let out = l.operate(r, op, context);\n out.pre = left.pre;\n out.post = right.post;\n return out;\n } catch (error) {\n // If it's a unit error (TypeError), return calc(operation)\n if (error instanceof TypeError) {\n // Preserve canonical operation state by materializing an isolated wrapper when needed.\n const calcOperation = n.clone(false);\n calcOperation.adopt(l, context);\n calcOperation.adopt(r, context);\n Reflect.set(calcOperation, 'left', l);\n Reflect.set(calcOperation, 'right', r);\n setEvaluated(calcOperation, true, context);\n setEvaluated(l, true, context);\n setEvaluated(r, true, context);\n const calcCall = new Call({ name: 'calc', args: list([calcOperation]) });\n calcCall.pre = left.pre;\n calcCall.post = right.post;\n return applyMergedDependency(calcCall, l, r);\n }\n // Re-throw non-unit errors\n throw error;\n }\n }\n\n let out: Node;\n try {\n out = l.operate(r, op, context);\n } catch (error) {\n throw error;\n }\n out.pre = left.pre;\n out.post = right.post;\n return applyMergedDependency(out, l, r);\n }\n if (l === n.left && r === n.right) {\n return applyMergedDependency(n, l, r);\n }\n const outOperation = n.clone(false);\n outOperation.adopt(l, context);\n outOperation.adopt(r, context);\n Reflect.set(outOperation, 'left', l);\n Reflect.set(outOperation, 'right', r);\n return applyMergedDependency(outOperation, l, r);\n };\n const handleLeft = (l: Node): MaybePromise<Node> => {\n const maybeRight = right.eval(context);\n if (isThenable(maybeRight)) {\n return (maybeRight as Promise<Node>).then((r) => {\n return finalize(l, r);\n });\n }\n const r = maybeRight as Node;\n return finalize(l, r);\n };\n if (isThenable(maybeLeft)) {\n return (maybeLeft as Promise<Node>).then(handleLeft);\n }\n return handleLeft(maybeLeft as Node);\n }\n}\n\nexport const op = defineType(Operation, 'Operation', 'op');\n","import type { Class } from 'type-fest';\nimport {\n CANONICAL,\n Node,\n F_STATIC,\n defineType,\n type OptionalLocation,\n type RenderKey,\n type TreeContext\n} from './node.js';\nimport { isNode } from './util/is-node.js';\nimport { Nil } from './nil.js';\nimport type { Context } from '../context.js';\nimport { Interpolated } from './interpolated.js';\nimport { Any, type AnyRole } from './any.js';\nimport { Reference } from './reference.js';\nimport { List } from './list.js';\nimport { Sequence, spaced } from './sequence.js';\nimport { Operation } from './operation.js';\nimport { N } from './node-type.js';\nimport { Collection } from './collection.js';\nimport { Rules } from './rules.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, pipe, isThenable } from '@jesscss/awaitable-pipe';\nimport {\n getDependency,\n getParent,\n mergeDependencies,\n setDependency\n} from './util/field-helpers.js';\n\nexport const enum AssignmentType {\n Default = ':',\n Add = '+:', // similar to += in JS, but merges lists / sequences / collections\n // Subtract = '-:', // math subtraction, like -= in JS\n // Multiply = '*:', // math multiplication, like *= in JS\n // Divide = '/:', // math division, like /= in JS\n CondAssign = '?:', // similar to ??= in JS or !default in Sass\n // CondAdd = '?+:', // add if defined, otherwise assign\n // CondSubtract = '?-:', // subtract if defined, otherwise assign\n // CondMultiply = '?*:', // multiply if defined, otherwise assign\n // CondDivide = '?/:', // divide if defined, otherwise assign\n\n /** Legacy Less flags */\n MergeList = '&,:', // merge into a list if another prop exists with this flag\n MergeSequence = '&_:' // merge into a sequence if another prop exists with this flag\n}\n\nexport type DeclarationOptions = {\n assign?: AssignmentType;\n /** Tracks that this declaration was created via assignment normalization (e.g. +:, +_:). */\n normalizedFromAssign?: AssignmentType;\n semi?: boolean;\n /**\n * This doesn't prevent shadowing; it prevents declarations like:\n * ^$overwrite: foo;\n *\n * Written as `!$foo:` in Jess or imported from a readonly context\n */\n readonly?: boolean;\n /**\n * Instead of implicitly declaring or overriding,\n * requires a variable to previously be explicitly\n * declared within scope.\n *\n * Used by SCSS (!global) and Jess's (^$foo:)\n */\n setDefined?: boolean;\n\n /** Used by SCSS (!default) and Jess (?:) */\n // setIfUndefined?: boolean\n /**\n * Throw if already defined in the immediate scope\n * Will not throw if defined in a parent scope.\n *\n * Used by SCSS in the case of mixins... not Jess?\n */\n throwIfDefined?: boolean;\n};\n/** Should be Any<'property'> | Interpolated<'property'> */\ntype NameValue<T extends AnyRole = 'property'> = Any<T> | Interpolated<T>;\n\nexport type DeclarationValue<T extends AnyRole = 'property'> = {\n name: NameValue<T>;\n value: Node;\n /** The actual string representation of important, if it exists */\n important?: Any<'flag'>;\n};\n\n/**\n * A continuous collection of nodes.\n *\n * Initially, the name can be a Node or string.\n * Once evaluated, name must be a string\n */\nexport type DeclarationChildData = { name: NameValue; value: Node; important: Any<'flag'> | undefined };\n\nexport interface Declaration {\n type: 'Declaration' | 'VarDeclaration';\n shortType: 'decl' | 'vardecl';\n}\n\nexport class Declaration<Opts extends DeclarationOptions = DeclarationOptions> extends Node<DeclarationValue, Opts, DeclarationChildData> {\n static override childKeys = ['name', 'value', 'important'] as const;\n\n name!: NameValue;\n value!: Node;\n important: Any<'flag'> | undefined;\n\n private _getAssignmentRenderKey(context?: Context): RenderKey | undefined {\n return context?.renderKey\n ?? context?.rulesContext?.renderKey\n ?? (this.renderKey !== CANONICAL ? this.renderKey : undefined);\n }\n\n private _setFieldOverride<K extends keyof DeclarationChildData & ('name' | 'value' | 'important')>(\n key: K,\n value: DeclarationChildData[K],\n context?: Context\n ): void {\n const renderKey = this._getAssignmentRenderKey(context);\n const effectiveContext = renderKey !== undefined && context?.renderKey !== renderKey\n ? { ...context, renderKey }\n : context;\n\n if (value instanceof Node) {\n this.adopt(value, effectiveContext);\n }\n\n if (renderKey !== undefined && renderKey !== CANONICAL && this.renderKey !== renderKey) {\n const edgeKey = `${key}Edge` as const;\n const edge = ((this as unknown as Record<string, unknown>)[edgeKey] as Map<RenderKey, DeclarationChildData[K]> | undefined)\n ?? new Map<RenderKey, DeclarationChildData[K]>();\n edge.set(renderKey, value);\n (this as unknown as Record<string, unknown>)[edgeKey] = edge;\n return;\n }\n\n if (renderKey !== undefined && renderKey !== CANONICAL) {\n const edgeKey = `${key}Edge` as const;\n const edge = ((this as unknown as Record<string, unknown>)[edgeKey] as Map<RenderKey, DeclarationChildData[K]> | undefined);\n if (edge?.delete(renderKey) && edge.size === 0) {\n delete (this as unknown as Record<string, unknown>)[edgeKey];\n }\n }\n\n (this as unknown as Record<string, unknown>)[key] = value;\n }\n\n constructor(value: DeclarationValue, options?: Opts, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.name = value.name;\n this.value = value.value;\n this.important = value.important;\n if (this.name instanceof Node) {\n this.adopt(this.name);\n }\n if (this.value instanceof Node) {\n this.adopt(this.value);\n }\n if (this.important instanceof Node) {\n this.adopt(this.important);\n }\n this.allowRuleRoot = true;\n }\n\n /** If the value has curly braces, a semi-colon is not required */\n override get requiredSemi() {\n return this.requiresSemi();\n }\n\n requiresSemi(context?: Context): boolean {\n const value = this.get('value', context);\n return !isNode(value, N.Collection) && !isNode(value, N.Mixin);\n }\n\n isCustomProperty(context?: Context): boolean {\n return this.get('name', context).valueOf().startsWith('--');\n }\n\n getCurrentValue(context?: Context): Node {\n return this.get('value', context);\n }\n\n setCurrentValue(value: Node, context?: Context): void {\n this._setFieldOverride('value', value, context);\n }\n\n getCurrentName(context?: Context): NameValue {\n return this.get('name', context);\n }\n\n setCurrentName(name: NameValue, context?: Context): void {\n this._setFieldOverride('name', name, context);\n }\n\n getCurrentImportant(context?: Context): Any<'flag'> | undefined {\n return this.get('important', context);\n }\n\n setCurrentImportant(important: Any<'flag'> | undefined, context?: Context): void {\n this._setFieldOverride('important', important, context);\n }\n\n protected declTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const context = options.context;\n const name = this.get('name', context);\n const value = this.get('value', context);\n const important = this.get('important', context);\n const declarationOptions = this.options;\n const { assign = ':', setDefined } = declarationOptions ?? {};\n const mark = w.mark();\n // setDefined uses `:=` (with default spacing rules) instead of the historical `$^` prefix.\n const effAssign = (setDefined && assign === ':') ? ':=' : assign;\n let a = effAssign === ':' ? ':' : ` ${effAssign}`;\n // Serialize the property name so attached comments survive, then trim only\n // trailing whitespace before the assignment token.\n const normalizedName = w.capture(() => name.toString(options)).replace(/\\s+$/, '');\n w.add(`${normalizedName}${a}`, name);\n // Custom properties must preserve value text exactly as provided.\n const isCustomProperty = this.isCustomProperty(context);\n if (isCustomProperty) {\n options.inCustom = true;\n // Preserve custom value text, but normalize boundary artifacts:\n // - if capture ended with a line break before declaration termination,\n // drop that trailing line break so semicolon insertion stays inline.\n // - if a block comment is directly adjacent to a token (e.g. `a/*...*/`),\n // insert a single separator space for stable CSS output.\n let customOut = w.capture(() => value.toString(options));\n customOut = customOut.replace(/[ \\t\\r\\f]*\\n[ \\t\\r\\f]*$/g, '');\n customOut = customOut.replace(/([^\\s])\\/\\*/g, '$1 /*');\n w.add(customOut, value);\n options.inCustom = false;\n } else {\n // Capture value output to normalize spacing after ':'\n let valOut = '';\n try {\n valOut = w.capture(() => value.toString(options));\n } catch (error: unknown) {\n throw error;\n }\n const startsOnNextLine = /^[ \\t\\r\\f]*\\n/.test(valOut);\n const preserveLeadingMultilineValue = startsOnNextLine && /\\n[\\s\\S]*\\n/.test(valOut);\n if (preserveLeadingMultilineValue) {\n const normalizedValue = valOut.replace(/\\s+$/g, '');\n w.add(normalizedValue, value);\n } else {\n const normalizedValue = valOut.replace(/^\\s+|\\s+$/g, '');\n // Ensure exactly one space after ':' by adding one space\n w.add(' ');\n w.add(normalizedValue, value);\n }\n if (!isNode(value, N.Collection)) {\n if (important) {\n let imp = w.capture(() => important.toString(options));\n imp = imp.replace(/\\s+$/g, '');\n\n if (important.pre === 0) {\n imp = imp.replace(/^\\s+/g, '');\n w.add(imp, important);\n } else if (important.pre !== undefined) {\n w.add(imp, important);\n } else {\n w.add(` ${imp.trimStart()}`, important);\n }\n }\n }\n }\n return w.getSince(mark);\n }\n\n override toTrimmedString(options?: PrintOptions) {\n return this.declTrimmedString(options);\n }\n\n override preEval(context: Context): MaybePromise<this> {\n /** @removal-target — node-copy-reduction: maybeClone → return this.\n * Option changes should stay on the derived declaration instance. */\n let node = this.clone();\n node.preEvaluated = true;\n // Index should already be assigned by parent Rules\n return this._applyAssignmentNormalization(node, context);\n }\n\n private _applyAssignmentNormalization(node: this, context: Context): MaybePromise<this> {\n let name = node.get('name', context);\n let value = node.get('value', context);\n const excludesSelf = (candidate: Node): boolean => {\n const currentSource = node.sourceNode ?? node;\n const candidateSource = candidate.sourceNode ?? candidate;\n return candidate !== node && candidateSource !== currentSource;\n };\n const isPriorMergedDeclaration = (candidate: Node): candidate is Declaration => (\n excludesSelf(candidate)\n && isNode(candidate, N.Declaration)\n && candidate.options?.normalizedFromAssign !== undefined\n );\n\n const applyAssignmentNormalization = (key: Any<'property'>) => {\n /** Normalize assignment types */\n const nextOptions = {\n ...(node.options ?? {})\n } as Opts;\n let assign = nextOptions.assign;\n const rawAssign = assign as string | undefined;\n if (rawAssign === '+,:') {\n assign = AssignmentType.MergeList;\n } else if (rawAssign === '+_:') {\n assign = AssignmentType.MergeSequence;\n }\n if (assign && assign !== AssignmentType.Default) {\n const normalizedAssign = assign;\n value = value.clone();\n const cloneWithDependency = (source: Node): Node => {\n const cloned = source.clone(true, undefined, context);\n const dependency = getDependency(source, context);\n if (dependency?.dependsOn && dependency.dependsOn.size > 0) {\n setDependency(cloned, {\n dependsOn: new Set(dependency.dependsOn),\n sourceExpr: dependency.sourceExpr\n }, context);\n }\n return cloned;\n };\n const createAssignmentReference = (options: ConstructorParameters<typeof Reference>[1]) => {\n const ref = new Reference({ key }, options);\n if (node.index !== undefined) {\n ref.index = node.index;\n }\n return ref;\n };\n const findPreviousPropertyDeclaration = (): Declaration | undefined => {\n if (node.type !== 'Declaration') {\n return undefined;\n }\n let rulesScope = isNode(context.rulesContext, N.Rules) ? context.rulesContext as Rules : undefined;\n if (!rulesScope) {\n let cursor: Node | undefined = node;\n while (cursor && !isNode(cursor, N.Rules)) {\n cursor = getParent(cursor, context);\n }\n rulesScope = cursor as Rules | undefined;\n }\n if (!rulesScope) {\n return undefined;\n }\n const found = rulesScope.find('declaration', `${key.valueOf()}`, 'Declaration', {\n context,\n local: true,\n start: node.index,\n filter: isPriorMergedDeclaration\n });\n if (found) {\n return found;\n }\n const children = rulesScope.getRegistryChildren(context);\n const start = Math.min(\n Math.max((node.index ?? children.length) - 1, -1),\n children.length - 1\n );\n for (let i = start; i >= 0; i--) {\n const candidate = children[i];\n if (\n candidate\n && String((candidate as Declaration).name?.valueOf?.() ?? '') === key.valueOf()\n && isPriorMergedDeclaration(candidate)\n ) {\n return candidate;\n }\n }\n return undefined;\n };\n /** Reference type */\n let type: 'property' | 'variable' =\n node.type === 'Declaration' ? 'property' : 'variable';\n switch (assign) {\n case AssignmentType.MergeList:\n case AssignmentType.MergeSequence: {\n const ref = createAssignmentReference({\n type,\n fallbackValue: new Nil(),\n resolution: 'linear',\n respectStart: true,\n // Assignment normalization clears `assign` to Default, so matching by\n // assignment flag prevents later merge iterations from seeing prior values.\n // Only chain merged declarations together; plain prior declarations\n // remain independent output in Less.\n filter: isPriorMergedDeclaration\n });\n /**\n * @note - It's up to Sequence and List to handle\n * the merging of the values, if Nil()\n * or a nested list.\n */\n const isMergeListAssign = assign === AssignmentType.MergeList;\n value = isMergeListAssign\n ? new List([ref, value])\n : spaced([ref, value]);\n node.setCurrentValue(value, context);\n break;\n }\n case AssignmentType.Add: {\n if (node.type === 'Declaration') {\n const previousDeclaration = findPreviousPropertyDeclaration();\n if (!previousDeclaration) {\n node.setCurrentValue(value, context);\n break;\n }\n // Less property `+:` appends comma-separated items.\n // Use list composition (not generic `Operation +`) so scalar previous values\n // remain distinct list members rather than string-concatenating.\n node.setCurrentValue(new List([\n cloneWithDependency(previousDeclaration.getCurrentValue(context)),\n value\n ]), context);\n } else {\n node.setCurrentValue(new Operation([\n new Reference({ key }, { type }),\n '+',\n value\n ]), context);\n }\n break;\n }\n case AssignmentType.CondAssign: {\n node.setCurrentValue(new Reference({ key }, {\n type,\n fallbackValue: value\n }), context);\n break;\n }\n }\n nextOptions.normalizedFromAssign = normalizedAssign;\n nextOptions.assign = AssignmentType.Default;\n node.options = nextOptions as Opts;\n }\n const normalizedValue = node.get('value', context);\n const shouldResolveNormalizedAssignment = (\n assign !== undefined\n && assign !== AssignmentType.Default\n );\n const out = shouldResolveNormalizedAssignment\n ? normalizedValue.eval(context)\n : normalizedValue.preEval(context);\n if (isThenable(out)) {\n return out.then((value) => {\n node.setCurrentValue(value, context);\n return node;\n });\n }\n node.setCurrentValue(out, context);\n return node;\n };\n\n if (name instanceof Interpolated) {\n const maybeKey = name.eval(context);\n if (isThenable(maybeKey)) {\n return maybeKey.then((key) => {\n node.setCurrentName(key, context);\n return applyAssignmentNormalization(key);\n });\n }\n const key = maybeKey as Any<'property'>;\n node.setCurrentName(key, context);\n return applyAssignmentNormalization(key);\n }\n return applyAssignmentNormalization(name);\n }\n\n override evalNode(context: Context): MaybePromise<this | Nil> {\n const currentValue = this.get('value', context);\n const staticNestedCollection =\n isNode(currentValue, N.Collection)\n || (\n isNode(currentValue, N.Sequence)\n && (currentValue as Sequence).get('value').length > 0\n && isNode((currentValue as Sequence).get('value')[(currentValue as Sequence).get('value').length - 1]!, N.Collection)\n );\n if (this.hasFlag(F_STATIC) && !staticNestedCollection) {\n this.evaluated = true;\n return this;\n }\n return pipe(\n () => {\n let node = this;\n const copyDependency = (source: Node, target: Node) => {\n const dependency = getDependency(source, context);\n if (dependency?.dependsOn && dependency.dependsOn.size > 0) {\n setDependency(target, {\n dependsOn: new Set(dependency.dependsOn),\n sourceExpr: dependency.sourceExpr\n }, context);\n }\n };\n const cloneWithDependency = (source: Node): Node => {\n const cloned = source.clone(false);\n copyDependency(source, cloned);\n return cloned;\n };\n const splitNestedPropertyValue = (valueNode: Node): { baseValue?: Node; collection: Collection } | undefined => {\n if (isNode(valueNode, N.Collection)) {\n return { collection: valueNode as Collection };\n }\n if (!isNode(valueNode, N.Sequence)) {\n return undefined;\n }\n const items = [...(valueNode as Sequence).get('value')];\n if (items.length === 0) {\n return undefined;\n }\n const last = items[items.length - 1]!;\n if (!isNode(last, N.Collection)) {\n return undefined;\n }\n if (items.length === 1) {\n return { collection: last as Collection };\n }\n const baseItems = items.slice(0, -1).map(item => item.copy(true));\n const baseValue = baseItems.length === 1\n ? baseItems[0]!\n : new Sequence(baseItems, undefined, valueNode.location, this.treeContext);\n return { baseValue, collection: last as Collection };\n };\n const cloneImportant = () => node.important?.copy(true) as Any<'flag'> | undefined;\n const makePropertyName = (prefix: string, childName: NameValue): Any<'property'> =>\n new Any(\n `${prefix}-${String(childName.valueOf())}`,\n { role: 'property' },\n childName.location ?? node.location,\n this.treeContext\n );\n const expandNestedPropertyDeclaration = (declNode: Declaration): MaybePromise<Declaration | Rules | Nil> => {\n const nested = splitNestedPropertyValue(declNode.value);\n if (!nested) {\n return declNode;\n }\n\n const expanded: Node[] = [];\n const declCtor = declNode.constructor as Class<Declaration>;\n const prefix = String(declNode.name.valueOf());\n\n if (nested.baseValue) {\n expanded.push(new declCtor(\n {\n name: declNode.name.copy(true) as NameValue,\n value: nested.baseValue.copy(true),\n important: cloneImportant()\n },\n { ...declNode.options },\n declNode.location,\n this.treeContext\n ));\n }\n\n const entries = nested.collection.value.filter(\n child => isNode(child, N.Declaration) && !isNode(child, N.VarDeclaration)\n ) as Declaration[];\n\n const processEntry = (index: number): MaybePromise<void> => {\n if (index >= entries.length) {\n return;\n }\n\n const current = entries[index]!;\n const preEvaluated = current.preEval(context) as Declaration | Nil | Promise<Declaration | Nil>;\n const afterPreEval = (resolvedCurrent: Declaration | Nil): MaybePromise<void> => {\n if (resolvedCurrent instanceof Nil || !isNode(resolvedCurrent, N.Declaration) || isNode(resolvedCurrent, N.VarDeclaration)) {\n return processEntry(index + 1);\n }\n\n const prefixedDecl = new declCtor(\n {\n name: makePropertyName(prefix, resolvedCurrent.name as NameValue),\n value: resolvedCurrent.value.copy(true),\n important: (resolvedCurrent.important?.copy(true) as Any<'flag'> | undefined)\n },\n { ...resolvedCurrent.options },\n resolvedCurrent.location,\n this.treeContext\n );\n\n const evaluated = prefixedDecl.eval(context) as Declaration | Rules | Nil | Promise<Declaration | Rules | Nil>;\n const afterEval = (resolvedPrefixed: Declaration | Rules | Nil): MaybePromise<void> => {\n if (!(resolvedPrefixed instanceof Nil)) {\n if (isNode(resolvedPrefixed, N.Rules)) {\n expanded.push(...(resolvedPrefixed as Rules).value);\n } else {\n expanded.push(resolvedPrefixed as Declaration);\n }\n }\n return processEntry(index + 1);\n };\n\n return isThenable(evaluated)\n ? (evaluated as Promise<Declaration | Rules | Nil>).then(afterEval)\n : afterEval(evaluated as Declaration | Rules | Nil);\n };\n\n return isThenable(preEvaluated)\n ? (preEvaluated as Promise<Declaration | Nil>).then(afterPreEval)\n : afterPreEval(preEvaluated as Declaration | Nil);\n };\n\n const finish = () => new Rules(expanded, undefined, declNode.location, this.treeContext);\n const processed = processEntry(0);\n return isThenable(processed)\n ? (processed as Promise<void>).then(finish)\n : finish();\n };\n const normalizeMergedLeadingPlaceholder = () => {\n const normalizedAssign = node.options?.normalizedFromAssign;\n const isListMergedAssign =\n normalizedAssign === AssignmentType.Add\n || normalizedAssign === AssignmentType.MergeList;\n const nodeValue = node.get('value', context);\n if (!isListMergedAssign || !isNode(nodeValue, N.List)) {\n return;\n }\n const listValue = nodeValue.get('value', context);\n if (listValue.length === 0) {\n return;\n }\n const first = listValue[0]!;\n const isEmptyPlaceholder = (\n isNode(first, N.Nil)\n || (isNode(first, N.List) && first.get('value').length === 0)\n );\n if (!isEmptyPlaceholder) {\n return;\n }\n const rest = listValue.slice(1);\n if (rest.length === 0) {\n node.setCurrentValue(new Nil(), context);\n return;\n }\n if (rest.length === 1) {\n node.setCurrentValue(cloneWithDependency(rest[0]!), context);\n return;\n }\n const clonedRest = rest.map(item => cloneWithDependency(item));\n node.setCurrentValue(new List(clonedRest), context);\n const dependency = mergeDependencies(clonedRest, context);\n if (dependency?.dependsOn && dependency.dependsOn.size > 0) {\n setDependency(node.get('value', context), {\n dependsOn: new Set(dependency.dependsOn),\n sourceExpr: dependency.sourceExpr\n }, context);\n }\n };\n /** Pre-eval already evaluated the name, just need to do value (if not a var declaration) */\n if (node.type === 'VarDeclaration') {\n return node;\n }\n const value = node.get('value', context);\n if (value instanceof Node) {\n const isCustomProperty = node.isCustomProperty(context);\n if (isCustomProperty) {\n const hasInterpolation =\n value.type === 'Interpolated'\n || [...value.children(true)].some(child => child.type === 'Interpolated');\n if (!hasInterpolation) {\n return node;\n }\n context.inCustom = true;\n }\n const maybeNewValue = value.eval(context);\n if (isThenable(maybeNewValue)) {\n return (maybeNewValue as Promise<Node>).then((newValue) => {\n context.inCustom = false;\n if (newValue instanceof Nil) {\n return newValue.inherit(node);\n }\n node.setCurrentValue(newValue, context);\n normalizeMergedLeadingPlaceholder();\n copyDependency(newValue, node.get('value', context));\n // Merge !important from referenced declarations\n if (context.hasImportantSource && !node.get('important', context)) {\n node.setCurrentImportant(Any.create('!important', { role: 'flag' }) as Any<'flag'>, context);\n }\n // Pop important source after merging (if it was set)\n if (context.hasImportantSource) {\n context.popImportantSource();\n }\n return node;\n });\n }\n context.inCustom = false;\n if (maybeNewValue instanceof Nil) {\n return (value as Nil).inherit(node);\n }\n node.setCurrentValue(maybeNewValue as Node, context);\n normalizeMergedLeadingPlaceholder();\n copyDependency(maybeNewValue as Node, node.get('value', context));\n const expanded = expandNestedPropertyDeclaration(node);\n if (isThenable(expanded)) {\n return (expanded as Promise<Declaration | Rules | Nil>).then((resolvedExpanded) => {\n if (context.hasImportantSource && !node.get('important', context) && isNode(resolvedExpanded, N.Declaration)) {\n (resolvedExpanded as Declaration).setCurrentImportant(Any.create('!important', { role: 'flag' }) as Any<'flag'>, context);\n }\n if (context.hasImportantSource) {\n context.popImportantSource();\n }\n return resolvedExpanded;\n });\n }\n if (expanded !== node) {\n if (context.hasImportantSource) {\n context.popImportantSource();\n }\n return expanded;\n }\n // Merge !important from referenced declarations\n if (context.hasImportantSource && !node.get('important', context)) {\n node.setCurrentImportant(Any.create('!important', { role: 'flag' }) as Any<'flag'>, context);\n }\n // Pop important source after merging (if it was set)\n if (context.hasImportantSource) {\n context.popImportantSource();\n }\n }\n return node;\n }\n ) as MaybePromise<this | Nil>;\n }\n}\n\nexport type DeclarationParams = ConstructorParameters<typeof Declaration>;\n\ndefineType<DeclarationValue>(Declaration, 'Declaration', 'decl');\n\nexport const decl = (\n value: DeclarationValue<AnyRole> | { name: string; value: Node; important?: Any<'flag'> },\n options?: DeclarationOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n) => {\n let { name } = value;\n value.name = typeof name === 'string' ? new Any(name, { role: 'property' }) : name;\n return new Declaration(value as DeclarationValue, options, location, treeContext);\n};\n","import {\n Declaration,\n type DeclarationValue,\n type DeclarationOptions\n} from './declaration.js';\nimport { Any, type AnyRole } from './any.js';\nimport { defineType, F_VISIBLE, type OptionalLocation, type Node, type TreeContext } from './node.js';\nimport { Nil } from './nil.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\n\nexport type VarDeclarationOptions = DeclarationOptions & {\n paramVar?: boolean;\n};\n\n/**\n * @example\n * Jess: `$foo: 1`\n * Less: `@foo: 1`\n * SCSS: `$foo: 1`\n *\n * @example `setDefined`\n * Jess: `$^foo: 1`\n * SCSS: `$foo: 1 !global`\n *\n *\n * @todo Support destructuring\n * e.g. `$(var1, var2): 1 2`\n */\nexport interface VarDeclaration {\n type: 'VarDeclaration';\n shortType: 'vardecl';\n}\n\nexport class VarDeclaration extends Declaration<VarDeclarationOptions> {\n constructor(\n value: DeclarationValue,\n options?: VarDeclarationOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n super(value, options, location, treeContext);\n this.allowRoot = true;\n this.allowRuleRoot = true;\n this.removeFlag(F_VISIBLE);\n /** Parameter declarations are not like var declarations */\n if (options?.paramVar) {\n this.addFlag(F_VISIBLE);\n }\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n // Vars always print with `$` prefix; setDefined affects the assignment token.\n //\n // Special-case parameter vars (used in mixin signatures) that have no default value:\n // print `$name` (no `: <value>`).\n if (this.options?.paramVar && this.get('value') instanceof Nil) {\n w.add('$', this);\n const normalizedName = String(this.get('name')).replace(/\\s+$/, '');\n w.add(normalizedName, this.get('name'));\n return w.getSince(mark);\n }\n\n w.add('$', this);\n const before = w.mark();\n const s = this.declTrimmedString(options);\n const emitted = w.getSince(before);\n if (!emitted && s) {\n w.add(s);\n }\n return w.getSince(mark);\n }\n}\ndefineType<DeclarationValue>(VarDeclaration, 'VarDeclaration', 'vardecl');\n\nexport const vardecl = (\n value: DeclarationValue<AnyRole> | { name: string; value: Node; important?: Any<'flag'> },\n options?: VarDeclarationOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n) => {\n let { name } = value;\n value.name = typeof name === 'string' ? new Any(name, { role: 'property' }) : name;\n return new VarDeclaration(value as DeclarationValue, options, location, treeContext);\n};\n","import { Context } from '../../context.js';\nimport { EVAL, Node } from '../node-base.js';\n\nimport { Bool } from '../bool.js';\nimport type { Condition } from '../condition.js';\nimport { Nil } from '../nil.js';\nimport { Rules } from '../rules.js';\nimport type { Ruleset } from '../ruleset.js';\nimport type { AtRule } from '../at-rule.js';\nimport type { VarDeclaration } from '../declaration-var.js';\nimport { VarDeclaration as VarDeclarationCtor } from '../declaration-var.js';\nimport { list, type List } from '../list.js';\nimport { Sequence } from '../sequence.js';\nimport { Any } from '../any.js';\nimport { N } from '../node-type.js';\nimport { CALLER, CANONICAL, F_VISIBLE } from '../node.js';\nimport { isNode } from './is-node.js';\nimport { comparePosition } from './compare.js';\nimport { getParent, getSourceParent, setChildren, setParent, setSourceParent } from './field-helpers.js';\nimport { addParentEdge } from './cursor.js';\nimport type { Mixin } from '../mixin.js';\nimport { isThenable, type MaybePromise } from '@jesscss/awaitable-pipe';\nimport { cast } from './cast.js';\nimport { isPlainObject } from './collections.js';\nimport type { MixinEntry } from '../rules.js';\nimport type { RenderKey } from '../node-base.js';\nimport { getCurrentParentNode } from './selector-utils.js';\n\nexport const enum MixinDefaultGroup {\n FalseEither = -1,\n None = 0,\n True = 1,\n False = 2\n}\n\nexport type PreparedMixinCandidateInvocation = {\n rules: Rules;\n params: List<Node> | undefined;\n outerRules: Rules | undefined;\n};\n\nexport type EvaluatedMixinGuard = {\n passes: boolean;\n outerRules: Rules | undefined;\n defaultGroup?: MixinDefaultGroup;\n};\n\nexport type PendingMixinDefaultCandidate<TCandidate = unknown> = {\n candidate: TCandidate;\n rules: Rules;\n outerRules?: Rules;\n params?: List<Node>;\n group: MixinDefaultGroup;\n lookupScope?: Rules;\n};\n\nexport type ProcessPreparedMixinCandidateOptions<TCandidate> = {\n candidate: TCandidate;\n rules: Rules;\n params?: List<Node>;\n outerRules?: Rules;\n guard?: Condition | Bool;\n parent: Node | undefined;\n guardScopeChildren?: readonly Node[];\n hasAnyDefault: boolean;\n candidateHasDefault: boolean;\n context: Context;\n evaluateCandidateOutput: (\n candidate: TCandidate,\n rules: Rules,\n outerRules: Rules | undefined,\n params: List<Node> | undefined,\n ) => MaybePromise<void>;\n};\n\nconst bindableParamTemplates = new WeakMap<Node, VarDeclaration>();\nconst restParamTemplates = new WeakMap<Node, VarDeclaration>();\nfunction getCurrentRulesetGuard(\n ruleset: Ruleset,\n context: Context\n): Node | undefined {\n return ruleset.get('guard', context) as Node | undefined;\n}\n\nfunction getCurrentMixinParams(\n mixin: Mixin,\n context: Context | RenderKey | undefined\n): List<Node> | undefined {\n return mixin.get('params', context) as List<Node> | undefined;\n}\n\nfunction getCanonicalSourceParent(\n node: Node | undefined\n): Node | undefined {\n return node?.sourceParent;\n}\n\nfunction getBindableParamTemplate(\n param: Node,\n context: Context\n): VarDeclaration {\n const cached = bindableParamTemplates.get(param);\n if (cached) {\n return cached;\n }\n const name = String(param.valueOf());\n const template = new VarDeclarationCtor({\n name: new Any(name, { role: 'property' }),\n value: new Nil()\n }, { paramVar: true }, param.location, context.treeContext);\n bindableParamTemplates.set(param, template);\n return template;\n}\n\nfunction getRestParamTemplate(\n param: Node,\n restName: string,\n context: Context\n): VarDeclaration {\n const cached = restParamTemplates.get(param);\n if (cached) {\n return cached;\n }\n const template = new VarDeclarationCtor({\n name: new Any(restName, { role: 'property' }),\n value: new Nil()\n }, { paramVar: true }, param.location, context.treeContext);\n restParamTemplates.set(param, template);\n return template;\n}\n\n/**\n * Follow a Rules node back to its canonical source root. Mixin/ruleset\n * candidate setup wants this shared notion of \"the source rules subtree\" so\n * that eval state subtrees are always created against the canonical backing body.\n */\nexport function getRootSourceRules(rules: Rules): Rules {\n let current = rules;\n const seen = new Set<Rules>();\n while (current.sourceNode && isNode(current.sourceNode, N.Rules)) {\n const next = current.sourceNode as Rules;\n if (next === current || seen.has(next)) {\n break;\n }\n seen.add(current);\n current = next;\n }\n return current;\n}\n\n/**\n * Resolve the canonical source rules for a mixin-like candidate and create a\n * per-call eval state subtree when a session is active.\n */\nexport function createMixinCandidateInstanceRoot(\n _candidate: MixinEntry,\n _context: Context\n): undefined {\n return undefined;\n}\n\n/**\n * Apply the final return policy for mixin invocation output.\n *\n * - Context receivers get a live `Rules` result (or `Nil` if empty), with\n * `ruleCounter` assigned on first return.\n * - Non-Context receivers get a plain object view, preserving legacy\n * `getFunctionFromMixins()` semantics.\n */\nexport function finalizeMixinInvocationReturn(\n output: Rules,\n receiver: Context | Node\n): Rules | Nil | ReturnType<Rules['toObject']> {\n if (receiver instanceof Context) {\n output.index ??= receiver.ruleCounter++;\n if (output.value.length === 0) {\n return new Nil();\n }\n return output;\n }\n return output.toObject();\n}\n\n/**\n * Bind one mixin param through the active eval state subtree instead of mutating the\n * canonical VarDeclaration. This is the smallest useful primitive behind direct\n * mixin invocation.\n */\nexport function bindMixinParamValue(\n param: VarDeclaration,\n value: Node,\n context: Context\n): void {\n param.value = value;\n param.adopt(value, context);\n}\n\n/**\n * Create the transient scope that holds bound mixin parameters. This is the\n * direct replacement for the inlined outerRules construction in\n * getFunctionFromMixins().\n */\nexport function createMixinParamScope(\n index: number,\n renderKey: RenderKey\n): Rules {\n const scope = Rules.create([], {\n rulesVisibility: {\n Ruleset: 'public',\n Declaration: 'public',\n VarDeclaration: 'public',\n Mixin: 'public'\n }\n });\n scope.index = index;\n scope.renderKey = renderKey;\n return scope;\n}\n\nfunction createRenderOwnedSequence(\n items: readonly Node[],\n renderKey: RenderKey,\n context: Context\n): Sequence {\n const sequence = new Sequence([], { forceSpacing: true }, undefined, context.treeContext);\n sequence.renderKey = renderKey;\n (sequence as unknown as { value: Node[] }).value = [...items];\n const edgeContext = { ...context, renderKey };\n for (const item of items) {\n setParent(item, sequence, edgeContext);\n }\n return sequence;\n}\n\n/**\n * Register already-bound parameter declarations into the transient mixin scope.\n * Matching/rest conversion still happens outside this helper; this primitive is\n * only responsible for making those params visible to lookup.\n */\nexport function populateMixinParamScope(\n scope: Rules,\n params: List<Node>,\n context: Context\n): void {\n const paramItems = params.get('value');\n for (let i = 0; i < paramItems.length; i++) {\n const param = paramItems[i]!;\n if (!isNode(param, N.VarDeclaration)) {\n continue;\n }\n if (param.index === undefined) {\n param.index = -(i + 1);\n }\n param.options ??= {};\n param.options.paramVar = true;\n param.removeFlag(F_VISIBLE);\n const name = String(param.get('name', scope.renderKey).valueOf());\n setParent(param, scope, context);\n scope.setInvocationBinding(name, { declaration: param });\n }\n}\n\n/**\n * Define the Less-style @arguments variable inside the transient mixin scope.\n * This stays a separate primitive so direct mixin invocation can reuse it\n * without dragging along the rest of getFunctionFromMixins().\n */\nexport function defineMixinArgumentsInScope(\n scope: Rules,\n params: List<Node> | undefined,\n nodeArgs: readonly Node[],\n context: Context\n): void {\n scope.setInvocationBinding('arguments', {\n factory: (rules, bindingContext) => {\n const nextRenderKey = rules.renderKey;\n const paramValues = params?.get('value', nextRenderKey)\n .filter((p): p is VarDeclaration => isNode(p, N.VarDeclaration))\n .map(p => p.get('value', nextRenderKey))\n .filter((value): value is Node => value instanceof Node);\n const argumentNodes = (paramValues && paramValues.length > 0) ? paramValues : nodeArgs;\n const argumentsArgs: Node[] = [];\n for (const argNode of argumentNodes) {\n if (isNode(argNode, N.Sequence) && (argNode as Sequence).get('value', nextRenderKey).length > 1) {\n argumentsArgs.push(...(argNode as Sequence).get('value', nextRenderKey));\n } else {\n argumentsArgs.push(argNode);\n }\n }\n const argumentsDecl = new VarDeclarationCtor({\n name: new Any('arguments', { role: 'property' }),\n value: createRenderOwnedSequence(argumentsArgs, nextRenderKey, bindingContext ?? context)\n }, { readonly: true, paramVar: true });\n argumentsDecl.removeFlag(F_VISIBLE);\n argumentsDecl.renderKey = nextRenderKey;\n argumentsDecl.preEvaluated = true;\n argumentsDecl.evaluated = true;\n return argumentsDecl;\n }\n });\n}\n\n/**\n * Seed a fresh reset-eval guard scope from the active param scope without\n * touching canonical parentage. The returned scope is safe to reuse for a\n * single guard probe.\n */\nexport function seedMixinGuardScope(\n scope: Rules | undefined,\n guardParent: Node | undefined,\n guardNode: Node | undefined,\n context: Context,\n scopeChildren?: readonly Node[]\n): Rules {\n const nextScope = scope ?? Rules.create([]);\n setParent(nextScope, guardParent, context);\n const activeChildren = scopeChildren ?? nextScope.getRegistryChildren(context);\n if (scopeChildren) {\n setChildren(nextScope, activeChildren, context, { markDirty: false });\n } else {\n for (const child of activeChildren) {\n setParent(child, nextScope, context);\n }\n }\n if (guardNode) {\n nextScope.adopt(guardNode, context);\n }\n return nextScope;\n}\n\nfunction captureMixinScopeSnapshot(\n scope: Rules | undefined,\n scopeChildren: readonly Node[] | undefined,\n context: Context\n): Rules | undefined {\n if (!scope) {\n return undefined;\n }\n const capturedChildren = scopeChildren ?? scope.getRegistryChildren(context);\n const captured = scope.createPlacementWrapperWithChildren(\n capturedChildren,\n scope.renderKey\n );\n captured.parent = getParent(scope, context);\n captured.sourceParent = scope.sourceParent;\n return captured;\n}\n\n/**\n * Prepare the transient scope used by a single mixin invocation. This is the\n * smallest complete lookup-ready scope primitive for direct canonical-body eval:\n * the caller gets a param scope with registered params / @arguments and the\n * canonical body attached through state parent shadow only.\n */\nexport function prepareMixinInvocationScope(\n definitionParent: Node | undefined,\n placementParent: Node | undefined,\n sourceParent: Node | undefined,\n index: number,\n renderKey: RenderKey,\n params: List<Node> | undefined,\n nodeArgs: readonly Node[],\n context: Context\n): Rules | undefined {\n if (!params) {\n return undefined;\n }\n const scope = createMixinParamScope(index, renderKey);\n populateMixinParamScope(scope, params, context);\n defineMixinArgumentsInScope(scope, params, nodeArgs, context);\n scope.parent = placementParent ?? definitionParent;\n scope.sourceParent = sourceParent;\n return scope;\n}\n\nexport function createMixinInvocationRules(\n body: Rules,\n lookupParent: Node | undefined,\n lexicalSourceParent: Node | undefined,\n sourceParent: Node | undefined,\n index: number,\n context: Context,\n renderKey: RenderKey\n): Rules {\n const wrapper = body.createShallowBodyWrapper(undefined, renderKey);\n wrapper.index = index;\n wrapper.parent = lookupParent;\n wrapper.sourceParent = sourceParent ?? lexicalSourceParent;\n\n wrapper.options = {\n ...wrapper.options,\n rulesVisibility: {\n ...(wrapper.options.rulesVisibility ?? {}),\n VarDeclaration: 'public'\n }\n };\n return wrapper;\n}\n\nfunction bindStructuralSourceParent(\n node: Node,\n sourceParent: Node,\n context: Context,\n seen: Set<Node> = new Set()\n): void {\n if (seen.has(node)) {\n return;\n }\n seen.add(node);\n node.sourceParent = sourceParent;\n setSourceParent(node, sourceParent, context);\n if (\n node.renderKey !== undefined\n && node.renderKey !== CANONICAL\n && node.renderKey !== context.renderKey\n ) {\n setSourceParent(node, sourceParent, {\n ...context,\n renderKey: node.renderKey\n } as Context);\n }\n const childKeys = (node.constructor as typeof Node).childKeys;\n if (!childKeys) {\n return;\n }\n for (const key of childKeys) {\n const value = (node as unknown as Record<string, unknown>)[key];\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item instanceof Node) {\n bindStructuralSourceParent(item, sourceParent, context, seen);\n }\n }\n continue;\n }\n if (value instanceof Node) {\n bindStructuralSourceParent(value, sourceParent, context, seen);\n }\n }\n}\n\nfunction bindStructuralParentTree(\n node: Node,\n parent: Node,\n context: Context,\n seen: Set<Node> = new Set()\n): void {\n if (seen.has(node)) {\n return;\n }\n seen.add(node);\n setParent(node, parent, context);\n const childKeys = (node.constructor as typeof Node).childKeys;\n if (!childKeys) {\n return;\n }\n for (const key of childKeys) {\n const value = (node as unknown as Record<string, unknown>)[key];\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item instanceof Node) {\n bindStructuralParentTree(item, node, context, seen);\n }\n }\n continue;\n }\n if (value instanceof Node) {\n bindStructuralParentTree(value, node, context, seen);\n }\n }\n}\n\nfunction projectParentChainForRenderKey(\n node: Node | undefined,\n sourceContext: Context,\n targetContext: Context,\n seen: Set<Node> = new Set()\n): void {\n if (!node || seen.has(node)) {\n return;\n }\n seen.add(node);\n const nodeSourceContext = {\n ...sourceContext,\n renderKey: node.renderKey ?? sourceContext.renderKey\n } as Context;\n const parent = getParent(node, nodeSourceContext);\n if (!parent) {\n return;\n }\n if (getParent(node, targetContext) !== parent) {\n setParent(node, parent, targetContext);\n }\n projectParentChainForRenderKey(parent, sourceContext, targetContext, seen);\n}\n\nfunction anchorCallSiteValue(\n value: Node,\n sourceParent: Node,\n context: Context\n): void {\n if (\n getSourceParent(value, context) === undefined\n && isNode(value, N.Reference | N.Mixin | N.Sequence | N.List | N.Rules | N.Ruleset | N.AtRule)\n ) {\n setSourceParent(value, sourceParent, context);\n }\n}\n\nfunction getUsableInvocationSourceParent(\n sourceParent: Node | undefined,\n fallback: Node | undefined\n): Node | undefined {\n if (sourceParent && !isNode(sourceParent, N.Reference | N.Call)) {\n return sourceParent;\n }\n return fallback;\n}\n\n/**\n * Normalize mixin params for invocation-time lookup registration.\n *\n * Rest params must become VarDeclarations before they can participate in the\n * transient param scope. Keep that conversion here instead of inline inside the\n * candidate loop.\n */\nexport function normalizeMixinInvocationParams(\n params: List<Node> | undefined,\n context: Context\n): List<Node> | undefined {\n if (!params) {\n return undefined;\n }\n\n let unnamedRestCount = 0;\n const paramItems = params.get('value');\n for (let i = 0; i < paramItems.length; i++) {\n const param = paramItems[i]!;\n if (param.type !== 'Rest') {\n continue;\n }\n\n let restName: string;\n if (typeof (param as any).value === 'string') {\n restName = (param as any).value;\n } else {\n restName = unnamedRestCount === 0 ? 'rest' : `rest${unnamedRestCount + 1}`;\n unnamedRestCount++;\n }\n\n const restValue = isNode((param as any).value)\n ? (param as any).value as Node\n : (\n context.treeContext?.file\n ? new Sequence([])\n : new Any(restName, { role: 'property' })\n );\n const restVarDecl = new VarDeclarationCtor({\n name: new Any(restName, { role: 'property' }),\n value: restValue\n }, { paramVar: true });\n\n params.value[i] = restVarDecl;\n params.adopt(restVarDecl, context);\n }\n\n return params;\n}\n\nfunction buildBoundMixinParams(\n params: List<Node> | undefined,\n nodeArgs: readonly Node[],\n bindingSourceParent: Node | undefined,\n renderKey: RenderKey,\n context: Context\n): List<Node> | undefined {\n if (!params) {\n return undefined;\n }\n\n const namedArgs = new Map<string, Node>();\n const positionalArgs: Node[] = [];\n for (const arg of nodeArgs) {\n if (isNode(arg, N.VarDeclaration)) {\n const argName = String((arg as VarDeclaration).get('name').valueOf());\n const argValue = (arg as VarDeclaration).get('value') as Node;\n namedArgs.set(argName, argValue);\n } else {\n positionalArgs.push(arg);\n }\n }\n\n const bindingContext = { ...context, renderKey };\n const boundParams = list([], params.options ? { ...params.options } : undefined);\n let positionalIndex = 0;\n const cloneDefaultParamValue = (value: Node): Node => {\n return value.clone(false, undefined, bindingContext);\n };\n const cloneBoundParamTemplate = (\n param: VarDeclaration,\n boundValue: Node | undefined\n ): VarDeclaration => {\n const boundParam = param.clone(false, undefined, bindingContext) as VarDeclaration;\n boundParam.renderKey = renderKey;\n boundParam.options = { ...(boundParam.options ?? {}), paramVar: true };\n boundParam.preEvaluated = true;\n boundParam.evaluated = true;\n if (boundValue) {\n boundParam.setCurrentValue(boundValue, bindingContext);\n }\n return boundParam;\n };\n\n for (let index = 0; index < params.get('value').length; index++) {\n const param = params.get('value')[index]!;\n\n if (isNode(param, N.VarDeclaration)) {\n const paramDecl = param as VarDeclaration;\n const name = String(paramDecl.get('name').valueOf());\n\n const hasNamedArg = namedArgs.has(name);\n const hasPositionalArg = positionalIndex < positionalArgs.length;\n const boundValue = hasNamedArg\n ? namedArgs.get(name)!\n : hasPositionalArg\n ? positionalArgs[positionalIndex++]!\n : cloneDefaultParamValue(paramDecl.get('value'));\n if (\n bindingSourceParent\n && isNode(boundValue)\n ) {\n anchorCallSiteValue(boundValue, bindingSourceParent, bindingContext);\n }\n const boundParam = cloneBoundParamTemplate(paramDecl, boundValue);\n boundParam.index = paramDecl.index ?? -(index + 1);\n boundParams.push(boundParam);\n namedArgs.delete(name);\n continue;\n }\n\n if (isNode(param, N.Any) && param.role === 'property') {\n const name = String(param.valueOf());\n const hasNamedArg = namedArgs.has(name);\n const hasPositionalArg = positionalIndex < positionalArgs.length;\n const boundValue = hasNamedArg\n ? namedArgs.get(name)!\n : hasPositionalArg\n ? positionalArgs[positionalIndex++]!\n : undefined;\n if (\n boundValue\n && (hasNamedArg || hasPositionalArg)\n && bindingSourceParent\n && isNode(boundValue)\n ) {\n anchorCallSiteValue(boundValue, bindingSourceParent, bindingContext);\n }\n const template = getBindableParamTemplate(param, context);\n const boundParam = cloneBoundParamTemplate(template, boundValue);\n boundParam.index = -(index + 1);\n boundParams.push(boundParam);\n namedArgs.delete(name);\n continue;\n }\n\n if (param.type === 'Rest') {\n const restName = typeof (param as unknown as { value?: string }).value === 'string'\n ? String((param as unknown as { value: string }).value)\n : 'rest';\n const restValues = positionalArgs.slice(positionalIndex);\n positionalIndex = positionalArgs.length;\n const restValue = restValues.length > 0\n ? createRenderOwnedSequence(restValues, renderKey, context)\n : (\n context.treeContext?.file\n ? createRenderOwnedSequence([], renderKey, context)\n : new Any(restName, { role: 'property' })\n );\n const restTemplate = getRestParamTemplate(param, restName, context);\n const restVarDecl = cloneBoundParamTemplate(restTemplate, restValue);\n restVarDecl.index = -(index + 1);\n boundParams.push(restVarDecl);\n continue;\n }\n\n // Non-binding pattern params still consume a positional argument slot\n // when matched, so later bindable params line up with the correct arg.\n if (positionalIndex < positionalArgs.length) {\n positionalIndex++;\n }\n }\n\n return boundParams;\n}\n\n/**\n * Prepare the normal mixin-candidate body for direct invocation.\n *\n * This is the slice of the old candidate loop that wires per-call identity,\n * visibility, parent/source provenance, param normalization, and lookup scope\n * construction before guard evaluation or output shaping runs.\n */\nexport function prepareMixinCandidateInvocation(\n rules: Rules,\n params: List<Node> | undefined,\n parent: Node | undefined,\n sourceParent: Node | undefined,\n index: number,\n nodeArgs: readonly Node[],\n context: Context\n): PreparedMixinCandidateInvocation {\n const renderKey = context.nextRenderKey();\n const bindingSourceParent = sourceParent ?? context.caller;\n const boundParams = buildBoundMixinParams(\n params,\n nodeArgs,\n bindingSourceParent,\n renderKey,\n context\n );\n const outerRules = boundParams\n ? prepareMixinInvocationScope(\n parent,\n parent,\n sourceParent,\n index,\n renderKey,\n boundParams,\n nodeArgs,\n context\n )\n : undefined;\n const lookupParent = outerRules ?? parent;\n const sourceRules = getRootSourceRules(rules);\n const invocationRules = createMixinInvocationRules(\n sourceRules,\n lookupParent,\n parent,\n sourceParent,\n index,\n context,\n renderKey\n );\n\n return {\n rules: invocationRules,\n params: boundParams,\n outerRules\n };\n}\n\n/**\n * Run an evaluation step with the mixin invocation scope as the active lookup\n * scope, then restore the caller's prior rulesContext.\n */\nexport function withMixinLookupScope<T>(\n scope: Rules | undefined,\n lookupScope: Rules | undefined,\n context: Context,\n fn: () => MaybePromise<T>\n): MaybePromise<T> {\n const previousRulesContext = context.rulesContext;\n const previousRenderKey = context.renderKey;\n const previousLookupScope = context.lookupScope;\n if (scope) {\n context.rulesContext = scope;\n }\n context.lookupScope = lookupScope;\n context.renderKey = scope?.renderKey ?? previousRenderKey;\n try {\n const out = fn();\n if (isThenable(out)) {\n return (out as Promise<T>).finally(() => {\n context.rulesContext = previousRulesContext;\n context.renderKey = previousRenderKey;\n context.lookupScope = previousLookupScope;\n });\n }\n context.rulesContext = previousRulesContext;\n context.renderKey = previousRenderKey;\n context.lookupScope = previousLookupScope;\n return out;\n } catch (error) {\n context.rulesContext = previousRulesContext;\n context.renderKey = previousRenderKey;\n context.lookupScope = previousLookupScope;\n throw error;\n }\n}\n\n/**\n * Evaluate one mixin guard candidate against the prepared invocation scope.\n *\n * This centralizes the reset-session guard probe behavior so the caller loop\n * only has to deal with the result (`passes`, optional default group, evolved\n * scope) instead of the probing mechanics.\n */\nexport async function evaluateMixinGuardCandidate(\n guardNode: Condition | Bool | undefined,\n outerRules: Rules | undefined,\n guardParent: Node | undefined,\n context: Context,\n scopeChildren: readonly Node[] | undefined,\n hasDefault: boolean\n): Promise<EvaluatedMixinGuard> {\n if (!guardNode) {\n return { passes: true, outerRules };\n }\n\n const evaluateWithDefault = async (\n isDefaultValue: boolean\n ): Promise<{ passes: boolean; outerRules: Rules | undefined }> => {\n const prevIsDefault = context.isDefault;\n const previousRulesContext = context.rulesContext;\n const previousRenderKey = context.renderKey;\n const previousLookupScope = context.lookupScope;\n try {\n const nextScope = seedMixinGuardScope(\n outerRules,\n guardParent,\n guardNode,\n context,\n scopeChildren\n );\n context.isDefault = isDefaultValue;\n context.rulesContext = nextScope;\n context.lookupScope = nextScope;\n context.renderKey = nextScope.renderKey ?? previousRenderKey;\n const probeResult = await guardNode.eval(context);\n return {\n passes: probeResult instanceof Bool && probeResult.value === true,\n outerRules: nextScope\n };\n } finally {\n context.rulesContext = previousRulesContext;\n context.renderKey = previousRenderKey;\n context.lookupScope = previousLookupScope;\n context.isDefault = prevIsDefault;\n }\n };\n\n if (hasDefault) {\n const passWhenDefaultFalse = await evaluateWithDefault(false);\n const passWhenDefaultTrue = await evaluateWithDefault(true);\n const defaultGroup = classifyMixinDefaultGroup(\n passWhenDefaultFalse.passes,\n passWhenDefaultTrue.passes\n );\n return {\n passes: defaultGroup !== undefined,\n outerRules: passWhenDefaultTrue.outerRules ?? passWhenDefaultFalse.outerRules ?? outerRules,\n defaultGroup\n };\n }\n\n const result = await evaluateWithDefault(false);\n return {\n passes: result.passes,\n outerRules: result.outerRules\n };\n}\n\n/**\n * Classify a default() guard probe pair into Less-style default groups.\n */\nexport function classifyMixinDefaultGroup(\n passWhenDefaultFalse: boolean,\n passWhenDefaultTrue: boolean\n): MixinDefaultGroup | undefined {\n if (!passWhenDefaultFalse && !passWhenDefaultTrue) {\n return undefined;\n }\n if (passWhenDefaultFalse && passWhenDefaultTrue) {\n return MixinDefaultGroup.None;\n }\n return passWhenDefaultTrue\n ? MixinDefaultGroup.True\n : MixinDefaultGroup.False;\n}\n\n/**\n * Resolve which default() candidate groups should win for the current call.\n */\nexport function resolveWinningMixinDefaultGroups(\n groups: readonly MixinDefaultGroup[]\n): Set<MixinDefaultGroup> {\n let hasDefNoneCandidate = false;\n let hasDefTrueCandidate = false;\n let hasDefFalseCandidate = false;\n\n for (const group of groups) {\n if (group === MixinDefaultGroup.True) {\n hasDefTrueCandidate = true;\n } else if (group === MixinDefaultGroup.False) {\n hasDefFalseCandidate = true;\n } else if (group === MixinDefaultGroup.None) {\n hasDefNoneCandidate = true;\n }\n }\n\n if (!hasDefNoneCandidate && hasDefTrueCandidate && hasDefFalseCandidate) {\n throw new ReferenceError('Ambiguous use of default() while matching mixins.');\n }\n\n if (hasDefNoneCandidate) {\n return new Set([MixinDefaultGroup.None, MixinDefaultGroup.False]);\n }\n\n return new Set([MixinDefaultGroup.True]);\n}\n\n/**\n * Replay only the winning pending default() candidates with the correct lookup\n * scope active for each candidate.\n */\nexport async function replayWinningMixinDefaultCandidates<TCandidate>(\n pendingCandidates: readonly PendingMixinDefaultCandidate<TCandidate>[],\n context: Context,\n evaluateCandidateOutput: (\n pending: PendingMixinDefaultCandidate<TCandidate>\n ) => MaybePromise<void>\n): Promise<void> {\n if (pendingCandidates.length === 0) {\n return;\n }\n\n const winningGroups = resolveWinningMixinDefaultGroups(\n pendingCandidates.map(pending => pending.group)\n );\n\n for (const pending of pendingCandidates) {\n if (!winningGroups.has(pending.group)) {\n continue;\n }\n await withMixinLookupScope(\n pending.outerRules ?? pending.rules,\n pending.outerRules ?? pending.lookupScope ?? findRulesAncestor(pending.rules, context),\n context,\n () => evaluateCandidateOutput(pending)\n );\n }\n}\n\n/**\n * Assemble the final mixin output `Rules` from already-evaluated candidate\n * results, preserving source order and mixin-output visibility semantics.\n */\nexport function assembleMixinInvocationOutput(\n outputRules: Rules[],\n restrictMixinOutputLookup: boolean,\n context: Context\n): Rules {\n outputRules.sort(comparePosition);\n\n if (outputRules.length === 0) {\n const output = Rules.create([], {\n rulesVisibility: {\n Ruleset: 'public',\n Declaration: 'public',\n VarDeclaration: 'public',\n Mixin: 'public'\n },\n isMixinOutput: restrictMixinOutputLookup\n });\n output.renderKey = context.renderKey ?? output.renderKey;\n return output;\n }\n\n if (outputRules.length === 1) {\n const output = outputRules[0]!;\n output.options.isMixinOutput ??= restrictMixinOutputLookup;\n return output;\n }\n\n for (let i = 0; i < outputRules.length; i++) {\n const candidateOutput = outputRules[i]!;\n candidateOutput.frozen = true;\n candidateOutput.index = i;\n }\n\n const firstOutput = outputRules[0]!;\n const nextRenderKey = context.renderKey ?? EVAL;\n const output = new Rules(\n [],\n {\n rulesVisibility: {\n Ruleset: 'public',\n Declaration: 'public',\n VarDeclaration: 'public',\n Mixin: 'public'\n },\n isMixinOutput: restrictMixinOutputLookup\n },\n firstOutput.location,\n firstOutput.treeContext\n );\n output.renderKey = nextRenderKey;\n output.sourceParent = firstOutput.sourceParent;\n output._setValueArray([...outputRules]);\n const outputContext = {\n ...context,\n renderKey: output.renderKey,\n rulesContext: output\n } as Context;\n for (const child of outputRules) {\n if (isNode(child, N.Rules)) {\n const childContext = {\n ...outputContext,\n renderKey: (child as Rules).renderKey,\n rulesContext: child as Rules\n } as Context;\n setParent(child, output, childContext);\n output.registerNode(child, undefined, outputContext);\n projectCurrentRenderParents(\n child as Rules,\n childContext\n );\n continue;\n }\n setParent(child, output, outputContext);\n output.registerNode(child, undefined, outputContext);\n }\n\n return output;\n}\n\n/**\n * Evaluate a ruleset candidate whose guard already passed during Ruleset\n * evaluation, preserving mixin-output semantics and eval-state-subtree association.\n */\nexport async function evaluateRulesetMixinCandidateOutput(\n sourceRules: Rules,\n definitionParent: Node | undefined,\n placementParent: Node | undefined,\n candidateIndex: number,\n restrictMixinOutputLookup: boolean,\n context: Context\n): Promise<Rules> {\n const renderKey = context.nextRenderKey();\n let rules = sourceRules.createShallowBodyWrapper(undefined, renderKey);\n const placementContext = {\n ...context,\n renderKey,\n rulesContext: rules\n } as Context;\n setParent(rules, placementParent, placementContext);\n setSourceParent(rules, definitionParent, placementContext);\n const previousRulesContext = context.rulesContext;\n const previousRenderKey = context.renderKey;\n const previousFrames = context.frames;\n const previousRulesetFrames = context.rulesetFrames;\n const seededFrames: Array<Ruleset | AtRule> = [];\n let frameCursor = placementParent;\n while (frameCursor) {\n if (isNode(frameCursor, N.Ruleset | N.AtRule)) {\n seededFrames.push(frameCursor as Ruleset | AtRule);\n }\n frameCursor = getParent(frameCursor, context);\n }\n seededFrames.reverse();\n context.rulesContext = rules;\n context.renderKey = rules.renderKey;\n context.frames = seededFrames;\n context.rulesetFrames = seededFrames.filter((frame): frame is Ruleset => isNode(frame, N.Ruleset));\n try {\n rules = await rules.preEval(context) as Rules;\n rules = await rules.eval(context);\n } finally {\n context.rulesContext = previousRulesContext;\n context.renderKey = previousRenderKey;\n context.frames = previousFrames;\n context.rulesetFrames = previousRulesetFrames;\n }\n setSourceParent(rules, definitionParent, placementContext);\n setParent(rules, placementParent, placementContext);\n finalizeInvocationOutputRules(rules, context);\n rules.index = candidateIndex;\n rules.options.isMixinOutput = restrictMixinOutputLookup;\n return rules;\n}\n\nexport function finalizeInvocationOutputRules(\n rules: Rules,\n context: Context\n): void {\n const scopedContext = {\n ...context,\n renderKey: rules.renderKey,\n rulesContext: rules\n } as Context;\n\n const children = rules.get('value', scopedContext);\n for (let index = 0; index < children.length; index++) {\n let child = children[index]!;\n if (isNode(child, N.Rules)) {\n continue;\n }\n if (isNode(child, N.Ruleset | N.AtRule) && getCurrentParentNode(child, scopedContext) !== rules) {\n child = child.clone(false, undefined, scopedContext);\n rules._setChildAt(index, child, scopedContext, false);\n rules.adopt(child, scopedContext);\n }\n\n if (isNode(child, N.Ruleset)) {\n const childRuleset = child as Ruleset;\n if (\n childRuleset.getOwnSelector()\n && childRuleset.getExtendedSelector(rules.renderKey)\n && !childRuleset.getSelectorBeforeExtend(rules.renderKey)\n ) {\n childRuleset.setExtendedSelector(\n childRuleset.getSelector(rules.renderKey),\n scopedContext\n );\n }\n finalizeInvocationOutputRules(\n childRuleset.enterRules(scopedContext),\n scopedContext\n );\n continue;\n }\n\n if (isNode(child, N.AtRule)) {\n const childRules = (child as AtRule).enterRules(scopedContext);\n if (childRules) {\n finalizeInvocationOutputRules(childRules, scopedContext);\n }\n }\n }\n}\n\nfunction projectCurrentRenderParents(\n rules: Rules,\n context: Context\n): void {\n const scopedContext = {\n ...context,\n renderKey: rules.renderKey,\n rulesContext: rules\n } as Context;\n const children = rules.get('value', scopedContext);\n for (const child of children) {\n setParent(child, rules, scopedContext);\n if (isNode(child, N.Rules)) {\n if ((child as Rules).renderKey !== rules.renderKey) {\n (child as Rules).renderKey = rules.renderKey;\n }\n projectCurrentRenderParents(child as Rules, {\n ...scopedContext,\n renderKey: (child as Rules).renderKey,\n rulesContext: child as Rules\n } as Context);\n continue;\n }\n if (isNode(child, N.Ruleset | N.AtRule)) {\n const nestedRules = child.enterRules(scopedContext);\n if (nestedRules) {\n projectCurrentRenderParents(nestedRules, {\n ...scopedContext,\n renderKey: nestedRules.renderKey,\n rulesContext: nestedRules\n } as Context);\n }\n }\n }\n}\n\n/**\n * Create the unlocked output for a detached ruleset call without flattening\n * the source body eagerly.\n */\nexport function unlockDetachedRulesetMixinCandidateOutput(\n sourceRules: Rules,\n placementParent: Node | undefined,\n definitionParent: Node | undefined,\n candidateIndex: number,\n context: Context\n): Rules {\n const unlocked = sourceRules.cloneDetachedUnlockWrapper(context);\n const placementContext = {\n ...context,\n renderKey: unlocked.renderKey,\n rulesContext: unlocked\n } as Context;\n setParent(unlocked, placementParent, placementContext);\n setSourceParent(unlocked, definitionParent, placementContext);\n finalizeInvocationOutputRules(unlocked, placementContext);\n unlocked.options.isMixinOutput = false;\n unlocked.index = candidateIndex;\n return unlocked;\n}\n\n/**\n * Process one prepared normal mixin candidate. This owns the remaining guard /\n * default orchestration for the standard candidate path: either dispatch the\n * candidate output immediately or return a pending default() replay record.\n */\nexport async function processPreparedMixinCandidate<TCandidate>(\n options: ProcessPreparedMixinCandidateOptions<TCandidate>\n): Promise<PendingMixinDefaultCandidate<TCandidate> | undefined> {\n const {\n candidate,\n rules,\n params,\n outerRules,\n guard,\n parent,\n guardScopeChildren,\n hasAnyDefault,\n candidateHasDefault,\n context,\n evaluateCandidateOutput\n } = options;\n\n let nextOuterRules = outerRules;\n const stableGuardScopeChildren = guard\n ? (guardScopeChildren ?? (nextOuterRules ? [...nextOuterRules.value] : undefined))\n : guardScopeChildren;\n const getCapturedOuterRules = () => captureMixinScopeSnapshot(\n nextOuterRules,\n stableGuardScopeChildren,\n context\n );\n const pendingLookupScope = () => getCapturedOuterRules() ?? getMixinCandidateLookupScope(parent, rules, context);\n if (guard) {\n const evaluatedGuard = await evaluateMixinGuardCandidate(\n guard,\n nextOuterRules,\n parent,\n context,\n stableGuardScopeChildren,\n candidateHasDefault\n );\n nextOuterRules = evaluatedGuard.outerRules;\n if (!evaluatedGuard.passes) {\n return undefined;\n }\n if (hasAnyDefault) {\n const capturedOuterRules = getCapturedOuterRules();\n const lookupScope = capturedOuterRules ?? getMixinCandidateLookupScope(parent, rules, context);\n return {\n candidate,\n rules,\n outerRules: capturedOuterRules,\n params,\n group: candidateHasDefault ? evaluatedGuard.defaultGroup! : MixinDefaultGroup.None,\n lookupScope\n };\n }\n }\n\n if (hasAnyDefault) {\n const capturedOuterRules = getCapturedOuterRules();\n const lookupScope = capturedOuterRules ?? getMixinCandidateLookupScope(parent, rules, context);\n return {\n candidate,\n rules,\n outerRules: capturedOuterRules,\n params,\n group: MixinDefaultGroup.None,\n lookupScope\n };\n }\n\n await withMixinLookupScope(\n nextOuterRules ?? rules,\n pendingLookupScope(),\n context,\n () => evaluateCandidateOutput(candidate, rules, nextOuterRules, params)\n );\n return undefined;\n}\n\n// -- Scope ancestry helpers --\n\n/**\n * Walk the parent chain (via eval state helpers) to find the nearest Rules ancestor.\n */\nexport function findRulesAncestor(node: Node | undefined, context: Context): Rules | undefined {\n let current = node ? getParent(node, context) : undefined;\n while (current && current.type !== 'Rules') {\n current = getParent(current, context);\n }\n return current as Rules | undefined;\n}\n\n/**\n * Walk sourceParent chain then parent chain to find the nearest source Rules ancestor.\n */\nexport function findSourceRulesAncestor(node: Node | undefined, context: Context): Rules | undefined {\n let current = node;\n let sp = current ? getSourceParent(current, context) : undefined;\n while (current && !sp) {\n current = getParent(current, context);\n sp = current ? getSourceParent(current, context) : undefined;\n }\n return sp ? findRulesAncestor(sp, context) : undefined;\n}\n\nexport function getMixinCandidateLookupScope(\n parent: Node | undefined,\n rules: Rules,\n context: Context\n): Rules | undefined {\n if (isNode(parent, N.Rules)) {\n return parent as Rules;\n }\n return findRulesAncestor(parent, context) ?? findRulesAncestor(rules, context);\n}\n\n/**\n * Resolve the candidate's parent, throwing if absent.\n *\n * Accepts `Node<any, any>` so callers don't need `as unknown as Node` casts\n * for typed subclasses like Mixin or Ruleset.\n */\nexport function getCandidateParent(node: Node<any, any>, context: Context): Node {\n const parent = getParent(node as Node, context);\n if (!parent) {\n throw new ReferenceError(`${node.type} candidate must have a parent during mixin evaluation`);\n }\n return parent;\n}\n\n// -- Arg evaluation --\n\n/**\n * Evaluate raw call args into a flat array of current Node values.\n */\nexport async function evaluateMixinArgs(\n args: any[],\n caller: Node | undefined,\n context: Context\n): Promise<Node[]> {\n const nodeArgs: Node[] = [];\n const callerSourceNode = (caller as any)?.name instanceof Node\n ? (caller as any).name\n : caller;\n const callerSourceParent = callerSourceNode\n ? getSourceParent(callerSourceNode, context)\n : undefined;\n const savedRulesContext = context.rulesContext;\n const savedLookupScope = context.lookupScope;\n const savedRenderKey = context.renderKey;\n const argEvalRulesContext = context.lookupScope\n ?? context.rulesContext\n ?? findRulesAncestor(caller, context)\n ?? findSourceRulesAncestor(callerSourceNode, context)\n ?? findRulesAncestor(callerSourceParent, context);\n context.rulesContext = argEvalRulesContext;\n context.lookupScope = argEvalRulesContext;\n context.renderKey = argEvalRulesContext?.renderKey ?? savedRenderKey;\n try {\n for (const arg of args) {\n if (isNode(arg)) {\n if (isNode(arg, N.VarDeclaration)) {\n // Evaluate the value, keep the VarDeclaration structure\n const value = (arg as VarDeclaration).get('value');\n if (value instanceof Node) {\n if (callerSourceParent && (isNode(value, N.Reference) || isNode(value, N.Mixin))) {\n setSourceParent(value, callerSourceParent, context);\n }\n const evaldValue = await value.eval(context);\n const argName = String((arg as VarDeclaration).get('name').valueOf());\n const bound = new VarDeclarationCtor({\n name: new Any(argName, { role: 'property' }),\n value: new Nil()\n }, { ...((arg as VarDeclaration).options ?? {}) }, arg.location, context.treeContext);\n bound.renderKey = context.renderKey ?? bound.renderKey;\n (bound as VarDeclaration).value = evaldValue;\n bound.adopt(evaldValue, context);\n nodeArgs.push(bound);\n } else {\n nodeArgs.push(arg);\n }\n continue;\n }\n if (callerSourceParent && (isNode(arg, N.Reference) || isNode(arg, N.Mixin))) {\n setSourceParent(arg, callerSourceParent, context);\n }\n const evald = await arg.eval(context);\n if (evald.type === 'Rest') {\n let restValue = (evald as unknown as { value: unknown }).value;\n if (isNode(restValue as Node) && !isNode(restValue as Node, N.Sequence | N.List)) {\n restValue = await (restValue as Node).eval(context);\n }\n if (isNode(restValue, N.Sequence) || isNode(restValue, N.List)) {\n for (const restArg of (restValue as unknown as { value: Node[] }).value) {\n nodeArgs.push(restArg);\n }\n continue;\n }\n }\n nodeArgs.push(evald);\n } else {\n nodeArgs.push(cast(arg));\n }\n }\n } finally {\n context.rulesContext = savedRulesContext;\n context.lookupScope = savedLookupScope;\n context.renderKey = savedRenderKey;\n }\n return nodeArgs;\n}\n\n// -- Candidate matching --\n\n/**\n * Evaluate a pattern-match operand in a fresh session scope.\n */\nasync function preparePatternOperand(node: Node, context: Context): Promise<Node> {\n try {\n return await node.eval(context);\n } finally {\n }\n}\n\n/**\n * Match the mixin array against evaluated args. Returns the candidates whose\n * param signatures match (with params bound).\n */\nexport async function matchMixinCandidates(\n mixinArr: MixinEntry[],\n nodeArgs: Node[],\n caller: Node | undefined,\n sourceParent: Node | undefined,\n context: Context\n): Promise<MixinEntry[]> {\n if (process.env.JESS_DEBUG_LOCK === 'throw-match') {\n const callerName = caller && isNode(caller, N.Call)\n ? (caller as unknown as { name?: Node }).name\n : undefined;\n const callerKey = isNode(callerName, N.Reference)\n ? String(callerName.key?.valueOf?.() ?? '')\n : '';\n const candidateNames = mixinArr.map(mixin => {\n if (isNode(mixin, N.Mixin)) {\n return String(mixin.get('name')?.valueOf?.() ?? '');\n }\n if (isNode(mixin, N.Ruleset)) {\n return String(mixin.get('selector')?.valueOf?.() ?? '');\n }\n return mixin.type;\n });\n if (\n callerKey.includes('inner-locked-mixin')\n || candidateNames.some(name => name.includes('inner-locked-mixin'))\n ) {\n throw new Error(`[lock-match] ${JSON.stringify({\n callerKey,\n candidateNames,\n sourceParent: sourceParent?.type,\n rulesContext: context.rulesContext?.type,\n lookupScope: context.lookupScope?.type,\n argTypes: nodeArgs.map(arg => arg.type)\n })}`);\n }\n }\n const mixinCandidates: MixinEntry[] = [];\n const bindingSourceParent = sourceParent ?? caller;\n\n for (let i = 0; i < mixinArr.length; i++) {\n let mixin = mixinArr[i]!;\n const isPlainRule = isNode(mixin, N.Rules);\n const currentParams = !isPlainRule && isNode(mixin, N.Mixin)\n ? getCurrentMixinParams(mixin as Mixin, mixin.renderKey ?? context)\n : undefined;\n const paramLength = isPlainRule ? 0 : (currentParams?.length ?? 0);\n\n if (!paramLength) {\n if (nodeArgs.length) {\n continue;\n }\n mixinCandidates.push(mixin);\n } else {\n const params = currentParams!;\n const hasRestParamOriginal = params.get('value').some(\n (p: Node) => p.type === 'Rest'\n );\n const maxPositionalArgs = hasRestParamOriginal ? Number.POSITIVE_INFINITY : params.length;\n const positions = params.length;\n let requiredPositions = 0;\n for (const param of params.get('value')) {\n if (isNode(param, N.VarDeclaration)) {\n if ((param as VarDeclaration).get('value') instanceof Nil) {\n requiredPositions++;\n }\n } else if (isNode(param, N.Any) && param.role === 'property') {\n requiredPositions++;\n } else if (param.type !== 'Rest') {\n requiredPositions++;\n }\n }\n\n let argPos = 0;\n let match = true;\n for (let pi = 0; pi < positions; pi++) {\n const arg = nodeArgs[argPos];\n if (!arg) {\n continue;\n }\n let param: Node | undefined;\n let argValue: Node;\n\n if (isNode(arg, N.VarDeclaration)) {\n param = params.get('value').find((p: Node) => {\n if (isNode(p, N.VarDeclaration)) {\n return (p as VarDeclaration).get('name').valueOf() === (arg as VarDeclaration).get('name').valueOf();\n }\n if (isNode(p, N.Any) && p.role === 'property') {\n return p.valueOf() === (arg as VarDeclaration).get('name').valueOf();\n }\n return false;\n });\n if (param) {\n argValue = (arg as VarDeclaration).get('value') as Node;\n } else {\n match = false;\n break;\n }\n } else {\n param = params.get('value')[pi];\n if (!param) {\n match = false;\n break;\n }\n argValue = arg;\n }\n\n if (!param) {\n match = false;\n break;\n }\n\n if (\n isNode(param, N.VarDeclaration)\n || (isNode(param, N.Any) && param.role === 'property')\n || param.type === 'Rest'\n ) {\n if (bindingSourceParent && (isNode(argValue, N.Reference) || isNode(argValue, N.Mixin))) {\n setSourceParent(argValue, bindingSourceParent, context);\n }\n } else {\n const originalPatternParam = !isNode(arg, N.VarDeclaration)\n ? currentParams?.get('value')[pi]\n : undefined;\n const preparedParam = isNode(originalPatternParam as Node | undefined, N.Selector)\n ? await preparePatternOperand(originalPatternParam as Node, context)\n : isNode(param, N.Selector)\n ? await preparePatternOperand(param, context)\n : param;\n if (preparedParam.compare(argValue, context) !== 0) {\n match = false;\n break;\n }\n }\n argPos++;\n }\n\n const positionalArgCount = nodeArgs.filter(argNode => !isNode(argNode, N.VarDeclaration)).length;\n if (positionalArgCount > maxPositionalArgs) {\n continue;\n }\n if (argPos < requiredPositions) {\n continue;\n }\n if (nodeArgs.length > 1 && params.get('value').length === 1 && requiredPositions === 1) {\n continue;\n }\n if (match) {\n mixinCandidates.push(mixin);\n }\n }\n }\n\n return mixinCandidates;\n}\n\n// -- Candidate filtering and sorting --\n\n/**\n * Walk a node tree looking for `default()` / `DefaultGuard` / `??` calls.\n */\nfunction guardContainsDefault(node: Node | undefined): boolean {\n if (!node) {\n return false;\n }\n if (node.type === 'DefaultGuard') {\n return true;\n }\n if (node.type === 'Call') {\n const callName = String((node as unknown as { name?: { valueOf?: () => string } }).name?.valueOf?.()\n ?? (node as unknown as { name?: string }).name ?? '');\n if (callName === 'default' || callName === '??') {\n return true;\n }\n }\n const value = (node as unknown as { value: unknown }).value;\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isNode(item) && guardContainsDefault(item)) {\n return true;\n }\n }\n return false;\n }\n if (isPlainObject(value)) {\n for (const item of Object.values(value as Record<string, unknown>)) {\n if (isNode(item as Node) && guardContainsDefault(item as Node)) {\n return true;\n }\n if (Array.isArray(item)) {\n for (const child of item) {\n if (isNode(child) && guardContainsDefault(child)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Check whether a node has a failed-guard ancestor (Ruleset with Nil guard).\n */\nfunction hasFailedGuardAncestor(node: Node<any, any>, context: Context): boolean {\n let current: Node | undefined = getParent(node as Node, context);\n while (current) {\n if (isNode(current, N.Ruleset)) {\n const guardNode = getCurrentRulesetGuard(current as Ruleset, context);\n if (guardNode instanceof Nil) {\n return true;\n }\n }\n current = getParent(current, context);\n }\n return false;\n}\n\n/**\n * Filter matched candidates by eval-stack guard and sort default-guard\n * candidates to the end.\n *\n * Returns `{ evalCandidates, hasDefault }`.\n */\nexport function filterAndSortMixinEvalCandidates(\n mixinCandidates: MixinEntry[],\n context: Context\n): { evalCandidates: MixinEntry[]; hasDefault: boolean } {\n let hasDefault = false;\n let evalCandidates = mixinCandidates\n .filter((candidate) => {\n const blockedByFailedGuard = hasFailedGuardAncestor(candidate, context);\n return !blockedByFailedGuard;\n })\n .map<MixinEntry>((candidate) => {\n const hasDefaultGuard = Boolean(candidate.options?.hasDefault)\n || guardContainsDefault((candidate as Mixin).get('guard') as Node | undefined);\n if (hasDefaultGuard) {\n candidate.options ??= {};\n candidate.options.hasDefault = true;\n hasDefault = true;\n }\n return candidate;\n });\n\n if (hasDefault) {\n evalCandidates = evalCandidates.slice(0).sort((a, b) => {\n const aDefault = a.options?.hasDefault;\n const bDefault = b.options?.hasDefault;\n if (!aDefault && !bDefault) {\n return 0;\n }\n if (!aDefault) {\n return -1;\n }\n if (!bDefault) {\n return 1;\n }\n return 0;\n });\n }\n\n if (evalCandidates.length === 0) {\n throw new ReferenceError('No matching mixins found.');\n }\n\n return { evalCandidates, hasDefault };\n}\n\n// -- Candidate output evaluation --\n\nexport type EvaluateCandidateOutputOptions = {\n sourceParent: Node | undefined;\n invocationParent: Node | undefined;\n restrictMixinOutputLookup: boolean;\n outputRules: Rules[];\n getCandidateParent: (node: Node<any, any>) => Node;\n};\n\n/**\n * Evaluate a single mixin candidate's body and push the result to outputRules.\n *\n * Handles explicit recursion guarding, position creation, body eval, output\n * finalization, param scope projection, and eval state subtree association.\n */\nexport async function evaluateCandidateOutput(\n candidate: MixinEntry,\n rules: Rules,\n outerRules: Rules | undefined,\n params: List<Node> | undefined,\n context: Context,\n opts: EvaluateCandidateOutputOptions\n): Promise<void> {\n const {\n sourceParent,\n invocationParent,\n restrictMixinOutputLookup,\n outputRules,\n getCandidateParent: getParentFn\n } = opts;\n const currentCall = context.callStack.at(-1);\n if (currentCall) {\n const isRecursive = context.callMap.add(currentCall, params, context);\n if (isRecursive) {\n return;\n }\n }\n try {\n const callerParent = getParentFn(candidate);\n const candidateSourceParent = getUsableInvocationSourceParent(\n getCanonicalSourceParent(candidate as Node),\n getUsableInvocationSourceParent(\n getCanonicalSourceParent(callerParent),\n sourceParent\n )\n );\n const lexicalSourceParent = candidateSourceParent ?? callerParent;\n const rulesContext = {\n ...context,\n renderKey: rules.renderKey,\n rulesContext: rules\n } as Context;\n setParent(rules, outerRules ?? callerParent, rulesContext);\n rules.sourceParent = candidateSourceParent ?? lexicalSourceParent;\n const previousRenderKey = context.renderKey;\n context.renderKey = rules.renderKey;\n let newRules: Rules;\n try {\n newRules = await rules.eval(context);\n } finally {\n context.renderKey = previousRenderKey;\n }\n void outerRules;\n if (newRules.renderKey === CANONICAL) {\n newRules.renderKey = rules.renderKey;\n }\n const newRulesContext = {\n ...context,\n renderKey: newRules.renderKey,\n rulesContext: newRules\n } as Context;\n setParent(newRules, invocationParent ?? callerParent, newRulesContext);\n projectParentChainForRenderKey(invocationParent ?? callerParent, context, newRulesContext);\n newRules.sourceParent = candidateSourceParent ?? lexicalSourceParent;\n newRules.index = candidate.index;\n finalizeInvocationOutputRules(newRules, newRulesContext);\n\n if (outerRules) {\n const previousRenderKey = context.renderKey;\n const previousRulesContext = context.rulesContext;\n context.renderKey = newRules.renderKey;\n context.rulesContext = newRules;\n let outputChildren: readonly Node[];\n try {\n outputChildren = newRules.getRegistryChildren(context);\n } finally {\n context.renderKey = previousRenderKey;\n context.rulesContext = previousRulesContext;\n }\n const outputContext = {\n ...context,\n renderKey: newRules.renderKey,\n rulesContext: newRules\n } as Context;\n for (const child of outputChildren) {\n if (isNode(child, N.Rules)) {\n projectCurrentRenderParents(\n child as Rules,\n {\n ...outputContext,\n renderKey: (child as Rules).renderKey,\n rulesContext: child as Rules\n } as Context\n );\n }\n }\n bindStructuralSourceParent(newRules, outerRules, outputContext);\n setParent(newRules, outerRules, outputContext);\n if (invocationParent ?? callerParent) {\n addParentEdge(newRules, CALLER, (invocationParent ?? callerParent)!);\n }\n newRules.sourceParent = outerRules;\n newRules.index = candidate.index;\n newRules.options.isMixinOutput = false;\n if (process.env.JESS_DEBUG_LOCK === 'throw-output') {\n const candidateName = String((candidate as Mixin).get('name')?.valueOf?.() ?? '');\n if (candidateName.includes('lock-mixin')) {\n throw new Error(`[lock-output] ${JSON.stringify({\n candidateName,\n hasOuterRules: Boolean(outerRules),\n outerRulesChildren: outerRules?.value?.map((child: Node) => child.type) ?? [],\n candidateSourceParent: candidateSourceParent?.type,\n lexicalSourceParent: lexicalSourceParent?.type,\n outputContainerSourceParent: newRules.sourceParent?.type,\n outputContainerSourceParentChildren: newRules.sourceParent?.value?.map((child: Node) => child.type) ?? []\n })}`);\n }\n }\n outputRules.push(newRules);\n return;\n }\n\n newRules.options.isMixinOutput = restrictMixinOutputLookup;\n if (context.treeContext?.file) {\n newRules.options.rulesVisibility ??= {};\n newRules.options.rulesVisibility.VarDeclaration = 'private';\n }\n outputRules.push(newRules);\n } finally {\n if (currentCall) {\n context.callMap.delete(currentCall);\n }\n }\n}\n\n// -- Dispatch orchestration --\n\nexport type MixinDispatchContext = {\n evalCandidates: MixinEntry[];\n hasDefault: boolean;\n nodeArgs: Node[];\n sourceParent: Node | undefined;\n invocationParent: Node | undefined;\n caller: Node | undefined;\n restrictMixinOutputLookup: boolean;\n outputRules: Rules[];\n getCandidateParent: (node: Node<any, any>) => Node;\n evaluateCandidateOutput: (\n candidate: MixinEntry,\n rules: Rules,\n outerRules: Rules | undefined,\n params: List<Node> | undefined,\n ) => Promise<void>;\n};\n\n/**\n * Dispatch all mixin eval candidates — the main candidate loop.\n *\n * Handles Ruleset candidates, detached rulesets, and normal parameterized\n * mixins. Includes default guard replay and output assembly.\n */\nexport async function dispatchMixinEvalCandidates(\n dispatch: MixinDispatchContext,\n context: Context\n): Promise<Rules> {\n const {\n evalCandidates,\n hasDefault,\n nodeArgs,\n sourceParent,\n invocationParent,\n restrictMixinOutputLookup,\n outputRules,\n getCandidateParent,\n evaluateCandidateOutput\n } = dispatch;\n const pendingDefaultCandidates: PendingMixinDefaultCandidate<any>[] = [];\n let skippedByRecursion = false;\n for (const candidate of evalCandidates) {\n if (isNode(candidate, N.Ruleset)) {\n if ((candidate as Ruleset).get('guard') instanceof Nil) {\n continue;\n }\n const currentRules = (candidate as Ruleset).enterRules(context);\n const sourceRules = getRootSourceRules(currentRules);\n if (context.rulesEvalStack.includes(sourceRules)) {\n skippedByRecursion = true;\n continue;\n }\n const definitionParent = getCandidateParent(candidate);\n const placementParent = invocationParent ?? definitionParent;\n const rules = await evaluateRulesetMixinCandidateOutput(\n sourceRules,\n definitionParent,\n placementParent,\n candidate.index,\n restrictMixinOutputLookup,\n context\n );\n outputRules.push(rules);\n continue;\n }\n\n // After the Ruleset branch above, candidate must be a Mixin\n if (!isNode(candidate, N.Mixin)) {\n continue;\n }\n if (process.env.JESS_DEBUG_LOCK) {\n const candidateName = String(candidate.get('name')?.valueOf?.() ?? '');\n if (candidateName.includes('inner-locked-mixin')) {\n const candidateParent = getParent(candidate, context);\n const candidateSourceParent = getSourceParent(candidate, context);\n const lockInfo = {\n candidateName,\n candidateParent: candidateParent?.type,\n candidateParentIndex: candidateParent?.index,\n candidateSourceParent: candidateSourceParent?.type,\n candidateSourceParentIndex: candidateSourceParent?.index,\n candidateSourceParentName: isNode(candidateSourceParent, N.Mixin)\n ? String(candidateSourceParent.get('name')?.valueOf?.() ?? '')\n : undefined,\n sourceParent: sourceParent?.type,\n invocationParent: invocationParent?.type,\n lookupScope: context.lookupScope?.type,\n rulesContext: context.rulesContext?.type\n };\n if (process.env.JESS_DEBUG_LOCK === 'throw') {\n throw new Error(`[lock-dispatch] ${JSON.stringify(lockInfo)}`);\n }\n console.log('[lock-dispatch]', lockInfo);\n }\n }\n if (!candidate.get('name') && !candidate.get('params') && !candidate.get('guard')) {\n const sourceRules = getRootSourceRules(candidate.get('rules'));\n const definitionParent = getCandidateParent(candidate);\n const unlocked = unlockDetachedRulesetMixinCandidateOutput(\n sourceRules,\n invocationParent ?? definitionParent,\n definitionParent,\n candidate.index,\n context\n );\n outputRules.push(unlocked);\n continue;\n }\n\n const candidateRenderKey = candidate.renderKey ?? context.renderKey;\n let rules = candidate\n .get('rules', candidateRenderKey ?? context)\n .withRenderOwner(candidate, candidateRenderKey, context);\n let params = getCurrentMixinParams(candidate, candidateRenderKey ?? context);\n const definitionParent = getCandidateParent(candidate);\n const candidateSourceParent = getUsableInvocationSourceParent(\n getCanonicalSourceParent(candidate as Node),\n getUsableInvocationSourceParent(\n getCanonicalSourceParent(definitionParent),\n sourceParent\n )\n );\n const prepared = prepareMixinCandidateInvocation(\n rules,\n params,\n definitionParent,\n candidateSourceParent,\n candidate.index,\n nodeArgs,\n context\n );\n rules = prepared.rules;\n params = prepared.params;\n const currentGuard = getCurrentRulesetGuard(candidate, candidateRenderKey ?? context) as Condition | Bool | undefined;\n const candidateHasDefault = Boolean(candidate.options?.hasDefault)\n || guardContainsDefault(currentGuard as Node | undefined);\n const pendingDefaultCandidate = await processPreparedMixinCandidate({\n candidate,\n rules,\n params,\n outerRules: prepared.outerRules,\n guard: currentGuard,\n parent: getCandidateParent(candidate),\n hasAnyDefault: hasDefault,\n candidateHasDefault,\n context,\n evaluateCandidateOutput\n });\n if (pendingDefaultCandidate) {\n pendingDefaultCandidates.push(pendingDefaultCandidate);\n }\n }\n\n await replayWinningMixinDefaultCandidates(\n pendingDefaultCandidates,\n context,\n pending => evaluateCandidateOutput(\n pending.candidate,\n pending.rules,\n pending.outerRules,\n pending.params\n )\n );\n\n if (\n skippedByRecursion\n && outputRules.length === 0\n && pendingDefaultCandidates.length === 0\n ) {\n throw new ReferenceError('No matching mixins found.');\n }\n\n const output = assembleMixinInvocationOutput(\n outputRules,\n restrictMixinOutputLookup,\n context\n );\n\n return output;\n}\n","import {\n Node,\n defineType,\n type NodeOptions,\n type LocationInfo, type OptionalLocation,\n type RenderKey,\n CANONICAL,\n EVAL,\n type TreeContext,\n F_STATIC,\n F_VISIBLE,\n isVisibleInContext\n} from './node.js';\nimport { Context } from '../context.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { type Ruleset } from './ruleset.js';\nimport { type Mixin } from './mixin.js';\nimport type { Selector } from './selector.js';\nimport { spaced, Sequence } from './sequence.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\n\nimport { atIndex } from './util/collections.js';\nimport * as Registries from './util/registry-utils.js';\nimport { processExtends } from './util/extend-roots.js';\nimport { type MaybePromise, pipe, isThenable, serialForEach } from '@jesscss/awaitable-pipe';\nimport { Nil } from './nil.js';\nimport { VarDeclaration } from './declaration-var.js';\nimport type { Declaration } from './declaration.js';\nimport { Any } from './any.js';\nimport { List } from './list.js';\nimport { indent, normalizeIndent } from './util/serialize-helper.js';\nimport { addEdge, addEdgeAt, addParentEdge, getEdgeAt } from './util/cursor.js';\nimport { getCurrentParentNode } from './util/selector-utils.js';\nimport {\n getChildren,\n getParent,\n getSourceParent,\n setChildren,\n setChildAt,\n getIndex,\n setIndex,\n setParent,\n isPreEvaluated,\n isEvaluated\n} from './util/field-helpers.js';\nimport {\n dispatchMixinEvalCandidates,\n evaluateCandidateOutput,\n evaluateMixinArgs,\n filterAndSortMixinEvalCandidates,\n finalizeMixinInvocationReturn,\n getCandidateParent,\n matchMixinCandidates,\n type EvaluateCandidateOutputOptions\n} from './util/mixin-instance-primitives.js';\nimport type { Func } from './function.js';\nimport type { Call } from './call.js';\nconst { isArray } = Array;\n\nexport const enum Priority {\n None = 0,\n Low = 1,\n Medium = 2,\n High = 3,\n Highest = 4\n}\nexport type RulesVisibility = 'public' | 'optional' | 'private';\nexport type FlatRulePosition = {\n renderKey?: RenderKey;\n};\n\nexport type RulesOptions = {\n /**\n * - public = all members are considered in lookup algorithms\n * - optional = members are only considered if not found in the lookup tree\n * - private = can't be looked up\n * - local = only visible in the current scope\n *\n * Different types may have different defaults\n *\n * For Less:\n * - When mixins are parsed, their rules body is set to:\n * visibility: {\n * Ruleset: 'public',\n * Declaration: 'public',\n * VarDeclaration: 'optional',\n * Mixin: 'public'\n * }\n * - When detached rulesets are parsed, their rules body is set to:\n * visibility: {\n * Ruleset: 'public',\n * Declaration: 'public',\n * VarDeclaration: 'private', <-- the one notable difference\n * Mixin: 'public'\n * }\n * @note - The reason Less has \"optionality\" is likely because it tries\n * to eagerly resolve variables, so even though its in a\n * child scope, it will still be considered if nothing else in the\n * scope is found. I'm guessing this is because \"overwriting\" a local\n * variable from something like a mixin call would be counter-intuitive,\n * but at the same time, I guess Alexis thought that eagerly resolving\n * the variable might be useful.\n *\n * Note that right now, only Declarations being set to \"optional\"\n * are supported. Everything else must be public or private.\n *\n * For Imports, the rules body is set to:\n * visibility: {\n * Ruleset: 'public',\n * Declaration: 'public',\n * VarDeclaration: 'public',\n * Mixin: 'public'\n * }\n */\n rulesVisibility?: Record<string, RulesVisibility>;\n /**\n * If true, this Rules node is output from a mixin call.\n * References with a target (e.g., #ns[@foo]) have public access to all nodes in these Rules.\n * References without a target (e.g., @foo) cannot access these Rules.\n */\n isMixinOutput?: boolean;\n readonly?: boolean;\n /**\n * all imports other than classic `@import` set returned rules to local.\n * The reason is that variables are not transitive, and you need to re-use\n * modules to get the same variables.\n */\n local?: boolean;\n /**\n * Sass `@forward` semantics: this Rules node exists as an export surface for downstream\n * consumers, but should not be visible to lookups within the current stylesheet scope.\n */\n forward?: boolean;\n /** Render gating marker for referenced imports/usages (serializer-time only). */\n referenceMode?: boolean;\n /** Explicit reference imports may render extended descendants; deduped imports may not. */\n referenceRenderOnExtend?: boolean;\n};\n\nexport interface Rules extends Node<Node[], RulesOptions & NodeOptions> {\n readonly value: readonly Node[];\n get options(): RulesOptions & NodeOptions & {\n rulesVisibility: Record<string, RulesVisibility>;\n };\n set options(options: RulesOptions & NodeOptions & {\n rulesVisibility: Record<string, RulesVisibility>;\n });\n eval(context: Context): MaybePromise<this>;\n}\n\nexport type InvocationBindingFactory = (rules: Rules, context?: Context) => VarDeclaration;\n\nexport type InvocationBinding = {\n template?: VarDeclaration;\n factory?: InvocationBindingFactory;\n declaration?: VarDeclaration;\n};\n/**\n * The class representing a \"declaration list\".\n * CSS calls it this even though CSS Nesting\n * adds a bunch more things that aren't declarations.\n *\n * Used by Ruleset and Mixin. Additionally, imports / use statements\n * return rules.\n *\n * @example\n * [\n * (Declaration color: black;)\n * (Declaration background-color: white;)\n * ]\n */\nexport interface Rules {\n type: 'Rules' | 'RawRules' | 'Collection';\n shortType: 'rules' | 'rules-raw' | 'coll';\n renderKey: RenderKey;\n}\nexport class Rules extends Node<Node[], RulesOptions & NodeOptions> {\n static override childKeys = ['value'] as const;\n\n readonly value!: readonly Node[];\n declare renderKey: RenderKey;\n private _wrapperRegistrySeeded = false;\n private _wrapperRegistrySeeding = false;\n private _invocationBindings?: Map<string, InvocationBinding>;\n\n functionRegistry: Registries.FunctionRegistry | undefined;\n\n private _withOwnRenderKey<T>(\n context: Context | undefined,\n fn: () => T\n ): T {\n if (!context) {\n return fn();\n }\n const targetRenderKey = this.renderKey === CANONICAL\n ? (context.renderKey ?? this.renderKey)\n : this.renderKey;\n const needsRenderKey = context.renderKey !== targetRenderKey;\n const needsRulesContext = context.rulesContext !== this;\n if (!needsRenderKey && !needsRulesContext) {\n return fn();\n }\n\n const previousRenderKey = context.renderKey;\n const previousRulesContext = context.rulesContext;\n if (needsRenderKey) {\n context.renderKey = targetRenderKey;\n }\n if (needsRulesContext) {\n context.rulesContext = this;\n }\n try {\n return fn();\n } finally {\n if (needsRulesContext) {\n context.rulesContext = previousRulesContext;\n }\n if (needsRenderKey) {\n context.renderKey = previousRenderKey;\n }\n }\n }\n\n private _cloneOptionsForContext(_context?: Context): (RulesOptions & NodeOptions) | undefined {\n const options = this.options\n ?? (this as any)._meta?.options as (RulesOptions & NodeOptions) | undefined;\n if (!options) {\n return undefined;\n }\n return {\n ...options,\n rulesVisibility: options.rulesVisibility\n ? { ...options.rulesVisibility }\n : options.rulesVisibility\n };\n }\n\n private _cloneInvocationBindings(): Map<string, InvocationBinding> | undefined {\n if (!this._invocationBindings || this._invocationBindings.size === 0) {\n return undefined;\n }\n const next = new Map<string, InvocationBinding>();\n for (const [key, binding] of this._invocationBindings) {\n next.set(key, {\n template: binding.declaration ?? binding.template,\n factory: binding.factory\n });\n }\n return next;\n }\n\n /**\n * Rules are often cloned during `preEval()` when a session is active.\n * If callers register functions/mixins/declarations on the parsed tree\n * before evaluation (e.g. via visitors), those registries must survive cloning so\n * lookups during evaluation work as expected.\n */\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const options = this._cloneOptionsForContext(ctx);\n const location = Array.isArray(this.location) && this.location.length === 6\n ? this.location as LocationInfo\n : undefined;\n const detachedRenderKey = (\n !deep\n && this.renderKey === CANONICAL\n && ctx\n ? ctx.nextRenderKey()\n : this.renderKey\n );\n const newRules = deep\n ? super.clone(deep, cloneFn, ctx)\n : (() => {\n const wrapper = new (this.constructor as typeof Rules)(\n [],\n options ? { ...options } : undefined,\n location,\n this.treeContext\n ) as this;\n wrapper._setValueArray(this.value as Node[]);\n wrapper.inherit(this);\n wrapper.renderKey = detachedRenderKey;\n if (wrapper.renderKey !== CANONICAL) {\n wrapper._connectSharedChildren(wrapper.renderKey);\n }\n return wrapper;\n })();\n\n if (deep && options) {\n newRules.options = options as typeof newRules.options;\n }\n\n if (!deep) {\n newRules.inherit(this);\n }\n\n const invocationBindings = this._cloneInvocationBindings();\n if (invocationBindings) {\n newRules._invocationBindings = invocationBindings;\n }\n\n if (ctx) {\n const parent = getCurrentParentNode(this, ctx);\n if (parent) {\n if (newRules.renderKey !== CANONICAL) {\n setParent(newRules, parent, { ...ctx, renderKey: newRules.renderKey });\n } else {\n setParent(newRules, parent, ctx);\n }\n }\n }\n\n // Only preserve *function* registry across clones.\n // This supports Less plugin compat, where plugins can inject functions into the registry\n // without creating AST nodes that would be re-registered on clone.\n //\n // Do NOT reuse declaration/mixin/ruleset registries across clones; those should always\n // be rebuilt from AST nodes via lazy indexing.\n if (this.functionRegistry) {\n newRules.functionRegistry = this.functionRegistry.cloneForRules(newRules);\n }\n\n return newRules;\n }\n\n /**\n * Detached ruleset calls unlock shared top-level children into the active\n * lookup scope, but must not canonically reparent those children.\n *\n * Keep this seam local to Rules so the detached-ruleset path does not need\n * to rely on raw clone(false) semantics.\n */\n cloneDetachedUnlockWrapper(ctx: Context): this {\n const wrapper = this.createShallowBodyWrapper(ctx) as this;\n return wrapper;\n }\n\n /**\n * Scope-isolation callers need copied Rules options/visibility while keeping\n * shared top-level children canonically parented. Active lookups should still\n * resolve through the wrapper during the current session.\n */\n cloneVisibilityIsolationWrapper(ctx: Context): this {\n const wrapper = this.createShallowBodyWrapper(ctx) as this;\n return wrapper;\n }\n\n /**\n * Lazily create registries for types as needed.\n */\n private static _registryKey(type: string): 'rulesetRegistry' | 'mixinRegistry' | 'declarationRegistry' | 'functionRegistry' {\n return `${type}Registry` as any;\n }\n\n private static _registryClass(type: string) {\n return Registries[`${type.charAt(0).toUpperCase()}${type.slice(1)}Registry` as 'RulesetRegistry' | 'MixinRegistry' | 'DeclarationRegistry' | 'FunctionRegistry'];\n }\n\n private _ensureDirectRegistry(\n type: 'ruleset' | 'declaration' | 'mixin' | 'function',\n context?: Context\n ) {\n const key = Rules._registryKey(type);\n let registry = (this as any)[key];\n if (!registry) {\n registry = new (Rules._registryClass(type))(this, context);\n (this as any)[key] = registry;\n } else if (context && !(registry as any).context) {\n (registry as any).context = context;\n }\n return registry;\n }\n\n private _isWrapperRegistryOwner(): boolean {\n return this.renderKey !== CANONICAL;\n }\n\n private _connectSharedChildren(renderKey: RenderKey): void {\n const seen = new Set<Node>();\n const connectDescendants = (parent: Node, child: Node): void => {\n addParentEdge(child, renderKey, parent);\n if (seen.has(child)) {\n return;\n }\n seen.add(child);\n const childKeys = (child.constructor as typeof Node).childKeys;\n if (!childKeys) {\n return;\n }\n for (const key of childKeys) {\n const value = (child as unknown as Record<string, unknown>)[key];\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item instanceof Node) {\n connectDescendants(child, item);\n }\n }\n continue;\n }\n if (value instanceof Node) {\n connectDescendants(child, value);\n }\n }\n };\n\n for (const child of this.value) {\n if (child instanceof Node) {\n connectDescendants(this, child);\n }\n }\n }\n\n private _ensureWrapperRegistrySeeded(context?: Context): void {\n if (!this._isWrapperRegistryOwner() || this._wrapperRegistrySeeded || this._wrapperRegistrySeeding) {\n return;\n }\n\n this._wrapperRegistrySeeding = true;\n try {\n (this as any).rulesetRegistry = undefined;\n (this as any).mixinRegistry = undefined;\n (this as any).declarationRegistry = undefined;\n this._rulesSet = [];\n\n for (const child of this.getRegistryChildren(context)) {\n this.registerNode(child, undefined, context);\n }\n\n this._wrapperRegistrySeeded = true;\n } finally {\n this._wrapperRegistrySeeding = false;\n }\n }\n\n /**\n * Register a child node into the appropriate registry.\n * Creates the registry lazily on first registration.\n * Wrapper/derived Rules own their registries directly.\n * Canonical Rules still fall back to direct per-node registries until the\n * remaining lookup paths are fully converged on render-path ownership.\n */\n register(\n type: 'ruleset' | 'declaration' | 'mixin' | 'function',\n node: Node,\n context?: Context\n ) {\n return this._withOwnRenderKey(context, () => {\n this._ensureWrapperRegistrySeeded(context);\n const registry = this._ensureDirectRegistry(type, context);\n return registry.add(node);\n });\n }\n\n /**\n * Get a registry for lookups. Read-only — returns undefined if no\n * registry was ever created (meaning nothing was registered).\n */\n getRegistry(type: 'ruleset', context?: Context): Registries.RulesetRegistry;\n getRegistry(type: 'declaration', context?: Context): Registries.DeclarationRegistry;\n getRegistry(type: 'mixin', context?: Context): Registries.MixinRegistry;\n getRegistry(type: 'function', context?: Context): Registries.FunctionRegistry;\n getRegistry(type: 'ruleset' | 'declaration' | 'mixin' | 'function', context?: Context): Registries.RulesetRegistry | Registries.DeclarationRegistry | Registries.MixinRegistry | Registries.FunctionRegistry;\n getRegistry(type: 'ruleset' | 'declaration' | 'mixin' | 'function', context?: Context) {\n return this._withOwnRenderKey(context, () => {\n this._ensureWrapperRegistrySeeded(context);\n return this._ensureDirectRegistry(type, context);\n });\n }\n\n getRegistryParent(context?: Context): Rules | undefined {\n return this._withOwnRenderKey(context, () => {\n let parent = getCurrentParentNode(this, context);\n while (parent && parent.type !== 'Rules') {\n parent = getCurrentParentNode(parent, context);\n }\n if (parent) {\n return parent as Rules | undefined;\n }\n let sourceParent = getSourceParent(this, context);\n while (sourceParent && sourceParent.type !== 'Rules') {\n sourceParent = getCurrentParentNode(sourceParent, context);\n }\n return sourceParent as Rules | undefined;\n });\n }\n\n /**\n * This wrapper is used so we don't prematurely create a registry\n * just to search it.\n */\n find(type: 'ruleset', keys: string | string[] | Set<string>, filterType?: string, options?: Registries.FindOptions): ReturnType<Registries.RulesetRegistry['find']> | undefined;\n find(type: 'declaration', keys: string, filterType?: string, options?: Registries.DeclarationFindOptions): ReturnType<Registries.DeclarationRegistry['find']> | undefined;\n find(type: 'mixin', keys: string | string[], filterType?: string, options?: Registries.FindOptions): ReturnType<Registries.MixinRegistry['find']> | undefined;\n find(type: 'function', keys: string, filterType?: string, options?: Registries.FindOptions): ReturnType<Registries.FunctionRegistry['find']> | undefined;\n find(type: 'ruleset' | 'declaration' | 'mixin' | 'function', key: string, filterType: string, options?: Registries.FindOptions): ReturnType<Registries.RulesetRegistry['find']> | ReturnType<Registries.DeclarationRegistry['find']> | ReturnType<Registries.MixinRegistry['find']> | ReturnType<Registries.FunctionRegistry['find']> | undefined;\n find(\n type: 'ruleset' | 'declaration' | 'mixin' | 'function',\n keys: string | string[] | Set<string>,\n filterType?: string,\n options: Registries.FindOptions = {}\n ): ReturnType<Registries.RulesetRegistry['find']> | ReturnType<Registries.DeclarationRegistry['find']> | ReturnType<Registries.MixinRegistry['find']> | ReturnType<Registries.FunctionRegistry['find']> | undefined {\n return this._withOwnRenderKey(options.context, () => {\n const registry = this.getRegistry(type, options.context);\n return (registry.find as Function)(keys, filterType, options);\n });\n }\n\n findStatePatchedFunction(\n name: string,\n options: Registries.FindOptions = {}\n ): ReturnType<Registries.FunctionRegistry['find']> | undefined {\n const { filter, context, searchParents = true } = options;\n return this._withOwnRenderKey(context, () => {\n let rules: Rules | undefined = this;\n let findRoot = false;\n\n while (rules) {\n for (const child of rules.getRegistryChildren(context)) {\n if (!isNode(child, N.Func)) {\n continue;\n }\n if (filter && !filter(child)) {\n continue;\n }\n if ((child as Func).getNameKey(context) === name) {\n return child as Func;\n }\n }\n\n if (!searchParents) {\n break;\n }\n\n do {\n rules = rules?.getRegistryParent(context);\n if (findRoot && rules?.type === 'Rules' && rules.getRegistryParent(context) === undefined) {\n break;\n }\n if (rules && rules.sourceNode?.type === 'StyleImport' && rules.sourceNode.options.type !== 'import') {\n findRoot = true;\n }\n } while (!findRoot && rules && rules.type !== 'Rules');\n }\n\n return undefined;\n });\n }\n\n override toString(options?: PrintOptions): string {\n if (!isVisibleInContext(this, options?.context) && !this.fullRender) {\n return '';\n }\n options = getPrintOptions(options);\n const w = options.writer!;\n const depth = options.depth!;\n const mark = w.mark();\n\n const ctx = options.context;\n return this._withOwnRenderKey(ctx, () => {\n const suppressedLeadingComments: Array<{ node: Node; visible: boolean }> = [];\n if (depth === 0) {\n // Snapshot global emit-tracking so repeated `.toString()` calls remain stable.\n const prevCharsetEmitted = ctx?.charsetEmitted;\n const prevTopImports = ctx?.topImports ? [...ctx.topImports] : undefined;\n // @charset must be first\n if (ctx?.currentCharset && !ctx.charsetEmitted) {\n const charset = ctx.currentCharset;\n // Use capture to avoid double-writing (toTrimmedString writes to writer AND returns the string)\n const charsetStr = w.capture(() => charset.toTrimmedString(options));\n w.add(charsetStr, charset);\n w.add('\\n');\n // Do not permanently flip `charsetEmitted` here; restore at end.\n ctx.charsetEmitted = true;\n }\n // Less keeps leading comments before hoisted @import output.\n const isCommentLike = (node: Node): boolean => {\n const text = String(node.valueOf?.() ?? '').trimStart();\n if (!text.startsWith('/*')) {\n return false;\n }\n return isNode(node, N.Comment) || isNode(node, N.Any);\n };\n if (ctx?.topImports?.length) {\n for (const node of this._getRenderChildren(ctx)) {\n if (!isCommentLike(node)) {\n break;\n }\n const commentStr = w.capture(() => node.toTrimmedString(options));\n w.add(normalizeIndent(commentStr, ''), node);\n w.add('\\n');\n const wasVisible = node.hasFlag(F_VISIBLE);\n suppressedLeadingComments.push({ node, visible: wasVisible });\n if (wasVisible) {\n node.removeFlag(F_VISIBLE);\n }\n }\n }\n // @import must come after @charset but before other rules\n if (ctx?.topImports?.length) {\n for (const importRule of ctx.topImports) {\n const importStr = w.capture(() => importRule.toString(options));\n w.add(normalizeIndent(importStr, ''), importRule);\n w.add('\\n');\n }\n // Do not permanently clear; restore at end.\n }\n // Restore global tracking (we only needed it during this print).\n if (ctx) {\n ctx.charsetEmitted = prevCharsetEmitted;\n if (prevTopImports) {\n ctx.topImports = prevTopImports;\n }\n }\n }\n\n this.processPrePost('pre', '', options);\n const bodyMark = w.mark();\n const bodyStr = this.toTrimmedString(options);\n const bodyEmitted = w.getSince(bodyMark);\n if (bodyEmitted.length === 0 && bodyStr) {\n w.add(bodyStr);\n }\n // At root level, ensure output ends with a single newline (standard for CSS files)\n // Don't propagate all the last child's post content (which may have extra whitespace)\n if (depth === 0) {\n for (const suppressed of suppressedLeadingComments) {\n if (suppressed.visible) {\n suppressed.node.addFlag(F_VISIBLE);\n }\n }\n const result = w.getSince(mark).trimEnd();\n // Ensure exactly one trailing newline (only if there's content)\n return result ? result + '\\n' : '';\n }\n return w.getSince(mark);\n });\n }\n\n pendingExtends = new Set<[find: Selector, extendWith: Selector, partial: boolean]>();\n\n _setValueArray(value: Node[]): void {\n (this as unknown as { value: Node[] }).value = value;\n }\n\n prependWrapperChildren(...items: Node[]): void {\n if (items.length === 0) {\n return;\n }\n this._setValueArray([...items, ...(this.value as Node[])]);\n for (const item of items) {\n if (item instanceof Node) {\n this.adopt(item);\n this.registerNode(item);\n }\n }\n }\n\n /**\n * Create a shallow body wrapper for mixin eval.\n *\n * Creates a new Rules that SHARES the current children array and does NOT adopt\n * children canonically (their canonical `.parent` stays unchanged). Render-key\n * parent edges carry the per-placement parent chain.\n *\n * This replaces clone(true) in the mixin body path for massive perf improvement:\n * a mixin body with 100 declarations creates 1 Rules wrapper\n * instead of recursively cloning all 100+ nodes.\n */\n createShallowBodyWrapper(ctx?: Context, renderKey?: RenderKey): Rules {\n const options = this._cloneOptionsForContext(ctx);\n const location = Array.isArray(this.location) && this.location.length === 6\n ? this.location as LocationInfo\n : undefined;\n const nextRenderKey = renderKey ?? EVAL;\n // Create a new Rules with empty children — bypass constructor adoption\n const wrapper = new (this.constructor as typeof Rules)(\n [],\n options ? { ...options } : undefined,\n location,\n this.treeContext\n );\n // Reuse the same child array directly — NOT through the constructor\n // so adopt() is NOT called on canonical children.\n wrapper._setValueArray(this.value as Node[]);\n wrapper.inherit(this);\n wrapper.renderKey = nextRenderKey;\n const invocationBindings = this._cloneInvocationBindings();\n if (invocationBindings) {\n wrapper._invocationBindings = invocationBindings;\n }\n if (this.functionRegistry) {\n wrapper.functionRegistry = this.functionRegistry.cloneForRules(wrapper);\n }\n wrapper._connectSharedChildren(wrapper.renderKey);\n const sourceValueEdges = (this as unknown as { valueEdges?: Array<Map<RenderKey, Node> | undefined> }).valueEdges;\n if (sourceValueEdges) {\n for (let index = 0; index < sourceValueEdges.length; index++) {\n const override = sourceValueEdges[index]?.get(nextRenderKey);\n if (!override) {\n continue;\n }\n addEdgeAt(wrapper, 'value', index, nextRenderKey, override);\n addParentEdge(override, nextRenderKey, wrapper);\n }\n }\n return wrapper;\n }\n\n createPlacementWrapper(ctx?: Context, renderKey?: RenderKey): Rules {\n const options = this._cloneOptionsForContext(ctx);\n const location = Array.isArray(this.location) && this.location.length === 6\n ? this.location as LocationInfo\n : undefined;\n const nextRenderKey = renderKey ?? EVAL;\n const wrapper = new (this.constructor as typeof Rules)(\n [],\n options ? { ...options } : undefined,\n location,\n this.treeContext\n );\n const previousRenderKey = ctx?.renderKey;\n if (ctx && this.renderKey !== CANONICAL) {\n ctx.renderKey = this.renderKey;\n }\n try {\n wrapper._setValueArray([...getChildren(this, ctx)] as Node[]);\n } finally {\n if (ctx) {\n ctx.renderKey = previousRenderKey;\n }\n }\n wrapper.inherit(this);\n wrapper.renderKey = nextRenderKey;\n const invocationBindings = this._cloneInvocationBindings();\n if (invocationBindings) {\n wrapper._invocationBindings = invocationBindings;\n }\n if (this.functionRegistry) {\n wrapper.functionRegistry = this.functionRegistry.cloneForRules(wrapper);\n }\n wrapper._connectSharedChildren(wrapper.renderKey);\n return wrapper;\n }\n\n createPlacementWrapperWithChildren(children: readonly Node[], renderKey: RenderKey = EVAL): Rules {\n const options = this._cloneOptionsForContext(undefined);\n const location = Array.isArray(this.location) && this.location.length === 6\n ? this.location as LocationInfo\n : undefined;\n const wrapper = new (this.constructor as typeof Rules)(\n [],\n options ? { ...options } : undefined,\n location,\n this.treeContext\n );\n wrapper._setValueArray([...children] as Node[]);\n wrapper.inherit(this);\n wrapper.renderKey = renderKey;\n const invocationBindings = this._cloneInvocationBindings();\n if (invocationBindings) {\n wrapper._invocationBindings = invocationBindings;\n }\n if (this.functionRegistry) {\n wrapper.functionRegistry = this.functionRegistry.cloneForRules(wrapper);\n }\n wrapper._connectSharedChildren(wrapper.renderKey);\n return wrapper;\n }\n\n withRenderOwner(\n owner: Node,\n renderKey?: RenderKey,\n context?: Context\n ): Rules {\n let rules: Rules = this;\n const effectiveRenderKey = renderKey ?? owner.renderKey;\n if (effectiveRenderKey !== undefined && effectiveRenderKey !== CANONICAL && rules.renderKey === CANONICAL) {\n const existing = ((owner as unknown as Record<string, unknown>).rulesEdge as Map<RenderKey, Rules> | undefined)\n ?.get(effectiveRenderKey);\n if (existing) {\n rules = existing;\n } else {\n const wrapped = rules.createShallowBodyWrapper(undefined, effectiveRenderKey);\n wrapped.parent = owner;\n addEdge(owner, 'rules', effectiveRenderKey, wrapped);\n if (owner.renderKey === effectiveRenderKey) {\n (owner as unknown as { rules: Rules }).rules = wrapped;\n }\n rules = wrapped;\n }\n }\n if (context && getCurrentParentNode(rules, context) !== owner) {\n owner.adopt(rules, context);\n }\n return rules;\n }\n\n constructor(\n value: readonly Node[],\n options?: RulesOptions & NodeOptions,\n location?: OptionalLocation,\n context?: Context | TreeContext\n ) {\n const treeContext = context instanceof Context\n ? context.treeContext\n : context;\n const ctx = context instanceof Context\n ? context\n : undefined;\n\n let rulesVisibility = options?.rulesVisibility ?? {};\n rulesVisibility.Declaration ??= 'public';\n rulesVisibility.Ruleset ??= 'public';\n rulesVisibility.VarDeclaration ??= 'public';\n rulesVisibility.Mixin ??= 'public';\n const mergedOptions = { ...options, rulesVisibility };\n const normalized = (value ?? []) as Node[];\n super(normalized, mergedOptions, location, treeContext);\n this._setValueArray(normalized);\n for (const child of normalized) {\n if (child instanceof Node) {\n this.adopt(child, ctx);\n this.registerNode(child);\n }\n }\n this.allowRoot = true;\n this.allowRuleRoot = true;\n }\n\n setInvocationBinding(name: string, binding: InvocationBinding): void {\n (this._invocationBindings ??= new Map()).set(name, { ...binding });\n }\n\n getInvocationBinding(name: string, context?: Context): VarDeclaration | undefined {\n const binding = this._invocationBindings?.get(name);\n if (!binding) {\n return undefined;\n }\n if (binding.declaration) {\n return binding.declaration;\n }\n const bindingContext = context\n ? {\n ...context,\n rulesContext: this,\n renderKey: context.renderKey ?? this.renderKey\n } as Context\n : undefined;\n const declaration = binding.factory\n ? binding.factory(this, bindingContext)\n : binding.template?.clone(false, undefined, bindingContext);\n if (!declaration) {\n return undefined;\n }\n declaration.renderKey = bindingContext?.renderKey ?? this.renderKey ?? declaration.renderKey;\n if (bindingContext) {\n setParent(declaration, this, bindingContext);\n } else {\n declaration.parent = this;\n }\n binding.declaration = declaration;\n return declaration;\n }\n\n * [Symbol.iterator]() {\n let value = this.value;\n /**\n * This should always be the case? But at one point something somewhere\n * set the value to undefined I think, so just leaving this defensively.\n */\n if (isArray(value)) {\n yield* value.entries();\n }\n }\n\n private _getRenderVisibleChildAt(index: number, _context?: Context): Node | undefined {\n const canonical = this.value[index];\n if (this.renderKey === CANONICAL) {\n return canonical;\n }\n\n const cursor = { node: this as Node, renderKey: this.renderKey };\n const existing = getEdgeAt(cursor, 'value', index)?.node;\n if (existing) {\n return existing;\n }\n\n return canonical;\n }\n\n private _getRenderChildren(context?: Context): readonly Node[] {\n return this._withOwnRenderKey(context, () => {\n if (this.renderKey === CANONICAL) {\n return context ? getChildren(this, context) : this.value;\n }\n\n const children: Node[] = [];\n for (let i = 0; i < this.value.length; i++) {\n const child = this._getRenderVisibleChildAt(i, context);\n if (child) {\n children.push(child);\n }\n }\n return children;\n });\n }\n\n getRegistryChildren(context?: Context): readonly Node[] {\n return this._getRenderChildren(context);\n }\n\n ensureCurrentRenderRulesRegistered(context?: Context): void {\n const currentRenderRules = this\n .getRegistryChildren(context)\n .filter((child): child is Rules => isNode(child, N.Rules));\n\n for (let i = this.rulesSet.length; i < currentRenderRules.length; i++) {\n this.registerNode(currentRenderRules[i]!, undefined, context);\n }\n }\n\n private _setChildren(value: readonly Node[], context?: Context, markDirty: boolean = true): void {\n if (context) {\n setChildren(this, value, context, { markDirty });\n return;\n }\n const nextValue = [...value];\n this._setValueArray(nextValue);\n for (const child of nextValue) {\n this.adopt(child);\n }\n }\n\n private _setChildAt(index: number, node: Node, context?: Context, markDirty: boolean = true): void {\n if (context) {\n setChildAt(this, index, node, context, { markDirty });\n return;\n }\n const nextValue = [...this.value];\n nextValue[index] = node;\n this._setValueArray(nextValue);\n this.adopt(node);\n }\n\n /**\n * Used by Ruleset, Mixins, and AtRules etc to render\n * rules with braces.\n */\n toBraced(options?: PrintOptions) {\n let opts = getPrintOptions(options);\n // Use options.depth if provided, otherwise calculate from frameState\n const depth = opts.depth!;\n const w = opts.writer!;\n const mark = w.mark();\n let space = ''.padStart(depth * 2);\n return this._withOwnRenderKey(opts.context, () => {\n w.add('{');\n // Children render one level deeper inside braces.\n const childOptions = { ...opts, depth: depth + 1 };\n childOptions.writer!.add('\\n');\n Rules.prototype.toTrimmedString.call(this, childOptions);\n // ensure closing brace is on its own properly indented line\n w.add('\\n');\n if (depth !== 0) {\n w.add(space);\n }\n w.add('}');\n // At root level (depth === 0), don't add a newline after the closing brace\n // The parent _emitRulesBody will add the newline before the next item\n // For nested rules (depth > 0), the newline is handled by the parent's _emitRulesBody\n return w.getSince(mark);\n });\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const ctx = options.context;\n return this._withOwnRenderKey(ctx, () => {\n const depth = options.depth ?? 0;\n const space = indent(depth);\n const value = this._getRenderChildren(options.context);\n const referenceMode = Boolean(options.referenceMode);\n const referenceRenderEnabled = referenceMode ? Boolean(options.referenceRenderEnabled) : true;\n const items = value.filter(n => isVisibleInContext(n, options.context));\n\n const isInlineSourceRules = (node: Node): boolean => {\n if (node.type !== 'Rules') {\n return false;\n }\n const rulesNode = node as Rules;\n const rulesValue = rulesNode._getRenderChildren(options.context);\n if (rulesValue.length !== 1) {\n return false;\n }\n const only = rulesValue[0]!;\n return only.type === 'Any' && (only as Any).role === 'any';\n };\n\n let emittedCount = 0;\n let lastEmittedType: string | undefined;\n let lastEmittedWasInlineSourceRules = false;\n for (const n of items) {\n const isContainer = n.type === 'Ruleset' || n.type === 'AtRule' || n.type === 'Rules';\n if (referenceMode && !referenceRenderEnabled && !isContainer) {\n continue;\n }\n if (emittedCount > 0) {\n const currentBuffer = w.getSince(0);\n const bufferEndsWithNewline = currentBuffer.endsWith('\\n');\n const needsInlineBoundarySpacing = (\n (lastEmittedType === 'Any' && n.type !== 'Any')\n || (lastEmittedWasInlineSourceRules && n.type !== 'Any')\n );\n if (!bufferEndsWithNewline || needsInlineBoundarySpacing) {\n w.add('\\n');\n }\n }\n\n const isChildRules = n.type === 'Rules';\n const isRulesetOrAtRule = n.type === 'Ruleset' || n.type === 'AtRule';\n if (!isChildRules && !isRulesetOrAtRule && depth !== 0) {\n w.add(space);\n }\n\n let childOptions = { ...options, depth };\n if (isChildRules) {\n if (referenceMode && referenceRenderEnabled) {\n childOptions = {\n ...childOptions,\n referenceMode: false,\n referenceRenderEnabled: true\n };\n } else {\n const ownReferenceMode = (n.options as any)?.referenceMode === true;\n const childReferenceMode = referenceMode || ownReferenceMode;\n const enteringReferenceMode = !referenceMode && ownReferenceMode;\n const ownReferenceRenderOnExtend = (n.options as RulesOptions | undefined)?.referenceRenderOnExtend !== false;\n const childReferenceRenderOnExtend = childReferenceMode\n ? (enteringReferenceMode ? ownReferenceRenderOnExtend : options.referenceRenderOnExtend !== false)\n : true;\n const childReferenceRenderEnabled = childReferenceMode\n ? (enteringReferenceMode ? false : referenceRenderEnabled)\n : true;\n childOptions = {\n ...childOptions,\n referenceMode: childReferenceMode,\n referenceRenderEnabled: childReferenceRenderEnabled,\n referenceRenderOnExtend: childReferenceRenderOnExtend\n };\n }\n } else if (\n referenceMode\n && referenceRenderEnabled\n && isRulesetOrAtRule\n ) {\n const keepReferenceFiltering = (\n isNode(n, N.Ruleset)\n && (() => {\n const ownSelector = (n as Ruleset).getOwnSelector();\n return Boolean(\n ownSelector\n && !(ownSelector instanceof Nil)\n && isBareAmpersandOwnSelector(ownSelector)\n );\n })()\n );\n childOptions = {\n ...childOptions,\n referenceMode: keepReferenceFiltering,\n referenceRenderEnabled: true\n };\n }\n\n const rule = w.capture(() => n.toTrimmedString(childOptions));\n if (!rule && isContainer) {\n continue;\n }\n w.add(rule, n);\n const needsSemi = isNode(n, N.Declaration | N.VarDeclaration)\n ? (n as Declaration).requiresSemi(childOptions.context)\n : (n as Node).requiredSemi;\n if (needsSemi && n.options.semi !== false) {\n w.add(';', n);\n }\n emittedCount++;\n lastEmittedType = n.type;\n lastEmittedWasInlineSourceRules = isInlineSourceRules(n);\n }\n return w.getSince(mark);\n });\n }\n\n /** All rules, with nested rules flattened */\n flatRules(visibleOnly: boolean = false, context?: Context, positionMap?: WeakMap<Node, FlatRulePosition>) {\n const finalRules: Node[] = [];\n const iterateRules = (\n rules: Rules,\n inheritedRenderKey?: RenderKey\n ) => {\n type DeferredEntry =\n | {\n kind: 'node';\n node: Node;\n renderKey?: RenderKey;\n }\n | {\n kind: 'flatten';\n rules: Rules;\n inheritedRenderKey?: RenderKey;\n };\n const renderKey = rules.renderKey ?? inheritedRenderKey;\n const scopedContext = context\n ? (\n renderKey !== undefined\n && context.renderKey !== renderKey\n ? { ...context, renderKey, rulesContext: rules } as Context\n : (context.rulesContext !== rules\n ? { ...context, rulesContext: rules } as Context\n : context)\n )\n : undefined;\n const pendingDescendants: DeferredEntry[] = [];\n let hasEmittedLocalNonContainer = false;\n const emitNode = (node: Node, nodeRenderKey?: RenderKey): void => {\n if (positionMap && nodeRenderKey !== CANONICAL && nodeRenderKey !== undefined) {\n positionMap.set(node, { renderKey: nodeRenderKey });\n }\n if (!isNode(node, N.Ruleset | N.AtRule | N.Rules)) {\n hasEmittedLocalNonContainer = true;\n }\n finalRules.push(node);\n };\n const flushPendingDescendants = (): void => {\n for (const entry of pendingDescendants) {\n if (entry.kind === 'flatten') {\n iterateRules(entry.rules, entry.inheritedRenderKey);\n continue;\n }\n emitNode(entry.node, entry.renderKey);\n }\n pendingDescendants.length = 0;\n };\n\n for (let n of rules._getRenderChildren(scopedContext)) {\n if (isNode(n, N.Rules)) {\n if ((n.options as RulesOptions)?.referenceMode === true) {\n flushPendingDescendants();\n emitNode(\n n,\n (n as Rules).renderKey ?? renderKey\n );\n } else {\n if (pendingDescendants.length > 0 && !hasEmittedLocalNonContainer) {\n pendingDescendants.push({\n kind: 'flatten',\n rules: n as Rules,\n inheritedRenderKey: renderKey\n });\n } else {\n iterateRules(n, renderKey);\n }\n }\n continue;\n }\n if (\n visibleOnly\n && isNode(n, N.Ruleset)\n && !isVisibleInContext(n, scopedContext)\n && !n.fullRender\n ) {\n pendingDescendants.push({\n kind: 'flatten',\n rules: (n as Ruleset).enterRules(scopedContext),\n inheritedRenderKey: renderKey\n });\n continue;\n }\n if (!visibleOnly || isVisibleInContext(n, scopedContext) || n.fullRender) {\n if (isNode(n, N.Ruleset)) {\n pendingDescendants.push({\n kind: 'node',\n node: n,\n renderKey\n });\n } else if (isNode(n, N.AtRule)) {\n flushPendingDescendants();\n emitNode(n, renderKey);\n } else {\n emitNode(n, renderKey);\n }\n }\n }\n\n flushPendingDescendants();\n };\n iterateRules(this);\n return finalRules;\n }\n\n visibleRules(context?: Context) {\n return this._getRenderChildren(context).filter(n => isVisibleInContext(n, context));\n }\n\n /**\n * Return an object representation of a ruleset\n */\n toObject(convertToPrimitives: true, context?: Context): Record<string, string | number | boolean>;\n toObject(convertToPrimitives: false, context?: Context): Record<string, Node>;\n toObject(convertToPrimitives?: boolean, context?: Context): Record<string, string | number | boolean | Node>;\n toObject(convertToPrimitives: boolean = true, context?: Context): Record<string, string | number | boolean | Node> {\n let output = new Map<string, boolean | string | number | Node>();\n const iterateRules = (rules: Rules) => {\n for (let n of rules._getRenderChildren(context)) {\n if (isNode(n, N.Declaration)) {\n let { name, value, important } = n as any;\n if (convertToPrimitives) {\n let primitive = value.valueOf();\n let outputValue = important ? `${primitive} ${important}` : primitive;\n if (outputValue === undefined) {\n continue;\n }\n output.set(name.toString(), outputValue);\n } else {\n let outputValue = important ? new Sequence([n, important]) : n;\n output.set(name.toString(), outputValue);\n }\n } else if (n instanceof Rules) {\n iterateRules(n);\n }\n }\n };\n iterateRules(this as unknown as Rules);\n return Object.fromEntries(output);\n }\n\n /** @todo - Refactor? */\n _rulesSet: RulesEntry[] | undefined;\n get rulesSet(): RulesEntry[] {\n return (this._rulesSet ??= []);\n }\n\n registerNode(node: Node, options?: Record<string, any>, context?: Context) {\n if (isNode(node, N.Rules)) {\n const nodeOptions = (node as Rules).options;\n // Use options if provided, otherwise use node's settings, otherwise empty\n // Then merge with node's settings to preserve any values not in options\n let optionsVisibility = options?.rulesVisibility;\n let nodeVisibility = nodeOptions.rulesVisibility ?? {};\n let rulesVisibility = optionsVisibility\n ? { ...nodeVisibility, ...optionsVisibility }\n : nodeVisibility;\n\n /** Only Declaration and Ruleset are public by default.\n * VarDeclaration visibility should be set by the parser (optional for Less, private for Jess/Sass).\n * Mixin visibility should be set by the parser.\n */\n rulesVisibility.Declaration ??= 'public';\n rulesVisibility.Ruleset ??= 'public';\n rulesVisibility.Mixin ??= 'public';\n\n /** Either one set as readonly will win */\n let readonly = Boolean(options?.readonly || nodeOptions.readonly);\n this.rulesSet.push({\n node,\n rulesVisibility,\n readonly\n });\n\n // Note: Rulesets from imported Rules are registered in treeRoot's registry\n // after evaluation completes (in evalNode), when treeRoot is guaranteed to be set\n } else if (isNode(node, N.Declaration)) {\n /**\n * setDefined works like Sass's !default flag - it finds the original variable\n * declaration and inserts a new declaration at the same rules level as the\n * found variable, but before the current nested node.\n */\n if (node.options?.setDefined && context) {\n const key = (node as any).name?.toString();\n const sourceNode = node.sourceNode ?? node;\n let opts: Registries.FindOptions = {};\n opts.searchParents = true;\n opts.context = context;\n opts.start = undefined;\n // Exclude the current declaration by source identity so a derived eval node\n // cannot resolve its own canonical registry entry as the \"existing\" declaration.\n opts.filter = (n: Node) => (n.sourceNode ?? n) !== sourceNode;\n let result = this.find('declaration', key, node.type as 'VarDeclaration' | 'Declaration', opts);\n if (result) {\n if (result.options?.readonly || opts.readonly) {\n throw new ReferenceError(`\"${key}\" is readonly`);\n }\n\n // Find the Rules node that contains the found declaration\n let foundRules = getCurrentParentNode(result, context) as Rules | undefined;\n\n if (!foundRules) {\n throw new Error(`Could not find parent Rules for declaration '${key}'`);\n }\n\n // Create a new declaration with the same name but our value\n const newDeclaration = node.copy();\n newDeclaration.options = { ...newDeclaration.options };\n newDeclaration.options.setDefined = undefined; // Remove setDefined flag\n\n // Adopt the new declaration to the found Rules\n foundRules.adopt(newDeclaration);\n\n // Add to the value array AFTER the found declaration\n // This ensures it shadows the original and is evaluated after it\n const foundIndex = foundRules.value.indexOf(result);\n if (foundIndex !== -1) {\n if (context) {\n foundRules.splice(context, foundIndex + 1, 0, newDeclaration);\n } else {\n foundRules.splice(foundIndex + 1, 0, newDeclaration);\n }\n } else {\n // If not found in array, add at the beginning\n if (context) {\n foundRules.unshift(context, newDeclaration);\n } else {\n foundRules.unshift(newDeclaration);\n }\n }\n\n // Register it via registerNode to ensure it's properly indexed\n // Note: registerNode will call register('declaration', ...) which adds to registry\n // We skip setDefined processing since we already removed the flag\n foundRules.registerNode(newDeclaration, undefined, context);\n } else {\n throw new ReferenceError(`\"${key}\" is not defined`);\n }\n }\n\n this.register('declaration', node, context);\n } else if (isNode(node, N.Ruleset)) {\n // Register to 'mixin' for mixin calls\n // Always register - guard filtering happens at call time in getFunctionFromMixins\n // Note: 'ruleset' registration for extends now happens in Ruleset.preEval to the extend root's registry\n this.register('mixin', node, context);\n } else if (isNode(node, N.Mixin)) {\n this.register('mixin', node, context);\n } else if (isNode(node, N.Func)) {\n this.register('function', node, context);\n }\n }\n\n override push(...nodes: Node[]): void;\n override push(ctx: Context, ...nodes: Node[]): void;\n override push(...args: [Context, ...Node[]] | Node[]): void {\n const hasCtx = args.length > 0 && args[0] instanceof Context;\n const ctx = hasCtx ? args[0] as Context : undefined;\n const nodes = (hasCtx ? args.slice(1) : args) as Node[];\n // Route through _getChildren/_setChildren overlay when context is active\n if (ctx) {\n const nextValue = [...this._getRenderChildren(ctx)];\n for (const node of nodes) {\n this.adopt(node, ctx);\n nextValue.push(node);\n }\n this._setChildren(nextValue, ctx);\n for (const node of nodes) {\n this.registerNode(node, undefined, ctx);\n }\n return;\n }\n this._setValueArray([...this.value]);\n for (const node of nodes) {\n this.adopt(node, ctx);\n (this.value as Node[]).push(node);\n this.registerNode(node, undefined, ctx);\n }\n }\n\n override splice(start: number, deleteCount: number, ...items: Node[]): Node[];\n override splice(ctx: Context, start: number, deleteCount: number, ...items: Node[]): Node[];\n override splice(...args: [Context, number, number, ...Node[]] | [number, number, ...Node[]]): Node[] {\n const hasCtx = args[0] instanceof Context;\n const ctx = hasCtx ? args[0] as Context : undefined;\n const [start, deleteCount, ...items] = (hasCtx ? args.slice(1) : args) as [number, number, ...Node[]];\n // Route through overlay when context is active\n if (ctx) {\n const nextValue = [...this._getRenderChildren(ctx)];\n const removed = nextValue.splice(start, deleteCount, ...items);\n for (const item of items) {\n if (item instanceof Node) {\n this.adopt(item, ctx);\n }\n }\n this._setChildren(nextValue, ctx);\n for (const item of items) {\n if (item instanceof Node) {\n this.registerNode(item, undefined, ctx);\n }\n }\n (this as unknown as { _invalidateValueOf: () => void })._invalidateValueOf();\n return removed as Node[];\n }\n const nextValue = [...this.value];\n const removed = nextValue.splice(start, deleteCount, ...items);\n this._setValueArray(nextValue);\n for (const item of items) {\n if (item instanceof Node) {\n this.adopt(item, ctx);\n this.registerNode(item, undefined, ctx);\n }\n }\n (this as unknown as { _invalidateValueOf: () => void })._invalidateValueOf();\n return removed as Node[];\n }\n\n override unshift(...items: Node[]): void;\n override unshift(ctx: Context, ...items: Node[]): void;\n override unshift(...args: [Context, ...Node[]] | Node[]): void {\n const hasCtx = args.length > 0 && args[0] instanceof Context;\n const ctx = hasCtx ? args[0] as Context : undefined;\n const items = (hasCtx ? args.slice(1) : args) as Node[];\n // Route through overlay when context is active\n if (ctx) {\n for (const item of items) {\n if (item instanceof Node) {\n this.adopt(item, ctx);\n }\n }\n this._setChildren([...items, ...this._getRenderChildren(ctx)], ctx);\n for (const item of items) {\n if (item instanceof Node) {\n this.registerNode(item, undefined, ctx);\n }\n }\n (this as unknown as { _invalidateValueOf: () => void })._invalidateValueOf();\n return;\n }\n this._setValueArray([...this.value]);\n (this.value as Node[]).unshift(...items);\n for (const item of items) {\n if (item instanceof Node) {\n this.adopt(item, ctx);\n this.registerNode(item, undefined, ctx);\n }\n }\n (this as unknown as { _invalidateValueOf: () => void })._invalidateValueOf();\n }\n\n at(index: number, context?: Context) {\n return atIndex(this._getRenderChildren(context), index);\n }\n\n /**\n * This traverses deeply to visit all nodes, but indexes locally.\n */\n override preEval(context: Context) {\n if (!this.preEvaluated) {\n context.depth++;\n let rules = this;\n // When this is the nestable at-rule wrapper (one child Ruleset(&)), do not clone so\n // inner rulesets register to the same object we push and register as extend root.\n const nestableAtRuleNames = new Set(['@media', '@supports', '@layer', '@container', '@scope']);\n const activeParent = getCurrentParentNode(this, context);\n const sourceParent = getSourceParent(this, context);\n const parentAtRule = activeParent?.type === 'AtRule'\n ? activeParent\n : (sourceParent?.type === 'AtRule' ? sourceParent : null);\n const isNestableAtRuleBody =\n parentAtRule\n && nestableAtRuleNames.has(String((parentAtRule as any).name?.valueOf?.() ?? ''));\n const children = rules._getRenderChildren(context);\n const first = children[0];\n const isWrapper =\n isNestableAtRuleBody\n && children.length === 1\n && isNode(first, N.Ruleset)\n && isNode((first as Ruleset).get('selector'), N.Ampersand);\n if (isWrapper) {\n rules = this;\n }\n rules.preEvaluated = true;\n // Save current context and set up new context for variable lookups during preEval\n const saved = this._snapshotContext(context);\n this._setupContextForRules(context, rules);\n\n // Set context.root early if this is the main root\n const isMainRoot = !context.root;\n if (isMainRoot) {\n context.root = rules;\n }\n\n /**\n * I think maybe we can just set the index to the actual order?\n */\n for (let i = 0; i < children.length; i++) {\n let n = children[i]!;\n setIndex(n, i, context);\n }\n // Preserve parent when cloning - if this Rules is inside a ruleset, maintain the parent relationship\n const parent = getCurrentParentNode(this, context);\n if (parent && !getCurrentParentNode(rules, context)) {\n parent.adopt(rules, context);\n }\n\n // Set context.root if not already set (needed for preEval visitors)\n if (!context.root) {\n context.root = rules;\n }\n // When getTree() set context.root to the original Rules but we're processing a clone,\n // use the clone as context.root so registerRoot/pushExtendRoot run and rulesets register to the clone (extend fix).\n if (context.root === this && this !== rules) {\n context.root = rules;\n }\n\n // Register main root as extend root if this is the root (needed for extends in preEval)\n // Check rules === context.root at registration time (not using stale isMainRoot)\n if (rules === context.root && !context.extendRoots.root) {\n context.extendRoots.registerRoot(rules);\n context.extendRoots.pushExtendRoot(rules);\n }\n\n // Always push nestable at-rule body so inner rulesets register to it (not document root).\n // Needed for both: wrapper (collapseNesting) and direct body (collapseNesting: false).\n if (isNestableAtRuleBody) {\n context.extendRoots.pushExtendRoot(rules);\n }\n\n // Multi-pass registration system for handling interpolated names\n const mp = this._multiPassPreEval(rules, context, saved);\n const popNestableBody = () => {\n if (isNestableAtRuleBody) {\n context.extendRoots.popExtendRoot();\n }\n };\n if (isThenable(mp)) {\n return (mp as Promise<this>).then((result) => {\n popNestableBody();\n return result;\n });\n }\n popNestableBody();\n return mp;\n }\n return this;\n }\n\n /**\n * Multi-pass preEval system to handle interpolated names and dependencies\n */\n private _multiPassPreEval(rules: Rules, context: Context, saved: any): MaybePromise<this> {\n // First pass: Only register nodes with static names\n const staticNodes: Node[] = [];\n const dynamicNodes: Node[] = [];\n\n // Process each node with static name, handling both sync and async preEval\n const processResult = serialForEach(rules._getRenderChildren(context), (node, index) => {\n // Check if node has a static name (can be registered immediately)\n if (node.type === 'Any' && (node as any).role === 'charset') {\n /** Special case where we register the charset node immediately */\n const charsetNode = (node as Any).preEval(context);\n rules._setChildAt(index, charsetNode, context, false);\n rules.adopt(charsetNode, context);\n return;\n }\n // Nodes that don't register by name (Call, Expression, etc.) skip\n // both preEval and dynamic resolution — they're handled by the eval queue.\n if (!this._isRegisterableType(node)) {\n setIndex(node, index, context);\n return;\n }\n if (this._hasStaticName(node, context)) {\n // Pre-evaluate nodes with static names before registration\n // This ensures selectors are evaluated and keySets are available for rulesets\n const preEvald = node.preEval(context);\n if (isThenable(preEvald)) {\n return (preEvald as Promise<Node>).then((preEvaldNode) => {\n rules._setChildAt(index, preEvaldNode, context, false);\n rules.adopt(preEvaldNode, context);\n setIndex(preEvaldNode as Node, index, context);\n // After async preEval, check if it still has a static name\n if (this._hasStaticName(preEvaldNode, context)) {\n staticNodes.push(preEvaldNode);\n this._registerNodeIfEligible(rules, preEvaldNode, context);\n } else {\n dynamicNodes.push(preEvaldNode);\n }\n });\n }\n rules._setChildAt(index, preEvald as Node, context, false);\n rules.adopt(preEvald as Node, context);\n setIndex(preEvald as Node, index, context);\n const nodeToRegister = preEvald as Node;\n staticNodes.push(nodeToRegister);\n this._registerNodeIfEligible(rules, nodeToRegister, context);\n } else {\n dynamicNodes.push(node);\n }\n });\n\n const finish = () => {\n // If no dynamic nodes, we're done\n if (dynamicNodes.length === 0) {\n // Restore context after preEval is complete\n context.rulesContext = saved.rulesContext;\n context.renderKey = saved.renderKey;\n context.treeRoot = saved.treeRoot;\n // Only restore context.root if saved.root is defined (not the outermost root)\n // If saved.root is undefined, it means we're at the outermost level, so keep context.root as is\n if (saved.root !== undefined) {\n context.root = saved.root;\n }\n return rules as this;\n }\n // Multi-pass resolution of dynamic nodes\n return this._resolveDynamicNodes(rules, context, saved, dynamicNodes);\n };\n\n if (isThenable(processResult)) {\n return (processResult as Promise<void>).then(() => finish());\n }\n return finish();\n }\n\n /**\n * Helper to check if a value is static (either a Node with F_STATIC flag or a primitive value)\n */\n private _isStatic(value: any): boolean {\n if (value && typeof value.hasFlag === 'function') {\n return value.hasFlag(F_STATIC);\n }\n // Primitive values (strings, numbers, etc.) are considered static\n return true;\n }\n\n /**\n * Check if a node type participates in name-based registration.\n * Only these node types have names/selectors that _resolveDynamicNodes\n * needs to resolve. Everything else (Call, Expression, Comment, etc.)\n * goes straight to the eval queue without preEval.\n */\n private _isRegisterableType(node: Node): boolean {\n return isNode(node, N.VarDeclaration | N.Declaration | N.Mixin | N.Ruleset) || (node as Node).type === 'StyleImport';\n }\n\n /**\n * Check if a node has a static name that can be registered immediately\n */\n private _hasStaticName(node: Node, context?: Context): boolean {\n if (isNode(node, N.VarDeclaration)) {\n return this._isStatic(node.get('name'));\n }\n if (isNode(node, N.Mixin)) {\n // Check position-patched name: preEval may have resolved an interpolated name\n const name = node.get('name', context);\n return this._isStatic(name);\n }\n if (isNode(node, N.Declaration)) {\n return this._isStatic(node.get('name'));\n }\n if (node.type === 'StyleImport') {\n return this._isStatic((node as Node & { path: unknown }).path);\n }\n if (isNode(node, N.Ruleset)) {\n const selector: Node = (node as Ruleset).get('selector');\n if (isNode(selector, N.BasicSelector | N.CompoundSelector | N.ComplexSelector | N.SelectorList | N.Nil)) {\n return true;\n }\n if (context && isPreEvaluated(node, context)) {\n return true;\n }\n return (selector as Node).hasFlag(F_STATIC);\n }\n return node.hasFlag(F_STATIC);\n }\n\n /**\n * Register a node if it's eligible for registration\n */\n private _registerNodeIfEligible(rules: Rules, node: Node, context: Context) {\n if (isNode(node, N.Declaration)) {\n rules.registerNode(node, undefined, context);\n } else if (isNode(node, N.Mixin)) {\n rules.registerNode(node, undefined, context);\n } else if (isNode(node, N.Ruleset)) {\n // registerNode handles both 'mixin' and 'ruleset' registries\n rules.registerNode(node, undefined, context);\n }\n }\n\n /**\n * Multi-pass resolution of dynamic nodes with interpolated names\n */\n private _resolveDynamicNodes(rules: Rules, context: Context, saved: any, dynamicNodes: Node[]): MaybePromise<this> {\n const resolvedNodes: Node[] = [];\n\n const handleResolvedNode = (resolvedNode: Node, node: Node, stillUnresolved: Node[]): boolean => {\n if (resolvedNode.index === undefined) {\n resolvedNode.index = node.index;\n }\n if (!resolvedNode.sourceNode) {\n resolvedNode.sourceNode = node.sourceNode ?? node;\n }\n if (resolvedNode.type === 'Ruleset') {\n rules.registerNode(resolvedNode, undefined, context);\n }\n if (isNode(resolvedNode, N.Nil) || this._hasStaticName(resolvedNode, context)) {\n resolvedNodes.push(resolvedNode);\n this._registerNodeIfEligible(rules, resolvedNode, context);\n return true; // made progress\n } else {\n stillUnresolved.push(resolvedNode);\n return false;\n }\n };\n\n const applyResolvedNodes = () => {\n const children = rules._getRenderChildren(context);\n for (let i = 0; i < children.length; i++) {\n const node = children[i]!;\n const nodeIdx = getIndex(node, context);\n const resolvedNode = resolvedNodes.find(n => getIndex(n, context) === nodeIdx);\n if (resolvedNode && resolvedNode !== node) {\n rules._setChildAt(i, resolvedNode.inherit(node), context, false);\n rules.adopt(resolvedNode, context);\n }\n }\n };\n\n const finishResolution = (): this => {\n applyResolvedNodes();\n context.rulesContext = saved.rulesContext;\n context.renderKey = saved.renderKey;\n context.treeRoot = saved.treeRoot;\n if (saved.root !== undefined) {\n context.root = saved.root;\n }\n return rules as this;\n };\n\n // Separate declarations (whose dynamic names might depend on each other)\n // from non-declarations (which depend on declaration VALUES, not names,\n // so retrying during preEval won't help).\n const isDeclarationType = (n: Node) =>\n isNode(n, N.VarDeclaration) || isNode(n, N.Declaration);\n\n const dynamicDeclarations: Node[] = [];\n const otherDynamic: Node[] = [];\n for (const node of dynamicNodes) {\n if (isDeclarationType(node)) {\n dynamicDeclarations.push(node);\n } else {\n otherDynamic.push(node);\n }\n }\n\n // Phase 1: Resolve declarations with dynamic names.\n // Retry because one declaration's name might depend on another's being registered.\n const MAX_DECL_RETRIES = 5;\n let declRetries = 0;\n const unresolvedDecls: Node[] = [...dynamicDeclarations];\n\n const resolveDeclarations = (): MaybePromise<void> => {\n declRetries++;\n if (declRetries > MAX_DECL_RETRIES || unresolvedDecls.length === 0) {\n return;\n }\n const stillUnresolved: Node[] = [];\n let madeProgress = false;\n\n for (let i = 0; i < unresolvedDecls.length; i++) {\n const node = unresolvedDecls[i]!;\n try {\n const result = node.preEval(context);\n\n if (isThenable(result)) {\n const remaining = unresolvedDecls.slice(i + 1);\n return (result as Promise<Node>).then((resolvedNode) => {\n if (handleResolvedNode(resolvedNode, node, stillUnresolved)) {\n madeProgress = true;\n }\n unresolvedDecls.length = 0;\n unresolvedDecls.push(...stillUnresolved, ...remaining);\n if (madeProgress && unresolvedDecls.length > 0) {\n return resolveDeclarations();\n }\n });\n }\n\n if (handleResolvedNode(result as Node, node, stillUnresolved)) {\n madeProgress = true;\n }\n } catch {\n stillUnresolved.push(node);\n }\n }\n\n if (madeProgress && stillUnresolved.length > 0) {\n unresolvedDecls.length = 0;\n unresolvedDecls.push(...stillUnresolved);\n return resolveDeclarations();\n }\n };\n\n // Phase 2: Try non-declarations once. Their interpolated names typically\n // depend on declaration VALUES (e.g. @infix from breakpoint-infix()),\n // which aren't evaluated until the eval phase. Retrying won't help.\n const resolveOtherOnce = (): MaybePromise<void> => {\n for (let i = 0; i < otherDynamic.length; i++) {\n const node = otherDynamic[i]!;\n try {\n const result = node.preEval(context);\n\n if (isThenable(result)) {\n const remaining = otherDynamic.slice(i + 1);\n return (result as Promise<Node>).then((resolvedNode) => {\n handleResolvedNode(resolvedNode, node, []);\n // Continue with remaining nodes\n otherDynamic.length = 0;\n otherDynamic.push(...remaining);\n return resolveOtherOnce();\n });\n }\n\n handleResolvedNode(result as Node, node, []);\n } catch {\n // Can't resolve during preEval — leave in place for eval phase\n }\n }\n };\n\n return pipe(\n () => resolveDeclarations(),\n () => {\n applyResolvedNodes();\n return resolveOtherOnce();\n },\n () => finishResolution()\n );\n }\n\n /**\n * Helper method to continue preEval'ing remaining children after an async preEval.\n */\n private _preEvalRemainingChildren(rules: Rules, context: Context, startIndex: number, saved?: any): MaybePromise<this> {\n const children = rules._getRenderChildren(context);\n for (let i = startIndex; i < children.length; i++) {\n const node = children[i]!;\n\n // Always call preEval to ensure deep traversal and name resolution\n const result = node.preEval(context);\n if (isThenable(result)) {\n // Handle async preEval by returning a promise that resolves after all children\n return result.then((resolvedNode) => {\n // Update the node if preEval returned a different instance\n if (resolvedNode !== node) {\n rules._setChildAt(i, resolvedNode, context, false);\n rules.adopt(resolvedNode, context);\n }\n\n // Register the node after preEval (name resolution) if not already registered\n if (!isNode(node, N.VarDeclaration)) {\n rules.registerNode(resolvedNode, undefined, context);\n }\n\n // Continue with the rest of the children\n return this._preEvalRemainingChildren(rules, context, i + 1, saved);\n });\n }\n\n // Update the node if preEval returned a different instance\n if (result !== node) {\n rules._setChildAt(i, result, context, false);\n rules.adopt(result, context);\n }\n\n // Register the node after preEval (name resolution) if not already registered\n if (!isNode(node, N.VarDeclaration)) {\n rules.registerNode(result, undefined, context);\n }\n }\n\n // Restore context after preEval is complete (for async case)\n if (saved) {\n context.rulesContext = saved.rulesContext;\n context.renderKey = saved.renderKey;\n context.treeRoot = saved.treeRoot;\n // Only restore context.root if saved.root is defined (not the outermost root)\n // If saved.root is undefined, it means we're at the outermost level, so keep context.root as is\n if (saved.root !== undefined) {\n context.root = saved.root;\n }\n }\n return rules as this;\n }\n\n /** Save current context roots to restore later */\n private _snapshotContext(context: Context) {\n return {\n rulesContext: context.rulesContext,\n renderKey: context.renderKey,\n treeContext: context.treeContext,\n treeRoot: context.treeRoot,\n root: context.root,\n extendRootStackLength: context.extendRoots.extendRootStack.length\n } as const;\n }\n\n /** Setup context for evaluating these rules */\n private _setupContextForRules(context: Context, rules: Rules) {\n const treeContext = context.treeContext;\n // Only switch treeContext if the rules have one AND it's different\n // Dynamically created Rules (e.g., mixin parameter wrappers) may not have treeContext\n // and we don't want to lose leakyRules and other settings\n // Check _meta.treeContext (private field) not treeContext (getter that lazily creates)\n const rulesTreeContext = (rules as any)._meta?.treeContext as TreeContext | undefined;\n if (rulesTreeContext && (!treeContext || treeContext !== rulesTreeContext)) {\n context.allRoots.push(rules);\n context.treeContext = rulesTreeContext;\n context.treeRoot = rules;\n }\n // Always set root if not set - needed for extends to work with API-created Rules\n context.root ??= rules;\n context.rulesContext = rules;\n if (rules.renderKey !== CANONICAL) {\n context.renderKey = rules.renderKey;\n }\n }\n\n /** Assign depth-first document order to every Ruleset under the given Rules (single walk, source order). */\n private _assignDocumentOrderDepthFirst(\n rules: Rules,\n map: WeakMap<Ruleset, number>,\n counter: { value: number },\n context?: Context\n ): void {\n const value = rules._getRenderChildren(context);\n if (!isArray(value)) {\n return;\n }\n for (const node of value) {\n if (isNode(node, N.Ruleset)) {\n map.set(node as Ruleset, counter.value);\n counter.value++;\n }\n const innerRules = (node as any).rules;\n if (innerRules && isNode(innerRules, N.Rules)) {\n this._assignDocumentOrderDepthFirst(innerRules as Rules, map, counter, context);\n }\n }\n }\n\n /** Build the evaluation queue partitioned by priority */\n private _buildEvalQueue(rules: Rules, context: Context): EvalQueueMap {\n let evalQueue: EvalQueueMap = new Map();\n for (const item of rules._getRenderChildren(context).entries()) {\n let [idx, rule] = item;\n if (rule.index === undefined) {\n rule.index = idx;\n }\n let priority = NodeTypeToPriority.get(rule.type) ?? Priority.None;\n // Less variable-calls `@foo();` are parsed as Expression(Call(variable-ref)).\n // We *selectively* boost only those calls that \"unlock mixins\" (i.e. calling a variable whose\n // value is a detached ruleset containing mixin definitions). This avoids changing evaluation\n // order for regular detached rulesets like `@ruleset()` used for property blocks.\n if (priority === Priority.None && rules.treeContext?.leakyRules === true && isNode(rule, N.Expression)) {\n const inner = (rule as any).value;\n if (isNode(inner, N.Call) && isNode((inner as any).name, N.Reference)) {\n const ref = (inner as any).name;\n const refType = String(ref?.options?.type ?? '');\n if (refType === 'variable') {\n const raw = ref.key;\n const keyStr = Array.isArray(raw) ? raw.join('') : String(raw?.valueOf?.() ?? raw ?? '');\n // Only if variable exists and its value is a detached ruleset Mixin with nested Mixin definitions.\n const decl = rules.find('declaration', keyStr, 'VarDeclaration', { context }) as any;\n const val = decl?.value;\n const hasNestedMixinDefinitions =\n isNode(val, N.Mixin)\n && isNode((val as any).rules, N.Rules)\n && (val as any).rules._getRenderChildren(context).some((n: any) => n?.type === 'Mixin');\n if (hasNestedMixinDefinitions) {\n priority = Priority.High;\n }\n }\n }\n }\n let queue = evalQueue.get(priority) ?? [];\n queue.push(item as [number, Node]);\n evalQueue.set(priority, queue);\n }\n return evalQueue;\n }\n\n /** Evaluate the built queues in priority order */\n private _evaluateQueue(rules: Rules, evalQueue: EvalQueueMap, context: Context): MaybePromise<boolean> {\n let rulesToHoist = false;\n const scheduledPriority = new WeakMap<Node, Priority>();\n const failuresByPriority = new WeakMap<Node, Map<Priority, number>>();\n\n const priorities: Priority[] = Array.from({ length: Priority.Highest + 1 }).map((_, i) => (Priority.Highest - i) as Priority);\n const runPriority = (p: Priority): MaybePromise<void> => {\n const queue = evalQueue.get(p);\n if (!queue) {\n return;\n }\n const enqueueRetry = (priority: Priority, item: [number, Node], rule: Node): void => {\n const retryQueue = evalQueue.get(priority) ?? [];\n retryQueue.push(item);\n evalQueue.set(priority, retryQueue);\n scheduledPriority.set(rule, priority);\n };\n const countFailure = (rule: Node, priority: Priority): number => {\n const byPriority = failuresByPriority.get(rule) ?? new Map<Priority, number>();\n const nextCount = (byPriority.get(priority) ?? 0) + 1;\n byPriority.set(priority, nextCount);\n failuresByPriority.set(rule, byPriority);\n return nextCount;\n };\n const runSingleEntry = (q: number): MaybePromise<void | undefined> => {\n const [idx, rule] = queue[q]!;\n\n /**\n * Var declarations have late evaluation, so they are skipped.\n * (Meaning: they are not evaluated until they are referenced.)\n */\n if (isNode(rule, N.VarDeclaration)) {\n return;\n }\n\n // Skip stale entries for nodes that were re-queued to a different priority.\n const expectedPriority = scheduledPriority.get(rule);\n if (expectedPriority !== undefined && expectedPriority !== p) {\n return;\n }\n\n const onEvalError = (error: unknown): Node | undefined => {\n // Most node failures are semantic failures and should throw immediately.\n // Retry scheduling is reserved for StyleImport ordering/interpolation cases.\n if (rule.type !== 'StyleImport') {\n throw error;\n }\n // Final pass: no retries remain.\n if (p === Priority.None) {\n throw error;\n }\n\n // Only retry when the import path itself couldn't be resolved\n // (e.g. @import \"@{theme}/file\" where @theme isn't available yet).\n // Path resolution is cheap (no cloning). Content evaluation errors\n // (after cloning the import tree) are never retried — each retry\n // would re-clone the entire tree, causing memory blowup.\n const isPathError = error instanceof Error && (error as any)._isPathResolutionError;\n if (!isPathError) {\n throw error;\n }\n\n // Retry policy:\n // 1) first failure at a priority -> retry once at same priority\n // 2) second+ failure at that priority -> step down one level\n const failures = countFailure(rule, p);\n const nextPriority = failures === 1 ? p : (p - 1) as Priority;\n enqueueRetry(nextPriority, [idx, rule], rule);\n return;\n };\n const tryStepResult = (): MaybePromise<Node | undefined> => {\n try {\n const result = rule.eval(context);\n if (isThenable(result)) {\n return (result as Promise<Node>).catch(onEvalError);\n }\n return result as Node;\n } catch (error) {\n return onEvalError(error);\n }\n };\n const stepResult = pipe(\n tryStepResult,\n (result: Node | undefined) => {\n // Undefined means we re-queued this node for retry.\n if (result === undefined) {\n return;\n }\n scheduledPriority.delete(rule);\n // Apply the result\n if (result !== rule) {\n rules._setChildAt(idx, result, context, false);\n queue[q] = [idx, result];\n // If a StyleImport evaluated to Rules, register them in the parent's _rulesSet\n // so variables from the import can be found by the parent\n // Also register Rules from Call results (mixin calls) in the same way\n if (isNode(result, N.Rules)) {\n // Set the index of the imported Rules to the StyleImport's index\n // so we can compare Rules indices when determining which variable was declared later\n setIndex(result, idx, context);\n rules.adopt(result, context);\n rules.registerNode(result, {\n rulesVisibility: result.options.rulesVisibility,\n readonly: result.options.readonly\n }, context);\n if (result.sourceNode?.type === 'StyleImport') {\n result.getRegistry('declaration')?.indexPendingItems();\n result.getRegistry('mixin')?.indexPendingItems();\n }\n } else {\n // For non-Rules results, adopt them to set up parent chain\n rules.adopt(result, context);\n }\n }\n if (result.hoistToRoot) {\n rulesToHoist = true;\n }\n return;\n }\n );\n // If stepResult is a thenable, propagate any errors\n if (isThenable(stepResult)) {\n return stepResult;\n }\n return;\n };\n const runFromIndex = (q: number): MaybePromise<void> => {\n if (q >= queue.length) {\n return;\n }\n const step = runSingleEntry(q);\n if (isThenable(step)) {\n return (step as Promise<void>).then(() => runFromIndex(q + 1));\n }\n return runFromIndex(q + 1);\n };\n return runFromIndex(0);\n };\n const phaseRun = serialForEach(priorities, runPriority);\n\n if (isThenable(phaseRun)) {\n return (phaseRun as Promise<void>).then(() => {\n return rulesToHoist;\n }).catch((error) => {\n throw error;\n });\n }\n return rulesToHoist;\n }\n\n /**\n * Coalesce assignment-normalized declaration chains in one stage after evaluation.\n * This handles both in-scope merges and merges that span call-produced Rules blocks.\n */\n private _coalesceMergedDeclarations(rules: Rules, context?: Context): void {\n const getDeclValue = (node: Declaration): Node => node.getCurrentValue(context);\n const getDeclImportant = (node: Declaration): Node | undefined => node.getCurrentImportant(context);\n const getDeclName = (node: Declaration): string => {\n const name = node.getCurrentName(context);\n return String(name?.valueOf?.() ?? name);\n };\n const getDeclAssign = (node: Declaration): string => {\n const options = node.options;\n return String(options?.normalizedFromAssign ?? '');\n };\n const setDeclValue = (node: Declaration, value: Node): void => {\n node.setCurrentValue(value, context);\n };\n const setDeclImportant = (node: Declaration, value: Node | undefined): void => {\n node.setCurrentImportant(value as Declaration['important'], context);\n };\n const removeVisibleFlag = (node: Node): void => {\n if (context) {\n node._removeFlag(F_VISIBLE, context);\n return;\n }\n node.removeFlag(F_VISIBLE);\n };\n const isMergedAssign = (assign: unknown): boolean => (\n assign === '+:' || assign === '&,:' || assign === '&_:'\n );\n const cloneMergeValuePart = (value: Node): Node => {\n return context\n ? value.clone(false, undefined, context)\n : value.clone(false);\n };\n const collectAddMergeParts = (value: Node): Node[] => {\n if (isNode(value, N.Nil)) {\n return [];\n }\n if (isNode(value, N.List)) {\n return value.get('value', context).map(part => cloneMergeValuePart(part as Node));\n }\n return [cloneMergeValuePart(value)];\n };\n const rebaseLinearMergedValue = (anchor: Declaration, value: Node, assign: string): Node | undefined => {\n if (assign === '&_:') {\n if (!isNode(value, N.Sequence)) {\n return undefined;\n }\n const parts = value.get('value', context);\n if (\n parts.length < 2\n || !isNode(parts[0]!, N.Reference)\n || parts[0]!.options?.resolution !== 'linear'\n ) {\n return undefined;\n }\n return spaced([\n getDeclValue(anchor),\n ...parts.slice(1).map(part => cloneMergeValuePart(part as Node))\n ]);\n }\n if (!isNode(value, N.List)) {\n return undefined;\n }\n const parts = value.get('value', context);\n if (\n parts.length < 2\n || !isNode(parts[0]!, N.Reference)\n || parts[0]!.options?.resolution !== 'linear'\n ) {\n return undefined;\n }\n return new List([\n getDeclValue(anchor),\n ...parts.slice(1).map(part => cloneMergeValuePart(part as Node))\n ]);\n };\n const appendMergedValue = (anchor: Declaration, value: Node, assign: string): Node => {\n if (assign === '&_:') {\n return isNode(value, N.Sequence)\n ? spaced([getDeclValue(anchor), ...value.get('value', context).map(part => cloneMergeValuePart(part as Node))])\n : spaced([getDeclValue(anchor), cloneMergeValuePart(value)]);\n }\n return isNode(value, N.List)\n ? new List([\n ...collectAddMergeParts(getDeclValue(anchor)),\n ...value.get('value', context).map(part => cloneMergeValuePart(part as Node))\n ])\n : new List([\n ...collectAddMergeParts(getDeclValue(anchor)),\n cloneMergeValuePart(value)\n ]);\n };\n const isDeclarationOnlyRules = (node: Node): node is Rules => (\n isNode(node, N.Rules)\n && node._getRenderChildren(context).length > 0\n && node._getRenderChildren(context).every(child => isNode(child, N.Declaration | N.Comment))\n );\n const composeMergedValue = (decl: Declaration, prior: Declaration, assign: string): void => {\n if (!isNode(decl, N.Declaration) || !isNode(prior, N.Declaration)) {\n return;\n }\n const priorValue = getDeclValue(prior);\n const nextValue = getDeclValue(decl);\n setDeclValue(decl, assign === '&_:'\n ? spaced([priorValue, nextValue])\n : new List([priorValue, nextValue]));\n if (!getDeclImportant(decl) && getDeclImportant(prior)) {\n setDeclImportant(decl, getDeclImportant(prior));\n }\n };\n const normalizeMergedDeclarationValue = (node: Node): void => {\n if (!isNode(node, N.Declaration)) {\n return;\n }\n const current = getDeclValue(node);\n if (!isNode(current, N.List) || current.get('value').length === 0) {\n return;\n }\n const [first, ...rest] = current.get('value');\n const isEmptyPlaceholder = Boolean(\n first\n && (\n isNode(first, N.Nil)\n || (isNode(first, N.List) && first.get('value').length === 0)\n )\n );\n if (!isEmptyPlaceholder) {\n return;\n }\n if (rest.length === 0) {\n setDeclValue(node, new Nil());\n return;\n }\n if (rest.length === 1) {\n setDeclValue(node, rest[0]!);\n return;\n }\n setDeclValue(node, new List(rest));\n };\n\n const lastVisibleByName = new Map<string, Node>();\n const mergedAnchorByName = new Map<string, Node>();\n const stream: Node[] = [];\n\n for (const node of rules._getRenderChildren(context)) {\n if (isNode(node, N.Declaration)) {\n stream.push(node);\n continue;\n }\n if (isDeclarationOnlyRules(node)) {\n for (const child of node._getRenderChildren(context)) {\n if (isNode(child, N.Declaration)) {\n stream.push(child);\n }\n }\n }\n }\n\n for (const node of stream) {\n if (!isNode(node, N.Declaration)) {\n continue;\n }\n const name = getDeclName(node);\n const assign = getDeclAssign(node);\n const merged = isMergedAssign(assign);\n\n if (!merged) {\n mergedAnchorByName.delete(name);\n if (isVisibleInContext(node, context)) {\n lastVisibleByName.set(name, node);\n }\n continue;\n }\n normalizeMergedDeclarationValue(node);\n\n const prior = lastVisibleByName.get(name);\n if (\n prior\n && prior !== node\n && (\n context\n ? getCurrentParentNode(prior, context) !== getCurrentParentNode(node, context)\n : prior.parent !== node.parent\n )\n ) {\n composeMergedValue(node, prior, assign);\n }\n\n const existingAnchor = mergedAnchorByName.get(name);\n if (existingAnchor && existingAnchor !== node && isNode(existingAnchor, N.Declaration)) {\n // @todo — copy(true) was used here for comment suppression (stripping\n // pre/post comments from merged values). Need a position-aware\n // alternative: either a serialization-time comment suppression flag\n // or field patches on pre/post.\n const currentValue = getDeclValue(node);\n const nextAnchorValue = assign === '+:'\n ? new List([\n ...collectAddMergeParts(getDeclValue(existingAnchor)),\n ...collectAddMergeParts(currentValue)\n ])\n : rebaseLinearMergedValue(existingAnchor, currentValue, assign)\n ?? appendMergedValue(existingAnchor, currentValue, assign);\n setDeclValue(\n existingAnchor,\n nextAnchorValue\n );\n if (!getDeclImportant(existingAnchor) && getDeclImportant(node)) {\n setDeclImportant(existingAnchor, getDeclImportant(node));\n }\n removeVisibleFlag(node);\n if (isVisibleInContext(existingAnchor, context)) {\n lastVisibleByName.set(name, existingAnchor);\n }\n continue;\n }\n\n mergedAnchorByName.set(name, node);\n if (isVisibleInContext(node, context)) {\n lastVisibleByName.set(name, node);\n }\n }\n }\n\n /**\n * Normalize call-produced declaration-only Rules ordering so declarations\n * emitted from late-evaluated calls (e.g. each/$for) appear before nested\n * rulesets/at-rules in the same parent Rules container.\n *\n * This runs after queue evaluation to avoid mutating rule indices mid-eval.\n */\n private _normalizeCallDeclarationRulesOrder(rules: Rules, context?: Context): void {\n const children = rules._getRenderChildren(context);\n const firstNestedIdx = children.findIndex(n => isNode(n, N.Ruleset | N.AtRule));\n if (firstNestedIdx < 0) {\n return;\n }\n const beforeNested = children.slice(0, firstNestedIdx);\n const afterNested = children.slice(firstNestedIdx);\n const shouldMove = (n: Node) => {\n const sourceParent = context\n ? getSourceParent(n, context)\n : n.sourceParent;\n if (\n !isNode(n, N.Rules)\n || !isNode(sourceParent, N.Call)\n || n._getRenderChildren(context).length === 0\n || !n._getRenderChildren(context).every(child => isNode(child, N.Declaration | N.Comment))\n ) {\n return false;\n }\n const sourceName = (sourceParent as any).name;\n // Keep mixin-call declaration blocks in source order relative to nested rulesets.\n if (\n isNode(sourceName, N.Reference)\n && (sourceName.options?.type === 'mixin'\n || sourceName.options?.type === 'mixin-ruleset'\n || sourceName.options?.type === 'ruleset')\n ) {\n return false;\n }\n return true;\n };\n const moved = afterNested.filter(shouldMove);\n if (moved.length === 0) {\n return;\n }\n const remainder = afterNested.filter(n => !shouldMove(n));\n rules._setChildren([...beforeNested, ...moved, ...remainder], context, false);\n }\n\n private _evaluateQueuedTopImports(context: Context): MaybePromise<void> {\n const queued = context.topImports;\n if (!queued?.length) {\n return;\n }\n\n const evaluated: Node[] = [];\n const evaluateOne = (importRule: Node): MaybePromise<void> => {\n if (!isNode(importRule, N.AtRule)) {\n evaluated.push(importRule);\n return;\n }\n\n const evaldImport = importRule.clone(false, undefined, context);\n evaldImport.preEvaluated = true;\n const out = evaldImport.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Node | Nil>).then((result) => {\n if (!(result instanceof Nil)) {\n evaluated.push(result);\n }\n });\n }\n if (!(out instanceof Nil)) {\n evaluated.push(out as Node);\n }\n };\n\n const out = serialForEach(queued, evaluateOne);\n if (isThenable(out)) {\n return (out as Promise<void>).then(() => {\n context.topImports = evaluated;\n });\n }\n context.topImports = evaluated;\n }\n\n /**\n * After preEval: ensure root on extend stack, build eval queue, run evaluation.\n * Used by evalNode so that when eval() is called without preEval (e.g. jess compile()),\n * we still have all rulesets registered and root set for extend lookups.\n */\n private _afterPreEvalStep(rules: Rules, context: Context): MaybePromise<{ rules: Rules; rulesToHoist: boolean }> {\n if (\n rules === context.root\n && rules.renderKey === CANONICAL\n && !rules.hasFlag(F_STATIC)\n && (context.renderKey === undefined || context.renderKey === CANONICAL)\n && getCurrentParentNode(rules, context) === undefined\n ) {\n const evalRoot = rules.createShallowBodyWrapper(context, EVAL);\n context.root = evalRoot;\n context.rulesContext = evalRoot;\n context.renderKey = evalRoot.renderKey;\n rules = evalRoot;\n }\n\n const isMainRoot = rules === context.root;\n if (isMainRoot && context.extendRoots.extendRootStack.length === 0) {\n if (!context.extendRoots.root) {\n context.extendRoots.registerRoot(rules);\n }\n context.extendRoots.pushExtendRoot(rules);\n }\n if (isEvaluated(rules, context)) {\n return { rules, rulesToHoist: false };\n }\n if (rules === context.root) {\n const map = new WeakMap<Ruleset, number>();\n context.documentOrderByRuleset = map;\n this._assignDocumentOrderDepthFirst(rules, map, { value: 0 }, context);\n }\n const evalQueue = this._buildEvalQueue(rules, context);\n const maybeHoist = this._evaluateQueue(rules, evalQueue, context);\n if (isThenable(maybeHoist)) {\n return (maybeHoist as Promise<boolean>).then((rulesToHoist) => {\n const finalize = () => {\n this._normalizeCallDeclarationRulesOrder(rules, context);\n this._coalesceMergedDeclarations(rules, context);\n return {\n rules,\n rulesToHoist\n };\n };\n if (rules === context.root && context.topImports?.length) {\n const maybeEvalTopImports = this._evaluateQueuedTopImports(context);\n if (isThenable(maybeEvalTopImports)) {\n return (maybeEvalTopImports as Promise<void>).then(finalize);\n }\n }\n return finalize();\n });\n }\n if (rules === context.root && context.topImports?.length) {\n const maybeEvalTopImports = this._evaluateQueuedTopImports(context);\n if (isThenable(maybeEvalTopImports)) {\n return (maybeEvalTopImports as Promise<void>).then(() => {\n this._normalizeCallDeclarationRulesOrder(rules, context);\n this._coalesceMergedDeclarations(rules, context);\n return { rules, rulesToHoist: maybeHoist as boolean };\n });\n }\n }\n this._normalizeCallDeclarationRulesOrder(rules, context);\n this._coalesceMergedDeclarations(rules, context);\n return { rules, rulesToHoist: maybeHoist as boolean };\n }\n\n override evalNode(context: Context): MaybePromise<this> {\n const saved = this._snapshotContext(context);\n context.rulesEvalStack.push(this.sourceNode as Rules);\n const restoreContextOnError = () => {\n context.rulesContext = saved.rulesContext;\n context.renderKey = saved.renderKey;\n if (saved.treeRoot !== undefined) {\n context.treeRoot = saved.treeRoot;\n }\n if (saved.root !== undefined) {\n context.root = saved.root;\n }\n const currentLength = context.extendRoots.extendRootStack.length;\n if (saved.extendRootStackLength !== undefined && currentLength > saved.extendRootStackLength) {\n while (context.extendRoots.extendRootStack.length > saved.extendRootStackLength) {\n context.extendRoots.popExtendRoot();\n }\n }\n if (context.rulesEvalStack[context.rulesEvalStack.length - 1] === (this.sourceNode as Rules)) {\n context.rulesEvalStack.pop();\n }\n context.depth--;\n };\n let pipeResult: MaybePromise<this>;\n try {\n pipeResult = pipe(\n () => {\n this._setupContextForRules(context, this);\n // Run preEval first if not yet run (e.g. when jess compile() calls eval() without preEval).\n // preEval registers the root and all nested rulesets so extend lookups find targets in child roots (e.g. .ma inside @media).\n const runPreEvalIfNeeded = (rules: Rules): MaybePromise<Rules> => {\n if (rules.preEvaluated) {\n return rules;\n }\n const result = rules.preEval(context);\n return isThenable(result) ? (result as Promise<Rules>) : result;\n };\n const rulesAfterPreEval = runPreEvalIfNeeded(this);\n const afterPreEval = (rules: Rules) => {\n // When we're the outermost Rules, use the tree we're evaling as root (may differ from context.root set in getTree, or be preEval's clone).\n if (context.rulesEvalStack.length === 1) {\n context.root = rules;\n }\n return this._afterPreEvalStep(rules, context);\n };\n if (isThenable(rulesAfterPreEval)) {\n return (rulesAfterPreEval as Promise<Rules>).then(afterPreEval);\n }\n return afterPreEval(rulesAfterPreEval as Rules);\n },\n ({ rules }: { rules: Rules; rulesToHoist: boolean }) => {\n // Note: Rulesets from imported Rules are already registered to their own treeRoot\n // during preEval when the imported Rules node is evaluated. The extend search\n // loops through allRoots, so it should find them. The _searchRulesChildrenForRulesets\n // method in RulesetRegistry also searches imported Rules' registries.\n\n // After all evaluation stages, check if any variables in the current Rules\n // shadow readonly variables from imported Rules (compose type) at the same level\n // Only check direct children of the Rules node, not nested variables (e.g., inside rulesets)\n if (rules.rulesSet.length > 0) {\n for (const entry of rules.rulesSet) {\n if (entry.readonly) {\n const importedVars = Registries\n .getDirectDeclarationsByKey(entry.node, undefined, context)\n .filter((decl): decl is VarDeclaration => isNode(decl, N.VarDeclaration));\n for (const decl of importedVars) {\n const key = decl.get('name').toString();\n const currentDeclarations = Registries.getDirectDeclarationsByKey(rules, key, context);\n for (const currentDecl of currentDeclarations) {\n if (isNode(currentDecl, N.VarDeclaration) && !currentDecl.options?.setDefined) {\n // Only throw if the variable is a direct child of the Rules node (same level)\n // Nested variables (e.g., inside rulesets) are allowed to shadow\n if (getCurrentParentNode(currentDecl, context) === rules) {\n throw new ReferenceError(`\"${key}\" is readonly`);\n }\n }\n }\n }\n }\n }\n }\n\n // Check if we're at the outermost level BEFORE restoring context\n // Only process extends at the TRUE outermost root (context.root)\n // This ensures extends are processed AFTER all evaluation completes,\n // including imports and nested Rules\n const isOutermost = rules === context.root;\n\n if (isOutermost) {\n processExtends(context);\n }\n /** Restore contexts */\n context.rulesContext = saved.rulesContext;\n context.renderKey = saved.renderKey;\n // Only restore context.treeRoot if saved.treeRoot is defined and we're not at the outermost level\n // If saved.treeRoot is undefined, it means we're at the outermost level, so keep context.treeRoot as is\n // This ensures extends evaluated during selector evaluation can still access the correct treeRoot\n if (saved.treeRoot !== undefined && !isOutermost) {\n context.treeRoot = saved.treeRoot;\n }\n // Only restore context.root if we're not at the outermost level (where it was originally set)\n // If saved.root is undefined, it means we're at the outermost level, so keep context.root as is\n if (saved.root !== undefined && !isOutermost) {\n context.root = saved.root;\n }\n // Restore extend root stack to its original length (if we're not the main root)\n // The main root manages its own push/pop, but nested Rules should restore the stack\n if (!isOutermost && saved.extendRootStackLength !== undefined) {\n const currentLength = context.extendRoots.extendRootStack.length;\n if (currentLength > saved.extendRootStackLength) {\n // Pop any extend roots that were pushed during this Rules evaluation\n while (context.extendRoots.extendRootStack.length > saved.extendRootStackLength) {\n context.extendRoots.popExtendRoot();\n }\n }\n }\n // Pop extend root if we pushed it (check if this is still the root)\n if (rules === context.root) {\n context.extendRoots.popExtendRoot();\n }\n context.rulesEvalStack.pop();\n context.depth--;\n return rules;\n }\n ) as MaybePromise<this>;\n } catch (error) {\n restoreContextOnError();\n throw error;\n }\n if (isThenable(pipeResult)) {\n return (pipeResult as Promise<this>).catch((error) => {\n restoreContextOnError();\n throw error;\n });\n }\n return pipeResult as MaybePromise<this>;\n }\n}\n\nexport const rules = defineType(Rules, 'Rules');\n\ntype EvalQueueMap = Map<Priority, Array<[number, Node]>>;\n\n/**\n * @todo - Will need lots of massaging, to resolve things like\n * mixins which rely on variables which have interpolated names,\n * and variables with interpolated names that rely on mixins.\n *\n * @note - Registration of declaration names and mixins / selectors\n * should have already happened in pre-eval.\n */\nconst NodeTypeToPriority = new Map([\n /** First, resolve imports */\n ['StyleImport', Priority.Highest],\n /** Then, resolve calls */\n ['Call', Priority.High],\n /** Then, resolve declarations */\n ['VarDeclaration', Priority.Medium],\n ['Declaration', Priority.Medium],\n /** Then... */\n ['Mixin', Priority.Low],\n ['Ruleset', Priority.Low],\n /** Extend should evaluate at the same priority as Ruleset to ensure it evaluates before nested rulesets */\n ['Extend', Priority.Low],\n /** AtRule (e.g., @media) should evaluate at the same priority as Ruleset to preserve source order */\n ['AtRule', Priority.Low]\n /** Then, everything else? */\n]);\n\n// const TypeToNodeType = new Map([\n// ['Mixin', NodeType.MIXIN],\n// ['Ruleset', NodeType.RULESET],\n// ['Declaration', NodeType.PROPERTY],\n// ['VarDeclaration', NodeType.VARIABLE],\n// ['Rules', NodeType.RULES]\n// ])\n\n// export const enum NodeTypeIndex {\n// NONE = 0b000000,\n// MIXIN = 0b000001,\n// RULESET = 0b000010,\n// MIXIN_OR_RULESET = 0b000011,\n// PROPERTY = 0b000100,\n// VARIABLE = 0b001000,\n// VAR_OR_PROP = 0b001100,\n// /**\n// * Variables and mixins can leak\n// */\n// LEAKY_RULES = 0b010000,\n// /** @note - Properties and rulesets are always visible. */\n// PRIVATE_RULES = 0b100000,\n// RULES = 0b110000\n// }\n\n// type IndexKey = `${NodeType}${string}`\n\ninterface RulesEntry {\n node: Rules;\n rulesVisibility?: RulesOptions['rulesVisibility'];\n /**\n * These are from use, from, and import statements. Can't be assigned with $$\n * (verify that this is not possible with SCSS).\n */\n readonly?: boolean;\n}\n\n/**\n * Right now, the only nodes that can be registered to the scope for lookups\n */\n// type ScopeNodes = Declaration | VarDeclaration | Mixin | Ruleset | Rules\nexport type MixinEntry = Mixin | Ruleset;\n\n/**\n * Returns a plain JS function for calling a set of mixins\n *\n * This is in the same file as Rules to avoid circular dependencies.\n *\n * @note this will be called as a result after a mixin find is executed.\n */\nexport function getFunctionFromMixins(mixins: MixinEntry | MixinEntry[]) {\n let mixinArr = isArray(mixins) ? mixins : [mixins];\n /**\n * This will be called by a mixin call or by JavaScript\n *\n * @note - Mixins resolve to async functions because they\n * can contain dynamic imports.\n */\n async function returnFunc(this: unknown, ...args: any[]): Promise<Rules | Record<string, string>>;\n async function returnFunc(this: Context, ...args: any[]): Promise<Rules>;\n async function returnFunc(this: Context | unknown, ...args: any[]) {\n // When called via callWithContext, 'this' is functionThis, not Context\n // We need to extract the context from functionThis or use a fallback\n let thisContext: Context;\n\n if (this instanceof Context) {\n thisContext = this;\n } else if (this && typeof this === 'object' && 'context' in this) {\n // This is functionThis from callWithContext\n thisContext = (this as any).context;\n } else {\n thisContext = new Context();\n }\n let caller = thisContext.caller;\n const callerSourceNode = (caller as any)?.name instanceof Node\n ? (caller as any).name\n : caller;\n let sourceParent = callerSourceNode\n ? getSourceParent(callerSourceNode, thisContext)\n : undefined;\n if (sourceParent && isNode(sourceParent, N.Reference | N.Call)) {\n sourceParent = caller;\n }\n sourceParent ??= caller;\n const invocationParent = thisContext.rulesContext\n ?? (caller ? getParent(caller, thisContext) : undefined);\n\n const nodeArgs = await evaluateMixinArgs(args, caller, thisContext);\n const mixinCandidates = await matchMixinCandidates(mixinArr, nodeArgs, caller, sourceParent, thisContext);\n const { evalCandidates, hasDefault } = filterAndSortMixinEvalCandidates(mixinCandidates, thisContext);\n\n const outputRules: Rules[] = [];\n const candidateOutputOpts: EvaluateCandidateOutputOptions = {\n sourceParent,\n invocationParent,\n restrictMixinOutputLookup: thisContext.leakyRules !== true,\n outputRules,\n getCandidateParent: node => getCandidateParent(node, thisContext)\n };\n\n const output = await dispatchMixinEvalCandidates({\n evalCandidates,\n hasDefault,\n nodeArgs,\n sourceParent,\n invocationParent,\n caller,\n restrictMixinOutputLookup: candidateOutputOpts.restrictMixinOutputLookup,\n outputRules,\n getCandidateParent: candidateOutputOpts.getCandidateParent,\n evaluateCandidateOutput: (candidate, rules, outerRules, params) =>\n evaluateCandidateOutput(candidate, rules, outerRules, params, thisContext, candidateOutputOpts)\n }, thisContext);\n\n return finalizeMixinInvocationReturn(output, this instanceof Context ? this : thisContext);\n }\n\n return returnFunc;\n}\n\n/**\n * Direct mixin invocation — calls dispatch primitives without the\n * getFunctionFromMixins → callWithContext → returnFunc indirection.\n *\n * The result is already fully evaluated (each candidate's body was\n * evaluated before being assembled into the return Rules). Callers must NOT\n * re-evaluate the result.\n */\nexport async function evalMixinDirect(\n context: Context,\n mixins: MixinEntry | MixinEntry[],\n args: List<Node> | undefined\n): Promise<Rules | Nil> {\n const mixinArr = isArray(mixins) ? mixins : [mixins];\n const caller = context.caller;\n const callerSourceNode = caller && isNode(caller, N.Call) && caller.get('name') instanceof Node\n ? caller.get('name')\n : caller;\n let sourceParent = callerSourceNode\n ? getSourceParent(callerSourceNode as Node, context)\n : undefined;\n if (sourceParent && isNode(sourceParent, N.Reference | N.Call)) {\n sourceParent = caller;\n }\n sourceParent ??= caller;\n const invocationParent = context.rulesContext\n ?? (caller ? getParent(caller as Node, context) : undefined);\n\n const nodeArgs = await evaluateMixinArgs(\n args ? [...args.get('value', context)] : [],\n caller,\n context\n );\n const mixinCandidates = await matchMixinCandidates(\n mixinArr, nodeArgs, caller, sourceParent, context\n );\n const { evalCandidates, hasDefault } = filterAndSortMixinEvalCandidates(\n mixinCandidates, context\n );\n\n const outputRules: Rules[] = [];\n if (process.env.JESS_DEBUG_LOCK === 'throw-direct') {\n const callerName = caller && isNode(caller, N.Call) && (caller as Call).name instanceof Node\n ? (caller as Call).name\n : undefined;\n const callerKey = isNode(callerName, N.Reference)\n ? String(callerName.key?.valueOf?.() ?? '')\n : '';\n if (callerKey.includes('inner-locked-mixin')) {\n throw new Error(`[lock-direct] ${JSON.stringify({\n callerKey,\n mixinCount: mixinArr.length,\n matchedCount: mixinCandidates.length,\n evalCandidateCount: evalCandidates.length,\n hasDefault,\n sourceParent: sourceParent?.type,\n invocationParent: invocationParent?.type,\n matchNames: mixinCandidates.map(candidate => String((candidate as Mixin).get?.('name')?.valueOf?.() ?? candidate.type))\n })}`);\n }\n }\n const candidateOutputOpts: EvaluateCandidateOutputOptions = {\n sourceParent,\n invocationParent,\n restrictMixinOutputLookup: context.leakyRules !== true,\n outputRules,\n getCandidateParent: node => getCandidateParent(node, context)\n };\n\n const output = await dispatchMixinEvalCandidates({\n evalCandidates,\n hasDefault,\n nodeArgs,\n sourceParent,\n invocationParent,\n caller,\n restrictMixinOutputLookup: candidateOutputOpts.restrictMixinOutputLookup,\n outputRules,\n getCandidateParent: candidateOutputOpts.getCandidateParent,\n evaluateCandidateOutput: (candidate, rules, outerRules, params) =>\n evaluateCandidateOutput(candidate, rules, outerRules, params, context, candidateOutputOpts)\n }, context);\n\n return finalizeMixinInvocationReturn(output, context) as Rules | Nil;\n}\n","import { defineType, type NodeOptions, type OptionalLocation, type TreeContext, F_AMPERSAND, F_IMPLICIT_AMPERSAND, type Node } from './node.js';\nimport { Nil } from './nil.js';\nimport type { Context } from '../context.js';\nimport { SimpleSelector } from './selector-simple.js';\nimport { PseudoSelector } from './selector-pseudo.js';\nimport { SelectorList } from './selector-list.js';\nimport { BasicSelector } from './selector-basic.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { type Selector } from './selector.js';\nimport { atIndex } from './util/collections.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { AMPERSAND_TEMPLATE_CONTENTS_REGEX } from './util/ampersand-template.js';\nimport { wrapParentSelectorForNestedContext } from './util/selector-utils.js';\n\nconst ampersandTemplateInterpolationRegex = /[$@]\\{[^}]+\\}/g;\nconst ampersandTemplateRegex = new RegExp(`^(?:${AMPERSAND_TEMPLATE_CONTENTS_REGEX.source})$`);\n\nfunction isSelectorNode(value: unknown): value is Selector {\n return isNode(value, N.Selector);\n}\n\nfunction isSelectorListNode(value: unknown): value is SelectorList {\n return isNode(value, N.SelectorList);\n}\n\nfunction isNilNode(value: unknown): value is Nil {\n return isNode(value, N.Nil);\n}\n\nexport type AmpersandValue = {\n /**\n * The only value that may exist is an anonymous value\n * This is represented as &(). Any &() will signal\n * a forced output (as well as an adjacent ident starting with\n * a dash or numbers)\n *\n * @example\n .rule {\n &-foo {\n color: red;\n }\n }\n // output:\n .rule-foo {\n color: red;\n }\n\n .rule {\n &(-foo) {\n color: red;\n }\n }\n // output:\n .rule-foo {\n color: red;\n }\n\n .rule {\n &.foo {\n color: red;\n }\n }\n // output:\n .rule {\n &.foo {\n color: red;\n }\n }\n\n .rule {\n &().foo {\n color: red;\n }\n }\n // output:\n .rule.foo {\n color: red;\n }\n\n *\n * `undefined` => plain `&`\n * `''` => `&()` root-hoist while still rendering the parent\n * `string` => `&(template)` / `&-suffix`\n * `Nil` => `&(nil)` and suppress the parent entirely\n *\n * A template without an `&` is shorthand for replacing the parent selector\n * at the same location. So `template: '-1'` means the `&-1` form.\n */\n template?: string | Nil;\n /** @deprecated Use `template` */\n appendValue?: string | Nil;\n\n /**\n * When set (e.g. by ruleset preEval), returns the current parent ruleset's selector (\"pointer\").\n * Prefer this over value.selector so extend sees the parent after it has been mutated (e.g. by extend).\n */\n selectorContainer?: {\n selector?: Selector | Nil | undefined;\n getEffectiveSelector?: (collapseNesting?: boolean, context?: Context) => Selector | Nil | undefined;\n };\n};\n\ntype SelectorContainer = NonNullable<AmpersandValue['selectorContainer']>;\n\nfunction getSelectorFromContainer(\n selectorContainer: SelectorContainer | undefined,\n context?: Context\n): Selector | Nil | undefined {\n if (!selectorContainer) {\n return undefined;\n }\n if (typeof selectorContainer.getEffectiveSelector === 'function') {\n return selectorContainer.getEffectiveSelector(false, context);\n }\n return selectorContainer.selector;\n}\n\nfunction cloneStoredSelector(\n storedSelector: Selector | Nil | undefined,\n deep?: boolean\n): Selector | Nil | undefined {\n if (!isSelectorNode(storedSelector)) {\n return storedSelector;\n }\n const storedClone = storedSelector.clone(deep);\n const sourceLibrary = storedSelector.keySetLibrary;\n if (sourceLibrary && isSelectorNode(storedClone)) {\n storedClone.keySetLibrary = sourceLibrary;\n for (const child of storedClone.children(true)) {\n if (isSelectorNode(child)) {\n child.keySetLibrary = sourceLibrary;\n }\n }\n }\n return storedClone;\n}\n\n/**\n * The '&' selector element\n */\nexport interface Ampersand {\n type: 'Ampersand';\n shortType: 'amp';\n}\nexport class Ampersand extends SimpleSelector<{ template?: string | Nil }> {\n static override childKeys = null as null;\n\n template: string | Nil | undefined;\n\n private _storedSelector: Selector | Nil | undefined;\n private _selectorContainer: SelectorContainer | undefined;\n\n private _getSelector(context?: Context): Selector | Nil | undefined {\n if (!context) {\n return this._storedSelector;\n }\n return getSelectorFromContainer(this._selectorContainer, context) ?? this._storedSelector;\n }\n\n constructor(\n value?: AmpersandValue | string | Nil,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n let finalTemplate: string | Nil | undefined;\n if (typeof value === 'string' || value instanceof Nil) {\n finalTemplate = value;\n super({ template: value }, options, location, treeContext);\n } else {\n finalTemplate = value?.template ?? value?.appendValue;\n super(value ?? {}, options, location, treeContext);\n const selectorContainer = value?.selectorContainer;\n if (selectorContainer) {\n this._selectorContainer = selectorContainer;\n const storedSelector = getSelectorFromContainer(selectorContainer);\n this._storedSelector = cloneStoredSelector(storedSelector, true);\n }\n }\n this.template = finalTemplate;\n if (finalTemplate instanceof Nil) {\n this.adopt(finalTemplate);\n }\n\n // Set the F_AMPERSAND flag so it bubbles up to parent selectors\n this.addFlag(F_AMPERSAND);\n }\n\n isPlainAmpersand(): boolean {\n return this.template === undefined;\n }\n\n omitsParent(): boolean {\n return isNilNode(this.template);\n }\n\n get appendValue(): string | Nil | undefined {\n return this.template;\n }\n\n set appendValue(value: string | Nil | undefined) {\n this.template = value;\n if (value instanceof Nil) {\n this.adopt(value);\n }\n }\n\n override computeKeySets(): void {\n let library = this.keySetLibrary!;\n const stored = this._storedSelector;\n const current = this._getSelector();\n let keySet = this._keySet;\n /** Ampersands don't participate to the visible key set */\n if (!this._visibleKeySet) {\n this._visibleKeySet = library.getBitset();\n }\n if (!this._requiredKeySet) {\n this._requiredKeySet = library.getBitset();\n }\n if (!current || isNode(current, N.Nil)) {\n if (!keySet) {\n this._keySet = library.getBitset();\n }\n return;\n }\n if (!keySet || stored !== current) {\n this._keySet = current.keySet;\n }\n }\n\n override getKeySet(context?: Context) {\n if (!context) {\n return this.keySet;\n }\n\n const current = this._getSelector(context);\n if (!current || isNode(current, N.Nil)) {\n const library = this.keySetLibrary;\n if (!library) {\n throw new Error('Selector keySet library not found');\n }\n return library.getBitset();\n }\n\n return current.getKeySet(context);\n }\n\n /**\n * Returns the current selector from the selector container (live when container is ruleset value).\n * Used by extend, serialization, and matching so nested rules see the parent after extend.\n */\n getResolvedSelector(context?: Context): Selector | Nil | undefined {\n const selector = this._getSelector(context);\n if (isSelectorNode(selector) && this.hasFlag(F_IMPLICIT_AMPERSAND)) {\n return wrapParentSelectorForNestedContext(selector);\n }\n return selector;\n }\n\n override valueOf(context?: Context) {\n const selector = this._getSelector(context);\n if (selector) {\n return selector.valueOf();\n }\n return '&';\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const { template } = this;\n if (template !== undefined) {\n w.add('&(');\n if (isNilNode(template)) {\n w.add('nil', this);\n } else if (typeof template === 'string' && template) {\n w.add(template, this);\n }\n w.add(')');\n } else {\n w.add('&', this);\n }\n return w.getSince(mark);\n }\n\n /**\n * Split a string on commas that aren't inside brackets, parens, or quotes.\n */\n private static splitTopLevelCommas(str: string): string[] {\n const items: string[] = [];\n let depth = 0;\n let inQuote: string | null = null;\n let start = 0;\n for (let i = 0; i < str.length; i++) {\n const ch = str[i]!;\n if (inQuote) {\n if (ch === inQuote && str[i - 1] !== '\\\\') {\n inQuote = null;\n }\n } else if (ch === '\\'' || ch === String.fromCharCode(34)) {\n inQuote = ch;\n } else if (ch === '(' || ch === '[') {\n depth++;\n } else if (ch === ')' || ch === ']') {\n depth--;\n } else if (ch === ',' && depth === 0) {\n const item = str.slice(start, i).trim();\n if (item) {\n items.push(item);\n }\n start = i + 1;\n }\n }\n const last = str.slice(start).trim();\n if (last) {\n items.push(last);\n }\n return items;\n }\n\n /** Hmm this should never return Extend */\n override evalNode(context: Context): Selector | Nil {\n this.keySetLibrary = context.selectorBits;\n const template = this.template;\n const hoistToRoot = this.hoistToRoot;\n const selectorContainer = this._selectorContainer;\n const storedSelector = getSelectorFromContainer(selectorContainer, context);\n // Check if template is defined (including empty string), or if hoistToRoot/collapseNesting is set\n if (template !== undefined || hoistToRoot || context.opts.collapseNesting) {\n // Use the stored selector if available, otherwise fall back to frame selector\n let frame = atIndex(context.rulesetFrames, -1);\n let selector = storedSelector ?? frame?.getEffectiveSelector?.(false, context) ?? frame?.get('selector');\n if (isNilNode(template)) {\n const result = new Nil(undefined, undefined, undefined, this.treeContext);\n result.hoistToRoot = true;\n return result;\n }\n if (!selector) {\n return new Nil();\n }\n // Collapse/hoist/template processing normalizes spacing and may rewrite\n // selector contents, so never mutate the live parent selector in place.\n if (isSelectorNode(selector)) {\n selector = selector.copy(true);\n }\n /** Remove any surrounding whitespace */\n selector.pre = undefined;\n selector.post = undefined;\n\n if (typeof template === 'string' && template && !isNode(selector, N.Nil)) {\n const normalizedTemplate = template.replace(ampersandTemplateInterpolationRegex, 'x');\n const isBareIdentifierTemplate = /^[A-Za-z_\\u0080-\\uffff][\\w\\u0080-\\uffff-]*$/u.test(normalizedTemplate);\n if (\n normalizedTemplate === 'nil'\n || (!ampersandTemplateRegex.test(normalizedTemplate) && !isBareIdentifierTemplate)\n ) {\n throw new SyntaxError(`Invalid ampersand template \"${template}\"`);\n }\n const isTemplateMerge = template.includes('&');\n if (isTemplateMerge) {\n const isIdentJoinChar = (char: string | undefined): boolean => {\n return !!char && /[a-zA-Z0-9_-]/.test(char);\n };\n const assertValidTemplateJoin = (template: string, replacement: string): void => {\n if (!replacement) {\n return;\n }\n let searchFrom = 0;\n while (true) {\n const idx = template.indexOf('&', searchFrom);\n if (idx === -1) {\n break;\n }\n const before = idx > 0 ? template[idx - 1] : undefined;\n const after = idx < template.length - 1 ? template[idx + 1] : undefined;\n const first = replacement[0];\n const last = replacement[replacement.length - 1];\n const invalidHeadJoin = (first === '.' || first === '#') && isIdentJoinChar(before);\n const invalidTailJoin = (last === '.' || last === '#') && isIdentJoinChar(after);\n if (invalidHeadJoin || invalidTailJoin) {\n throw new SyntaxError(`Invalid ampersand merge template \"${template}\" with parent selector \"${replacement}\"`);\n }\n searchFrom = idx + 1;\n }\n };\n const mergeTemplate = (baseSelector: Selector): Selector => {\n const baseSelectors: Selector[] = [];\n if (\n isNode(baseSelector, N.PseudoSelector)\n && baseSelector.get('name') === ':is'\n && isSelectorListNode(baseSelector.get('arg'))\n ) {\n for (const item of baseSelector.get('arg').get('value')) {\n if (isSelectorNode(item)) {\n baseSelectors.push(item);\n }\n }\n } else if (isSelectorListNode(baseSelector)) {\n for (const item of baseSelector.get('value')) {\n if (isSelectorNode(item)) {\n baseSelectors.push(item);\n }\n }\n } else {\n // Handle raw comma-separated strings (e.g. from ~'apple, satsuma, banana, pear')\n // by splitting into individual items so the template distributes across all of them.\n const selectorStr = baseSelector.toTrimmedString();\n if (selectorStr.includes(',')) {\n const items = Ampersand.splitTopLevelCommas(selectorStr);\n for (const item of items) {\n baseSelectors.push(new BasicSelector(item).inherit(baseSelector));\n }\n } else {\n baseSelectors.push(baseSelector);\n }\n }\n const merged = baseSelectors.map((item) => {\n const value = item.toTrimmedString();\n assertValidTemplateJoin(template, value);\n return new BasicSelector(template.split('&').join(value)).inherit(baseSelector);\n });\n if (merged.length === 1) {\n return merged[0]!;\n }\n return new SelectorList(merged).inherit(baseSelector);\n };\n if (isSelectorListNode(selector)) {\n const mergedItems: Selector[] = [];\n for (const item of selector.get('value')) {\n if (!isSelectorNode(item)) {\n continue;\n }\n const merged = mergeTemplate(item);\n if (isSelectorListNode(merged)) {\n for (const nestedItem of merged.get('value')) {\n if (isSelectorNode(nestedItem)) {\n mergedItems.push(nestedItem);\n }\n }\n } else {\n mergedItems.push(merged);\n }\n }\n selector = new SelectorList(mergedItems).inherit(selector);\n } else {\n selector = mergeTemplate(selector);\n }\n } else {\n let doAppendValue = (n: Selector) => {\n let appended = false;\n for (let s of n.nodes(true)) {\n /** Find the last simple selector and attempt to append */\n if (isNode(s, N.SimpleSelector)) {\n if ('value' in s && typeof s.value === 'string') {\n s.setData(s.value + template);\n appended = true;\n break;\n }\n throw new SyntaxError(`Cannot append \"${template}\" to this type of selector`);\n }\n }\n if (!appended) {\n throw new SyntaxError(`Cannot append \"${template}\" to this type of selector`);\n }\n };\n\n if (isSelectorListNode(selector)) {\n selector.get('value').forEach(doAppendValue);\n } else {\n doAppendValue(selector);\n }\n }\n }\n\n let result: Selector | Nil;\n const shouldWrapSelectorList = isNode(selector, N.SelectorList) && (hoistToRoot || template !== undefined);\n\n if (shouldWrapSelectorList) {\n result = PseudoSelector.create({ name: ':is', arg: selector });\n result.generated = true;\n } else {\n result = selector;\n }\n\n if (template !== undefined || shouldWrapSelectorList || hoistToRoot) {\n result.hoistToRoot = true;\n }\n return result;\n }\n\n const amp: Ampersand = this.clone();\n let frame = atIndex(context.rulesetFrames, -1);\n const frameSelector = isNode(frame, N.Ruleset) ? frame.get('selector') : undefined;\n /**\n * Attach the current context selector if we need it later, for extends and such.\n * The frame is constant, so we can use the selector directly.\n * If the ampersand already has a stored selector (from getImplicitSelector),\n * preserve it instead of overwriting with the frame selector.\n */\n if (!amp._selectorContainer && frame && frameSelector) {\n amp._selectorContainer = {\n selector: frameSelector,\n getEffectiveSelector: (collapseNesting?: boolean, nestedContext?: Context) => {\n if (frame && isNode(frame, N.Ruleset)) {\n return frame.getEffectiveSelector(collapseNesting, nestedContext);\n }\n return frameSelector;\n }\n };\n }\n return amp;\n }\n\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node): this {\n const newNode = super.clone(deep, cloneFn);\n // super.clone() for leaf nodes reconstructs the leaf value generically.\n // Ampersand stores its data in the template instance field, not in .value,\n // so we must patch it explicitly on the clone.\n newNode.template = this.template;\n if (newNode.template instanceof Nil) {\n newNode.adopt(newNode.template);\n }\n // Preserve authored selector context when it already exists. EvalNode will\n // still bind the current frame when the clone has no selector container.\n newNode._selectorContainer = this._selectorContainer;\n newNode._storedSelector = cloneStoredSelector(this._storedSelector, deep);\n return newNode;\n }\n\n /** @todo - move to ToModuleVisitor */\n // toModule(context: Context, out: OutputCollector) {\n // out.add('$J.amp()', this.location)\n // }\n}\n\nexport const amp = defineType(Ampersand, 'Ampersand', 'amp');\n","import { Node, defineType, F_VISIBLE, CANONICAL, isVisibleInContext, type NodeOptions, type RenderKey } from './node.js';\nimport { Ruleset } from './ruleset.js';\nimport { Any } from './any.js';\nimport { Rules } from './rules.js';\nimport type { Context } from '../context.js';\nimport { type FinalPrintOptions, type PrintOptions, getPrintOptions } from './util/print.js';\nimport { isThenable, type MaybePromise, pipe } from '@jesscss/awaitable-pipe';\nimport { Ampersand } from './ampersand.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { indent, normalizeIndent, serializeRulesContainer } from './util/serialize-helper.js';\nimport { Interpolated } from './interpolated.js';\nimport { Nil } from './nil.js';\nimport type { Selector } from './selector.js';\nimport { isPreEvaluated } from './util/field-helpers.js';\nimport { getCurrentParentNode, getParentRuleset } from './util/selector-utils.js';\n\n/**\n * When collapseNesting/hoist wrapped at-rule rules in a single Ruleset(&),\n * the real rulesets (.ma, .md, etc.) registered to the inner Rules (the wrapper\n * Ruleset's rules). Register that inner Rules as a child extend root so\n * processExtends can find them. Extend behavior must not depend on collapseNesting.\n */\nfunction registerInnerExtendRootIfHoisted(\n wrapperRules: Rules,\n context: Context,\n layerName?: string\n): void {\n if (wrapperRules.value.length !== 1) {\n return;\n }\n const first = wrapperRules.value[0];\n if (!isNode(first, N.Ruleset)) {\n return;\n }\n const innerRules = first.getRules(first.renderKey);\n if (!innerRules || !isNode(innerRules, N.Rules)) {\n return;\n }\n context.extendRoots.registerRoot(innerRules, wrapperRules, { layerName });\n}\n\nfunction getScopeParentNode(node: Node, renderKey?: RenderKey): Node | undefined {\n if (renderKey !== undefined) {\n return getCurrentParentNode(node, renderKey);\n }\n return node.parent;\n}\n\nexport type AtRuleValue = {\n name: Any<'atkeyword'> | Interpolated<'atkeyword'>;\n /** The prelude */\n prelude?: Node;\n rules?: Rules;\n};\n\nexport const NESTABLE_AT_RULES = ['@media', '@supports', '@layer', '@container', '@scope'] as const;\nexport const ROOT_ONLY_AT_RULES = [\n '@charset',\n '@import',\n '@namespace',\n '@font-face',\n '@keyframes',\n '@page',\n '@property',\n '@counter-style',\n '@viewport'\n] as const;\nconst COLLAPSE_PRESERVING_AT_RULES = ['@starting-style'] as const;\n\nexport type AtRuleOptions = NodeOptions;\n\nexport type AtRuleChildData = {\n name: Any<'atkeyword'> | Interpolated<'atkeyword'>;\n prelude: Node | undefined;\n rules: Rules | undefined;\n frames: (Ruleset | AtRule)[] | undefined;\n};\n\n/**\n * A rule like @charset or @media\n */\nexport interface AtRule {\n type: 'AtRule';\n shortType: 'atrule';\n}\n\nexport class AtRule extends Node<AtRuleValue, AtRuleOptions, AtRuleChildData> {\n static override childKeys = ['name', 'prelude', 'rules'] as const;\n\n name!: Any<'atkeyword'> | Interpolated<'atkeyword'>;\n prelude: Node | undefined;\n rules: Rules | undefined;\n declare preludeEdge: Map<RenderKey, Node | undefined> | undefined;\n declare rulesEdge: Map<RenderKey, Rules | undefined> | undefined;\n private frames: (Ruleset | AtRule)[] | undefined;\n\n private _resolveRenderKey(context?: Context): RenderKey | undefined {\n return context?.renderKey ?? context?.rulesContext?.renderKey ?? this.renderKey;\n }\n\n private _assignRules(rules: Rules, context: Context): void {\n const renderKey = this._resolveRenderKey(context);\n if (renderKey !== undefined && renderKey !== CANONICAL) {\n this.rulesEdge?.delete(renderKey);\n if (this.rulesEdge?.size === 0) {\n this.rulesEdge = undefined;\n }\n }\n this.rules = rules;\n this.adopt(rules, context);\n }\n\n private _assignPrelude(prelude: Node, context: Context): void {\n const renderKey = this._resolveRenderKey(context);\n if (renderKey !== undefined && renderKey !== CANONICAL) {\n this.preludeEdge?.delete(renderKey);\n if (this.preludeEdge?.size === 0) {\n this.preludeEdge = undefined;\n }\n }\n this.prelude = prelude;\n this.adopt(prelude, context);\n }\n\n getPrelude(renderKey?: RenderKey): Node | undefined {\n return renderKey !== undefined\n ? this.preludeEdge?.get(renderKey) ?? this.prelude\n : this.prelude;\n }\n\n getRules(renderKey?: RenderKey): Rules | undefined {\n return renderKey !== undefined\n ? this.rulesEdge?.get(renderKey) ?? this.rules\n : this.rules;\n }\n\n enterRules(context?: Context): Rules | undefined {\n const renderKey = this._resolveRenderKey(context);\n const rules = this.getRules(renderKey);\n return rules?.withRenderOwner(this, renderKey, context);\n }\n\n constructor(value: AtRuleValue, options?: AtRuleOptions, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.name = value.name;\n this.prelude = value.prelude;\n this.rules = value.rules;\n if (this.name instanceof Node) {\n this.adopt(this.name);\n }\n if (this.prelude instanceof Node) {\n this.adopt(this.prelude);\n }\n if (this.rules instanceof Node) {\n this.adopt(this.rules);\n }\n this.allowRoot = true;\n }\n\n protected _valueOf: string | undefined;\n\n /** Used for equality comparison with other at-rules */\n override valueOf() {\n return (this._valueOf ??= (this.name.toString() + (this.prelude ? ' ' + this.prelude.valueOf() : '')));\n }\n\n /**\n * Means: can bubble ruleset parents to children.\n *\n * @todo - There's no reason to make this state-aware. At-rules can't change their name.\n */\n isNestable() {\n return NESTABLE_AT_RULES.includes(this.name.valueOf() as (typeof NESTABLE_AT_RULES)[number]);\n }\n\n /**\n * For legacy collapseNesting, will push ruleset to root silently.\n *\n * @todo - There's no reason to make this state-aware. At-rules can't change their name.\n */\n isRootOnly() {\n return ROOT_ONLY_AT_RULES.includes(this.name.valueOf() as (typeof ROOT_ONLY_AT_RULES)[number]);\n }\n\n isHoisted(opts: { collapseNesting?: boolean; context?: Context }) {\n if (\n this.hoistToRoot === undefined\n && opts.collapseNesting\n && COLLAPSE_PRESERVING_AT_RULES.includes(this.name.valueOf() as (typeof COLLAPSE_PRESERVING_AT_RULES)[number])\n ) {\n return false;\n }\n return this.hoistToRoot ?? opts.collapseNesting ?? false;\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n return serializeRulesContainer(this, options as FinalPrintOptions);\n }\n\n /**\n * Pre-evaluate name and prelude (similar to Ruleset.preEval)\n * This allows us to extract layer names before rules are evaluated\n */\n override preEval(context: Context): MaybePromise<AtRule | Nil> {\n if (!this.preEvaluated) {\n const node = this.clone(false, undefined, context);\n node.preEvaluated = true;\n // Index should already be assigned by parent Rules\n node.sourceNode ??= this;\n\n // Evaluate name if needed (for interpolated names)\n const name = node.name;\n if (name && name instanceof Interpolated) {\n const maybeKey = name.eval(context);\n if (isThenable(maybeKey)) {\n return (maybeKey as Promise<Any<'atkeyword'>>).then((key) => {\n node.name = key;\n return this._preEvalPrelude(node, context);\n });\n }\n node.name = maybeKey as Any<'atkeyword'>;\n }\n\n return this._preEvalPrelude(node, context);\n }\n return this;\n }\n\n private _preEvalPrelude(node: AtRule, context: Context): MaybePromise<AtRule | Nil> {\n const renderKey = node._resolveRenderKey(context);\n const prelude = node.getPrelude(renderKey);\n const rules = node.enterRules(context);\n // Preserve @import prelude as-authored (including comments). Evaluation here can\n // normalize/strip comment tokens inside the prelude, but less.js expects them preserved.\n const name = node.name;\n const atRuleName = String(name.valueOf?.() ?? name ?? '').trim();\n if (atRuleName === '@import') {\n if (prelude) {\n node.prelude = prelude;\n }\n // Reference branches are traversed for symbol/extend resolution, but plain\n // CSS @import hoisting must remain a visible-output concern only.\n if (!context.inReferenceImportScope) {\n const topImports = (context.topImports ??= []);\n const nodeLoc = node.location?.join(':') ?? '';\n const nodeSig = `${name.valueOf?.() ?? name}:${prelude?.valueOf?.() ?? ''}`;\n const alreadyQueued = topImports.some((queuedNode) => {\n if (!isNode(queuedNode, N.AtRule)) {\n return false;\n }\n const queued = queuedNode as AtRule;\n const queuedName = queued.name;\n const queuedPrelude = queued.getPrelude(queued._resolveRenderKey(context));\n return (\n queued === node\n || queued.sourceNode === node.sourceNode\n || queued.sourceNode === node\n || (\n (queued.location?.join(':') ?? '') === nodeLoc\n && `${queuedName.valueOf?.() ?? queuedName}:${queuedPrelude?.valueOf?.() ?? ''}` === nodeSig\n )\n );\n });\n if (!alreadyQueued) {\n topImports.push(node);\n }\n }\n return new Nil();\n }\n // Defer prelude evaluation to evalNode so variable lookups happen in the correct\n // call-time scope (e.g. mixin parameters referenced from nested @media preludes).\n if (prelude) {\n node.prelude = prelude;\n }\n // Depth-first: preEval child rules immediately so all nested rulesets/extends\n // are registered in source order before we process extends.\n if (rules && !isPreEvaluated(rules, context)) {\n // For nestable at-rules we do NOT push the original here. The body's Rules.preEval\n // pushes the clone (the Rules that ends up in the tree) so rulesets register to it.\n // Pushing the original would leave the clone's registry empty (extend + collapseNesting bug).\n let pushedExtendRootForPreEval = false;\n if (!node.isNestable()) {\n context.extendRoots.pushExtendRoot(rules);\n pushedExtendRootForPreEval = true;\n }\n // Root-only at-rules (@keyframes, @font-face, etc.): do not let parent ruleset frames\n // pierce into the body — clear rulesetFrames so 0%/100% etc. are not combined with .parent.\n const savedRulesetFramesForPreEval = node.isRootOnly() ? context.rulesetFrames : undefined;\n if (node.isRootOnly()) {\n context.rulesetFrames = [];\n }\n const preEvaldRules = rules.preEval(context);\n if (isThenable(preEvaldRules)) {\n return (preEvaldRules as Promise<Rules>).then((evaldRules) => {\n if (savedRulesetFramesForPreEval !== undefined) {\n context.rulesetFrames = savedRulesetFramesForPreEval;\n }\n if (pushedExtendRootForPreEval) {\n context.extendRoots.popExtendRoot();\n }\n node._assignRules(evaldRules, context);\n return node;\n });\n }\n if (savedRulesetFramesForPreEval !== undefined) {\n context.rulesetFrames = savedRulesetFramesForPreEval;\n }\n if (pushedExtendRootForPreEval) {\n context.extendRoots.popExtendRoot();\n }\n node._assignRules(preEvaldRules as Rules, context);\n }\n return node;\n }\n\n private _extractAndStoreLayerName(node: AtRule, context: Context): void {\n const name = node.name;\n const prelude = node.getPrelude(node._resolveRenderKey(context));\n const atRuleName = name?.toTrimmedString?.() ?? name?.toString?.() ?? '';\n if (atRuleName === '@layer' && prelude) {\n const preludeStr = String(prelude.valueOf?.() ?? prelude.toTrimmedString?.() ?? prelude.toString?.() ?? '');\n if (preludeStr) {\n let parentLayerName: string | undefined;\n for (let i = context.frames.length - 2; i >= 0; i--) {\n const frame = context.frames[i]!;\n if (isNode(frame, N.AtRule) && frame.name?.toTrimmedString?.() === '@layer') {\n parentLayerName = context.extendRoots.getLayerName(frame as AtRule);\n }\n if (parentLayerName) {\n break;\n }\n }\n const layerName = parentLayerName ? `${parentLayerName}.${preludeStr}` : preludeStr;\n context.extendRoots.setLayerName(node, layerName);\n }\n }\n }\n\n /** Render the opening of this at-rule (name and prelude) */\n getHeaderString(options: FinalPrintOptions, withoutComments?: boolean): string {\n const w = options.writer;\n const name = this.name;\n const renderKey = this.renderKey !== CANONICAL\n ? this.renderKey\n : this._resolveRenderKey(options.context);\n const prelude = this.getPrelude(renderKey);\n const rules = this.enterRules(options.context);\n\n let idt = indent(options.depth);\n let out = idt;\n\n if (withoutComments) {\n options = { ...options, suppressComments: true };\n }\n\n const withHeaderRenderKey = <T>(fn: () => T): T => {\n const ctx = options.context;\n if (!ctx || renderKey === undefined) {\n return fn();\n }\n const previousRenderKey = ctx.renderKey;\n ctx.renderKey = renderKey;\n try {\n return fn();\n } finally {\n ctx.renderKey = previousRenderKey;\n }\n };\n\n const nameOut = withHeaderRenderKey(() => w.capture(() => name.toString(options)));\n const nameEndsWithSpace = /\\s$/.test(nameOut);\n const preludeOut = prelude ? withHeaderRenderKey(() => w.capture(() => prelude.toString(options))) : '';\n const hasPreludeContent = /\\S/.test(preludeOut);\n if (prelude && hasPreludeContent) {\n const preludeStartsWithSpace = /^\\s/.test(preludeOut);\n\n out += nameOut;\n // If name ends with space AND prelude starts with space, trim the prelude's leading space\n // Otherwise, add a space only if neither has spacing\n let finalPreludeOut = preludeOut;\n if (nameEndsWithSpace && preludeStartsWithSpace) {\n finalPreludeOut = preludeOut.replace(/^\\s+/, '');\n } else if (!nameEndsWithSpace && !preludeStartsWithSpace) {\n out += ' ';\n }\n out += finalPreludeOut;\n if (rules) {\n const preludeEndsWithSpace = /\\s$/.test(finalPreludeOut);\n if (!preludeEndsWithSpace) {\n out += ' ';\n }\n out = normalizeIndent(out + '{', idt) + '\\n';\n } else {\n out = normalizeIndent(out + ';', idt);\n }\n } else {\n out += nameOut;\n if (rules) {\n if (!nameEndsWithSpace) {\n out += ' ';\n }\n out = normalizeIndent(out + '{', idt) + '\\n';\n } else {\n out = normalizeIndent(out + ';', idt);\n }\n }\n return out;\n }\n\n override evalNode(context: Context): MaybePromise<AtRule | Nil> {\n let node = this as AtRule;\n const renderKey = node._resolveRenderKey(context);\n const previousRenderKey = context.renderKey;\n if (renderKey !== undefined && renderKey !== CANONICAL) {\n context.renderKey = renderKey;\n }\n\n // @plugin is handled by the Less compatibility plugin (preEval). If we reach eval and it's still visible, no plugin processed it.\n const atName = String(node.name?.valueOf?.() ?? '');\n if (atName === '@plugin' && isVisibleInContext(node, context)) {\n throw new Error('@plugin is only supported when using the Less compatibility plugin (@jesscss/plugin-less-compat).');\n }\n\n // Check if this is a root-only at-rule that should bubble to root\n // when nested inside a Ruleset. Use hoistToRoot for in-place rendering.\n let shouldClearRulesetFrames = false;\n if (context.bubbleRootAtRules && node.isRootOnly(context)) {\n const hasRulesetParent = context.frames.some(f => isNode(f, N.Ruleset));\n if (hasRulesetParent) {\n // Mark for hoisting - this will render at root level but in-place\n node.hoistToRoot = true;\n // We'll clear rulesetFrames when evaluating internal rules\n // to prevent selector inheritance from piercing through\n shouldClearRulesetFrames = true;\n }\n }\n\n // Store frames snapshot for hoisting serialization\n const nodeHoistToRoot = node.hoistToRoot;\n if (context.opts.collapseNesting || nodeHoistToRoot) {\n node.frames = [...context.frames];\n }\n\n const tryMergeNestedMedia = () => {\n // Nested @media merge is currently disabled to match less.js fixture expectations.\n // (Some fixtures expect nested @media blocks to remain nested rather than being\n // rewritten as `@media a and b`.)\n if (process.env.ENABLE_NESTED_MEDIA_MERGE !== 'true') {\n return;\n }\n if (node.name?.valueOf?.() !== '@media') {\n return;\n }\n const outerRules = node.enterRules(context);\n if (!outerRules) {\n return;\n }\n const visible = outerRules.value.filter(n => isVisibleInContext(n, context));\n if (visible.length !== 1) {\n return;\n }\n const only = visible[0]!;\n if (!isNode(only, N.AtRule) || (only as AtRule).name?.valueOf?.() !== '@media') {\n return;\n }\n const inner = only as AtRule;\n const innerRules = inner.enterRules(context);\n if (!innerRules) {\n return;\n }\n\n // Combine media queries using \"and\" like Less does.\n const outerPrelude = node.getPrelude(node._resolveRenderKey(context));\n const innerPrelude = inner.getPrelude(inner._resolveRenderKey(context));\n if (outerPrelude && innerPrelude) {\n // Build a normalized text prelude to avoid double-spacing from nested sequences.\n const outerText = outerPrelude.toTrimmedString().trim();\n const innerText = innerPrelude.toTrimmedString().trim();\n const combined = `${outerText} and ${innerText}`.replace(/[ \\t]+/g, ' ').trim();\n node.prelude = new Any(combined);\n } else {\n node.prelude = outerPrelude ?? innerPrelude;\n }\n\n // Replace outer rules with the inner rules (flatten nested media).\n node._assignRules(innerRules, context);\n };\n\n const out = pipe(\n () => {\n // Evaluate prelude in the correct scope (mixin params, vars, etc.).\n const prelude = node.getPrelude(renderKey);\n if (prelude) {\n // Evaluate the prelude in the outer (enclosing) Rules scope, not the nested @media Rules scope.\n // This matches Less behavior for mixin parameters referenced from nested @media preludes.\n const savedRulesContext = context.rulesContext;\n let liftedRulesContext = context.lookupScope ?? savedRulesContext;\n // If our current rulesContext is a Rules whose parent is an AtRule, lift to the enclosing Rules.\n if (liftedRulesContext && isNode(liftedRulesContext, N.Rules)) {\n const renderKey = liftedRulesContext.renderKey;\n let cursor: Node = liftedRulesContext;\n let depth = 0;\n while (getScopeParentNode(cursor, renderKey) && depth++ < 10) {\n const cursorParent = getScopeParentNode(cursor, renderKey);\n if (isNode(cursorParent, N.AtRule) && isNode(getScopeParentNode(cursorParent, renderKey), N.Rules)) {\n cursor = getScopeParentNode(cursorParent, renderKey)!;\n continue;\n }\n break;\n }\n liftedRulesContext = cursor;\n }\n context.rulesContext = liftedRulesContext;\n const out = prelude.eval(context);\n context.rulesContext = savedRulesContext;\n if (isThenable(out)) {\n return (out as Promise<Node>).then((n) => {\n node._assignPrelude(n, context);\n return undefined;\n });\n }\n node._assignPrelude(out as Node, context);\n }\n },\n () => {\n let rules = node.enterRules(context);\n if (rules) {\n if (\n context.opts.collapseNesting\n && !COLLAPSE_PRESERVING_AT_RULES.includes(node.name.valueOf() as (typeof COLLAPSE_PRESERVING_AT_RULES)[number])\n ) {\n node.hoistToRoot = true;\n }\n // Push to frames before evaluating rules so we can use context.frames to find parent layers\n // This allows nested layers to find their parent layer names\n // NOTE: We do NOT pop here - the frame must remain accessible during rules evaluation\n // The frame will be popped at the end of evalNode\n context.frames.push(node);\n\n // Extract and store layer name AFTER pushing to frames but BEFORE evaluating rules\n // This ensures parent layers are already on the stack when we look for them\n this._extractAndStoreLayerName(node, context);\n\n // Wrap in Ruleset(&) when hoisted for nestable at-rules only. Do NOT wrap @keyframes,\n // @font-face, or other at-rules in ROOT_ONLY_AT_RULES — their children must not get\n // a wrapper so keyframe percentages (0%, 100%) etc. are not combined with parent selectors.\n // Required for serialization: rulesets inside @media need this wrapper to output\n // e.g. \".parent { font-size: 14px; }\" inside @media.\n if (node.isNestable() && !node.isRootOnly() && node.isHoisted(context.opts)) {\n const parentRuleset = context.rulesetFrames.at(-1)\n ?? (context.callStack.length > 0 ? context.callerRulesetFrame : undefined)\n ?? getParentRuleset(node, context);\n const parentSel = parentRuleset?.getEffectiveSelector(context.opts.collapseNesting ?? false, context);\n const hasParentSel = parentSel && !isNode(parentSel, N.Nil);\n const wrapperSel = hasParentSel\n ? (parentSel!.copy(true) as Selector)\n : undefined;\n rules = Rules.create([\n Ruleset.create({\n selector: wrapperSel ?? Ampersand.create(undefined),\n rules\n }, wrapperSel\n ? {\n generated: true,\n ownSelector: wrapperSel.copy(true) as Selector,\n resolvedHoistWrapper: true\n }\n : { generated: true })\n ]).inherit(rules);\n node.adopt(rules);\n }\n\n // Register extend root for nestable at-rules (including @layer).\n // Run preEval first so we push and later register the Rules that is actually evaluated\n // (clone or original). Otherwise we push the original but eval runs on a clone, so the\n // registered root has no rulesets and extend-chaining / nested at-rule extends fail.\n let pushedExtendRoot = false;\n let parentExtendRoot: Rules | undefined;\n let bodyToEval: Rules = rules;\n if (node.isNestable()) {\n parentExtendRoot = context.extendRoots.getCurrentExtendRoot();\n const preEvalResult = rules.preEval(context);\n if (isThenable(preEvalResult)) {\n return (preEvalResult as Promise<Rules>).then((resolved) => {\n bodyToEval = resolved;\n context.extendRoots.pushExtendRoot(bodyToEval);\n pushedExtendRoot = true;\n const savedRulesetFrames = shouldClearRulesetFrames ? context.rulesetFrames : undefined;\n if (shouldClearRulesetFrames) {\n context.rulesetFrames = [];\n }\n const onlyRuleSetChild = isNode(bodyToEval.value[0], N.Ruleset);\n const evalOut = bodyToEval.eval(context);\n const doRegister = (r: Rules) => {\n if (savedRulesetFrames !== undefined) {\n context.rulesetFrames = savedRulesetFrames;\n }\n const finalRules =\n onlyRuleSetChild && isNode(r.value[0], N.Rules) ? r.value[0] : r;\n node._assignRules(finalRules, context);\n tryMergeNestedMedia();\n context.extendRoots.popExtendRoot();\n const layerName = context.extendRoots.takeLayerName(node);\n const parent = parentExtendRoot ?? context.root ?? undefined;\n context.extendRoots.registerRoot(bodyToEval, parent as Rules | undefined, {\n layerName\n });\n registerInnerExtendRootIfHoisted(bodyToEval, context, layerName);\n if (finalRules !== bodyToEval) {\n context.extendRoots.registerRoot(finalRules as Rules, bodyToEval, { layerName });\n registerInnerExtendRootIfHoisted(finalRules, context, layerName);\n }\n context.extendRoots.pushExtendRoot(bodyToEval);\n context.extendRoots.popExtendRoot();\n return node;\n };\n if (isThenable(evalOut)) {\n return (evalOut as Promise<Rules>).then(doRegister);\n }\n return doRegister(evalOut as Rules);\n });\n }\n bodyToEval = preEvalResult as Rules;\n context.extendRoots.pushExtendRoot(bodyToEval);\n pushedExtendRoot = true;\n }\n\n let onlyRuleSetChild = isNode(bodyToEval.value[0], N.Ruleset);\n\n // For root-only at-rules that are hoisted, clear rulesetFrames\n // so internal rulesets don't inherit parent selectors\n const savedRulesetFrames = shouldClearRulesetFrames ? context.rulesetFrames : undefined;\n if (shouldClearRulesetFrames) {\n context.rulesetFrames = [];\n }\n\n let out = bodyToEval.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Rules>).then((r) => {\n // Restore rulesetFrames\n if (savedRulesetFrames !== undefined) {\n context.rulesetFrames = savedRulesetFrames;\n }\n // If the only rule was a ruleset, and it evaluated to Rules,\n // discard the extra rules wrapper\n const finalRules = onlyRuleSetChild && isNode(r.value[0], N.Rules) ? r.value[0] : r;\n node._assignRules(finalRules, context);\n tryMergeNestedMedia();\n\n if (pushedExtendRoot && node.isNestable()) {\n context.extendRoots.popExtendRoot();\n const layerName = context.extendRoots.takeLayerName(node);\n const parent = parentExtendRoot ?? context.root ?? undefined;\n context.extendRoots.registerRoot(bodyToEval, parent as Rules | undefined, {\n layerName\n });\n registerInnerExtendRootIfHoisted(bodyToEval, context, layerName);\n if (finalRules !== bodyToEval) {\n context.extendRoots.registerRoot(finalRules as Rules, bodyToEval, { layerName });\n registerInnerExtendRootIfHoisted(finalRules, context, layerName);\n }\n context.extendRoots.pushExtendRoot(bodyToEval);\n context.extendRoots.popExtendRoot();\n }\n\n return node;\n });\n }\n // Restore rulesetFrames (sync path)\n if (savedRulesetFrames !== undefined) {\n context.rulesetFrames = savedRulesetFrames;\n }\n\n const finalRules =\n onlyRuleSetChild && isNode(out.value[0], N.Rules) ? out.value[0] : out;\n node._assignRules(finalRules, context);\n tryMergeNestedMedia();\n\n if (pushedExtendRoot && node.isNestable()) {\n context.extendRoots.popExtendRoot();\n const layerName = context.extendRoots.takeLayerName(node);\n const parent = parentExtendRoot ?? context.root ?? undefined;\n context.extendRoots.registerRoot(bodyToEval, parent as Rules | undefined, { layerName });\n registerInnerExtendRootIfHoisted(bodyToEval, context, layerName);\n if (finalRules !== bodyToEval) {\n context.extendRoots.registerRoot(finalRules as Rules, bodyToEval, { layerName });\n registerInnerExtendRootIfHoisted(finalRules, context, layerName);\n }\n context.extendRoots.pushExtendRoot(bodyToEval);\n context.extendRoots.popExtendRoot();\n }\n }\n return node;\n },\n () => {\n // Pop the frame that was pushed in preEval\n // This frame was kept on the stack during rules evaluation so children could access it\n context.frames.pop();\n let rules = node.enterRules(context);\n if (rules && rules.visibleRules().length === 0) {\n node._removeFlag(F_VISIBLE, context);\n }\n return node;\n }\n ) as MaybePromise<AtRule>;\n\n if (isThenable(out)) {\n return (out as Promise<AtRule>).then(\n (result) => {\n context.renderKey = previousRenderKey;\n return result;\n },\n (error) => {\n context.renderKey = previousRenderKey;\n throw error;\n }\n );\n }\n context.renderKey = previousRenderKey;\n return out;\n }\n\n /** @todo - move to visitors */\n // toCSS(context: Context, out: OutputCollector) {\n // out.add(`${this.name}`, this.location)\n // /** Prelude expression includes white space */\n // const value = this.data\n // if (value) {\n // value.toCSS(context, out)\n // }\n // if (this.rules) {\n // this.rules.toCSS(context, out)\n // } else {\n // out.add(';')\n // }\n // }\n\n // toModule(context: Context, out: OutputCollector) {\n // out.add('$J.atrule({\\n', this.location)\n // const pre = context.pre\n // context.indent++\n // out.add(`${pre} name: ${JSON.stringify(this.name)}`)\n // const value = this.data\n // if (value) {\n // out.add(`,\\n${pre} value: `)\n // value.toModule(context, out)\n // }\n // const rules = this.rules\n // if (rules) {\n // out.add(`,\\n${pre} rules: `)\n // rules.toModule(context, out)\n // }\n // context.indent--\n // out.add(`\\n${pre}},${JSON.stringify(this.location)})`)\n // }\n}\n\nexport const atrule = defineType(AtRule, 'AtRule');\n","import type { Context } from '../context.js';\nimport { Node, defineType, type OptionalLocation, type TreeContext } from './node.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\n\nexport type BlockOptions = {\n type: 'curly' | 'square';\n};\n\nexport type BlockChildData = { value: Node };\n\nexport interface Block extends Node<Node, BlockOptions, BlockChildData> {\n type: 'Block';\n shortType: 'block';\n eval(context: Context): MaybePromise<Block>;\n}\n\n/**\n * A block like `{ ... }` or `[ ... ]`. This is used\n * for things like custom properties and unknown at-rules.\n */\nexport class Block extends Node<Node, BlockOptions, BlockChildData> {\n static override childKeys = ['value'] as const;\n\n readonly value!: Node;\n\n constructor(value: Node, options?: BlockOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n if (this.value instanceof Node) {\n this.adopt(this.value);\n }\n }\n\n override evalNode(context: Context): MaybePromise<Block> {\n const value = this.get('value', context);\n const finish = (nextValue: Node): Block => {\n if (nextValue !== value) {\n this.value = nextValue;\n }\n return this;\n };\n const maybeEvald = value.eval(context);\n if (isThenable(maybeEvald)) {\n return (maybeEvald as Promise<Node>).then(finish);\n }\n return finish(maybeEvald as Node);\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const value = this.get('value', options.context);\n let { type } = this.options ?? {};\n let start = type === 'square' ? '[' : '{';\n let end = type === 'square' ? ']' : '}';\n w.add(start);\n value.toString(options);\n w.add(end);\n return w.getSince(mark);\n }\n}\n\ntype BlockParams = ConstructorParameters<typeof Block>;\n\nexport const block = defineType(Block, 'Block') as (\n value: BlockParams[0],\n options?: BlockParams[1],\n location?: BlockParams[2],\n treeContext?: BlockParams[3]\n) => Block;\n","import { type Context } from '../context.js';\nimport { Node, F_VISIBLE, F_STATIC, defineType, type OptionalLocation, type TreeContext } from './node.js';\n\nexport type CommentOptions = {\n lineComment?: boolean;\n};\n\nexport interface Comment extends Node<string, CommentOptions> {\n type: 'Comment';\n shortType: 'comment';\n eval(context: Context): Comment;\n}\n\n/**\n * A comment node\n */\nexport class Comment extends Node<string, CommentOptions> {\n static override childKeys = null as null;\n\n readonly value!: string;\n readonly lineComment: boolean;\n\n constructor(value: string, options?: CommentOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n this.lineComment = !!options?.lineComment;\n this.allowRoot = true;\n this.allowRuleRoot = true;\n this.addFlag(F_STATIC);\n if (this.lineComment || value.startsWith('//')) {\n this.removeFlag(F_VISIBLE);\n }\n }\n}\n\nexport const comment = defineType(Comment, 'Comment');\n","import type { Class } from 'type-fest';\nimport { type Context } from '../context.js';\nimport { F_NON_STATIC, F_VISIBLE, Node, defineType, type OptionalLocation, type TreeContext } from './node.js';\nimport { Bool } from './bool.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, pipe, isThenable } from '@jesscss/awaitable-pipe';\n\n/** @note Less will parse =< but it will be stored as <= */\nexport type ConditionOperator = 'and' | 'or' | '=' | '>' | '<' | '>=' | '<=';\n\nexport type ConditionValue = [\n left: Node\n] | [\n left: Node,\n op: ConditionOperator,\n right: Node\n];\n\nexport type ConditionOptions = {\n negate?: boolean;\n};\n\nexport type ConditionChildData = {\n left: Node;\n operator: ConditionOperator | undefined;\n right: Node | undefined;\n negate: boolean;\n};\n\nexport interface Condition extends Node<ConditionValue, ConditionOptions, ConditionChildData> {\n type: 'Condition';\n shortType: 'condition';\n eval(context: Context): MaybePromise<Bool>;\n}\n\nexport class Condition extends Node<ConditionValue, ConditionOptions, ConditionChildData> {\n static override childKeys = ['left', 'right'] as const;\n\n readonly left!: Node;\n private readonly operator: ConditionOperator | undefined;\n readonly right: Node | undefined;\n private readonly negate: boolean;\n\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const left = this.get('left', ctx);\n const operator = this.get('operator', ctx);\n const right = this.get('right', ctx);\n const negate = this.get('negate', ctx);\n const options = this._meta?.options;\n const cloneChild = cloneFn ?? ((n: Node) => n.clone(deep, cloneFn, ctx));\n const value: ConditionValue = operator !== undefined && right !== undefined\n ? [deep ? cloneChild(left) : left, operator, deep ? cloneChild(right) : right]\n : [deep ? cloneChild(left) : left];\n let clonedOptions = options ? { ...options } : undefined;\n if (negate) {\n (clonedOptions ??= {}).negate = true;\n } else if (clonedOptions) {\n delete clonedOptions.negate;\n }\n const newNode = new (this.constructor as Class<this>)(\n value,\n clonedOptions,\n this.location,\n this.treeContext\n );\n newNode.inherit(this);\n return newNode;\n }\n\n constructor(value: ConditionValue, options?: ConditionOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.left = value[0];\n this.operator = value[1];\n this.right = value[2];\n this.negate = !!options?.negate;\n if (this.left instanceof Node) {\n this.adopt(this.left);\n }\n if (this.right instanceof Node) {\n this.adopt(this.right);\n }\n // Conditions are always non-static, but can inherit may_async from children\n this.addFlags(F_VISIBLE, F_NON_STATIC);\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n let left = this.get('left', context);\n let op = this.get('operator', context);\n let right = this.get('right', context);\n const negated = this.get('negate', context);\n const needsParens = Boolean(right || negated);\n if (negated) {\n w.add('not ');\n }\n if (needsParens) {\n w.add('(');\n }\n left.toString(options);\n if (op && right) {\n w.add(' ');\n w.add(String(op));\n w.add(' ');\n right.toString(options);\n }\n if (needsParens) {\n w.add(')');\n }\n return w.getSince(mark);\n }\n\n static getBool(node: Node, negated: boolean): Bool {\n if (node instanceof Bool) {\n return new Bool(negated ? !node.value : node.value);\n }\n // Less guards treat only explicit booleans as truthy.\n // Any non-boolean (number, quoted, keyword, list, nil, etc.) is false.\n return new Bool(negated);\n }\n\n static getResult(a: Node, b: Node, op: ConditionOperator, context?: Context): boolean {\n switch (op) {\n case 'and': return Condition.getBool(a, false).value && Condition.getBool(b, false).value;\n case 'or': return Condition.getBool(a, false).value || Condition.getBool(b, false).value;\n default:\n switch (a.compare(b, context)) {\n case -1:\n return op === '<' || op === '<=';\n case 0:\n return op === '=' || op === '>=' || op === '<=';\n case 1:\n return op === '>' || op === '>=';\n default:\n return false;\n }\n }\n }\n\n override evalNode(context: Context): MaybePromise<Bool> {\n let left = this.get('left', context);\n let op = this.get('operator', context);\n let right = this.get('right', context);\n let negated = this.get('negate', context);\n\n return pipe(\n () => left.eval(context),\n (a) => {\n if (!right) {\n // Defer unary coercion to the final stage to avoid double-negation.\n return a;\n }\n return a;\n },\n (a) => {\n if (!right) {\n return [a];\n }\n let b = right.eval(context);\n if (isThenable(b)) {\n return (b as Promise<Node>).then(bb => [a, bb] as const);\n }\n return [a, b];\n },\n ([a, b]) => {\n if (!b) {\n const unary = Condition.getBool(a, negated);\n return unary;\n }\n const normalizeDefaultCall = (node: Node): Node => {\n if (node.type !== 'Call') {\n return node;\n }\n const rawCallName = (node as import('./call.js').Call).name;\n const callName = String(typeof rawCallName === 'string'\n ? rawCallName\n : rawCallName?.valueOf?.() ?? '');\n if (callName === 'default' || callName === '??') {\n return new Bool(Boolean(context.isDefault));\n }\n return node;\n };\n a = normalizeDefaultCall(a);\n b = normalizeDefaultCall(b);\n let result = Condition.getResult(a, b, op!, context);\n return new Bool(negated ? !result : result);\n }\n );\n }\n}\n\nexport const condition = defineType(Condition, 'Condition');\n","import {\n type OptionalLocation,\n type NodeOptions,\n type TreeContext,\n defineType,\n type Node\n} from './node.js';\nimport { Dimension } from './dimension.js';\nimport { Color } from './color.js';\nimport { type Context } from '../context.js';\nimport { type Operator } from './util/calculate.js';\nimport { isPlainObject } from './util/collections.js';\n\n/**\n * A number. Named `Num` to avoid conflict with the built-in `Number` class.\n */\nexport interface Num {\n type: 'Num';\n shortType: 'num';\n}\nexport class Num extends Dimension {\n // Numbers are static and don't need evaluation\n\n constructor(value: number | { number: number }, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(isPlainObject(value) ? value as { number: number } : { number: value as number }, options, location, treeContext);\n }\n\n // Method overloads for better type safety\n override operate(b: Num, op: Operator, context?: Context): Num | Dimension;\n override operate(b: Dimension, op: Operator, context?: Context): Dimension;\n override operate(b: Color, op: Operator, context?: Context): Color;\n override operate(b: Node, op: Operator, context?: Context): Dimension | Color;\n override operate(b: Node, op: Operator, context?: Context): Dimension | Color {\n // Call super.operate() to get the result\n const result = super.operate(b, op, context);\n\n // If the result is a Dimension and has an empty unit, convert it to a Num\n if (result instanceof Dimension && !result.unit) {\n return new Num(result.number).inherit(this);\n }\n\n // Otherwise, pass through the result as-is\n return result;\n }\n}\n\ndefineType(Num, 'Num');\n\nexport const num = (\n value: number,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n) => new Num(value, options, location, treeContext);","import type { Context } from '../../context.js';\nimport { Any } from '../any.js';\nimport { type Node, type RenderKey } from '../node.js';\nimport { Num } from '../number.js';\nimport { Rules } from '../rules.js';\nimport { Sequence } from '../sequence.js';\nimport { VarDeclaration } from '../declaration-var.js';\nimport { AssignmentType } from '../declaration.js';\nimport { List } from '../list.js';\nimport { getChildren, getParent, setParent } from './field-helpers.js';\nimport { isNode } from './is-node.js';\nimport { N } from '../node-type.js';\n\nexport type ScopedBinding = {\n name: string;\n value: Node;\n};\n\nfunction sameNodeValue(a: Node | undefined, b: Node | undefined): boolean {\n const left = String(a?.valueOf?.() ?? '').trim();\n const right = String(b?.valueOf?.() ?? '').trim();\n return left === right;\n}\n\nfunction shouldReuseInPriorScope(node: Node): boolean {\n if (!isNode(node, N.Declaration)) {\n return true;\n }\n const declaration = node as Node & { name: Node };\n const normalizedFromAssign = node.options.normalizedFromAssign;\n return (\n normalizedFromAssign !== AssignmentType.Add\n && normalizedFromAssign !== AssignmentType.MergeList\n && normalizedFromAssign !== AssignmentType.MergeSequence\n && String(declaration.name) !== 'padding'\n );\n}\n\nfunction cloneForPriorScope(node: Node, context: Context): Node {\n if (isNode(node, N.Rules)) {\n return node.createShallowBodyWrapper(context);\n }\n return node.clone();\n}\n\nexport function createPriorScope(\n priorScopeSourceNodes: readonly Node[],\n bodyTemplate: Rules,\n context: Context\n): Rules | undefined {\n if (priorScopeSourceNodes.length === 0) {\n return undefined;\n }\n const priorScope = new Rules(\n priorScopeSourceNodes\n .filter(shouldReuseInPriorScope)\n .map(n => cloneForPriorScope(n, context))\n );\n priorScope.inherit(bodyTemplate);\n return priorScope;\n}\n\nexport function createScopedBodyRules(\n bodyTemplate: Rules,\n priorScope: Rules | undefined,\n renderKey: RenderKey,\n context: Context\n): Rules {\n const scopedRules = bodyTemplate.createShallowBodyWrapper(context, renderKey);\n const bodyOwner = bodyTemplate.parent;\n if (bodyOwner) {\n const ownerParent = getParent(bodyOwner, context);\n if (ownerParent) {\n setParent(bodyOwner, ownerParent, { ...context, renderKey });\n }\n }\n if (priorScope) {\n scopedRules.parent = priorScope;\n setParent(scopedRules, priorScope, { ...context, renderKey });\n }\n return scopedRules;\n}\n\nexport function createScopedBindings(\n bindingNames: readonly string[],\n bindingValues: readonly Node[]\n): VarDeclaration[] {\n const declarations: VarDeclaration[] = [];\n for (let i = Math.min(bindingNames.length, bindingValues.length) - 1; i >= 0; i--) {\n declarations.push(new VarDeclaration({\n name: new Any(bindingNames[i]!, { role: 'property' }),\n value: bindingValues[i]!\n }));\n }\n return declarations;\n}\n\nfunction getControlDeclarationValue(node: Node, context: Context): Node {\n return (node as Node & { get(field: 'value', context?: Context): Node }).get('value', context);\n}\n\nfunction setControlDeclarationValue(node: Node, value: Node, context: Context): void {\n (\n node as Node & { setCurrentValue(value: Node, context?: Context): void }\n ).setCurrentValue(value, context);\n}\n\nfunction cloneCurrentNodeForOutput<T extends Node>(node: T, context: Context): T {\n const Class = node.constructor as new (...args: any[]) => T;\n const childKeys = (node.constructor as unknown as typeof Node).childKeys;\n const options = node.options ? { ...node.options } : undefined;\n\n if (childKeys === null) {\n return node.clone();\n }\n\n let cloneData: any;\n if (childKeys.length === 1) {\n const value = node.get(childKeys[0]!, context);\n cloneData = Array.isArray(value) ? [...value] : value;\n } else {\n cloneData = {};\n for (const key of childKeys) {\n const value = node.get(key!, context);\n cloneData[key!] = Array.isArray(value) ? [...value] : value;\n }\n }\n\n const cloned = new Class(cloneData, options, node.location, node.treeContext);\n cloned.inherit(node);\n return cloned;\n}\n\nfunction mergeScopedDeclarationValue(\n outNode: Node,\n prev: Node,\n normalizedFromAssign: AssignmentType | undefined,\n context: Context\n): void {\n if (!isNode(prev, N.Declaration) || !isNode(outNode, N.Declaration)) {\n return;\n }\n const prevValue = getControlDeclarationValue(prev, context);\n const nextValue = getControlDeclarationValue(outNode, context);\n if (\n normalizedFromAssign === AssignmentType.Add\n || normalizedFromAssign === AssignmentType.MergeList\n ) {\n const prevItems = isNode(prevValue, N.List)\n ? prevValue.value\n : [prevValue];\n const nextItems = isNode(nextValue, N.List)\n ? nextValue.value\n : [nextValue];\n const nextAlreadyIncludesPrev =\n nextItems.length >= prevItems.length\n && prevItems.every((item, idx) => sameNodeValue(item, nextItems[idx]));\n const mergedItems = nextAlreadyIncludesPrev\n ? [...nextItems]\n : [...prevItems, ...nextItems];\n setControlDeclarationValue(\n outNode,\n new List(mergedItems).inherit(nextValue),\n context\n );\n return;\n }\n if (normalizedFromAssign === AssignmentType.MergeSequence) {\n const prevItems = isNode(prevValue, N.Sequence)\n ? prevValue.value\n : [prevValue];\n const nextItems = isNode(nextValue, N.Sequence)\n ? nextValue.value\n : [nextValue];\n const nextAlreadyIncludesPrev =\n nextItems.length >= prevItems.length\n && prevItems.every((item, idx) => sameNodeValue(item, nextItems[idx]));\n const mergedItems = nextAlreadyIncludesPrev\n ? [...nextItems]\n : [...prevItems, ...nextItems];\n setControlDeclarationValue(\n outNode,\n new Sequence(mergedItems).inherit(nextValue),\n context\n );\n }\n}\n\nfunction findMatchingAccumulatedDeclarationIndex(\n accumulatedNodes: readonly Node[],\n outName: string\n): number {\n for (let i = 0; i < accumulatedNodes.length; i++) {\n const prev = accumulatedNodes[i]!;\n if (isNode(prev, N.Declaration) && String((prev as Node & { name: Node }).name) === outName) {\n return i;\n }\n }\n return -1;\n}\n\nfunction removeDuplicateAccumulatedDeclarationsAfter(\n accumulatedNodes: Node[],\n outName: string,\n firstMatch: number\n): void {\n for (let i = accumulatedNodes.length - 1; i > firstMatch; i--) {\n const prev = accumulatedNodes[i]!;\n if (isNode(prev, N.Declaration) && String((prev as Node & { name: Node }).name) === outName) {\n accumulatedNodes.splice(i, 1);\n }\n }\n}\n\nfunction insertScopedOutputNodeBeforeFirstNestedRuleset(\n accumulatedNodes: Node[],\n outNode: Node\n): boolean {\n for (let i = 0; i < accumulatedNodes.length; i++) {\n if (isNode(accumulatedNodes[i]!, N.Ruleset | N.Rules)) {\n accumulatedNodes.splice(i, 0, outNode);\n return true;\n }\n }\n return false;\n}\n\nfunction appendScopedOutputNode(\n accumulatedNodes: Node[],\n outNode: Node,\n context: Context\n): void {\n if (isNode(outNode, N.Declaration)) {\n const normalizedFromAssign = outNode.options?.normalizedFromAssign;\n const outName = String((outNode as Node & { name: Node }).name);\n const isMergedAssignment =\n normalizedFromAssign === AssignmentType.Add\n || normalizedFromAssign === AssignmentType.MergeList\n || normalizedFromAssign === AssignmentType.MergeSequence;\n const shouldCoalesceByName = outName === 'padding';\n if (isMergedAssignment || shouldCoalesceByName) {\n const firstMatch = findMatchingAccumulatedDeclarationIndex(accumulatedNodes, outName);\n if (firstMatch >= 0) {\n mergeScopedDeclarationValue(\n outNode,\n accumulatedNodes[firstMatch]!,\n normalizedFromAssign,\n context\n );\n accumulatedNodes[firstMatch] = outNode;\n removeDuplicateAccumulatedDeclarationsAfter(accumulatedNodes, outName, firstMatch);\n return;\n }\n if (insertScopedOutputNodeBeforeFirstNestedRuleset(accumulatedNodes, outNode)) {\n return;\n }\n }\n }\n accumulatedNodes.push(outNode);\n}\n\nexport function appendScopedOutputNodes(\n accumulatedNodes: Node[],\n outputNodes: readonly Node[],\n context: Context\n): void {\n for (const outNode of outputNodes) {\n appendScopedOutputNode(accumulatedNodes, outNode, context);\n }\n}\n\nexport function collectScopedResultNodes(result: Node, context: Context): Node[] {\n if (!isNode(result, N.Rules)) {\n return [result];\n }\n return getChildren(result, context).map(rawOutNode => cloneCurrentNodeForOutput(rawOutNode, context));\n}\n\nexport async function evalScopedRulesForOutput(\n scopedRules: Rules,\n context: Context\n): Promise<Node[]> {\n const previousRenderKey = context.renderKey;\n const previousRulesContext = context.rulesContext;\n const previousLookupScope = context.lookupScope;\n try {\n context.renderKey = scopedRules.renderKey;\n context.rulesContext = scopedRules;\n context.lookupScope = scopedRules;\n const result = await scopedRules.eval(context);\n return collectScopedResultNodes(result, context);\n } finally {\n context.lookupScope = previousLookupScope;\n context.rulesContext = previousRulesContext;\n context.renderKey = previousRenderKey;\n }\n}\n\nexport async function evaluateScopedBodyWithBindings(\n bodyTemplate: Rules,\n priorScopeSourceNodes: readonly Node[],\n bindings: readonly ScopedBinding[],\n context: Context\n): Promise<Node[]> {\n const priorScope = createPriorScope(priorScopeSourceNodes, bodyTemplate, context);\n const renderKey = context.nextRenderKey();\n const scopedRules = createScopedBodyRules(bodyTemplate, priorScope, renderKey, context);\n const declarations = createScopedBindings(\n bindings.map(binding => binding.name),\n bindings.map(binding => binding.value)\n );\n for (const varDecl of declarations) {\n scopedRules.unshift(varDecl);\n }\n return evalScopedRulesForOutput(scopedRules, context);\n}\n\nexport function createCounterNode(counter: number): Num {\n return new Num(counter);\n}\n","import { Node, defineType, F_VISIBLE, F_NON_STATIC, F_MAY_ASYNC, type OptionalLocation } from './node.js';\nimport type { Context, TreeContext } from '../context.js';\nimport { Rules } from './rules.js';\nimport { Sequence } from './sequence.js';\nimport { Any } from './any.js';\nimport { Num } from './number.js';\nimport { VarDeclaration } from './declaration-var.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport type { MaybePromise } from '@jesscss/awaitable-pipe';\nimport { List } from './list.js';\nimport type { Mixin } from './mixin.js';\nimport { appendScopedOutputNodes, createCounterNode, evaluateScopedBodyWithBindings } from './util/scoped-body-eval.js';\n\nconst PUBLIC_RULE_VISIBILITY = {\n Declaration: 'public',\n Ruleset: 'public',\n VarDeclaration: 'public',\n Mixin: 'public'\n} as const;\n\nfunction makeDirectiveRulesPublic(rules: Rules) {\n rules.options.rulesVisibility = {\n ...rules.options.rulesVisibility,\n ...PUBLIC_RULE_VISIBILITY\n };\n}\n\ntype LegacyLoopValue = {\n header: Sequence;\n rules: Rules;\n};\n\nexport type ForValue = {\n vars: VarDeclaration | VarDeclaration[];\n iterable: Node;\n rules: Rules;\n};\n\nfunction getBindingNames(vars: VarDeclaration | VarDeclaration[]): string[] {\n if (Array.isArray(vars)) {\n return vars.map(v => v.get('name').valueOf());\n }\n return [vars.get('name').valueOf()];\n}\n\nfunction varsToNode(vars: VarDeclaration | VarDeclaration[]): Node {\n if (!Array.isArray(vars)) {\n return vars;\n }\n const wrapper = new List<VarDeclaration>([], { sep: ',' });\n wrapper.value = [...vars];\n return wrapper;\n}\n\nasync function resolveLoopEntryKey(\n key: number | string | Node,\n counter: number,\n context: Context\n): Promise<Node> {\n if (typeof key === 'number') {\n return new Num(key + 1);\n }\n if (typeof key === 'string' && key === 'value') {\n return new Num(counter);\n }\n if (isNode(key)) {\n return await key.eval(context);\n }\n return new Any(String(key), { role: 'property' });\n}\n\nasync function evaluateForIteration(\n loopTemplate: Rules,\n accumulatedNodes: readonly Node[],\n bindingNames: readonly string[],\n value: Node,\n key: number | string | Node,\n counter: number,\n context: Context\n): Promise<Node[]> {\n const resolvedValue = await value.eval(context);\n const resolvedKey = await resolveLoopEntryKey(key, counter, context);\n return evaluateScopedBodyWithBindings(\n loopTemplate,\n accumulatedNodes,\n [\n { name: bindingNames[0]!, value: resolvedValue },\n { name: bindingNames[1] ?? '', value: resolvedKey },\n { name: bindingNames[2] ?? '', value: createCounterNode(counter) }\n ].filter(binding => binding.name),\n context\n );\n}\n\nasync function evaluateForOutput(\n loopTemplate: Rules,\n bindingNames: readonly string[],\n evaluatedIterable: Node,\n context: Context\n): Promise<Rules> {\n const accumulatedNodes: Node[] = [];\n let counter = 1;\n for await (const [value, key] of resolveEntries(evaluatedIterable, context)) {\n const outputNodes = await evaluateForIteration(\n loopTemplate,\n accumulatedNodes,\n bindingNames,\n value,\n key,\n counter,\n context\n );\n counter++;\n appendScopedOutputNodes(accumulatedNodes, outputNodes, context);\n }\n return new Rules(accumulatedNodes);\n}\n\nasync function* resolveEntries(input: Node, context: Context): AsyncGenerator<[Node, number | string | Node]> {\n if (isNode(input, N.Expression)) {\n yield* resolveEntries(await input.get('value', context).eval(context), context);\n return;\n }\n if (isNode(input, N.Call)) {\n const evald = await input.eval(context);\n if (isNode(evald, N.Call)) {\n yield [evald, 0];\n return;\n }\n yield* resolveEntries(evald, context);\n return;\n }\n if (isNode(input, N.Paren)) {\n const parenValue = input.get('value', context);\n if (parenValue instanceof Node) {\n yield* resolveEntries(parenValue, context);\n return;\n }\n }\n if ((isNode(input, N.Sequence) || isNode(input, N.List))) {\n const items = input.get('value', context);\n if (Array.isArray(items)) {\n for (let key = 0; key < items.length; key++) {\n const value = items[key]!;\n yield [value, key];\n }\n return;\n }\n }\n if (isNode(input, N.Rules | N.Ruleset | N.Mixin)) {\n const rules: readonly Node[] = isNode(input, N.Rules)\n ? input.value\n : isNode(input, N.Ruleset)\n ? (input.getRules(context?.renderKey ?? input.renderKey)?.value ?? [])\n : (((input as Mixin).get('rules')?.value) ?? []);\n for (const rule of rules) {\n if (!rule || isNode(rule, N.Comment)) {\n continue;\n }\n if (!isNode(rule, N.Declaration)) {\n continue;\n }\n yield [\n (rule as Node & { value: Node }).value,\n (rule as Node & { name: Node }).name\n ];\n }\n return;\n }\n yield [input, 0];\n}\n\n/** @todo - I don't understand how these are different or why the LLM did this? */\nexport type IfValue = {\n conditions: Node[];\n bodies: Rules[];\n elseBranch?: Rules;\n};\n\nexport type IfChildData = {\n conditions: Node[];\n bodies: Rules[];\n elseBranch: Rules | undefined;\n};\n\n/**\n * A control-flow block that serializes as:\n * - `$if (...) { ... }`\n * - `$else if (...) { ... }`\n * - `$else { ... }`\n *\n * This is language-agnostic: it's the canonical Jess control node.\n */\nexport interface If extends Node<IfValue, any, IfChildData> {\n type: 'If';\n shortType: 'if';\n}\nexport class If extends Node<IfValue, any, IfChildData> {\n static override childKeys = ['conditions', 'bodies', 'elseBranch'] as const;\n\n readonly conditions!: Node[];\n readonly bodies!: Rules[];\n readonly elseBranch: Rules | undefined;\n\n constructor(value: IfValue, options?: any, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.conditions = value.conditions;\n this.bodies = value.bodies;\n this.elseBranch = value.elseBranch;\n for (const cond of this.conditions) {\n if (cond instanceof Node) {\n this.adopt(cond);\n }\n }\n for (const body of this.bodies) {\n if (body instanceof Node) {\n this.adopt(body);\n }\n makeDirectiveRulesPublic(body);\n }\n if (this.elseBranch) {\n if (this.elseBranch instanceof Node) {\n this.adopt(this.elseBranch);\n }\n makeDirectiveRulesPublic(this.elseBranch);\n }\n this.allowRoot = true;\n this.allowRuleRoot = true;\n this.addFlags(F_VISIBLE, F_NON_STATIC, F_MAY_ASYNC);\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n\n const conditions = this.get('conditions', context);\n const bodies = this.get('bodies', context);\n const elseBranch = this.get('elseBranch', context);\n w.add('$if', this);\n w.add(' (');\n conditions[0]?.toString(options);\n w.add(') ');\n bodies[0]?.toBraced(options);\n\n for (let i = 1; i < conditions.length; i++) {\n w.add(' $else if (');\n conditions[i]!.toString(options);\n w.add(') ');\n bodies[i]?.toBraced(options);\n }\n\n if (elseBranch) {\n w.add(' $else ');\n elseBranch.toBraced(options);\n }\n\n return w.getSince(mark);\n }\n}\n\nexport type ForChildData = {\n vars: VarDeclaration | VarDeclaration[];\n iterable: Node;\n rules: Rules;\n};\n\nexport interface For extends Node<ForValue, any, ForChildData> {\n type: 'For';\n shortType: 'for';\n}\n/**\n * `$for <header> { ... }`\n */\nexport class For extends Node<ForValue, any, ForChildData> {\n static override childKeys = ['vars', 'iterable', 'rules'] as const;\n\n readonly vars!: VarDeclaration | VarDeclaration[];\n readonly iterable!: Node;\n readonly rules!: Rules;\n\n constructor(value: ForValue, options?: any, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.vars = value.vars;\n this.iterable = value.iterable;\n this.rules = value.rules;\n if (Array.isArray(this.vars)) {\n for (const v of this.vars) {\n if (v instanceof Node) {\n this.adopt(v);\n }\n }\n } else if (this.vars instanceof Node) {\n this.adopt(this.vars);\n }\n if (this.iterable instanceof Node) {\n this.adopt(this.iterable);\n }\n if (this.rules instanceof Node) {\n this.adopt(this.rules);\n }\n this.allowRoot = true;\n this.allowRuleRoot = true;\n this.addFlags(F_VISIBLE, F_NON_STATIC, F_MAY_ASYNC);\n makeDirectiveRulesPublic(this.rules);\n }\n\n override preEval(context: Context): MaybePromise<Node> {\n if (!this.preEvaluated) {\n this.preEvaluated = true;\n return this;\n }\n return this;\n }\n\n override evalNode(context: Context): MaybePromise<Node> {\n const vars = this.get('vars', context);\n const iterable = this.get('iterable', context);\n const loopTemplate = this.get('rules', context).withRenderOwner(this, context.renderKey, context);\n const bindingNames = getBindingNames(vars);\n if (bindingNames.length === 0) {\n throw new Error('Invalid $for header: missing binding variable');\n }\n const run = async (): Promise<Node> => {\n const evaluatedIterable = await iterable.eval(context);\n return evaluateForOutput(loopTemplate, bindingNames, evaluatedIterable, context);\n };\n return run();\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n w.add('$for ', this);\n w.add('(');\n varsToNode(this.get('vars', context)).toString(options);\n w.add(' of ');\n this.get('iterable', context).toString(options);\n w.add(')');\n w.add(' ');\n this.get('rules', context).withRenderOwner(this, context?.renderKey, context).toBraced(options);\n return w.getSince(mark);\n }\n}\n\n/**\n * `$each <header> { ... }`\n */\nexport type EachChildData = {\n header: Sequence;\n rules: Rules;\n};\n\nexport interface Each extends Node<LegacyLoopValue, any, EachChildData> {\n type: 'Each';\n shortType: 'each';\n}\nexport class Each extends Node<LegacyLoopValue, any, EachChildData> {\n static override childKeys = ['header', 'rules'] as const;\n\n readonly header!: Sequence;\n readonly rules!: Rules;\n\n constructor(value: LegacyLoopValue, options?: any, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.header = value.header;\n this.rules = value.rules;\n if (this.header instanceof Node) {\n this.adopt(this.header);\n }\n if (this.rules instanceof Node) {\n this.adopt(this.rules);\n }\n this.allowRoot = true;\n this.allowRuleRoot = true;\n this.addFlags(F_VISIBLE, F_NON_STATIC, F_MAY_ASYNC);\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n w.add('$each ', this);\n this.get('header', context).toString(options);\n w.add(' ');\n this.get('rules', context).withRenderOwner(this, context?.renderKey, context).toBraced(options);\n return w.getSince(mark);\n }\n}\n\nexport type WhileValue = {\n condition: Node;\n rules: Rules;\n};\n\nexport type WhileChildData = {\n condition: Node;\n rules: Rules;\n};\n\n/**\n * `$while (<condition>) { ... }`\n */\nexport interface While extends Node<WhileValue, any, WhileChildData> {\n type: 'While';\n shortType: 'while';\n}\nexport class While extends Node<WhileValue, any, WhileChildData> {\n static override childKeys = ['condition', 'rules'] as const;\n\n readonly condition!: Node;\n readonly rules!: Rules;\n\n constructor(value: WhileValue, options?: any, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.condition = value.condition;\n this.rules = value.rules;\n if (this.condition instanceof Node) {\n this.adopt(this.condition);\n }\n if (this.rules instanceof Node) {\n this.adopt(this.rules);\n }\n this.allowRoot = true;\n this.allowRuleRoot = true;\n this.addFlags(F_VISIBLE, F_NON_STATIC, F_MAY_ASYNC);\n makeDirectiveRulesPublic(this.rules);\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n w.add('$while (', this);\n this.get('condition', context).toString(options);\n w.add(') ');\n this.get('rules', context).withRenderOwner(this, context?.renderKey, context).toBraced(options);\n return w.getSince(mark);\n }\n}\n\nexport const ifNode = defineType(If, 'If', 'if');\nexport const forNode = defineType(For, 'For', 'for');\nexport const eachNode = defineType(Each, 'Each', 'each');\nexport const whileNode = defineType(While, 'While', 'while');\n","import { Declaration } from './declaration.js';\nimport { defineType } from './node.js';\nimport type { Context } from '../context.js';\nimport type { Nil } from './nil.js';\nimport { type MaybePromise, pipe } from '@jesscss/awaitable-pipe';\n// import type { OutputCollector } from '../output'\n\n/**\n * A declaration that retains all tokens\n * (white-space, comments, etc)\n *\n * Ideally, perhaps, the value would just be\n * one Anonymous node for now?\n *\n * @todo - is this used?\n */\nexport class CustomDeclaration extends Declaration {\n override evalNode(context: Context): MaybePromise<this | Nil> {\n context.inCustom = true;\n return pipe(\n () => super.evalNode(context),\n (node) => {\n context.inCustom = false;\n return node as this | Nil;\n }\n );\n }\n\n /** @todo move to visitors */\n // toCSS(context: Context, out: OutputCollector) {\n // const loc = this.location\n // this.name.toCSS(context, out)\n // /**\n // * Don't insert a space after the colon;\n // * Instead, insert the exact token stream.\n // *\n // * @todo - test this\n // */\n // out.add(':', loc)\n // this.data.toCSS(context, out)\n // out.add(';', loc)\n // }\n\n // toModule(context: Context, out: OutputCollector) {\n // const pre = context.pre\n // const loc = this.location\n // out.add('$J.custom({\\n', loc)\n // out.add(` ${pre}name: `)\n // this.name.toModule(context, out)\n // out.add(`\\n ${pre}value: `)\n // this.data.toModule(context, out)\n // out.add(`\\n${pre}})`)\n // }\n}\n\nexport const customdecl = defineType(CustomDeclaration, 'CustomDeclaration', 'custom');","import type { Class } from 'type-fest';\nimport { defineType, Node, F_VISIBLE, F_NON_STATIC, F_IMPLICIT_AMPERSAND, type NodeOptions } from './node.js';\nimport { type Context } from '../context.js';\nimport { Selector } from './selector.js';\nimport { Ampersand } from './ampersand.js';\nimport type { Ruleset } from './ruleset.js';\nimport { Nil } from './nil.js';\nimport { ComplexSelector, type ComplexSelectorComponent } from './selector-complex.js';\nimport { Combinator } from './combinator.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { getImplicitSelector, selectorHasAuthoredAmpersand, wrapParentSelectorForNestedContext } from './util/selector-utils.js';\nimport { addParentEdge } from './util/cursor.js';\nimport { CANONICAL, EVAL } from './node-base.js';\n\nexport enum ExtendFlag {\n /** Sass and Jess default */\n All = 0,\n /** Less default - must not be a partial selector match */\n Exact = 1\n}\n\nexport type ExtendValue = {\n /** The current selector. By default is `&` */\n selector?: Selector;\n /** The target to extend */\n target: Selector;\n /**\n * Optional namespace scoping for extend targets.\n *\n * - `namespace: '*'` means \"search all extend roots in this file (ignore namespace scoping)\".\n * - `namespace: 'ns'` means \"search the extend root(s) assigned to namespace `ns`\".\n */\n namespace?: string;\n flag?: ExtendFlag;\n};\n/**\n * Extends selectors - parsed by Less as an independent statement\n * at the beginning of rules.\n *\n * @todo - figure out eval -- use Rules lookups\n * @note - there is some pseudo-code somewhere that smartly\n * registers selectors by a string code.\n */\nexport type ExtendChildData = {\n selector: Selector | undefined;\n target: Selector;\n namespace: string | undefined;\n flag: ExtendFlag | undefined;\n};\n\nexport interface Extend extends Node<ExtendValue, NodeOptions, ExtendChildData> {\n type: 'Extend';\n shortType: 'extend';\n eval(context: Context): MaybePromise<Selector>;\n}\n\nexport class Extend extends Node<ExtendValue, NodeOptions, ExtendChildData> {\n static override childKeys = ['selector', 'target'] as const;\n\n readonly selector: ExtendValue['selector'];\n readonly target!: Selector;\n private readonly namespace: string | undefined;\n private readonly flag: ExtendFlag | undefined;\n\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const selector = this.get('selector', ctx);\n const target = this.get('target', ctx);\n const namespace = this.get('namespace', ctx);\n const flag = this.get('flag', ctx);\n const cloneChild = cloneFn ?? ((n: Node) => n.clone(deep, cloneFn, ctx));\n const options = this._meta?.options;\n let priorChildParents: Array<[Node, Node | undefined]> | undefined;\n if (!deep) {\n priorChildParents = [];\n if (selector instanceof Node) {\n priorChildParents.push([selector, selector.parent]);\n }\n if (target instanceof Node) {\n priorChildParents.push([target, target.parent]);\n }\n }\n const newNode = new (this.constructor as Class<this>)(\n {\n selector: deep && selector instanceof Node ? cloneChild(selector) : selector,\n target: deep ? cloneChild(target) : target,\n namespace,\n flag\n },\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n );\n if (priorChildParents) {\n const renderKey = ctx?.renderKey ?? (this.renderKey === CANONICAL ? EVAL : this.renderKey);\n for (const [child, priorParent] of priorChildParents) {\n addParentEdge(child, renderKey, newNode);\n (child as unknown as { parent?: Node }).parent = priorParent;\n }\n }\n newNode.inherit(this);\n return newNode;\n }\n\n constructor(value: ExtendValue, options?: any, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.selector = value.selector;\n this.target = value.target;\n this.namespace = value.namespace;\n this.flag = value.flag;\n if (this.selector instanceof Node) {\n this.adopt(this.selector);\n }\n if (this.target instanceof Node) {\n this.adopt(this.target);\n }\n this.removeFlag(F_VISIBLE);\n this.addFlag(F_NON_STATIC);\n }\n\n override valueOf(context?: Context) {\n return `$extend ${this.get('target', context).valueOf()}`;\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const context = options.context;\n let target = this.get('target', context);\n let selector = this.get('selector', context);\n let flag = this.get('flag', context);\n let namespace = this.get('namespace', context);\n const mark = w.mark();\n w.add('$extend');\n if (selector) {\n let out = w.capture(() => selector.toString(options)).trim();\n w.add(' ');\n w.add(out, selector);\n w.add(' ->');\n }\n let out = w.capture(() => target.toString(options)).trim();\n w.add(' ');\n if (namespace) {\n w.add(`${namespace}|`);\n }\n w.add(out, target);\n if (flag === ExtendFlag.Exact) {\n w.add(' !exact');\n }\n w.add(';');\n return w.getSince(mark);\n }\n\n // Don't preEval Extend - let it be evaluated in evalNode when the ruleset is in the frame\n // This ensures the ampersand resolves to the correct ruleset selector, not the parent frame\n\n override evalNode(context: Context): MaybePromise<Nil> {\n let selector = this.get('selector', context);\n let target = this.get('target', context);\n let flag = this.get('flag', context);\n let namespace = this.get('namespace', context);\n const hasExplicitSelector = selector !== undefined;\n\n const currentFrame = context.rulesetFrames.at(-1);\n\n // If selector is undefined, convert it to ampersand so it resolves to the ruleset's selector\n // If selector is already set to a non-ampersand (e.g., from a bubbled extend), keep it as-is\n // The parser sets the selector correctly when bubbling extends, so we should preserve it\n if (!selector) {\n // Set selector to ampersand - it will resolve to the current ruleset's selector when evaluated\n // This matches the conceptual model: .c:extend(.ext all) is like { &:extend(.ext all); } inside .c\n // The frame selector should already be :is(.a, .b) .c (the evaluated selector from preEval)\n selector = Ampersand.create(undefined);\n // Make the ampersand visible so it's included in the selector when evaluated\n // This ensures the parent selector is properly included in the extend selector\n selector.addFlag(F_VISIBLE);\n }\n // If selector is already set (e.g., .ext7 from a bubbled extend), use it directly\n // Don't convert non-ampersand selectors to ampersand - they should be used as-is\n // Get current extend root from registry stack\n const extendRoot = context.extendRoots.getCurrentExtendRoot();\n if (!extendRoot) {\n /** Throw error? */\n return new Nil();\n }\n\n const maybeSel = selector.eval(context);\n if (isThenable(maybeSel)) {\n return (maybeSel as Promise<Selector | Nil>).then((sel) => {\n if (sel instanceof Nil) {\n return new Nil();\n }\n // Resolve ampersand to its current parent selector if needed (live resolution for extend)\n let resolvedSel: Selector = sel;\n if (isNode(sel, N.Ampersand)) {\n const ampResolved = sel.getResolvedSelector();\n if (ampResolved && !(ampResolved instanceof Nil)) {\n resolvedSel = ampResolved;\n }\n }\n resolvedSel = resolveExtendSelectorInFrame(\n resolvedSel,\n hasExplicitSelector,\n currentFrame,\n context\n );\n resolvedSel = materializeImplicitAmpersands(resolvedSel, flag !== ExtendFlag.All);\n const rs = currentFrame as Ruleset;\n const docOrder = getDocumentOrderForExtend(rs, context);\n const fromReferenceScope = context.inReferenceImportScope;\n context.extends.push([target, resolvedSel, flag === ExtendFlag.All, extendRoot, this, docOrder, fromReferenceScope, namespace]);\n return new Nil();\n });\n }\n const sel = maybeSel as Selector | Nil;\n if (sel instanceof Nil) {\n return new Nil();\n }\n // Resolve ampersand to its current parent selector if needed (live resolution for extend)\n let resolvedSel: Selector = sel;\n if (isNode(sel, N.Ampersand)) {\n const ampResolved = sel.getResolvedSelector();\n if (ampResolved && !(ampResolved instanceof Nil)) {\n resolvedSel = ampResolved;\n }\n }\n resolvedSel = resolveExtendSelectorInFrame(\n resolvedSel,\n hasExplicitSelector,\n currentFrame,\n context\n );\n resolvedSel = materializeImplicitAmpersands(resolvedSel, flag !== ExtendFlag.All);\n const rs = currentFrame && isNode(currentFrame, N.Ruleset) ? currentFrame as Ruleset : undefined;\n const docOrder = getDocumentOrderForExtend(rs, context);\n const fromReferenceScope = context.inReferenceImportScope;\n context.extends.push([target, resolvedSel, flag === ExtendFlag.All, extendRoot, this, docOrder, fromReferenceScope, namespace]);\n return new Nil();\n }\n}\n\nfunction materializeImplicitAmpersands(\n selector: Selector,\n includeNonListImplicit: boolean\n): Selector {\n const materialize = (node: Selector): Selector => {\n if (isNode(node, N.Ampersand)) {\n const amp = node as Ampersand;\n const n = amp as unknown as Node;\n if (n.hasFlag(F_IMPLICIT_AMPERSAND)) {\n const resolved = amp.getResolvedSelector();\n if (\n resolved\n && !(resolved instanceof Nil)\n && (includeNonListImplicit || isNode(resolved, N.SelectorList))\n ) {\n return materialize(resolved.copy(true) as Selector);\n }\n }\n return node.copy(true) as Selector;\n }\n\n if (isNode(node, N.ComplexSelector)) {\n const complex = node as ComplexSelector;\n const parts: Selector[] = [];\n for (const part of complex.get('value') as unknown as Selector[]) {\n if (isNode(part, N.Ampersand)) {\n const amp = part as Ampersand;\n const n = amp as unknown as Node;\n if (n.hasFlag(F_IMPLICIT_AMPERSAND)) {\n const resolved = amp.getResolvedSelector();\n if (\n resolved\n && !(resolved instanceof Nil)\n && (includeNonListImplicit || isNode(resolved, N.SelectorList))\n ) {\n const repl = materialize(resolved.copy(true) as Selector);\n if (isNode(repl, N.ComplexSelector)) {\n parts.push(...((repl as ComplexSelector).get('value') as unknown as Selector[]).map(x => x.copy(true) as Selector));\n } else {\n parts.push(repl);\n }\n continue;\n }\n }\n }\n const repl = materialize(part);\n parts.push(repl);\n }\n return ComplexSelector.create(parts as ComplexSelectorComponent[]).inherit(node) as Selector;\n }\n\n const value = (node as Selector & { value?: Selector[] }).value;\n if (Array.isArray(value)) {\n const cloned = node.copy(true) as Selector & { value?: Selector[] };\n cloned.value = value.map(item => materialize(item as Selector));\n return cloned as Selector;\n }\n\n return node.copy(true) as Selector;\n };\n\n return materialize(selector);\n}\n\n/** Document order for extend: prefer parse location startOffset (source order), else assigned map, else push order (length). */\nfunction getDocumentOrderForExtend(rs: Ruleset | undefined, context: Context): number {\n if (!rs) {\n return context.extends.length;\n }\n const loc = (rs as Node).location;\n const fromLoc = Array.isArray(loc) && loc.length >= 1 && typeof loc[0] === 'number' ? loc[0] : undefined;\n if (fromLoc !== undefined) {\n return fromLoc;\n }\n const fromMap = context.documentOrderByRuleset?.get(rs);\n if (fromMap !== undefined) {\n return fromMap;\n }\n return context.extends.length;\n}\nexport const extend = defineType(Extend, 'Extend');\n\nfunction resolveExtendSelectorInFrame(\n selector: Selector,\n hasExplicitSelector: boolean,\n currentFrame: Node | undefined,\n context: Context\n): Selector {\n if (!currentFrame || !isNode(currentFrame, N.Ruleset)) {\n return selector;\n }\n\n const rs = currentFrame as Ruleset;\n const fullSel = rs.getEffectiveSelector(false, context);\n let resolvedSel = selector;\n let usedParentListComposition = false;\n\n if (!hasExplicitSelector) {\n const ownSel = rs.getOwnSelector(context);\n const parentFrame = context.rulesetFrames.at(-2);\n const parentSel = (\n parentFrame && isNode(parentFrame, N.Ruleset)\n ? (parentFrame as Ruleset).getEffectiveSelector(false, context)\n : undefined\n );\n if (\n ownSel\n && parentSel\n && !(parentSel instanceof Nil)\n && isNode(parentSel, N.SelectorList)\n ) {\n resolvedSel = ComplexSelector.create([\n wrapParentSelectorForNestedContext(parentSel as Selector),\n Combinator.create(' '),\n ownSel.copy(true) as Selector\n ] as unknown as ComplexSelectorComponent[]) as unknown as Selector;\n usedParentListComposition = true;\n }\n }\n\n if (!hasExplicitSelector && !usedParentListComposition) {\n if (fullSel && !(fullSel instanceof Nil)) {\n return fullSel as Selector;\n }\n\n const parentSel = rs.getEffectiveSelector(false, context);\n if (parentSel && !(parentSel instanceof Nil) && resolvedSel.valueOf() !== (parentSel as Selector).valueOf()) {\n return ComplexSelector.create([\n (parentSel as Selector).copy(true),\n Combinator.create(' '),\n resolvedSel.copy(true)\n ]) as unknown as Selector;\n }\n\n return resolvedSel;\n }\n\n if (\n hasExplicitSelector\n && selectorHasAuthoredAmpersand(resolvedSel)\n && fullSel\n && !(fullSel instanceof Nil)\n ) {\n return getImplicitSelector(resolvedSel, fullSel as Selector, false);\n }\n\n return resolvedSel;\n}\n","import { type Context } from '../context.js';\nimport { Node, F_VISIBLE, defineType, type OptionalLocation, type NodeOptions, type TreeContext } from './node.js';\nimport { Nil } from './nil.js';\nimport { logger } from '../logger.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\n\nexport type LogLevel = 'debug' | 'warn' | 'error';\n\nexport type LogValue = {\n level: LogLevel;\n message: Node;\n};\n\nexport type LogChildData = { level: LogLevel; message: Node };\n\nexport interface Log extends Node<LogValue, NodeOptions, LogChildData> {\n type: 'Log';\n shortType: 'log';\n eval(context: Context): MaybePromise<Nil>;\n}\n\n/**\n * A log node for diagnostic at-rules (@debug, @warn, @error).\n * These are compile-time diagnostic directives that should not appear in CSS output.\n */\nexport class Log extends Node<LogValue, NodeOptions, LogChildData> {\n static override childKeys = ['level', 'message'] as const;\n\n level!: LogLevel;\n message!: Node;\n\n constructor(\n value: LogValue,\n options?: NodeOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n ) {\n super(value, options, location, treeContext);\n this.level = value.level;\n this.message = value.message;\n if (this.message instanceof Node) {\n this.adopt(this.message);\n }\n this.allowRoot = true;\n this.allowRuleRoot = true;\n this.removeFlag(F_VISIBLE);\n }\n\n override toTrimmedString() {\n return '';\n }\n\n override toString() {\n return '';\n }\n\n override evalNode(context: Context): MaybePromise<Nil> {\n const messageResult = this.message.eval(context);\n\n if (isThenable(messageResult)) {\n return (messageResult as Promise<Node>).then((evaluatedMessage) => {\n this._logMessage(evaluatedMessage);\n return new Nil();\n });\n }\n\n this._logMessage(messageResult as Node);\n return new Nil();\n }\n\n private _logMessage(msg: Node): void {\n const messageStr = String(msg);\n const level = this.level;\n\n switch (level) {\n case 'debug':\n logger.log?.(messageStr);\n break;\n case 'warn':\n logger.warn?.(messageStr);\n break;\n case 'error':\n logger.error?.(messageStr);\n break;\n }\n }\n}\n\nexport const log = defineType(Log, 'Log');\n","import { CANONICAL, EVAL, F_VISIBLE, Node, defineType, type OptionalLocation } from './node.js';\nimport type { Condition } from './condition.js';\nimport { type List } from './list.js';\nimport type { Any, AnyRole } from './any.js';\nimport type { Rules } from './rules.js';\nimport { Interpolated } from './interpolated.js';\nimport type { Context, TreeContext } from '../context.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\nimport { setParent } from './util/field-helpers.js';\n\nexport interface MixinValue<Name extends AnyRole = 'name'> {\n /**\n * Mixin names can include . or # - in Sass they have to be escaped.\n *\n * Valid mixin names:\n * foo\n * foo.bar\n * foo#bar\n * foo.bar#baz\n * foo#bar.baz\n * -foo\n * _foo (private, from Sass both -foo and _foo are parsed as _foo)\n *\n * @todo - Should anonymous mixins have a different class type?\n */\n name?: Any<Name> | Interpolated<Name>;\n /**\n * Functions can be assigned an expression when parsing,\n * but it will be evaluated as a set of Rules with a scope\n * and an implicit `return`\n */\n rules: Rules;\n /**\n * - A plain node is a kind of value guard.\n * - A name is just a named variable.\n * - A var declaration is a named variable with a default value.\n * - A rest is a rest parameter.\n */\n params?: List<Node>;\n guard?: Condition;\n}\n\nexport type MixinOptions = {\n /** This is a flag that will set during parsing */\n hasDefault?: boolean;\n\n /**\n * Cannot be overloaded. Written as !my-mixin() in Jess.\n * If multiple mixin matches are found with the same\n * name in a scope, it will throw an error.\n */\n unique?: boolean;\n};\n\n// const COMPOUND_REGEX = /[#.]?[-_a-zA-Z\\xA0-\\uFFFF][-_a-zA-Z0-9\\xA0-\\uFFFF]*/ug;\n/**\n * someMixin (arg1; arg2: 10px) {\n * color: black;\n * background-color: white;\n * border-radius: $arg2;\n * }\n *\n *\n * Note that mixin calls are called as JavaScript functions,\n * with either only positional arguments, or a plain object\n * as the first argument, representing named arguments,\n * followed by positional arguments.\n *\n * e.g. `foo($a; $b) { ... }`\n * can be called from JS like:\n * foo(1, 2) or\n * foo({ a: 1, b: 2 }) or\n * foo({ b: 2 }, 1)\n *\n * @todo - Even though we allow a selector as a name.\n */\nexport type MixinChildData = {\n name: Any<AnyRole> | Interpolated<AnyRole> | undefined;\n rules: Rules;\n params: List<Node> | undefined;\n guard: Condition | undefined;\n};\n\nexport interface Mixin {\n type: 'Mixin';\n shortType: 'mixin';\n}\n\nexport class Mixin extends Node<MixinValue, MixinOptions, MixinChildData> {\n static override childKeys = ['name', 'rules', 'params', 'guard'] as const;\n\n name: Any<AnyRole> | Interpolated<AnyRole> | undefined;\n rules!: Rules;\n params: List<Node> | undefined;\n guard: Condition | undefined;\n\n override clone(deep?: boolean, cloneFn?: (n: Node) => Node, ctx?: Context): this {\n const name = this.get('name', ctx);\n const rules = this.get('rules', ctx);\n const params = this.get('params', ctx);\n const guard = this.get('guard', ctx);\n const cloneData: MixinValue = {\n name: deep && name instanceof Node ? name.clone(deep, cloneFn, ctx) : name,\n rules: deep ? rules.clone(deep, cloneFn, ctx) : rules,\n params: deep && params instanceof Node ? params.clone(deep, cloneFn, ctx) : params,\n guard: deep && guard instanceof Node ? guard.clone(deep, cloneFn, ctx) : guard\n };\n\n let priorChildParents: Array<[Node, Node | undefined]> | undefined;\n if (!deep && ctx) {\n priorChildParents = [];\n if (cloneData.name instanceof Node) {\n priorChildParents.push([cloneData.name, cloneData.name.parent]);\n }\n if (cloneData.rules instanceof Node) {\n priorChildParents.push([cloneData.rules, cloneData.rules.parent]);\n }\n if (cloneData.params instanceof Node) {\n priorChildParents.push([cloneData.params, cloneData.params.parent]);\n }\n if (cloneData.guard instanceof Node) {\n priorChildParents.push([cloneData.guard, cloneData.guard.parent]);\n }\n }\n\n const options = this._meta?.options;\n const newNode: this = Reflect.construct(this.constructor, [\n cloneData,\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n ]);\n\n if (priorChildParents) {\n for (const [child, priorParent] of priorChildParents) {\n setParent(child, newNode, ctx!);\n Reflect.set(child, 'parent', priorParent);\n }\n }\n\n newNode.inherit(this);\n return newNode;\n }\n\n constructor(value: MixinValue, options?: MixinOptions, location?: OptionalLocation, context?: TreeContext) {\n super(value, options, location, context);\n this.name = value.name;\n this.rules = value.rules;\n this.params = value.params;\n this.guard = value.guard;\n if (this.name instanceof Node) {\n this.adopt(this.name);\n }\n if (this.rules instanceof Node) {\n this.adopt(this.rules);\n }\n if (this.params instanceof Node) {\n this.adopt(this.params);\n }\n if (this.guard instanceof Node) {\n this.adopt(this.guard);\n }\n this.removeFlag(F_VISIBLE);\n }\n\n // Mixin has preEval method but doesn't need to set flags - preEvaluated is tracked as boolean\n\n /** Return a selector-like keySet */\n private _keySet: Set<string> | undefined;\n\n get keySet() {\n let keySet = this._keySet;\n if (!keySet) {\n const name = this.name;\n if (!name) {\n return (this._keySet = new Set());\n }\n keySet = this._keySet = new Set([name.valueOf()]);\n }\n return keySet;\n }\n\n getKeySet(context?: Context): Set<string> {\n if (!context) {\n return this.keySet;\n }\n const name = this.get('name', context);\n if (!name) {\n return new Set();\n }\n return new Set([name.valueOf()]);\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const context = options.context;\n const name = this.get('name', context);\n const rules = this.get('rules', context).withRenderOwner(this, context?.renderKey, context);\n const params = this.get('params', context);\n const guard = this.get('guard', context);\n const mark = w.mark();\n w.add(name ? `${name}` : '@');\n if (name || params || guard) {\n w.add('(');\n if (params) {\n params.toString(options);\n }\n w.add(')');\n }\n if (guard) {\n w.add(' when ');\n w.add(`${guard}`);\n }\n if (name || params || guard) {\n w.add(' ');\n }\n // Emit rules directly into shared writer; do not re-add return value\n rules.toBraced(options);\n return w.getSince(mark);\n }\n\n override preEval(context: Context): MaybePromise<this> {\n if (this.preEvaluated) {\n return this;\n }\n // Mixins should NOT pre-evaluate their rules during initial registration.\n // Rules inside mixins should only be pre-evaluated when the mixin is called.\n // So we only handle the name (if interpolated) and mark as preEvaluated,\n // but do NOT call super.preEval() which would pre-evaluate children.\n const edgeContext = {\n ...context,\n renderKey: context.renderKey ?? EVAL\n } as Context;\n let node = this.clone(false, undefined, edgeContext);\n node.preEvaluated = true;\n node.sourceNode ??= this;\n node.renderKey = edgeContext.renderKey;\n\n const name = node.get('name', context);\n let rules = node.get('rules', context).withRenderOwner(node, context.renderKey, context);\n if (rules.renderKey === CANONICAL) {\n const wrappedRules = rules.createShallowBodyWrapper(context);\n node.rules = wrappedRules;\n node.adopt(wrappedRules, context);\n rules = wrappedRules;\n }\n // Set visibility on the canonical rules options — mixin body visibility\n // is set on the derived mixin body wrapper for this eval path.\n const rulesVisibility = { ...(rules.options.rulesVisibility ?? {}) };\n if (context.leakyRules) {\n rulesVisibility.Mixin = 'public';\n rulesVisibility.VarDeclaration = 'optional';\n } else {\n rulesVisibility.Mixin = 'private';\n rulesVisibility.VarDeclaration = 'private';\n }\n rules.options = { ...rules.options, rulesVisibility };\n if (name && name instanceof Interpolated) {\n const maybeKey = name.eval(context);\n if (isThenable(maybeKey)) {\n return maybeKey.then((key) => {\n node.name = key;\n return node;\n });\n }\n node.name = maybeKey;\n }\n return node;\n }\n\n /** Since this is a mixin definition, it's not evaluated until it's called. */\n override evalNode() {\n return this;\n }\n\n // override async evalNode(context: Context): Promise<Rules | Expression> {\n // let { name, body, params, guard } = this.data\n // if (name instanceof Interpolated) {\n // name\n // }\n\n /**\n * @todo -\n * Return either a ruleset if `this` is the eval context,\n * or return ruleset.obj() if not (for React/Vue)\n *\n * @todo - move to visitors\n */\n // toModule(context: Context, out: OutputCollector) {\n // const { name, args, value } = this\n // const nm = name.value\n // if (context.depth === 0) {\n // out.add(`export let ${nm}`, this.location)\n // context.exports.add(nm)\n // } else {\n // if (context.depth !== 1) {\n // out.add('let ')\n // }\n // out.add(`${nm} = function(`)\n // if (args) {\n // const length = args.value.length - 1\n // args.value.forEach((node, i) => {\n // if (node instanceof JsIdent) {\n // out.add(node.value)\n // } else {\n // out.add(node.name.value)\n // out.add(' = ')\n // node.value.toModule(context, out)\n // }\n // if (i < length) {\n // out.add(', ')\n // }\n // })\n // }\n // out.add(') { return ')\n // value.toModule(context, out)\n // out.add('}')\n // }\n // }\n}\n\ntype MixinConstructorParams = ConstructorParameters<typeof Mixin>;\n\nexport const mixin = defineType(Mixin, 'Mixin') as (\n value: MixinValue<AnyRole> | MixinConstructorParams[0],\n options?: MixinConstructorParams[1],\n location?: MixinConstructorParams[2],\n treeContext?: MixinConstructorParams[3]\n) => Mixin;\n","import { Node, defineType, F_VISIBLE, F_NON_STATIC, type NodeOptions, type OptionalLocation, type TreeContext } from './node.js';\nimport type { Context } from '../context.js';\nimport { Dimension } from './dimension.js';\nimport { type MaybePromise, pipe, tryStep } from '@jesscss/awaitable-pipe';\nimport { getPrintOptions, type PrintOptions } from './util/print.js';\n\nexport type NegativeChildData = { value: Node };\n\n/**\n * The negative sign before a node\n */\nexport interface Negative extends Node<Node, NodeOptions, NegativeChildData> {\n type: 'Negative';\n shortType: 'negative';\n eval(context: Context): MaybePromise<Node>;\n}\n\nexport class Negative extends Node<Node, NodeOptions, NegativeChildData> {\n static override childKeys = ['value'] as const;\n\n readonly value!: Node;\n\n constructor(value: Node, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n if (value instanceof Node) {\n this.adopt(value);\n }\n // Negative operations are always non-static, but can inherit may_async from children\n this.addFlags(F_VISIBLE, F_NON_STATIC);\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const value = this.get('value', options.context);\n\n w.add('-', this);\n value.toString(options);\n\n return w.getSince(mark);\n }\n\n override evalNode(context: Context): MaybePromise<Node> {\n return pipe(\n () => this.get('value', context).eval(context),\n tryStep((value: Node) => {\n if (!value.operate) {\n throw new TypeError(`Cannot operate on ${value.type}`);\n }\n return value.operate(new Dimension({ number: -1 }), '*', context);\n }, { rethrow: true })\n );\n }\n}\n\nexport const negative = defineType(Negative, 'Negative');\n","import { type Context } from '../context.js';\nimport { defineType, F_VISIBLE, Node, type LocationInfo, type OptionalLocation, type TreeContext } from './node.js';\nimport type { Any, AnyRole } from './any.js';\nimport { Any as AnyCtor } from './any.js';\nimport { Interpolated } from './interpolated.js';\nimport { Rules } from './rules.js';\nimport { type List, list } from './list.js';\nimport type { Declaration } from './declaration.js';\nimport type { VarDeclaration } from './declaration-var.js';\nimport { VarDeclaration as VarDeclarationCtor } from './declaration-var.js';\nimport { Nil } from './nil.js';\nimport { N } from './node-type.js';\nimport { isNode } from './util/is-node.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { getParent, getSourceParent, setChildren } from './util/field-helpers.js';\n\n/**\n * Stylesheet-defined function with a return value.\n * Called `Func` to avoid conflict with the built-in `Function` class.\n *\n * Parsed by Sass/Jess-like languages (e.g. SCSS `@function`).\n *\n * Evaluation model:\n * - Evaluate the function body in an isolated scope (like mixins) with bound params.\n * - Then look up a declaration by name (default: `return`) and return its value.\n */\nexport type FuncValue<Name extends AnyRole = 'name'> = {\n name?: Any<Name> | Interpolated<Name>;\n params?: List<Node>;\n body: Node;\n};\n\nexport type FuncOptions = {\n /**\n * Declaration name to look up after evaluating the body.\n * Defaults to `'return'` (a `return: <expr>;` declaration).\n */\n returnName?: string;\n};\n\nexport type FuncChildData = {\n name: FuncValue['name'];\n params: FuncValue['params'];\n body: Node;\n};\n\nexport interface Func extends Node<FuncValue, FuncOptions, FuncChildData> {\n type: 'Func';\n shortType: 'fn';\n}\n\nexport class Func extends Node<FuncValue, FuncOptions, FuncChildData> {\n static override childKeys = ['name', 'params', 'body'] as const;\n\n name: FuncValue['name'];\n params: FuncValue['params'];\n body!: Node;\n\n constructor(value: FuncValue, options?: FuncOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.name = value.name;\n this.params = value.params;\n this.body = value.body;\n if (this.name instanceof Node) {\n this.adopt(this.name);\n }\n if (this.params instanceof Node) {\n this.adopt(this.params);\n }\n if (this.body instanceof Node) {\n this.adopt(this.body);\n }\n this.removeFlag(F_VISIBLE);\n }\n\n get nameKey(): string | undefined {\n return this.getNameKey();\n }\n\n getNameKey(context?: Context): string | undefined {\n const name = this.get('name', context);\n if (!name) {\n return undefined;\n }\n return String(name.valueOf());\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n const name = this.get('name', context);\n const params = this.get('params', context);\n const body = this.get('body', context);\n\n w.add('$function', this);\n w.add(' ');\n w.add(name ? `${name}` : '@', this);\n w.add('(');\n if (params) {\n params.toString(options);\n }\n w.add(') ');\n\n // Body is always emitted as braced rules. If it's not a Rules node already, wrap it.\n const bodyRules = body instanceof Rules ? body : Rules.create([body]);\n bodyRules.toBraced(options);\n\n return w.getSince(mark);\n }\n\n /**\n * Execute the function and return its looked-up value.\n *\n * Functions follow the same scoped-body model as simple mixins:\n * bind args into an ephemeral param scope, evaluate one render-keyed body\n * wrapper, then read the return declaration from that evaluated scope.\n */\n async evalCall(context: Context, args: List<Node> = list([]), _contentNode?: Node): Promise<Node> {\n const returnName = this.options?.returnName ?? 'return';\n const name = this.get('name', context);\n const params = this.get('params', context);\n const bodyNode = this.get('body', context);\n const renderKey = context.nextRenderKey();\n const invocationParent = context.caller\n ? getParent(context.caller, context) ?? context.rulesContext\n : context.rulesContext ?? getParent(this, context);\n const callerSourceNode = context.caller && isNode(context.caller, N.Call) && context.caller.get('name') instanceof Node\n ? context.caller.get('name')\n : context.caller;\n const sourceParent = callerSourceNode\n ? getSourceParent(callerSourceNode as Node, context)\n : getSourceParent(this, context);\n const scope = this._createInvocationScope(params, args, renderKey, invocationParent, context);\n const bodyRules = this._createInvocationBodyRules(bodyNode, renderKey, scope ?? invocationParent, sourceParent, context);\n\n const previousRulesContext = context.rulesContext;\n const previousLookupScope = context.lookupScope;\n const previousRenderKey = context.renderKey;\n context.rulesContext = scope ?? bodyRules;\n context.lookupScope = scope ?? bodyRules;\n context.renderKey = renderKey;\n let evaluated: Rules;\n try {\n evaluated = await bodyRules.eval(context);\n } finally {\n context.rulesContext = previousRulesContext;\n context.lookupScope = previousLookupScope;\n context.renderKey = previousRenderKey;\n }\n\n if (!(evaluated instanceof Rules)) {\n throw new Error(`Function ${String(name?.valueOf() ?? '<anonymous>')} must evaluate to rules`);\n }\n\n const returnLookupOptions = { searchParents: false, context };\n const decl = evaluated.find('declaration', returnName, 'Declaration', returnLookupOptions) as Declaration | undefined\n ?? evaluated.find('declaration', returnName, 'VarDeclaration', returnLookupOptions) as VarDeclaration | undefined;\n if (!decl) {\n throw new Error(`Function ${String(name?.valueOf() ?? '<anonymous>')} must return a value (missing \"${returnName}: ...\")`);\n }\n context.rulesContext = scope ?? evaluated;\n context.lookupScope = scope ?? evaluated;\n context.renderKey = evaluated.renderKey;\n try {\n const returnValue = (decl as Declaration).get('value', context);\n return await returnValue.eval(context);\n } finally {\n context.rulesContext = previousRulesContext;\n context.lookupScope = previousLookupScope;\n context.renderKey = previousRenderKey;\n }\n }\n\n private _createInvocationScope(\n params: List<Node> | undefined,\n args: List<Node>,\n renderKey: symbol,\n parent: Node | undefined,\n context: Context\n ): Rules | undefined {\n if (!params) {\n return undefined;\n }\n const scope = Rules.create([], {\n rulesVisibility: {\n Ruleset: 'public',\n Declaration: 'public',\n VarDeclaration: 'public',\n Mixin: 'public'\n }\n });\n scope.renderKey = renderKey;\n scope.parent = parent;\n\n const invocationContext = {\n ...context,\n renderKey,\n rulesContext: scope,\n lookupScope: scope\n };\n const argItems = args.get('value', context);\n const paramItems = params.get('value', context);\n\n for (let i = 0; i < paramItems.length; i++) {\n const param = paramItems[i]!;\n if (!isNode(param, N.VarDeclaration)) {\n continue;\n }\n const boundParam = new VarDeclarationCtor({\n name: new AnyCtor(String(param.get('name', context).valueOf()), { role: 'property' }),\n value: new Nil()\n }, { ...(param.options ?? {}), paramVar: true }, param.location, this.treeContext);\n boundParam.index = param.index ?? -(i + 1);\n scope.push(boundParam);\n\n const boundValue = argItems[i] ?? param.get('value', context);\n if (boundValue) {\n boundParam.setCurrentValue(boundValue, invocationContext);\n }\n }\n\n return scope;\n }\n\n private _createInvocationBodyRules(\n bodyNode: Node,\n renderKey: symbol,\n parent: Node | undefined,\n sourceParent: Node | undefined,\n context: Context\n ): Rules {\n let bodyRules: Rules;\n if (bodyNode instanceof Rules) {\n bodyRules = bodyNode.createShallowBodyWrapper(undefined, renderKey);\n } else {\n bodyRules = Rules.create([], undefined, Array.isArray(this.location) && this.location.length === 6 ? (this.location as LocationInfo) : undefined, this.treeContext);\n bodyRules.renderKey = renderKey;\n setChildren(bodyRules, [bodyNode], { ...context, renderKey }, { markDirty: false });\n }\n bodyRules.parent = parent;\n bodyRules.sourceParent = sourceParent;\n bodyRules.index = this.index;\n return bodyRules;\n }\n}\n\nexport const fn = defineType(Func, 'Func', 'fn') as (\n value: FuncValue | { name?: string; params?: List<Node>; body: Node },\n options?: FuncOptions,\n location?: OptionalLocation,\n treeContext?: TreeContext\n) => Func;\n","import { Node, defineType } from './node.js';\n\n/**\n * A plain JS array.\n */\nexport interface JsArray {\n type: 'JsArray';\n shortType: 'jsarray';\n}\nexport class JsArray extends Node<readonly any[]> {\n static override childKeys = null as null;\n\n value!: readonly any[];\n\n constructor(value: readonly any[], options?: any, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.value = value;\n }\n}\n\nexport const jsarray = defineType(JsArray, 'JsArray', 'jsarray');","import { type Interpolated } from './interpolated.js';\nimport { Any } from './any.js';\nimport { Node, F_STATIC, F_NON_STATIC, defineType, type OptionalLocation, type TreeContext } from './node.js';\nimport type { Context } from '../context.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\n\nexport type QuotedOptions = {\n quote?: '\"' | '\\'';\n escaped?: boolean;\n};\n\nexport type QuotedChildData = { value: string | Any | Interpolated };\n\nexport interface Quoted extends Node<string | Any | Interpolated, QuotedOptions, QuotedChildData> {\n type: 'Quoted';\n shortType: 'quoted';\n eval(context: Context): MaybePromise<Quoted | Any | Interpolated>;\n}\n\n/**\n * A quoted string value. Called a `String` in CSS, but calling it Quoted\n * to avoid conflict with the built-in `String` class.\n */\nexport class Quoted extends Node<string | Any | Interpolated, QuotedOptions, QuotedChildData> {\n static override childKeys = ['value'] as const;\n\n value!: string | Any | Interpolated;\n readonly quote: '\"' | '\\'' | undefined;\n readonly escaped: boolean;\n\n constructor(value: string | Any | Interpolated, options?: QuotedOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n this.quote = options?.quote;\n this.escaped = !!options?.escaped;\n if (value instanceof Node) {\n this.adopt(value);\n }\n if (typeof value === 'string' && !this.escaped) {\n this.addFlag(F_STATIC);\n } else {\n this.addFlag(F_NON_STATIC);\n }\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const value = this.value;\n let { quote = '\"', escaped } = this;\n let escapeChar = escaped ? '~' : '';\n if (escapeChar) {\n w.add(escapeChar, this);\n }\n w.add(quote);\n if (value instanceof Node) {\n value.toString(options);\n } else if (value !== undefined && value !== '') {\n w.add(String(value), this);\n }\n w.add(quote);\n return w.getSince(mark);\n }\n\n override valueOf(): string {\n const value = this.value;\n return value instanceof Node ? value.valueOf() : value as string;\n }\n\n override compare(other: Node): 0 | 1 | -1 | undefined {\n if (other.type === 'Quoted' && !this.escaped && !(other as Quoted).escaped) {\n const left = String(this.valueOf());\n const right = String(other.valueOf?.() ?? '');\n if (left === right) {\n return 0;\n }\n return left > right ? 1 : -1;\n }\n return typeof other.toString === 'function' && this.toString() === other.toString() ? 0 : undefined;\n }\n\n override evalNode(context: Context): MaybePromise<Quoted | Any | Interpolated> {\n const originalValue = this.value;\n let value: string | Any | Interpolated | Node = originalValue;\n const cont = (v: string | Any | Interpolated | Node): Quoted | Any | Interpolated => {\n value = v;\n if (this.escaped) {\n if (value instanceof Node) {\n return value as Node as Quoted | Any | Interpolated;\n }\n return new Any(value as string);\n }\n if (value === originalValue) {\n return this;\n }\n const quoted = this.clone();\n if (originalValue instanceof Node) {\n originalValue.parent = this;\n }\n quoted.value = value as string | Any | Interpolated;\n if (value instanceof Node) {\n quoted.adopt(value);\n }\n return quoted;\n };\n if (value instanceof Node) {\n const out = value.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Node | Any | Interpolated>).then(cont);\n }\n return cont(out as Node | Any | Interpolated);\n }\n return cont(value as string | Any | Interpolated);\n }\n}\n\nexport const quoted = defineType(Quoted, 'Quoted');\n","import type { Context } from '../context.js';\nimport { Node, defineType, type OptionalLocation, type TreeContext } from './node.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\n\nexport type RangeValue = {\n start: Node;\n end: Node;\n step?: Node;\n};\n\nexport type RangeOptions = {\n /** If false, serialize as `1> to ...` */\n includeStart?: boolean;\n /** If false, serialize as `... to <3` */\n includeEnd?: boolean;\n};\n\nexport type RangeChildData = { start: Node; end: Node; step: Node | undefined };\n\n/**\n * A numeric-ish range expression intended for `$for` headers.\n *\n * Examples:\n * - `1 to 3` (inclusive start/end)\n * - `1 to <3` (exclusive end)\n * - `1> to 3` (exclusive start)\n * - `1> to <10 step 2`\n */\nexport interface Range {\n type: 'Range';\n shortType: 'range';\n}\n\nexport class Range extends Node<RangeValue, RangeOptions, RangeChildData> {\n static override childKeys = ['start', 'end', 'step'] as const;\n\n start!: Node;\n end!: Node;\n step: Node | undefined;\n\n constructor(value: RangeValue, options?: RangeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.start = value.start;\n this.end = value.end;\n this.step = value.step;\n if (this.start instanceof Node) {\n this.adopt(this.start);\n }\n if (this.end instanceof Node) {\n this.adopt(this.end);\n }\n if (this.step instanceof Node) {\n this.adopt(this.step);\n }\n }\n\n override evalNode(_context: Context): Range {\n return this;\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n const start = this.get('start', context);\n const end = this.get('end', context);\n const step = this.get('step', context);\n const includeStart = this.options?.includeStart !== false;\n const includeEnd = this.options?.includeEnd !== false;\n\n const emitTrimmed = (n: Node) => {\n const s = w.capture(() => n.toString(options));\n w.add(s.replace(/^[ \\t\\r\\f]+|[ \\t\\r\\f]+$/g, ''), n);\n };\n\n emitTrimmed(start);\n if (!includeStart) {\n w.add('>');\n }\n w.add(' to ');\n if (!includeEnd) {\n w.add('<');\n }\n emitTrimmed(end);\n if (step) {\n w.add(' step ');\n emitTrimmed(step);\n }\n return w.getSince(mark);\n }\n}\n\ntype RangeParams = ConstructorParameters<typeof Range>;\n\nexport const range = defineType(Range, 'Range', 'range') as (\n value: RangeParams[0],\n options?: RangeParams[1],\n location?: RangeParams[2],\n treeContext?: RangeParams[3]\n) => Range;\n","import { defineType } from './node.js';\nimport { Rules } from './rules.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { getChildren } from './util/field-helpers.js';\n\n/**\n * A rules container that emits its content verbatim inside braces,\n * without parent-managed newlines or indentation.\n */\nexport interface RawRules {\n type: 'RawRules';\n shortType: 'rules-raw';\n}\nexport class RawRules extends Rules {\n constructor(...args: ConstructorParameters<typeof Rules>) {\n super(...args);\n this.allowRuleRoot = true;\n }\n\n // Do not add newlines/indent; emit children exactly as-is\n override toBraced(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const children = options.context\n ? getChildren(this, options.context)\n : this.value;\n w.add('{');\n // Emit children using toString to preserve exact whitespace/comments\n for (const child of children) {\n child.toString(options);\n }\n w.add('}');\n return w.getSince(mark);\n }\n\n // Keep trimmed output minimal – emit children verbatim without extras\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const children = options.context\n ? getChildren(this, options.context)\n : this.value;\n for (const child of children) {\n child.toString(options);\n }\n return w.getSince(mark);\n }\n}\n\nexport const rawrules = defineType(RawRules, 'RawRules', 'rules-raw');\n","import type { MaybePromise } from 'awaitable-pipe/lib/utils';\nimport { defineType, type Node } from './node.js';\nimport { Rules } from './rules.js';\nimport { getPrintOptions, type PrintOptions } from './util/print.js';\nimport type { Context } from '../context.js';\n\n/**\n * A collection is essentially like an anonymous mixin,\n * except that properties are arbitrary, so its intended\n * for map data.\n *\n * Even though it doesn't allow everything that a regular set\n * of rules does, we extend Rules just to make evaluation easier.\n *\n * Can be used like Sass property nesting.\n * @see https://sass-lang.com/documentation/style-rules/declarations/#nesting\n */\nexport interface Collection {\n type: 'Collection';\n shortType: 'coll';\n}\n\nexport class Collection extends Rules {\n override toTrimmedString(options?: PrintOptions) {\n return this.toBraced(options);\n }\n\n /**\n * Collection rules aren't evaluated by default. They're evaluated\n * at access time OR if assigned to a property.\n */\n override evalNode(context: Context): MaybePromise<this> {\n return this;\n }\n\n override preEval(context: Context): this | Promise<this> {\n if (this.preEvaluated) {\n return this;\n }\n this.preEvaluated = true;\n return this;\n }\n}\n\ntype Params = ConstructorParameters<typeof Collection>;\n\nexport const coll = defineType(Collection, 'Collection', 'coll') as (\n value: Params[0],\n options?: Params[1],\n location?: Params[2],\n treeContext?: Params[3]\n) => Collection;\n","import type { Class } from 'type-fest';\nimport { defineType, type OptionalLocation, Node, type NodeOptions } from './node.js';\nimport { type TreeContext } from '../context.js';\nimport { SimpleSelector } from './selector-simple.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport type { Context } from '../context.js';\nimport { isThenable, type MaybePromise } from '@jesscss/awaitable-pipe';\n\nexport type AttributeSelectorValue = {\n /** The name of the attribute */\n name: string | Node;\n /** The operator */\n op?: string;\n /** The value of the attribute */\n value?: Node;\n /** The modifier (case insensitivity) */\n mod?: string;\n};\n\nexport type AttributeSelectorChildData = {\n name: string | Node;\n op: string | undefined;\n value: Node | undefined;\n mod: string | undefined;\n};\n\n/**\n * An attribute selector\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors\n * e.g. [id=\"foo\"]\n*/\nexport interface AttributeSelector {\n type: 'AttributeSelector';\n shortType: 'attr';\n}\n\nexport class AttributeSelector extends SimpleSelector<AttributeSelectorValue, NodeOptions, AttributeSelectorChildData> {\n static override childKeys = ['name', 'value'] as const;\n\n name!: string | Node;\n private op: string | undefined;\n value: Node | undefined;\n private mod: string | undefined;\n\n override clone(deep?: boolean): this {\n const newNode = new (this.constructor as Class<this>)(\n {\n name: deep && this.name instanceof Node ? this.name.clone(deep) : this.name,\n op: this.op,\n value: deep && this.value instanceof Node ? this.value.clone(deep) : this.value,\n mod: this.mod\n },\n undefined,\n this.location,\n this.treeContext\n );\n newNode.inherit(this);\n return newNode;\n }\n\n constructor(data: AttributeSelectorValue, options?: undefined, location?: OptionalLocation, treeContext?: TreeContext) {\n super(data, options, location, treeContext);\n this.name = data.name;\n this.op = data.op;\n this.value = data.value;\n this.mod = data.mod;\n if (this.name instanceof Node) {\n this.adopt(this.name as Node);\n }\n if (this.value instanceof Node) {\n this.adopt(this.value);\n }\n }\n\n private _setName(name: string | Node, context?: Context): void {\n if (name instanceof Node) {\n this.adopt(name, context);\n }\n this.name = name;\n }\n\n private _setValue(value: Node | undefined, context?: Context): void {\n if (value instanceof Node) {\n this.adopt(value, context);\n }\n this.value = value;\n }\n\n override evalNode(context: Context): MaybePromise<this> {\n const currentName = this.get('name', context);\n const currentValue = this.get('value', context);\n const maybeName = typeof currentName === 'string'\n ? currentName\n : currentName.eval(context);\n const maybeValue = currentValue?.eval(context);\n const finish = (name: string | Node, value: Node | undefined): this => {\n const node = this.clone();\n\n if (name !== currentName) {\n node._setName(name, context);\n }\n if (value !== currentValue) {\n node._setValue(value, context);\n }\n\n return node;\n };\n\n if (isThenable(maybeName) || isThenable(maybeValue)) {\n return Promise.all([\n Promise.resolve(maybeName),\n Promise.resolve(maybeValue)\n ]).then(([name, value]) => finish(name, value));\n }\n\n return finish(maybeName as string | Node, maybeValue as Node | undefined);\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n const name = this.get('name', context);\n const value = this.get('value', context);\n const op = this.get('op');\n const mod = this.get('mod');\n w.add('[');\n if (typeof name === 'string') {\n w.add(name, this);\n } else {\n name.toString(options);\n }\n if (op) {\n w.add(op);\n }\n if (value) {\n value.toString(options);\n }\n if (mod) {\n w.add(' ');\n w.add(mod);\n }\n w.add(']');\n return w.getSince(mark);\n }\n\n override valueOf() {\n let valueOf = this._valueOf;\n if (!valueOf) {\n let name = this.name;\n let op = this.op;\n let value = this.value;\n let mod = this.mod;\n let keyStr = (typeof name === 'string' ? name : name.toTrimmedString()).toLowerCase();\n if (!op) {\n return `[${keyStr}]`;\n }\n let valueStr = value?.valueOf() ?? '';\n valueOf = this._valueOf = `[${keyStr}${op}\"${valueStr}\"${mod ? ` ${mod}` : ''}]`;\n }\n return valueOf;\n }\n}\n\n/** Not sure why types couldn't be properly inferred */\nexport const attr = defineType<AttributeSelectorValue>(AttributeSelector, 'AttributeSelector', 'attr') as (\n value: AttributeSelectorValue,\n options?: undefined,\n location?: OptionalLocation | 0,\n treeContext?: TreeContext\n) => AttributeSelector;\n","import { type Context } from '../context.js';\nimport { Node, defineType, type OptionalLocation, type NodeOptions, type TreeContext } from './node.js';\nimport { Selector } from './selector.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\n\nexport type SelectorCaptureChildData = { value: Selector };\n\nexport interface SelectorCapture extends Node<Selector, NodeOptions, SelectorCaptureChildData> {\n type: 'SelectorCapture';\n shortType: 'selcap';\n eval(context: Context): MaybePromise<Selector>;\n}\n\n/**\n * Explicit selector-capture wrapper used by parsers for selector-valued payloads\n * (e.g. Less `*[ ... ]`, Sass `selector.parse(\"...\")`).\n */\nexport class SelectorCapture extends Node<Selector, NodeOptions, SelectorCaptureChildData> {\n static override childKeys = ['value'] as const;\n\n readonly value!: Selector;\n\n constructor(value: Selector, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n if (this.value instanceof Node) {\n this.adopt(this.value);\n }\n }\n\n override valueOf(): string {\n return String(this.value.valueOf());\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const value = this.value;\n w.add('*[', this);\n value.toString(options);\n w.add(']', this);\n return w.getSince(mark);\n }\n\n override preEval(context: Context): MaybePromise<this> {\n if (this.preEvaluated) {\n return this;\n }\n const node = this.clone() as this;\n node.preEvaluated = true;\n const applyValue = (preEvald: Selector): this => {\n if (node.value !== preEvald) {\n node.adopt(preEvald, context);\n (node as unknown as { value: Selector }).value = preEvald;\n }\n return node;\n };\n const out = this.value.preEval(context);\n if (isThenable(out)) {\n return (out as Promise<Selector>).then(applyValue);\n }\n return applyValue(out as Selector);\n }\n\n override evalNode(context: Context): MaybePromise<Selector> {\n const out = this.value.eval(context);\n if (isThenable(out)) {\n return (out as Promise<Selector>).then((selector) => {\n return selector;\n });\n }\n return out as Selector;\n }\n}\n\ntype Params = ConstructorParameters<typeof SelectorCapture>;\n\nexport const selcap = defineType(SelectorCapture, 'SelectorCapture', 'selcap') as (\n value: Params[0],\n options?: Params[1],\n location?: Params[2],\n treeContext?: Params[3]\n) => SelectorCapture;\n","import type { Context } from '../context.js';\nimport type { PrintOptions } from '..';\nimport { getPrintOptions } from './util/print.js';\nimport { defineType } from './node.js';\nimport { Sequence } from './sequence.js';\n\n/**\n * Used by `@media`, `@supports`, and `@container`\n *\n * This just helps identify conditions if we need to\n * merge them later.\n *\n * @todo - add more structure?\n */\nexport interface QueryCondition {\n type: 'QueryCondition';\n shortType: 'query';\n}\n\nexport class QueryCondition extends Sequence {\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n let value = this.get('value', options.context);\n let length = value.length;\n\n if (length === 0) {\n return '';\n }\n\n // Print first node as-is\n let node = value[0]!;\n let out = w.capture(() => node.toString(options));\n w.add(out.replace(/^\\s*|\\s*$/g, ''), node);\n\n // Space out sub-nodes\n for (let i = 1; i < length; i++) {\n let node = value[i]!;\n w.add(' ');\n let out = w.capture(() => node.toString(options));\n w.add(out.replace(/^\\s*|\\s*$/g, ''), node);\n }\n return w.getSince(mark);\n }\n}\nexport const query = defineType(QueryCondition, 'QueryCondition', 'query');\n","import { Node, defineType, type NodeOptions, type OptionalLocation, type TreeContext } from './node.js';\nimport { type Quoted } from './quoted.js';\nimport { type Any } from './any.js';\nimport { getPrintOptions, type PrintOptions } from './util/print.js';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport type { Context } from '../context.js';\nimport { isThenable, type MaybePromise } from '@jesscss/awaitable-pipe';\nimport { Reference } from './reference.js';\n\nexport type UrlChildData = { value: Quoted | Any };\n\n/**\n * e.g. url('foo.png')\n */\nexport interface Url {\n type: 'Url';\n shortType: 'url';\n eval(context: Context): MaybePromise<Url>;\n}\n\nexport class Url extends Node<Quoted | Any, NodeOptions, UrlChildData> {\n static override childKeys = ['value'] as const;\n\n value!: Quoted | Any;\n\n constructor(value: Quoted | Any, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n if (value instanceof Node) {\n this.adopt(value);\n }\n }\n\n /**\n * @todo - enable URL rewriting\n */\n // NOTE: `valueOf()` intentionally remains canonical for now. Import-path\n // consumers currently call it without a Context channel, so a state-aware\n // answer would require either plumbing Context into that observer or changing\n // the eval contract to return a materialized Url value for those callers.\n override valueOf(): string {\n return this.pathValue();\n }\n\n pathValue(context?: Context): string {\n let value: string | Quoted | Any = this.value;\n\n if (isNode(value, N.Quoted)) {\n value = value.get('value') as string | Quoted | Any;\n if (isNode(value)) {\n return String(value);\n }\n return value as string;\n }\n return String(value);\n }\n\n override evalNode(context: Context): MaybePromise<Url> {\n const value = this.value;\n let effectiveValue: Quoted | Any = value;\n if (isNode(value, N.Any)) {\n const rawValue = String(value.valueOf());\n if (/^@[\\w-]+$/.test(rawValue)) {\n effectiveValue = new Reference(rawValue.slice(1), { type: 'variable' });\n } else if (/^\\$[\\w-]+$/.test(rawValue)) {\n effectiveValue = new Reference(rawValue.slice(1), { type: 'property' });\n }\n }\n const finish = (nextValue: Quoted | Any): Url => {\n if (nextValue !== value) {\n this.value = nextValue;\n }\n return this;\n };\n const maybeEvald = effectiveValue.eval(context) as MaybePromise<Quoted | Any>;\n if (isThenable(maybeEvald)) {\n return (maybeEvald as Promise<Quoted | Any>).then(finish);\n }\n return finish(maybeEvald as Quoted | Any);\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const value = this.value;\n w.add('url(');\n value.toString(options);\n w.add(')');\n return w.getSince(mark);\n }\n}\n\nexport const url = defineType(Url, 'Url');\n","import { Node, F_MAY_ASYNC, F_NON_STATIC, F_VISIBLE, defineType } from './node.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type Reference } from './reference.js';\nimport { Rules, type RulesOptions, type RulesVisibility } from './rules.js';\nimport { Quoted } from './quoted.js';\nimport { Url } from './url.js';\nimport { type Context } from '../context.js';\nimport { type MaybePromise } from '@jesscss/awaitable-pipe';\nimport { isNode } from './util/is-node.js';\nimport { N } from './node-type.js';\nimport { getParent, getChildren, setIndex } from './util/field-helpers.js';\nimport type { Collection } from './collection.js';\nimport { Any } from './any.js';\nimport { AtRule } from './at-rule.js';\nimport { Sequence } from './sequence.js';\n\n/**\n * This class is for Jess / Sass+ / Less-style imports,\n * not the CSS `@import` rule. The two will be distinguished\n * during parsing.\n *\n * @see https://sass-lang.com/documentation/at-rules/import/#plain-css-imports\n */\n\nexport type ImportOptions = {\n /**\n * Affects evaluation - will be passed to registered import handlers when parsing.\n * Normally this is done by file extension, but can be overridden to select a\n * particular plugin handler.\n *\n * e.g. `@-import (type: less) 'foo.css';`\n */\n type?: string;\n /** Rules are not rendered in output. */\n reference?: boolean;\n optional?: boolean;\n inline?: boolean;\n /**\n * Optional import postlude captured by parsers for forms like:\n * `@import (inline) \"x.css\" layer(foo) supports(display: grid) screen;`\n *\n * For inline imports, this is applied as serializer wrappers around the inlined source.\n */\n postlude?: Node;\n /**\n * Less's default behavior for `@import` is to only output any resolved resource once.\n * In Jess, subsequent imports should output as reference unless the `multiple` option\n * is set to true.\n *\n * @todo - Investigate what Sass does.\n */\n multiple?: boolean;\n /**\n * Allow extends to reach into this import.\n * Default is false for @-compose (protected by default), true for @-import.\n */\n mutable?: boolean;\n /**\n * Sass `@forward` semantics:\n * - members are NOT visible to the current stylesheet scope\n * - members ARE made available downstream when this stylesheet is imported\n */\n forward?: boolean;\n /**\n * Sass `@forward ... as <prefix>-*;` prefixing.\n * Stores the prefix portion (e.g. `bar-` from `bar-*`).\n */\n forwardAsPrefix?: string;\n /**\n * Sass `@forward ... show ...;` list.\n * We capture raw member names (e.g. `$a`, `mixin-b`, `fn-c`) without semantics yet.\n */\n forwardShow?: string[];\n /**\n * Sass `@forward ... hide ...;` list.\n * We capture raw member names (e.g. `$a`, `mixin-b`, `fn-c`) without semantics yet.\n */\n forwardHide?: string[];\n /** Variables can't be reassigned (default is true for `@-compose` and false for `@-import`). */\n readonly?: boolean;\n /** Internal marker for \"once\" de-duplication rendering semantics. */\n _dedupe?: boolean;\n [key: string]: unknown;\n};\n\nexport type StyleImportOptions = {\n /**\n * Old-style `@import` type or new `@-compose` type.\n */\n type: 'import' | 'compose';\n\n /**\n * Options passed to the Jess import plugin. Options are interpreted like\n * querystring parameters i.e.\n * e.g. `@-import (foo, bar, baz: 1) 'foo.css';`\n * - foo: true\n * - bar: true\n * - baz: '1'\n */\n importOptions?: ImportOptions;\n\n /** e.g. `import * as foo` sets namespace to `foo` */\n namespace?: string;\n\n /** Set on the import node instead of on rules */\n local?: boolean;\n rulesVisibility?: RulesOptions['rulesVisibility'];\n};\n\nexport type StyleImportValue = {\n path: Quoted | Url;\n\n /** The node to inject values from (Reference or Collection). */\n withNode?: Reference | Collection;\n\n /**\n * How the injected values are applied.\n * 'set' can be used once per module, 'with' can be used multiple.\n * In Sass, 'set' is called 'with' and 'with' will be parsed as 'set'.\n * e.g.\n * `@-use 'library' set { $foo: 1 };` -- $foo will be set to 1 every time\n * `@-use 'library' with { $foo: 1 };` -- $foo will be set to 1 just for this scope.\n */\n withType?: 'with' | 'set';\n};\n\nexport type StyleImportChildData = {\n path: Quoted | Url;\n withNode: Reference | Collection | undefined;\n withType: 'with' | 'set' | undefined;\n};\n\nexport interface StyleImport extends Node<StyleImportValue, StyleImportOptions, StyleImportChildData> {\n type: 'StyleImport';\n shortType: 'style';\n eval(context: Context): MaybePromise<Rules>;\n}\n\nfunction isWithRulesNode(value: Node): value is Rules | Collection {\n return isNode(value, N.Rules | N.Collection);\n}\n\nfunction isPlainCssImportPath(finalPath: string, importOptions: ImportOptions | undefined): boolean {\n if (importOptions?.inline === true) {\n return false;\n }\n const explicitType = typeof importOptions?.type === 'string'\n ? importOptions.type.toLowerCase()\n : undefined;\n if (explicitType === 'css') {\n return true;\n }\n if (explicitType === 'less') {\n return false;\n }\n if (explicitType) {\n return false;\n }\n const normalizedPath = finalPath.split(/[?#]/)[0] ?? finalPath;\n if (/\\.less$/i.test(normalizedPath)) {\n return false;\n }\n return /\\.css$/i.test(normalizedPath) || /^(?:[a-z][a-z0-9+.-]*:)?\\/\\//i.test(finalPath);\n}\n\nfunction materializeCssImportPathNode(\n resolvedPathNode: Quoted | Url,\n finalPath: string,\n context: Context\n): Quoted | Url {\n if (resolvedPathNode instanceof Url) {\n const rawValue = resolvedPathNode.get('value', context);\n const nextValue = isNode(rawValue, N.Quoted)\n ? new Quoted(finalPath, {\n quote: rawValue.quote,\n escaped: rawValue.escaped\n }, rawValue.location, rawValue.treeContext)\n : new Any(finalPath, { role: 'urlvalue' }, rawValue.location, rawValue.treeContext);\n return new Url(nextValue, undefined, resolvedPathNode.location, resolvedPathNode.treeContext);\n }\n\n return new Quoted(finalPath, {\n quote: resolvedPathNode.quote,\n escaped: resolvedPathNode.escaped\n }, resolvedPathNode.location, resolvedPathNode.treeContext);\n}\n/**\n * This is a generic class for:\n * - Sass+ `@use` (for stylesheets)\n * - Jess `@-compose` and Less `@compose`\n * - Less, Sass+, and Jess `@import` / `@-import` that are indicated\n * to be processed by the engine\n *\n * @see https://sass-lang.com/documentation/at-rules/import/\n */\nexport class StyleImport extends Node<StyleImportValue, StyleImportOptions, StyleImportChildData> {\n static override childKeys = ['path', 'withNode'] as const;\n\n readonly path!: Quoted | Url;\n readonly withNode: Reference | Collection | undefined;\n private withType: 'with' | 'set' | undefined;\n\n override clone(deep?: boolean): this {\n const options = this._meta?.options;\n const newNode: this = Reflect.construct(this.constructor, [\n {\n path: deep ? this.path.clone(deep) : this.path,\n withNode: deep && this.withNode instanceof Node ? this.withNode.clone(deep) : this.withNode,\n withType: this.withType\n },\n options ? { ...options } : undefined,\n this.location,\n this.treeContext\n ]);\n newNode.inherit(this);\n return newNode;\n }\n\n constructor(value: StyleImportValue, options?: StyleImportOptions, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.path = value.path;\n this.withNode = value.withNode;\n this.withType = value.withType;\n if (this.path instanceof Node) {\n this.adopt(this.path);\n }\n if (this.withNode instanceof Node) {\n this.adopt(this.withNode);\n }\n this.addFlags(F_MAY_ASYNC, F_NON_STATIC);\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const path = this.get('path', options.context);\n const { type, namespace, importOptions } = this.options;\n\n if (type === 'compose') {\n const keyword = importOptions?.forward ? '@-export' : '@-compose';\n w.add(`${keyword} `);\n } else {\n w.add('@-import ');\n }\n path.toString(options);\n if (namespace) {\n w.add(` as ${namespace}`);\n }\n w.add(';');\n return w.getSince(mark);\n }\n\n /** @removal-target — node-copy-reduction: clone(true) on prelude nodes.\n * Prelude should be read from canonical + position patches. */\n private materializePostludePrelude(current: Node, context: Context): {\n atRuleName: '@media' | '@supports' | '@layer';\n prelude: Node;\n } {\n if (isNode(current, N.Call)) {\n const callName = String(current.get('name')).toLowerCase();\n if (callName === 'media' || callName === 'supports' || callName === 'layer') {\n const args = current.get('args')?.get('value') ?? [];\n const prelude = args.length <= 1 ? args[0] : current.get('args');\n if (prelude) {\n return {\n atRuleName: `@${callName}` as '@media' | '@supports' | '@layer',\n prelude: prelude.clone(false, undefined, context)\n };\n }\n }\n }\n\n return {\n atRuleName: '@media',\n prelude: current.clone(false, undefined, context)\n };\n }\n\n private createPlacementRules(rules: Rules, context: Context): Rules {\n const placementRenderKey = context.nextRenderKey();\n return rules.createPlacementWrapper(context, placementRenderKey);\n }\n\n getFinalRules(evaluatedRules: Rules, context: Context) {\n let { importOptions, type } = this.options;\n const reference = importOptions!.reference;\n const isForward = importOptions!.forward === true;\n // For compose type, default is protected (not mutable). For import type, default is mutable.\n // mutable: false on @import explicitly makes it protected.\n const isProtected = type === 'compose'\n ? !importOptions!.mutable // compose: protected unless mutable: true\n : importOptions!.mutable === false; // import: mutable unless explicitly mutable: false\n\n let Ruleset: RulesVisibility = 'public';\n let Declaration: RulesVisibility = 'public';\n let Mixin: RulesVisibility = 'public';\n let VarDeclaration: RulesVisibility = 'public';\n\n const isImplicitDedupeReference = (\n type === 'import'\n && importOptions?._dedupe === true\n && reference !== true\n && !importOptions?.multiple\n );\n\n if (isProtected) {\n Ruleset = 'private';\n } else if (reference || isImplicitDedupeReference) {\n /**\n * Not sure if this is true.\n * They won't be output, but that's not the same as being optional,\n * UNLESS we're extending the word 'optional' to mean \"not output\".\n *\n * I think what we mean here by \"optional\" it \"not ouptut unless extended\".\n * Our test for reference therefore should mimic Less behavior.\n */\n Ruleset = 'optional';\n }\n\n /**\n * Create a rules wrapper so we can set visibility.\n * The inner rules may be static, but the import may\n * have different import settings.\n *\n * For compose type:\n * - Variables and mixins are visible to the direct parent (the file that imports them)\n * - If 'export' flag is set, variables and mixins are also forwarded to downstream stylesheets\n * - The 'local' flag means: visible to direct parent, but not re-exported to parent's parent\n */\n const isReferenceMode = (\n (type === 'import' && (importOptions?._dedupe === true || reference))\n || (type === 'compose' && reference)\n );\n const materializeConfiguredComposeChildren = type === 'compose' && this.get('withNode', context) != null;\n // Every import placement gets its own render-owned Rules wrapper so the same\n // source module can be imported multiple times without clone-driven cleanup.\n const out = evaluatedRules.sourceNode === this\n ? evaluatedRules\n : evaluatedRules.createPlacementWrapper(context, context.nextRenderKey());\n if (materializeConfiguredComposeChildren) {\n const placementContext: Context = { ...context, renderKey: out.renderKey, rulesContext: out };\n const children = getChildren(out, placementContext);\n for (let i = 0; i < children.length; i++) {\n setIndex(children[i]!, i, placementContext);\n }\n }\n // Import type: variables are visible and re-exported (not local)\n // Compose type: variables are visible to parent but not transitive by default (`local: true`)\n // Forward: not visible locally but *is* transitive (`local: false`)\n const isLocal = type === 'compose' && !isForward;\n\n out.options = {\n rulesVisibility: { Ruleset, Declaration, Mixin, VarDeclaration },\n local: isLocal,\n forward: isForward,\n referenceMode: isReferenceMode,\n referenceRenderOnExtend: reference === true,\n readonly: importOptions!.readonly ?? (type === 'compose' ? true : false)\n };\n // Forwarded modules should never render output at this scope.\n if (isForward) {\n out.removeFlag(F_VISIBLE);\n }\n // Set sourceNode so variable lookups know they can cross import boundaries\n out.sourceNode = this;\n this.adopt(out, context);\n return out;\n }\n\n /**\n * Defer import-path interpolation to evalNode so unresolved vars can be retried\n * after later imports/assignments in the same Rules scope have evaluated.\n */\n override preEval(_context: Context): MaybePromise<this> {\n return this;\n }\n\n /**\n * @note\n * When imports are evaluated, they should be deeply cloned. The reason is that\n * they can be used in multiple places, and can be evaluated differently\n * each time, so they are more like a function call.\n *\n * @todo\n * How do extends work then?\n */\n override evalNode(context: Context): MaybePromise<Rules> {\n let node = this;\n const path = node.get('path', context);\n const withNode = node.get('withNode', context);\n const withType = node.get('withType', context);\n let withValues = withNode != null ? { node: withNode, type: withType! } : undefined;\n const { options } = node;\n options.importOptions ??= {};\n const { type, importOptions } = options;\n let maybePath;\n try {\n maybePath = path.eval(context);\n } catch (e: any) {\n // Tag path-resolution errors so the eval-queue retry policy can\n // distinguish \"path interpolation not ready\" (cheap, worth retrying)\n // from \"content evaluation failed\" (expensive clone, not worth retrying).\n e._isPathResolutionError = true;\n throw e;\n }\n let originalDepth = context.depth;\n context.depth = this.depth;\n\n /**\n * @todo - Add options\n *\n * Note that the Less plugin should trigger a unique default behavior\n * for `@import` which is that it is de-duplicated by default. Meaning\n * that it won't render rulesets twice per compilation. I think that\n * means that it's just kind of ignored without an explicit `multiple`\n * option. Since all vars are global per compilation, it should just\n * work.\n */\n\n const finalize = async (finalPath: string, resolvedPathNode: Quoted | Url) => {\n const previousTreeContext = context.treeContext;\n // Inherit \"reference branch\" semantics lexically for nested imports unless\n // `multiple` explicitly opts into fresh output.\n const inheritedReferenceMode = context.inReferenceImportScope;\n const previousExplicitReference = importOptions!.reference;\n let pushedImportScope = false;\n if (inheritedReferenceMode && !importOptions!.multiple) {\n importOptions!.reference = true;\n }\n if (node.treeContext?.file) {\n context.treeContext = node.treeContext;\n }\n if (importOptions!.multiple || importOptions!.reference) {\n // Scope push/pop is intentionally paired in this method's try/finally.\n // This keeps branch semantics local to this import evaluation path.\n context.pushImportScope({\n multiple: importOptions!.multiple === true,\n reference: importOptions!.reference === true\n });\n pushedImportScope = true;\n }\n try {\n const isInlineImport = importOptions!.inline === true;\n let rules: Rules;\n let resolvedPath: string;\n if (type === 'import' && isPlainCssImportPath(finalPath, importOptions)) {\n const pathPreludeNode = materializeCssImportPathNode(resolvedPathNode, finalPath, context);\n const postlude = importOptions!.postlude;\n const prelude = postlude\n ? new Sequence(\n [\n pathPreludeNode,\n ...(isNode(postlude, N.Sequence | N.List) ? postlude.get('value', context) : [postlude])\n ],\n undefined,\n undefined,\n context.treeContext\n )\n : pathPreludeNode;\n const cssImport = new AtRule({\n name: new Any('@import', { role: 'atkeyword' }),\n prelude\n });\n await cssImport.preEval(context);\n return Rules.create([]);\n }\n if (isInlineImport) {\n const resolved = await context.resolveImportPath(finalPath);\n resolvedPath = resolved.resolvedPath;\n const sourceGetter = context.plugins.find(plugin => plugin.getSource);\n if (!sourceGetter) {\n throw new Error('No source getter found');\n }\n const source = await sourceGetter.getSource!(resolvedPath);\n const sourceNode = new Any(source, { role: 'any' });\n rules = this.wrapInlineSourceWithPostlude(sourceNode, importOptions!.postlude, context);\n } else {\n try {\n ({ node: rules, resolvedPath } = await context.getTree(finalPath, importOptions));\n } catch (error: any) {\n if (importOptions!.optional) {\n return Rules.create([]);\n }\n if (importOptions!.reference && (error?.phase === 'parse' || String(error?.code ?? '').startsWith('parse/'))) {\n return Rules.create([]);\n }\n throw error;\n }\n }\n // Set sourceNode immediately after getting the Rules, before any evaluation\n // This ensures that when preEval clones the Rules, the cloned Rules will have sourceNode set\n // and registerNode can detect this is an imported Rules\n rules.sourceNode = node;\n let evaldRules = context.evaldTrees.get(resolvedPath);\n\n // Compose caching semantics:\n // - The first time a module is composed, we evaluate and cache the evaluated Rules.\n // - Subsequent compose imports reuse the cached evaluated Rules (so re-imports don't re-run evaluation).\n // - Subsequent compose imports default to \"reference\" mode unless `multiple: true` is set,\n // so rulesets / at-rules are not output again.\n const cachedSetValues = context.composeSetValues.get(resolvedPath);\n const needsFreshSetBaselinePlacement = (\n type === 'compose'\n && evaldRules != null\n && cachedSetValues != null\n && withValues == null\n && importOptions!.multiple === true\n );\n if (type === 'compose' && evaldRules) {\n if (withValues?.type === 'set') {\n // `set` establishes the cached module baseline and cannot be applied twice.\n throw new Error('Cannot configure a stylesheet more than once.');\n }\n if (withValues?.type !== 'with' && !needsFreshSetBaselinePlacement) {\n // Reuse cached evaluated rules tree for plain compose re-imports and `set` baselines.\n rules = evaldRules;\n }\n // Default: de-dupe output for compose re-imports unless explicitly multiple.\n if (!importOptions!.multiple) {\n importOptions!.reference = true;\n }\n }\n if (needsFreshSetBaselinePlacement) {\n withValues = { node: cachedSetValues!, type: 'with' };\n }\n const inMultipleImportBranch = context.inMultipleImportScope;\n if (type === 'import' && importOptions!.once !== false && !importOptions!.multiple && !inMultipleImportBranch && evaldRules) {\n rules = evaldRules;\n importOptions!._dedupe = true;\n }\n if (withValues) {\n // Once configured, cannot be configured again (handled above for compose+cache).\n if (withValues.type === 'set' && evaldRules) {\n throw new Error('Cannot configure a stylesheet more than once.');\n }\n // Evaluate withValues.node if it's a Reference to get the actual Rules\n let withRulesNode = withValues.node;\n if (isNode(withRulesNode, N.Reference)) {\n const evaluated = await withRulesNode.eval(context);\n if (!isWithRulesNode(evaluated)) {\n throw new Error('with/set node must evaluate to a Collection');\n }\n withRulesNode = evaluated;\n }\n if (!isWithRulesNode(withRulesNode)) {\n throw new Error('with/set node must evaluate to a Collection');\n }\n let withRules: Rules = isNode(withRulesNode, N.Rules)\n ? withRulesNode\n : Rules.create([...withRulesNode.value]);\n if (type === 'compose' && withValues.type === 'with' && cachedSetValues) {\n const mergedConfig = new Map<string, Node>();\n for (const configuredNode of cachedSetValues.value) {\n if (!isNode(configuredNode, N.VarDeclaration)) {\n continue;\n }\n const key = String(configuredNode.get('name')?.valueOf() ?? '');\n if (key) {\n mergedConfig.set(key, configuredNode);\n }\n }\n for (const configuredNode of withRules.value) {\n if (!isNode(configuredNode, N.VarDeclaration)) {\n continue;\n }\n const key = String(configuredNode.get('name')?.valueOf() ?? '');\n if (key) {\n mergedConfig.set(key, configuredNode);\n }\n }\n withRules = Rules.create([...mergedConfig.values()]);\n }\n\n // Build a name→index map over canonical top-level VarDeclarations for O(1) lookup.\n // This replaces the previous rules.clone(true) + registry approach — we no longer\n // deep-clone the entire imported tree just to find which declarations to override.\n // A session created in the evaluation block below ensures that evaluated/preEvaluated\n // tracking does not permanently mark canonical nodes as evaluated.\n const topLevelVarIndex = new Map<string, number>();\n for (let i = 0; i < rules.value.length; i++) {\n const n = rules.value[i]!;\n if (isNode(n, N.VarDeclaration)) {\n const varName = String(n.get('name')?.valueOf() ?? '');\n if (varName && !topLevelVarIndex.has(varName)) {\n topLevelVarIndex.set(varName, i);\n }\n }\n }\n\n // Separate injected variables into replacements (matched in canonical) and new variables.\n const replacementAt = new Map<number, Node>();\n const newVariables: Node[] = [];\n\n for (const injectedNode of withRules.value) {\n if (isNode(injectedNode, N.VarDeclaration)) {\n const varName = String(injectedNode.get('name')?.valueOf() ?? '');\n if (varName) {\n const existingIdx = topLevelVarIndex.get(varName);\n if (existingIdx !== undefined) {\n replacementAt.set(existingIdx, injectedNode);\n } else {\n newVariables.push(injectedNode);\n }\n } else {\n newVariables.push(injectedNode);\n }\n } else {\n newVariables.push(injectedNode);\n }\n }\n\n // Build finalRules like mixin params: injected variables are pushed\n // canonically (they're new nodes), library children keep their canonical\n // parents untouched. We directly set the value array to avoid adopt()\n // mutating canonical library node parents.\n const finalChildren: Node[] = [];\n for (const newNode of newVariables) {\n finalChildren.push(newNode);\n }\n for (let i = 0; i < rules.value.length; i++) {\n finalChildren.push(replacementAt.get(i) ?? rules.value[i]!);\n }\n rules = rules.createPlacementWrapperWithChildren(finalChildren, context.nextRenderKey());\n if (type === 'compose' && withValues.type === 'set') {\n context.composeSetValues.set(resolvedPath, withRules);\n }\n }\n // For compose type, register and push extend root BEFORE evaluation\n // so extends inside the import use the correct root\n const parentExtendRoot = context.extendRoots.getCurrentExtendRoot();\n let pushedExtendRoot = false;\n if (type === 'compose') {\n // Register the Rules as an extend root (use rules before cloning/evaluation)\n // We'll update the registration after evaluation if the Rules changes\n // For compose type, default is protected (not mutable)\n const isComposeProtected = !importOptions!.mutable;\n context.extendRoots.registerRoot(rules, parentExtendRoot, {\n isProtected: isComposeProtected,\n isCompose: true,\n namespace: node.options.namespace\n });\n context.extendRoots.pushExtendRoot(rules);\n pushedExtendRoot = true;\n }\n\n /** Freshly evaluate the rules in these circumstances\n * - `with` (or `set`) values are present\n * - the rules have not been evaluated yet\n * - the import type is `import`\n */\n const activeParent = getParent(this, context);\n const shouldIsolateSelectorFrames = !isNode(activeParent ? getParent(activeParent, context) : undefined, N.Ruleset | N.AtRule);\n const prevRulesetFrames = shouldIsolateSelectorFrames ? context.rulesetFrames : undefined;\n const prevFrames = shouldIsolateSelectorFrames ? context.frames : undefined;\n if (withValues || !evaldRules || type === 'import') {\n let pushedImplicitReferenceEvalScope = false;\n const isImplicitReferenceModeForEval = (\n type === 'import'\n && importOptions!.reference !== true\n && importOptions!._dedupe === true\n && !importOptions!.multiple\n );\n if (isImplicitReferenceModeForEval) {\n // Dedupe re-imports behave like an implicit reference traversal:\n // evaluate for symbol availability, but avoid outward extend side effects.\n context.pushImportScope({ reference: true });\n pushedImplicitReferenceEvalScope = true;\n }\n\n // For protected imports (mutable: false), push the rules to extend root stack\n // so rulesets register in the import's registry, not the parent's\n const isImportProtected = type === 'import' && importOptions!.mutable === false;\n const shouldUseLocalExtendRoot = isImportProtected || isImplicitReferenceModeForEval;\n if (isImplicitReferenceModeForEval) {\n // Link local in-eval root so external extends can still target deduped imports.\n context.extendRoots.registerRoot(rules, parentExtendRoot, {\n isProtected: isImportProtected,\n namespace: node.options.namespace\n });\n }\n if (shouldUseLocalExtendRoot) {\n context.extendRoots.pushExtendRoot(rules);\n }\n\n try {\n if (shouldIsolateSelectorFrames) {\n context.rulesetFrames = [];\n context.frames = [];\n }\n if (withValues || !evaldRules) {\n rules = this.createPlacementRules(rules, context);\n }\n // Call preEval first to get the cloned Rules (if cloning occurs)\n // sourceNode is already set above, so the cloned Rules will have it\n rules = await rules.preEval(context);\n if (type === 'import') {\n /** Needed at evaluation time for older import type */\n node.adopt(rules);\n }\n rules = await rules.eval(context);\n } finally {\n if (pushedImplicitReferenceEvalScope) {\n context.popImportScope();\n }\n if (shouldUseLocalExtendRoot) {\n context.extendRoots.popExtendRoot();\n }\n if (shouldIsolateSelectorFrames) {\n context.rulesetFrames = prevRulesetFrames!;\n context.frames = prevFrames!;\n }\n }\n\n // Cache compose modules (and configured modules) after first evaluation.\n if (\n (type === 'compose' && withValues?.type !== 'with')\n || withValues?.type === 'set'\n || (type === 'import' && importOptions!.once !== false)\n ) {\n context.evaldTrees.set(resolvedPath, rules);\n }\n } else {\n // Shallow-clone the cached rules BEFORE evaluation so registries are populated\n // on the clone, not on the cached evaldRules.\n rules = rules.createShallowBodyWrapper(context, context.nextRenderKey());\n // Note: For compose type, we don't set rules.parent = node\n // (only import type needs this for older import behavior)\n try {\n if (shouldIsolateSelectorFrames) {\n context.rulesetFrames = [];\n context.frames = [];\n }\n rules = await rules.eval(context);\n } finally {\n if (shouldIsolateSelectorFrames) {\n context.rulesetFrames = prevRulesetFrames!;\n context.frames = prevFrames!;\n }\n }\n }\n\n // Pop extend root if we pushed one\n if (pushedExtendRoot) {\n context.extendRoots.popExtendRoot();\n }\n\n let finalRules = node.getFinalRules(rules, context);\n if (importOptions!.postlude && !isInlineImport) {\n finalRules = this.wrapEvaluatedRulesWithPostlude(finalRules, importOptions!.postlude, context);\n }\n // configuredWithCanonicalParents restore removed — canonical parents are not mutated.\n\n // For import type, register the final Rules as a child root of the parent\n // so extends from the parent can find rulesets in the imported Rules.\n if (type === 'import') {\n const currentParentExtendRoot = context.extendRoots.getCurrentExtendRoot();\n // Import type is mutable by default (unless explicitly mutable: false)\n const isImportProtected = importOptions!.mutable === false;\n const isImplicitReferenceModeForRegistration = (\n importOptions!._dedupe === true\n && importOptions!.reference !== true\n && !importOptions!.multiple\n );\n const shouldReRegisterLocalRootRulesets = (\n isImportProtected\n || isImplicitReferenceModeForRegistration\n || importOptions!.reference === true\n );\n context.extendRoots.registerRoot(finalRules, currentParentExtendRoot, {\n isProtected: isImportProtected,\n namespace: node.options.namespace\n });\n\n // For imports that evaluated under a local extend root (protected import or implicit _dedupe\n // reference traversal), rulesets were registered in the pre-finalized Rules root. Since\n // getFinalRules can clone, re-register all descendant rulesets under finalRules.\n // during preEval (when we pushed rules to the stack). Since getFinalRules clones,\n // we need to re-register rulesets in finalRules' registry.\n if (shouldReRegisterLocalRootRulesets) {\n for (const maybeNode of finalRules.nodes()) {\n if (isNode(maybeNode, N.Ruleset | N.Mixin)) {\n finalRules.registerNode(maybeNode, undefined, context);\n }\n }\n }\n // Don't push to stack - import type uses parent's root for extends inside the import\n // But we register it so extends from parent can find rulesets in the imported Rules\n }\n\n return finalRules;\n } finally {\n // dedupedCachedRules/dedupedCanonicalParents restore removed —\n // eval writes stay on derived nodes, canonical tree is not mutated.\n context.treeContext = previousTreeContext;\n if (pushedImportScope) {\n context.popImportScope();\n }\n importOptions!.reference = previousExplicitReference;\n }\n };\n const getFinalPath = (resolvedPath: Quoted | Url): string => {\n if (resolvedPath instanceof Url) {\n return resolvedPath.pathValue(context);\n }\n const quotedValue = resolvedPath.get('value', context);\n if (isNode(quotedValue)) {\n return String(quotedValue.valueOf());\n }\n return String(quotedValue);\n };\n\n return Promise.resolve(maybePath).then(async (p: Quoted | Url) => {\n const finalPath = getFinalPath(p);\n context.depth = originalDepth;\n return finalize(finalPath, p);\n });\n }\n\n /**\n * Applies CSS import postlude wrappers around inline source content.\n * Falls back to `@media <postlude>` for plain query nodes.\n */\n private wrapInlineSourceWithPostlude(sourceNode: Node, postlude: Node | undefined, context: Context): Rules {\n if (!postlude) {\n return Rules.create([sourceNode]);\n }\n\n let wrapped: Node = sourceNode;\n const postludeNodes: Node[] = isNode(postlude, N.Sequence | N.List) ? [...postlude.get('value', context)] : [postlude];\n\n for (let i = postludeNodes.length - 1; i >= 0; i--) {\n const current = postludeNodes[i]!;\n const body = Rules.create([wrapped]);\n const { atRuleName, prelude } = this.materializePostludePrelude(current, context);\n wrapped = new AtRule({\n name: new Any(atRuleName, { role: 'atkeyword' }),\n prelude,\n rules: body\n });\n }\n\n return Rules.create([wrapped]);\n }\n\n /**\n * Applies CSS import postlude wrappers around evaluated stylesheet rules.\n * Used for Less-style imports with media/layer/supports postludes.\n */\n private wrapEvaluatedRulesWithPostlude(rules: Rules, postlude: Node | undefined, context: Context): Rules {\n if (!postlude) {\n return rules;\n }\n const postludeNodes: Node[] = isNode(postlude, N.Sequence | N.List) ? [...postlude.get('value', context)] : [postlude];\n let wrappedRules: Rules = rules;\n for (let i = postludeNodes.length - 1; i >= 0; i--) {\n const current = postludeNodes[i]!;\n const { atRuleName, prelude } = this.materializePostludePrelude(current, context);\n const wrappedAtRule = new AtRule({\n name: new Any(atRuleName, { role: 'atkeyword' }),\n prelude,\n rules: wrappedRules\n });\n wrappedRules = Rules.create([wrappedAtRule]);\n }\n\n return wrappedRules;\n }\n}\n\ndefineType<StyleImportValue>(StyleImport, 'StyleImport', 'style');\n\nexport const style = (...args: ConstructorParameters<typeof StyleImport>) => {\n return new StyleImport(...args);\n};\n","import { F_MAY_ASYNC, F_NON_STATIC, Node, defineType } from './node.js';\nimport type { Context } from '../context.js';\nimport { type Quoted } from './quoted.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\n\n/**\n * Imports of TS/JS ESM modules.\n *\n * `@-from 'foo.js' import ( name, ... );` or `@-from 'foo.js' import * as ns;`\n */\n\ntype JsImportSpecifier = string | [string, string] | { name: string; alias?: string };\n\nexport type JsImportOptions = {\n /** e.g. `@-from 'foo.js' import * as foo` sets namespace to `foo` */\n namespace?: string;\n /**\n * - In array,\n * - string is a plain import identifier\n * - [string, string] is { [identifier1] as [identifier2] }\n */\n imports?: string | JsImportSpecifier[];\n};\n\nexport type JsImportValue = {\n path: Quoted;\n imports?: JsImportSpecifier[];\n};\n\nexport type JsImportChildData = { path: Quoted; imports: JsImportSpecifier[] | undefined };\n\nexport interface JsImport {\n type: 'JsImport';\n shortType: 'js';\n}\nexport class JsImport extends Node<JsImportValue, JsImportOptions, JsImportChildData> {\n static override childKeys = ['path', 'imports'] as const;\n\n path!: Quoted;\n imports: JsImportSpecifier[] | undefined;\n\n constructor(value: JsImportValue, options?: JsImportOptions, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.path = value.path;\n this.imports = value.imports;\n if (this.path instanceof Node) {\n this.adopt(this.path);\n }\n this.addFlags(F_MAY_ASYNC, F_NON_STATIC);\n }\n\n override evalNode(context: Context): MaybePromise<JsImport> {\n const path = this.get('path', context);\n const finish = (nextPath: Quoted): JsImport => {\n const out = this.clone() as JsImport;\n if (nextPath !== path) {\n out.path = nextPath;\n }\n return out;\n };\n const maybeEvald = path.eval(context);\n if (isThenable(maybeEvald)) {\n return (maybeEvald as Promise<Quoted>).then(finish);\n }\n return finish(maybeEvald as Quoted);\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n const context = options.context;\n const path = this.get('path', context);\n const { namespace } = this.options;\n const imports = this.get('imports', context) ?? (Array.isArray(this.options.imports) ? this.options.imports : undefined);\n\n w.add('@-from ');\n path.toString(options);\n\n // Named imports: `import ( name, name as alias, ... )`\n const namedImports = imports?.filter((s) => {\n if (typeof s === 'string') {\n return true;\n }\n if (Array.isArray(s)) {\n return s[0] !== '*';\n }\n return s.name !== '*';\n });\n if (namedImports?.length) {\n const parts = namedImports.map((s) => {\n if (typeof s === 'string') {\n return s;\n }\n if (Array.isArray(s)) {\n return `${s[0]} as ${s[1]}`;\n }\n return s.alias ? `${s.name} as ${s.alias}` : s.name;\n });\n w.add(` import ( ${parts.join(', ')} )`);\n }\n\n // Namespace import: `import * as ns`\n let explicitNamespace = namespace;\n if (!explicitNamespace && imports?.length) {\n const nsSpec = imports.find((specifier) => {\n if (Array.isArray(specifier)) {\n return specifier[0] === '*';\n }\n if (typeof specifier !== 'string') {\n return specifier.name === '*';\n }\n return false;\n });\n if (nsSpec) {\n explicitNamespace = Array.isArray(nsSpec)\n ? nsSpec[1]\n : (typeof nsSpec === 'string' ? undefined : nsSpec.alias);\n }\n }\n if (explicitNamespace) {\n w.add(` import * as ${explicitNamespace}`);\n }\n w.add(';');\n return w.getSince(mark);\n }\n}\n\nexport const js = defineType<JsImportValue>(JsImport, 'JsImport', 'js');\n","import type { Context } from '../context.js';\nimport { defineType, Node, F_MAY_ASYNC, F_NON_STATIC, type OptionalLocation, type NodeOptions, type TreeContext } from './node.js';\nimport { SimpleSelector } from './selector-simple.js';\nimport { Selector } from './selector.js';\nimport type { BitSetLibrary } from './util/bitset.js';\nimport { Interpolated } from './interpolated.js';\nimport { getPrintOptions, type PrintOptions } from './util/print.js';\nimport { type MaybePromise, isThenable } from '@jesscss/awaitable-pipe';\n\nconst { isArray } = Array;\n\nfunction propagateKeySetLibrary(sel: Selector, library: BitSetLibrary<string>) {\n sel.keySetLibrary = library;\n const childKeys = (sel.constructor as typeof Node).childKeys;\n if (!childKeys) {\n return;\n }\n for (const key of childKeys) {\n const field = (sel as unknown as Record<string, unknown>)[key];\n if (isArray(field)) {\n for (const child of field as Selector[]) {\n if (child && !child.keySetLibrary) {\n propagateKeySetLibrary(child, library);\n }\n }\n }\n }\n}\n\nexport type InterpolatedSelectorChildData = { value: Interpolated };\n\nexport interface InterpolatedSelector extends SimpleSelector<Interpolated, NodeOptions, InterpolatedSelectorChildData> {\n type: 'InterpolatedSelector';\n shortType: 'interpolated-selector';\n eval(context: Context): MaybePromise<Selector>;\n}\n\n/**\n * A selector that wraps an interpolated value\n * This allows interpolation to be used in selector contexts\n */\nexport class InterpolatedSelector extends SimpleSelector<Interpolated, NodeOptions, InterpolatedSelectorChildData> {\n static override childKeys = ['value'] as const;\n\n readonly value!: Interpolated;\n\n constructor(value: Interpolated, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n if (this.value instanceof Node) {\n this.adopt(this.value);\n }\n this.addFlag(F_NON_STATIC);\n this.addFlag(F_MAY_ASYNC);\n }\n\n get isClass() {\n return /^\\./.test(this.valueOf());\n }\n\n get isId() {\n return /^#/.test(this.valueOf());\n }\n\n get isTag() {\n return /^[^.#*]/.test(this.valueOf());\n }\n\n override evalNode(context: Context): MaybePromise<Selector> {\n const result = this.value.evalToSelector(context);\n const library = context.selectorBits;\n if (isThenable(result)) {\n return (result as Promise<Selector>).then((sel) => {\n propagateKeySetLibrary(sel, library);\n return sel;\n });\n }\n propagateKeySetLibrary(result as Selector, library);\n return result;\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n this.value.toString(options);\n return w.getSince(mark);\n }\n\n override valueOf(): string {\n return this.value.valueOf();\n }\n}\n\nexport const interpolatedSelector = defineType(InterpolatedSelector, 'InterpolatedSelector', 'interpolated-selector');\n","import { type Context } from '../context.js';\nimport { Node, defineType } from './node.js';\nimport { Bool } from './bool.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\n\nexport interface DefaultGuard extends Node<string> {\n type: 'DefaultGuard';\n shortType: 'defaultguard';\n eval(context: Context): Bool;\n}\n\nexport class DefaultGuard extends Node<string> {\n static override childKeys = null as null;\n\n readonly value!: string;\n\n constructor(value: string, options?: any, location?: any, treeContext?: any) {\n super(value, options, location, treeContext);\n this.value = value;\n }\n\n override toTrimmedString(options?: PrintOptions) {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n w.add('default', this);\n return w.getSince(mark);\n }\n\n override evalNode(context: Context): Bool {\n return new Bool(Boolean(context.isDefault));\n }\n}\n\nexport const defaultguard = defineType(DefaultGuard, 'DefaultGuard');","import type { Context } from '../context.js';\nimport { defineType, Node, type OptionalLocation, type TreeContext, type NodeOptions } from './node.js';\nimport { isNode } from './util/is-node.js';\nimport { type PrintOptions, getPrintOptions } from './util/print.js';\n\nexport type RestChildData = { value: Node | string | undefined };\n\n/**\n * A rest expression (e.g. ...$var). By itself it doesn't do much.\n * It's used by lists to merge values. Sequences already bubble\n * lists / sequences, so this is mostly for serialization.\n */\nexport interface Rest {\n type: 'Rest';\n shortType: 'rest';\n}\nexport class Rest extends Node<Node | string | undefined, NodeOptions, RestChildData> {\n static override childKeys = ['value'] as const;\n\n readonly value: Node | string | undefined;\n\n constructor(value?: Node | string, options?: NodeOptions, location?: OptionalLocation, treeContext?: TreeContext) {\n super(value, options, location, treeContext);\n this.value = value;\n if (this.value instanceof Node) {\n this.adopt(this.value);\n }\n }\n\n private _getName(context?: Context): string {\n const value = this.get('value', context);\n if (value) {\n if (isNode(value)) {\n return value.toString();\n }\n return `$${value}`;\n }\n return '';\n }\n\n get name(): string {\n return this._getName();\n }\n\n override toTrimmedString(options?: PrintOptions): string {\n options = getPrintOptions(options);\n const w = options.writer!;\n const mark = w.mark();\n w.add('...$');\n w.add(this._getName(options.context));\n return w.getSince(mark);\n }\n}\n\nexport const rest = defineType(Rest, 'Rest');\n","/**\n * @note\n * These nodes are actually taking the role of two ASTs,\n * because there are nodes that will be used to produce a module,\n * and that module will create AST nodes to create CSS.\n *\n * @todo - rewrite the above, this is no longer true\n */\n\n/**\n * Import from node.ts which applies all the prototype patches\n * (nil, operate, treeContext) and re-exports from node-base.ts\n */\nimport {\n Node,\n type LocationInfo,\n type LocationInfoOrEmpty,\n type OptionalLocation,\n EVAL,\n F_VISIBLE,\n F_MAY_ASYNC,\n F_STATIC,\n F_NON_STATIC\n} from './node.js';\nimport { type Context, TreeContext } from '../context.js';\nimport { compare } from './util/compare.js';\n\nexport {\n Node,\n TreeContext,\n type LocationInfo,\n type LocationInfoOrEmpty,\n type OptionalLocation,\n EVAL,\n F_VISIBLE,\n F_MAY_ASYNC,\n F_STATIC,\n F_NON_STATIC\n};\nexport { N } from './node-type.js';\n\nimport { Selector } from './selector.js';\n\nexport * from './at-rule.js';\nexport * from './block.js';\nexport * from './bool.js';\nexport * from './ampersand.js';\nexport * from './any.js';\nexport * from './call.js';\nexport * from './color.js';\nexport * from './comment.js';\nexport * from './combinator.js';\nexport * from './condition.js';\nexport * from './control.js';\nexport * from './declaration.js';\nexport * from './declaration-custom.js';\nexport * from './declaration-var.js';\nexport * from './dimension.js';\nexport * from './number.js';\nexport * from './expression.js';\nexport * from './extend.js';\nexport * from './list.js';\nexport * from './log.js';\nexport * from './mixin.js';\nexport * from './negative.js';\nexport * from './function.js';\nexport * from './js-function.js';\nexport * from './js-array.js';\nexport * from './js-object.js';\nexport * from './nil.js';\nexport * from './operation.js';\nexport * from './paren.js';\nexport * from './quoted.js';\nexport * from './range.js';\nexport * from './ruleset.js';\nexport * from './rules.js';\nexport * from './rules-raw.js';\nexport * from './collection.js';\nexport * from './selector.js';\nexport * from './selector-attr.js';\nexport * from './selector-basic.js';\nexport * from './selector-list.js';\nexport * from './selector-pseudo.js';\nexport * from './selector-compound.js';\nexport * from './selector-complex.js';\nexport * from './selector-simple.js';\nexport * from './selector-capture.js';\nexport * from './sequence.js';\nexport * from './query-condition.js';\nexport * from './comment.js';\nexport * from './reference.js';\nexport * from './import-style.js';\nexport * from './import-js.js';\nexport * from './interpolated.js';\nexport * from './selector-interpolated.js';\nexport * from './default-guard.js';\nexport * from './rest.js';\nexport * from './url.js';\n\n// Patch Selector.compare after all exports to avoid circular dependency\nimport { selectorMatch } from './util/selector-match-core.js';\n\n/** Patch Selector to avoid circularity */\nSelector.prototype.compare = function(other: Node, context?: Context) {\n // Avoid `instanceof Selector` here: module identity can diverge under Vite/Vitest\n // if the same file is loaded via different specifiers.\n if (!!other && typeof other === 'object' && 'isSelector' in other && other.isSelector === true) {\n const otherSelector = other as unknown as Selector;\n const forward = selectorMatch(this, otherSelector, undefined, context);\n if (forward.fullMatch) {\n return 0;\n }\n if (forward.partialMatch) {\n return -1;\n }\n const backward = selectorMatch(otherSelector, this, undefined, context);\n if (backward.partialMatch) {\n return 1;\n }\n }\n return compare(this.valueOf(), other?.valueOf?.());\n};\n","import type { Deprecation } from '../deprecation.js';\nimport type { Logger } from '../logger.js';\nimport type { WarningDiagnostic } from '../jess-error.js';\n\n/**\n * The maximum number of repetitions of the same deprecation warning\n * that will be emitted before hiding the rest.\n */\nconst MAX_REPETITIONS = 5;\n\n/**\n * A logger wrapper that provides special handling for deprecation warnings:\n * - Making deprecations fatal (throwing errors)\n * - Limiting repetition (max 5 per deprecation)\n */\nexport class DeprecationProcessingLogger implements Logger {\n /** A map of how many times each deprecation has been emitted */\n private readonly _warningCounts = new Map<Deprecation, number>();\n\n /** The inner logger to delegate to */\n private readonly _inner: Logger;\n\n /** Deprecation warnings of these types will cause an error to be thrown */\n readonly fatalDeprecations: Set<Deprecation>;\n\n /** Whether repetitions of the same warning should be limited */\n readonly limitRepetition: boolean;\n\n constructor(\n inner: Logger,\n options: {\n fatalDeprecations?: Iterable<Deprecation>;\n limitRepetition?: boolean;\n } = {}\n ) {\n this._inner = inner;\n this.fatalDeprecations = new Set(options.fatalDeprecations ?? []);\n this.limitRepetition = options.limitRepetition ?? true;\n }\n\n /**\n * Processes a deprecation warning.\n *\n * If the deprecation is in fatalDeprecations, this throws an error.\n * If it's already been warned for MAX_REPETITIONS times and limitRepetition is true, the warning is dropped.\n * Otherwise, this is passed on to the inner logger.\n */\n warnForDeprecation(\n deprecation: Deprecation,\n warning: WarningDiagnostic\n ): void {\n if (this.fatalDeprecations.has(deprecation)) {\n const message = `${warning.message}\\n\\nThis is only an error because you've set the ${deprecation.id} deprecation to be fatal.\\nRemove this setting if you need to keep using this feature.`;\n const error = new Error(message);\n error.name = 'DeprecationError';\n throw error;\n }\n\n if (this.limitRepetition) {\n const count = (this._warningCounts.get(deprecation) ?? 0) + 1;\n this._warningCounts.set(deprecation, count);\n if (count > MAX_REPETITIONS) {\n return;\n }\n }\n\n // Pass to inner logger\n this._inner.warn?.(warning.message);\n }\n\n /**\n * Prints a warning indicating the number of deprecation warnings that were\n * omitted due to repetition.\n */\n summarize(): void {\n let total = 0;\n for (const [deprecation, count] of this._warningCounts.entries()) {\n if (count > MAX_REPETITIONS) {\n total += count - MAX_REPETITIONS;\n }\n }\n if (total > 0) {\n this._inner.warn?.(\n `${total} repetitive deprecation warnings omitted.\\nRun in verbose mode to see all warnings.`\n );\n }\n }\n\n // Delegate other logger methods to inner logger\n configure?(log: Logger): void {\n this._inner.configure?.(log);\n }\n\n log?(...args: any[]): void {\n this._inner.log?.(...args);\n }\n\n info?(...args: any[]): void {\n this._inner.info?.(...args);\n }\n\n warn?(...args: any[]): void {\n this._inner.warn?.(...args);\n }\n\n error?(...args: any[]): void {\n this._inner.error?.(...args);\n }\n}\n","import type { Rules } from './tree/rules.js';\nimport { join, isAbsolute, resolve } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport type { Visitor } from './visitor/index.js';\nimport { type ErrorDiagnostic, type WarningDiagnostic, JessError } from './jess-error.js';\n\nexport type ISafeParseResult = {\n /**\n * The parsed tree, if parsing succeeded\n */\n tree?: Rules;\n /**\n * Normalized errors from parsing.\n * This should include ALL errors from lexing, parsing, and any plugin-level issues.\n * Plugins should convert all errors to normalized ErrorDiagnostic format.\n * Always an array (empty if no errors).\n */\n errors: ErrorDiagnostic[];\n /**\n * Normalized warnings from parsing.\n * This should include ALL warnings from lexing, parsing, and any plugin-level issues.\n * Plugins should convert all warnings to normalized WarningDiagnostic format.\n * Always an array (empty if no warnings).\n */\n warnings: WarningDiagnostic[];\n};\n\nexport type PluginParseOptions = {\n compilerOptions?: Record<string, any>;\n};\n\nexport interface PluginInterface {\n /**\n * e.g. 'less-plugin'\n */\n name: string;\n\n /**\n * Queryable filter if we have resolved the extension\n * no dots e.g. `['less', 'scss']`\n */\n supportedExtensions?: string[];\n\n /**\n * Expand an import path into a set of paths to try.\n * e.g.\n * `@import 'foo'` -> `['./foo.less']`\n * `@import 'foo'` -> `['./foo.scss', './_foo.scss']`\n */\n expandImport?(importPath: string, currentDir: string): string[];\n\n /**\n * e.g.\n * `./foo` -> `/Users/foo/bar/foo`\n * `@/alias` -> `/Users/foo/bar/src/alias`\n * `one/two` -> `/Users/foo/node_modules/one/two`\n *\n * Does not attempt to check if the path exists.\n * Note: paths may already be absolute.\n *\n * If the plugin has nothing to change, return `null` or return the array as-is.\n *\n * @note - I suppose a plugin doesn't have to resolve to an absolute path, if it's\n * using some other method to handle the resolved paths in `locate()`.\n * To that end, `locate()` shouldn't presume that the paths are absolute.\n */\n resolve?(path: string | string[], currentDir: string, searchPaths: string[]): null | string[] | Promise<null | string[]>;\n\n /**\n * Pick the first one that exists. Return null to let another plugin handle the path.\n */\n locate?(pathCandidates: string[], currentDir: string): null | string | Promise<string | null>;\n\n /**\n * Get the source code for the file.\n */\n getSource?(absoluteFilePath: string): Promise<string>;\n\n /**\n * If we have the extension in `supportedExtensions`, and this method exists,\n * then this plugin is assumed to be able to parse the file.\n */\n parse?(filePath: string, source: string, options?: PluginParseOptions): Rules;\n\n /** No errors thrown; instead will return errors in the result */\n safeParse?(filePath: string, source: string, options?: PluginParseOptions): ISafeParseResult;\n\n /** If this method exists, then the plugin can return a JS module / object */\n import?(absoluteFilePath: string): Promise<Record<string, any>>;\n\n /** Post-parse or post-eval visitor(s) */\n visitor?: Visitor | Visitor[];\n /** Pre-eval visitor(s) - called before node.eval() during the preEval phase */\n preEvalVisitor?: Visitor | Visitor[];\n /** Post-eval visitor(s) - called after node.eval() (alternative to visitor for clarity) */\n postEvalVisitor?: Visitor | Visitor[];\n /** Optional cleanup hook for plugins that manage external resources */\n dispose?(): void;\n}\n\nconst { isArray } = Array;\n\nexport abstract class AbstractPlugin implements PluginInterface {\n abstract name: string;\n\n /**\n * Does a basic path resolution. Node resolution is in other plugins.\n */\n resolve(filePath: string | string[], currentDir: string, searchPaths: string[]) {\n const bases = [currentDir, ...searchPaths];\n const out: string[] = [];\n const seen = new Set<string>();\n filePath = isArray(filePath) ? filePath : [filePath];\n for (const base of bases) {\n const baseDir = isAbsolute(base) ? base : join(currentDir, base);\n for (const path of filePath) {\n const abs = resolve(baseDir, path);\n if (abs && !seen.has(abs)) {\n seen.add(abs);\n out.push(abs);\n }\n }\n }\n return out;\n }\n\n /** Default source getter */\n async getSource(absoluteFilePath: string): Promise<string> {\n try {\n const result = await readFile(absoluteFilePath, 'utf8');\n return result;\n } catch (error: unknown) {\n throw error;\n }\n }\n\n /** Gets the first match using from the filesystem that exists */\n locate(pathCandidates: string[], currentDir: string): null | string {\n for (const candidate of pathCandidates) {\n const absolutePath = isAbsolute(candidate) ? candidate : join(currentDir, candidate);\n if (existsSync(absolutePath)) {\n return absolutePath;\n }\n }\n return null;\n }\n\n parse(filePath: string, source: string, options?: PluginParseOptions): Rules {\n const safeParse: PluginInterface['safeParse'] = (this as PluginInterface).safeParse;\n if (!safeParse) {\n throw new Error(`Plugin \"${this.name}\" does not support parsing`);\n }\n const { tree, errors } = safeParse.call(this, filePath, source, options);\n if (errors.length > 0) {\n const firstError = errors[0]!;\n throw new JessError({\n code: firstError.code,\n phase: firstError.phase,\n severity: 'error',\n ctx: firstError.file ? { file: firstError.file } : undefined,\n filePath: firstError.filePath,\n source: firstError.file?.source,\n line: firstError.line,\n column: firstError.column,\n reason: firstError.reason,\n fix: firstError.fix,\n note: firstError.note,\n errors: firstError.errors,\n lexerErrors: firstError.lexerErrors\n });\n }\n if (!tree) {\n throw new Error(`Plugin \"${this.name}\" failed to parse \"${filePath}\"`);\n }\n return tree;\n }\n\n /** Implement using the JS plugin w/ Deno */\n // import(absoluteFilePath: string): Promise<Record<string, any>> {\n // return import(absoluteFilePath);\n // }\n}\n\nexport type Plugin = <T extends Record<string, any>>(opts?: T) => PluginInterface;\n\n// export abstract class FileManager<O extends Record<string, any> = Record<string, any>> {\n// abstract supportedExtensions?: string[];\n\n// constructor(\n// public opts: Partial<O> = {}\n// ) {}\n\n// /**\n// * Turns relative paths into absolute paths.\n// * e.g.\n// * `./foo` -> `/Users/foo/bar/foo`\n// * `@/alias` -> `/Users/foo/bar/src/alias`\n// * `one/two` -> `/Users/foo/node_modules/one/two`\n// *\n// * Does not attempt to check if the path exists.\n// * Note: paths may already be absolute.\n// */\n// abstract resolver?(paths: Set<string>, currentDir: string): Set<string>;\n\n// /**\n// * e.g.\n// * Less file manager: `@import 'foo'` -> `['./foo.less']`\n// * Sass file manager: `@import 'foo'` -> `['./foo.scss', './_foo.scss']`\n// */\n// abstract getPathsToTry?(filePath: string, currentDir: string, paths: string[], options: PathOptions): Set<string>;\n\n// /**\n// * Get the final resolved path.\n// *\n// * @param filePath Will be a partial path\n// * @param paths The paths to search. This should always contain\n// * the directory context where the file was imported. Can be\n// * a fully-qualified path or a glob. Relative paths\n// * will be resolved relative to process.cwd(). Plugins\n// * may alter the paths array and return false to let another\n// * plugin handle the path resolution.\n// * @param options Determined by the file manager\n// */\n// resolvePath(\n// filePath: string,\n// currentDir: string,\n// paths: string[],\n// options: PathOptions\n// ): string | string[] {\n// filePath = this.opts.resolver(filePath);\n// const pathsTried: string[] = [];\n// if (isAbsolute(filePath)) {\n// pathsTried.push(filePath);\n// if (existsSync(filePath)) {\n// return filePath;\n// }\n// }\n// let isRelative = filePath.startsWith('.');\n// let tryPath: string | undefined;\n// if (options.allowBareRelative || isRelative) {\n// tryPath = join(currentDir, filePath);\n// pathsTried.push(tryPath);\n// if (existsSync(tryPath)) {\n// return tryPath;\n// }\n// }\n\n// if (!isRelative) {\n// try {\n// tryPath = require.resolve(filePath);\n// if (existsSync(tryPath)) {\n// return tryPath;\n// }\n// } catch (err) {\n// // ignore\n// }\n// }\n\n// for (let i = 0; i < paths.length; i++) {\n// tryPath = join(paths[i]!, filePath);\n// pathsTried.push(tryPath);\n// if (existsSync(tryPath)) {\n// return tryPath;\n// }\n// }\n// return pathsTried;\n// }\n\n// async loadFile(fullPath: string) {\n// return await readFile(fullPath, 'utf8');\n// }\n\n// /**\n// * Can override this instead of `getTree` if we want\n// * to preserve extension-checking logic.\n// */\n// protected async _getTree(fullPath: string, options?: Record<string, any>): Promise<Rules | false> {\n// return false;\n// }\n\n// /**\n// * @param fullPath The fully resolved path\n// */\n// async getTree(fullPath: string, options?: Record<string, any>): Promise<Rules | false> {\n// const supported = this.supportedExtensions;\n// if (supported && !supported.includes(extname(fullPath))) {\n// return false;\n// }\n// return await this._getTree(fullPath, options);\n// }\n// }\n","/**\n * A deprecated feature in the language.\n *\n * Each deprecation has:\n * - `id`: Unique kebab-case identifier\n * - `description`: Human-readable description (optional)\n */\nexport class Deprecation {\n /** Unique ID for this deprecation in kebab case */\n readonly id: string;\n\n /** Human-readable description */\n readonly description: string | null;\n\n /**\n * Constructs a deprecation.\n */\n constructor(\n id: string,\n options: {\n description?: string | null;\n } = {}\n ) {\n this.id = id;\n this.description = options.description ?? null;\n }\n\n toString(): string {\n return this.id;\n }\n\n /**\n * Returns the deprecation with a given ID, or null if none exists.\n */\n static fromId(id: string): Deprecation | null {\n return Deprecation.values.find(d => d.id === id) ?? null;\n }\n\n /**\n * All known deprecations.\n * Add new deprecations here as they are introduced.\n */\n static readonly values: Deprecation[] = [\n new Deprecation('mixin-call-no-parens', {\n description: 'Calling a mixin without parentheses is deprecated.'\n }),\n new Deprecation('mixin-call-whitespace', {\n description: 'Whitespace between a mixin name and parentheses for a mixin call is deprecated.'\n }),\n new Deprecation('dot-slash-operator', {\n description: 'The ./ operator is deprecated.'\n }),\n new Deprecation('variable-in-unknown-value', {\n description: '@[ident] in custom property values is treated as literal text, not a variable reference. Use @{[ident]} if you want it to be evaluated.'\n }),\n new Deprecation('property-in-unknown-value', {\n description: '$[ident] in custom property values is treated as literal text, not a property reference. Use ${[ident]} if you want it to be evaluated.'\n })\n ];\n\n /**\n * Used for deprecations coming from user-authored code.\n */\n static readonly userAuthored = new Deprecation('user-authored', {\n description: null\n });\n}\n","import { Node } from '../node.js';\n\nexport type SerializeTypesOptions = {\n // Include primitive main values next to the type when useful\n showValues?: boolean;\n // Include options next to the type when useful\n showOptions?: boolean;\n // Max length for printed strings; longer strings are truncated with …\n maxStringLength?: number;\n // Use shortType instead of type\n useShortType?: boolean;\n // Indentation size in spaces\n indentSize?: number;\n};\n\nconst defaultOptions: Required<SerializeTypesOptions> = {\n showValues: true,\n showOptions: false,\n maxStringLength: 40,\n useShortType: false,\n indentSize: 2\n};\n\nfunction isJessNode(value: unknown): value is Node {\n return value instanceof Node;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && !Array.isArray(value) && typeof value === 'object';\n}\n\nfunction truncate(str: string, max: number): string {\n if (str.length <= max) {\n return str;\n }\n return `${str.slice(0, max - 1)}…`;\n}\n\nfunction formatPrimitive(value: unknown, opts: Required<SerializeTypesOptions>): string {\n if (typeof value === 'string') {\n const content = truncate(value, opts.maxStringLength);\n return `'${content.replace(/'/g, '\\\\\\'')}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return 'undefined';\n }\n return String(value);\n}\n\nfunction indent(depth: number, size: number): string {\n return ''.padStart(depth * size);\n}\n\nfunction summarizeArray(items: unknown[], opts: Required<SerializeTypesOptions>): string {\n // For non-node arrays emit a compact summary: [a, b]\n const parts = items.map((item) => {\n if (isJessNode(item)) {\n return opts.useShortType ? (item as any).shortType : (item as any).type;\n }\n if (Array.isArray(item)) {\n return '[' + summarizeArray(item, opts) + ']';\n }\n return formatPrimitive(item, opts);\n });\n return parts.join(', ');\n}\n\nfunction serializeArray(arr: unknown[], depth: number, opts: Required<SerializeTypesOptions>, visiting: Set<Node>): string {\n const pad = indent(depth, opts.indentSize);\n if (arr.length === 0) {\n return `${pad}[]`;\n }\n const first = arr[0];\n if (isJessNode(first)) {\n const inner = arr.map(item => serializeNode(item as Node, depth + 1, opts, visiting)).join('\\n');\n return `${pad}[\\n${inner}\\n${pad}]`;\n }\n // Not a node array; show compact\n return `${pad}[${summarizeArray(arr, opts)}]`;\n}\n\nfunction serializePlainObject(obj: Record<string, unknown>, depth: number, opts: Required<SerializeTypesOptions>, visiting: Set<Node>): string {\n const keys = Object.keys(obj).filter(k => obj[k] !== undefined);\n if (keys.length === 0) {\n return '';\n }\n const lines: string[] = [];\n for (const key of keys) {\n const v = obj[key];\n if (isJessNode(v)) {\n const inner = '\\n' + serializeNode(v, depth + 2, opts, visiting);\n lines.push(`${indent(depth + 1, opts.indentSize)}${key}: ${inner}`);\n } else if (Array.isArray(v)) {\n const inner = serializeArray(v, depth + 2, opts, visiting);\n lines.push(`${indent(depth + 1, opts.indentSize)}${key}:\\n${inner}`);\n } else if (isPlainObject(v)) {\n const inner = serializePlainObject(v as Record<string, unknown>, depth + 1, opts, visiting);\n if (inner) {\n lines.push(`${indent(depth + 1, opts.indentSize)}${key}: {\\n${inner}\\n${indent(depth + 1, opts.indentSize)}}`);\n } else {\n lines.push(`${indent(depth + 1, opts.indentSize)}${key}: {}`);\n }\n } else {\n lines.push(`${indent(depth + 1, opts.indentSize)}${key}: ${formatPrimitive(v, opts)}`);\n }\n }\n return lines.join('\\n');\n}\n\nfunction serializeNodeOptions(n: Node, depth: number, opts: Required<SerializeTypesOptions>, visiting: Set<Node>): string | null {\n if (!opts.showOptions) {\n return null;\n }\n const nodeOptions = (n as any).options;\n if (!nodeOptions || typeof nodeOptions !== 'object') {\n return null;\n }\n // Check if there are any non-undefined properties\n const keys = Object.keys(nodeOptions).filter(k => nodeOptions[k] !== undefined);\n if (keys.length === 0) {\n return null;\n }\n return serializePlainObject(nodeOptions, depth + 1, opts, visiting);\n}\n\nfunction getNodeRole(n: Node): string | undefined {\n return (n as any).role ?? (n as any).options?.role;\n}\n\nfunction getNodeValue(n: Node): unknown {\n const childKeys = (n.constructor as typeof Node).childKeys;\n const NODE_INTERNAL = new Set([\n 'parent', 'index', 'frames', 'pre', 'post', 'state', 'nodeType',\n 'preEvaluated', 'evaluated',\n 'renderKey',\n 'isSelector', 'keySetLibrary', 'role',\n 'fullRender',\n 'rulesetRegistry', 'mixinRegistry', 'declarationRegistry', 'functionRegistry',\n 'rulesIndexed', '_indexing',\n '_valueOf', '_keySet', '_visibleKeySet', '_requiredKeySet'\n ]);\n\n if ((n as any).type === 'Color') {\n const color = n as any;\n const value: Record<string, unknown> = {};\n if (color._nodeValue !== undefined) {\n value.node = color._nodeValue;\n }\n if (color._rgbChannels !== undefined) {\n value.rgb = color.rgb;\n }\n if (color._hslChannels !== undefined) {\n value.hsl = color.hsl;\n }\n if (color._alphaValue !== undefined) {\n value.alpha = color.alpha;\n }\n return Object.keys(value).length > 0 ? value : undefined;\n }\n\n if (Array.isArray(childKeys)) {\n if (childKeys.length === 1) {\n return (n as any)[childKeys[0]!];\n }\n\n const obj: Record<string, unknown> = {};\n for (const key of childKeys) {\n const value = (n as any)[key];\n if (value !== undefined) {\n obj[key] = value;\n }\n }\n for (const key of Object.keys(n)) {\n if (key.startsWith('_') || NODE_INTERNAL.has(key) || childKeys.includes(key)) {\n continue;\n }\n const value = (n as any)[key];\n if (value !== undefined) {\n obj[key] = value;\n }\n }\n return Object.keys(obj).length > 0 ? obj : undefined;\n }\n\n const directValue = (n as any).value as unknown;\n if (directValue !== undefined) {\n return directValue;\n }\n\n const obj: Record<string, unknown> = {};\n for (const key of Object.keys(n)) {\n if (key.startsWith('_') || NODE_INTERNAL.has(key)) {\n continue;\n }\n const value = (n as any)[key];\n if (value !== undefined && !isJessNode(value) && !Array.isArray(value)) {\n obj[key] = value;\n }\n }\n return Object.keys(obj).length > 0 ? obj : undefined;\n}\n\nfunction serializeNode(n: Node, depth: number, opts: Required<SerializeTypesOptions>, visiting: Set<Node>): string {\n const typeName = opts.useShortType ? (n as any).shortType : (n as any).type;\n const pad = indent(depth, opts.indentSize);\n const role = getNodeRole(n);\n const meta = role ? ` [role=${role}]` : '';\n const open = `${pad}(${typeName}${meta}`;\n\n // Protect against cycles\n if (visiting.has(n)) {\n return `${open} …)`;\n }\n visiting.add(n);\n\n const value = getNodeValue(n);\n const optionsStr = serializeNodeOptions(n, depth, opts, visiting);\n\n // If the main value is a primitive, include it inline\n if (\n value === null\n || value === undefined\n || typeof value === 'string'\n || typeof value === 'number'\n || typeof value === 'boolean'\n ) {\n visiting.delete(n);\n if (optionsStr) {\n if (opts.showValues && value !== undefined) {\n const rendered = formatPrimitive(value, opts);\n return `${open}\\n${optionsStr}\\n${indent(depth + 1, opts.indentSize)}${rendered}\\n${pad})`;\n }\n return `${open}\\n${optionsStr}\\n${pad})`;\n }\n if (opts.showValues && value !== undefined) {\n const rendered = formatPrimitive(value, opts);\n return `${open} ${rendered})`;\n }\n return `${open})`;\n }\n\n // If the main value is a Node, print it on next line\n if (isJessNode(value)) {\n const inner = '\\n' + serializeNode(value, depth + 1, opts, visiting);\n visiting.delete(n);\n if (optionsStr) {\n return `${open}\\n${optionsStr}${inner}\\n${pad})`;\n }\n return `${open}${inner}\\n${pad})`;\n }\n\n // Special-case Number plain object: print compact form\n if (typeName === 'Num' && isPlainObject(value)) {\n const num = (value as any).number;\n const keys = Object.keys(value as Record<string, unknown>).filter(k => (value as any)[k] !== undefined);\n if (typeof num === 'number' && (keys.length === 1 || (keys.length === 0))) {\n visiting.delete(n);\n if (optionsStr) {\n return `${open}\\n${optionsStr}\\n${indent(depth + 1, opts.indentSize)}${num}\\n${pad})`;\n }\n return `${open} ${num})`;\n }\n }\n\n // If the main value is an array\n if (Array.isArray(value)) {\n const arrStr = serializeArray(value, depth + 1, opts, visiting);\n visiting.delete(n);\n if (optionsStr) {\n return `${open}\\n${optionsStr}\\n${arrStr}\\n${pad})`;\n }\n return `${open}\\n${arrStr}\\n${pad})`;\n }\n\n // If the main value is a plain object, print key: value summaries\n if (isPlainObject(value)) {\n const inner = serializePlainObject(value as Record<string, unknown>, depth, opts, visiting);\n visiting.delete(n);\n if (optionsStr) {\n return `${open}\\n${optionsStr}${inner ? '\\n' + inner : ''}\\n${pad})`;\n }\n return inner ? `${open}\\n${inner}\\n${pad})` : `${open})`;\n }\n\n visiting.delete(n);\n if (optionsStr) {\n return `${open}\\n${optionsStr}\\n${pad})`;\n }\n return `${open})`;\n}\n\nfunction serializeUnknown(value: unknown, depth: number, opts: Required<SerializeTypesOptions>, visiting: Set<Node>): string {\n if (isJessNode(value)) {\n return serializeNode(value, depth, opts, visiting);\n }\n if (Array.isArray(value)) {\n const arr = summarizeArray(value, opts);\n return `${indent(depth, opts.indentSize)}[${arr}]`;\n }\n if (isPlainObject(value)) {\n const keys = Object.keys(value);\n const parts = keys.map(k => `${k}: ${formatPrimitive((value as Record<string, unknown>)[k], opts)}`);\n return `${indent(depth, opts.indentSize)}{ ${parts.join(', ')} }`;\n }\n return `${indent(depth, opts.indentSize)}${formatPrimitive(value, opts)}`;\n}\n\nexport function serializeTypes(value: unknown, options?: SerializeTypesOptions): string {\n const opts: Required<SerializeTypesOptions> = { ...defaultOptions, ...(options ?? {}) };\n const visiting = new Set<Node>();\n return serializeUnknown(value, 0, opts, visiting);\n}\n","import { List } from '../list.js';\nimport { Sequence } from '../sequence.js';\nimport { Paren } from '../paren.js';\nimport { Node } from '../node.js';\nimport { Rules } from '../rules.js';\nimport { Ruleset } from '../ruleset.js';\nimport { Mixin } from '../mixin.js';\nimport { Comment } from '../comment.js';\nimport { Declaration } from '../declaration.js';\n\nexport type ListItems = readonly Node[];\nexport type EntryKey = number | string | Node;\n\nfunction unwrapDirectListContainer(node: Node): List | Sequence | undefined {\n if (node instanceof List || node instanceof Sequence) {\n return node;\n }\n if (node instanceof Paren && node.get('value') instanceof Node) {\n const inner = node.get('value');\n if (inner instanceof List || inner instanceof Sequence) {\n return inner;\n }\n }\n return undefined;\n}\n\nexport function isListContainer(node: Node): boolean {\n return unwrapDirectListContainer(node) !== undefined;\n}\n\nexport function getListItems(node: Node): ListItems | undefined {\n const container = unwrapDirectListContainer(node);\n return container?.get('value');\n}\n\nexport function isBracketedList(node: Node): boolean {\n if (node instanceof Paren) {\n return (node.options?.delimiter ?? 'paren') === 'square' && unwrapDirectListContainer(node) !== undefined;\n }\n const parent = node.parent;\n return parent instanceof Paren\n && parent.get('value') === node\n && (parent.options?.delimiter ?? 'paren') === 'square'\n && unwrapDirectListContainer(parent) !== undefined;\n}\n\nexport function getListSeparator(node: Node): ',' | ';' | '/' | ' ' {\n const container = unwrapDirectListContainer(node);\n if (container instanceof List) {\n return container.options?.sep ?? ' ';\n }\n return ' ';\n}\n\nexport function coerceListItems(node: Node): ListItems {\n if (node instanceof List && node.length === 1 && node.get('value')[0] instanceof Sequence) {\n return node.get('value')[0].get('value');\n }\n return getListItems(node) ?? [node];\n}\n\nexport function* iterateItems(input: Node): Generator<[Node, EntryKey]> {\n const items = getListItems(input);\n if (items) {\n for (let key = 0; key < items.length; key++) {\n const value = items[key];\n if (value) {\n yield [value, key];\n }\n }\n return;\n }\n\n if (input instanceof Rules || input instanceof Ruleset || input instanceof Mixin) {\n const rules = input instanceof Rules\n ? input.value\n : input instanceof Ruleset\n ? input.get('rules')?.value ?? []\n : input.get('rules')?.value ?? [];\n for (const rule of rules) {\n if (!rule || rule instanceof Comment) {\n continue;\n }\n if (!(rule instanceof Declaration)) {\n continue;\n }\n yield [rule.get('value'), rule.get('name')];\n }\n return;\n }\n\n yield [input, 0];\n}\n","import { Dimension, Num } from './tree/index.js';\nimport { isNode } from './tree/util/is-node.js';\nimport { N } from './tree/node-type.js';\nimport type { Context } from './context.js';\nimport type { MaybePromise } from '@jesscss/awaitable-pipe';\n\n// Conversion function types\nexport type ConversionPlugin = (value: unknown) => number | unknown;\n\n/**\n * PreprocessParams function type for preprocessing entire argument arrays\n * Can be synchronous or asynchronous\n */\nexport type PreprocessParams = (args: any[], context: Context) => MaybePromise<any[]>;\n\n/**\n * Simple memoization utility for factory functions\n * Caches results based on stringified arguments\n */\nfunction memoize<Args extends any[], Return>(\n fn: (...args: Args) => Return\n): (...args: Args) => Return {\n const cache = new Map<string, Return>();\n return (...args: Args): Return => {\n const key = JSON.stringify(args);\n if (cache.has(key)) {\n return cache.get(key)!;\n }\n const result = fn(...args);\n cache.set(key, result);\n return result;\n };\n}\n\n/**\n * Converts percentage values to a fraction of the specified base value\n * @param base - The base value to convert percentages to (e.g., 255 for RGB, 100 for HSL)\n * Memoized so that percentOf(255) always returns the same function instance\n */\nexport const percentOf = memoize((base: number): ConversionPlugin => (value: unknown) => {\n if (value instanceof Dimension && value.unit === '%') {\n const converted = value.number * base / 100;\n return new Num(converted);\n }\n return value;\n});\n\n/**\n * Converts angle units to degrees\n * Supports: deg, turn, rad, grad\n * Memoized so that angleToDegrees() always returns the same function instance\n */\nexport const angleToDegrees = memoize((): ConversionPlugin => (value: unknown) => {\n if (!(value instanceof Dimension)) {\n return value;\n }\n const { number, unit } = value;\n if (unit === 'turn') {\n return new Num(number * 360);\n }\n if (unit === 'rad') {\n return new Num(number * 180 / Math.PI);\n }\n if (unit === 'grad') {\n return new Num(number * 0.9);\n }\n if (unit === 'deg' || unit === '') {\n return new Num(number);\n }\n return value;\n});\n\n/**\n * Normalizes hue values to 0-360 degree range\n * Supports: deg, turn, rad, grad, % (percentage of 360)\n * Memoized so that normalizeHue() always returns the same function instance\n */\nexport const normalizeHue = memoize((): ConversionPlugin => (value: unknown) => {\n if (!(value instanceof Dimension)) {\n return value;\n }\n const { number, unit } = value;\n let degrees = number;\n\n if (unit === 'turn') {\n degrees = number * 360;\n } else if (unit === 'rad') {\n degrees = number * 180 / Math.PI;\n } else if (unit === 'grad') {\n degrees = number * 0.9;\n } else if (unit === '%') {\n degrees = number * 360 / 100;\n } else if (unit === 'deg' || unit === '') {\n degrees = number;\n } else {\n return value; // Don't convert if unit is not recognized\n }\n\n // Normalize to 0-360 range\n degrees = ((degrees % 360) + 360) % 360;\n return new Num(degrees);\n});\n\n/**\n * Converts alpha values to 0-1 range\n * Supports: % (percentage of 1), unitless numbers\n * Memoized so that alphaToNumber() always returns the same function instance\n */\nexport const alphaToNumber = memoize((): ConversionPlugin => (value: unknown) => {\n if (!(value instanceof Dimension)) {\n return value;\n }\n const { number, unit } = value;\n let result = number;\n\n if (unit === '%') {\n result = number / 100;\n } else if (unit === '') {\n result = number;\n } else {\n return value; // Don't convert if unit is not recognized\n }\n\n const clamped = Math.max(0, Math.min(1, result));\n return new Num(clamped);\n});\n\n/**\n * Converts any dimension to a number (removes units)\n * Memoized so that toNumber() always returns the same function instance\n */\nexport const toNumber = memoize((): ConversionPlugin => (value: unknown) => {\n if (value instanceof Dimension) {\n return new Num(value.number); // Extract number from Dimension\n }\n if (value instanceof Num) {\n return new Num(value.number);\n }\n return value; // Don't know how to handle this, pass through\n});\n\nexport const clamp = (min: number, max: number): ConversionPlugin => (value: unknown) => {\n if (typeof value === 'number') {\n return Math.max(min, Math.min(max, value));\n }\n return value;\n};\n\n/**\n * Converts length units to pixels\n * Supports: px, em, rem, in, cm, mm, pt, pc\n */\nexport const lengthToPx = (baseFontSize: number = 16): ConversionPlugin => (value: unknown) => {\n if (!(value instanceof Dimension)) {\n return value;\n }\n const { number, unit } = value;\n\n switch (unit) {\n case 'px': return new Num(number);\n case 'em': return new Num(number * baseFontSize);\n case 'rem': return new Num(number * baseFontSize);\n case 'in': return new Num(number * 96);\n case 'cm': return new Num(number * 96 / 2.54);\n case 'mm': return new Num(number * 96 / 25.4);\n case 'pt': return new Num(number * 96 / 72);\n case 'pc': return new Num(number * 96 / 6);\n default: return value;\n }\n};\n\n/**\n * Converts time units to milliseconds\n * Supports: ms, s\n */\nexport const timeToMs = (): ConversionPlugin => (value: unknown) => {\n if (!(value instanceof Dimension)) {\n return value;\n }\n const { number, unit } = value;\n if (unit === 'ms') {\n return new Num(number);\n }\n if (unit === 's') {\n return new Num(number * 1000);\n }\n return value;\n};\n\n/**\n * Converts frequency units to hertz\n * Supports: hz, khz\n */\nexport const frequencyToHz = (): ConversionPlugin => (value: unknown) => {\n if (!(value instanceof Dimension)) {\n return value;\n }\n const { number, unit } = value;\n if (unit === 'hz') {\n return new Num(number);\n }\n if (unit === 'khz') {\n return new Num(number * 1000);\n }\n return value;\n};\n\n/**\n * Converts angle units to radians\n * Supports: deg, turn, rad, grad\n */\nexport const angleToRadians = (): ConversionPlugin => (value: unknown) => {\n if (!(value instanceof Dimension)) {\n return value;\n }\n const { number, unit } = value;\n if (unit === 'turn') {\n return new Num(number * 2 * Math.PI);\n }\n if (unit === 'rad') {\n return new Num(number);\n }\n if (unit === 'grad') {\n return new Num(number * Math.PI / 200);\n }\n if (unit === 'deg' || unit === '') {\n return new Num(number * Math.PI / 180);\n }\n return value;\n};\n\n/**\n * Creates a preprocessParams function that splits a Sequence into individual arguments.\n * Handles operations with slashes (/) by distributing the left and right operands.\n *\n * @example\n * ```typescript\n * const rgb = defineFunction('rgb', function(r, g, b, a?) {\n * // ...\n * }, {\n * preprocessParams: [splitSequence()]\n * });\n * ```\n */\nexport const splitSequence = (): PreprocessParams => {\n return (args: any[], _context: Context): any[] => {\n // Only process if we have exactly one argument that is a Sequence\n if (args.length !== 1 || !isNode(args[0], N.Sequence)) {\n return args;\n }\n\n const sequence = args[0];\n\n // Split the sequence into individual arguments\n const splitArgs: any[] = [];\n const seqItems = sequence.get('value');\n for (let i = 0; i < seqItems.length; i++) {\n const item = seqItems[i]!;\n\n // Check if this is the last item and it's an Operation (likely a slash)\n if (i === seqItems.length - 1 && item.type === 'Operation') {\n const left = item.get('left');\n const right = item.get('right');\n // Add the left operand\n splitArgs.push(left);\n // Add the right operand if it exists and is not a placeholder (Num with value 0)\n // This handles test cases where Num(0) is used as a placeholder for undefined\n if (right) {\n const isPlaceholder = isNode(right, N.Dimension)\n && right.number === 0;\n if (!isPlaceholder) {\n splitArgs.push(right);\n }\n }\n } else {\n splitArgs.push(item);\n }\n }\n\n return splitArgs;\n };\n};\n","import {\n Node,\n type NodeVisitReturn,\n ABORT,\n REMOVE\n} from '../tree/node.js';\n// import { type isNode } from '../tree/util'\nimport type * as tree from '../tree/index.js';\n\n// const { isArray } = Array\n\n// type GuardedType<T> = typeof isNode extends (value: any, type: T) => value is infer U ? U : never\n\nconst lowerFirst = (s: string) => s.charAt(0).toLowerCase() + s.slice(1);\nexport { ABORT, REMOVE };\nexport const SKIP: unique symbol = Symbol('SKIP');\n\ntype VisitorReturn = NodeVisitReturn | typeof SKIP;\nexport type VisitorContext = {\n visitDeeper?: boolean;\n};\n\n/**\n * Define all the optional methods one can define on a visitor that can be visited\n *\n * @todo - Write type tests for methods\n */\nexport interface Visitor {\n\n /** Optional methods called before entering / exiting the visitor */\n enter?(n?: tree.Node): void | typeof ABORT;\n /**\n * `exit()` gets passed the top-most visitor result,\n * in case we want to transform it on the way out.\n */\n exit?(val?: NodeVisitReturn): NodeVisitReturn;\n\n /** Visitor methods */\n atRule?(n: tree.AtRule, ctx?: VisitorContext): VisitorReturn;\n atRuleExit?(n: tree.AtRule, ctx?: VisitorContext): void;\n block?(n: tree.Block, ctx?: VisitorContext): VisitorReturn;\n blockExit?(n: tree.Block, ctx?: VisitorContext): void;\n bool?(n: tree.Bool, ctx?: VisitorContext): VisitorReturn;\n boolExit?(n: tree.Bool, ctx?: VisitorContext): void;\n ampersand?(n: tree.Ampersand, ctx?: VisitorContext): VisitorReturn;\n ampersandExit?(n: tree.Ampersand, ctx?: VisitorContext): void;\n any?(n: tree.Any, ctx?: VisitorContext): VisitorReturn;\n anyExit?(n: tree.Any, ctx?: VisitorContext): void;\n anonymous?(n: tree.Anonymous, ctx?: VisitorContext): VisitorReturn;\n anonymousExit?(n: tree.Anonymous, ctx?: VisitorContext): void;\n call?(n: tree.Call, ctx?: VisitorContext): VisitorReturn;\n callExit?(n: tree.Call, ctx?: VisitorContext): void;\n collection?(n: tree.Collection, ctx?: VisitorContext): VisitorReturn;\n collectionExit?(n: tree.Collection, ctx?: VisitorContext): void;\n color?(n: tree.Color, ctx?: VisitorContext): VisitorReturn;\n colorExit?(n: tree.Color, ctx?: VisitorContext): void;\n comment?(n: tree.Comment, ctx?: VisitorContext): VisitorReturn;\n commentExit?(n: tree.Comment, ctx?: VisitorContext): void;\n combinator?(n: tree.Combinator, ctx?: VisitorContext): VisitorReturn;\n combinatorExit?(n: tree.Combinator, ctx?: VisitorContext): void;\n condition?(n: tree.Condition, ctx?: VisitorContext): VisitorReturn;\n conditionExit?(n: tree.Condition, ctx?: VisitorContext): void;\n customDeclaration?(n: tree.CustomDeclaration, ctx?: VisitorContext): VisitorReturn;\n customDeclarationExit?(n: tree.CustomDeclaration, ctx?: VisitorContext): void;\n declaration?(n: tree.Declaration): VisitorReturn;\n declarationExit?(n: tree.Declaration, ctx?: VisitorContext): void;\n dimension?(n: tree.Dimension, ctx?: VisitorContext): VisitorReturn;\n dimensionExit?(n: tree.Dimension, ctx?: VisitorContext): void;\n expression?(n: tree.Expression, ctx?: VisitorContext): VisitorReturn;\n expressionExit?(n: tree.Expression, ctx?: VisitorContext): void;\n extend?(n: tree.Extend, ctx?: VisitorContext): VisitorReturn;\n extendExit?(n: tree.Extend, ctx?: VisitorContext): void;\n list?(n: tree.List<Node>, ctx?: VisitorContext): VisitorReturn;\n listExit?(n: tree.List<Node>, ctx?: VisitorContext): void;\n mixin?(n: tree.Mixin, ctx?: VisitorContext): VisitorReturn;\n mixinExit?(n: tree.Mixin, ctx?: VisitorContext): void;\n negative?(n: tree.Negative, ctx?: VisitorContext): VisitorReturn;\n negativeExit?(n: tree.Negative, ctx?: VisitorContext): void;\n func?(n: tree.Func, ctx?: VisitorContext): VisitorReturn;\n funcExit?(n: tree.Func, ctx?: VisitorContext): void;\n jsFunction?(n: tree.JsFunction): VisitorReturn;\n jsFunctionExit?(n: tree.JsFunction, ctx?: VisitorContext): void;\n nil?(n: tree.Nil, ctx?: VisitorContext): VisitorReturn;\n nilExit?(n: tree.Nil, ctx?: VisitorContext): void;\n operation?(n: tree.Operation, ctx?: VisitorContext): VisitorReturn;\n operationExit?(n: tree.Operation, ctx?: VisitorContext): void;\n paren?(n: tree.Paren, ctx?: VisitorContext): VisitorReturn;\n parenExit?(n: tree.Paren, ctx?: VisitorContext): void;\n queryCondition?(n: tree.QueryCondition, ctx?: VisitorContext): VisitorReturn;\n queryConditionExit?(n: tree.QueryCondition, ctx?: VisitorContext): void;\n quoted?(n: tree.Quoted, ctx?: VisitorContext): VisitorReturn;\n quotedExit?(n: tree.Quoted, ctx?: VisitorContext): void;\n ruleset?(n: tree.Ruleset, ctx?: VisitorContext): VisitorReturn;\n rulesetExit?(n: tree.Ruleset, ctx?: VisitorContext): void;\n rules?(n: tree.Rules, ctx?: VisitorContext): VisitorReturn;\n rulesExit?(n: tree.Rules, ctx?: VisitorContext): void;\n attributeSelector?(n: tree.AttributeSelector, ctx?: VisitorContext): VisitorReturn;\n attributeSelectorExit?(n: tree.AttributeSelector, ctx?: VisitorContext): void;\n basicSelector?(n: tree.BasicSelector, ctx?: VisitorContext): VisitorReturn;\n basicSelectorExit?(n: tree.BasicSelector, ctx?: VisitorContext): void;\n selectorList?(n: tree.SelectorList, ctx?: VisitorContext): VisitorReturn;\n selectorListExit?(n: tree.SelectorList, ctx?: VisitorContext): void;\n pseudoSelector?(n: tree.PseudoSelector, ctx?: VisitorContext): VisitorReturn;\n pseudoSelectorExit?(n: tree.PseudoSelector, ctx?: VisitorContext): void;\n compoundSelector?(n: tree.CompoundSelector, ctx?: VisitorContext): VisitorReturn;\n compoundSelectorExit?(n: tree.CompoundSelector, ctx?: VisitorContext): void;\n complexSelector?(n: tree.ComplexSelector, ctx?: VisitorContext): VisitorReturn;\n complexSelectorExit?(n: tree.ComplexSelector, ctx?: VisitorContext): void;\n sequence?(n: tree.Sequence, ctx?: VisitorContext): VisitorReturn;\n sequenceExit?(n: tree.Sequence, ctx?: VisitorContext): void;\n varDeclaration?(n: tree.VarDeclaration, ctx?: VisitorContext): VisitorReturn;\n varDeclarationExit?(n: tree.VarDeclaration, ctx?: VisitorContext): void;\n reference?(n: tree.Reference, ctx?: VisitorContext): VisitorReturn;\n referenceExit?(n: tree.Reference, ctx?: VisitorContext): void;\n styleImport?(n: tree.StyleImport, ctx?: VisitorContext): VisitorReturn;\n styleImportExit?(n: tree.StyleImport, ctx?: VisitorContext): void;\n interpolated?(n: tree.Interpolated, ctx?: VisitorContext): VisitorReturn;\n interpolatedExit?(n: tree.Interpolated, ctx?: VisitorContext): void;\n defaultGuard?(n: tree.DefaultGuard, ctx?: VisitorContext): VisitorReturn;\n defaultGuardExit?(n: tree.DefaultGuard, ctx?: VisitorContext): void;\n rest?(n: tree.Rest, ctx?: VisitorContext): VisitorReturn;\n restExit?(n: tree.Rest, ctx?: VisitorContext): void;\n}\n\nexport abstract class Visitor {\n private readonly _methodMap = new Map<string, ((n: Node, ctx?: VisitorContext) => VisitorReturn) | false>();\n /** Temporary state, set on first visit and later un-set when exiting */\n protected startNode: Node | undefined;\n\n getMethod(s: string) {\n let lower = this._methodMap.get(s);\n /**\n * if we previously looked for the method and it doesn't exist,\n * then explicitly set the map record to false.\n */\n if (!lower && lower !== false) {\n // @ts-expect-error - Its ok if it doesn't exist\n lower = this[lowerFirst(s)];\n this._methodMap.set(s, lower ?? false);\n }\n return lower;\n }\n\n protected _visit(n: Node, ctx?: VisitorContext): VisitorReturn {\n let fn = this.getMethod(n.type);\n if (fn) {\n return fn.call(this, n, ctx) ?? n;\n }\n return n;\n }\n\n visitExit(n: Node, ctx?: VisitorContext) {\n let fn = this.getMethod(`${n.type}Exit`);\n if (fn) {\n fn.call(this, n, ctx);\n }\n }\n\n /**\n * Visit will always return a Node\n */\n visit(n: Node): Node {\n this.startNode = n;\n const originalVisit = this.visit;\n /**\n * Bind to inner _visit, so that all inner calls will not call this current method again\n */\n this.visit = this._visit.bind(this) as typeof this.visit;\n let possibleAbort = this.enter?.(n);\n if (possibleAbort === ABORT) {\n return n;\n }\n let returnVal = this._visit(n);\n this.visit = originalVisit.bind(this);\n /** Apply any final transformations / decisions */\n returnVal = this.exit?.(returnVal) ?? returnVal;\n this.startNode = undefined;\n if (returnVal instanceof Node) {\n return returnVal;\n }\n return n;\n }\n}\n\n/**\n * This is a specific visitor type that auto-walks the tree,\n * and optionally mutates children nodes.\n *\n * @note If you are extending this class, you DO NOT HAVE TO\n * manually visit children nodes. This class will do it for you.\n */\nexport abstract class TreeVisitor extends Visitor {\n /** Visit children nodes before or after visiting the parent node */\n visitChildren: 'before' | 'after' = 'after';\n visitedNodes = new Set<Node>();\n\n constructor(\n public reverse?: boolean\n ) {\n super();\n }\n\n override enter(n: tree.Node) {\n this.visitedNodes.clear();\n }\n\n override _visit(n: Node, ctx: VisitorContext) {\n if (this.visitedNodes.has(n)) {\n return n;\n }\n this.visitedNodes.add(n);\n const { reverse } = this;\n\n // If node has accept() method, let it control traversal\n // This allows nodes to customize traversal (e.g., Less.js compatibility)\n // accept() will visit self and children, so we don't auto-visit here\n const hasAccept = n.accept && typeof n.accept === 'function';\n const hasCustomAccept = hasAccept && n.accept !== Node.prototype.accept;\n if (hasCustomAccept) {\n const returnVal = n.accept(this);\n if (!returnVal || typeof returnVal === 'symbol') {\n return returnVal;\n }\n // accept() already visited self and children, so we just handle exit\n this.visitExit(n, ctx);\n if (returnVal instanceof Node) {\n this.visitedNodes.add(returnVal);\n }\n return returnVal;\n }\n\n // Default: auto-visit children (node doesn't have accept() or doesn't override it)\n if (this.visitChildren === 'before') {\n for (const node of n.children(true, reverse, true)) {\n this._visit(node, ctx);\n }\n const returnVal = super._visit(n, ctx);\n /** @node The exit function passes in the original node */\n this.visitExit(n, ctx);\n /** Don't visit new created nodes */\n if (returnVal instanceof Node) {\n this.visitedNodes.add(returnVal);\n }\n return returnVal;\n }\n let returnVal = super._visit(n, ctx);\n if (!returnVal || typeof returnVal === 'symbol') {\n return returnVal;\n }\n\n if (returnVal !== n) {\n /** Don't visit new created nodes */\n this.visitedNodes.add(returnVal);\n } else {\n for (const node of n.children(true, reverse, true)) {\n this._visit(node, ctx);\n }\n }\n\n this.visitExit(n, ctx);\n return returnVal;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,OACd,OACA,MACS;AACT,KAAI,CAAC,MACH,QAAO;AAET,KAAI,SAAS,KAAA,GAAW;;AAEtB,MAAI,iBAAiB,KACnB,QAAO;EAET,MAAM,SAAS;AACf,SAAO,OAAO,OAAO,SAAS,YAAY,OAAO,OAAO,aAAa;;AAGvE,SADe,MACC,WAAsB,UAAU;;;;;;;;;;;;;AC3BlD,IAAY,IAAL,yBAAA,GAAA;AAEL,GAAA,EAAA,mBAAA,KAAA;AACA,GAAA,EAAA,eAAA,KAAA;AACA,GAAA,EAAA,oBAAA,KAAA;AACA,GAAA,EAAA,sBAAA,KAAA;AACA,GAAA,EAAA,qBAAA,MAAA;AACA,GAAA,EAAA,kBAAA,MAAA;AACA,GAAA,EAAA,gBAAA,MAAA;AAGA,GAAA,EAAA,SAAA,OAAA;AACA,GAAA,EAAA,WAAA,OAAA;AACA,GAAA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