@motionscript/core 0.1.0 → 0.1.1-alpha.1

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 (1072) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/assets/asset-index.d.ts +1 -8
  3. package/dist/assets/asset-index.d.ts.map +1 -1
  4. package/dist/assets/asset-index.js +1 -8
  5. package/dist/assets/asset-index.js.map +1 -1
  6. package/dist/assets/catalog.d.ts +10 -72
  7. package/dist/assets/catalog.d.ts.map +1 -1
  8. package/dist/assets/catalog.js +3 -29
  9. package/dist/assets/catalog.js.map +1 -1
  10. package/dist/assets/errors.d.ts +8 -20
  11. package/dist/assets/errors.d.ts.map +1 -1
  12. package/dist/assets/errors.js +8 -20
  13. package/dist/assets/errors.js.map +1 -1
  14. package/dist/assets/index.d.ts.map +1 -1
  15. package/dist/assets/index.js.map +1 -1
  16. package/dist/assets/manager.d.ts +9 -51
  17. package/dist/assets/manager.d.ts.map +1 -1
  18. package/dist/assets/manager.js +13 -78
  19. package/dist/assets/manager.js.map +1 -1
  20. package/dist/assets/record.d.ts +2 -18
  21. package/dist/assets/record.d.ts.map +1 -1
  22. package/dist/assets/record.js.map +1 -1
  23. package/dist/assets/scope.d.ts +3 -18
  24. package/dist/assets/scope.d.ts.map +1 -1
  25. package/dist/assets/scope.js +2 -11
  26. package/dist/assets/scope.js.map +1 -1
  27. package/dist/attributes/audio/effects/chain.d.ts +2 -12
  28. package/dist/attributes/audio/effects/chain.d.ts.map +1 -1
  29. package/dist/attributes/audio/effects/chain.js +1 -7
  30. package/dist/attributes/audio/effects/chain.js.map +1 -1
  31. package/dist/attributes/audio/effects/registry.d.ts +3 -18
  32. package/dist/attributes/audio/effects/registry.d.ts.map +1 -1
  33. package/dist/attributes/audio/effects/registry.js +4 -23
  34. package/dist/attributes/audio/effects/registry.js.map +1 -1
  35. package/dist/attributes/audio/ramp.d.ts +5 -38
  36. package/dist/attributes/audio/ramp.d.ts.map +1 -1
  37. package/dist/attributes/audio/ramp.js +3 -28
  38. package/dist/attributes/audio/ramp.js.map +1 -1
  39. package/dist/attributes/audio/request.d.ts +10 -80
  40. package/dist/attributes/audio/request.d.ts.map +1 -1
  41. package/dist/attributes/audio/request.js +1 -4
  42. package/dist/attributes/audio/request.js.map +1 -1
  43. package/dist/attributes/audio/schedule.d.ts +2 -12
  44. package/dist/attributes/audio/schedule.d.ts.map +1 -1
  45. package/dist/attributes/audio/schedule.js +2 -11
  46. package/dist/attributes/audio/schedule.js.map +1 -1
  47. package/dist/attributes/audio/sound.d.ts +2 -26
  48. package/dist/attributes/audio/sound.d.ts.map +1 -1
  49. package/dist/attributes/audio/sound.js +1 -9
  50. package/dist/attributes/audio/sound.js.map +1 -1
  51. package/dist/attributes/audio/transition.d.ts +1 -8
  52. package/dist/attributes/audio/transition.d.ts.map +1 -1
  53. package/dist/attributes/audio/transition.js.map +1 -1
  54. package/dist/attributes/layout/alignment.d.ts +6 -38
  55. package/dist/attributes/layout/alignment.d.ts.map +1 -1
  56. package/dist/attributes/layout/alignment.js.map +1 -1
  57. package/dist/attributes/layout/insets.d.ts +2 -27
  58. package/dist/attributes/layout/insets.d.ts.map +1 -1
  59. package/dist/attributes/layout/insets.js.map +1 -1
  60. package/dist/attributes/layout/matrix2d.d.ts +29 -114
  61. package/dist/attributes/layout/matrix2d.d.ts.map +1 -1
  62. package/dist/attributes/layout/matrix2d.js +26 -110
  63. package/dist/attributes/layout/matrix2d.js.map +1 -1
  64. package/dist/attributes/layout/size.d.ts +3 -25
  65. package/dist/attributes/layout/size.d.ts.map +1 -1
  66. package/dist/attributes/layout/size.js +2 -18
  67. package/dist/attributes/layout/size.js.map +1 -1
  68. package/dist/attributes/layout/space3d.d.ts +16 -79
  69. package/dist/attributes/layout/space3d.d.ts.map +1 -1
  70. package/dist/attributes/layout/space3d.js +17 -81
  71. package/dist/attributes/layout/space3d.js.map +1 -1
  72. package/dist/attributes/layout/transform3d.d.ts +2 -23
  73. package/dist/attributes/layout/transform3d.d.ts.map +1 -1
  74. package/dist/attributes/layout/transform3d.js +1 -7
  75. package/dist/attributes/layout/transform3d.js.map +1 -1
  76. package/dist/attributes/layout/world-transform.d.ts +2 -16
  77. package/dist/attributes/layout/world-transform.d.ts.map +1 -1
  78. package/dist/attributes/layout/world-transform.js.map +1 -1
  79. package/dist/attributes/properties/decorator.d.ts +13 -73
  80. package/dist/attributes/properties/decorator.d.ts.map +1 -1
  81. package/dist/attributes/properties/decorator.js +9 -40
  82. package/dist/attributes/properties/decorator.js.map +1 -1
  83. package/dist/attributes/properties/typed.d.ts +6 -45
  84. package/dist/attributes/properties/typed.d.ts.map +1 -1
  85. package/dist/attributes/properties/typed.js +6 -37
  86. package/dist/attributes/properties/typed.js.map +1 -1
  87. package/dist/attributes/render3d/orbit.d.ts +11 -83
  88. package/dist/attributes/render3d/orbit.d.ts.map +1 -1
  89. package/dist/attributes/render3d/orbit.js +10 -73
  90. package/dist/attributes/render3d/orbit.js.map +1 -1
  91. package/dist/attributes/shape/corners/corner-radius.d.ts +1 -6
  92. package/dist/attributes/shape/corners/corner-radius.d.ts.map +1 -1
  93. package/dist/attributes/shape/corners/corner-radius.js.map +1 -1
  94. package/dist/attributes/shape/corners/corner-style.d.ts +4 -25
  95. package/dist/attributes/shape/corners/corner-style.d.ts.map +1 -1
  96. package/dist/attributes/shape/corners/corner-style.js +2 -12
  97. package/dist/attributes/shape/corners/corner-style.js.map +1 -1
  98. package/dist/attributes/shape/corners/corners.d.ts +2 -21
  99. package/dist/attributes/shape/corners/corners.d.ts.map +1 -1
  100. package/dist/attributes/shape/corners/corners.js +2 -12
  101. package/dist/attributes/shape/corners/corners.js.map +1 -1
  102. package/dist/attributes/shape/effects/backdrop.d.ts +2 -18
  103. package/dist/attributes/shape/effects/backdrop.d.ts.map +1 -1
  104. package/dist/attributes/shape/effects/backdrop.js +3 -26
  105. package/dist/attributes/shape/effects/backdrop.js.map +1 -1
  106. package/dist/attributes/shape/effects/chain.d.ts +36 -328
  107. package/dist/attributes/shape/effects/chain.d.ts.map +1 -1
  108. package/dist/attributes/shape/effects/chain.js +24 -242
  109. package/dist/attributes/shape/effects/chain.js.map +1 -1
  110. package/dist/attributes/shape/effects/effect-data.d.ts +19 -127
  111. package/dist/attributes/shape/effects/effect-data.d.ts.map +1 -1
  112. package/dist/attributes/shape/effects/effect-data.js +6 -33
  113. package/dist/attributes/shape/effects/effect-data.js.map +1 -1
  114. package/dist/attributes/shape/effects/implementations/ascii.d.ts +6 -26
  115. package/dist/attributes/shape/effects/implementations/ascii.d.ts.map +1 -1
  116. package/dist/attributes/shape/effects/implementations/ascii.js +0 -3
  117. package/dist/attributes/shape/effects/implementations/ascii.js.map +1 -1
  118. package/dist/attributes/shape/effects/implementations/bit-crush.d.ts +2 -21
  119. package/dist/attributes/shape/effects/implementations/bit-crush.d.ts.map +1 -1
  120. package/dist/attributes/shape/effects/implementations/bit-crush.js +0 -1
  121. package/dist/attributes/shape/effects/implementations/bit-crush.js.map +1 -1
  122. package/dist/attributes/shape/effects/implementations/block-displace.d.ts +1 -14
  123. package/dist/attributes/shape/effects/implementations/block-displace.d.ts.map +1 -1
  124. package/dist/attributes/shape/effects/implementations/block-displace.js +0 -1
  125. package/dist/attributes/shape/effects/implementations/block-displace.js.map +1 -1
  126. package/dist/attributes/shape/effects/implementations/bloom.d.ts +0 -1
  127. package/dist/attributes/shape/effects/implementations/bloom.d.ts.map +1 -1
  128. package/dist/attributes/shape/effects/implementations/bloom.js +0 -1
  129. package/dist/attributes/shape/effects/implementations/bloom.js.map +1 -1
  130. package/dist/attributes/shape/effects/implementations/blur.d.ts +0 -1
  131. package/dist/attributes/shape/effects/implementations/blur.d.ts.map +1 -1
  132. package/dist/attributes/shape/effects/implementations/blur.js +0 -1
  133. package/dist/attributes/shape/effects/implementations/blur.js.map +1 -1
  134. package/dist/attributes/shape/effects/implementations/bulge.d.ts +0 -1
  135. package/dist/attributes/shape/effects/implementations/bulge.d.ts.map +1 -1
  136. package/dist/attributes/shape/effects/implementations/bulge.js +0 -1
  137. package/dist/attributes/shape/effects/implementations/bulge.js.map +1 -1
  138. package/dist/attributes/shape/effects/implementations/chromatic-aberration.d.ts +0 -1
  139. package/dist/attributes/shape/effects/implementations/chromatic-aberration.d.ts.map +1 -1
  140. package/dist/attributes/shape/effects/implementations/chromatic-aberration.js +0 -1
  141. package/dist/attributes/shape/effects/implementations/chromatic-aberration.js.map +1 -1
  142. package/dist/attributes/shape/effects/implementations/color-adjustment.d.ts +1 -12
  143. package/dist/attributes/shape/effects/implementations/color-adjustment.d.ts.map +1 -1
  144. package/dist/attributes/shape/effects/implementations/color-adjustment.js +0 -1
  145. package/dist/attributes/shape/effects/implementations/color-adjustment.js.map +1 -1
  146. package/dist/attributes/shape/effects/implementations/curves.d.ts +1 -11
  147. package/dist/attributes/shape/effects/implementations/curves.d.ts.map +1 -1
  148. package/dist/attributes/shape/effects/implementations/curves.js +1 -6
  149. package/dist/attributes/shape/effects/implementations/curves.js.map +1 -1
  150. package/dist/attributes/shape/effects/implementations/directional-blur.d.ts +0 -1
  151. package/dist/attributes/shape/effects/implementations/directional-blur.d.ts.map +1 -1
  152. package/dist/attributes/shape/effects/implementations/directional-blur.js +0 -1
  153. package/dist/attributes/shape/effects/implementations/directional-blur.js.map +1 -1
  154. package/dist/attributes/shape/effects/implementations/dither.d.ts +4 -35
  155. package/dist/attributes/shape/effects/implementations/dither.d.ts.map +1 -1
  156. package/dist/attributes/shape/effects/implementations/dither.js +1 -7
  157. package/dist/attributes/shape/effects/implementations/dither.js.map +1 -1
  158. package/dist/attributes/shape/effects/implementations/drop-shadow.d.ts +1 -22
  159. package/dist/attributes/shape/effects/implementations/drop-shadow.d.ts.map +1 -1
  160. package/dist/attributes/shape/effects/implementations/drop-shadow.js +0 -1
  161. package/dist/attributes/shape/effects/implementations/drop-shadow.js.map +1 -1
  162. package/dist/attributes/shape/effects/implementations/duotone.d.ts +1 -9
  163. package/dist/attributes/shape/effects/implementations/duotone.d.ts.map +1 -1
  164. package/dist/attributes/shape/effects/implementations/duotone.js +0 -1
  165. package/dist/attributes/shape/effects/implementations/duotone.js.map +1 -1
  166. package/dist/attributes/shape/effects/implementations/edges.d.ts +2 -15
  167. package/dist/attributes/shape/effects/implementations/edges.d.ts.map +1 -1
  168. package/dist/attributes/shape/effects/implementations/edges.js +0 -1
  169. package/dist/attributes/shape/effects/implementations/edges.js.map +1 -1
  170. package/dist/attributes/shape/effects/implementations/glass.d.ts +1 -14
  171. package/dist/attributes/shape/effects/implementations/glass.d.ts.map +1 -1
  172. package/dist/attributes/shape/effects/implementations/glass.js +0 -1
  173. package/dist/attributes/shape/effects/implementations/glass.js.map +1 -1
  174. package/dist/attributes/shape/effects/implementations/glow.d.ts +7 -47
  175. package/dist/attributes/shape/effects/implementations/glow.d.ts.map +1 -1
  176. package/dist/attributes/shape/effects/implementations/glow.js +1 -9
  177. package/dist/attributes/shape/effects/implementations/glow.js.map +1 -1
  178. package/dist/attributes/shape/effects/implementations/grain.d.ts +1 -14
  179. package/dist/attributes/shape/effects/implementations/grain.d.ts.map +1 -1
  180. package/dist/attributes/shape/effects/implementations/grain.js +0 -1
  181. package/dist/attributes/shape/effects/implementations/grain.js.map +1 -1
  182. package/dist/attributes/shape/effects/implementations/grayscale.d.ts +0 -1
  183. package/dist/attributes/shape/effects/implementations/grayscale.d.ts.map +1 -1
  184. package/dist/attributes/shape/effects/implementations/grayscale.js +0 -1
  185. package/dist/attributes/shape/effects/implementations/grayscale.js.map +1 -1
  186. package/dist/attributes/shape/effects/implementations/halftone.d.ts +5 -29
  187. package/dist/attributes/shape/effects/implementations/halftone.d.ts.map +1 -1
  188. package/dist/attributes/shape/effects/implementations/halftone.js +0 -1
  189. package/dist/attributes/shape/effects/implementations/halftone.js.map +1 -1
  190. package/dist/attributes/shape/effects/implementations/invert.d.ts +3 -12
  191. package/dist/attributes/shape/effects/implementations/invert.d.ts.map +1 -1
  192. package/dist/attributes/shape/effects/implementations/invert.js +0 -1
  193. package/dist/attributes/shape/effects/implementations/invert.js.map +1 -1
  194. package/dist/attributes/shape/effects/implementations/kaleidoscope.d.ts +2 -19
  195. package/dist/attributes/shape/effects/implementations/kaleidoscope.d.ts.map +1 -1
  196. package/dist/attributes/shape/effects/implementations/kaleidoscope.js +1 -5
  197. package/dist/attributes/shape/effects/implementations/kaleidoscope.js.map +1 -1
  198. package/dist/attributes/shape/effects/implementations/lut.d.ts +11 -36
  199. package/dist/attributes/shape/effects/implementations/lut.d.ts.map +1 -1
  200. package/dist/attributes/shape/effects/implementations/lut.js +2 -8
  201. package/dist/attributes/shape/effects/implementations/lut.js.map +1 -1
  202. package/dist/attributes/shape/effects/implementations/magnify.d.ts +0 -1
  203. package/dist/attributes/shape/effects/implementations/magnify.d.ts.map +1 -1
  204. package/dist/attributes/shape/effects/implementations/magnify.js +0 -1
  205. package/dist/attributes/shape/effects/implementations/magnify.js.map +1 -1
  206. package/dist/attributes/shape/effects/implementations/motion-blur.d.ts +3 -17
  207. package/dist/attributes/shape/effects/implementations/motion-blur.d.ts.map +1 -1
  208. package/dist/attributes/shape/effects/implementations/motion-blur.js +2 -11
  209. package/dist/attributes/shape/effects/implementations/motion-blur.js.map +1 -1
  210. package/dist/attributes/shape/effects/implementations/oil-paint.d.ts +1 -12
  211. package/dist/attributes/shape/effects/implementations/oil-paint.d.ts.map +1 -1
  212. package/dist/attributes/shape/effects/implementations/oil-paint.js +0 -1
  213. package/dist/attributes/shape/effects/implementations/oil-paint.js.map +1 -1
  214. package/dist/attributes/shape/effects/implementations/outline.d.ts +2 -14
  215. package/dist/attributes/shape/effects/implementations/outline.d.ts.map +1 -1
  216. package/dist/attributes/shape/effects/implementations/outline.js +0 -1
  217. package/dist/attributes/shape/effects/implementations/outline.js.map +1 -1
  218. package/dist/attributes/shape/effects/implementations/pixelate.d.ts +1 -15
  219. package/dist/attributes/shape/effects/implementations/pixelate.d.ts.map +1 -1
  220. package/dist/attributes/shape/effects/implementations/pixelate.js +0 -1
  221. package/dist/attributes/shape/effects/implementations/pixelate.js.map +1 -1
  222. package/dist/attributes/shape/effects/implementations/posterize.d.ts +1 -10
  223. package/dist/attributes/shape/effects/implementations/posterize.d.ts.map +1 -1
  224. package/dist/attributes/shape/effects/implementations/posterize.js +0 -1
  225. package/dist/attributes/shape/effects/implementations/posterize.js.map +1 -1
  226. package/dist/attributes/shape/effects/implementations/progressive-blur.d.ts +3 -26
  227. package/dist/attributes/shape/effects/implementations/progressive-blur.d.ts.map +1 -1
  228. package/dist/attributes/shape/effects/implementations/progressive-blur.js +1 -2
  229. package/dist/attributes/shape/effects/implementations/progressive-blur.js.map +1 -1
  230. package/dist/attributes/shape/effects/implementations/radial-blur.d.ts +2 -16
  231. package/dist/attributes/shape/effects/implementations/radial-blur.d.ts.map +1 -1
  232. package/dist/attributes/shape/effects/implementations/radial-blur.js +0 -1
  233. package/dist/attributes/shape/effects/implementations/radial-blur.js.map +1 -1
  234. package/dist/attributes/shape/effects/implementations/rgb-shift.d.ts +1 -13
  235. package/dist/attributes/shape/effects/implementations/rgb-shift.d.ts.map +1 -1
  236. package/dist/attributes/shape/effects/implementations/rgb-shift.js +0 -1
  237. package/dist/attributes/shape/effects/implementations/rgb-shift.js.map +1 -1
  238. package/dist/attributes/shape/effects/implementations/scanlines.d.ts +1 -8
  239. package/dist/attributes/shape/effects/implementations/scanlines.d.ts.map +1 -1
  240. package/dist/attributes/shape/effects/implementations/scanlines.js +0 -1
  241. package/dist/attributes/shape/effects/implementations/scanlines.js.map +1 -1
  242. package/dist/attributes/shape/effects/implementations/scatter.d.ts +0 -1
  243. package/dist/attributes/shape/effects/implementations/scatter.d.ts.map +1 -1
  244. package/dist/attributes/shape/effects/implementations/scatter.js +0 -1
  245. package/dist/attributes/shape/effects/implementations/scatter.js.map +1 -1
  246. package/dist/attributes/shape/effects/implementations/shader.d.ts +10 -53
  247. package/dist/attributes/shape/effects/implementations/shader.d.ts.map +1 -1
  248. package/dist/attributes/shape/effects/implementations/shader.js +2 -9
  249. package/dist/attributes/shape/effects/implementations/shader.js.map +1 -1
  250. package/dist/attributes/shape/effects/implementations/sharpen.d.ts +1 -12
  251. package/dist/attributes/shape/effects/implementations/sharpen.d.ts.map +1 -1
  252. package/dist/attributes/shape/effects/implementations/sharpen.js +0 -1
  253. package/dist/attributes/shape/effects/implementations/sharpen.js.map +1 -1
  254. package/dist/attributes/shape/effects/implementations/streak.d.ts +1 -8
  255. package/dist/attributes/shape/effects/implementations/streak.d.ts.map +1 -1
  256. package/dist/attributes/shape/effects/implementations/streak.js +0 -1
  257. package/dist/attributes/shape/effects/implementations/streak.js.map +1 -1
  258. package/dist/attributes/shape/effects/implementations/threshold.d.ts +1 -9
  259. package/dist/attributes/shape/effects/implementations/threshold.d.ts.map +1 -1
  260. package/dist/attributes/shape/effects/implementations/threshold.js +0 -1
  261. package/dist/attributes/shape/effects/implementations/threshold.js.map +1 -1
  262. package/dist/attributes/shape/effects/implementations/twirl.d.ts +1 -13
  263. package/dist/attributes/shape/effects/implementations/twirl.d.ts.map +1 -1
  264. package/dist/attributes/shape/effects/implementations/twirl.js +0 -1
  265. package/dist/attributes/shape/effects/implementations/twirl.js.map +1 -1
  266. package/dist/attributes/shape/effects/implementations/vignette.d.ts +1 -9
  267. package/dist/attributes/shape/effects/implementations/vignette.d.ts.map +1 -1
  268. package/dist/attributes/shape/effects/implementations/vignette.js +0 -1
  269. package/dist/attributes/shape/effects/implementations/vignette.js.map +1 -1
  270. package/dist/attributes/shape/effects/implementations/vintage.d.ts +0 -1
  271. package/dist/attributes/shape/effects/implementations/vintage.d.ts.map +1 -1
  272. package/dist/attributes/shape/effects/implementations/vintage.js +0 -1
  273. package/dist/attributes/shape/effects/implementations/vintage.js.map +1 -1
  274. package/dist/attributes/shape/effects/implementations/wave.d.ts +3 -24
  275. package/dist/attributes/shape/effects/implementations/wave.d.ts.map +1 -1
  276. package/dist/attributes/shape/effects/implementations/wave.js +1 -5
  277. package/dist/attributes/shape/effects/implementations/wave.js.map +1 -1
  278. package/dist/attributes/shape/effects/registry.d.ts +6 -41
  279. package/dist/attributes/shape/effects/registry.d.ts.map +1 -1
  280. package/dist/attributes/shape/effects/registry.js +7 -45
  281. package/dist/attributes/shape/effects/registry.js.map +1 -1
  282. package/dist/attributes/shape/effects/spec.d.ts +6 -30
  283. package/dist/attributes/shape/effects/spec.d.ts.map +1 -1
  284. package/dist/attributes/shape/effects/spec.js +3 -9
  285. package/dist/attributes/shape/effects/spec.js.map +1 -1
  286. package/dist/attributes/shape/fill/blend.d.ts +1 -17
  287. package/dist/attributes/shape/fill/blend.d.ts.map +1 -1
  288. package/dist/attributes/shape/fill/blend.js +2 -15
  289. package/dist/attributes/shape/fill/blend.js.map +1 -1
  290. package/dist/attributes/shape/fill/chain.d.ts +17 -125
  291. package/dist/attributes/shape/fill/chain.d.ts.map +1 -1
  292. package/dist/attributes/shape/fill/chain.js +22 -109
  293. package/dist/attributes/shape/fill/chain.js.map +1 -1
  294. package/dist/attributes/shape/fill/coerce.d.ts +10 -35
  295. package/dist/attributes/shape/fill/coerce.d.ts.map +1 -1
  296. package/dist/attributes/shape/fill/coerce.js +12 -47
  297. package/dist/attributes/shape/fill/coerce.js.map +1 -1
  298. package/dist/attributes/shape/fill/color/parser.d.ts +10 -44
  299. package/dist/attributes/shape/fill/color/parser.d.ts.map +1 -1
  300. package/dist/attributes/shape/fill/color/parser.js +15 -91
  301. package/dist/attributes/shape/fill/color/parser.js.map +1 -1
  302. package/dist/attributes/shape/fill/gradient-stops.d.ts +1 -8
  303. package/dist/attributes/shape/fill/gradient-stops.d.ts.map +1 -1
  304. package/dist/attributes/shape/fill/gradient-stops.js +2 -13
  305. package/dist/attributes/shape/fill/gradient-stops.js.map +1 -1
  306. package/dist/attributes/shape/fill/implementations/canvas3d.d.ts +2 -24
  307. package/dist/attributes/shape/fill/implementations/canvas3d.d.ts.map +1 -1
  308. package/dist/attributes/shape/fill/implementations/canvas3d.js +2 -9
  309. package/dist/attributes/shape/fill/implementations/canvas3d.js.map +1 -1
  310. package/dist/attributes/shape/fill/implementations/dot-grid.d.ts +1 -14
  311. package/dist/attributes/shape/fill/implementations/dot-grid.d.ts.map +1 -1
  312. package/dist/attributes/shape/fill/implementations/dot-grid.js.map +1 -1
  313. package/dist/attributes/shape/fill/implementations/fractal-noise.d.ts +5 -28
  314. package/dist/attributes/shape/fill/implementations/fractal-noise.d.ts.map +1 -1
  315. package/dist/attributes/shape/fill/implementations/fractal-noise.js +0 -1
  316. package/dist/attributes/shape/fill/implementations/fractal-noise.js.map +1 -1
  317. package/dist/attributes/shape/fill/implementations/grid.d.ts +8 -21
  318. package/dist/attributes/shape/fill/implementations/grid.d.ts.map +1 -1
  319. package/dist/attributes/shape/fill/implementations/grid.js +2 -8
  320. package/dist/attributes/shape/fill/implementations/grid.js.map +1 -1
  321. package/dist/attributes/shape/fill/implementations/image.d.ts +13 -79
  322. package/dist/attributes/shape/fill/implementations/image.d.ts.map +1 -1
  323. package/dist/attributes/shape/fill/implementations/image.js +6 -23
  324. package/dist/attributes/shape/fill/implementations/image.js.map +1 -1
  325. package/dist/attributes/shape/fill/implementations/noise.d.ts +2 -15
  326. package/dist/attributes/shape/fill/implementations/noise.d.ts.map +1 -1
  327. package/dist/attributes/shape/fill/implementations/noise.js.map +1 -1
  328. package/dist/attributes/shape/fill/implementations/shader.d.ts +11 -45
  329. package/dist/attributes/shape/fill/implementations/shader.d.ts.map +1 -1
  330. package/dist/attributes/shape/fill/implementations/shader.js +5 -17
  331. package/dist/attributes/shape/fill/implementations/shader.js.map +1 -1
  332. package/dist/attributes/shape/fill/implementations/video.d.ts +12 -64
  333. package/dist/attributes/shape/fill/implementations/video.d.ts.map +1 -1
  334. package/dist/attributes/shape/fill/implementations/video.js +12 -50
  335. package/dist/attributes/shape/fill/implementations/video.js.map +1 -1
  336. package/dist/attributes/shape/fill/lerp.d.ts +2 -13
  337. package/dist/attributes/shape/fill/lerp.d.ts.map +1 -1
  338. package/dist/attributes/shape/fill/lerp.js +2 -9
  339. package/dist/attributes/shape/fill/lerp.js.map +1 -1
  340. package/dist/attributes/shape/fill/media-preset.d.ts +8 -49
  341. package/dist/attributes/shape/fill/media-preset.d.ts.map +1 -1
  342. package/dist/attributes/shape/fill/media-preset.js +8 -35
  343. package/dist/attributes/shape/fill/media-preset.js.map +1 -1
  344. package/dist/attributes/shape/fill/registry.d.ts +2 -26
  345. package/dist/attributes/shape/fill/registry.d.ts.map +1 -1
  346. package/dist/attributes/shape/fill/registry.js +5 -40
  347. package/dist/attributes/shape/fill/registry.js.map +1 -1
  348. package/dist/attributes/shape/fill/union.d.ts +6 -30
  349. package/dist/attributes/shape/fill/union.d.ts.map +1 -1
  350. package/dist/attributes/shape/fill/union.js +1 -9
  351. package/dist/attributes/shape/fill/union.js.map +1 -1
  352. package/dist/attributes/shape/filters/chain.d.ts +15 -168
  353. package/dist/attributes/shape/filters/chain.d.ts.map +1 -1
  354. package/dist/attributes/shape/filters/chain.js +8 -132
  355. package/dist/attributes/shape/filters/chain.js.map +1 -1
  356. package/dist/attributes/shape/filters/implementations/color-matrix.d.ts +1 -7
  357. package/dist/attributes/shape/filters/implementations/color-matrix.d.ts.map +1 -1
  358. package/dist/attributes/shape/filters/implementations/color-matrix.js.map +1 -1
  359. package/dist/attributes/shape/filters/implementations/curves.d.ts +1 -7
  360. package/dist/attributes/shape/filters/implementations/curves.d.ts.map +1 -1
  361. package/dist/attributes/shape/filters/implementations/curves.js.map +1 -1
  362. package/dist/attributes/shape/filters/implementations/echo.d.ts +1 -11
  363. package/dist/attributes/shape/filters/implementations/echo.d.ts.map +1 -1
  364. package/dist/attributes/shape/filters/implementations/echo.js.map +1 -1
  365. package/dist/attributes/shape/filters/index.d.ts +1 -6
  366. package/dist/attributes/shape/filters/index.d.ts.map +1 -1
  367. package/dist/attributes/shape/filters/index.js +0 -2
  368. package/dist/attributes/shape/filters/index.js.map +1 -1
  369. package/dist/attributes/shape/filters/registry.d.ts +5 -35
  370. package/dist/attributes/shape/filters/registry.d.ts.map +1 -1
  371. package/dist/attributes/shape/filters/registry.js +7 -50
  372. package/dist/attributes/shape/filters/registry.js.map +1 -1
  373. package/dist/attributes/shape/filters/union.d.ts +10 -51
  374. package/dist/attributes/shape/filters/union.d.ts.map +1 -1
  375. package/dist/attributes/shape/filters/union.js.map +1 -1
  376. package/dist/attributes/shape/path/anchors.d.ts +18 -106
  377. package/dist/attributes/shape/path/anchors.d.ts.map +1 -1
  378. package/dist/attributes/shape/path/anchors.js +15 -124
  379. package/dist/attributes/shape/path/anchors.js.map +1 -1
  380. package/dist/attributes/shape/path/bezier.d.ts +6 -54
  381. package/dist/attributes/shape/path/bezier.d.ts.map +1 -1
  382. package/dist/attributes/shape/path/bezier.js +10 -98
  383. package/dist/attributes/shape/path/bezier.js.map +1 -1
  384. package/dist/attributes/shape/path/index.d.ts +1 -11
  385. package/dist/attributes/shape/path/index.d.ts.map +1 -1
  386. package/dist/attributes/shape/path/index.js +1 -11
  387. package/dist/attributes/shape/path/index.js.map +1 -1
  388. package/dist/attributes/shape/path/measure.d.ts +5 -41
  389. package/dist/attributes/shape/path/measure.d.ts.map +1 -1
  390. package/dist/attributes/shape/path/measure.js +8 -57
  391. package/dist/attributes/shape/path/measure.js.map +1 -1
  392. package/dist/attributes/shape/path/morph.d.ts +4 -41
  393. package/dist/attributes/shape/path/morph.d.ts.map +1 -1
  394. package/dist/attributes/shape/path/morph.js +17 -117
  395. package/dist/attributes/shape/path/morph.js.map +1 -1
  396. package/dist/attributes/shape/path/ops.d.ts +5 -19
  397. package/dist/attributes/shape/path/ops.d.ts.map +1 -1
  398. package/dist/attributes/shape/path/ops.js.map +1 -1
  399. package/dist/attributes/shape/path/types.d.ts +10 -67
  400. package/dist/attributes/shape/path/types.d.ts.map +1 -1
  401. package/dist/attributes/shape/path/types.js +0 -1
  402. package/dist/attributes/shape/path/types.js.map +1 -1
  403. package/dist/attributes/shape/path/walk.d.ts +9 -63
  404. package/dist/attributes/shape/path/walk.d.ts.map +1 -1
  405. package/dist/attributes/shape/path/walk.js +21 -100
  406. package/dist/attributes/shape/path/walk.js.map +1 -1
  407. package/dist/attributes/shape/shaders/language.d.ts +2 -14
  408. package/dist/attributes/shape/shaders/language.d.ts.map +1 -1
  409. package/dist/attributes/shape/shaders/language.js +1 -8
  410. package/dist/attributes/shape/shaders/language.js.map +1 -1
  411. package/dist/attributes/shape/shaders/pack.d.ts +13 -78
  412. package/dist/attributes/shape/shaders/pack.d.ts.map +1 -1
  413. package/dist/attributes/shape/shaders/pack.js +1 -10
  414. package/dist/attributes/shape/shaders/pack.js.map +1 -1
  415. package/dist/attributes/shape/shaders/resolve.d.ts +1 -11
  416. package/dist/attributes/shape/shaders/resolve.d.ts.map +1 -1
  417. package/dist/attributes/shape/shaders/resolve.js +3 -28
  418. package/dist/attributes/shape/shaders/resolve.js.map +1 -1
  419. package/dist/attributes/shape/shaders/uniforms.d.ts +3 -24
  420. package/dist/attributes/shape/shaders/uniforms.d.ts.map +1 -1
  421. package/dist/attributes/shape/shaders/uniforms.js +0 -0
  422. package/dist/attributes/shape/shaders/uniforms.js.map +1 -1
  423. package/dist/attributes/shape/shadow/shadow.d.ts +3 -20
  424. package/dist/attributes/shape/shadow/shadow.d.ts.map +1 -1
  425. package/dist/attributes/shape/shadow/shadow.js +0 -3
  426. package/dist/attributes/shape/shadow/shadow.js.map +1 -1
  427. package/dist/attributes/shape/stroke/stroke.d.ts +9 -58
  428. package/dist/attributes/shape/stroke/stroke.d.ts.map +1 -1
  429. package/dist/attributes/shape/stroke/stroke.js +0 -6
  430. package/dist/attributes/shape/stroke/stroke.js.map +1 -1
  431. package/dist/attributes/shared/operators.d.ts +1 -8
  432. package/dist/attributes/shared/operators.d.ts.map +1 -1
  433. package/dist/attributes/shared/operators.js.map +1 -1
  434. package/dist/attributes/text/index.d.ts +1 -11
  435. package/dist/attributes/text/index.d.ts.map +1 -1
  436. package/dist/attributes/text/index.js +1 -11
  437. package/dist/attributes/text/index.js.map +1 -1
  438. package/dist/attributes/text/ops.d.ts +4 -30
  439. package/dist/attributes/text/ops.d.ts.map +1 -1
  440. package/dist/attributes/text/ops.js +7 -23
  441. package/dist/attributes/text/ops.js.map +1 -1
  442. package/dist/attributes/text/types.d.ts +5 -28
  443. package/dist/attributes/text/types.d.ts.map +1 -1
  444. package/dist/attributes/text/types.js.map +1 -1
  445. package/dist/browser/chunks/chunk-5GLXFSCC.js +13 -0
  446. package/dist/browser/chunks/chunk-5GLXFSCC.js.map +7 -0
  447. package/dist/browser/chunks/{chunk-CCGVIR4F.js → chunk-5TDMGUXQ.js} +3 -3
  448. package/dist/browser/chunks/chunk-5TDMGUXQ.js.map +7 -0
  449. package/dist/browser/chunks/{chunk-4BDLFEOC.js → chunk-GEJEQQER.js} +1 -1
  450. package/dist/browser/chunks/chunk-GEJEQQER.js.map +7 -0
  451. package/dist/browser/chunks/chunk-MNMIIGNE.js +6 -0
  452. package/dist/browser/chunks/chunk-MNMIIGNE.js.map +7 -0
  453. package/dist/browser/component.js +1 -1
  454. package/dist/browser/experimental.js +1 -1
  455. package/dist/browser/index.js +1 -1
  456. package/dist/browser/index.js.map +4 -4
  457. package/dist/browser/manifest.json +1 -1
  458. package/dist/browser/sdk.js +1 -1
  459. package/dist/component.d.ts +3 -10
  460. package/dist/component.d.ts.map +1 -1
  461. package/dist/component.js +3 -10
  462. package/dist/component.js.map +1 -1
  463. package/dist/components/builtins/geometry/geometry.d.ts +15 -62
  464. package/dist/components/builtins/geometry/geometry.d.ts.map +1 -1
  465. package/dist/components/builtins/geometry/geometry.js.map +1 -1
  466. package/dist/components/builtins/geometry/shape-outline.d.ts +12 -61
  467. package/dist/components/builtins/geometry/shape-outline.d.ts.map +1 -1
  468. package/dist/components/builtins/geometry/shape-outline.js +29 -168
  469. package/dist/components/builtins/geometry/shape-outline.js.map +1 -1
  470. package/dist/components/builtins/layout/layout.d.ts +1 -14
  471. package/dist/components/builtins/layout/layout.d.ts.map +1 -1
  472. package/dist/components/builtins/layout/layout.js.map +1 -1
  473. package/dist/components/builtins/media/media.d.ts +11 -51
  474. package/dist/components/builtins/media/media.d.ts.map +1 -1
  475. package/dist/components/builtins/media/media.js +3 -7
  476. package/dist/components/builtins/media/media.js.map +1 -1
  477. package/dist/components/builtins/text/number-format.d.ts +14 -47
  478. package/dist/components/builtins/text/number-format.d.ts.map +1 -1
  479. package/dist/components/builtins/text/number-format.js +19 -69
  480. package/dist/components/builtins/text/number-format.js.map +1 -1
  481. package/dist/components/builtins/text/number-pattern.d.ts +3 -37
  482. package/dist/components/builtins/text/number-pattern.d.ts.map +1 -1
  483. package/dist/components/builtins/text/number-pattern.js +6 -48
  484. package/dist/components/builtins/text/number-pattern.js.map +1 -1
  485. package/dist/components/builtins/text/text-defaults.d.ts +7 -25
  486. package/dist/components/builtins/text/text-defaults.d.ts.map +1 -1
  487. package/dist/components/builtins/text/text-defaults.js +7 -25
  488. package/dist/components/builtins/text/text-defaults.js.map +1 -1
  489. package/dist/components/builtins/text/text-layout.d.ts +2 -11
  490. package/dist/components/builtins/text/text-layout.d.ts.map +1 -1
  491. package/dist/components/builtins/text/text-layout.js +7 -22
  492. package/dist/components/builtins/text/text-layout.js.map +1 -1
  493. package/dist/components/builtins/text/text.d.ts +8 -46
  494. package/dist/components/builtins/text/text.d.ts.map +1 -1
  495. package/dist/components/builtins/text/text.js.map +1 -1
  496. package/dist/components/builtins/three/canvas3d.d.ts +6 -51
  497. package/dist/components/builtins/three/canvas3d.d.ts.map +1 -1
  498. package/dist/components/builtins/three/canvas3d.js.map +1 -1
  499. package/dist/components/builtins/three/grid-geometry3d.d.ts +3 -39
  500. package/dist/components/builtins/three/grid-geometry3d.d.ts.map +1 -1
  501. package/dist/components/builtins/three/grid-geometry3d.js +8 -46
  502. package/dist/components/builtins/three/grid-geometry3d.js.map +1 -1
  503. package/dist/components/builtins/three/three.d.ts +22 -117
  504. package/dist/components/builtins/three/three.d.ts.map +1 -1
  505. package/dist/components/builtins/three/three.js +5 -17
  506. package/dist/components/builtins/three/three.js.map +1 -1
  507. package/dist/components/factory/api.d.ts.map +1 -1
  508. package/dist/components/factory/api.js.map +1 -1
  509. package/dist/components/factory/style.d.ts +38 -0
  510. package/dist/components/factory/style.d.ts.map +1 -0
  511. package/dist/components/factory/style.js +104 -0
  512. package/dist/components/factory/style.js.map +1 -0
  513. package/dist/components/factory/types.d.ts +9 -0
  514. package/dist/components/factory/types.d.ts.map +1 -1
  515. package/dist/components/factory/types.js +11 -0
  516. package/dist/components/factory/types.js.map +1 -1
  517. package/dist/components/factory/views.d.ts.map +1 -1
  518. package/dist/components/factory/views.js +0 -2
  519. package/dist/components/factory/views.js.map +1 -1
  520. package/dist/components/trees/2d/group-bounds.d.ts +12 -41
  521. package/dist/components/trees/2d/group-bounds.d.ts.map +1 -1
  522. package/dist/components/trees/2d/group-bounds.js +3 -22
  523. package/dist/components/trees/2d/group-bounds.js.map +1 -1
  524. package/dist/components/trees/2d/node-lifecycle.d.ts +8 -36
  525. package/dist/components/trees/2d/node-lifecycle.d.ts.map +1 -1
  526. package/dist/components/trees/2d/node-lifecycle.js +35 -127
  527. package/dist/components/trees/2d/node-lifecycle.js.map +1 -1
  528. package/dist/components/trees/2d/node-motion.d.ts +4 -36
  529. package/dist/components/trees/2d/node-motion.d.ts.map +1 -1
  530. package/dist/components/trees/2d/node-motion.js +3 -31
  531. package/dist/components/trees/2d/node-motion.js.map +1 -1
  532. package/dist/components/trees/2d/node-render.d.ts +3 -20
  533. package/dist/components/trees/2d/node-render.d.ts.map +1 -1
  534. package/dist/components/trees/2d/node-render.js +4 -23
  535. package/dist/components/trees/2d/node-render.js.map +1 -1
  536. package/dist/components/trees/2d/node-space.d.ts +4 -23
  537. package/dist/components/trees/2d/node-space.d.ts.map +1 -1
  538. package/dist/components/trees/2d/node-space.js +3 -17
  539. package/dist/components/trees/2d/node-space.js.map +1 -1
  540. package/dist/components/trees/2d/node-transform.d.ts +4 -33
  541. package/dist/components/trees/2d/node-transform.d.ts.map +1 -1
  542. package/dist/components/trees/2d/node-transform.js +4 -33
  543. package/dist/components/trees/2d/node-transform.js.map +1 -1
  544. package/dist/components/trees/2d/node2d.d.ts +112 -622
  545. package/dist/components/trees/2d/node2d.d.ts.map +1 -1
  546. package/dist/components/trees/2d/node2d.js +131 -605
  547. package/dist/components/trees/2d/node2d.js.map +1 -1
  548. package/dist/components/trees/audio/node-audio.d.ts +17 -65
  549. package/dist/components/trees/audio/node-audio.d.ts.map +1 -1
  550. package/dist/components/trees/audio/node-audio.js +18 -68
  551. package/dist/components/trees/audio/node-audio.js.map +1 -1
  552. package/dist/components/trees/node/node-editor-state.d.ts +5 -45
  553. package/dist/components/trees/node/node-editor-state.d.ts.map +1 -1
  554. package/dist/components/trees/node/node-editor-state.js +1 -13
  555. package/dist/components/trees/node/node-editor-state.js.map +1 -1
  556. package/dist/components/trees/node/node-reactive.d.ts +6 -53
  557. package/dist/components/trees/node/node-reactive.d.ts.map +1 -1
  558. package/dist/components/trees/node/node-reactive.js +4 -33
  559. package/dist/components/trees/node/node-reactive.js.map +1 -1
  560. package/dist/components/trees/node/node-time.d.ts +2 -15
  561. package/dist/components/trees/node/node-time.d.ts.map +1 -1
  562. package/dist/components/trees/node/node-time.js.map +1 -1
  563. package/dist/components/trees/node/node-walk.d.ts +7 -32
  564. package/dist/components/trees/node/node-walk.d.ts.map +1 -1
  565. package/dist/components/trees/node/node-walk.js +7 -32
  566. package/dist/components/trees/node/node-walk.js.map +1 -1
  567. package/dist/components/trees/node/node.d.ts +43 -248
  568. package/dist/components/trees/node/node.d.ts.map +1 -1
  569. package/dist/components/trees/node/node.js +51 -229
  570. package/dist/components/trees/node/node.js.map +1 -1
  571. package/dist/components/trees/root/canvas2d-node.d.ts +7 -60
  572. package/dist/components/trees/root/canvas2d-node.d.ts.map +1 -1
  573. package/dist/components/trees/root/canvas2d-node.js +7 -47
  574. package/dist/components/trees/root/canvas2d-node.js.map +1 -1
  575. package/dist/components/trees/three/node3d.d.ts +24 -112
  576. package/dist/components/trees/three/node3d.d.ts.map +1 -1
  577. package/dist/components/trees/three/node3d.js +22 -104
  578. package/dist/components/trees/three/node3d.js.map +1 -1
  579. package/dist/document/audio.d.ts +9 -21
  580. package/dist/document/audio.d.ts.map +1 -1
  581. package/dist/document/audio.js +13 -28
  582. package/dist/document/audio.js.map +1 -1
  583. package/dist/document/builtins.d.ts +3 -9
  584. package/dist/document/builtins.d.ts.map +1 -1
  585. package/dist/document/builtins.js +43 -89
  586. package/dist/document/builtins.js.map +1 -1
  587. package/dist/document/command-traits.d.ts +14 -37
  588. package/dist/document/command-traits.d.ts.map +1 -1
  589. package/dist/document/command-traits.js +22 -39
  590. package/dist/document/command-traits.js.map +1 -1
  591. package/dist/document/deny-globals.d.ts +9 -43
  592. package/dist/document/deny-globals.d.ts.map +1 -1
  593. package/dist/document/deny-globals.js +18 -58
  594. package/dist/document/deny-globals.js.map +1 -1
  595. package/dist/document/diff.d.ts +6 -16
  596. package/dist/document/diff.d.ts.map +1 -1
  597. package/dist/document/diff.js +5 -11
  598. package/dist/document/diff.js.map +1 -1
  599. package/dist/document/doc-index.d.ts +5 -13
  600. package/dist/document/doc-index.d.ts.map +1 -1
  601. package/dist/document/doc-index.js +0 -2
  602. package/dist/document/doc-index.js.map +1 -1
  603. package/dist/document/expression/compile.d.ts +2 -2
  604. package/dist/document/expression/compile.d.ts.map +1 -1
  605. package/dist/document/expression/compile.js +8 -18
  606. package/dist/document/expression/compile.js.map +1 -1
  607. package/dist/document/expression/index.d.ts +11 -41
  608. package/dist/document/expression/index.d.ts.map +1 -1
  609. package/dist/document/expression/index.js +11 -41
  610. package/dist/document/expression/index.js.map +1 -1
  611. package/dist/document/expression/ops.d.ts +3 -12
  612. package/dist/document/expression/ops.d.ts.map +1 -1
  613. package/dist/document/expression/ops.js +4 -20
  614. package/dist/document/expression/ops.js.map +1 -1
  615. package/dist/document/expression/parse.d.ts +4 -14
  616. package/dist/document/expression/parse.d.ts.map +1 -1
  617. package/dist/document/expression/parse.js +34 -55
  618. package/dist/document/expression/parse.js.map +1 -1
  619. package/dist/document/expression/refs.d.ts +2 -8
  620. package/dist/document/expression/refs.d.ts.map +1 -1
  621. package/dist/document/expression/refs.js +2 -6
  622. package/dist/document/expression/refs.js.map +1 -1
  623. package/dist/document/expression/types.d.ts +18 -63
  624. package/dist/document/expression/types.d.ts.map +1 -1
  625. package/dist/document/expression/types.js +4 -15
  626. package/dist/document/expression/types.js.map +1 -1
  627. package/dist/document/expression/walk.d.ts +6 -20
  628. package/dist/document/expression/walk.d.ts.map +1 -1
  629. package/dist/document/expression/walk.js +18 -44
  630. package/dist/document/expression/walk.js.map +1 -1
  631. package/dist/document/index.js +2 -3
  632. package/dist/document/index.js.map +1 -1
  633. package/dist/document/migrate.d.ts +7 -22
  634. package/dist/document/migrate.d.ts.map +1 -1
  635. package/dist/document/migrate.js +44 -15
  636. package/dist/document/migrate.js.map +1 -1
  637. package/dist/document/missing-node.d.ts +4 -11
  638. package/dist/document/missing-node.d.ts.map +1 -1
  639. package/dist/document/missing-node.js +2 -5
  640. package/dist/document/missing-node.js.map +1 -1
  641. package/dist/document/node-decorator.d.ts +12 -53
  642. package/dist/document/node-decorator.d.ts.map +1 -1
  643. package/dist/document/node-decorator.js +16 -57
  644. package/dist/document/node-decorator.js.map +1 -1
  645. package/dist/document/node-descriptor.d.ts +25 -62
  646. package/dist/document/node-descriptor.d.ts.map +1 -1
  647. package/dist/document/node-descriptor.js.map +1 -1
  648. package/dist/document/placement.d.ts +18 -41
  649. package/dist/document/placement.d.ts.map +1 -1
  650. package/dist/document/placement.js +4 -11
  651. package/dist/document/placement.js.map +1 -1
  652. package/dist/document/project.d.ts +19 -52
  653. package/dist/document/project.d.ts.map +1 -1
  654. package/dist/document/project.js +2 -6
  655. package/dist/document/project.js.map +1 -1
  656. package/dist/document/prop-evolution.d.ts +10 -20
  657. package/dist/document/prop-evolution.d.ts.map +1 -1
  658. package/dist/document/prop-evolution.js +3 -7
  659. package/dist/document/prop-evolution.js.map +1 -1
  660. package/dist/document/registry.d.ts +80 -318
  661. package/dist/document/registry.d.ts.map +1 -1
  662. package/dist/document/registry.js +43 -147
  663. package/dist/document/registry.js.map +1 -1
  664. package/dist/document/settled-index.d.ts +11 -23
  665. package/dist/document/settled-index.d.ts.map +1 -1
  666. package/dist/document/settled-index.js +15 -34
  667. package/dist/document/settled-index.js.map +1 -1
  668. package/dist/document/timeline-patch.d.ts +6 -15
  669. package/dist/document/timeline-patch.d.ts.map +1 -1
  670. package/dist/document/timeline-patch.js +12 -21
  671. package/dist/document/timeline-patch.js.map +1 -1
  672. package/dist/document/timeline.d.ts +56 -263
  673. package/dist/document/timeline.d.ts.map +1 -1
  674. package/dist/document/timeline.js +71 -275
  675. package/dist/document/timeline.js.map +1 -1
  676. package/dist/document/types.d.ts +90 -264
  677. package/dist/document/types.d.ts.map +1 -1
  678. package/dist/document/types.js +13 -30
  679. package/dist/document/types.js.map +1 -1
  680. package/dist/document/validate.d.ts +10 -40
  681. package/dist/document/validate.d.ts.map +1 -1
  682. package/dist/document/validate.js +72 -137
  683. package/dist/document/validate.js.map +1 -1
  684. package/dist/document/vocabulary.d.ts +4 -7
  685. package/dist/document/vocabulary.d.ts.map +1 -1
  686. package/dist/document/vocabulary.js +0 -1
  687. package/dist/document/vocabulary.js.map +1 -1
  688. package/dist/experimental.d.ts +2 -0
  689. package/dist/experimental.d.ts.map +1 -1
  690. package/dist/index.d.ts +0 -1
  691. package/dist/index.d.ts.map +1 -1
  692. package/dist/index.js +0 -1
  693. package/dist/index.js.map +1 -1
  694. package/dist/layout/bounds.d.ts +1 -11
  695. package/dist/layout/bounds.d.ts.map +1 -1
  696. package/dist/layout/bounds.js.map +1 -1
  697. package/dist/layout/flex.d.ts +6 -20
  698. package/dist/layout/flex.d.ts.map +1 -1
  699. package/dist/layout/flex.js +7 -28
  700. package/dist/layout/flex.js.map +1 -1
  701. package/dist/layout/ops.d.ts +2 -11
  702. package/dist/layout/ops.d.ts.map +1 -1
  703. package/dist/layout/ops.js +2 -22
  704. package/dist/layout/ops.js.map +1 -1
  705. package/dist/layout/types.d.ts +11 -55
  706. package/dist/layout/types.d.ts.map +1 -1
  707. package/dist/layout/types.js.map +1 -1
  708. package/dist/platform/audio-sink.d.ts +7 -43
  709. package/dist/platform/audio-sink.d.ts.map +1 -1
  710. package/dist/platform/audio-sink.js +4 -29
  711. package/dist/platform/audio-sink.js.map +1 -1
  712. package/dist/platform/exporter.d.ts +5 -31
  713. package/dist/platform/exporter.d.ts.map +1 -1
  714. package/dist/platform/exporter.js.map +1 -1
  715. package/dist/platform/stepped-clock.d.ts +1 -16
  716. package/dist/platform/stepped-clock.d.ts.map +1 -1
  717. package/dist/platform/stepped-clock.js +1 -16
  718. package/dist/platform/stepped-clock.js.map +1 -1
  719. package/dist/platform/storage-adapter.d.ts +8 -68
  720. package/dist/platform/storage-adapter.d.ts.map +1 -1
  721. package/dist/platform/storage-adapter.js +8 -60
  722. package/dist/platform/storage-adapter.js.map +1 -1
  723. package/dist/platform/ticker.d.ts +11 -45
  724. package/dist/platform/ticker.d.ts.map +1 -1
  725. package/dist/platform/ticker.js +10 -37
  726. package/dist/platform/ticker.js.map +1 -1
  727. package/dist/project/config.d.ts +4 -14
  728. package/dist/project/config.d.ts.map +1 -1
  729. package/dist/project/config.js.map +1 -1
  730. package/dist/project/tree.d.ts +6 -35
  731. package/dist/project/tree.d.ts.map +1 -1
  732. package/dist/project/tree.js +1 -8
  733. package/dist/project/tree.js.map +1 -1
  734. package/dist/props/host.d.ts +2 -13
  735. package/dist/props/host.d.ts.map +1 -1
  736. package/dist/props/host.js.map +1 -1
  737. package/dist/props/layout.d.ts +1 -12
  738. package/dist/props/layout.d.ts.map +1 -1
  739. package/dist/props/layout.js +1 -12
  740. package/dist/props/layout.js.map +1 -1
  741. package/dist/props/observer.d.ts +1 -7
  742. package/dist/props/observer.d.ts.map +1 -1
  743. package/dist/props/observer.js.map +1 -1
  744. package/dist/props/slot.d.ts +6 -19
  745. package/dist/props/slot.d.ts.map +1 -1
  746. package/dist/props/slot.js +5 -14
  747. package/dist/props/slot.js.map +1 -1
  748. package/dist/render/canvas-render-context2d.d.ts +8 -68
  749. package/dist/render/canvas-render-context2d.d.ts.map +1 -1
  750. package/dist/render/canvas-render-context2d.js +8 -69
  751. package/dist/render/canvas-render-context2d.js.map +1 -1
  752. package/dist/render/clip-contains.d.ts +2 -16
  753. package/dist/render/clip-contains.d.ts.map +1 -1
  754. package/dist/render/clip-contains.js +21 -82
  755. package/dist/render/clip-contains.js.map +1 -1
  756. package/dist/render/clip.d.ts +7 -25
  757. package/dist/render/clip.d.ts.map +1 -1
  758. package/dist/render/clip.js +5 -17
  759. package/dist/render/clip.js.map +1 -1
  760. package/dist/render/descriptors/ellipse.d.ts.map +1 -1
  761. package/dist/render/descriptors/ellipse.js +0 -1
  762. package/dist/render/descriptors/ellipse.js.map +1 -1
  763. package/dist/render/descriptors/line.d.ts.map +1 -1
  764. package/dist/render/descriptors/line.js +0 -1
  765. package/dist/render/descriptors/line.js.map +1 -1
  766. package/dist/render/descriptors/path-builder.d.ts +4 -32
  767. package/dist/render/descriptors/path-builder.d.ts.map +1 -1
  768. package/dist/render/descriptors/path-builder.js +3 -25
  769. package/dist/render/descriptors/path-builder.js.map +1 -1
  770. package/dist/render/descriptors/path.d.ts +1 -11
  771. package/dist/render/descriptors/path.d.ts.map +1 -1
  772. package/dist/render/descriptors/path.js +0 -1
  773. package/dist/render/descriptors/path.js.map +1 -1
  774. package/dist/render/descriptors/polygon.d.ts.map +1 -1
  775. package/dist/render/descriptors/polygon.js +0 -1
  776. package/dist/render/descriptors/polygon.js.map +1 -1
  777. package/dist/render/descriptors/polygram.d.ts.map +1 -1
  778. package/dist/render/descriptors/polygram.js +0 -1
  779. package/dist/render/descriptors/polygram.js.map +1 -1
  780. package/dist/render/descriptors/rect.d.ts.map +1 -1
  781. package/dist/render/descriptors/rect.js +0 -1
  782. package/dist/render/descriptors/rect.js.map +1 -1
  783. package/dist/render/descriptors/richtext.d.ts.map +1 -1
  784. package/dist/render/descriptors/richtext.js +0 -1
  785. package/dist/render/descriptors/richtext.js.map +1 -1
  786. package/dist/render/descriptors/shape.d.ts +17 -77
  787. package/dist/render/descriptors/shape.d.ts.map +1 -1
  788. package/dist/render/descriptors/shape.js +13 -47
  789. package/dist/render/descriptors/shape.js.map +1 -1
  790. package/dist/render/descriptors/text.d.ts +15 -94
  791. package/dist/render/descriptors/text.d.ts.map +1 -1
  792. package/dist/render/descriptors/text.js +8 -50
  793. package/dist/render/descriptors/text.js.map +1 -1
  794. package/dist/render/descriptors/transform.d.ts +5 -16
  795. package/dist/render/descriptors/transform.d.ts.map +1 -1
  796. package/dist/render/descriptors/transform.js +1 -17
  797. package/dist/render/descriptors/transform.js.map +1 -1
  798. package/dist/render/graphics2d.d.ts +24 -116
  799. package/dist/render/graphics2d.d.ts.map +1 -1
  800. package/dist/render/graphics2d.js +23 -108
  801. package/dist/render/graphics2d.js.map +1 -1
  802. package/dist/render/measure-context.d.ts +5 -29
  803. package/dist/render/measure-context.d.ts.map +1 -1
  804. package/dist/render/measure-context.js.map +1 -1
  805. package/dist/render/null-render-context.d.ts +2 -20
  806. package/dist/render/null-render-context.d.ts.map +1 -1
  807. package/dist/render/null-render-context.js +2 -20
  808. package/dist/render/null-render-context.js.map +1 -1
  809. package/dist/render/render-context2d.d.ts +52 -208
  810. package/dist/render/render-context2d.d.ts.map +1 -1
  811. package/dist/render/render-context2d.js.map +1 -1
  812. package/dist/render/surface.d.ts +2 -19
  813. package/dist/render/surface.d.ts.map +1 -1
  814. package/dist/render/surface.js.map +1 -1
  815. package/dist/render/text-defaults.d.ts +1 -17
  816. package/dist/render/text-defaults.d.ts.map +1 -1
  817. package/dist/render/text-defaults.js +6 -40
  818. package/dist/render/text-defaults.js.map +1 -1
  819. package/dist/render/text-layout.d.ts +12 -55
  820. package/dist/render/text-layout.d.ts.map +1 -1
  821. package/dist/render/text-layout.js +2 -16
  822. package/dist/render/text-layout.js.map +1 -1
  823. package/dist/render3d/bounds3d.d.ts +10 -32
  824. package/dist/render3d/bounds3d.d.ts.map +1 -1
  825. package/dist/render3d/bounds3d.js +2 -12
  826. package/dist/render3d/bounds3d.js.map +1 -1
  827. package/dist/render3d/builders.d.ts +8 -35
  828. package/dist/render3d/builders.d.ts.map +1 -1
  829. package/dist/render3d/builders.js +8 -35
  830. package/dist/render3d/builders.js.map +1 -1
  831. package/dist/render3d/camera.d.ts +10 -57
  832. package/dist/render3d/camera.d.ts.map +1 -1
  833. package/dist/render3d/camera.js +4 -26
  834. package/dist/render3d/camera.js.map +1 -1
  835. package/dist/render3d/fill3d.d.ts +7 -45
  836. package/dist/render3d/fill3d.d.ts.map +1 -1
  837. package/dist/render3d/fill3d.js +15 -85
  838. package/dist/render3d/fill3d.js.map +1 -1
  839. package/dist/render3d/geometry.d.ts +18 -106
  840. package/dist/render3d/geometry.d.ts.map +1 -1
  841. package/dist/render3d/geometry.js +2 -20
  842. package/dist/render3d/geometry.js.map +1 -1
  843. package/dist/render3d/graphics3d.d.ts +29 -133
  844. package/dist/render3d/graphics3d.d.ts.map +1 -1
  845. package/dist/render3d/graphics3d.js +23 -110
  846. package/dist/render3d/graphics3d.js.map +1 -1
  847. package/dist/render3d/index.d.ts +1 -16
  848. package/dist/render3d/index.d.ts.map +1 -1
  849. package/dist/render3d/index.js +1 -16
  850. package/dist/render3d/index.js.map +1 -1
  851. package/dist/render3d/inert.d.ts.map +1 -1
  852. package/dist/render3d/inert.js +1 -14
  853. package/dist/render3d/inert.js.map +1 -1
  854. package/dist/render3d/light.d.ts +3 -26
  855. package/dist/render3d/light.d.ts.map +1 -1
  856. package/dist/render3d/light.js.map +1 -1
  857. package/dist/render3d/material.d.ts +13 -87
  858. package/dist/render3d/material.d.ts.map +1 -1
  859. package/dist/render3d/material.js +2 -16
  860. package/dist/render3d/material.js.map +1 -1
  861. package/dist/render3d/matrix4.d.ts +14 -68
  862. package/dist/render3d/matrix4.d.ts.map +1 -1
  863. package/dist/render3d/matrix4.js +11 -60
  864. package/dist/render3d/matrix4.js.map +1 -1
  865. package/dist/render3d/render-context3d.d.ts +13 -51
  866. package/dist/render3d/render-context3d.d.ts.map +1 -1
  867. package/dist/render3d/render-context3d.js +9 -21
  868. package/dist/render3d/render-context3d.js.map +1 -1
  869. package/dist/render3d/resources.d.ts +9 -53
  870. package/dist/render3d/resources.d.ts.map +1 -1
  871. package/dist/render3d/resources.js +8 -48
  872. package/dist/render3d/resources.js.map +1 -1
  873. package/dist/render3d/rounded-box.d.ts +7 -21
  874. package/dist/render3d/rounded-box.d.ts.map +1 -1
  875. package/dist/render3d/rounded-box.js +7 -46
  876. package/dist/render3d/rounded-box.js.map +1 -1
  877. package/dist/render3d/scene-settings.d.ts +20 -78
  878. package/dist/render3d/scene-settings.d.ts.map +1 -1
  879. package/dist/render3d/scene-settings.js.map +1 -1
  880. package/dist/render3d/scene3d.d.ts +11 -53
  881. package/dist/render3d/scene3d.d.ts.map +1 -1
  882. package/dist/render3d/scene3d.js +12 -59
  883. package/dist/render3d/scene3d.js.map +1 -1
  884. package/dist/render3d/segments.d.ts +2 -25
  885. package/dist/render3d/segments.d.ts.map +1 -1
  886. package/dist/render3d/segments.js +1 -11
  887. package/dist/render3d/segments.js.map +1 -1
  888. package/dist/render3d/texture.d.ts +25 -112
  889. package/dist/render3d/texture.d.ts.map +1 -1
  890. package/dist/render3d/texture.js +3 -27
  891. package/dist/render3d/texture.js.map +1 -1
  892. package/dist/render3d/tracking.d.ts +2 -19
  893. package/dist/render3d/tracking.d.ts.map +1 -1
  894. package/dist/render3d/tracking.js +2 -19
  895. package/dist/render3d/tracking.js.map +1 -1
  896. package/dist/render3d/transform.d.ts +14 -60
  897. package/dist/render3d/transform.d.ts.map +1 -1
  898. package/dist/render3d/transform.js +0 -2
  899. package/dist/render3d/transform.js.map +1 -1
  900. package/dist/render3d/vector3.d.ts +6 -48
  901. package/dist/render3d/vector3.d.ts.map +1 -1
  902. package/dist/render3d/vector3.js +4 -38
  903. package/dist/render3d/vector3.js.map +1 -1
  904. package/dist/render3d/walk.d.ts +3 -27
  905. package/dist/render3d/walk.d.ts.map +1 -1
  906. package/dist/render3d/walk.js +5 -33
  907. package/dist/render3d/walk.js.map +1 -1
  908. package/dist/runtime/asset-refine.d.ts +34 -20
  909. package/dist/runtime/asset-refine.d.ts.map +1 -1
  910. package/dist/runtime/asset-refine.js +127 -31
  911. package/dist/runtime/asset-refine.js.map +1 -1
  912. package/dist/runtime/asset-timeline.d.ts +14 -53
  913. package/dist/runtime/asset-timeline.d.ts.map +1 -1
  914. package/dist/runtime/asset-timeline.js +6 -27
  915. package/dist/runtime/asset-timeline.js.map +1 -1
  916. package/dist/runtime/asset-update.d.ts +7 -26
  917. package/dist/runtime/asset-update.d.ts.map +1 -1
  918. package/dist/runtime/asset-update.js +6 -18
  919. package/dist/runtime/asset-update.js.map +1 -1
  920. package/dist/runtime/audio-index.d.ts +0 -2
  921. package/dist/runtime/audio-index.d.ts.map +1 -1
  922. package/dist/runtime/audio-index.js +0 -2
  923. package/dist/runtime/audio-index.js.map +1 -1
  924. package/dist/runtime/builtin-context.d.ts +3 -9
  925. package/dist/runtime/builtin-context.d.ts.map +1 -1
  926. package/dist/runtime/builtin-context.js +3 -9
  927. package/dist/runtime/builtin-context.js.map +1 -1
  928. package/dist/runtime/clip-instance.d.ts +12 -39
  929. package/dist/runtime/clip-instance.d.ts.map +1 -1
  930. package/dist/runtime/clip-instance.js +21 -45
  931. package/dist/runtime/clip-instance.js.map +1 -1
  932. package/dist/runtime/clip-store.d.ts +26 -68
  933. package/dist/runtime/clip-store.d.ts.map +1 -1
  934. package/dist/runtime/clip-store.js +47 -81
  935. package/dist/runtime/clip-store.js.map +1 -1
  936. package/dist/runtime/engine.d.ts +31 -85
  937. package/dist/runtime/engine.d.ts.map +1 -1
  938. package/dist/runtime/engine.js +16 -49
  939. package/dist/runtime/engine.js.map +1 -1
  940. package/dist/runtime/frame-time.d.ts +4 -15
  941. package/dist/runtime/frame-time.d.ts.map +1 -1
  942. package/dist/runtime/frame-time.js +5 -12
  943. package/dist/runtime/frame-time.js.map +1 -1
  944. package/dist/runtime/index.d.ts +0 -1
  945. package/dist/runtime/index.d.ts.map +1 -1
  946. package/dist/runtime/index.js +0 -1
  947. package/dist/runtime/index.js.map +1 -1
  948. package/dist/runtime/node-picking.d.ts +59 -139
  949. package/dist/runtime/node-picking.d.ts.map +1 -1
  950. package/dist/runtime/node-picking.js +87 -157
  951. package/dist/runtime/node-picking.js.map +1 -1
  952. package/dist/runtime/node-picking3d.d.ts +39 -96
  953. package/dist/runtime/node-picking3d.d.ts.map +1 -1
  954. package/dist/runtime/node-picking3d.js +98 -141
  955. package/dist/runtime/node-picking3d.js.map +1 -1
  956. package/dist/runtime/placement.d.ts +8 -17
  957. package/dist/runtime/placement.d.ts.map +1 -1
  958. package/dist/runtime/placement.js +7 -16
  959. package/dist/runtime/placement.js.map +1 -1
  960. package/dist/runtime/playback-controller.d.ts +78 -207
  961. package/dist/runtime/playback-controller.d.ts.map +1 -1
  962. package/dist/runtime/playback-controller.js +111 -226
  963. package/dist/runtime/playback-controller.js.map +1 -1
  964. package/dist/runtime/playback.d.ts +6 -14
  965. package/dist/runtime/playback.d.ts.map +1 -1
  966. package/dist/runtime/playback.js +6 -14
  967. package/dist/runtime/playback.js.map +1 -1
  968. package/dist/runtime/project-assets.d.ts +6 -14
  969. package/dist/runtime/project-assets.d.ts.map +1 -1
  970. package/dist/runtime/project-assets.js +7 -16
  971. package/dist/runtime/project-assets.js.map +1 -1
  972. package/dist/runtime/session.d.ts +22 -45
  973. package/dist/runtime/session.d.ts.map +1 -1
  974. package/dist/runtime/session.js +26 -46
  975. package/dist/runtime/session.js.map +1 -1
  976. package/dist/runtime/settle.d.ts +4 -10
  977. package/dist/runtime/settle.d.ts.map +1 -1
  978. package/dist/runtime/settle.js +4 -10
  979. package/dist/runtime/settle.js.map +1 -1
  980. package/dist/runtime/state-evaluator.d.ts +15 -37
  981. package/dist/runtime/state-evaluator.d.ts.map +1 -1
  982. package/dist/runtime/state-evaluator.js +27 -44
  983. package/dist/runtime/state-evaluator.js.map +1 -1
  984. package/dist/runtime/text-geometry.d.ts +18 -47
  985. package/dist/runtime/text-geometry.d.ts.map +1 -1
  986. package/dist/runtime/text-geometry.js +13 -27
  987. package/dist/runtime/text-geometry.js.map +1 -1
  988. package/dist/sdk/index.d.ts +2 -7
  989. package/dist/sdk/index.d.ts.map +1 -1
  990. package/dist/sdk/index.js +30 -138
  991. package/dist/sdk/index.js.map +1 -1
  992. package/dist/tween/command-decorator.d.ts +6 -26
  993. package/dist/tween/command-decorator.d.ts.map +1 -1
  994. package/dist/tween/command-decorator.js +1 -6
  995. package/dist/tween/command-decorator.js.map +1 -1
  996. package/dist/tween/command.d.ts +6 -53
  997. package/dist/tween/command.d.ts.map +1 -1
  998. package/dist/tween/command.js +5 -40
  999. package/dist/tween/command.js.map +1 -1
  1000. package/dist/tween/ease/curve.d.ts +2 -17
  1001. package/dist/tween/ease/curve.d.ts.map +1 -1
  1002. package/dist/tween/ease/curve.js +1 -6
  1003. package/dist/tween/ease/curve.js.map +1 -1
  1004. package/dist/tween/ease/describe.d.ts +0 -11
  1005. package/dist/tween/ease/describe.d.ts.map +1 -1
  1006. package/dist/tween/ease/describe.js +0 -23
  1007. package/dist/tween/ease/describe.js.map +1 -1
  1008. package/dist/tween/ease/spec.d.ts +2 -18
  1009. package/dist/tween/ease/spec.d.ts.map +1 -1
  1010. package/dist/tween/ease/spec.js.map +1 -1
  1011. package/dist/tween/inert.d.ts +1 -14
  1012. package/dist/tween/inert.d.ts.map +1 -1
  1013. package/dist/tween/inert.js +1 -14
  1014. package/dist/tween/inert.js.map +1 -1
  1015. package/dist/tween/lerp.d.ts +2 -26
  1016. package/dist/tween/lerp.d.ts.map +1 -1
  1017. package/dist/tween/lerp.js +2 -26
  1018. package/dist/tween/lerp.js.map +1 -1
  1019. package/dist/tween/loop.d.ts +9 -50
  1020. package/dist/tween/loop.d.ts.map +1 -1
  1021. package/dist/tween/loop.js +6 -31
  1022. package/dist/tween/loop.js.map +1 -1
  1023. package/dist/tween/prepare.d.ts +2 -30
  1024. package/dist/tween/prepare.d.ts.map +1 -1
  1025. package/dist/tween/prepare.js +2 -30
  1026. package/dist/tween/prepare.js.map +1 -1
  1027. package/dist/tween/stepper.d.ts +4 -25
  1028. package/dist/tween/stepper.d.ts.map +1 -1
  1029. package/dist/tween/stepper.js.map +1 -1
  1030. package/dist/tween/to-command.d.ts +1 -8
  1031. package/dist/tween/to-command.d.ts.map +1 -1
  1032. package/dist/tween/to-command.js +2 -25
  1033. package/dist/tween/to-command.js.map +1 -1
  1034. package/dist/util/context.d.ts +4 -29
  1035. package/dist/util/context.d.ts.map +1 -1
  1036. package/dist/util/context.js +3 -15
  1037. package/dist/util/context.js.map +1 -1
  1038. package/dist/util/csv.d.ts +4 -29
  1039. package/dist/util/csv.d.ts.map +1 -1
  1040. package/dist/util/csv.js +3 -22
  1041. package/dist/util/csv.js.map +1 -1
  1042. package/dist/util/metrics.d.ts +2 -26
  1043. package/dist/util/metrics.d.ts.map +1 -1
  1044. package/dist/util/metrics.js +2 -26
  1045. package/dist/util/metrics.js.map +1 -1
  1046. package/dist/util/random.d.ts +20 -87
  1047. package/dist/util/random.d.ts.map +1 -1
  1048. package/dist/util/random.js +20 -87
  1049. package/dist/util/random.js.map +1 -1
  1050. package/dist/util/reference.d.ts +6 -35
  1051. package/dist/util/reference.d.ts.map +1 -1
  1052. package/dist/util/reference.js +1 -4
  1053. package/dist/util/reference.js.map +1 -1
  1054. package/dist/util/scheduler.d.ts +6 -27
  1055. package/dist/util/scheduler.d.ts.map +1 -1
  1056. package/dist/util/scheduler.js +8 -35
  1057. package/dist/util/scheduler.js.map +1 -1
  1058. package/package.json +1 -1
  1059. package/dist/browser/chunks/chunk-4BDLFEOC.js.map +0 -7
  1060. package/dist/browser/chunks/chunk-CCGVIR4F.js.map +0 -7
  1061. package/dist/browser/chunks/chunk-N4WSN5WY.js +0 -13
  1062. package/dist/browser/chunks/chunk-N4WSN5WY.js.map +0 -7
  1063. package/dist/browser/chunks/chunk-WZSI3GSK.js +0 -6
  1064. package/dist/browser/chunks/chunk-WZSI3GSK.js.map +0 -7
  1065. package/dist/renamed-scene-names.d.ts +0 -17
  1066. package/dist/renamed-scene-names.d.ts.map +0 -1
  1067. package/dist/renamed-scene-names.js +0 -9
  1068. package/dist/renamed-scene-names.js.map +0 -1
  1069. package/dist/runtime/precompisition.d.ts +0 -24
  1070. package/dist/runtime/precompisition.d.ts.map +0 -1
  1071. package/dist/runtime/precompisition.js +0 -7
  1072. package/dist/runtime/precompisition.js.map +0 -1
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/attributes/audio/schedule.ts", "../../../src/attributes/audio/sound.ts", "../../../src/attributes/audio/effects/union.ts", "../../../src/attributes/audio/transition.ts", "../../../src/attributes/audio/request.ts", "../../../src/attributes/shape/shaders/pack.ts", "../../../src/project/tree.ts", "../../../src/components/trees/node/node-walk.ts", "../../../src/components/trees/node/node-editor-state.ts", "../../../src/components/trees/root/canvas2d-node.ts", "../../../src/components/builtins/geometry/geometry.ts", "../../../src/components/builtins/geometry/composite.ts", "../../../src/components/builtins/layout/layout.ts", "../../../src/components/builtins/text/text.ts", "../../../src/components/builtins/providers/providers.ts", "../../../src/components/builtins/audio/audio.ts", "../../../src/components/builtins/media/media.ts", "../../../src/render3d/camera.ts", "../../../src/components/builtins/three/three.ts", "../../../src/components/builtins/three/canvas3d.ts", "../../../src/document/types.ts", "../../../src/document/project.ts", "../../../src/document/migrate.ts", "../../../src/document/validate.ts", "../../../src/document/missing-node.ts", "../../../src/document/vocabulary.ts", "../../../src/document/builtins.ts", "../../../src/document/deny-globals.ts", "../../../src/document/registry.ts", "../../../src/document/placement.ts", "../../../src/document/audio.ts", "../../../src/document/command-traits.ts", "../../../src/document/diff.ts", "../../../src/document/expression/refs.ts", "../../../src/document/doc-index.ts", "../../../src/document/settled-index.ts", "../../../src/document/timeline-patch.ts", "../../../src/document/timeline.ts", "../../../src/render/descriptors/richtext.ts", "../../../src/render/descriptors/transform.ts", "../../../src/render/descriptors/path.ts", "../../../src/render/text-layout.ts", "../../../src/render/render-issue.ts", "../../../src/render3d/builders.ts", "../../../src/render3d/segments.ts", "../../../src/render3d/rounded-box.ts", "../../../src/render3d/transform.ts", "../../../src/render3d/geometry.ts", "../../../src/render3d/matrix4.ts", "../../../src/render3d/bounds3d.ts", "../../../src/render3d/material.ts", "../../../src/assets/manager.ts", "../../../src/assets/scope.ts", "../../../src/util/scheduler.ts", "../../../src/runtime/frame-time.ts", "../../../src/runtime/placement.ts", "../../../src/runtime/clip-instance.ts", "../../../src/assets/asset-index.ts", "../../../src/runtime/asset-refine.ts", "../../../src/runtime/asset-update.ts", "../../../src/runtime/audio-index.ts", "../../../src/runtime/clip-store.ts", "../../../src/runtime/state-evaluator.ts", "../../../src/runtime/settle.ts", "../../../src/runtime/project-assets.ts", "../../../src/runtime/asset-timeline.ts", "../../../src/runtime/node-picking3d.ts", "../../../src/runtime/node-picking.ts", "../../../src/runtime/text-geometry.ts", "../../../src/runtime/playback-controller.ts", "../../../src/assets/catalog.ts", "../../../src/runtime/playback.ts", "../../../src/platform/ticker.ts", "../../../src/platform/stepped-clock.ts", "../../../src/runtime/session.ts", "../../../src/util/csv.ts", "../../../src/util/generateList.ts", "../../../src/util/reference.ts", "../../../src/util/random.ts", "../../../src/tween/stepper.ts"],
4
- "sourcesContent": ["import type { AssetCatalog } from \"@/assets/catalog\";\nimport { resolveAudioEffects, type AudioEffectsInput } from \"./effects/chain\";\nimport { integrateSpeedToClipTime, isRamp, sourceTimeAtClipElapsed, staticValue, type Param } from \"./ramp\";\nimport type { AudioTransition } from \"./transition\";\nimport type { AudioBusStop, AudioRequest } from \"./request\";\n\n/** One clip a command's sound plays, in its clip's seconds. */\nexport interface AudioClip {\n src: string;\n /** When it starts. */\n at?: number;\n /** When it is cut, however much of it is left. */\n until?: number;\n /** In-point inside the source, in seconds. */\n trimStart?: number;\n /** Out-point inside the source. Absent plays to the source's end. */\n trimEnd?: number;\n loop?: boolean;\n volume?: Param;\n /** Playback rate; a ramp runs over source seconds after `trimStart`. */\n speed?: Param;\n effects?: AudioEffectsInput;\n transitionIn?: AudioTransition;\n transitionOut?: AudioTransition;\n /** Source-adjacent first — see {@link AudioRequest.bus}. */\n bus?: readonly AudioBusStop[];\n /** Sound nobody asked for by name — see {@link AudioRequest.optional}. */\n optional?: boolean;\n}\n\nfunction scalarSpeed(speed: number): number {\n return Number.isFinite(speed) && speed > 0 ? speed : 1;\n}\n\n/**\n * Clip seconds spent playing the first `sourceElapsed` of `sourceLength` source\n * seconds at `speed`. Must match the device's `playbackRate` schedule, or a\n * request ends before or after its sound does.\n */\nexport function clipTimeAtSource(speed: Param, sourceLength: number, sourceElapsed: number = sourceLength): number {\n if (isRamp(speed)) return integrateSpeedToClipTime(speed, sourceLength, sourceElapsed);\n return Math.max(0, Math.min(sourceElapsed, sourceLength)) / scalarSpeed(speed);\n}\n\n/** Inverse of {@link clipTimeAtSource}: the source seconds reached `clipElapsed` clip seconds in. */\nexport function sourceTimeAtClip(speed: Param, sourceLength: number, clipElapsed: number): number {\n if (isRamp(speed)) return sourceTimeAtClipElapsed(speed, sourceLength, clipElapsed);\n return Math.max(0, Math.min(sourceLength, clipElapsed * scalarSpeed(speed)));\n}\n\n/** How long a clip lasts on the timeline: its trimmed source at its speed. `trimEnd` absent plays to `mediaDuration`. */\nexport function clipDurationOf(clip: { readonly trimStart?: number; readonly trimEnd?: number; readonly speed?: Param }, mediaDuration: number): number {\n const length = Math.max(0, (clip.trimEnd ?? mediaDuration) - (clip.trimStart ?? 0));\n return clipTimeAtSource(clip.speed ?? 1, length);\n}\n\n/**\n * The request `clip` schedules.\n *\n * Bounded when it has an end — a trim, or an `until` — and **open** otherwise, so\n * a bed nothing cuts continues across later tracks; see `AudioRequest.open`.\n */\nexport function requestOf(clip: AudioClip, catalog: AssetCatalog, ownerKey: string, n: number): AudioRequest {\n const at = clip.at ?? 0;\n const until = clip.until ?? Infinity;\n const trimStart = clip.trimStart ?? 0;\n const trimEnd = clip.trimEnd ?? Infinity;\n const loop = clip.loop ?? false;\n const effects = resolveAudioEffects(clip.effects);\n // Read even when the length goes unused: a missing file throws here, as a\n // build error, rather than playing silence.\n const mediaDuration = catalog.getMediaDuration(clip.src);\n\n let speed = clip.speed ?? 1;\n if (loop && isRamp(speed)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(`[motionscript] A speed ramp on a looping clip (${clip.src}) has no one source axis to run over; it plays at its start value.`);\n }\n speed = staticValue(speed, 1);\n }\n const sourceLength = Math.max(0, (Number.isFinite(trimEnd) ? trimEnd : mediaDuration) - trimStart);\n\n const request: AudioRequest = {\n id: `${ownerKey}|${clip.src}|${at}|${n}`,\n src: clip.src,\n startAt: at,\n endAt: Infinity,\n trimStart,\n volume: clip.volume ?? 1,\n speed,\n loop,\n ownerId: ownerKey,\n };\n if (isRamp(speed)) request.sourceLength = sourceLength;\n if (effects.length > 0) request.effects = effects;\n if (clip.transitionIn) request.transitionIn = clip.transitionIn;\n if (clip.transitionOut) request.transitionOut = clip.transitionOut;\n if (clip.bus) request.bus = clip.bus;\n if (clip.optional) request.optional = true;\n\n // A loop repeats the trimmed region, so a `trimEnd` bounds one pass and says\n // nothing about when the clip stops: only a cut (`until`) ends it, and with\n // none it runs open to the project end like any other bed.\n if (loop && trimEnd > trimStart && Number.isFinite(trimEnd)) request.trimEnd = trimEnd;\n\n if (loop && Number.isFinite(until)) {\n request.endAt = until;\n } else if (loop) {\n request.open = true;\n } else if (Number.isFinite(trimEnd)) {\n request.endAt = Math.min(until, at + clipTimeAtSource(speed, sourceLength));\n } else {\n const natural = clipTimeAtSource(speed, sourceLength);\n if (Number.isFinite(until)) {\n request.endAt = Math.min(until, at + natural);\n } else {\n request.open = true;\n request.mediaDuration = natural;\n }\n }\n return request;\n}\n", "import type { AudioEffect } from \"@/attributes/audio/effects/union\";\nimport { type AudioEffectsInput, resolveAudioEffects } from \"@/attributes/audio/effects/chain\";\nimport type { Param } from \"@/attributes/audio/ramp\";\nimport { clipTimeAtSource } from \"@/attributes/audio/schedule\";\n\ninterface SoundPropsBase {\n src: string;\n volume?: Param;\n /** Playback rate; a ramp runs over source seconds after `trimStart`. */\n speed?: Param;\n loop?: boolean;\n /** Audio effects applied to the clip (gain, eq, tremolo, echo). */\n effects?: AudioEffectsInput;\n}\n\n/**\n * Author-facing sound props. Two mutually-exclusive ways to bound the clip:\n *\n * - `{ trimStart?, trimEnd? }` — explicit in/out points into the source file.\n * - `{ duration? }` — syntax sugar for a clip that runs `duration` seconds from\n * the start (equivalent to `trimStart: 0, trimEnd: duration`).\n *\n * When neither `trimEnd` nor `duration` is given, the clip runs to the source's\n * full length (resolved from the asset catalog). `trimStart` defaults to 0.\n */\nexport type SoundProps =\n | (SoundPropsBase & { trimStart?: number; trimEnd?: number; duration?: undefined })\n | (SoundPropsBase & { duration?: number; trimStart?: undefined; trimEnd?: undefined });\n\n/** Canonical, fully-resolved sound props. `trimEnd` is resolved against the catalog. */\nexport interface ResolvedSoundProps {\n src: string;\n volume?: Param;\n speed?: Param;\n loop?: boolean;\n trimStart?: number;\n trimEnd?: number;\n effects?: AudioEffect[];\n}\n\n/**\n * A clip's resolved props, and how long it runs. What a node plays is declared\n * through `declareAudio`; this is only the arithmetic over one clip.\n */\nexport class Sound {\n readonly src: string;\n volume: Param;\n speed: Param;\n loop: boolean;\n trimStart: number;\n trimEnd: number;\n effects: AudioEffect[];\n\n constructor(props: SoundProps) {\n this.src = props.src;\n this.volume = props.volume ?? 1;\n this.speed = props.speed ?? 1;\n this.loop = props.loop ?? false;\n // `duration` is sugar for `trimStart: 0, trimEnd: duration`.\n this.trimStart = props.trimStart ?? 0;\n this.trimEnd = props.trimEnd ?? props.duration ?? Infinity;\n this.effects = resolveAudioEffects(props.effects);\n }\n\n /** Clip seconds `trimmedSourceLength` source seconds take at this clip's speed. */\n clipDurationFor(trimmedSourceLength: number): number {\n return clipTimeAtSource(this.speed, trimmedSourceLength);\n }\n\n /** @deprecated Renamed to {@link clipDurationFor}; kept until 1.0. */\n sceneDurationFor(trimmedSourceLength: number): number {\n return this.clipDurationFor(trimmedSourceLength);\n }\n\n /** Clip seconds, speed profile applied; `undefined` when nothing bounds the clip. */\n get clipDuration(): number | undefined {\n return this.trimEnd !== Infinity\n ? this.clipDurationFor(this.trimEnd - this.trimStart)\n : undefined;\n }\n}\n", "import type { GainEffect } from \"./implementations/gain\";\nimport type { HighPassEffect } from \"./implementations/highpass\";\nimport type { LowPassEffect } from \"./implementations/lowpass\";\nimport type { TremoloEffect } from \"./implementations/tremolo\";\nimport type { EchoEffect } from \"./implementations/echo\";\nimport { paramKey } from \"../ramp\";\n\n/** Every concrete audio effect a sound or a bus can carry. */\nexport type AudioEffect =\n | GainEffect\n | HighPassEffect\n | LowPassEffect\n | TremoloEffect\n | EchoEffect;\n\n/**\n * Equal for two chains exactly when they sound the same. A device keys its\n * playback by it, so an edited effect tears down the stale source rather than\n * playing it until the next stop.\n */\nexport function effectsKey(effects: readonly AudioEffect[] | undefined): string {\n if (!effects || effects.length === 0) return \"\";\n return effects.map((f) => {\n switch (f.type) {\n case \"gain\":\n return `gain:${paramKey(f.value)}`;\n case \"highpass\":\n case \"lowpass\":\n return `${f.type}:${paramKey(f.frequency)}:${paramKey(f.q)}`;\n case \"tremolo\":\n return `tremolo:${paramKey(f.rate)}:${paramKey(f.depth)}`;\n case \"echo\":\n return `echo:${paramKey(f.delay)}:${paramKey(f.feedback)}:${paramKey(f.mix)}`;\n }\n }).join(\"|\");\n}\n", "import { easeOfSpec, type EaseSpec } from \"@/tween/ease/spec\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\n\n/**\n * What happens as a clip enters (`transitionIn`) or leaves (`transitionOut`):\n * today, a fade over its first or last `duration` clip seconds.\n *\n * A cross-fade is two clips that overlap, the first carrying a `transitionOut`\n * and the second a `transitionIn` as long as the overlap; equal-power shapes\n * are complementary, so the pair needs no link between them.\n */\nexport interface AudioTransition {\n readonly duration: number;\n /**\n * Progress through the transition (x, 0→1) to how far it has come (y, the\n * gain for a fade), read as entering; a `transitionOut` plays it backwards.\n * Default `\"equalPower\"`, sin(πx/2).\n */\n readonly curve?: \"equalPower\" | EaseSpec;\n}\n\nconst EQUAL_POWER: EasingFunction = (x) => Math.sin((Math.max(0, Math.min(1, x)) * Math.PI) / 2);\nconst shapes = new WeakMap<EaseSpec, EasingFunction>();\n\nfunction shapeOf(transition: AudioTransition): EasingFunction {\n const curve = transition.curve;\n if (curve === undefined || curve === \"equalPower\") return EQUAL_POWER;\n let shape = shapes.get(curve);\n if (!shape) shapes.set(curve, (shape = easeOfSpec(curve)));\n return shape;\n}\n\n/**\n * The two transitions' durations on a clip `length` seconds long: shrunk in\n * proportion when together they would overrun it.\n */\nexport function transitionSpans(length: number, transitionIn?: AudioTransition, transitionOut?: AudioTransition): { readonly in: number; readonly out: number } {\n const wanted = { in: Math.max(0, transitionIn?.duration ?? 0), out: Math.max(0, transitionOut?.duration ?? 0) };\n if (!Number.isFinite(length)) return { in: wanted.in, out: 0 };\n const total = wanted.in + wanted.out;\n if (total <= length || total === 0) return wanted;\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(`[motionscript] Transitions of ${total.toFixed(3)}s overrun a ${length.toFixed(3)}s clip; both are shortened to fit.`);\n }\n const scale = Math.max(0, length) / total;\n return { in: wanted.in * scale, out: wanted.out * scale };\n}\n\n/**\n * The gain the transitions put on a clip at `t` of its `length` seconds: 1\n * outside both. An open clip (`length` not finite) has no end to leave from.\n */\nexport function transitionGainAt(t: number, length: number, transitionIn?: AudioTransition, transitionOut?: AudioTransition): number {\n const spans = transitionSpans(length, transitionIn, transitionOut);\n let gain = 1;\n if (transitionIn && spans.in > 0 && t < spans.in) gain *= Math.max(0, shapeOf(transitionIn)(Math.max(0, t) / spans.in));\n if (transitionOut && spans.out > 0 && t > length - spans.out) gain *= Math.max(0, shapeOf(transitionOut)(Math.max(0, length - t) / spans.out));\n return gain;\n}\n\nexport function transitionKey(transition: AudioTransition | undefined): string {\n if (!transition) return \"_\";\n return `${transition.duration}:${typeof transition.curve === \"object\" ? JSON.stringify(transition.curve) : transition.curve ?? \"equalPower\"}`;\n}\n", "import { effectsKey, type AudioEffect } from \"@/attributes/audio/effects/union\";\nimport { paramKey, type Param } from \"@/attributes/audio/ramp\";\nimport { transitionKey, type AudioTransition } from \"@/attributes/audio/transition\";\n\n/**\n * One bus a clip's signal passes through on its way to the master.\n *\n * A flattened snapshot of an {@link AudioBus} node, not a reference to it: core\n * describes what the graph should be and a platform builds it, so what crosses\n * that seam has to be plain data.\n *\n * {@link id} is what makes it a *bus* rather than per-clip processing — two\n * clips naming the same id share one live chain, so a reverb on a bus is a\n * single tail fed by both, which is not the same sound as that reverb applied\n * to each clip separately.\n */\nexport interface AudioBusStop {\n id: string;\n /** Linear gain. A {@link Param}, so a bus fade is a ramp rather than a per-frame write. */\n volume: Param;\n /** -1 hard left … +1 hard right. */\n pan: Param;\n mute: boolean;\n /** Applied in array order, index 0 closest to the source. */\n effects?: AudioEffect[];\n transitionIn?: AudioTransition;\n transitionOut?: AudioTransition;\n /**\n * When the bus is present, in the same seconds as the request carrying the\n * stop: what a ramp in {@link volume} or {@link effects}, and its\n * transitions, run over, as a clip's run over the clip. Not the clip's span, because one bus\n * feeds many clips and its fade has to mean one thing to all of them.\n */\n startAt: number;\n endAt: number;\n}\n\n/**\n * Everything about a stop that changes what passes through it, as a string — so\n * a device can tell an edited bus from the one it already built.\n */\nexport function busStopKey(stop: AudioBusStop): string {\n return `${stop.id}:${paramKey(stop.volume)}:${paramKey(stop.pan)}:${stop.mute ? 1 : 0}:${effectsKey(stop.effects)}:${transitionKey(stop.transitionIn)}:${transitionKey(stop.transitionOut)}:${stop.startAt}:${stop.endAt}`;\n}\n\nexport interface AudioParams {\n src: string;\n volume?: Param;\n loop?: boolean;\n trimStart?: number; // in seconds\n trimEnd?: number; // in seconds\n effects?: AudioEffect[];\n}\n\nexport interface AudioRequest {\n id: string;\n /** The asset path or URL. ('src' is standard for media) */\n src: string;\n\n // --- Timeline Synchronization (Clip Time) ---\n\n /** The clip timestamp when the audio should START playing. */\n startAt: number; // in seconds\n\n /**\n * The clip timestamp when the audio should STOP playing.\n *\n * Always a number, and **`Infinity` is the open/unbounded sentinel** — never\n * `null` or `undefined`. An unstopped clip carries `Infinity` until\n * {@link open} resolution pins it to the project end.\n *\n * So test it with `Number.isFinite(endAt)`. A `?? Infinity` or `!== null`\n * guard is dead code that reads as if the field were nullable.\n */\n endAt: number; // in seconds\n\n /**\n * True when this request was started and left running at its scene's end —\n * neither explicitly stopped nor finite-trimmed. Open requests\n * are exempt from the per-scene audio clamp and instead **continue across scene\n * boundaries**: `assembleTimeline` shifts them to absolute time and resolves\n * `endAt = min(startAt + mediaDuration, projectTotalDuration)` (a looped open\n * request runs to the project end). Bounded requests are unaffected.\n */\n open?: boolean;\n\n /**\n * Source media length in seconds, carried on **open** requests so the\n * cross-scene end can be resolved at assembly time without re-reading the\n * asset catalog. Ignored for bounded requests.\n */\n mediaDuration?: number;\n\n // --- Media Trimming (Local Audio Time) ---\n\n /** Offset in seconds to skip ahead in the audio file. Default: 0 */\n trimStart: number;\n\n /**\n * Out-point inside the source, in seconds, carried **only by a looping\n * request that has one** (`trimEnd` greater than {@link trimStart}). A device\n * loops the region `[trimStart, trimEnd)` rather than the whole buffer; for a\n * request that does not loop, {@link endAt} already ends playback at the\n * out-point and this is absent.\n */\n trimEnd?: number;\n\n // --- Playback Settings ---\n\n /** Linear gain over the clip's own seconds. Default 1. */\n volume: Param;\n /** Playback rate, default 1. A ramp runs over the first {@link sourceLength} source seconds after `trimStart`. */\n speed?: Param;\n /** The source seconds a speed ramp is placed on; carried only with one, so the device and the timeline place it alike. */\n sourceLength?: number;\n loop: boolean; // Default: false\n\n // --- Processing ---\n\n /** Audio effects applied in array order (index 0 closest to the source). */\n effects?: AudioEffect[];\n /** A gain over the clip's first and last seconds, on top of {@link volume}. */\n transitionIn?: AudioTransition;\n transitionOut?: AudioTransition;\n\n /**\n * The buses this clip feeds, **source-adjacent first** — the same ordering\n * convention {@link effects} uses, so the whole chain reads in signal order:\n * the clip's own effects, then each stop in turn, then the master.\n *\n * Absent means the clip goes straight to the master, which is what every\n * request did before buses existed.\n */\n bus?: readonly AudioBusStop[];\n\n // --- Timeline attribution (display only) ---\n\n /**\n * The owner key of the node that declared this request: its document row's\n * id, plus the path below that row for a node a composite built. Lets a\n * timeline draw the waveform on that node's bar. Never affects playback.\n */\n ownerId?: string;\n\n /**\n * The sound of something that is also a picture — a video's own track. A\n * source only such requests want is silence when it holds no audio, where\n * for a request without this it is a failure to report. Never part of the\n * request's identity: it changes nothing a device plays.\n */\n optional?: boolean;\n}", "import type { ShaderUniformRecord } from \"./uniforms\";\nimport type { ShaderLanguage } from \"./language\";\n\n/**\n * A **shader pack**: a program, plus what a host may edit about it.\n *\n * The interchange format for a shader — authored as JSON, imported as a value,\n * handed to `Fills.shader` or `Effects.shader`. It exists because a bare source\n * string says nothing about which of its uniforms are meant to be touched, what\n * they are called in a panel, or what range they take, so every host that wanted\n * to offer a slider had to keep that table itself, beside a program it did not\n * own.\n *\n * **Two scopes, one shape.** A fill paints inside a shape's path and may sample\n * textures; an effect paints over a layer and may sample what is beneath it.\n * Those are the only two differences, and making them arms of a union rather\n * than optional fields on one type is what makes `Fills.shader(anEffectShader)`\n * a compile error instead of a program that fails at the first frame.\n */\nexport type Shader = FillShader | EffectShader;\n\n/** What both scopes carry. */\nexport interface ShaderBase {\n /**\n * Format tag, so a file that is not one of these can be told apart from one\n * that is merely from a newer version.\n */\n $kind?: string;\n /**\n * Provenance, when the pack came from a library row. **Not** how it is\n * registered — `Registry.addShader` takes the key separately, exactly as\n * `Registry.addNode` does, so the same file can be registered under whatever\n * name a project wants and the file itself stays portable.\n */\n id?: string;\n name: string;\n description?: string;\n /** The language `source` is written in; normalising a pack stamps WGSL when absent. */\n language?: ShaderLanguage;\n /**\n * The program. In WGSL, a fill defines `fn fill(in: FillIn) -> vec4f` and an\n * effect `fn effect(in: EffectIn) -> vec4f`, and the uniforms are the\n * members of `struct Params` (types, layout and all); `properties` name\n * those members in their `inputs`.\n */\n source: string;\n /** Uniform values the properties do not cover, by name. */\n uniforms?: ShaderUniformRecord;\n /** The editable values, by property id. */\n properties: Record<string, ShaderProperty>;\n}\n\n/** A shader that paints inside a shape's path. */\nexport interface FillShader extends ShaderBase {\n scope: \"fill\";\n /**\n * The images the program samples, by name. In WGSL, `sample_texture(uv)`\n * samples the first; the fill that applies the pack supplies each `src`.\n */\n textures?: readonly { name: string; description?: string }[];\n}\n\n/** A shader that paints over a layer. */\nexport interface EffectShader extends ShaderBase {\n scope: \"effect\";\n /**\n * Whether the program is meant to run on the backdrop path, where\n * `sample_src` reads what is beneath the node rather than its own layer.\n *\n * A fact about the **program**, which is why it lives here rather than on\n * the effect instance: the instance keeps `mode`, the cross-cutting field\n * five generic consumers read without knowing what type they hold. The\n * builder maps this to `mode: \"backdrop\"` as the default and a caller may\n * still override it.\n */\n backdrop?: boolean;\n}\n\n/** One editable value. */\nexport type ShaderProperty = KnownShaderProperty | UnknownShaderProperty;\n\nexport type KnownShaderProperty =\n | NumberProperty\n | SliderProperty\n | AngleProperty\n | HueProperty\n | BooleanProperty\n | ColorProperty\n | VectorProperty\n | PointProperty;\n\ninterface ShaderPropertyBase {\n /** What a panel calls it. Falls back to the property id. */\n name?: string;\n /**\n * The uniform each of this property's components writes.\n *\n * The composite mechanism, and the reason a property is not just a uniform\n * under another name: one editable value may span several uniforms. A\n * scalar names one component, `value`; a point may name `value` for a\n * `float2`, or `x` and `y` for two separate floats.\n */\n inputs: Record<string, string>;\n}\n\n/** A scalar, drawn as a number input. */\nexport interface NumberProperty extends ShaderPropertyBase {\n kind: \"number\";\n default: number;\n min?: number;\n max?: number;\n step?: number;\n}\n\n/** A scalar with a bounded range, drawn as a slider. */\nexport interface SliderProperty extends ShaderPropertyBase {\n kind: \"slider\";\n default: number;\n min: number;\n max: number;\n step?: number;\n}\n\n/** Degrees, matching every other angle in the library. */\nexport interface AngleProperty extends ShaderPropertyBase {\n kind: \"angle\";\n default: number;\n}\n\n/** Degrees around the colour wheel. */\nexport interface HueProperty extends ShaderPropertyBase {\n kind: \"hue\";\n default: number;\n}\n\n/** Written to its uniform as 1 or 0, since a `bool` cannot be a uniform member in WGSL. */\nexport interface BooleanProperty extends ShaderPropertyBase {\n kind: \"boolean\";\n default: boolean;\n}\n\n/** RGBA in 0–1. A CSS string is accepted and parsed, so theme tokens work. */\nexport interface ColorProperty extends ShaderPropertyBase {\n kind: \"color\";\n default: string | readonly number[];\n}\n\n/** A fixed-width run of floats. */\nexport interface VectorProperty extends ShaderPropertyBase {\n kind: \"vector\";\n default: readonly number[];\n}\n\n/** Two floats, as one `float2` or as separate `x`/`y` uniforms. */\nexport interface PointProperty extends ShaderPropertyBase {\n kind: \"point\";\n default: readonly number[] | { x: number; y: number };\n}\n\n/**\n * A property whose kind this version of the vocabulary does not name.\n *\n * Open at the edges on purpose: a pack written against a newer version should\n * draw the controls a host knows and say so about the rest, instead of\n * failing to load at all.\n *\n * An unknown property is still *resolved* — its `default` is written to its\n * `inputs` unchanged — so a shader whose panel a host cannot fully draw still\n * renders correctly.\n */\nexport interface UnknownShaderProperty extends ShaderPropertyBase {\n kind: string;\n default?: unknown;\n [option: string]: unknown;\n}\n\nconst KNOWN_KINDS = new Set([\n \"number\", \"slider\", \"angle\", \"hue\", \"boolean\", \"color\", \"vector\", \"point\",\n]);\n\n/** Whether `property` is one this version knows how to draw. */\nexport function isKnownShaderProperty(property: ShaderProperty): property is KnownShaderProperty {\n return KNOWN_KINDS.has(property.kind);\n}\n\n/** Ceiling on properties in one pack, so a malformed import cannot exhaust a host. */\nexport const MAX_SHADER_PROPERTIES = 64;\n\n/** Ceiling on source length, matching what a compile cache can reasonably hold. */\nexport const MAX_SHADER_SOURCE = 64_000;\n\n/**\n * Validate and normalise an authored pack.\n *\n * **Throws** when the pack is structurally not one — no source, no usable\n * scope — because there is nothing to render and a silent empty shader is a\n * blank frame with no explanation. **Warns and drops** an individual malformed\n * property, because the rest of the shader still works and a panel missing one\n * control is a better answer than a scene that will not build. That split is the\n * same one `normalizeUniforms` makes.\n */\nexport function normalizeShaderPack(input: unknown): Shader {\n if (typeof input !== \"object\" || input === null) {\n throw new Error(\"A shader pack must be an object.\");\n }\n const raw = input as Record<string, unknown>;\n\n const scope = raw.scope;\n if (scope !== \"fill\" && scope !== \"effect\") {\n throw new Error(\n `A shader pack needs scope \"fill\" or \"effect\", got ${JSON.stringify(scope)}. ` +\n `The two are written against different contracts — a fill has no backdrop to ` +\n `sample and an effect has no shape box to map coordinates onto.`,\n );\n }\n\n const source = typeof raw.source === \"string\" ? raw.source.trim() : \"\";\n if (source === \"\") throw new Error(`Shader pack \"${String(raw.name ?? \"?\")}\" has no source.`);\n if (source.length > MAX_SHADER_SOURCE) {\n throw new Error(\n `Shader pack \"${String(raw.name ?? \"?\")}\" source is ${source.length} characters, ` +\n `over the ${MAX_SHADER_SOURCE} ceiling.`,\n );\n }\n\n if (raw.language !== undefined && raw.language !== \"wgsl\") {\n throw new Error(\n `Shader pack \"${String(raw.name ?? \"?\")}\" is written in ${JSON.stringify(raw.language)}; ` +\n `only WGSL is supported. Port it to WGSL.`,\n );\n }\n\n const base: ShaderBase = {\n ...(typeof raw.$kind === \"string\" ? { $kind: raw.$kind } : {}),\n ...(typeof raw.id === \"string\" ? { id: raw.id } : {}),\n name: typeof raw.name === \"string\" && raw.name !== \"\" ? raw.name : \"Shader\",\n ...(typeof raw.description === \"string\" ? { description: raw.description } : {}),\n language: \"wgsl\",\n source,\n ...(isRecord(raw.uniforms) ? { uniforms: raw.uniforms as ShaderUniformRecord } : {}),\n properties: normalizeProperties(raw.properties, String(raw.name ?? \"?\")),\n };\n\n if (scope === \"fill\") {\n const textures = Array.isArray(raw.textures)\n ? (raw.textures as unknown[]).filter((t): t is { name: string; description?: string } =>\n isRecord(t) && typeof t.name === \"string\").map((t) => ({ name: t.name, ...(typeof t.description === \"string\" ? { description: t.description } : {}) }))\n : [];\n return {\n ...base,\n scope: \"fill\",\n ...(textures.length ? { textures } : {}),\n };\n }\n return { ...base, scope: \"effect\", ...(raw.backdrop === true ? { backdrop: true } : {}) };\n}\n\nfunction normalizeProperties(input: unknown, where: string): Record<string, ShaderProperty> {\n if (!isRecord(input)) return {};\n const out: Record<string, ShaderProperty> = {};\n const claimed = new Map<string, string>();\n\n for (const [id, value] of Object.entries(input)) {\n if (Object.keys(out).length >= MAX_SHADER_PROPERTIES) {\n warn(`shader \"${where}\" declares more than ${MAX_SHADER_PROPERTIES} properties; the rest are ignored.`);\n break;\n }\n if (!isRecord(value) || typeof value.kind !== \"string\") {\n warn(`shader \"${where}\" property \"${id}\" has no kind; ignored.`);\n continue;\n }\n const inputs = value.inputs;\n if (!isRecord(inputs) || Object.keys(inputs).length === 0) {\n warn(`shader \"${where}\" property \"${id}\" names no uniform in \"inputs\"; ignored.`);\n continue;\n }\n let conflict = false;\n for (const uniform of Object.values(inputs)) {\n if (typeof uniform !== \"string\") {\n warn(`shader \"${where}\" property \"${id}\" has a non-string uniform name; ignored.`);\n conflict = true;\n break;\n }\n const prior = claimed.get(uniform);\n if (prior !== undefined) {\n // Two properties writing one uniform means the panel has two\n // controls for one value and whichever resolves last silently wins.\n warn(`shader \"${where}\" properties \"${prior}\" and \"${id}\" both write uniform \"${uniform}\"; \"${id}\" ignored.`);\n conflict = true;\n break;\n }\n claimed.set(uniform, id);\n }\n if (conflict) continue;\n\n out[id] = value as unknown as ShaderProperty;\n }\n return out;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst warned = new Set<string>();\n\n/** Warn once per message — a pack may be normalised on every scene build. */\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n if (warned.size > 256) warned.clear();\n warned.add(message);\n console.warn(`[shader] ${message}`);\n}\n", "/**\n * Structural key for a node within its scene: the child-index path from the\n * scene root, joined with \".\". The root is \"\". Not every node has an authored id\n * — the children a composite node builds for itself get a UUID apiece — so\n * lifespan tracking keys on this instead, which every node has. The build is\n * deterministic, so the same structural slot maps to the same path in both the\n * precomp pass and playback.\n */\n/** @internal */\nexport function nodePath(parentPath: string, childIndex: number): string {\n return parentPath === \"\" ? String(childIndex) : `${parentPath}.${childIndex}`;\n}\n\n/** @internal */\nexport interface NodeState {\n id: string;\n type: string;\n /** Attribute overrides applied when this state is active. */\n properties: Record<string, any>;\n\n\n}\n\n/**\n * A single audio clip exposed by a node for timeline display. Times are in\n * clip seconds; `src` is the (fetchable) audio source path. Nodes that own\n * audio — e.g. a Scene with managed sounds — report one entry per play range.\n */\n/** @internal */\nexport interface WaveformInfo {\n /** Fetchable audio source path / URL. */\n src: string;\n /** Clip timestamp (seconds) when the clip starts. */\n startTime: number;\n /** Clip timestamp (seconds) when the clip ends, or null if open-ended. */\n endTime: number | null;\n}\n\nexport interface TreeState {\n /**\n * The node's `NodeSpec.id` when it came from a document row, otherwise a\n * per-instance UUID — so it survives a rebuild for an authored node and\n * changes for one a composite built for itself. {@link path} is the key that\n * is stable for both.\n */\n id: string;\n /**\n * Structural path from the scene root (`\"\"` for the root, `\"0.2\"` for the\n * third child of the first). Stable across rebuilds for every node, authored\n * or not, so a host can key selection, expansion, and overrides on it. It is\n * also what `getNodeBox` / `setNodeOverride` accept.\n */\n path: string;\n type: string;\n meta?: Record<string, unknown>;\n /** Audio clips owned by this node, for waveform rendering in the timeline. */\n waveform?: WaveformInfo[];\n /**\n * Absolute timeline frame (across the whole video) at which this node first\n * appears. Undefined when its lifespan is unknown (e.g. no precomp data).\n */\n startFrame?: number;\n /**\n * Absolute timeline frame at which this node was last present. Together with\n * startFrame this bounds the node's track bar to its true lifespan.\n */\n endFrame?: number;\n children: TreeState[];\n}", "import { nodePath } from \"@/project/tree\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport type { Node } from \"./node\";\n\n/**\n * The subtree traversals the runtime drives, as free functions over a {@link Node}:\n * what is left on `Node` is what a node *is*, and what is here is what the engine\n * *does to* one. Every walk stops at an unmounted node — see {@link Node.mounted}.\n *\n * @internal\n */\n\n/**\n * Declare one node's own assets — never its children's, so each node's\n * declarations stay attributable to it.\n */\nexport function declareNode(node: Node, scope: AssetScope): void {\n node.declareAssets(scope);\n}\n\n/** {@link declareNode} over `root` and every mounted descendant, in every dimension. */\nexport function declareTree(root: Node, scope: AssetScope): void {\n if (!root.mounted) return;\n declareNode(root, scope);\n const children = root._allChildren;\n for (let i = 0; i < children.length; i++) declareTree(children[i], scope);\n}\n\n/**\n * Visit `root` and every mounted descendant with its structural path.\n *\n * Indexed over every dimension's children, so a path does not shift when a sibling\n * of another dimension comes or goes the way a filtered `children` index would.\n */\nexport function forEachOwner(root: Node, visit: (node: Node, path: string) => void): void {\n visitOwners(root, \"\", visit);\n}\n\nfunction visitOwners(node: Node, path: string, visit: (node: Node, path: string) => void): void {\n if (!node.mounted) return;\n visit(node, path);\n const children = node._allChildren;\n for (let i = 0; i < children.length; i++) visitOwners(children[i], nodePath(path, i), visit);\n}\n\n/**\n * Bind `node` with `host`'s catalog, context and clock without adopting it — what a\n * runtime passes as `AssetDeclaration`'s `bindSubtree` for a `Tex.surface` source.\n */\nexport function bindDetached(host: Node, node: Node): void {\n (host as unknown as { attachDetached(node: Node): void }).attachDetached(node);\n}\n\n/**\n * Sample every node's derived render state (currently motion) for this frame.\n *\n * Normally done by `attach` as it advances the clock; this is the seam for the\n * priming path, which needs the same state seeded without moving time (see\n * `StateEvaluator.resetSlot`).\n */\nexport function sampleTree(node: Node): void {\n node._sample();\n for (const child of node.children) sampleTree(child);\n}\n\n/**\n * Record the subtree's current positions as the motion history's previous frame,\n * stamped `at`, deriving no velocity.\n *\n * The driven path calls this with the props evaluated one frame back, so the\n * {@link sampleTree} that follows measures against the timeline rather than\n * against wherever the playhead happened to be.\n */\nexport function primeMotionTree(node: Node, at: number): void {\n node._primeMotion(at);\n for (const child of node.children) primeMotionTree(child, at);\n}\n", "import { Node } from \"./node\";\n\n/**\n * What an editor says about one node, as against what the document says.\n *\n * Neither of these is a prop. They are not authored values, they do not tween,\n * they are not part of the scene's meaning — an exported frame is the same\n * whether or not the person who made it had a layer folded away. They are the\n * editor's view of the tree, so they arrive on the side and are applied over it.\n */\nexport interface NodeEditorState {\n /**\n * Hide the node and everything under it: no paint, no pick, and no layout\n * slot — a hidden child of a row gives up its cell and its gap, the way\n * `display: none` does rather than `visibility: hidden`.\n *\n * The node **stays in the tree**. Dropping it instead would renumber every\n * later sibling's structural path, which is what a host's boxes, its\n * lifespans and its picking are all keyed on.\n */\n hidden?: boolean;\n /**\n * Take the node out of reach of the pointer while leaving the picture\n * untouched — Figma's padlock.\n *\n * Not the opposite of {@link hidden} and not a weaker form of it. A locked\n * node still draws, still lays out, and still confines its children; what it\n * declines is being the *answer* to a pick. Its children stay pickable,\n * because locking a group is about the group.\n */\n locked?: boolean;\n}\n\n/**\n * Editor state for a whole tree, keyed by {@link Node.key}.\n *\n * A record rather than a list: the walk that applies it asks once per node, and\n * a host with a thousand-node scene should not pay a scan for each.\n */\nexport type NodeEditorStates = Record<string, NodeEditorState>;\n\n/**\n * Push `states` onto the tree under `root`.\n *\n * Resolved onto the nodes rather than consulted from them, so `render` and the\n * pick walk read a local field instead of probing a record they would first have\n * to reach the scene to find. Called once per frame from `ClipInstance.attach`, which\n * is after the tree is built and before it is laid out — a node that appeared\n * this frame therefore gets its state on the same frame it appears.\n *\n * A node with no `key`, or a key the record does not mention, is reset rather\n * than left alone: the record is the whole truth about editor state, so a key\n * dropped from it is a node unhidden.\n */\nexport function applyEditorStates(root: Node, states: NodeEditorStates | undefined): void {\n const walk = (node: Node): void => {\n const state = node.key !== undefined ? states?.[node.key] : undefined;\n node._setEditorState(state?.hidden === true, state?.locked === true);\n for (const child of node._allChildren) walk(child);\n };\n walk(root);\n}\n", "import { RenderContext2D, RenderPass2D } from \"@/render/render-context2d\";\nimport { Graphics2D } from \"@/render/graphics2d\";\nimport { Clip } from \"@/render/clip\";\nimport { type Command, type CommandArgs } from \"@/tween/command\";\nimport { command } from \"@/tween/command-decorator\";\nimport { lerpLookAt, type LookAt, type SpaceCamera } from \"@/attributes/layout/space3d\";\nimport { NO_PROJECTION_3D, type Projection3D } from \"@/attributes/layout/matrix2d\";\nimport { Alignment } from \"@/attributes/layout/alignment\";\nimport type { FlowMode, FlowProps, FlowSettings, GapSize } from \"@/layout/types\";\nimport { fillOps } from \"@/attributes/shape/fill/registry\";\nimport { FillResolved } from \"@/attributes/shape/fill/union\";\nimport { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport { CameraScope, Node2D, NodeConfig, Node2DProps } from \"@/components/trees/2d/node2d\";\nimport { spaceRootFrame } from \"@/components/trees/2d/node-space\";\nimport type { Node, NodeDimension } from \"@/components/trees/node/node\";\nimport { NodeAudio } from \"@/components/trees/audio/node-audio\";\nimport { declareMembers, property } from \"@/attributes/properties/decorator\";\nimport { alignmentProperty, fillProperty, flowProperty } from \"@/attributes/properties/typed\";\n\n/** @internal */\nexport interface Canvas2DProps extends Node2DProps, FlowProps {\n /**\n * Background fill layer(s). Each item can be a CSS color string, a fill\n * prop object, an already-resolved fill, or a {@link FillChain} from the\n * `Fills` builder. Painted behind the scene's children.\n */\n fill: Fill;\n /**\n * Overlay layer(s) — same loose values as {@link fill}, but painted *over*\n * the fill **and** the children (clipped to the viewport). Use for textures\n * laid across the whole scene, e.g. a VHS-grain image or video.\n */\n overlay: Fill;\n /** Camera magnification factor. Values > 1 zoom in; < 1 zoom out. */\n zoom: number;\n /**\n * World-space point that maps to the centre of the viewport. In a\n * {@link space3D} it is also what the camera orbits, and `z` puts it in\n * depth — the same sense as a node's `depth`, so a negative `z` flies in.\n */\n lookAt: LookAt;\n /** Rotation of the camera view in degrees (clockwise). */\n heading: number;\n /**\n * Place the children in one 3D space seen through this camera, rather than\n * each projecting through a perspective of its own. Their `depth` and tilt\n * are then positions and turns in that space, and siblings paint far to\n * near. A switch rather than something read off the camera's numbers, so\n * turning it on can never jump a tween.\n *\n * While it is on, `perspective` is the camera's distance from {@link lookAt}\n * at `dolly: 0` — CSS's convention, so that plane draws 1:1 and `0` is a\n * parallel projection — and the stage's own tilt and depth are unused.\n */\n space3D: boolean;\n /** Degrees about the vertical axis through {@link lookAt}. 0 is head-on; positive moves the camera to the right. Same as `Camera3D`. */\n orbit: number;\n /** Degrees above the layers. Positive looks down on them. Same as `Camera3D`. */\n elevation: number;\n /** Px the camera has moved in toward {@link lookAt}. Inert with no perspective, as depth is. */\n dolly: number;\n}\n\n/**\n * The single root container every clip document builds into.\n *\n * A `Canvas2D` is a plain {@link Node2D} that doubles as the clip's layout frame\n * and camera. It lays its children out (flex `horizontal`/`vertical` or\n * `freeform`, with `gap`, `align`, `padding`) and paints a scene-wide background\n * (`fill`) and `overlay` — *and* views those laid-out children through a viewport\n * transform (`zoom`, `lookAt`, `heading`).\n *\n * Unlike a {@link Rect} it is **not a shape**: it has no stroke, shadow, corner,\n * or `start`/`end` props. It carries only the scene-wide concerns — background\n * paint, child layout, and camera — so `stage.fill`, `stage.flow`, etc. read\n * the root directly without exposing per-shape geometry the scene root never has.\n *\n * Its layout props are the arrangement {@link Node2D} lays its children out by,\n * the same as a {@link Rect}'s — see {@link flowArrangement}.\n */\n/** @internal */\nexport class Canvas2D extends Node2D<Canvas2DProps> {\n\n // ---- Background paint -------------------------------------------------\n // Author-facing paint props. Like Rect, the declared type is the loose\n // `Fill` so assignment (`this.fill = 'red'`) and reads share one type; the\n // property accessor stores the *resolved* value via the mapper.\n declare fill: Fill;\n declare overlay: Fill;\n\n // ---- Layout container -------------------------------------------------\n declare flow: FlowMode;\n declare readonly gap: GapSize;\n declare readonly wrap: boolean;\n // `undefined` means \"follow `gap`\", not \"missing\" — see FlowProps.crossGap.\n declare readonly crossGap: number | undefined;\n declare readonly columns: number;\n // Declared loose as `Alignment` (covers `this.align = 'center'`); the\n // accessor stores the resolved per-axis `Vector2` pivot. See Rect.\n declare align: Alignment;\n\n // ---- Camera -----------------------------------------------------------\n /** Camera magnification factor (default: 1). */\n declare zoom: number;\n /** World-space focus point (default: {x:0, y:0}). */\n declare lookAt: LookAt;\n /** Camera view rotation in degrees (default: 0). */\n declare heading: number;\n declare space3D: boolean;\n declare orbit: number;\n declare elevation: number;\n declare dolly: number;\n\n constructor(props: NodeConfig<Canvas2D, Canvas2DProps>) {\n super(props);\n }\n\n // ---- Camera motion commands -------------------------------------------\n // Mirror the Camera node's viewport commands.\n\n /** Animate `zoom`. Values > 1 zoom in; < 1 zoom out. */\n zoomTo(args: CommandArgs<{ zoom: number }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n /** Pan — animate `lookAt`, the world-space point mapped to the viewport center. `z` moves it in depth. */\n panTo(args: CommandArgs<{ lookAt: LookAt }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n /**\n * Swing the camera round {@link lookAt}. The argument names are the ones the\n * 3D components' `orbitTo` takes, less `zoom`: here that is the lens, not a\n * distance, and it has a command of its own.\n */\n orbitTo(args: CommandArgs<{ orbit?: number; elevation?: number }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n /** Move the camera in toward {@link lookAt} (positive) or back out. */\n dollyTo(args: CommandArgs<{ dolly: number }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n /** Animate the view rotation (`heading`), in degrees clockwise. */\n headingTo(args: CommandArgs<{ heading: number }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n fillTo(args: CommandArgs<Fill, FillResolved[]> & { duration: number }): Command<Canvas2DProps> {\n const from = this.fill as FillResolved[];\n const target = fillOps.resolve(args.data as Fill);\n const lerp = args.lerp ?? fillOps.lerp;\n return this.command<Canvas2DProps>(t => ({ fill: lerp(from, target, t) }) as Partial<Canvas2DProps>, args.duration, args.easing);\n }\n\n overlayTo(args: CommandArgs<Fill, FillResolved[]> & { duration: number }): Command<Canvas2DProps> {\n const from = this.overlay as FillResolved[];\n const target = fillOps.resolve(args.data as Fill);\n const lerp = args.lerp ?? fillOps.lerp;\n return this.command<Canvas2DProps>(t => ({ overlay: lerp(from, target, t) }) as Partial<Canvas2DProps>, args.duration, args.easing);\n }\n\n // ---- Layout -----------------------------------------------------------\n\n protected override flowArrangement(): FlowSettings {\n return this;\n }\n\n // ---- Drawing ----------------------------------------------------------\n\n // The viewport-sized background box behind the children.\n private shapeGraphics(): Graphics2D {\n return new Graphics2D().rect({\n width: this.layoutBounds.width,\n height: this.layoutBounds.height,\n });\n }\n\n protected override renderSelf(draw: RenderContext2D): void {\n const fill = this.fill as FillResolved[];\n if (fill.length === 0) return;\n draw.draw(this.shapeGraphics().fill(fill));\n }\n\n // Overlay over fill + children, clipped to the viewport silhouette.\n protected override renderOverlay(ctx: RenderContext2D): void {\n const overlay = this.overlay as FillResolved[];\n if (overlay.length === 0) return;\n ctx.draw(this.shapeGraphics().fill(overlay));\n }\n\n /**\n * Accept audio children as well as 2D ones.\n *\n * The scene root is where the two trees meet, mirroring `Canvas3D` — and for\n * the same reason it is *this* node: a composition already carries both\n * halves of a clip, so a voiceover belongs in the document that shows the\n * picture it is narrating rather than in a second document beside it.\n *\n * Nothing partitions them by hand. `Node2D.children` already filters to its\n * own kind, so layout and render skip the audio subtree for free, and the\n * audio declaration walk reads the unfiltered list.\n */\n protected override acceptsChild(child: Node): boolean {\n return child.dimension === \"2d\" || child.dimension === \"audio\";\n }\n\n override get _childTrees(): readonly NodeDimension[] {\n return [\"2d\", \"audio\"];\n }\n\n /** This node's children in the audio tree. */\n get childrenAudio(): NodeAudio[] {\n return this._allChildren.filter((c): c is NodeAudio => c instanceof NodeAudio);\n }\n\n // The world container, not a shape, so it declares its own `fill`/`overlay`.\n override declareAssets(assets: AssetScope): void {\n super.declareAssets(assets);\n assets.fill(this.fill as FillResolved[]);\n assets.fill(this.overlay as FillResolved[]);\n }\n\n // The viewport outline — used for `clip` and as the area backdrop effects\n // are confined to.\n protected override clipSelf(): Clip {\n return new Clip().rect({\n width: this.layoutBounds.width,\n height: this.layoutBounds.height,\n });\n }\n\n // ---- Rendering --------------------------------------------------------\n\n // Children are laid out by the flow engine; here we view that laid-out\n // world through the camera viewport transform, the same way the Camera node\n // does. When the camera is at rest (zoom 1, no heading, origin at 0) this is\n // the identity, so a plain layout root pays nothing extra.\n // Non-null exactly when renderChildren below opens a camera, so a consumer\n // reproducing the render transform (node picking) inserts the same scope in\n // the same place — and skips it on the at-rest fast path, where the renderer\n // pushes nothing at all.\n override _cameraScope(): CameraScope | null {\n if (this.space3D) return null;\n if (this.zoom === 1 && this.heading === 0 && this.lookAt.x === 0 && this.lookAt.y === 0) return null;\n return { lookAt: this.lookAt, zoom: this.zoom, heading: this.heading };\n }\n\n override _spaceCamera(): SpaceCamera | null {\n if (!this.space3D) return null;\n const rect = this.layoutBounds;\n return {\n perspective: this.perspective,\n orbit: this.orbit,\n elevation: this.elevation,\n dolly: this.dolly,\n lookAt: this.lookAt,\n zoom: this.zoom,\n heading: this.heading,\n viewportX: rect?.x ?? 0,\n viewportY: -(rect?.y ?? 0),\n };\n }\n\n // In a space the stage's own tilt and depth would turn the whole scene as\n // one flat card; its `perspective` is the camera's instead.\n protected override _projection(): Projection3D {\n return this.space3D ? NO_PROJECTION_3D : super._projection();\n }\n\n protected override renderChildren(ctx: RenderPass2D): void {\n const camera = this._spaceCamera();\n if (camera) {\n this._renderInSpace(ctx, spaceRootFrame(this, camera));\n return;\n }\n if (this.zoom === 1 && this.heading === 0 && this.lookAt.x === 0 && this.lookAt.y === 0) {\n super.renderChildren(ctx);\n return;\n }\n\n const rect = this.layoutBounds;\n const w = rect?.width ?? 0;\n const h = rect?.height ?? 0;\n const cx = rect?.x ?? 0;\n const cy = rect?.y ?? 0;\n\n ctx.beginCamera(\n { x: cx, y: -cy, width: w, height: h },\n this.lookAt,\n this.zoom,\n this.heading,\n );\n\n for (const child of this._children) if (child instanceof Node2D) child.render(ctx);\n\n ctx.endCamera();\n }\n}\n\ndeclareMembers(Canvas2D, {\n fill: fillProperty(),\n overlay: fillProperty(),\n flow: flowProperty(),\n gap: property({ default: 0 }),\n wrap: property({ default: false }),\n crossGap: property({ default: undefined }),\n columns: property({ default: 1 }),\n align: alignmentProperty(),\n zoom: property({ default: 1 }),\n lookAt: property({ default: { x: 0, y: 0 }, tween: lerpLookAt }),\n heading: property({ default: 0 }),\n space3D: property({ default: false }),\n orbit: property({ default: 0 }),\n elevation: property({ default: 0 }),\n dolly: property({ default: 0 }),\n\n zoomTo: command({ args: [{ key: \"zoom\", kind: \"number\", min: 0.01, step: 0.1, unit: \"×\" }] }),\n panTo: command({ args: [{ key: \"lookAt\", kind: \"vector2\", properties: { x: { kind: \"number\" }, y: { kind: \"number\" }, z: { kind: \"number\" } } }] }),\n orbitTo: command({ args: [{ key: \"orbit\", kind: \"number\", step: 1, unit: \"°\" }, { key: \"elevation\", kind: \"number\", step: 1, unit: \"°\" }] }),\n dollyTo: command({ args: [{ key: \"dolly\", kind: \"number\", step: 10 }] }),\n headingTo: command({ args: [{ key: \"heading\", kind: \"number\", step: 1, unit: \"°\" }] }),\n fillTo: command(),\n overlayTo: command(),\n});\n", "import { lerpCornerScalarStyle, type CornerStyle, type RectCornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport { pathOps } from \"@/attributes/shape/path/ops\";\nimport { STAR_DEFAULT_POINTS, STAR_DEFAULT_RATIO, type ShapeOutlineKind } from \"@/components/builtins/geometry/shape-outline\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport * as Shapes from \"@/components/modules/shapes\";\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\nimport type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Stroke } from \"@/attributes/shape/stroke/stroke\";\nimport type { Shadow } from \"@/attributes/shape/shadow/shadow\";\nimport type { FlowProps } from \"@/layout/types\";\nimport type { RectCornerRadius } from \"@/attributes/shape/corners/corner-radius\";\nimport type { PathData } from \"@/render/descriptors/path\";\n\n/**\n * The geometry built-ins: paint, the flow engine for children (clear of the\n * stroke), and each one's outline.\n */\n\nconst scalarCorners = {\n cornerRadius: Types.number(0),\n cornerStyle: Types.custom<CornerStyle>(\"rounded\", { lerp: lerpCornerScalarStyle }),\n};\n\nexport const Rect = component2d({\n key: \"rect\",\n state: { ...Paint.state, ...Flow.state, ...Corners.state },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Corners.rect(ctx.size, state)),\n});\n\nexport const Ellipse = component2d({\n key: \"ellipse\",\n state: {\n ...Paint.state, ...Flow.state,\n startAngle: Types.number(0),\n sweep: Types.number(360),\n ratio: Types.number(0),\n },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.ellipse(ctx.size, state)),\n});\n\nexport const Polygon = component2d({\n key: \"polygon\",\n state: { ...Paint.state, ...Flow.state, sides: Types.number(5), ...scalarCorners },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.polygon(ctx.size, state)),\n});\n\nexport const Polygram = component2d({\n key: \"polygram\",\n state: { ...Paint.state, ...Flow.state, sides: Types.number(5), ratio: Types.number(0.5), ...scalarCorners },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.polygram(ctx.size, state)),\n});\n\n/** The document's `path`: `data` in the unit space of its own box, so a resize is a width/height write. */\nexport const PathShape = component2d({\n key: \"path\",\n state: { ...Paint.state, ...Flow.state, data: Types.path },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.unitPath(ctx.size, state.data), { clipShape: Shapes.box(ctx.size) }),\n});\n\n/** Path data drawn at face value, hugging it: geometry written in code. */\nexport const Path = component2d({\n key: \"facePath\",\n state: { ...Paint.state, ...Flow.state, data: Types.path },\n defaults: { width: \"hug\", height: \"hug\" },\n commands: { ...Paint.commands },\n measure: (_measurer, state) => {\n const intrinsic = pathOps.size(state.data);\n const pad = state.padding;\n return { width: intrinsic.width + pad.left + pad.right, height: intrinsic.height + pad.top + pad.bottom };\n },\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.facePath(state.data), { clipShape: null }),\n});\n\nfunction boundsShape<const K extends string>(key: K, kind: ShapeOutlineKind) {\n return component2d({\n key,\n state: { ...Paint.state, ...Flow.state, ...scalarCorners },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.outline(kind, ctx.size, state), { clipShape: Shapes.box(ctx.size) }),\n });\n}\n\nexport const Triangle = boundsShape(\"triangle\", \"triangle\");\nexport const RightTriangle = boundsShape(\"rightTriangle\", \"rightTriangle\");\nexport const Pentagon = boundsShape(\"pentagon\", \"pentagon\");\nexport const Hexagon = boundsShape(\"hexagon\", \"hexagon\");\nexport const Octagon = boundsShape(\"octagon\", \"octagon\");\n\nexport const Star = component2d({\n key: \"star\",\n state: {\n ...Paint.state, ...Flow.state, ...scalarCorners,\n points: Types.number(STAR_DEFAULT_POINTS),\n ratio: Types.number(STAR_DEFAULT_RATIO),\n },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.outline(\"star\", ctx.size, {\n cornerRadius: state.cornerRadius, cornerStyle: state.cornerStyle, sides: Math.max(3, Math.round(state.points)), ratio: state.ratio,\n }), { clipShape: Shapes.box(ctx.size) }),\n});\n\nexport type Rect = NodeOf<typeof Rect>;\nexport type Ellipse = NodeOf<typeof Ellipse>;\nexport type Polygon = NodeOf<typeof Polygon>;\nexport type Polygram = NodeOf<typeof Polygram>;\nexport type PathShape = NodeOf<typeof PathShape>;\nexport type Path = NodeOf<typeof Path>;\nexport type Triangle = NodeOf<typeof Triangle>;\nexport type RightTriangle = NodeOf<typeof RightTriangle>;\nexport type Pentagon = NodeOf<typeof Pentagon>;\nexport type Hexagon = NodeOf<typeof Hexagon>;\nexport type Octagon = NodeOf<typeof Octagon>;\nexport type Star = NodeOf<typeof Star>;\n\n// What code building a shape names its props as. A call's own type is `CallProps<typeof Rect>`.\n\nexport interface PaintProps extends Node2DProps {\n /**\n * Fill layer(s). Each item can be:\n * - A plain CSS color string → treated as a solid fill\n * - A fill prop object (SolidFillProp, LinearGradientFillProp, …)\n * - An already-resolved fill object\n * - A {@link FillChain} from the `Fills` builder (e.g. `Fills.color('red')`)\n */\n fill?: Fill;\n /**\n * Stroke layer(s): a single {@link StrokeProp}, an array of them, or an\n * already-resolved stroke. `fill` inside each stroke accepts the same loose\n * values as the top-level fill prop.\n */\n stroke?: Stroke;\n /**\n * Shadow layer(s): a single {@link ShadowProp}, an array of them, or an\n * already-resolved shadow. `fill` inside each shadow accepts the same loose\n * values as the top-level fill prop.\n */\n shadow?: Shadow;\n start?: number;\n end?: number;\n}\n\nexport interface ShapeProps extends PaintProps, FlowProps {\n /**\n * Overlay layer(s) — the same loose values as {@link PaintProps.fill}, but\n * painted *over* this node's fill **and** its children (clipped to the node's\n * silhouette) while still sitting **under** the stroke. Use for textures\n * laid across the whole subtree, e.g. a VHS-grain image or video.\n */\n overlay?: Fill;\n}\n\nexport type FlexSize = number | \"fill\" | \"hug\";\n\nexport interface RectProps extends ShapeProps {\n /** Corner radius in pixels — uniform, per-corner, or per-axis. */\n cornerRadius: RectCornerRadius;\n /** How each corner is shaped once it has a radius: `'rounded'` or `'angled'`. */\n cornerStyle: RectCornerStyle;\n}\n\nexport interface EllipseProps extends ShapeProps {\n ratio: number;\n sweep: number;\n startAngle: number;\n}\n\nexport interface PolygonProps extends ShapeProps {\n /** Number of sides. Must be ≥ 3. */\n sides: number;\n /** Vertex rounding radius in pixels. */\n cornerRadius: number;\n /** Vertex shape: `'rounded'` (circular arc) or `'angled'` (chamfer). */\n cornerStyle: CornerStyle;\n}\n\nexport interface PolygramProps extends ShapeProps {\n /** Number of outer points. Must be ≥ 3. */\n sides: number;\n /**\n * Inner-to-outer radius ratio (0–1). Controls how deeply the star points are cut.\n * At 1 the shape degenerates into a regular polygon; lower values produce sharper points.\n */\n ratio: number;\n /** Vertex rounding radius in pixels applied to both inner and outer vertices. */\n cornerRadius: number;\n /** Vertex shape: `'rounded'` (circular arc) or `'angled'` (chamfer). */\n cornerStyle: CornerStyle;\n}\n\nexport interface PathShapeProps extends ShapeProps {\n /**\n * The geometry, as an SVG `d` string in the node's **unit box** — see\n * {@link PathData}.\n */\n data: PathData\n}\n\nexport interface PathProps extends ShapeProps {\n data: PathData;\n}\n\n/**\n * The named shapes — a triangle, a right triangle, a pentagon, a hexagon, an\n * octagon, a star — as engine nodes.\n *\n * ## Why they aren't just a Polygon with `sides` set\n *\n * A `Polygon` inscribes its n-gon in the node's box, so a three-sided one leaves\n * a visible gap under its base (see `./shape-outline` for the full reason,\n * which is a good one: it's what makes a `sides` tween smooth). These fill the\n * box instead. The two behaviours can't be one node with a switch, because\n * \"which shape is this\" is the sort of thing a scene's author picks once and a\n * reader of the layers panel needs to see at a glance — so each is a type of its\n * own, named for what it draws.\n *\n * ## Why they're paths rather than polygons\n *\n * The silhouette is handed to the renderer as a `path` op rather than a\n * `polygon` one, which is what lets corner rounding be *ours*: the engine's\n * polygon geometry rounds the inscribed figure, and rounding a stretched one is\n * a different arc at every vertex. Drawing the outline ourselves also means the\n * shape a user is looking at and the shape they get when they start editing its\n * points are built by the same function, so converting to a Path node changes\n * nothing on screen.\n *\n * The outline is rebuilt per draw rather than cached against the box. It is a\n * handful of trig per vertex on a shape with at most ten of them, and the\n * alternative — a cache keyed on width, height, radius, style and the two\n * parametric fields — costs more to keep honest than it saves.\n */\nexport interface BoundsShapeProps extends ShapeProps {\n /** Vertex rounding radius in pixels. */\n cornerRadius: number\n /** Vertex shape: `'rounded'` (circular arc) or `'angled'` (chamfer). */\n cornerStyle: CornerStyle\n}\n\nexport interface StarProps extends BoundsShapeProps {\n /** How many points the star has. */\n points: number\n /** Inner radius as a fraction of the outer one — how deep the points cut. */\n ratio: number\n}\n", "import type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport type { BooleanOperation } from \"@/attributes/mask/boolean\";\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\nimport type { ShapeProps } from \"@/components/builtins/geometry/geometry\";\nimport type { MaskMode } from \"@/attributes/mask/mask\";\n\n/**\n * The compositing built-ins: children drawn as one. `op`, `mode` and\n * `inverted` are entries, where the classes kept them in unlisted slots, so a\n * host lists them and a command can switch them.\n */\n\n/** Its children become one shape by `op`, painted with its own fill, stroke and shadow. */\nexport const BooleanGroup = component2d({\n key: \"boolean\",\n state: { ...Paint.state, ...Flow.state, op: Types.oneOf([\"union\", \"subtract\", \"intersect\", \"exclude\"]) },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => ctx.merge(state.op, state),\n});\n\n/** Its first child is the stencil the rest draw through. */\nexport const MaskGroup = component2d({\n key: \"mask\",\n state: { mode: Types.oneOf([\"alpha\", \"vector\", \"luminance\"]), inverted: false },\n render: (ctx, state) => ctx.mask(state),\n});\n\nexport type BooleanGroup = NodeOf<typeof BooleanGroup>;\nexport type MaskGroup = NodeOf<typeof MaskGroup>;\n\n// What code building a boolean or a mask names its props as.\n\nexport interface BooleanGroupProps extends ShapeProps {\n op: BooleanOperation;\n}\n\nexport interface MaskGroupProps extends Node2DProps {\n // How the mask shape determines content visibility:\n // \"alpha\" — mask alpha drives content alpha (default; matches Figma)\n // \"vector\" — fast hard clip using the mask's outline only\n // \"luminance\" — mask brightness drives content alpha\n mode: MaskMode;\n // When true, content shows where the mask is *not* (Figma's \"subtract\" mask).\n inverted: boolean;\n}\n", "import { lerpLookAt, type LookAt } from \"@/attributes/layout/space3d\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { commandsFor } from \"@/components/factory/commands-for\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Aim from \"@/components/modules/aim\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { RectCornerRadius } from \"@/attributes/shape/corners/corner-radius\";\nimport type { RectCornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport type { ShapeProps } from \"@/components/builtins/geometry/geometry\";\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\n\n/** A framed viewport: painted like a rect, its children seen through a camera aimed inside it. */\nexport const Camera = component2d({\n key: \"camera\",\n state: { ...Paint.state, ...Flow.state, ...Aim.state, ...Corners.state },\n commands: { ...Paint.commands, ...Aim.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Corners.rect(ctx.size, state), { children: () => Aim.camera(ctx, state) }),\n});\n\nconst orbit = {\n lookAt: Types.custom<LookAt>({ x: 0, y: 0 }, {\n lerp: lerpLookAt, kind: \"vector2\", properties: { x: { kind: \"number\" }, y: { kind: \"number\" }, z: { kind: \"number\" } },\n }),\n zoom: Types.number(1, { min: 0.01, step: 0.1, unit: \"×\" }),\n heading: Types.number(0, { step: 1, unit: \"°\" }),\n orbit: Types.number(0, { step: 1, unit: \"°\" }),\n elevation: Types.number(0, { step: 1, unit: \"°\" }),\n dolly: Types.number(0, { step: 10 }),\n orbitSpeed: Types.number(0),\n};\n\n/** The stage's 2.5D camera for one subtree: its children stand in one space, orbited in depth. */\nexport const OrbitCamera = component2d({\n key: \"orbitCamera\",\n state: orbit,\n defaults: { width: \"hug\", height: \"hug\", perspective: 1000 },\n commands: commandsFor(orbit, {\n orbitTo: { args: [\"orbit\", \"elevation\"] },\n dollyTo: { args: [\"dolly\"] },\n zoomTo: { args: [\"zoom\"] },\n panTo: { args: [\"lookAt\"] },\n headingTo: { args: [\"heading\"] },\n }),\n render: (ctx, state) => ctx.space({\n perspective: state.perspective,\n orbit: state.orbit + state.orbitSpeed * ctx.time.total,\n elevation: state.elevation,\n dolly: state.dolly,\n lookAt: state.lookAt,\n zoom: state.zoom,\n heading: state.heading,\n viewportX: 0,\n viewportY: 0,\n }),\n});\n\n/** Its children laid out in a box turned by `angle`, and turned with it: the box it reports is the turned one's bounds. */\nexport const RotatedBox = component2d({\n key: \"rotated-box\",\n state: { angle: Types.number(-90) },\n defaults: { rotation: (state) => state.angle },\n measure: (measurer, state, children) => {\n const { cos, sin } = turn(state.angle);\n const { width: w, height: h } = measurer.max;\n const ortho = Math.abs(state.angle % 180) === 90;\n const room = w !== undefined && h !== undefined\n ? { width: w * cos + h * sin, height: w * sin + h * cos }\n : { width: ortho ? h : w, height: ortho ? w : h };\n let width = 0;\n let height = 0;\n for (const child of children) {\n const size = child.measure(room);\n width = Math.max(width, size.width);\n height = Math.max(height, size.height);\n }\n return { width: width * cos + height * sin, height: width * sin + height * cos };\n },\n layout: (box, state, children) => {\n const { cos, sin } = turn(state.angle);\n const turned = { x: 0, y: 0, width: box.width * cos + box.height * sin, height: box.width * sin + box.height * cos };\n return Flow.layout(turned, state as unknown as Flow.FlowState, children);\n },\n});\n\nfunction turn(angle: number): { cos: number; sin: number } {\n const rad = angle * (Math.PI / 180);\n return { cos: Math.abs(Math.cos(rad)), sin: Math.abs(Math.sin(rad)) };\n}\n\nexport type Camera = NodeOf<typeof Camera>;\nexport type OrbitCamera = NodeOf<typeof OrbitCamera>;\nexport type RotatedBox = NodeOf<typeof RotatedBox>;\n\n// What code building a camera or a rotated box names its props as.\n\nexport interface CameraProps extends ShapeProps {\n /** Magnification factor. Values > 1 zoom in; < 1 zoom out. */\n zoom: number;\n /**\n * World-space point that maps to the centre of the camera viewport — what\n * the camera is pointed at. Same name and meaning as\n * `Graphics3D.perspective({ lookAt })`, so a 2D and a 3D camera are aimed\n * with the same word.\n */\n lookAt: Vector2;\n /** Rotation of the camera view in degrees (clockwise). */\n heading: number;\n /**\n * A node of the camera's world to keep in view, by id: the camera is aimed\n * at its centre each frame, and {@link lookAt} becomes an offset from it.\n */\n follow: string;\n /** Corner radius in pixels — uniform, per-corner, or per-axis. */\n cornerRadius: RectCornerRadius;\n /** How each corner is shaped once it has a radius: `'rounded'` or `'angled'`. */\n cornerStyle: RectCornerStyle;\n}\n\nexport interface OrbitCameraProps extends Node2DProps {\n /** The point the camera orbits and looks at; `z` puts it in depth, as a node's `depth` does. */\n lookAt: LookAt;\n /** Lens zoom, applied after the projection. Values > 1 zoom in. */\n zoom: number;\n /** Roll of the view in degrees, clockwise. */\n heading: number;\n /** Degrees about the vertical axis through {@link lookAt}. 0 is head-on; positive moves the camera right. */\n orbit: number;\n /** Degrees above the layers. Positive looks down on them. */\n elevation: number;\n /** Px the camera has moved in toward {@link lookAt}. Inert with no perspective. */\n dolly: number;\n /** Degrees per second the camera orbits on its own — a turntable. */\n orbitSpeed: number;\n}\n\n// Adjust this import path if needed\n\nexport interface RotatedBoxProps extends Node2DProps {\n /** \n * Visual rotation angle in degrees. Unlike standard `rotation`, \n * animating this ALSO dynamically calculates a new bounding box \n * for the flex/layout engine. \n */\n angle: number;\n}\n", "import { fillOps } from \"@/attributes/shape/fill/registry\";\nimport { strokeOps } from \"@/attributes/shape/stroke/stroke\";\nimport type { ResolvedTextRun, TextRun, TextSpan, FontStyle, TextAlign, TextCase, TextDecoration, VerticalAlign } from \"@/attributes/text/types\";\nimport { formatNumber } from \"@/components/builtins/text/number-format\";\nimport { numberNodePattern } from \"@/components/builtins/text/number-pattern\";\nimport type { PathData } from \"@/render/descriptors/path\";\nimport { PathBuilder } from \"@/render/descriptors/path-builder\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Paint from \"@/components/modules/paint\";\nimport * as TextLayout from \"@/components/modules/text-layout\";\nimport * as TextStyle from \"@/components/modules/text-style\";\n\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\nimport type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Stroke } from \"@/attributes/shape/stroke/stroke\";\nimport type { PaintProps } from \"@/components/builtins/geometry/geometry\";\nimport type { Shadow } from \"@/attributes/shape/shadow/shadow\";\n\n/**\n * The text built-ins. A glyph node paints like a shape, but has no outline to\n * lay an overlay over, so it takes Paint without one; its face comes from\n * TextStyle, which inherits what the author left unset.\n */\n\nconst { overlay: _overlay, ...glyphPaint } = Paint.state;\nconst { overlayTo: _overlayTo, ...glyphCommands } = Paint.commands;\n\n/** Glyphs hug themselves; `'autofit'` fills the box it fits to. */\nconst autofits = (state: { readonly fontSize: number | \"autofit\" }) => (state.fontSize === \"autofit\" ? \"fill\" : \"hug\");\n\nconst NO_RUNS: readonly never[] = [];\n\nfunction resolvePath(value: PathData | PathBuilder | null | undefined): PathData | null {\n if (value == null) return null;\n return value instanceof PathBuilder ? value.toCommands() : value;\n}\n\nfunction resolveRuns(value: TextRun[] | null | undefined): ResolvedTextRun[] {\n if (!Array.isArray(value)) return [];\n return value.map(({ fill, stroke, ...run }) => ({\n ...run,\n ...(fill === undefined ? {} : { fill: fillOps.resolve(fill) }),\n ...(stroke === undefined ? {} : { stroke: strokeOps.resolve(stroke) }),\n }));\n}\n\nconst textState = {\n ...glyphPaint,\n ...TextStyle.state,\n text: Types.text(\"\", { typing: true }),\n wrap: false,\n path: Types.custom<PathData | PathBuilder | null, PathData | null>(null, { resolve: resolvePath }),\n runs: Types.custom<TextRun[], ResolvedTextRun[]>([], { resolve: resolveRuns, animatable: false }),\n};\n\nconst textSource = (state: { readonly text: string; readonly wrap: boolean; readonly path: PathData | null; readonly runs: ResolvedTextRun[] }) =>\n ({ text: state.text, wraps: state.wrap, glyphPath: state.path, runs: state.runs });\n\n/** Copy somebody typed: wraps when asked, rides a path, styles stretches of itself. */\nexport const Text = component2d({\n key: \"text\",\n allowedChildren: [],\n state: textState,\n defaults: {\n width: (state) => (state.fontSize === \"autofit\" || state.wrap ? \"fill\" : \"hug\"),\n height: autofits,\n },\n commands: {\n ...glyphCommands,\n append: {\n args: { text: Types.text(\"\", { multiline: true }) },\n run: (timeline, state) => timeline.tween({ text: state.text + timeline.args.text }),\n },\n prepend: {\n args: { text: Types.text(\"\", { multiline: true }) },\n run: (timeline, state) => timeline.tween({ text: timeline.args.text + state.text }),\n },\n },\n load: (loader, state) => TextLayout.load(loader, state, textSource(state)),\n measure: (measurer, state) => TextLayout.measure(measurer, state, textSource(state)),\n render: (ctx, state) => TextLayout.draw(ctx, state, textSource(state)),\n});\n\nconst numberState = {\n ...glyphPaint,\n ...TextStyle.state,\n value: 0,\n format: Types.custom<NumberFormat>(\"number\"),\n customPattern: \"\",\n fractionDigits: 0,\n grouped: true,\n currencySymbol: \"$\",\n};\n\nconst numberSource = (state: Parameters<typeof numberNodePattern>[0] & { readonly value: number }) =>\n ({ text: formatNumber(state.value, numberNodePattern(state)), wraps: false, glyphPath: null, runs: NO_RUNS });\n\n/** A figure, formatted from its value: a quantity, not copy. */\nexport const NumberNode = component2d({\n key: \"number\",\n allowedChildren: [],\n state: numberState,\n defaults: { width: autofits, height: autofits },\n commands: { ...glyphCommands, countTo: { args: [\"value\"] } },\n load: (loader, state) => TextLayout.load(loader, state, numberSource(state)),\n measure: (measurer, state) => TextLayout.measure(measurer, state, numberSource(state)),\n render: (ctx, state) => TextLayout.draw(ctx, state, numberSource(state)),\n});\n\nconst { verticalAlign: _v, textDecoration: _d, textCase: _c, minFontSize: _m, ...richStyle } = TextStyle.state;\n\n/** Spans of text, each styled on its own, set on lines that break only where they say. */\nexport const RichText = component2d({\n key: \"richtext\",\n allowedChildren: [],\n state: {\n ...glyphPaint,\n ...richStyle,\n fontSize: Types.number(48, { inherit: TextStyle.inherit(\"fontSize\", { autofit: false }) }),\n spans: Types.custom<TextSpan | TextSpan[], TextSpan[]>([], {\n resolve: (v) => (v == null ? [] : Array.isArray(v) ? v : [v]),\n }),\n },\n defaults: { width: \"hug\", height: \"hug\" },\n commands: { ...glyphCommands },\n load: (loader, state) => TextLayout.loadRichText(loader, state),\n measure: (measurer, state) => TextLayout.measureRichText(measurer, state),\n render: (ctx, state) => TextLayout.drawRichText(ctx, state),\n});\n\n/** The face text below it is set in, field by field, over whatever is inherited from above. */\nexport const DefaultTextStyle = component2d({\n key: \"default-text-style\",\n state: TextStyle.provided,\n provide: (state, inherited) => TextStyle.provide(state, inherited),\n render: (ctx, state) => ctx.textStyle(TextStyle.current(state), () => ctx.children()),\n});\n\nexport type Text = NodeOf<typeof Text>;\nexport type NumberNode = NodeOf<typeof NumberNode>;\nexport type RichText = NodeOf<typeof RichText>;\nexport type DefaultTextStyle = NodeOf<typeof DefaultTextStyle>;\n\n// What code building a text node names its props as.\n\n/** The fields a string is shaped and set by, shared by every node that draws glyphs. */\nexport interface TextBaseProps extends PaintProps {\n fontSize: number | 'autofit';\n fontFamily: string;\n fontWeight: number;\n fontStyle: FontStyle;\n letterSpacing: number;\n lineHeight: number;\n textAlign: TextAlign;\n verticalAlign: VerticalAlign;\n textDecoration: TextDecoration;\n textCase: TextCase;\n minFontSize: number;\n /**\n * Name of a typography preset from `theme.typography` (e.g. `\"header\"`).\n * Supplies any text-style prop (fontSize, fontWeight, …) not set explicitly\n * here. An explicit prop always wins over the preset; the preset wins over an\n * inherited `<DefaultTextStyle>`.\n */\n variant: string;\n}\n\nexport interface TextProps extends TextBaseProps {\n text: string;\n /** Wrap onto more lines once the text runs out of width. */\n wrap: boolean;\n /**\n * Wrap the text around a path (text-on-path). Accepts the same value shapes\n * as the {@link Path} node's `d`: an SVG path string, a `PathCommand[]`, or a\n * {@link PathBuilder}. When set, `wrap` and multi-line (`\\n`) are ignored\n * (single line), and `runs` are not applied.\n */\n path: PathData | PathBuilder;\n /**\n * Stretches of `text` styled apart from the node — see {@link TextRun}.\n * Where two overlap the later one wins; offsets past the end of the string\n * style nothing. Ignored on a `path`.\n */\n runs: TextRun[];\n}\n\n/**\n * How a {@link NumberNode}'s value is written down.\n *\n * `'custom'` hands the pattern over verbatim through\n * {@link NumberProps.customPattern}; the other three compose one from\n * {@link NumberProps.fractionDigits} and {@link NumberProps.grouped}.\n */\nexport type NumberFormat = \"currency\" | \"percent\" | \"number\" | \"custom\";\n\nexport interface NumberProps extends TextBaseProps {\n /** The numeric value to display. Tweenable — `to({ value })` counts. */\n value: number;\n /**\n * How the figure is written:\n * - `'number'` — plain decimal (the default)\n * - `'currency'` — money, prefixed with {@link NumberProps.currencySymbol}\n * - `'percent'` — multiplies by 100 and appends `%` (so `0.42` → `42%`)\n * - `'custom'` — {@link NumberProps.customPattern}, verbatim\n */\n format: NumberFormat;\n /**\n * The pattern, when {@link NumberProps.format} is `'custom'` — the same\n * grammar `formatNumber` takes (`#,##0.00`, `0.0%`, `$#,##0`).\n */\n customPattern: string;\n /**\n * Fixed number of decimal places. Always exactly this many, which is what\n * keeps a counting animation from flickering trailing digits as the value\n * crosses an integer boundary.\n */\n fractionDigits: number;\n /** Group digits in threes — `1,000` rather than `1000`. */\n grouped: boolean;\n /** The symbol a `'currency'` figure is prefixed with. */\n currencySymbol: string;\n}\n\nexport interface RichTextProps extends PaintProps {\n spans: TextSpan | TextSpan[];\n /** Default font family inherited by spans that don't set one. */\n fontFamily: string;\n /** Default font size inherited by spans that don't set one. */\n fontSize: number;\n /** Default font weight inherited by spans that don't set one. */\n fontWeight: number;\n /** Default font style inherited by spans that don't set one. */\n fontStyle: FontStyle;\n /** Default letter spacing inherited by spans that don't set one. */\n letterSpacing: number;\n /** Line height multiplier applied to each run's font size. */\n lineHeight: number;\n textAlign: TextAlign;\n /**\n * Name of a typography preset from `theme.typography` (e.g. `\"body\"`).\n * Supplies any node-level default (fontSize, fontWeight, …) not set\n * explicitly here, which `runs()` then folds into each span. An explicit prop\n * wins over the preset; the preset wins over an inherited `<DefaultTextStyle>`.\n */\n variant: string;\n}\n\nexport interface DefaultTextStyleProps extends Node2DProps {\n fontFamily: string;\n fontSize: number | 'autofit';\n fontWeight: number;\n fontStyle: FontStyle;\n letterSpacing: number;\n lineHeight: number;\n textAlign: TextAlign;\n fill: Fill;\n stroke: Stroke;\n shadow: Shadow;\n}\n", "import { DataToken, SeedToken, ThemeToken } from \"@/runtime/builtin-context\";\nimport type { Context } from \"@/util/context\";\nimport { provides, type NodeOf, type Provided } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\n\n/** Hands its subtree `value` under `context`, or the context's default when it has no value. */\nexport const Provider = component2d({\n key: \"provider\",\n state: { context: Types.custom<Context<unknown> | undefined>(undefined), value: Types.custom<unknown>(undefined) },\n provide: (state) => (state.context ? [provides(state.context, state.value !== undefined ? state.value : state.context.defaultValue)] : []),\n});\n\n/** Lays its theme and data over what it inherits, and seeds the randomness below it. */\nexport const ThemeProvider = component2d({\n key: \"theme-provider\",\n state: {\n theme: Types.custom<Record<string, unknown> | undefined>(undefined),\n data: Types.custom<Record<string, unknown> | undefined>(undefined),\n seed: Types.custom<string | number | undefined>(undefined),\n },\n provide: (state, inherited) => {\n const out: Provided[] = [];\n if (state.theme) out.push(provides(ThemeToken, { ...inherited(ThemeToken), ...state.theme }));\n if (state.data) out.push(provides(DataToken, { ...inherited(DataToken), ...state.data }));\n if (state.seed !== undefined) out.push(provides(SeedToken, state.seed));\n return out;\n },\n});\n\nexport type Provider = NodeOf<typeof Provider>;\nexport type ThemeProvider = NodeOf<typeof ThemeProvider>;\n\n// What code building a provider names its props as.\n\nexport interface ProviderProps<T> extends Node2DProps {\n /** The context token this provider supplies to its descendants. */\n context: Context<T>;\n /** The value to provide. Omitted → the token's default value. */\n value: T;\n}\n\nexport interface ThemeProviderProps extends Node2DProps {\n /** Named values (e.g. colors) merged onto any ancestor theme, read via\n * `node.useContext(ThemeToken)`. */\n theme: Record<string, unknown>;\n /** Arbitrary data merged onto any ancestor data bag, read via\n * `node.useContext(DataToken)`. */\n data: Record<string, unknown>;\n /** A default seed passed down the tree, read via `node.useContext(SeedToken)`. */\n seed: string | number;\n}\n", "import { lerpParam, type Param } from \"@/attributes/audio/ramp\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { componentAudio } from \"@/components/factory/component-audio\";\nimport { Types } from \"@/components/factory/types\";\nimport type { NodeAudioProps } from \"@/components/trees/audio/node-audio\";\n\n/**\n * The audio built-ins. A sound plays when a command says so: its `play` runs\n * for the command's span, or to the source's end when the command has no length.\n * A document's `sound` row with no `play` of its own gets one over its span.\n */\n\n/** A clip from the catalog, playing into the buses it sits in. */\nexport const SoundNode = componentAudio({\n key: \"sound\",\n state: {\n src: Types.custom<string>(undefined as unknown as string),\n trimStart: 0,\n trimEnd: Types.custom<number | undefined>(undefined),\n loop: false,\n speed: Types.custom<Param>(1, { lerp: lerpParam, kind: \"audioParam\" }),\n },\n allowedChildren: [],\n commands: {\n play: (timeline, state) => timeline.sound(state.src, {\n trimStart: state.trimStart,\n trimEnd: state.trimEnd,\n loop: state.loop,\n volume: state.volume,\n speed: state.speed,\n effects: state.effects,\n transitionIn: state.transitionIn,\n transitionOut: state.transitionOut,\n }),\n },\n});\n\n/** A mix of the sounds and buses in it; `solo` silences its siblings. */\nexport const AudioBus = componentAudio({\n key: \"audioBus\",\n state: { solo: false },\n});\n\nexport type SoundNode = NodeOf<typeof SoundNode>;\nexport type AudioBus = NodeOf<typeof AudioBus>;\n\n// What code building a sound or a bus names its props as.\n\nexport interface AudioBusProps extends NodeAudioProps {\n /** Silence every other bus that is not itself soloed. */\n solo: boolean;\n}\n\nexport interface SoundNodeProps extends NodeAudioProps {\n /** Path/URL of the audio (or video) asset. Must exist in the asset manifest. */\n src: string;\n /** In-point inside the source file, in seconds. Defaults to 0. */\n trimStart: number;\n /** Out-point inside the source file. Defaults to the source's full length. */\n trimEnd: number | undefined;\n /** Repeat the trimmed clip until it is removed. */\n loop: boolean;\n /**\n * Playback-rate multiplier, pitch included: 2 plays twice as fast and takes\n * half the clip time. A ramp runs over source seconds after `trimStart`.\n */\n speed: Param;\n}\n", "import type { Alignment } from \"@/attributes/layout/alignment\";\nimport type { InsetsResolved } from \"@/attributes/layout/insets\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport { resolveAudioEffects, type AudioEffectsInput } from \"@/attributes/audio/effects/chain\";\nimport type { AudioEffect } from \"@/attributes/audio/effects/union\";\nimport type { ImageFit, ImageMatrix, ImageCrop } from \"@/attributes/shape/fill/implementations/image\";\nimport { sourceTimeFor, type VideoFillProp, type VideoFillResolved } from \"@/attributes/shape/fill/implementations/video\";\nimport { resolveFill, UNSET_MEDIA_FILL } from \"@/attributes/shape/fill/registry\";\nimport type { FillProp } from \"@/attributes/shape/fill/union\";\nimport { resolveChainAdjustments, type VideoAdjustment } from \"@/attributes/shape/filters/chain\";\nimport { lerpFilterArray, type AnyFilter } from \"@/attributes/shape/filters/registry\";\nimport { Graphics2D } from \"@/render/graphics2d\";\nimport type { NodeOf, Values } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport { internalsOf } from \"@/components/factory/views\";\nimport type { RectProps } from \"@/components/builtins/geometry/geometry\";\n\n/**\n * Video: a rect painted with a playing picture under its fill, and the\n * picture's sound. Its sound plays from `play`; a `video` row with no `play`\n * of its own gets one per segment, or one over its span while it plays.\n */\n\nconst video = {\n src: Types.custom<string | undefined>(undefined),\n fit: Types.custom<ImageFit | undefined>(undefined),\n crop: Types.insets,\n zoom: 1,\n anchor: Types.alignment,\n matrix: Types.custom<ImageMatrix | undefined>(undefined),\n filters: Types.custom<VideoAdjustment, AnyFilter[]>([] as never, {\n resolve: (v) => resolveChainAdjustments(v),\n lerp: lerpFilterArray,\n }),\n playing: true,\n timestamp: Types.custom<number | null | undefined>(undefined),\n trimStart: Types.custom<number | undefined>(undefined),\n trimEnd: Types.custom<number | undefined>(undefined),\n speed: Types.custom<number | undefined>(undefined),\n loop: Types.custom<\"forward\" | \"reverse\" | \"none\" | undefined>(undefined),\n duration: Types.custom<number | undefined>(undefined),\n volume: 1,\n muted: false,\n audioEffects: Types.custom<AudioEffectsInput, AudioEffect[]>([] as never, { resolve: (v) => resolveAudioEffects(v) }),\n bus: Types.custom<string | undefined>(undefined),\n segments: Types.custom<readonly VideoSegment[]>([]),\n};\n\ntype VideoState = Values<typeof video> & { readonly crop: InsetsResolved; readonly anchor: Alignment };\n\n/** Source seconds played by `elapsed` clip seconds into the segments, or `null` without any. */\nfunction playedAt(s: VideoState, elapsed: number): number | null {\n if (s.segments.length === 0) return null;\n let played = 0;\n for (const segment of s.segments) {\n if (elapsed <= segment.at) break;\n played += Math.min(elapsed - segment.at, segment.duration) * (segment.speed ?? s.speed ?? 1);\n }\n return played;\n}\n\nfunction scheduledTimestamp(s: VideoState, elapsed: number): number | undefined {\n const played = playedAt(s, elapsed);\n if (played === null) return undefined;\n const start = s.trimStart ?? 0;\n const first = s.segments[0];\n return sourceTimeFor(played + (first ? first.from - start : 0), start, s.trimEnd ?? Infinity, s.loop, s.duration);\n}\n\nconst pictures = new WeakMap<object, { readonly key: string; readonly fill: VideoFillResolved }>();\n\n/** The frame to paint, resolved once per change of what it depends on. */\nfunction pictureOf(host: object, s: VideoState, elapsed: number): VideoFillResolved | null {\n if (!s.src) {\n pictures.delete(host);\n return null;\n }\n const scheduled = scheduledTimestamp(s, elapsed);\n const crop = s.crop;\n const anchor = s.anchor as unknown as Vector2;\n const key = [\n s.src, s.fit ?? \"\", s.zoom, s.playing ? 1 : 0, crop.left, crop.right, crop.top, crop.bottom, anchor.x, anchor.y,\n s.timestamp ?? \"\", s.trimStart ?? \"\", s.trimEnd ?? \"\", s.speed ?? \"\", s.loop ?? \"\", s.duration ?? \"\", scheduled ?? \"\",\n ].join(\"|\");\n const kept = pictures.get(host);\n if (kept && kept.key === key) return kept.fill;\n const prop: VideoFillProp = {\n type: \"video\", src: s.src, fit: s.fit, crop: s.crop, zoom: s.zoom, anchor: s.anchor, matrix: s.matrix,\n filters: s.filters as never, playing: s.playing, timestamp: s.timestamp ?? scheduled,\n trimStart: s.trimStart, trimEnd: s.trimEnd, speed: s.speed, loop: s.loop, duration: s.duration,\n };\n const fill = resolveFill(prop as FillProp) as VideoFillResolved;\n pictures.set(host, { key, fill });\n return fill;\n}\n\nexport const Video = component2d({\n key: \"video\",\n state: { ...Paint.state, ...Flow.state, ...Corners.state, ...video },\n commands: {\n ...Paint.commands,\n /** Its sound: from `from` in the source for a segment, or as it plays. Cut when the command ends. */\n play: {\n args: {\n from: Types.custom<number | undefined>(undefined),\n volume: Types.custom<number | undefined>(undefined),\n speed: Types.custom<number | undefined>(undefined),\n },\n run: (timeline, state) => {\n const s = state as unknown as VideoState;\n const segment = timeline.args.from !== undefined;\n if (!s.src || s.muted || (!segment && !s.playing)) return timeline.together([]);\n const speed = timeline.args.speed ?? s.speed ?? 1;\n const loop = !segment && (s.loop ?? \"none\") !== \"none\";\n return timeline.sound(s.src, {\n volume: timeline.args.volume ?? s.volume,\n loop,\n trimStart: segment ? timeline.args.from : s.trimStart,\n trimEnd: s.trimEnd,\n speed,\n effects: s.audioEffects,\n bus: s.bus,\n optional: true,\n closed: !loop,\n });\n },\n },\n },\n load: (loader, state) => {\n if (!state.src) return;\n loader.fill(resolveFill({\n type: \"video\", src: state.src, filters: state.filters, trimStart: state.trimStart, trimEnd: state.trimEnd,\n } as unknown as FillProp));\n },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => {\n const s = state as unknown as VideoState & Values<typeof Paint.state> & Values<typeof Corners.state>;\n const picture = pictureOf(internalsOf(ctx).host, s, ctx.time.elapsed);\n const outline = { width: ctx.size.width, height: ctx.size.height, cornerRadius: s.cornerRadius, cornerStyle: s.cornerStyle, start: s.start, end: s.end };\n Paint.draw(ctx, state, Corners.rect(ctx.size, state), {\n fill: [(picture ?? UNSET_MEDIA_FILL), ...state.fill] as never,\n // The overlay lies on the picture only, masked by it.\n overlay: () => (picture\n ? new Graphics2D().mask().rect(outline).fill([picture] as never).applyMask().rect(outline).fill(state.overlay).endMask()\n : null),\n });\n },\n});\n\nexport type Video = NodeOf<typeof Video>;\n\n// What code building a video names its props as, and the segments it plays.\n\nexport interface VideoProps extends RectProps {\n src?: string;\n /** How the (cropped) frame is scaled into the node's bounds. Default 'fill'. */\n fit?: ImageFit;\n /** Window onto the source frame, in fractions of its own size, applied before `fit`. */\n crop?: ImageCrop;\n /** Magnification on top of the fitted scale. `1` (default) is the fitted size. */\n zoom?: number;\n /** The point held fixed as `zoom` scales; also the alignment when it doesn't cover. */\n anchor?: Alignment;\n /** Raw frame→shape matrix; bypasses `crop`/`fit`/`zoom`/`anchor` and the bounds. */\n matrix?: ImageMatrix;\n /** Visual filters applied to the rendered frame (blur, color, posterizeTime, echo, …). */\n filters?: VideoAdjustment;\n /** Whether playback advances with the node's clock (drives both picture and sound). Default true. */\n playing?: boolean;\n /**\n * Explicit source time to show, in seconds. Omit it (the default) and the\n * picture is timed from the moment this node appeared; set it to drive the\n * playhead yourself, and set it to `null` to hand the playhead back to the\n * clock (`set()` merges a partial, so `undefined` won't clear it).\n */\n timestamp?: number | null;\n trimStart?: number;\n trimEnd?: number;\n /** Playback-rate multiplier for both picture and audio. Default 1. */\n speed?: number;\n loop?: 'forward' | 'reverse' | 'none';\n /** Length of one loop cycle, in seconds. Defaults to the trimmed clip length. */\n duration?: number;\n /** Audio volume in [0, 1]. Default 1. */\n volume?: number;\n /** Silence the video's audio track without affecting the picture. Default false. */\n muted?: boolean;\n /** Audio effects applied to the video's sound track (gain, eq, echo, …). */\n audioEffects?: AudioEffectsInput;\n /**\n * The node id of an `AudioBus` in this clip to route the video's sound into.\n *\n * A `Video` is a `Node2D`, so it cannot be parented under a bus the way a\n * `SoundNode` is — its audio is welded to its picture, which has to stay in\n * the visual tree. Naming one instead is what lets a video's dialogue sit on\n * the same bus as everything else, so ducking the whole group is still one\n * edit — and it is the *same* id a `SoundNode` under that bus writes as its\n * `parentId`, rather than a second vocabulary for \"which bus\". An id matching\n * no bus routes straight to the master, the same as no bus at all.\n */\n bus?: string;\n /**\n * An explicit **playback schedule**: the stretches of this node's own clock\n * during which the clip advances, and where in the source each one starts.\n *\n * Omit it (the default) and playback is what it has always been — the clip\n * runs from the moment the node appears, at `speed`, until it or the node\n * runs out. Give it, and `playing`/`timestamp` are both superseded: the\n * picture takes its source time from whichever segment covers the current\n * `elapsed`, and the sound is scheduled one clip per segment.\n *\n * It exists because a **pause** cannot be expressed any other way. `playing:\n * false` holds the clip's *first* frame, because with playback derived\n * linearly from the clock there is nothing else it could hold; and the sound\n * runs on the node's own clock regardless, so a picture frozen by any means\n * would drift away from it. A schedule states the one thing both halves need\n * and neither could infer — that a paused stretch consumes no source — so\n * they cannot come apart.\n *\n * Still a pure function of the clock, which is the property everything else\n * here is built on: frame *N* is identical however the playhead reached it,\n * so a scrub, a playthrough and an export agree.\n */\n segments?: readonly VideoSegment[];\n\n}\n\n/**\n * One stretch of a {@link Video}'s own clock during which its source advances —\n * see {@link VideoProps.segments}.\n *\n * Trim and loop are applied *on top* of this, by the same code that applies them\n * to unscheduled playback, so a schedule says when the clip is running and the\n * clip's own props go on saying which part of the file it is running through.\n */\nexport interface VideoSegment {\n /** Second on the node's own clock (`NodeTime.elapsed`) this segment begins. */\n at: number;\n /** Source in-point for it, in seconds. */\n from: number;\n /**\n * How long it runs, in seconds of the node's clock.\n *\n * `Infinity` for a clip left running — the same open sentinel\n * `AudioRequest.endAt` uses — which resolves against the clip's length.\n */\n duration: number;\n /** Playback rate through it. Defaults to the node's own `speed`. */\n speed?: number;\n /** Linear gain for its sound. Defaults to the node's own `volume`. */\n volume?: number;\n}\n", "import type { Passthrough3D } from \"./geometry\";\nimport type { Transform3D } from \"./transform\";\nimport { resolveVector3, type Vector3, type Vector3Input } from \"./vector3\";\n\n/**\n * What every camera has, whatever it projects with.\n *\n * A camera can be placed two ways and they are not redundant. The\n * {@link Transform3D} half — `position` plus `lookAt` — is right when the shot is\n * pinned to something, and it is what a camera inside a moving rig uses. The\n * polar half — {@link target}, {@link orbit}, {@link elevation},\n * {@link distance} — is right when the shot is *about* the subject, which is\n * most of the time, and it is the only one of the two that animates cleanly:\n *\n * cam().to({ data: { orbit: 160, elevation: 30 }, duration: 4 });\n *\n * Writing that same move through `position` means composing sines by hand every\n * frame, which is what every scene did before this existed.\n *\n * Setting any polar field derives `position` and `lookAt`, so the two halves are\n * never in force at once. See {@link resolveCameraPlacement}.\n */\nexport interface CameraCommon3D extends Transform3D, Passthrough3D {\n /** The point the camera looks at, and orbits around. Default origin. */\n target?: Vector3Input;\n /** Azimuth around {@link target}, in **degrees**. 0 looks down −Z. */\n orbit?: number;\n /** Angle above the horizon, in **degrees**. Clamped just short of vertical. */\n elevation?: number;\n /** Distance from {@link target}. */\n distance?: number;\n\n /**\n * Near and far clip planes.\n *\n * Both are derived from the scene's own bounds when omitted, which is right\n * far more often than any constant: too near a `far` clips the back of the\n * scene, too far a `near` destroys depth precision. Set them only to override.\n */\n near?: number;\n far?: number;\n /** Zoom factor applied on top of the projection. */\n zoom?: number;\n}\n\n/**\n * A perspective camera — converging rays, so distant things shrink. What you want\n * unless you specifically need the flat look of an orthographic projection.\n */\nexport interface PerspectiveCameraData3D extends CameraCommon3D {\n type: \"perspective\";\n /** Vertical field of view in **degrees**. Default 50. */\n fov?: number;\n}\n\n/**\n * An orthographic camera — parallel rays, so size is independent of distance.\n * For isometric views, technical diagrams and 2.5D layouts.\n *\n * {@link frustumHeight} sets the visible world height and derives the width from\n * the node's aspect ratio. An asymmetric frustum is a `params` override rather\n * than four more fields, because four explicit edges is a projection-matrix\n * feature rather than a framing one.\n */\nexport interface OrthographicCameraData3D extends CameraCommon3D {\n type: \"orthographic\";\n /** Visible world-space height; width follows the node's aspect. Default 10. */\n frustumHeight?: number;\n}\n\n/** Every camera a scene can be viewed through. Discriminated on `type`. */\nexport type CameraData3D = PerspectiveCameraData3D | OrthographicCameraData3D;\n\n/**\n * True when the camera is placed polar-ly.\n *\n * `target` is deliberately not part of this. It answers \"what am I looking at\",\n * which is meaningful on its own — it is `lookAt` under a name that reads right\n * beside `orbit` — and only becomes a *placement* once one of the three fields\n * that orbit around it is set. Including it here would make every camera polar\n * the moment it named a subject, silently discarding its `position`.\n */\n/** What an unset polar field of an orbiting camera reads as. */\nexport const ORBIT_CAMERA_DEFAULTS = { orbit: 0, elevation: 0, distance: 10 } as const;\n\nexport function isOrbitCamera3D(camera: CameraData3D): boolean {\n return camera.orbit !== undefined\n || camera.elevation !== undefined\n || camera.distance !== undefined;\n}\n\n/**\n * A camera's effective position and aim.\n *\n * One definition, shared by the renderer and by the editor's picking geometry —\n * two places computing \"where is the camera\" from the same descriptor is two\n * chances to disagree about what the author sees, and a gizmo drawn against a\n * camera nobody renders is worse than no gizmo.\n *\n * The polar fields win over `position`/`lookAt` when any of them is set, so the\n * two placements can never both be half-applied.\n */\nexport function resolveCameraPlacement(camera: CameraData3D): {\n position: Vector3;\n lookAt: Vector3 | undefined;\n} {\n const target = resolveVector3(camera.target ?? 0);\n\n if (!isOrbitCamera3D(camera)) {\n // `target` is the subject either way, so a camera placed by `position`\n // still aims at it — which is what makes `target` one idea rather than a\n // polar-only field with `lookAt` as its non-polar twin.\n const aim = camera.lookAt ?? camera.target;\n return {\n position: resolveVector3(camera.position ?? 0),\n lookAt: aim === undefined ? undefined : resolveVector3(aim),\n };\n }\n\n const distance = camera.distance ?? ORBIT_CAMERA_DEFAULTS.distance;\n const azimuth = ((camera.orbit ?? ORBIT_CAMERA_DEFAULTS.orbit) * Math.PI) / 180;\n // Just short of the pole: at exactly ±90° the view direction is parallel to\n // the up vector and the look-at basis is undefined, which reads as the shot\n // snapping to an arbitrary roll on the frame it crosses.\n const elevation = (clamp(camera.elevation ?? ORBIT_CAMERA_DEFAULTS.elevation, -89.9, 89.9) * Math.PI) / 180;\n\n const horizontal = Math.cos(elevation) * distance;\n\n return {\n position: {\n x: target.x + Math.sin(azimuth) * horizontal,\n y: target.y + Math.sin(elevation) * distance,\n z: target.z + Math.cos(azimuth) * horizontal,\n },\n lookAt: target,\n };\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return value < low ? low : value > high ? high : value;\n}\n", "import type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport { ORBIT_CAMERA_DEFAULTS, type CameraData3D } from \"@/render3d/camera\";\nimport { lerpFill3D, type Fill3D } from \"@/render3d/fill3d\";\nimport type { Geometry3D, PolyhedronGeometry3D, BoxGeometry3D, CapsuleGeometry3D, CircleGeometry3D, ConeGeometry3D, CylinderGeometry3D, ExtrudeGeometry3D, LatheGeometry3D, PlaneGeometry3D, RingGeometry3D, SphereGeometry3D, TorusGeometry3D, TorusKnotGeometry3D, TubeGeometry3D } from \"@/render3d/geometry\";\nimport { Graphics3D, type LineStroke3D, type ModelAnimation3D } from \"@/render3d/graphics3d\";\nimport type { LightData3D, AmbientLightData3D, AreaLightData3D, DirectionalLightData3D, HemisphereLightData3D, PointLightData3D, SpotLightData3D } from \"@/render3d/light\";\nimport type { Material3D, Shading3D } from \"@/render3d/material\";\nimport type { EnvironmentData3D, FogData3D } from \"@/render3d/scene-settings\";\nimport type { Segments3D } from \"@/render3d/segments\";\nimport type { Transform3D, Blend3D, Faces3D } from \"@/render3d/transform\";\nimport type { Vector3Input } from \"@/render3d/vector3\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { component3d } from \"@/components/factory/component3d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Material from \"@/components/modules/material\";\nimport { defined, optional, optionalColor, optionalNumber, optionalVector3, stated } from \"@/components/modules/three-entries\";\nimport type { Node3DProps } from \"@/components/trees/three/node3d\";\nimport type { Texture3D } from \"@/render3d/texture\";\n\n/**\n * The 3D tree: groups, meshes and the other drawables, lights, the camera, fog\n * and the environment. Each draws the `Graphics3D` or scene call its class did.\n */\n\nexport const Group3D = component3d({ key: \"group3d\" });\nexport type Group3D = NodeOf<typeof Group3D>;\n\n// ---- meshes -----------------------------------------------------------------\n\nconst mesh = { geometry: optional<Geometry3D>(), ...Material.state };\n\nexport const Mesh3D = component3d({\n key: \"mesh3d\",\n state: mesh,\n render: (ctx, s) => ctx.draw(Material.mesh(s, s.geometry)),\n});\nexport type Mesh3D = NodeOf<typeof Mesh3D>;\n\nconst sweep = { startAngle: optional<number>(), sweep: optional<number>() };\nconst SWEEP_KEYS = [\"startAngle\", \"sweep\"] as const;\n\n/** A mesh of one built-in shape: `keys` are the entries its geometry descriptor takes. */\nfunction shape3d<const K extends string, const S extends Record<string, ReturnType<typeof optional>>>(\n key: K, type: Geometry3D[\"type\"], own: S, keys: readonly string[],\n) {\n return component3d({\n key,\n state: { ...mesh, ...own },\n render: (ctx, s) => ctx.draw(Material.mesh(s as never, stated<Geometry3D>(type, s, keys))),\n });\n}\n\nexport const Box3D = shape3d(\"box3d\", \"box\", {\n width: optional<number>(), height: optional<number>(), depth: optional<number>(),\n cornerRadius: optional<number>(), segments: optional<Segments3D>(),\n}, [\"width\", \"height\", \"depth\", \"cornerRadius\", \"segments\"]);\nexport type Box3D = NodeOf<typeof Box3D>;\n\nexport const Sphere3D = shape3d(\"sphere3d\", \"sphere\", {\n radius: optional<number>(), segments: optional<Segments3D>(), ...sweep,\n startLatitude: optional<number>(), latitudeSweep: optional<number>(),\n}, [\"radius\", \"segments\", \"startLatitude\", \"latitudeSweep\", ...SWEEP_KEYS]);\nexport type Sphere3D = NodeOf<typeof Sphere3D>;\n\nexport const Plane3D = shape3d(\"plane3d\", \"plane\", {\n width: optional<number>(), height: optional<number>(), segments: optional<Segments3D>(),\n}, [\"width\", \"height\", \"segments\"]);\nexport type Plane3D = NodeOf<typeof Plane3D>;\n\nexport const Cylinder3D = shape3d(\"cylinder3d\", \"cylinder\", {\n radius: optional<number | readonly [number, number]>(), height: optional<number>(),\n segments: optional<Segments3D>(), capped: optional<boolean>(), ...sweep,\n}, [\"radius\", \"height\", \"segments\", \"capped\", ...SWEEP_KEYS]);\nexport type Cylinder3D = NodeOf<typeof Cylinder3D>;\n\nexport const Cone3D = shape3d(\"cone3d\", \"cone\", {\n radius: optional<number>(), height: optional<number>(), segments: optional<Segments3D>(), capped: optional<boolean>(), ...sweep,\n}, [\"radius\", \"height\", \"segments\", \"capped\", ...SWEEP_KEYS]);\nexport type Cone3D = NodeOf<typeof Cone3D>;\n\nexport const Torus3D = shape3d(\"torus3d\", \"torus\", {\n radius: optional<number>(), thickness: optional<number>(), segments: optional<Segments3D>(), ...sweep,\n}, [\"radius\", \"thickness\", \"segments\", ...SWEEP_KEYS]);\nexport type Torus3D = NodeOf<typeof Torus3D>;\n\nexport const TorusKnot3D = shape3d(\"torus-knot3d\", \"torusKnot\", {\n radius: optional<number>(), thickness: optional<number>(), segments: optional<Segments3D>(),\n windings: optional<readonly [number, number]>(),\n}, [\"radius\", \"thickness\", \"segments\", \"windings\"]);\nexport type TorusKnot3D = NodeOf<typeof TorusKnot3D>;\n\nexport const Circle3D = shape3d(\"circle3d\", \"circle\", {\n radius: optional<number>(), segments: optional<Segments3D>(), ...sweep,\n}, [\"radius\", \"segments\", ...SWEEP_KEYS]);\nexport type Circle3D = NodeOf<typeof Circle3D>;\n\nexport const Ring3D = shape3d(\"ring3d\", \"ring\", {\n radius: optional<number>(), innerRadius: optional<number>(), segments: optional<Segments3D>(), ...sweep,\n}, [\"radius\", \"innerRadius\", \"segments\", ...SWEEP_KEYS]);\nexport type Ring3D = NodeOf<typeof Ring3D>;\n\nexport const Capsule3D = shape3d(\"capsule3d\", \"capsule\", {\n radius: optional<number>(), height: optional<number>(), segments: optional<Segments3D>(),\n}, [\"radius\", \"height\", \"segments\"]);\nexport type Capsule3D = NodeOf<typeof Capsule3D>;\n\nexport const Polyhedron3D = component3d({\n key: \"polyhedron3d\",\n state: { ...mesh, shape: Types.custom<PolyhedronGeometry3D[\"shape\"]>(\"icosahedron\"), radius: optional<number>(), segments: optional<Segments3D>() },\n render: (ctx, s) => ctx.draw(Material.mesh(s, stated<Geometry3D>(\"polyhedron\", s, [\"shape\", \"radius\", \"segments\"]))),\n});\nexport type Polyhedron3D = NodeOf<typeof Polyhedron3D>;\n\nexport const Extrude3D = shape3d(\"extrude3d\", \"extrude\", {\n path: optional<unknown>(), depth: optional<number>(), segments: optional<Segments3D>(), bevel: optional<unknown>(),\n}, [\"path\", \"depth\", \"segments\", \"bevel\"]);\nexport type Extrude3D = NodeOf<typeof Extrude3D>;\n\nexport const Lathe3D = shape3d(\"lathe3d\", \"lathe\", {\n points: optional<readonly unknown[]>(), segments: optional<Segments3D>(), ...sweep,\n}, [\"points\", \"segments\", ...SWEEP_KEYS]);\nexport type Lathe3D = NodeOf<typeof Lathe3D>;\n\nexport const Tube3D = shape3d(\"tube3d\", \"tube\", {\n points: optional<readonly Vector3Input[]>(), radius: optional<number>(), segments: optional<Segments3D>(), closed: optional<boolean>(),\n}, [\"points\", \"radius\", \"segments\", \"closed\"]);\nexport type Tube3D = NodeOf<typeof Tube3D>;\n\n// ---- other drawables ----------------------------------------------------------\n\nexport const Instances3D = component3d({\n key: \"instances3d\",\n state: { ...mesh, instances: optional<readonly Transform3D[]>(), colors: optional<readonly Color[]>() },\n render: (ctx, s) => {\n if (!s.geometry || !s.instances?.length) return;\n ctx.draw(new Graphics3D().instances(s.geometry, Material.single(s), s.instances, { colors: s.colors }));\n },\n});\nexport type Instances3D = NodeOf<typeof Instances3D>;\n\nexport const Points3D = component3d({\n key: \"points3d\",\n state: mesh,\n render: (ctx, s) => {\n if (s.geometry) ctx.draw(new Graphics3D().points(s.geometry, Material.points(s)));\n },\n});\nexport type Points3D = NodeOf<typeof Points3D>;\n\nexport const Line3D = component3d({\n key: \"line3d\",\n state: {\n points: optional<readonly Vector3Input[]>(),\n geometry: optional<Geometry3D>(),\n closed: Types.custom(false),\n segments: Types.custom(false),\n stroke: optional<LineStroke3D>(),\n opacity: optional<number>(),\n material: optional<Material3D>(),\n },\n render: (ctx, s) => {\n if (!s.geometry && !s.points?.length) return;\n ctx.draw(new Graphics3D().line({\n points: s.geometry ? undefined : s.points, geometry: s.geometry, closed: s.closed, segments: s.segments,\n stroke: s.stroke, opacity: s.opacity, material: s.material,\n }));\n },\n});\nexport type Line3D = NodeOf<typeof Line3D>;\n\nexport const Sprite3D = component3d({\n key: \"sprite3d\",\n state: {\n fill: Types.custom<Fill3D | undefined>(undefined, { lerp: lerpFill3D as never }),\n opacity: optional<number>(),\n material: optional<Material3D>(),\n },\n render: (ctx, s) => ctx.draw(new Graphics3D().sprite({ fill: s.fill as Fill3D, opacity: s.opacity, material: s.material })),\n});\nexport type Sprite3D = NodeOf<typeof Sprite3D>;\n\nexport const Model3D = component3d({\n key: \"model3d\",\n state: {\n src: optional<string>(),\n animation: optional<readonly ModelAnimation3D[] | ModelAnimation3D>(),\n override: optional<Readonly<Record<string, Material3D>>>(),\n },\n render: (ctx, s) => {\n if (s.src) ctx.draw(new Graphics3D().model({ src: s.src, animation: s.animation, override: s.override }));\n },\n});\nexport type Model3D = NodeOf<typeof Model3D>;\n\n/**\n * A loaded model with its animation restated as two flat entries: `clip` (a\n * clip name, or its index in the file as a string; empty is the first) and\n * `clipTime` (seconds into it). The timeline tweens a number, and\n * `Model3D.animation` is a list of records, so \"play the walk cycle\" is a tween\n * of `clipTime` here. The clip is still sampled at an explicit time, so seeking\n * and playing to a frame give the same pose.\n *\n * Before a file is picked it draws an unlit wireframe unit box: a node that\n * records no geometry has no box to pick, select or outline. Not registered: an\n * editor's node, not document API.\n */\nexport const ModelView3D = component3d({\n key: \"modelView3d\",\n state: {\n src: optional<string>(),\n animation: optional<readonly ModelAnimation3D[] | ModelAnimation3D>(),\n override: optional<Readonly<Record<string, Material3D>>>(),\n clip: \"\",\n clipTime: 0,\n },\n render: (ctx, s) => {\n if (!s.src) {\n ctx.draw(new Graphics3D().box({\n width: 1, height: 1, depth: 1,\n material: { type: \"basic\", color: \"#6b7280\", wireframe: true, transparent: true, opacity: 0.7 },\n }));\n return;\n }\n ctx.draw(new Graphics3D().model({ src: s.src, animation: { clip: modelClip(s.clip), time: s.clipTime }, override: s.override }));\n },\n});\nexport type ModelView3D = NodeOf<typeof ModelView3D>;\n\n/** A clip name, or a whole number as an index (`\"0\"` is the first clip, not one named `0`), or unset when empty. */\nfunction modelClip(clip: string): string | number | undefined {\n const trimmed = clip.trim();\n if (trimmed === \"\") return undefined;\n const index = Number(trimmed);\n return Number.isInteger(index) && index >= 0 ? index : trimmed;\n}\n\n// ---- lights -------------------------------------------------------------------\n\n/** A light that casts no shadow unless asked: shadow maps cost a render each. */\nconst castsNoShadow = { shadow: false } as const;\n\nexport const AmbientLight3D = component3d({\n key: \"ambient-light3d\",\n state: { color: optionalColor(), intensity: optional<number>() },\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"ambient\", s, [\"color\", \"intensity\"])),\n});\nexport type AmbientLight3D = NodeOf<typeof AmbientLight3D>;\n\nexport const HemisphereLight3D = component3d({\n key: \"hemisphere-light3d\",\n state: { sky: optionalColor(), ground: optionalColor(), intensity: optional<number>() },\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"hemisphere\", s, [\"sky\", \"ground\", \"intensity\"])),\n});\nexport type HemisphereLight3D = NodeOf<typeof HemisphereLight3D>;\n\nexport const DirectionalLight3D = component3d({\n key: \"directional-light3d\",\n state: { color: optionalColor(), intensity: optional<number>(), target: optionalVector3(\"origin\") },\n defaults: castsNoShadow,\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"directional\", s, [\"color\", \"intensity\", \"target\", \"shadow\"])),\n});\nexport type DirectionalLight3D = NodeOf<typeof DirectionalLight3D>;\n\nexport const PointLight3D = component3d({\n key: \"point-light3d\",\n state: { color: optionalColor(), intensity: optional<number>(), distance: optional<number>(), decay: optional<number>() },\n defaults: castsNoShadow,\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"point\", s, [\"color\", \"intensity\", \"distance\", \"decay\", \"shadow\"])),\n});\nexport type PointLight3D = NodeOf<typeof PointLight3D>;\n\nexport const SpotLight3D = component3d({\n key: \"spot-light3d\",\n state: {\n color: optionalColor(), intensity: optional<number>(), distance: optional<number>(), angle: optional<number>(),\n penumbra: optional<number>(), decay: optional<number>(), target: optionalVector3(\"origin\"),\n },\n defaults: castsNoShadow,\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"spot\", s, [\"color\", \"intensity\", \"distance\", \"angle\", \"penumbra\", \"decay\", \"target\", \"shadow\"])),\n});\nexport type SpotLight3D = NodeOf<typeof SpotLight3D>;\n\nexport const AreaLight3D = component3d({\n key: \"area-light3d\",\n state: { color: optionalColor(), intensity: optional<number>(), width: optional<number>(), height: optional<number>() },\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"area\", s, [\"color\", \"intensity\", \"width\", \"height\"])),\n});\nexport type AreaLight3D = NodeOf<typeof AreaLight3D>;\n\n// ---- camera, fog, environment -------------------------------------------------\n\nconst CAMERA_KEYS = [\"target\", \"orbit\", \"elevation\", \"distance\", \"fov\", \"frustumHeight\", \"near\", \"far\", \"zoom\"] as const;\nconst ORBIT_KEYS = [\"orbit\", \"elevation\", \"distance\"] as const;\n\nexport const Camera3D = component3d({\n key: \"camera3d\",\n state: {\n type: Types.custom<CameraData3D[\"type\"]>(\"perspective\"),\n target: optionalVector3(\"origin\"),\n orbit: optional<number>(),\n elevation: optional<number>(),\n distance: optional<number>(),\n fov: optional<number>(),\n frustumHeight: optional<number>(),\n near: optional<number>(),\n far: optional<number>(),\n zoom: optional<number>(),\n },\n commands: {\n /** Only the given angles move, each from where it stands (the orbit default while unset). */\n orbitTo: {\n args: {\n orbit: optionalNumber({ step: 1, unit: \"°\" }),\n elevation: optionalNumber({ min: -89, max: 89, step: 1, unit: \"°\" }),\n distance: optionalNumber({ min: 0.01, step: 0.1 }),\n },\n run: (timeline, s) => {\n const from = {\n orbit: s.orbit ?? ORBIT_CAMERA_DEFAULTS.orbit,\n elevation: s.elevation ?? ORBIT_CAMERA_DEFAULTS.elevation,\n distance: s.distance ?? ORBIT_CAMERA_DEFAULTS.distance,\n };\n return timeline.animate((t) => {\n const out: Record<string, number> = {};\n for (const key of ORBIT_KEYS) {\n const end = timeline.args[key];\n if (end !== undefined) out[key] = from[key] + (end - from[key]) * t;\n }\n return out;\n });\n },\n },\n lookTo: { args: [\"target\"] },\n },\n render: (ctx, s) => {\n const data: Record<string, unknown> = { type: s.type };\n for (const key of CAMERA_KEYS) if (s[key] !== undefined) data[key] = s[key];\n ctx.camera(data as unknown as CameraData3D);\n },\n});\nexport type Camera3D = NodeOf<typeof Camera3D>;\n\nexport const Fog3D = component3d({\n key: \"fog3d\",\n state: { color: optionalColor(), near: optional<number>(), far: optional<number>(), density: optional<number>() },\n render: (ctx, s) => {\n const out: FogData3D = {};\n if (s.color !== undefined) out.color = s.color as Color;\n if (s.density !== undefined) out.density = s.density;\n else {\n if (s.near !== undefined) out.near = s.near;\n if (s.far !== undefined) out.far = s.far;\n }\n ctx.fog(out);\n },\n});\nexport type Fog3D = NodeOf<typeof Fog3D>;\n\nexport const Environment3D = component3d({\n key: \"environment3d\",\n state: {\n src: optional<string>(),\n faces: optional<readonly string[]>(),\n preset: optional<\"studio\">(),\n intensity: optional<number>(),\n background: optional<boolean>(),\n blur: optional<number>(),\n },\n render: (ctx, s) => {\n if (s.src === undefined && s.faces === undefined && s.preset === undefined) return ctx.environment(null);\n const out = defined<EnvironmentData3D>(s, [\"src\", \"faces\", \"preset\", \"intensity\", \"background\", \"blur\"]);\n if (s.rotationX || s.rotationY || s.rotationZ) out.rotation = [s.rotationX, s.rotationY, s.rotationZ];\n ctx.environment(out);\n },\n});\nexport type Environment3D = NodeOf<typeof Environment3D>;\n\n// What code building a 3D node names its props as.\n\n/** Params of a geometry descriptor, minus its discriminant. */\ntype ParamsOf<G extends { type: string }> = Omit<G, \"type\">;\n/** A light's params, minus its discriminant and its shadow, which is a node prop of its own. */\ntype LightParamsOf<L extends { type: string }> = Omit<L, \"type\" | \"shadow\">;\n\nexport type Group3DProps = Node3DProps;\n\n/**\n * The material shorthand, as node props.\n *\n * Exactly the keys {@link MaterialShorthand3D} promotes onto the `Graphics3D`\n * sugar methods, so `Box3D({ fill: \"red\", roughness: 0.3 })` and\n * `g3.box({ fill: \"red\", roughness: 0.3 })` describe the same mesh — and each is\n * a real prop here, so any of them can be tweened.\n *\n * Ten props, where there were twenty-four. What went is everything that was a\n * renderer knob rather than a design decision — `depthWrite`, `depthTest`,\n * `alphaTest`, `toneMapped`, `polygonOffset`, `dithering` — which now live only\n * on a `Mat.*` descriptor passed through {@link material}; plus `transparent`,\n * which is derived; plus five texture slots, which are fills.\n */\nexport interface Material3DProps {\n /** A full descriptor (or an array, for multi-material). Wins over the rest. */\n material: Material3D | readonly Material3D[] | undefined;\n /** What the surface is made of — the same value a 2D `fill` takes. */\n fill: Fill3D;\n opacity: number;\n roughness: number;\n metalness: number;\n emission: Color | undefined;\n emissionStrength: number;\n normalMap: Texture3D | undefined;\n roughnessMap: Texture3D | undefined;\n metalnessMap: Texture3D | undefined;\n aoMap: Texture3D | undefined;\n alphaMap: Texture3D | undefined;\n envMapIntensity: number;\n wireframe: boolean;\n /** Facet or smooth shading. Default `\"smooth\"`. */\n shading: Shading3D;\n /** Which faces to rasterize. Default `\"front\"`. */\n faces: Faces3D;\n vertexColors: boolean;\n blend: Blend3D;\n /** Shade with an unlit `basic` material instead of `standard`. */\n unlit: boolean;\n}\n\nexport interface Mesh3DProps extends Node3DProps, Partial<Material3DProps> {\n /** The geometry to draw. Set directly, or built from a geometry component's entries. */\n geometry: Geometry3D;\n}\n\n// ─── box ─────────────────────────────────────────────────────────────────────\n\nexport interface Box3DProps extends Mesh3DProps, Partial<ParamsOf<BoxGeometry3D>> { }\n\n// ─── sphere ──────────────────────────────────────────────────────────────────\n\nexport interface Sphere3DProps extends Mesh3DProps, Partial<ParamsOf<SphereGeometry3D>> { }\n\n// ─── plane ───────────────────────────────────────────────────────────────────\n\nexport interface Plane3DProps extends Mesh3DProps, Partial<ParamsOf<PlaneGeometry3D>> { }\n\n// ─── cylinder ────────────────────────────────────────────────────────────────\n\nexport interface Cylinder3DProps extends Mesh3DProps, Partial<ParamsOf<CylinderGeometry3D>> { }\n\n// ─── cone ────────────────────────────────────────────────────────────────────\n\nexport interface Cone3DProps extends Mesh3DProps, Partial<ParamsOf<ConeGeometry3D>> { }\n\n// ─── torus ───────────────────────────────────────────────────────────────────\n\nexport interface Torus3DProps extends Mesh3DProps, Partial<ParamsOf<TorusGeometry3D>> { }\n\n// ─── torus knot ──────────────────────────────────────────────────────────────\n\nexport interface TorusKnot3DProps extends Mesh3DProps, Partial<ParamsOf<TorusKnotGeometry3D>> { }\n\n// ─── circle ──────────────────────────────────────────────────────────────────\n\nexport interface Circle3DProps extends Mesh3DProps, Partial<ParamsOf<CircleGeometry3D>> { }\n\n// ─── ring ────────────────────────────────────────────────────────────────────\n\nexport interface Ring3DProps extends Mesh3DProps, Partial<ParamsOf<RingGeometry3D>> { }\n\n// ─── capsule ─────────────────────────────────────────────────────────────────\n\nexport interface Capsule3DProps extends Mesh3DProps, Partial<ParamsOf<CapsuleGeometry3D>> { }\n\n// ─── polyhedron ──────────────────────────────────────────────────────────────\n\nexport interface Polyhedron3DProps extends Mesh3DProps, Partial<ParamsOf<PolyhedronGeometry3D>> { }\n\n// ─── extrude ─────────────────────────────────────────────────────────────────\n\nexport interface Extrude3DProps extends Mesh3DProps, Partial<ParamsOf<ExtrudeGeometry3D>> { }\n\n// ─── lathe ───────────────────────────────────────────────────────────────────\n\nexport interface Lathe3DProps extends Mesh3DProps, Partial<ParamsOf<LatheGeometry3D>> { }\n\n// ─── tube ────────────────────────────────────────────────────────────────────\n\nexport interface Tube3DProps extends Mesh3DProps, Partial<ParamsOf<TubeGeometry3D>> { }\n\n/**\n * The drawables that aren't a single mesh: instanced copies, point clouds,\n * polylines, sprites and loaded models.\n *\n * Each is the node form of the matching `Graphics3D` method, so what it draws and\n * what a builder chain draws are the same descriptor.\n */\n\n// ─── instances ───────────────────────────────────────────────────────────────\n\nexport interface Instances3DProps extends Mesh3DProps {\n /** Per-instance placement. Its length drives the instance count. */\n instances: readonly Transform3D[];\n /** Per-instance tint. Needs a material that reads instance colour. */\n colors: readonly Color[] | undefined;\n}\n\n// ─── points ──────────────────────────────────────────────────────────────────\n\nexport type Points3DProps = Mesh3DProps;\n\n// ─── line ────────────────────────────────────────────────────────────────────\n\nexport interface Line3DProps extends Node3DProps {\n /** The polyline's vertices. Give this or {@link geometry}, not both. */\n points: readonly Vector3Input[];\n /**\n * An explicit geometry to draw the lines of — `Geo.edges(...)` for a wireframe\n * outline, say. Wins over {@link points}.\n */\n geometry: Geometry3D;\n /** Join the last point back to the first. */\n closed: boolean;\n /** Treat the points as disjoint start/end pairs rather than one path. */\n segments: boolean;\n /** The line's paint. */\n stroke: LineStroke3D | undefined;\n opacity: number | undefined;\n material: Material3D | undefined;\n}\n\n// ─── sprite ──────────────────────────────────────────────────────────────────\n\nexport interface Sprite3DProps extends Node3DProps {\n /** What the billboard shows — the same value a 2D `fill` takes. */\n fill: Fill3D;\n opacity: number | undefined;\n material: Material3D | undefined;\n}\n\n// ─── model ───────────────────────────────────────────────────────────────────\n\nexport interface Model3DProps extends Node3DProps {\n /**\n * Path to a glTF/GLB file. **Only glTF/GLB loads**: any other format, an OBJ\n * included, resolves to an empty slot and draws nothing.\n */\n src: string;\n /**\n * Baked animation clips, each sampled at an **explicit** time — which is what\n * keeps a model identical whether the frame was played forward or scrubbed to.\n */\n animation: readonly ModelAnimation3D[] | ModelAnimation3D | undefined;\n /** Replace materials on the loaded graph, keyed by mesh or material name. */\n override: Readonly<Record<string, Material3D>> | undefined;\n}\n\nexport interface ModelView3DProps extends Model3DProps {\n /**\n * Which baked clip to sample — a clip name, or its index in the file as a\n * string. Empty means the first clip.\n */\n clip: string\n /** Seconds into that clip. Animate this to play it. */\n clipTime: number\n}\n\n// ─── ambient ─────────────────────────────────────────────────────────────────\n\nexport interface AmbientLight3DProps extends Node3DProps, Partial<LightParamsOf<AmbientLightData3D>> { }\n\n// ─── hemisphere ──────────────────────────────────────────────────────────────\n\nexport interface HemisphereLight3DProps extends Node3DProps, Partial<LightParamsOf<HemisphereLightData3D>> { }\n\n// ─── directional ─────────────────────────────────────────────────────────────\n\nexport interface DirectionalLight3DProps extends Node3DProps, Partial<LightParamsOf<DirectionalLightData3D>> { }\n\n// ─── point ───────────────────────────────────────────────────────────────────\n\nexport interface PointLight3DProps extends Node3DProps, Partial<LightParamsOf<PointLightData3D>> { }\n\n// ─── spot ────────────────────────────────────────────────────────────────────\n\nexport interface SpotLight3DProps extends Node3DProps, Partial<LightParamsOf<SpotLightData3D>> { }\n\n// ─── area ────────────────────────────────────────────────────────────────────\n\nexport interface AreaLight3DProps extends Node3DProps, Partial<LightParamsOf<AreaLightData3D>> { }\n\n/**\n * The camera — where the scene is viewed from.\n *\n * **One node, two projections.** `<Camera3D type=\"orthographic\">` is the flat\n * one; there is no second class, because a perspective and an orthographic\n * camera are one object with a projection setting, which is how every editor\n * presents it and how a scene switching between them has to be written.\n *\n * Camera3D({ target: [0, 0.2, 0], orbit: -18, elevation: 12, distance: 13, fov: 42 })\n *\n * cam().to({ data: { orbit: 160, elevation: 30 }, duration: 4, easing: easeInOut(\"quad\") });\n *\n * ── Orbit, not trigonometry ───────────────────────────────────────────────────\n * `target`/`orbit`/`elevation`/`distance` place the camera in polar coordinates\n * around the thing it is looking at, which is what a camera move almost always\n * *is*. Written through `position` the same move is a `Math.sin`/`Math.cos` pair\n * recomputed every frame in a prop binding — which is exactly what every scene\n * did before this existed.\n *\n * `position` and `lookAt` still work and are right for a shot pinned to\n * something; setting any polar field takes over, so the two can never be half\n * applied. Either way the camera is a node, so parenting it to a moving\n * `Group3D` carries the shot with the rig.\n *\n * ── What is derived ───────────────────────────────────────────────────────────\n * `near`/`far` come from the scene's own bounds unless you set them, and the\n * aspect ratio always tracks the viewport's layout box — it was a prop whose\n * documentation said \"don't set this\", and setting it stretched the render.\n * An asymmetric orthographic frustum is a `params` override rather than four\n * more fields.\n *\n * A scene with no camera gets a sensible default framing. A scene that declares\n * more than one keeps the last, since there is only ever one view.\n */\nexport interface Camera3DProps extends Node3DProps {\n /** `\"perspective\"` (default) or `\"orthographic\"`. */\n type: CameraData3D[\"type\"];\n /**\n * The point the camera looks at, and orbits around.\n *\n * On its own it is `lookAt` under a name that reads right beside `orbit`;\n * together with any of the three below it is also the centre they turn about.\n */\n target: Vector3Input | undefined;\n /** Azimuth around {@link target}, in **degrees**. */\n orbit: number | undefined;\n /** Angle above the horizon, in **degrees**. */\n elevation: number | undefined;\n /** Distance from {@link target}. */\n distance: number | undefined;\n /** Perspective only: vertical field of view in **degrees**. Default 50. */\n fov: number | undefined;\n /** Orthographic only: visible world height. Default 10. */\n frustumHeight: number | undefined;\n near: number | undefined;\n far: number | undefined;\n zoom: number | undefined;\n}\n\n/**\n * The two scene-wide nodes that are left: fog and environment.\n *\n * `Shadows3D`, `ToneMapping3D` and `PostEffects3D` used to be here and are now\n * props on `Canvas3D`. They were never scene *objects* — a viewport's shadow\n * quality, its tone curve and its post chain are settings of the thing doing the\n * rendering, and writing them as nodes meant a node with no position whose\n * duplicates silently did nothing. `Background3D` is gone entirely: what is drawn\n * behind a 3D scene is the viewport's own 2D `fill`.\n *\n * These two stay nodes because they *are* about the space: fog is a property of\n * the air in it, and an environment is the sky around it. Both are still\n * positionless, so declaring two of the same kind is not an error but only the\n * last takes effect.\n *\n * Fog3D({ near: 5, far: 30 })\n * Environment3D({ preset: \"studio\" })\n */\n\n// ─── fog ─────────────────────────────────────────────────────────────────────\n\nexport interface Fog3DProps extends Node3DProps {\n /** Defaults to the viewport's own fill — see below. */\n color: Color | undefined;\n /** Distance at which fog starts. Linear fog. */\n near: number | undefined;\n /** Distance at which fog is total. Linear fog. */\n far: number | undefined;\n /** Exponential-squared falloff. Wins over {@link near}/{@link far}. */\n density: number | undefined;\n}\n\n// ─── environment ─────────────────────────────────────────────────────────────\n\nexport interface Environment3DProps extends Node3DProps {\n /**\n * A 360° panorama — `.hdr`/`.exr` for real IBL, or a plain image.\n * **Inert today**: no backend loads it, so only `preset` renders.\n */\n src: string | undefined;\n /**\n * Six cubemap faces, in three's order: +X, −X, +Y, −Y, +Z, −Z.\n * **Inert today**: no backend loads them, so only `preset` renders.\n */\n faces: readonly string[] | undefined;\n /** A generated studio interior. Needs no asset. The only environment that renders. */\n preset: \"studio\" | undefined;\n intensity: number | undefined;\n /** Also draw it behind the scene, as an infinitely distant sky. */\n background: boolean | undefined;\n /** Blur the background only, 0–1. The lighting stays sharp. */\n blur: number | undefined;\n}\n", "import type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport * as View3D from \"@/components/modules/view3d\";\nimport type { PostEffect3D, Shadows3D, ToneMapping3D } from \"@/render3d/scene-settings\";\nimport type { RectProps } from \"@/components/builtins/geometry/geometry\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\n\n/**\n * The 3D viewport: a rect whose top fill layer is its 3D children's scene, seen\n * by their camera (or the default one), with its 2D children drawn over it.\n */\nexport const Canvas3D = component2d({\n key: \"canvas3d\",\n state: { ...Paint.state, ...Flow.state, ...Corners.state, ...View3D.state },\n defaults: { width: \"fill\", height: \"fill\" },\n commands: { ...Paint.commands, ...View3D.commands },\n allowedChildren: [\"2d\", \"3d\"],\n load: (loader) => View3D.load(loader),\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => View3D.draw(ctx, state),\n});\n\nexport type Canvas3D = NodeOf<typeof Canvas3D>;\n\n// What code building a 3D viewport names its props as.\n\nexport interface Canvas3DProps extends RectProps {\n /**\n * Ceiling on the 3D buffer's device-pixel ratio. Default 2.\n *\n * Lower it for an expensive scene: the 3D renders at a smaller buffer and is\n * scaled up on composite, which trades sharpness for fill rate.\n */\n maxPixelRatio: number;\n /** Multisample the 3D pass. Default true. */\n antialias: boolean;\n /**\n * Turn shadow casting on for the scene. A switch, or `{ quality }`.\n *\n * A render setting rather than a scene object, which is why it is a prop here\n * and not a `<Shadows3D>` node: it has no position, and two of them in a tree\n * meant one silently doing nothing.\n */\n shadows: Shadows3D;\n /** How HDR colour is compressed to what the screen can show. Default `\"aces\"`. */\n tone: ToneMapping3D;\n /** Stops of exposure applied before tone mapping. Default 1. */\n exposure: number;\n /**\n * Post-processing inside the 3D composite: `bloom`, `ssao`, `dof`, `outline`.\n *\n * Short by design — a `Canvas3D` is a `Node2D`, so vignette, grain, grading,\n * blur and the rest of the 2D `effects` chain already run over the composited\n * result. What is here is what genuinely needs the depth buffer, object ids,\n * or HDR radiance before tone mapping.\n *\n * **Inert today**: the chain is recorded on the scene and no pass is applied,\n * so a viewport with `post` renders exactly like one without (the first one\n * set warns in development). Use the viewport's 2D `effects` instead.\n */\n post: PostEffect3D | readonly PostEffect3D[];\n /**\n * The camera, as three numbers rather than a `<Camera3D>` child.\n *\n * A host that renders a **timeline** needs a camera a `to` command can tween\n * and a scrub can reproduce exactly, and a drag-to-orbit gesture that writes\n * the same values the timeline reads. Only read when the scene contains no\n * camera of its own, so a `<Camera3D>` child still wins.\n */\n\n /** Camera orbit about the vertical axis, in **degrees**. Animate this to spin. */\n orbit: number;\n /** Camera elevation above the ground plane, in **degrees**. */\n elevation: number;\n /** Camera distance from the origin, in scene units. */\n zoom: number;\n /** Vertical field of view, in **degrees**. */\n fov: number;\n /** Strength of the ambient fill. */\n ambientIntensity: number;\n /** Colour of the ambient fill. White leaves the meshes' own colours alone. */\n ambientColor: Color;\n /** Strength of the key light; the rim light is derived from it. */\n keyIntensity: number;\n /** Colour of the key light, and of the rim derived from it. */\n keyColor: Color;\n\n /**\n * Whether the ground plane is drawn. **Off by default** — it is an authoring\n * reference rather than part of the picture; see the property below.\n */\n showGrid: boolean;\n /** Total extent of the grid, in scene units. */\n gridSize: number;\n /** How many cells across it. */\n gridDivisions: number;\n /** Every Nth line is drawn heavier. */\n gridMajorEvery: number;\n gridColor: Color;\n gridMajorColor: Color;\n /** Whether the two coloured axis lines are drawn. Off by default, as above. */\n showAxes: boolean;\n axisXColor: Color;\n axisZColor: Color;\n /** How much of the way to the edge the grid has faded out, in `[0, 1]`. */\n gridFade: number;\n /**\n * What the grid fades into, when the node's own fills do not answer.\n *\n * **Derived, not authored.** The horizon dissolves into the first solid layer\n * of this node's `fill` — the viewport's background — and falls back to this\n * only when the stack has no solid in it to read (an empty stack, or a\n * gradient or image on its own). A grid that faded into a *different* colour\n * than the one behind it would ring the horizon with a halo, and the way to\n * make that impossible is for there to be nothing to keep in step: see\n * {@link Canvas3DView.fadeColor}.\n *\n * The same rule the engine applies to fog with no colour of its own, one\n * layer down (`View3D.scene`), and for the same reason.\n */\n gridFadeColor: Color;\n}\n", "import type { EaseSpec } from \"@/tween/ease/spec\";\nimport { loopPasses, type LoopSpec } from \"@/tween/loop\";\nimport type { Theme } from \"@/project/config\";\n\n/**\n * Re-exported as part of the document vocabulary: a loop is stored on a\n * {@link CommandSpec} the way an {@link EaseSpec} is, but its arithmetic is a\n * tween concern and lives with the tweens (`tween/loop.ts`).\n */\nexport type { LoopDirection, LoopSpec } from \"@/tween/loop\";\n\n/**\n * The clip document: what a clip **is**, as data.\n *\n * A visual clip used to be a generator function, so the only way to know what frame N\n * looked like was to run frames 0..N-1. That made a whole class of host\n * impossible — a document cannot be stored, diffed, synced or evaluated out of\n * order when its meaning is \"whatever running this code does\". These types are\n * the replacement: a clip is rows, and a frame is a pure function of them.\n *\n * The split between what is data and what is code is deliberate and total:\n *\n * - **Nodes are code.** A node type is a class registered under a string key\n * (see `document/registry.ts`). That is the extension point — a custom node\n * with its own `property` declarations, its own `renderSelf`, its own\n * `command` methods — and it is where anything a JSON value cannot express\n * (a computed lookup table, a generated point cloud) belongs.\n * - **Documents are data.** Which nodes exist, what props they carry, and what\n * happens to them over time are plain JSON.\n *\n * Everything here is JSON-serializable by construction: no functions, no class\n * instances. A document round-trips through a file or a database column without\n * a mapping layer.\n */\n\n/**\n * One node, as a row.\n *\n * Flat rather than nested, for two reasons that both bite immediately\n * otherwise: a command addresses its target by `id`, and a nested tree makes\n * \"move this node under that one\" a structural rewrite rather than a\n * single-field edit. It is also the shape a relational store already wants —\n * `parentId` is a self-referencing foreign key.\n *\n * The scene root is not special-cased here: it is the one row with\n * `id: \"\"`, `type: \"canvas2d\"` and `parentId: null` — see\n * {@link CommandSpec.targetId}.\n */\nexport interface NodeSpec {\n /** Stable identity. Command targets resolve to it; it survives reordering. */\n id: string;\n /**\n * Registry key of the node's class — `\"rect\"`, `\"text\"`, `\"canvas3d\"`, or\n * whatever a custom node registered itself as. A key the registry lacks\n * builds as an inert placeholder that keeps the row's id, props and\n * children and is reported in `buildErrors` (`missing-node.ts`), so one\n * missing component costs one node rather than the clip; `validateDocument`\n * with a registry reports it up front.\n */\n type: string;\n /**\n * The handle an **expression** names this node by: `\"=[card.x]\"` reads the\n * `x` of the node keyed `card`. See {@link CompositionDocument} and\n * `document/expression/`.\n *\n * Optional and **never generated**, unlike {@link id} — a node has one\n * because an author wrote one, which is what makes it safe to point a\n * formula at. Unique per document all the same: a second `card` would make\n * `[card.x]` mean whichever row was read last. It is a *reference*, not an\n * address — a `parentId` or a `targetId` is always an {@link id}, so there is\n * exactly one way to say which node and one way to say which handle.\n *\n * Not a display label. A host that wants one keeps it, since nothing here\n * reads it.\n */\n key?: string;\n /** Parent node id, or `null` for a direct child of the scene root. */\n parentId: string | null;\n /**\n * Position among siblings. Load-bearing rather than cosmetic: a `row`/\n * `column` parent lays its children out in exactly this order.\n */\n layerOrder: number;\n /**\n * Authored props, **sparse** — only what differs from the type's declared\n * defaults. A freshly created node is `{}`, which is what keeps a document\n * diff small and lets a change to a default actually reach existing\n * documents.\n */\n props: Record<string, unknown>;\n}\n\n/**\n * A {@link NodeSpec} placed on a clip's clock: present from {@link startAt} until\n * {@link endAt}.\n *\n * The span is a field of the node rather than a pair of commands, so a node is\n * the same row whether a still or a composition holds it — moving a subtree\n * between the two is dropping or adding these two fields, never rewriting rows.\n * Not `start`/`end`: a painted node already owns those as path-trim props.\n */\nexport interface TimedNodeSpec extends NodeSpec {\n /** Seconds from the clip's start at which the node enters the tree. Absent is `0`. */\n startAt?: number;\n /** Seconds at which it leaves. Absent is never — it stays to the clip's end. */\n endAt?: number;\n}\n\n/**\n * A **variable**: a value with a name, in neither the tree nor the command list.\n *\n * The thing that exists purely so a change can happen in *one* place. Twelve\n * nodes fading together used to be twelve `to` commands whose `at` and\n * `duration` had to be kept equal by hand; with a variable it is one\n * `variableTo` and twelve props bound to `\"=[fade]\"`.\n *\n * Every document kind declares them the same way, in `variables`. On a still\n * nothing can change one, so it is a fixed value; on a composition a\n * `variableTo`/`variableSet` command may drive it. A variable has no presence\n * span: an expression naming one that \"does not exist yet\" is a broken document,\n * so a variable holds its declared {@link value} from t=0 until a command\n * changes it.\n *\n * Nothing reads a variable except an expression (`document/expression/`), and an\n * expression can only appear in a prop — so a variable cannot read another\n * variable, and no chain of them can cycle. A prop reading another node's prop\n * (`[key.x]`) is the case that can, and `validate.ts` refuses it.\n */\nexport interface VariableSpec {\n /**\n * Stable identity. Commands target it, and `[id]` in an expression names\n * it — one key, not two, so there is nothing to keep in sync.\n */\n id: string;\n /** A display label for a host's UI. Expressions never see it. */\n name?: string;\n /**\n * What it holds before anything changes it, and the value type every\n * command that writes it is expected to produce.\n *\n * Any JSON value. A number is the common case, but a colour string, a\n * `Vector2` or a whole fill object all work — a lone `\"=[x]\"` hands the\n * value through untouched, so a variable is as expressive as the prop it\n * drives.\n */\n value: unknown;\n /**\n * How it interpolates, by registry key — `\"number\"`, `\"vector2\"`,\n * `\"vector3\"`, `\"color\"`, `\"step\"`, or anything `Registry.addLerp`\n * added. A command may override it per tween.\n *\n * Absent means `\"number\"` for a numeric {@link value} and `\"step\"` for\n * anything else: snap at the end rather than interpolate garbage.\n */\n lerp?: string;\n}\n\n/** How a command eases, as data — resolved to an `EasingFunction` once, at compile time. */\nexport type { EaseSpec } from \"@/tween/ease/spec\";\n\n/**\n * One command, **placed on the timeline**.\n *\n * The placement is the whole idea. A generator expressed sequencing by\n * suspending — running `a` to completion before `b` began — which is why order\n * of evaluation was order of execution, and why seeking backwards meant\n * starting over. A command\n * carries its own `at`, so:\n *\n * - **sequence** is `b.at === a.at + a.duration`,\n * - **parallel** is two commands sharing an `at`,\n * - **wait** is a gap between them.\n *\n * There are no `sequence`/`parallel`/`wait` primitives any more because there\n * is nothing left for them to do. And because every command's span is declared\n * rather than discovered, the scene's duration, its asset windows and each\n * node's lifespan are all readable straight off the document — see\n * `runtime/analysis.ts`.\n */\nexport interface CommandSpec {\n /** Stable identity, so a host can address and reorder one command. */\n id: string;\n /**\n * Registry key of the command — `\"to\"`, `\"set\"`, `\"variableTo\"`, or any\n * `command()` method a node class exposes (`\"moveTo\"`, `\"fillTo\"`,\n * `\"countTo\"`, …). See `document/registry.ts`. A command changes what a\n * node holds, never whether it exists — that is its {@link TimedNodeSpec} span.\n */\n type: string;\n /**\n * The node this command acts on, or `null` for the scene root — the\n * `Canvas2D` that is simultaneously the scene's layout frame, its\n * background paint and its camera (the node with `id: \"\"`,\n * `type: \"canvas2d\"`).\n *\n * A **variable** command (`\"variableTo\"`, `\"variableSet\"`) names a\n * {@link VariableSpec} here instead. The command type says which table the\n * id is looked up in, so there is no prefix to write; ids are required to be\n * unique across nodes and variables so a host grouping its timeline rows by\n * `targetId` cannot conflate the two.\n */\n targetId: string | null;\n /**\n * Seconds from the scene's start at which the command begins.\n *\n * Seconds rather than a frame index because a document has to survive an\n * fps change: the same scene rendered at 30 and at 60 must be the same\n * animation, not the same integers. Frames are derived (`at * fps`).\n */\n at: number;\n /**\n * Seconds **one pass** takes. Absent or `0` is a stamp — it applies at once.\n *\n * One pass rather than the whole span, so that {@link loop}ing a command\n * repeats it instead of squeezing the same motion into the same time: a\n * two-second spin repeated three times runs for six seconds and each turn\n * still takes two. The span is {@link commandSpan}.\n */\n duration?: number;\n /** How it eases, per pass. Absent means the command's own default. */\n easing?: EaseSpec;\n /**\n * How it repeats. Absent runs it once.\n *\n * A placement field beside {@link at} and {@link duration} rather than\n * something inside {@link args}, because repeating is not any one command's\n * business: the runtime wraps the *built* command, so `to`, `fillTo`,\n * `countTo` and a node's own `command()` all loop by the same code and a\n * newly written command type gets it for free.\n */\n loop?: LoopSpec;\n /**\n * The command's arguments. Shape is per command type: `\"to\"`/`\"set\"`'s *is*\n * the props diff, `\"variableTo\"`'s carries the `value`, a named command\n * carries its leading arguments by parameter name. Never wrapped in an extra\n * key for a command with exactly one argument.\n */\n args: Record<string, unknown>;\n}\n\n/**\n * A **still**: a node tree and nothing else.\n *\n * One frame, no timeline, no commands. It is its own document type rather than\n * \"an animation nobody ran\" because the two are edited by different tools and\n * validated by different rules — a still carrying a duration, or a half-applied\n * tween, is a document that should never have been representable.\n *\n * The scene root — `fill`, `overlay`, `flow`, `align`, `padding`, the camera\n * (`zoom`, `origin`, `heading`) — is not a separate field: it is the row in\n * {@link nodes} with `id: \"\"` and `type: \"canvas2d\"`. Omitting it gets the\n * default root.\n */\nexport interface StillDocument {\n kind: \"still\";\n /** The format it was written in — see `migrate.ts`. Absent is format 0, every document written before the field existed. */\n formatVersion?: number;\n /** Every node in the scene, including the root. Order here is irrelevant — `parentId`/`layerOrder` carry the structure. */\n nodes: NodeSpec[];\n /** Values props bind to with an expression. Fixed here — nothing on a still changes one. */\n variables?: VariableSpec[];\n /**\n * Colour tokens and typography presets this clip resolves against.\n *\n * On the clip, not only on the project, because a theme is part of what a\n * clip *looks like* — a lower third in a brand's palette is that document,\n * not that document plus a setting a host remembered to pass alongside it.\n * A project's own `theme` is the default for clips that declare none.\n */\n theme?: Theme;\n}\n\n/**\n * A **composition**: a still's node tree, placed in time, and the commands that\n * animate it.\n *\n * The nodes are the same rows a still holds, each with its own span, so when a\n * node appears is one editable field rather than an implicit consequence of\n * where a `stage.add(...)` sat in a function body — and a subtree lifted out of\n * a still drops in here unchanged.\n *\n * The scene root is the row in {@link nodes} with `id: \"\"` and\n * `type: \"canvas2d\"`, as on a still. Omitting it gets the default root; a\n * command targeting `null` animates it like any other node.\n */\nexport interface CompositionDocument {\n kind: \"composition\";\n /** The format it was written in — see `migrate.ts`. Absent is format 0, every document written before the field existed. */\n formatVersion?: number;\n /** Every node, the root included. Order is irrelevant — `parentId`/`layerOrder` carry the structure. */\n nodes: TimedNodeSpec[];\n /** Values props bind to with an expression, and that `variableTo`/`variableSet` may drive. */\n variables?: VariableSpec[];\n /** Every command. Order in the array is irrelevant; `at` is the placement. */\n commands: CommandSpec[];\n /**\n * Colour tokens and typography presets this clip resolves against.\n *\n * On the clip, not only on the project, because a theme is part of what a\n * clip *looks like* — a lower third in a brand's palette is that document,\n * not that document plus a setting a host remembered to pass alongside it.\n * A project's own `theme` is the default for clips that declare none.\n */\n theme?: Theme;\n\n /**\n * Total length in seconds. Defaults to the last moment anything happens — a\n * command's end, or a node's start or finite end — which is what you want\n * almost always; set it to hold on the final frame, or to cut a scene short.\n */\n duration?: number;\n}\n\n/**\n * An **audio document**: a bus tree placed in time, and the commands that move\n * it.\n *\n * The audio counterpart to {@link CompositionDocument}, and it reads the same\n * way for the same reason — when a sound starts is its node's `startAt`, not a\n * consequence of running something.\n *\n * The root is implicit, on the same convention a composition uses for its\n * `canvas2d`: `targetId: null` on a command, and `parentId: null` on a node,\n * name *this document's own root bus* — the row with `id: \"\"` and\n * `type: \"audioBus\"`. Omitting it gets the default one.\n *\n * There is deliberately no \"still\" case for audio: unlike a picture, sound with\n * no timeline is silence, so the degenerate case is not worth a document kind.\n */\nexport interface AudioDocument {\n kind: \"audio\";\n /** The format it was written in — see `migrate.ts`. Absent is format 0, every document written before the field existed. */\n formatVersion?: number;\n /** Every node, the root bus included. */\n nodes: TimedNodeSpec[];\n /** Values props bind to with an expression, and that `variableTo`/`variableSet` may drive. */\n variables?: VariableSpec[];\n /** Every command. Order in the array is irrelevant; `at` is the placement. */\n commands: CommandSpec[];\n /** Defaults to the last moment anything happens, same rule as {@link CompositionDocument}. */\n duration?: number;\n}\n\n/** Either **visual** document kind — the two that draw. */\nexport type VisualDocument = StillDocument | CompositionDocument;\n\n/**\n * Anything a project track can play: a picture, or sound.\n *\n * One union rather than two lists, because a track is a placement and a\n * placement does not care which. A composition already carries both halves —\n * its `canvas2d` root takes audio children as readily as visual ones — so an\n * {@link AudioDocument} is not \"the audio track kind\", it is the clip you reach\n * for when there is no picture to go with the sound.\n */\nexport type ClipDocument = VisualDocument | AudioDocument;\n\n/** Narrows a {@link VisualDocument} to a still. */\nexport function isStillDocument(doc: VisualDocument): doc is StillDocument {\n return doc.kind === \"still\";\n}\n\n/** Narrows a {@link VisualDocument} to a composition. */\nexport function isCompositionDocument(doc: VisualDocument): doc is CompositionDocument {\n return doc.kind === \"composition\";\n}\n\n/** Narrows a {@link ClipDocument} to an audio document. */\nexport function isAudioDocument(doc: ClipDocument): doc is AudioDocument {\n return doc.kind === \"audio\";\n}\n\n/** Narrows a {@link ClipDocument} to one that has a clock — anything but a still. */\nexport function hasTimeline(doc: ClipDocument): doc is CompositionDocument | AudioDocument {\n return doc.kind !== \"still\";\n}\n\n/**\n * The id the scene root answers to — the empty string, a real id rather than a\n * missing one. A host storing its root under some other id maps it here at the\n * one boundary its rows become a document.\n */\nexport const ROOT_NODE_ID = \"\";\n\n/** When a node is in the tree. `end` is `Infinity` for a node that never leaves. */\nexport interface NodeSpan {\n start: number;\n end: number;\n}\n\n/** A node's own span, as declared. A still's node — no span fields — is present always. */\nexport function nodeSpan(spec: NodeSpec | TimedNodeSpec): NodeSpan {\n const timed = spec as TimedNodeSpec;\n return { start: timed.startAt ?? 0, end: timed.endAt ?? Infinity };\n}\n\n/**\n * When a node is actually drawn: its own span intersected with every ancestor's.\n *\n * A child hangs off its parent, so it cannot outlive it — this is what the\n * runtime already does, and what an editor drawing a clipped bar or a validator\n * asking \"is the target there\" should read. Empty (`start >= end`) when the\n * spans never overlap; `undefined` for an id no row declares.\n */\nexport function effectiveSpan(nodes: readonly (NodeSpec | TimedNodeSpec)[], id: string): NodeSpan | undefined {\n return effectiveSpanIn(new Map(nodes.map((n) => [n.id, n])), id);\n}\n\n/**\n * {@link effectiveSpan} for every row at once, each ancestor chain walked once\n * however many descendants share it.\n */\nexport function effectiveSpans(nodes: readonly (NodeSpec | TimedNodeSpec)[]): Map<string, NodeSpan> {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const spans = new Map<string, NodeSpan>();\n const chain: (NodeSpec | TimedNodeSpec)[] = [];\n const inChain = new Set<string>();\n for (const start of byId.values()) {\n if (spans.has(start.id)) continue;\n chain.length = 0;\n inChain.clear();\n let above: NodeSpan | undefined;\n let spec: NodeSpec | TimedNodeSpec | undefined = start;\n while (spec) {\n const known = spans.get(spec.id);\n if (known) {\n above = known;\n break;\n }\n if (inChain.has(spec.id)) {\n // A parent cycle has no top to fold down from; an invalid document\n // gets the single-id answer for each member instead.\n for (const member of chain) spans.set(member.id, effectiveSpanIn(byId, member.id)!);\n chain.length = 0;\n break;\n }\n chain.push(spec);\n inChain.add(spec.id);\n spec = spec.parentId === null ? undefined : byId.get(spec.parentId);\n }\n for (let i = chain.length - 1; i >= 0; i--) {\n const span = nodeSpan(chain[i]);\n if (above) {\n span.start = Math.max(span.start, above.start);\n span.end = Math.min(span.end, above.end);\n }\n spans.set(chain[i].id, span);\n above = span;\n }\n }\n return spans;\n}\n\n/** @internal {@link effectiveSpan} over an id map a caller already holds. */\nexport function effectiveSpanIn(\n byId: ReadonlyMap<string, NodeSpec | TimedNodeSpec>,\n id: string,\n): NodeSpan | undefined {\n let spec = byId.get(id);\n if (!spec) return undefined;\n const span = nodeSpan(spec);\n const seen = new Set<string>();\n while (spec.parentId !== null && !seen.has(spec.id)) {\n seen.add(spec.id);\n const parent = byId.get(spec.parentId);\n if (!parent) break;\n const own = nodeSpan(parent);\n span.start = Math.max(span.start, own.start);\n span.end = Math.min(span.end, own.end);\n spec = parent;\n }\n return span;\n}\n\n/** A node with its span dropped — what a timed node becomes when it lands in a still. */\nexport function untimed(spec: NodeSpec | TimedNodeSpec): NodeSpec {\n const { startAt: _startAt, endAt: _endAt, ...rest } = spec as TimedNodeSpec;\n return rest;\n}\n\n/**\n * Seconds a command occupies: one pass, or every pass of a counted loop.\n *\n * An unlimited loop counts as **one** pass. It has no length of its own — it\n * runs for as long as there is clip — so letting it answer here would be a\n * command asking for a scene as long as it wants, which is a scene that can\n * never end.\n */\nexport function commandSpan(command: CommandSpec): number {\n const duration = command.duration ?? 0;\n if (duration <= 0 || !command.loop || command.loop.count === null) return duration;\n return duration * loopPasses(command.loop);\n}\n\n/**\n * How long a clip runs: its declared `duration`, else the last moment anything in\n * it happens — a command's end, or a node's arrival or finite departure. A still\n * has none.\n */\nexport function documentDuration(doc: ClipDocument): number {\n if (!hasTimeline(doc)) return 0;\n if (doc.duration !== undefined) return doc.duration;\n let end = 0;\n for (const command of doc.commands) {\n end = Math.max(end, command.at + commandSpan(command));\n }\n for (const node of doc.nodes) {\n if (node.startAt !== undefined) end = Math.max(end, node.startAt);\n if (node.endAt !== undefined && Number.isFinite(node.endAt)) end = Math.max(end, node.endAt);\n }\n return end;\n}\n", "import type { Size2D } from \"@/attributes/layout/size\";\nimport type { Theme } from \"@/project/config\";\n\nimport type { ClipDocument, VisualDocument } from \"./types\";\nimport { documentDuration } from \"./types\";\n\n/**\n * The **project** as data: a whole video, not one clip — and the one thing the\n * runtime plays.\n *\n * A clip document says what happens inside one composition. This says how those\n * compositions are laid against each other to make the finished thing — and it\n * is the same idea one level up, so it reads the same way: rows placed at times,\n * evaluated rather than played.\n *\n * ### One list of tracks\n *\n * A {@link ClipDocument} is a still, a composition *or* an audio document, and a\n * composition already carries both picture and sound — so there is one list for\n * all of it, not a second one for sound.\n *\n * **Array position is paint order**, first entry at the back, exactly as\n * position in a `fill` array is. A background is the first track; an overlay is\n * the last; a cross-dissolve is two tracks whose spans overlap and whose clips\n * fade themselves.\n */\nexport interface ProjectDocument {\n kind: \"project\";\n /** The format it was written in — see `migrate.ts`. Absent is format 0, every document written before the field existed. */\n formatVersion?: number;\n /** Human-readable project name. */\n name: string;\n /** Target frame rate. Defaults to 60. */\n fps?: number;\n /** Output canvas dimensions in pixels. Defaults to 1920×1080. */\n viewport?: Size2D;\n /** Visual design tokens (colors, typography) available to every clip. */\n theme?: Theme;\n /**\n * Every clip, placed. **Array position is paint order** — the first entry is\n * at the back.\n */\n tracks: Track[];\n}\n\n/**\n * One clip, placed on the project timeline.\n *\n * The clip document is **inline**, not referenced by id. A shared id would deduplicate JSON and\n * cost an id space, a resolution step and a dangling-reference failure mode — and\n * it would not buy what it looks like it buys, because the content that actually\n * repeats in an edit mostly has to *differ* per placement (a lower third with\n * different text, a chapter card with a different label).\n */\nexport interface Track {\n /**\n * Stable identity, so a host can address, reorder and diff one row — and so\n * the runtime can keep a track's built tree across an edit that leaves its\n * clip untouched.\n */\n id: string;\n /** Display label. */\n name?: string;\n /** What plays: a still, a composition, or sound. */\n clip: ClipDocument;\n /**\n * Second on the **project** timeline at which this clip's own clock reads 0.\n * Authored, never derived from the row above it, so a clip's start cannot\n * move because a neighbour changed. Defaults to 0.\n */\n startAt?: number;\n /**\n * Seconds this clip occupies. **Required.**\n *\n * So a project's length is arithmetic over its tracks rather than something\n * measured out of a media file or a timeline — a three-minute music bed\n * cannot silently make a thirty-second edit three minutes long. Longer than\n * the document holds its last frame; shorter cuts it off, which is also what\n * lets a **still**, a document with no length at all, be a backdrop.\n */\n duration: number;\n}\n\n/** Narrows an unknown document to a project. */\nexport function isProjectDocument(doc: unknown): doc is ProjectDocument {\n return typeof doc === \"object\" && doc !== null && (doc as ProjectDocument).kind === \"project\";\n}\n\n/**\n * The project a session plays, from either document it can open.\n *\n * A lone still or composition becomes the only track of a project around it.\n * Viewport and fps describe the output rather than the clip, so they come from\n * the caller.\n */\nexport function asProjectDocument(\n doc: ProjectDocument | VisualDocument,\n output: { name?: string; viewport?: Size2D; fps?: number } = {},\n): ProjectDocument {\n if (isProjectDocument(doc)) return doc;\n return {\n kind: \"project\",\n ...(doc.formatVersion !== undefined && { formatVersion: doc.formatVersion }),\n name: output.name ?? \"Untitled\",\n fps: output.fps,\n viewport: output.viewport,\n theme: doc.theme,\n tracks: [{ id: \"clip\", clip: doc, duration: documentDuration(doc) }],\n };\n}\n", "import type { ProjectDocument } from \"./project\";\nimport type { ClipDocument } from \"./types\";\n\n/**\n * Saved documents outlive the engine that wrote them, so each carries the\n * format it was written in and this module carries every step from one format\n * to the next.\n *\n * A step is a pure function over JSON: it never mutates what it is handed and\n * never needs a registry, so a host can run it over a row it has not opened\n * and a test can pin it with two literals. Steps only ever go up; a document\n * newer than the engine is refused with {@link DocumentTooNewError} rather than\n * read as whatever it happens to resemble.\n */\n\n/** The format this engine reads natively and writes. A document without `formatVersion` is format 0. */\nexport const DOCUMENT_FORMAT_VERSION = 2;\n\n/** A document written by a newer engine than this one. Thrown before anything reads it. */\nexport class DocumentTooNewError extends Error {\n readonly version: number;\n readonly supported: number;\n\n constructor(version: number, supported: number = DOCUMENT_FORMAT_VERSION) {\n super(\n `This document is format ${version}, newer than this engine reads (format ${supported}). ` +\n `Open it with a newer engine.`,\n );\n this.name = \"DocumentTooNewError\";\n this.version = version;\n this.supported = supported;\n }\n}\n\n/** A document as JSON, before anything has checked its shape. */\nexport type JsonDocument = Record<string, unknown>;\n\n/** One thing a migration changed. `path` locates it as a `ValidationIssue`'s does. */\nexport interface DocumentChange {\n /** The format the step that made it read. */\n from: number;\n path: string;\n message: string;\n}\n\n/** Records a change at `path`, relative to the document the step was handed. */\nexport type NoteChange = (path: string, message: string) => void;\n\n/** The step from format {@link from} to `from + 1`. */\nexport interface DocumentMigration {\n readonly from: number;\n /** What the format change was, for a changelog or a host's log. */\n readonly description: string;\n /** Run on every clip document, standalone or inside a project's track. */\n readonly clip?: (clip: JsonDocument, note: NoteChange) => JsonDocument;\n /** Run on a project's own fields, before its clips. */\n readonly project?: (project: JsonDocument, note: NoteChange) => JsonDocument;\n}\n\nexport interface DocumentMigrationResult<T> {\n /** The input itself when it was already current; otherwise a new document stamped with {@link to}. */\n document: T;\n from: number;\n to: number;\n changes: DocumentChange[];\n}\n\n/**\n * Every step, oldest first. A release that changes what a stored document\n * means adds the next one here, bumps {@link DOCUMENT_FORMAT_VERSION}, and\n * gives the step a test (`tests/migrate.test.ts`).\n */\nexport const DOCUMENT_MIGRATIONS: readonly DocumentMigration[] = [\n {\n from: 0,\n description: \"Documents start carrying `formatVersion`; a clip's retired `constants` rows become `variables`.\",\n clip: (clip, note) => {\n if (!Array.isArray(clip.constants)) return clip;\n const { constants, ...rest } = clip;\n const variables = Array.isArray(rest.variables) ? [...rest.variables] : [];\n for (const row of constants as unknown[]) {\n if (typeof row !== \"object\" || row === null) {\n variables.push(row);\n continue;\n }\n const { kind: _kind, ...variable } = row as Record<string, unknown>;\n variables.push(variable);\n }\n note(\"constants\", `${constants.length} constant row(s) moved into \\`variables\\`.`);\n return { ...rest, variables };\n },\n },\n {\n from: 1,\n description:\n \"SkSL is retired: every shader fill, shader effect and shader pack written in it says `language: \\\"sksl\\\"`, \" +\n \"the `sksl` effect key becomes `shader`, and `coords` is dropped.\",\n clip: (clip, note) => retireSkSL(clip, \"\", note) as JsonDocument,\n },\n];\n\n/** SkSL's entry point or an SkSL `uniform` declaration, neither of which a WGSL source can contain. */\nconst SKSL_SOURCE = /\\b(?:half4|float4|vec4)\\s+main\\s*\\(|^\\s*uniform\\s+\\w+\\s+\\w+/m;\n\ntype JsonObject = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is JsonObject =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// Fills and effects sit in node props, named fills, effect and filter arrays,\n// command values and tween keyframes alike, so the whole clip is walked.\nfunction retireSkSL(value: unknown, path: string, note: NoteChange): unknown {\n if (Array.isArray(value)) {\n let out: unknown[] | undefined;\n value.forEach((item, i) => {\n const next = retireSkSL(item, `${path}[${i}]`, note);\n if (next !== item) (out ??= [...value])[i] = next;\n });\n return out ?? value;\n }\n if (!isObject(value)) return value;\n let out: JsonObject | undefined;\n for (const [key, item] of Object.entries(value)) {\n const next = retireSkSL(item, path ? `${path}.${key}` : key, note);\n if (next !== item) (out ??= { ...value })[key] = next;\n }\n return retireShader(out ?? value, path, note);\n}\n\nfunction retireShader(shader: JsonObject, path: string, note: NoteChange): JsonObject {\n const legacyKey = shader.type === \"sksl\";\n const isShader = legacyKey\n || (shader.type === \"shader\" && (typeof shader.source === \"string\" || typeof shader.shader === \"string\"))\n || ((shader.scope === \"fill\" || shader.scope === \"effect\") && typeof shader.source === \"string\");\n if (!isShader) return shader;\n\n const out: JsonObject = { ...shader };\n if (legacyKey) out.type = \"shader\";\n const moved = out.type === \"shader\" && typeof out.shader === \"string\" && out.source === undefined;\n if (moved) {\n out.source = out.shader;\n delete out.shader;\n }\n // The `sksl` key meant SkSL whatever its source looked like, unless it said otherwise.\n const sksl = out.language === \"sksl\"\n || (out.language === undefined && (legacyKey || SKSL_SOURCE.test(typeof out.source === \"string\" ? out.source : \"\")));\n const stamped = sksl && out.language === undefined;\n if (stamped) out.language = \"sksl\";\n const hadCoords = \"coords\" in out;\n delete out.coords;\n\n if (sksl) note(path, \"SkSL shaders no longer draw; port it to WGSL.\");\n else if (legacyKey) note(path, \"The retired `sksl` effect key is now `shader`.\");\n else if (moved) note(path, \"The shader's `shader` field is now `source`.\");\n else if (hadCoords) note(path, \"`coords` dropped; it only ever applied to SkSL.\");\n return legacyKey || moved || stamped || hadCoords ? out : shader;\n}\n\n/** The format a document says it is in: its `formatVersion`, or 0 when it has none. */\nexport function documentFormatVersion(doc: unknown): number {\n if (typeof doc !== \"object\" || doc === null) return 0;\n const version = (doc as { formatVersion?: unknown }).formatVersion;\n if (version === undefined) return 0;\n if (typeof version !== \"number\" || !Number.isInteger(version) || version < 0) {\n throw new TypeError(`formatVersion must be a whole number >= 0 (got ${JSON.stringify(version)}).`);\n }\n return version;\n}\n\n/**\n * Bring a still, composition, audio or project document up to\n * {@link DOCUMENT_FORMAT_VERSION}.\n *\n * A clip inside a project with no `formatVersion` of its own is read at the\n * project's, since it was written alongside it. Anything that is not a\n * document comes back untouched, for validation to describe.\n */\nexport function migrateDocument<T extends ProjectDocument | ClipDocument>(doc: T): DocumentMigrationResult<T>;\nexport function migrateDocument(doc: unknown): DocumentMigrationResult<unknown>;\nexport function migrateDocument(doc: unknown): DocumentMigrationResult<unknown> {\n return migrateDocumentWith(doc, DOCUMENT_MIGRATIONS, DOCUMENT_FORMAT_VERSION);\n}\n\n/** @internal {@link migrateDocument} over a given list of steps, for a test pinning the runner. */\nexport function migrateDocumentWith(\n doc: unknown,\n migrations: readonly DocumentMigration[],\n target: number,\n): DocumentMigrationResult<unknown> {\n const from = documentFormatVersion(doc);\n if (from > target) throw new DocumentTooNewError(from, target);\n if (typeof doc !== \"object\" || doc === null || Array.isArray(doc)) {\n return { document: doc, from, to: from, changes: [] };\n }\n const changes: DocumentChange[] = [];\n const json = doc as JsonDocument;\n const migrated = json.kind === \"project\"\n ? migrateProject(json, from, migrations, target, changes)\n : migrateClip(json, from, migrations, target, changes, \"\");\n return { document: migrated, from, to: target, changes };\n}\n\nfunction stepsBetween(from: number, to: number, migrations: readonly DocumentMigration[]): DocumentMigration[] {\n const steps: DocumentMigration[] = [];\n for (let version = from; version < to; version++) {\n const step = migrations.find((m) => m.from === version);\n if (!step) throw new Error(`No document migration from format ${version} to ${version + 1}.`);\n steps.push(step);\n }\n return steps;\n}\n\nfunction noteInto(changes: DocumentChange[], from: number, prefix: string): NoteChange {\n return (path, message) => changes.push({ from, path: prefix && path ? `${prefix}.${path}` : prefix || path, message });\n}\n\n/** `stamp` false leaves a clip that inherits its project's version without a field of its own. */\nfunction migrateClip(\n clip: JsonDocument,\n from: number,\n migrations: readonly DocumentMigration[],\n target: number,\n changes: DocumentChange[],\n prefix: string,\n stamp = true,\n): JsonDocument {\n if (from === target) return clip;\n let out = clip;\n for (const step of stepsBetween(from, target, migrations)) {\n if (step.clip) out = step.clip(out, noteInto(changes, step.from, prefix));\n }\n return stamp ? { ...out, formatVersion: target } : out;\n}\n\nfunction migrateProject(\n project: JsonDocument,\n from: number,\n migrations: readonly DocumentMigration[],\n target: number,\n changes: DocumentChange[],\n): JsonDocument {\n let out = project;\n if (from < target) {\n for (const step of stepsBetween(from, target, migrations)) {\n if (step.project) out = step.project(out, noteInto(changes, step.from, \"\"));\n }\n }\n let tracksChanged = false;\n const tracks = Array.isArray(out.tracks)\n ? (out.tracks as unknown[]).map((track, i) => {\n if (typeof track !== \"object\" || track === null) return track;\n const clip = (track as { clip?: unknown }).clip;\n if (typeof clip !== \"object\" || clip === null || Array.isArray(clip)) return track;\n const own = (clip as { formatVersion?: unknown }).formatVersion !== undefined;\n const version = own ? documentFormatVersion(clip) : from;\n if (version > target) throw new DocumentTooNewError(version, target);\n const next = migrateClip(clip as JsonDocument, version, migrations, target, changes, `tracks[${i}].clip`, own);\n if (next === clip) return track;\n tracksChanged = true;\n return { ...(track as object), clip: next };\n })\n : out.tracks;\n if (from === target && !tracksChanged) return project;\n return { ...out, ...(tracksChanged ? { tracks } : {}), formatVersion: target };\n}\n", "import { isEaseCurve } from \"@/tween/ease/curve\";\nimport { EASE_KINDS } from \"@/tween/ease/spec\";\nimport { expressionOps } from \"./expression/ops\";\nimport { DOCUMENT_FORMAT_VERSION } from \"./migrate\";\nimport type { Registry } from \"./registry\";\nimport type {\n AudioDocument,\n ClipDocument,\n CommandSpec,\n CompositionDocument,\n EaseSpec,\n LoopSpec,\n NodeSpec,\n StillDocument,\n TimedNodeSpec,\n VariableSpec,\n} from \"./types\";\nimport { effectiveSpanIn } from \"./types\";\n\n/**\n * Schema validation for a {@link VisualDocument}.\n *\n * Hand-rolled rather than pulled from a schema library because\n * `@motionscript/core` has **no runtime dependencies**, and a renderer that\n * makes every consumer install a validator to draw a rectangle has made the\n * wrong trade.\n *\n * It checks *structure*, not props. Whether `cornerRadius` accepts a string is\n * the node class's business — it declares that with `property`, and it is\n * checked where it is applied. What can only be checked here is what spans\n * rows: that a parent exists, that the tree has no cycle, that a command's\n * target is present when the command runs. Audio rows are the exception: a\n * ramp or a transition is JSON their nodes read unchecked, and one a device\n * cannot schedule fails long after the document was accepted.\n */\n\n/** One problem with a document. `path` locates it, JSON-Pointer style. */\nexport interface ValidationIssue {\n /** Where the problem is — `\"nodes[2].parentId\"`, `\"commands[7].at\"`. */\n path: string;\n /** What is wrong, in a sentence a host can show. */\n message: string;\n}\n\n/** What {@link validateDocument} checks against beyond the format itself. */\nexport interface ValidateOptions {\n /**\n * Also report every node type and command this registry cannot build — the\n * strict check a build no longer makes, since a build stands an inert\n * placeholder in for an unknown type and skips an unknown command.\n */\n registry?: Registry;\n}\n\n/** The result of {@link validateDocument}. */\nexport interface ValidationResult {\n valid: boolean;\n issues: ValidationIssue[];\n}\n\nconst LOOP_DIRECTIONS = new Set([\"normal\", \"reverse\", \"alternate\"]);\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** A finite, non-negative number — what every time and duration field must be. */\nfunction isTime(v: unknown): v is number {\n return typeof v === \"number\" && Number.isFinite(v) && v >= 0;\n}\n\nfunction checkEase(ease: unknown, path: string, issues: ValidationIssue[]): void {\n if (ease === undefined) return;\n if (!isPlainObject(ease)) {\n issues.push({ path, message: \"easing must be an object with a `kind`.\" });\n return;\n }\n const { kind, args } = ease as Partial<EaseSpec>;\n if (typeof kind !== \"string\" || !EASE_KINDS.has(kind)) {\n issues.push({\n path: `${path}.kind`,\n message: `easing kind must be one of ${[...EASE_KINDS].join(\", \")} (got ${JSON.stringify(kind)}).`,\n });\n return;\n }\n if (kind === \"custom\" && args !== undefined && typeof args !== \"string\" && !isEaseCurve(args)) {\n issues.push({\n path: `${path}.args`,\n message: \"a custom easing's args must be its curve — two or more `{ x, y }` points — or a registered ease's key.\",\n });\n }\n}\n\n/** An audio ease runs on a device with no `Registry`, so a custom one has to be its drawn curve. */\nfunction checkAudioEase(ease: unknown, path: string, issues: ValidationIssue[]): void {\n checkEase(ease, path, issues);\n if (isPlainObject(ease) && ease.kind === \"custom\" && !isEaseCurve(ease.args)) {\n issues.push({ path: `${path}.args`, message: \"an audio ease cannot name a registered ease; draw its curve (two or more `{ x, y }` points) instead.\" });\n }\n}\n\nfunction checkParam(value: unknown, path: string, issues: ValidationIssue[]): void {\n if (value === undefined || (typeof value === \"number\" && Number.isFinite(value)) || expressionOps.isSource(value)) return;\n if (!isPlainObject(value) || !Array.isArray(value.keys)) {\n issues.push({ path, message: \"must be a finite number, an expression or a ramp, `{ keys: [{ at, value }, …] }`.\" });\n return;\n }\n value.keys.forEach((key: unknown, i: number) => {\n const at = `${path}.keys[${i}]`;\n if (!isPlainObject(key)) {\n issues.push({ path: at, message: \"a ramp key must be an object.\" });\n return;\n }\n if ((key.at === undefined) === (key.before === undefined) || !isTime(key.at ?? key.before)) {\n issues.push({ path: at, message: \"a ramp key needs exactly one of `at` (seconds after the start) or `before` (seconds before the end), >= 0.\" });\n }\n if (typeof key.value !== \"number\" || !Number.isFinite(key.value)) {\n issues.push({ path: `${at}.value`, message: \"a ramp key's value must be a finite number.\" });\n }\n checkAudioEase(key.ease, `${at}.ease`, issues);\n });\n}\n\nconst TRANSITION_KEYS = new Set([\"duration\", \"curve\"]);\n\nfunction checkTransition(transition: unknown, path: string, issues: ValidationIssue[]): void {\n if (transition === undefined) return;\n if (!isPlainObject(transition)) {\n issues.push({ path, message: \"a transition must be an object, `{ duration, curve? }`.\" });\n return;\n }\n if (!isTime(transition.duration)) {\n issues.push({ path: `${path}.duration`, message: \"a transition's duration must be a finite number of seconds >= 0.\" });\n }\n if (transition.curve !== undefined && transition.curve !== \"equalPower\") checkAudioEase(transition.curve, `${path}.curve`, issues);\n for (const key of Object.keys(transition)) {\n if (!TRANSITION_KEYS.has(key)) issues.push({ path: `${path}.${key}`, message: `a transition has no \"${key}\" (yet): only duration and curve.` });\n }\n}\n\nfunction checkAudioProps(type: string, props: Record<string, unknown>, path: string, issues: ValidationIssue[]): void {\n if (\"filters\" in props) {\n issues.push({ path: `${path}.filters`, message: \"audio `filters` was renamed to `effects`.\" });\n }\n for (const name of [\"volume\", \"pan\", ...(type === \"sound\" ? [\"speed\"] : [])]) checkParam(props[name], `${path}.${name}`, issues);\n if (type === \"sound\" && props.loop === true && isPlainObject(props.speed)) {\n issues.push({ path: `${path}.speed`, message: \"a looping sound cannot ramp its speed: there is no one pass of the source for the ramp to run over.\" });\n }\n const effects = props.effects;\n if (effects !== undefined) {\n const list = Array.isArray(effects) ? effects : [effects];\n list.forEach((effect: unknown, i: number) => {\n const at = Array.isArray(effects) ? `${path}.effects[${i}]` : `${path}.effects`;\n if (!isPlainObject(effect) || typeof effect.type !== \"string\") {\n issues.push({ path: at, message: \"an effect must be an object with a `type`.\" });\n return;\n }\n for (const [field, value] of Object.entries(effect)) {\n if (field !== \"type\") checkParam(value, `${at}.${field}`, issues);\n }\n });\n }\n checkTransition(props.transitionIn, `${path}.transitionIn`, issues);\n checkTransition(props.transitionOut, `${path}.transitionOut`, issues);\n}\n\nfunction checkLoop(loop: unknown, path: string, issues: ValidationIssue[]): void {\n if (loop === undefined) return;\n if (!isPlainObject(loop)) {\n issues.push({ path, message: \"loop must be an object with a `count`.\" });\n return;\n }\n const { direction, count } = loop as Partial<LoopSpec>;\n if (count !== null && (typeof count !== \"number\" || !Number.isInteger(count) || count < 0)) {\n issues.push({\n path: `${path}.count`,\n message: \"loop count must be a whole number of repeats >= 0, or null to repeat for the rest of the clip.\",\n });\n }\n if (direction !== undefined && !LOOP_DIRECTIONS.has(direction)) {\n issues.push({\n path: `${path}.direction`,\n message: `loop direction must be one of ${[...LOOP_DIRECTIONS].join(\", \")} (got ${JSON.stringify(direction)}).`,\n });\n }\n}\n\nfunction checkNodeSpec(node: unknown, path: string, issues: ValidationIssue[]): node is NodeSpec {\n if (!isPlainObject(node)) {\n issues.push({ path, message: \"node must be an object.\" });\n return false;\n }\n let ok = true;\n const { id, type, parentId, layerOrder, props, key } = node as Partial<NodeSpec>;\n\n // \"\" is reserved for the scene root (see `checkRootShape`) — every other\n // node needs a real id, since an empty one could never be a command's target.\n if (typeof id !== \"string\") {\n issues.push({ path: `${path}.id`, message: \"id must be a string.\" });\n ok = false;\n }\n if (typeof type !== \"string\" || type.length === 0) {\n issues.push({ path: `${path}.type`, message: \"type must be a non-empty string.\" });\n ok = false;\n }\n if (parentId !== null && typeof parentId !== \"string\") {\n issues.push({ path: `${path}.parentId`, message: \"parentId must be a node id or null.\" });\n ok = false;\n }\n if (typeof layerOrder !== \"number\" || !Number.isFinite(layerOrder)) {\n issues.push({ path: `${path}.layerOrder`, message: \"layerOrder must be a finite number.\" });\n ok = false;\n }\n if (!isPlainObject(props)) {\n issues.push({ path: `${path}.props`, message: \"props must be an object (`{}` when nothing is set).\" });\n ok = false;\n } else if (type === \"sound\" || type === \"audioBus\") {\n checkAudioProps(type, props, `${path}.props`, issues);\n }\n if (key !== undefined) {\n if (typeof key !== \"string\" || key.length === 0) {\n issues.push({ path: `${path}.key`, message: \"key must be a non-empty string when present.\" });\n ok = false;\n } else if (key.includes(\"]\") || key.includes(\".\")) {\n // `[key.prop]` is the reference syntax, so either character names\n // something an expression could never spell.\n issues.push({\n path: `${path}.key`,\n message: `node key \"${key}\" cannot contain \"]\" or \".\" — it is referenced as \"[${key}.prop]\".`,\n });\n ok = false;\n }\n }\n return ok;\n}\n\n/** One node spec, with where it was declared, so an issue can point at it. */\ninterface NodeSite {\n spec: NodeSpec;\n path: string;\n}\n\n/**\n * Gather every authored {@link NodeSpec.key} and check that no two rows claim one.\n *\n * Keys are their own namespace rather than part of {@link checkIdSpace}'s, and the\n * grammar is why: `[x]` is always a variable and `[x.p]` is always a\n * node, so the two can never be confused for one another — and a key is never a\n * `targetId`, which is the collision that one exists to prevent. Unique among keys\n * all the same: two rows keyed `card` would make `[card.x]` read whichever the\n * build reached last.\n */\nfunction checkNodeKeys(sites: readonly NodeSite[], issues: ValidationIssue[]): Map<string, NodeSite> {\n const byKey = new Map<string, NodeSite>();\n for (const site of sites) {\n const key = site.spec.key;\n if (typeof key !== \"string\" || key.length === 0) continue;\n const existing = byKey.get(key);\n if (existing) {\n issues.push({\n path: `${site.path}.key`,\n message: `duplicate node key \"${key}\" (also declared at ${existing.path}).`,\n });\n continue;\n }\n byKey.set(key, site);\n }\n return byKey;\n}\n\n/**\n * The row with `id: \"\"` is the document's root, and must be unparented and of\n * the type that document kind's root is.\n *\n * `canvas2d` for a scene, `audioBus` for an audio document — one rule, one\n * parameter, because the *convention* is the same in both: the root is an\n * ordinary row rather than a special field, and `targetId: null` names it.\n */\nfunction checkRootShape(\n spec: NodeSpec,\n path: string,\n rootType: string,\n issues: ValidationIssue[],\n): void {\n if (spec.id !== \"\") return;\n if (spec.type !== rootType || spec.parentId !== null) {\n issues.push({\n path,\n message: `the node with id \"\" is this document's root and must be \\`{ type: \"${rootType}\", parentId: null }\\`.`,\n });\n }\n}\n\nfunction checkCommandSpec(cmd: unknown, path: string, issues: ValidationIssue[]): cmd is CommandSpec {\n if (!isPlainObject(cmd)) {\n issues.push({ path, message: \"command must be an object.\" });\n return false;\n }\n let ok = true;\n const { id, type, targetId, at, duration, args } = cmd as Partial<CommandSpec>;\n\n if (typeof id !== \"string\" || id.length === 0) {\n issues.push({ path: `${path}.id`, message: \"id must be a non-empty string.\" });\n ok = false;\n }\n if (typeof type !== \"string\" || type.length === 0) {\n issues.push({ path: `${path}.type`, message: \"type must be a non-empty string.\" });\n ok = false;\n }\n if (targetId !== null && typeof targetId !== \"string\") {\n issues.push({ path: `${path}.targetId`, message: \"targetId must be a node id, or null for the scene root.\" });\n ok = false;\n }\n if (!isTime(at)) {\n issues.push({ path: `${path}.at`, message: \"at must be a finite number of seconds >= 0.\" });\n ok = false;\n }\n if (duration !== undefined && !isTime(duration)) {\n issues.push({ path: `${path}.duration`, message: \"duration must be a finite number of seconds >= 0.\" });\n ok = false;\n }\n if (!isPlainObject(args)) {\n issues.push({ path: `${path}.args`, message: \"args must be an object (`{}` when there are none).\" });\n ok = false;\n }\n checkEase((cmd as Partial<CommandSpec>).easing, `${path}.easing`, issues);\n checkLoop((cmd as Partial<CommandSpec>).loop, `${path}.loop`, issues);\n return ok;\n}\n\n/** One declared variable, with where it was declared, so an issue can point at it. */\ninterface VariableSite {\n spec: VariableSpec;\n path: string;\n}\n\nfunction checkVariableSpec(v: unknown, path: string, issues: ValidationIssue[]): v is VariableSpec {\n if (!isPlainObject(v)) {\n issues.push({ path, message: \"variable must be an object.\" });\n return false;\n }\n let ok = true;\n const { id, name, value, lerp } = v as Partial<VariableSpec>;\n\n if (typeof id !== \"string\" || id.length === 0) {\n issues.push({ path: `${path}.id`, message: \"id must be a non-empty string.\" });\n ok = false;\n } else if (id.includes(\"]\")) {\n // `[id]` is the reference syntax, so a `]` in an id names something an\n // expression could never spell.\n issues.push({ path: `${path}.id`, message: `variable id \"${id}\" cannot contain \"]\" — it is referenced as \"[${id}]\".` });\n ok = false;\n }\n if (name !== undefined && typeof name !== \"string\") {\n issues.push({ path: `${path}.name`, message: \"name must be a string when present.\" });\n ok = false;\n }\n if (!(\"value\" in (v as object))) {\n issues.push({ path: `${path}.value`, message: \"value is required — a variable is what it holds before anything changes it.\" });\n ok = false;\n } else if (expressionOps.isSource(value)) {\n issues.push({\n path: `${path}.value`,\n message: \"a variable holds a value, not an expression — only a node prop can be bound.\",\n });\n ok = false;\n }\n if (lerp !== undefined && typeof lerp !== \"string\") {\n issues.push({ path: `${path}.lerp`, message: \"lerp must be a registered lerp key when present.\" });\n ok = false;\n }\n return ok;\n}\n\n/** Read a document's `variables` rows, checking each row's shape. */\nfunction variableRows(rows: unknown, issues: ValidationIssue[]): VariableSite[] {\n if (rows === undefined) return [];\n if (!Array.isArray(rows)) {\n issues.push({ path: \"variables\", message: \"variables must be an array.\" });\n return [];\n }\n const sites: VariableSite[] = [];\n rows.forEach((v, i) => {\n const path = `variables[${i}]`;\n if (checkVariableSpec(v, path, issues)) sites.push({ spec: v, path });\n });\n return sites;\n}\n\n/** Gather every declared variable and check that no id is claimed twice. */\nfunction checkVariables(sites: VariableSite[], issues: ValidationIssue[]): Map<string, VariableSite> {\n const byId = new Map<string, VariableSite>();\n for (const site of sites) {\n const existing = byId.get(site.spec.id);\n if (existing) {\n issues.push({\n path: `${site.path}.id`,\n message: `duplicate variable id \"${site.spec.id}\" (also declared at ${existing.path}).`,\n });\n continue;\n }\n byId.set(site.spec.id, site);\n }\n return byId;\n}\n\n/**\n * A reference split into the node key and prop it names, or `undefined` when it\n * has no dot and so names a variable instead.\n *\n * The dot is the whole discriminator, in the parser (which hands the bracket's\n * contents over as one opaque name), here, and in `ClipTimeline`.\n */\nfunction splitNodeRef(ref: string): { key: string; prop: string } | undefined {\n const dot = ref.indexOf(\".\");\n return dot < 0 ? undefined : { key: ref.slice(0, dot), prop: ref.slice(dot + 1) };\n}\n\n/**\n * Check every expression inside an authored value.\n *\n * Three failures worth catching before anything is built: a formula that does not\n * parse, one naming a variable nothing declares, and one naming a node key\n * nothing is keyed with. All are silent otherwise — the first would reach the\n * timeline as a throw from deep inside a build, and the other two would bind a\n * prop to nothing at all.\n */\nfunction checkExpressions(\n value: unknown,\n path: string,\n declared: ReadonlySet<string>,\n keyed: ReadonlySet<string>,\n issues: ValidationIssue[],\n): void {\n for (const site of expressionOps.collect(value, path)) {\n const parsed = expressionOps.tryParse(site.source);\n if (\"error\" in parsed) {\n issues.push({ path: site.path, message: parsed.error });\n continue;\n }\n for (const ref of parsed.expression.refs) {\n const node = splitNodeRef(ref);\n if (!node) {\n if (declared.has(ref)) continue;\n issues.push({\n path: site.path,\n message: keyed.has(ref)\n ? `expression references \"[${ref}]\", which is a node key — a node is not a value, ` +\n `so name the prop too: \"[${ref}.x]\".`\n : `expression references \"[${ref}]\", which this document does not declare. ` +\n `Declared: ${[...declared].map((k) => `[${k}]`).join(\", \") || \"none\"}.`,\n });\n continue;\n }\n if (node.key.length === 0 || node.prop.length === 0 || node.prop.includes(\".\")) {\n issues.push({\n path: site.path,\n message: `expression references \"[${ref}]\", which is not a node reference — one is \"[key.prop]\".`,\n });\n continue;\n }\n if (keyed.has(node.key)) continue;\n issues.push({\n path: site.path,\n message:\n `expression references \"[${ref}]\", but no node in this document is keyed \"${node.key}\". ` +\n `Keyed: ${[...keyed].join(\", \") || \"none\"}.`,\n });\n }\n }\n}\n\n/** One expression-bound prop: what it is called in a reference, and what it reads. */\ninterface BoundProp {\n /** `\"key.prop\"` — exactly what another prop would write inside `[…]`. */\n id: string;\n /** Where the prop was authored, so an issue points at the row. */\n path: string;\n /** The `\"key.prop\"`s this prop's expressions read. */\n reads: string[];\n}\n\n/**\n * Collect the {@link BoundProp}s one props bag contributes.\n *\n * Per *top-level* prop, because that is the granularity a binding is installed at\n * — `bindProps` walks a bag's own keys and binds each — so a formula nested inside\n * `padding` makes `padding` the prop that reads.\n */\nfunction boundProps(key: string, props: unknown, path: string, out: BoundProp[]): void {\n if (!isPlainObject(props)) return;\n for (const prop of Object.keys(props)) {\n const reads: string[] = [];\n for (const site of expressionOps.collect(props[prop], `${path}.${prop}`)) {\n const parsed = expressionOps.tryParse(site.source);\n if (\"error\" in parsed) continue;\n for (const ref of parsed.expression.refs) {\n if (splitNodeRef(ref)) reads.push(ref);\n }\n }\n if (reads.length > 0) out.push({ id: `${key}.${prop}`, path: `${path}.${prop}`, reads });\n }\n}\n\n/**\n * Refuse a prop that reads a prop that reads it back.\n *\n * A failure mode `[key.prop]` introduces and variables never had: nothing can read\n * a variable, so no chain of them could close. At runtime it does not crash —\n * `PropSlot.get` refuses to re-enter and hands back the last value it settled on —\n * which is exactly why it is caught here: the cost of a cycle is otherwise a frame\n * that quietly disagrees with the document.\n *\n * Edges are per prop, not per node. `a.x → b.y → a.z` terminates, and rejecting it\n * would reject a working document.\n */\nfunction checkExpressionCycles(bound: readonly BoundProp[], issues: ValidationIssue[]): void {\n const byId = new Map(bound.map((b) => [b.id, b]));\n const settled = new Set<string>();\n const stack: string[] = [];\n const reported = new Set<string>();\n\n const walk = (id: string): void => {\n const entry = byId.get(id);\n // A prop nothing binds cannot continue a chain: it holds a literal.\n if (!entry || settled.has(id)) return;\n const at = stack.indexOf(id);\n if (at >= 0) {\n if (!reported.has(id)) {\n const cycle = [...stack.slice(at), id];\n for (const member of cycle) reported.add(member);\n issues.push({\n path: entry.path,\n message: `expression cycle ${cycle.join(\" → \")} — a prop cannot read a prop that reads it back.`,\n });\n }\n return;\n }\n stack.push(id);\n for (const next of entry.reads) walk(next);\n stack.pop();\n settled.add(id);\n };\n\n for (const entry of bound) walk(entry.id);\n}\n\n/**\n * Check that ids are unique, every `parentId` resolves, and no node is its own\n * ancestor.\n *\n * The cycle check is not defensive padding: a parent loop makes the layout walk\n * recurse until the stack overflows, and the trace points at the layout engine\n * rather than at the two rows that point at each other.\n */\nfunction checkTree(sites: readonly NodeSite[], issues: ValidationIssue[]): void {\n // `sites` holds only the rows that passed their shape check, so a position in\n // it is not a position in the document: every issue path comes from the\n // site, which remembers where its row was authored.\n const bySite = new Map<string, NodeSite>();\n for (const site of sites) {\n if (bySite.has(site.spec.id)) {\n issues.push({ path: `${site.path}.id`, message: `duplicate node id \"${site.spec.id}\".` });\n continue;\n }\n bySite.set(site.spec.id, site);\n }\n\n for (const site of sites) {\n const parent = site.spec.parentId;\n if (parent !== null && !bySite.has(parent)) {\n issues.push({\n path: `${site.path}.parentId`,\n message: `parentId \"${parent}\" is not a node in this document.`,\n });\n }\n }\n\n // Walk each node to the root; a revisit within one walk is a cycle.\n const settled = new Set<string>();\n for (const { spec: node } of sites) {\n if (settled.has(node.id)) continue;\n const seen = new Set<string>();\n let cursor: NodeSpec | undefined = node;\n while (cursor) {\n if (seen.has(cursor.id)) {\n issues.push({\n path: `${bySite.get(cursor.id)?.path}.parentId`,\n message: `node \"${cursor.id}\" is its own ancestor — parent chain forms a cycle.`,\n });\n break;\n }\n seen.add(cursor.id);\n if (settled.has(cursor.id)) break;\n const parentId: string | null = cursor.parentId;\n cursor = parentId === null ? undefined : bySite.get(parentId)?.spec;\n }\n for (const id of seen) settled.add(id);\n }\n}\n\n/**\n * Nodes and variables share one id space.\n *\n * They have to: a command names its target with one field, and which table that\n * field is looked up in is a fact of the command's *type*. Two rows answering to\n * one id would still resolve correctly here, but a host's timeline groups its\n * rows by `targetId` — so the collision would show up as two unrelated things\n * drawn on the same track, which is not a bug anyone would think to look for in\n * the document.\n *\n * A {@link NodeSpec.key} is deliberately *not* in this space — see\n * {@link checkNodeKeys}.\n */\nfunction checkIdSpace(\n nodes: NodeSpec[],\n variables: Map<string, VariableSite>,\n issues: ValidationIssue[],\n): void {\n for (const node of nodes) {\n const clash = variables.get(node.id);\n if (clash) {\n issues.push({\n path: `${clash.path}.id`,\n message: `\"${node.id}\" is already a node id — nodes and variables share one id space.`,\n });\n }\n }\n}\n\n/**\n * Refuse the fields the format folded away, by name.\n *\n * A document written before nodes carried their own spans would otherwise fail\n * as \"nodes must be an array\" or an unresolved `[id]`, neither of which names\n * the fix.\n */\nfunction checkRetiredFields(doc: object, issues: ValidationIssue[]): void {\n if ((doc as { constants?: unknown }).constants !== undefined) {\n issues.push({\n path: \"constants\",\n message: \"constants were merged into `variables` — move each row there and drop its `kind`.\",\n });\n }\n}\n\n/** A `formatVersion`, when present, is one this engine can read. Absent is format 0. */\nfunction checkFormatVersion(doc: object, issues: ValidationIssue[]): void {\n const version = (doc as { formatVersion?: unknown }).formatVersion;\n if (version === undefined) return;\n if (typeof version !== \"number\" || !Number.isInteger(version) || version < 0) {\n issues.push({ path: \"formatVersion\", message: \"formatVersion must be a whole number >= 0 when present.\" });\n } else if (version > DOCUMENT_FORMAT_VERSION) {\n issues.push({\n path: \"formatVersion\",\n message: `format ${version} is newer than this engine reads (${DOCUMENT_FORMAT_VERSION}) — open it with a newer engine.`,\n });\n }\n}\n\n/** A project's fields from before `tracks` was the one list, and where each went. */\nconst RETIRED_PROJECT_FIELDS: Readonly<Record<string, string>> = {\n visualTracks: \"visual and audio tracks were merged into `tracks` — move each row there.\",\n audioTracks: \"visual and audio tracks were merged into `tracks` — move each row there.\",\n backgrounds: \"a background is a track — put it first in `tracks`.\",\n overlays: \"an overlay is a track — put it last in `tracks`.\",\n commands: \"a project has no commands — each clip carries its own.\",\n constants: \"a project has no constants — declare `variables` in each clip.\",\n};\n\n/** Every node type and command a clip names, against `registry`. */\nfunction checkVocabulary(\n sites: readonly NodeSite[],\n commands: readonly { spec: CommandSpec; path: string }[],\n rootType: string,\n variables: ReadonlyMap<string, VariableSite>,\n registry: Registry,\n issues: ValidationIssue[],\n): void {\n const typeOf = new Map<string, string>([[\"\", rootType]]);\n for (const site of sites) {\n typeOf.set(site.spec.id, site.spec.type);\n if (!registry.hasNode(site.spec.type)) {\n issues.push({ path: `${site.path}.type`, message: `node type \"${site.spec.type}\" is not registered.` });\n }\n }\n for (const { spec, path } of commands) {\n if (registry.command(spec.type)) continue;\n if (spec.targetId !== null && variables.has(spec.targetId)) {\n issues.push({ path: `${path}.type`, message: `\"${spec.type}\" is not a variable command.` });\n continue;\n }\n const type = typeOf.get(spec.targetId ?? \"\");\n if (type === undefined || !registry.hasNode(type)) continue;\n if (!registry.takesCommand(type, spec.type)) {\n issues.push({ path: `${path}.type`, message: `node type \"${type}\" has no command \"${spec.type}\".` });\n }\n }\n}\n\n/**\n * The node rows every clip kind shares, checked the same way whichever holds\n * them — a cycle or a missing parent is the same bug in a still and a\n * composition.\n */\nfunction checkNodes(nodes: unknown, rootType: string, issues: ValidationIssue[]): NodeSite[] {\n if (!Array.isArray(nodes)) {\n issues.push({ path: \"nodes\", message: \"nodes must be an array.\" });\n return [];\n }\n const sites: NodeSite[] = [];\n nodes.forEach((n, i) => {\n const path = `nodes[${i}]`;\n if (checkNodeSpec(n, path, issues)) {\n sites.push({ spec: n, path });\n checkRootShape(n, path, rootType, issues);\n }\n });\n checkTree(sites, issues);\n return sites;\n}\n\n/** A timed node's span: two times in order, and none at all on the root. */\nfunction checkSpan(spec: TimedNodeSpec, path: string, issues: ValidationIssue[]): void {\n const { startAt, endAt } = spec;\n if (startAt !== undefined && !isTime(startAt)) {\n issues.push({ path: `${path}.startAt`, message: \"startAt must be a finite number of seconds >= 0.\" });\n }\n if (endAt !== undefined && !isTime(endAt)) {\n issues.push({ path: `${path}.endAt`, message: \"endAt must be a finite number of seconds >= 0.\" });\n }\n if (isTime(endAt) && endAt <= (isTime(startAt) ? startAt : 0)) {\n issues.push({ path: `${path}.endAt`, message: `endAt (${endAt}s) must be after startAt (${startAt ?? 0}s).` });\n }\n if (spec.id === \"\" && (startAt !== undefined || endAt !== undefined)) {\n issues.push({ path, message: \"the root is present for the whole clip — it cannot carry startAt or endAt.\" });\n }\n}\n\n/** Validate a still: a node tree, and nothing about time. */\nfunction validateStill(doc: StillDocument, issues: ValidationIssue[], registry: Registry | undefined): void {\n checkRetiredFields(doc, issues);\n if ((doc as { commands?: unknown }).commands !== undefined) {\n issues.push({\n path: \"commands\",\n message: \"a still has no timeline, so no commands — make it a composition to animate it.\",\n });\n }\n\n const variables = checkVariables(variableRows(doc.variables, issues), issues);\n const sites = checkNodes(doc.nodes, \"canvas2d\", issues);\n for (const site of sites) {\n const { startAt, endAt } = site.spec as TimedNodeSpec;\n if (startAt !== undefined || endAt !== undefined) {\n issues.push({\n path: site.path,\n message: \"a still has no timeline — drop startAt/endAt, or make it a composition.\",\n });\n }\n }\n const ok = sites.map((s) => s.spec);\n checkIdSpace(ok, variables, issues);\n if (registry) checkVocabulary(sites, [], \"canvas2d\", variables, registry, issues);\n const keyed = checkNodeKeys(sites, issues);\n\n const declared = new Set(variables.keys());\n const keys = new Set(keyed.keys());\n const bound: BoundProp[] = [];\n for (const site of sites) {\n checkExpressions(site.spec.props, `${site.path}.props`, declared, keys, issues);\n if (site.spec.key) boundProps(site.spec.key, site.spec.props, `${site.path}.props`, bound);\n }\n checkExpressionCycles(bound, issues);\n}\n\n/** Validate a composition: a still's rules over its nodes, plus their spans and the commands on them. */\nfunction validateComposition(doc: CompositionDocument, issues: ValidationIssue[], registry: Registry | undefined): void {\n validateTimedDocument(doc, \"canvas2d\", issues, registry);\n}\n\n/**\n * Validate an audio document.\n *\n * Every rule a composition has, with `audioBus` as the root type — because an\n * audio document *is* a composition, structurally. Sharing the checks rather\n * than restating them is what keeps a cycle, a duplicate id or a command\n * running before its target the same bug — and the same message — whichever\n * kind of clip it appears in.\n */\nfunction validateAudio(doc: AudioDocument, issues: ValidationIssue[], registry: Registry | undefined): void {\n validateTimedDocument(doc, \"audioBus\", issues, registry);\n}\n\n/** Command types the format no longer has, and where what they did went. */\nconst RETIRED_COMMANDS: Readonly<Record<string, string>> = {\n add: \"a node is a row in `nodes` — its `startAt` is when it enters.\",\n variable: \"a variable is declared in `variables`.\",\n};\n\n/** The shared body of {@link validateComposition} and {@link validateAudio}. */\nfunction validateTimedDocument(\n doc: CompositionDocument | AudioDocument,\n rootType: string,\n issues: ValidationIssue[],\n registry: Registry | undefined,\n): void {\n checkRetiredFields(doc, issues);\n if (!Array.isArray(doc.commands)) {\n issues.push({ path: \"commands\", message: \"commands must be an array.\" });\n return;\n }\n if (doc.duration !== undefined && !isTime(doc.duration)) {\n issues.push({ path: \"duration\", message: \"duration must be a finite number of seconds >= 0.\" });\n }\n\n // Variables, gathered before anything else looks at a prop: every\n // expression check needs to know what is declared.\n const variables = checkVariables(variableRows(doc.variables, issues), issues);\n\n const nodeSites = checkNodes(doc.nodes, rootType, issues);\n for (const site of nodeSites) checkSpan(site.spec as TimedNodeSpec, site.path, issues);\n const nodes = nodeSites.map((s) => s.spec);\n checkIdSpace(nodes, variables, issues);\n const keyed = checkNodeKeys(nodeSites, issues);\n\n // The commands that passed their shape check, each with the row it was\n // authored in: a position in this list is not a position in `commands`.\n const valid: { spec: CommandSpec; path: string }[] = [];\n const ids = new Set<string>();\n doc.commands.forEach((c: unknown, i: number) => {\n if (!checkCommandSpec(c, `commands[${i}]`, issues)) return;\n if (ids.has(c.id)) {\n issues.push({ path: `commands[${i}].id`, message: `duplicate command id \"${c.id}\".` });\n return;\n }\n const retired = RETIRED_COMMANDS[c.type];\n if (retired) {\n issues.push({ path: `commands[${i}].type`, message: `there is no \"${c.type}\" command — ${retired}` });\n return;\n }\n ids.add(c.id);\n valid.push({ spec: c, path: `commands[${i}]` });\n });\n\n // A command cannot act on a node that is not there yet. This is the one\n // ordering rule the document has, and it is the one a timeline editor\n // breaks by dragging a tween earlier than the node it animates. \"There\" is\n // the effective span — a child cannot enter before its parent does.\n //\n // A variable target is exempt because a variable has no lifespan: it holds\n // its declared value from t=0, so there is no \"before it exists\" to run\n // ahead of. See `VariableSpec`.\n const byId = new Map(nodes.map((n) => [n.id, n]));\n if (registry) checkVocabulary(nodeSites, valid, rootType, variables, registry, issues);\n for (const { spec: c, path } of valid) {\n if (c.targetId === null) continue;\n if (variables.has(c.targetId)) continue;\n const span = effectiveSpanIn(byId, c.targetId);\n if (span === undefined) {\n issues.push({\n path: `${path}.targetId`,\n message: `targetId \"${c.targetId}\" is not a node or variable in this document.`,\n });\n } else if (c.at < span.start) {\n issues.push({\n path: `${path}.at`,\n message: `command runs at ${c.at}s but its target \"${c.targetId}\" is not present until ${span.start}s.`,\n });\n }\n }\n\n // Expressions, wherever a prop can be authored: a node's props (the scene\n // root included), a `to`/`set` props bag, or a named command's arguments.\n const declared = new Set(variables.keys());\n const keys = new Set(keyed.keys());\n for (const site of nodeSites) {\n checkExpressions(site.spec.props, `${site.path}.props`, declared, keys, issues);\n }\n for (const { spec: c, path } of valid) checkExpressions(c.args, `${path}.args`, declared, keys, issues);\n\n // Cycles, over the two places a document installs a binding: a node's own\n // props, and a `set` — the one command whose args reach `node.set()`.\n const bound: BoundProp[] = [];\n for (const site of nodeSites) {\n if (site.spec.key) boundProps(site.spec.key, site.spec.props, `${site.path}.props`, bound);\n }\n for (const { spec: c, path } of valid) {\n if (c.type !== \"set\" || c.targetId === null) continue;\n const key = byId.get(c.targetId)?.key;\n if (key) boundProps(key, c.args, `${path}.args`, bound);\n }\n checkExpressionCycles(bound, issues);\n}\n\n/**\n * Validate a clip document.\n *\n * Returns every issue rather than throwing on the first: a host showing a\n * document's problems wants the list, and a fix-one-rerun loop over a large\n * scene is what makes an importer feel broken.\n */\nexport function validateDocument(doc: unknown, options: ValidateOptions = {}): ValidationResult {\n const issues: ValidationIssue[] = [];\n\n if (!isPlainObject(doc)) {\n return { valid: false, issues: [{ path: \"\", message: \"document must be an object.\" }] };\n }\n checkFormatVersion(doc, issues);\n const { registry } = options;\n const kind = (doc as Partial<ClipDocument>).kind;\n if (kind === \"still\") {\n validateStill(doc as unknown as StillDocument, issues, registry);\n } else if (kind === \"composition\") {\n validateComposition(doc as unknown as CompositionDocument, issues, registry);\n } else if (kind === \"audio\") {\n validateAudio(doc as unknown as AudioDocument, issues, registry);\n } else {\n issues.push({\n path: \"kind\",\n message: `kind must be \"still\", \"composition\" or \"audio\" (got ${JSON.stringify(kind)}).`,\n });\n }\n\n return { valid: issues.length === 0, issues };\n}\n\n/**\n * Validate a **project** document: the tracks, and every clip in them.\n *\n * Each clip is validated with the same rules a standalone one gets — a cycle or\n * an unresolved expression is the same bug wherever it appears — with its issues\n * prefixed by the track that carries it, so a host can point at the row rather\n * than at \"some clip\".\n */\nexport function validateProjectDocument(doc: unknown, options: ValidateOptions = {}): ValidationResult {\n const issues: ValidationIssue[] = [];\n\n if (!isPlainObject(doc)) {\n return { valid: false, issues: [{ path: \"\", message: \"document must be an object.\" }] };\n }\n const project = doc as Record<string, unknown>;\n if (project.kind !== \"project\") {\n issues.push({ path: \"kind\", message: `kind must be \"project\" (got ${JSON.stringify(project.kind)}).` });\n }\n if (typeof project.name !== \"string\" || project.name.length === 0) {\n issues.push({ path: \"name\", message: \"name must be a non-empty string.\" });\n }\n if (project.fps !== undefined && (typeof project.fps !== \"number\" || !(project.fps > 0) || !Number.isFinite(project.fps))) {\n issues.push({ path: \"fps\", message: \"fps must be a positive number when present.\" });\n }\n checkFormatVersion(project, issues);\n for (const [field, message] of Object.entries(RETIRED_PROJECT_FIELDS)) {\n if (project[field] !== undefined) issues.push({ path: field, message });\n }\n\n // The one field that used to be three. Zero tracks is a legitimate state,\n // not a mistake to reject — a freshly created project has no clips yet,\n // and every host of this array already treats an empty one as ordinary\n // rather than exceptional (`exportProject`/`mixTimelineAudio` no-op,\n // `screenshotProject` raises its own specific \"nothing to screenshot\").\n // Validation would be the odd one out insisting otherwise.\n if (!Array.isArray(project.tracks)) {\n issues.push({ path: \"tracks\", message: \"tracks must be an array.\" });\n return { valid: false, issues };\n }\n\n const ids = new Set<string>();\n project.tracks.forEach((raw, i) => {\n const path = `tracks[${i}]`;\n if (!isPlainObject(raw)) {\n issues.push({ path, message: \"track must be an object.\" });\n return;\n }\n const track = raw as Record<string, unknown>;\n\n if (typeof track.id !== \"string\" || track.id.length === 0) {\n issues.push({ path: `${path}.id`, message: \"id must be a non-empty string.\" });\n } else if (ids.has(track.id)) {\n issues.push({ path: `${path}.id`, message: `duplicate track id \"${track.id}\".` });\n } else {\n ids.add(track.id);\n }\n if (track.name !== undefined && typeof track.name !== \"string\") {\n issues.push({ path: `${path}.name`, message: \"name must be a string when present.\" });\n }\n if (track.startAt !== undefined && !isTime(track.startAt)) {\n issues.push({ path: `${path}.startAt`, message: \"startAt must be a finite number of seconds >= 0.\" });\n }\n // Required, not defaulted: a length that falls back to whatever a media\n // file happens to be is how a three-minute bed silently stretches a\n // thirty-second edit.\n if (!isTime(track.duration)) {\n issues.push({\n path: `${path}.duration`,\n message: \"duration is required, and must be a finite number of seconds >= 0.\",\n });\n }\n\n if (track.clip === undefined) {\n issues.push({ path: `${path}.clip`, message: \"clip is required — a track places a clip document inline.\" });\n return;\n }\n for (const issue of clipIssuesOf(track.clip, options)) {\n issues.push({ path: `${path}.clip${issue.path ? `.${issue.path}` : \"\"}`, message: issue.message });\n }\n });\n\n return { valid: issues.length === 0, issues };\n}\n\n/**\n * Keyed by clip object, because a host re-validates the whole project after every\n * edit and an edit replaces only the clip it touched. A clip mutated in place is\n * not seen again — the same identity contract `Session.replace` already holds.\n */\nconst CLIP_ISSUES = new WeakMap<object, readonly ValidationIssue[]>();\n\nfunction clipIssuesOf(clip: unknown, options: ValidateOptions): readonly ValidationIssue[] {\n if (!isPlainObject(clip) || options.registry) return validateDocument(clip, options).issues;\n let issues = CLIP_ISSUES.get(clip);\n if (!issues) {\n issues = validateDocument(clip).issues;\n CLIP_ISSUES.set(clip, issues);\n }\n return issues;\n}\n\n/** {@link validateProjectDocument}, but throwing. */\nexport function assertValidProjectDocument(doc: unknown, options?: ValidateOptions): void {\n const { valid, issues } = validateProjectDocument(doc, options);\n if (!valid) {\n const detail = issues.map((i) => ` ${i.path || \"<root>\"}: ${i.message}`).join(\"\\n\");\n throw new Error(`Invalid project document:\\n${detail}`);\n }\n}\n\n/**\n * {@link validateDocument}, but throwing. For a caller that has no UI to show\n * issues in and wants the document or an error.\n */\nexport function assertValidDocument(doc: unknown, options?: ValidateOptions): ClipDocument {\n const { valid, issues } = validateDocument(doc, options);\n if (!valid) {\n const detail = issues.map((i) => ` ${i.path || \"<root>\"}: ${i.message}`).join(\"\\n\");\n throw new Error(`Invalid clip document:\\n${detail}`);\n }\n return doc as ClipDocument;\n}\n", "import { getPropertyMeta } from \"@/attributes/properties/decorator\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { component3d } from \"@/components/factory/component3d\";\nimport { componentAudio } from \"@/components/factory/component-audio\";\nimport type { Node, NodeDimension } from \"@/components/trees/node/node\";\nimport type { NodeSpec } from \"./types\";\n\n/**\n * What a build puts where a row names a type its registry lacks: a node of the\n * row's tree that keeps the row's id, its placement and its children, and\n * draws nothing itself. One unknown type then costs one node rather than the\n * whole clip, and an editor still shows the row where it was.\n *\n * None of these is registered, so no document can name one.\n */\n\n/** The type a placeholder stands in for, and the props its row authored. */\nexport interface MissingNodeInfo {\n type: string;\n props: Readonly<Record<string, unknown>>;\n}\n\nconst MissingNode2D = component2d({ key: \"missingNode2d\" });\nconst MissingNode3D = component3d({ key: \"missingNode3d\" });\nconst MissingNodeAudio = componentAudio({ key: \"missingNodeAudio\" });\n\ntype PlaceholderCtor = new (props?: Record<string, unknown>) => Node;\n\nconst PLACEHOLDERS: Record<NodeDimension, PlaceholderCtor> = {\n \"2d\": MissingNode2D.node as unknown as PlaceholderCtor,\n \"3d\": MissingNode3D.node as unknown as PlaceholderCtor,\n audio: MissingNodeAudio.node as unknown as PlaceholderCtor,\n};\n\n/** Placement it keeps; nothing that would draw or composite, so it shows nothing of its own. */\nconst DRAWS = new Set([\"effects\", \"blend\", \"clip\", \"shadow\"]);\n\nconst KEPT = Object.fromEntries(Object.entries(PLACEHOLDERS).map(([dimension, ctor]) => [\n dimension,\n new Set(getPropertyMeta(Object.create(ctor.prototype) as object).map((m) => m.key).filter((key) => !DRAWS.has(key))),\n])) as unknown as Record<NodeDimension, ReadonlySet<string>>;\n\nconst MISSING = new WeakMap<Node, MissingNodeInfo>();\n\n/** Stands in for every placeholder's class when a build compares a live node's class with its row's. */\nexport const MISSING_TYPE: unique symbol = Symbol(\"missingNodeType\");\n\n/** @internal A placeholder for `spec`, in `dimension`, taking what it can of `props` (the literal half of the row's). */\nexport function missingNode(dimension: NodeDimension, spec: NodeSpec, props: Record<string, unknown>): Node {\n const node = new PLACEHOLDERS[dimension]({\n ...placeholderProps(dimension, props),\n id: spec.id,\n ...(spec.key !== undefined && { key: spec.key }),\n });\n MISSING.set(node, { type: spec.type, props: spec.props });\n return node;\n}\n\n/** @internal Of a props bag, what a placeholder of `dimension` takes. */\nexport function placeholderProps(dimension: NodeDimension, props: Record<string, unknown>): Record<string, unknown> {\n const kept = KEPT[dimension];\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(props)) if (kept.has(key)) out[key] = value;\n return out;\n}\n\n/**\n * The unknown type a live node stands in for, or `undefined` for a real node —\n * so a host can mark the row and keep its props for when the type is back.\n */\nexport function missingNodeOf(node: Node): MissingNodeInfo | undefined {\n return MISSING.get(node);\n}\n", "import type { Registry } from \"./registry\";\n\n/**\n * What a stored document can name and rely on, as JSON: every node type, the\n * props it declares with their defaults (a row is sparse, so a changed default\n * changes every document that leaves the prop out), and the commands it\n * publishes. Each release snapshots it beside its fixture documents, so a test\n * can tell what a change takes away from documents already saved.\n */\nexport interface RegistryVocabulary {\n nodes: Record<string, { properties: Record<string, { kind: string; default?: unknown }>; commands: string[] }>;\n /** The commands that resolve without a node type: `to`, `set`, the paints, the variable commands. */\n commands: string[];\n}\n\nexport function registryVocabulary(registry: Registry): RegistryVocabulary {\n const nodes: RegistryVocabulary[\"nodes\"] = {};\n for (const key of registry.nodeKeys()) {\n const properties: RegistryVocabulary[\"nodes\"][string][\"properties\"] = {};\n for (const [prop, described] of Object.entries(registry.describe(key)?.properties ?? {})) {\n properties[prop] = {\n kind: described.kind,\n ...(described.default !== undefined && { default: JSON.parse(JSON.stringify(described.default)) as unknown }),\n };\n }\n nodes[key] = { properties, commands: registry.commandKeys(key) };\n }\n return { nodes, commands: registry.commandKeys() };\n}\n\n/** One way `next` takes something away from what documents saved against `prev` relied on, named `type.prop`, `type.command` or `type`. */\nexport interface VocabularyBreak {\n name: string;\n what: \"node type removed\" | \"prop removed\" | \"default changed\" | \"command removed\";\n}\n\n/** What `next` removed or changed relative to `prev`. Anything it adds breaks nothing saved. */\nexport function vocabularyBreaks(prev: RegistryVocabulary, next: RegistryVocabulary): VocabularyBreak[] {\n const out: VocabularyBreak[] = [];\n for (const command of prev.commands) {\n if (!next.commands.includes(command)) out.push({ name: command, what: \"command removed\" });\n }\n for (const [type, was] of Object.entries(prev.nodes)) {\n const now = next.nodes[type];\n if (!now) {\n out.push({ name: type, what: \"node type removed\" });\n continue;\n }\n for (const [prop, { default: before }] of Object.entries(was.properties)) {\n const after = now.properties[prop];\n if (!after) out.push({ name: `${type}.${prop}`, what: \"prop removed\" });\n else if (JSON.stringify(before) !== JSON.stringify(after.default)) out.push({ name: `${type}.${prop}`, what: \"default changed\" });\n }\n for (const command of was.commands) {\n if (!now.commands.includes(command)) out.push({ name: `${type}.${command}`, what: \"command removed\" });\n }\n }\n return out;\n}\n", "import type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Shadow } from \"@/attributes/shape/shadow/shadow\";\nimport type { Stroke } from \"@/attributes/shape/stroke/stroke\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport { driveCommand, type Command, type CommandArgs } from \"@/tween/command\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport type { Node2D } from \"@/components/trees/2d/node2d\";\n\nimport { BooleanGroup, MaskGroup } from \"@/components/builtins/geometry/composite\";\nimport { Ellipse, PathShape, Polygon, Polygram, Rect } from \"@/components/builtins/geometry/geometry\";\nimport { Camera, OrbitCamera, RotatedBox } from \"@/components/builtins/layout/layout\";\nimport { Video } from \"@/components/builtins/media/media\";\nimport { AudioBus, SoundNode } from \"@/components/builtins/audio/audio\";\nimport { Canvas2D } from \"@/components/trees/root/canvas2d-node\";\nimport { Provider, ThemeProvider } from \"@/components/builtins/providers/providers\";\nimport { DefaultTextStyle, NumberNode, RichText, Text } from \"@/components/builtins/text/text\";\nimport { Canvas3D } from \"@/components/builtins/three/canvas3d\";\nimport {\n AmbientLight3D, AreaLight3D, Box3D, Camera3D, Capsule3D, Circle3D, Cone3D, Cylinder3D, DirectionalLight3D,\n Environment3D, Extrude3D, Fog3D, Group3D, HemisphereLight3D, Instances3D, Lathe3D, Line3D, Mesh3D, Model3D,\n Plane3D, PointLight3D, Points3D, Polyhedron3D, Ring3D, Sphere3D, SpotLight3D, Sprite3D, Torus3D, TorusKnot3D, Tube3D,\n} from \"@/components/builtins/three/three\";\n\nimport { lerpVector2 } from \"@/attributes/layout/vector2\";\nimport { lerpColor } from \"@/attributes/shape/fill/lerp\";\nimport { parseColor } from \"@/attributes/shape/fill/color/parser\";\nimport { lerpVector3 } from \"@/render3d/vector3\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\nimport type { NodeConstructor, Registry, VariableLerp } from \"./registry\";\n\n/**\n * Registration of everything `@motionscript/core` itself ships.\n *\n * The keys here are **document API**. A stored scene names its nodes and its\n * animations with these strings, so renaming one silently breaks every document\n * that used it — they are as much a public contract as an exported symbol, and\n * are deliberately spelled out rather than derived from `constructor.name`\n * (which a minifier is free to mangle).\n */\n\n/** Every built-in node type, keyed as a document names it. */\nconst NODE_TYPES: Record<string, NodeConstructor> = {\n // Clip root and structural\n canvas2d: Canvas2D as unknown as NodeConstructor,\n provider: Provider as unknown as NodeConstructor,\n \"theme-provider\": ThemeProvider as unknown as NodeConstructor,\n \"default-text-style\": DefaultTextStyle as unknown as NodeConstructor,\n\n // Geometry\n rect: Rect as unknown as NodeConstructor,\n ellipse: Ellipse as unknown as NodeConstructor,\n // The **unit-box** path, not `path-node.ts`'s face-value `Path`. A stored\n // document's `data` is a fraction of the node's own box, so a resize is an\n // ordinary `width`/`height` write and every editor gizmo works on it\n // unchanged (`box-path-node.ts` has the whole argument). `Path` draws its\n // `d` at face value and hugs it, which is right for geometry somebody wrote\n // in code — it stays exported for that, and is reached by importing the\n // class rather than by naming a type in a document.\n path: PathShape as unknown as NodeConstructor,\n polygon: Polygon as unknown as NodeConstructor,\n polygram: Polygram as unknown as NodeConstructor,\n boolean: BooleanGroup as unknown as NodeConstructor,\n mask: MaskGroup as unknown as NodeConstructor,\n\n // Layout\n camera: Camera as unknown as NodeConstructor,\n orbitCamera: OrbitCamera as unknown as NodeConstructor,\n \"rotated-box\": RotatedBox as unknown as NodeConstructor,\n\n // Text\n text: Text as unknown as NodeConstructor,\n richtext: RichText as unknown as NodeConstructor,\n number: NumberNode as unknown as NodeConstructor,\n\n // Media\n video: Video as unknown as NodeConstructor,\n\n // Audio — a bus groups, a sound plays. `audioBus` is also the root of an\n // AudioDocument, the way `canvas2d` is the root of a scene.\n audioBus: AudioBus as unknown as NodeConstructor,\n sound: SoundNode as unknown as NodeConstructor,\n\n // 3D — the viewport, then the tree that lives inside it\n canvas3d: Canvas3D as unknown as NodeConstructor,\n group3d: Group3D as unknown as NodeConstructor,\n mesh3d: Mesh3D as unknown as NodeConstructor,\n box3d: Box3D as unknown as NodeConstructor,\n sphere3d: Sphere3D as unknown as NodeConstructor,\n plane3d: Plane3D as unknown as NodeConstructor,\n circle3d: Circle3D as unknown as NodeConstructor,\n cylinder3d: Cylinder3D as unknown as NodeConstructor,\n cone3d: Cone3D as unknown as NodeConstructor,\n capsule3d: Capsule3D as unknown as NodeConstructor,\n torus3d: Torus3D as unknown as NodeConstructor,\n \"torus-knot3d\": TorusKnot3D as unknown as NodeConstructor,\n tube3d: Tube3D as unknown as NodeConstructor,\n lathe3d: Lathe3D as unknown as NodeConstructor,\n extrude3d: Extrude3D as unknown as NodeConstructor,\n ring3d: Ring3D as unknown as NodeConstructor,\n polyhedron3d: Polyhedron3D as unknown as NodeConstructor,\n points3d: Points3D as unknown as NodeConstructor,\n line3d: Line3D as unknown as NodeConstructor,\n sprite3d: Sprite3D as unknown as NodeConstructor,\n instances3d: Instances3D as unknown as NodeConstructor,\n model3d: Model3D as unknown as NodeConstructor,\n camera3d: Camera3D as unknown as NodeConstructor,\n \"ambient-light3d\": AmbientLight3D as unknown as NodeConstructor,\n \"directional-light3d\": DirectionalLight3D as unknown as NodeConstructor,\n \"point-light3d\": PointLight3D as unknown as NodeConstructor,\n \"spot-light3d\": SpotLight3D as unknown as NodeConstructor,\n \"hemisphere-light3d\": HemisphereLight3D as unknown as NodeConstructor,\n \"area-light3d\": AreaLight3D as unknown as NodeConstructor,\n fog3d: Fog3D as unknown as NodeConstructor,\n environment3d: Environment3D as unknown as NodeConstructor,\n};\n\n/** A node method taking one {@link CommandArgs}. */\ntype EasedMethod = (args: CommandArgs) => Command<Record<string, unknown>>;\n\n/** Call a paint command (`fillTo`/`overlayTo`/`strokeTo`/`shadowTo`). */\nfunction paintCommand(method: string, argKey: string) {\n return (\n target: Node,\n args: Record<string, unknown>,\n duration: number,\n easing?: EasingFunction,\n ): Command<Record<string, unknown>> => {\n const fn = (target as unknown as Record<string, unknown>)[method];\n if (typeof fn !== \"function\") {\n throw new Error(\n `Command \"${method}\" is not available on ${target.constructor.name}.`,\n );\n }\n return (fn as EasedMethod).call(target, { data: args[argKey] as Record<string, unknown>, duration, easing });\n };\n}\n\n/**\n * The interpolations a document can name in `VariableSpec.lerp`.\n *\n * Deliberately the small set a variable actually holds — a number, a point, a\n * colour — rather than one entry per attribute in the library. A variable drives\n * props *through* an expression, so it only has to carry the quantity that\n * varies: a gradient that shifts is one `stop` number bound into a fill, not a\n * whole fill being interpolated a second time. Anything else is a\n * `registry.addLerp` away.\n */\nconst VARIABLE_LERPS: Record<string, VariableLerp> = {\n number: lerpNumber as VariableLerp,\n vector2: lerpVector2 as VariableLerp,\n vector3: lerpVector3 as VariableLerp,\n /**\n * Parse both ends, blend per channel, hand back a CSS string.\n *\n * A string rather than the parsed tuple because that is what the prop on the\n * far side of the expression takes — every fill, stroke and shadow resolves\n * a colour from CSS text, and `parseColor` reads theme tokens and the\n * `\"white/10\"` opacity suffix too, so a variable can hold either.\n */\n color: ((from, to, t) => {\n const [r, g, b, a] = lerpColor(parseColor(String(from)), parseColor(String(to)), t);\n const channel = (v: number) => Math.round(Math.min(Math.max(v, 0), 1) * 255);\n return `rgba(${channel(r)}, ${channel(g)}, ${channel(b)}, ${Number(a.toFixed(4))})`;\n }) as VariableLerp,\n /**\n * No interpolation: hold `from` until the tween lands, then take `to`.\n *\n * The default for a non-numeric variable: a discrete value (a string of\n * text, an enum, a boolean) has no midpoint, and inventing one produces a\n * frame that is neither state.\n */\n step: ((from, to, t) => (t >= 1 ? to : from)) as VariableLerp,\n};\n\n/**\n * Seed a {@link Registry} with everything `@motionscript/core` itself ships.\n *\n * **Internal, and called from `Registry`'s own constructor.** It used to be\n * public and every host had to call it at module scope before compiling\n * anything — which `sideEffects: false` is entitled to delete, with a failure\n * mode (\"unknown node type rect\") that points nowhere near the cause. A registry\n * that seeds itself makes the vocabulary a value dependency of the engine\n * instead, so there is nothing left to tree-shake and nothing to remember.\n *\n * @internal\n */\nexport function installBuiltins(registry: Registry): void {\n for (const [key, ctor] of Object.entries(NODE_TYPES)) {\n registry.addNode(key, ctor);\n }\n for (const [key, lerp] of Object.entries(VARIABLE_LERPS)) {\n registry.addLerp(key, lerp);\n }\n\n // ── Props ────────────────────────────────────────────────────────────────\n // `args` *is* the props diff — no wrapper key, since `to`/`set` each carry\n // exactly one argument and a node's own props are already a fixed,\n // known-shape bag (not something a second command parameter could collide\n // with the way `to`/`set` never gained one).\n registry.addCommand(\"to\", (target, args, duration, easing) =>\n (target as Node2D).to({\n // Copied: `_prepareStep` expands sugar into its target in place, which\n // would rewrite the document row a diff compares by identity.\n data: { ...args } as Record<string, never>,\n duration,\n easing,\n }) as unknown as Command<Record<string, unknown>>);\n\n // A stamp: write props with no tween. `duration` is ignored, which is what\n // makes it usable as the \"set this here\" a keyframe editor needs.\n //\n // `binds` because its args reach `set()` verbatim, so an expression among\n // them is a binding — this is how a prop starts following a variable partway\n // through a scene rather than from the moment its node is authored.\n registry.addCommand(\"set\", (target, args) => {\n const props = args as Record<string, never>;\n return driveCommand(0, () => {\n (target as Node2D).set(props);\n }) as unknown as Command<Record<string, unknown>>;\n }, { binds: true });\n\n // ── Paint (shapes, text, Canvas2D) ─────────────────────────────────────\n // Node-less rather than per-type, like `to` and `set` above: these are\n // generic over every painted node, and they take a `TweenOptions` bag where\n // an ordinary command takes a bare easing function — so they need a factory\n // that knows that convention rather than the uniform one a node type's own\n // table dispatches through.\n // Each declares the one key it reads, in the kind its property uses, so a\n // host draws the same paint stack for the command as for the prop.\n registry.addCommand(\"fillTo\", paintCommand(\"fillTo\", \"fill\"), { args: [{ key: \"fill\", kind: \"fills\" }], method: \"fillTo\" });\n registry.addCommand(\"overlayTo\", paintCommand(\"overlayTo\", \"overlay\"), { args: [{ key: \"overlay\", kind: \"fills\" }], method: \"overlayTo\" });\n registry.addCommand(\"strokeTo\", paintCommand(\"strokeTo\", \"stroke\"), { args: [{ key: \"stroke\", kind: \"strokes\" }], method: \"strokeTo\" });\n registry.addCommand(\"shadowTo\", paintCommand(\"shadowTo\", \"shadow\"), { args: [{ key: \"shadow\", kind: \"shadows\" }], method: \"shadowTo\" });\n\n // Transform, camera, text and `restore` commands are not registered here:\n // they are `command()` methods, and `Registry.addNode` publishes them off\n // the classes above. See `document/registry.ts`.\n\n // ── Variables ────────────────────────────────────────────────────────────\n // Tween a variable. The one command that drives many nodes at once: every\n // prop bound to `\"=[id]\"` follows what this writes, with no command of its\n // own and nothing to keep in sync.\n registry.addVariableCommand(\"variableTo\", (target, args, duration, easing) => {\n const to = (args as { value?: unknown }).value;\n const lerpKey = (args as { lerp?: unknown }).lerp;\n const override = typeof lerpKey === \"string\" ? registry.lerp(lerpKey) : undefined;\n if (lerpKey !== undefined && !override) {\n throw new Error(\n `A \"lerp\" param must name a registered lerp (variable \"${target.id}\"), ` +\n `got ${JSON.stringify(lerpKey)}. Registered: ${registry.lerpKeys().join(\", \")}.`,\n );\n }\n const lerp = override ?? target.lerp;\n\n // `from` is captured on the command's first evaluation rather than here,\n // exactly as a node's `to()` does: the timeline builds commands in order\n // and runs each to `at(1)`, so the capture sees the state its\n // predecessors left. Captured once, it is then a pure function of `t`.\n let from: unknown;\n let captured = false;\n return driveCommand(duration, (t) => {\n if (!captured) {\n from = target.get();\n captured = true;\n }\n target.set(lerp(from, to, t));\n }, easing) as unknown as Command<Record<string, unknown>>;\n });\n\n // A stamp, matching `set`: write the value with no tween, ignoring duration.\n registry.addVariableCommand(\"variableSet\", (target, args) =>\n driveCommand(0, () => {\n target.set((args as { value?: unknown }).value);\n }) as unknown as Command<Record<string, unknown>>);\n\n // ── State ────────────────────────────────────────────────────────────────\n // `restore` pops the layer a `save` pushed, and is published off `Node`'s own\n // `command()`. `save` is not one, so it is registered here — both are\n // commands so the pair is placed on the timeline like anything else, and a\n // seek past the save still produces the same frame: the value is computed\n // from the chain rather than accumulated as the playhead moves.\n registry.addCommand(\"save\", (target) =>\n driveCommand(0, () => {\n (target as Node2D).save();\n }) as unknown as Command<Record<string, unknown>>);\n}\n\n/** Type-only re-exports, so a caller writing args gets the same shapes. */\nexport type { Fill, Shadow, Stroke, Vector2 };\n", "/**\n * The ambient capabilities a dynamic node's compiled source is denied.\n *\n * ## What this is, and what it very deliberately is not\n *\n * A dynamic node's compiled JS is evaluated with `new Function` **in the\n * host's own realm**, and that is forced by the architecture rather than\n * chosen: the node it produces has to be a live class that satisfies\n * `instanceof` against the host's own already-loaded `core`, and participate\n * in the same per-frame reactive `property` graph. A live class instance\n * cannot cross a worker or cross-origin iframe boundary, so the usual \"run it\n * in another realm\" answer is closed off by what the renderer is, not by how\n * much effort is spent on it.\n *\n * What *is* possible in one realm is taking the dangerous names out of scope.\n * Every identifier below becomes a parameter of the `new Function` factory\n * bound to `undefined`, so `fetch(...)` inside a compiled node is a call on\n * `undefined` rather than a network request. Under `\"use strict\"` — which the\n * factory already sets — a bare `this` is `undefined` too, so the usual back\n * door is shut.\n *\n * **This is hardening, not a sandbox.** A determined script can still reach\n * the real global object through the intrinsics: `({}).constructor.constructor`\n * is `Function`, and `Function(\"return globalThis\")()` walks straight back\n * out. Closing that would mean freezing or poisoning `Object.prototype`,\n * `Function` and every async/generator constructor, which breaks the engine\n * itself — it subclasses, it writes prototypes, it builds objects constantly.\n * So the honest security boundary is not this file. It is whatever gate the\n * *host* puts in front of calling `Registry.addNodeFromSource` at all — a\n * compiled node's source is not evaluated until something upstream decides\n * it should be.\n *\n * This file's job is to make the easy paths closed, the accidents impossible,\n * and the escape require obvious intent that a reviewer would notice.\n */\n\n/**\n * Names bound to `undefined` in every dynamic node module's scope.\n *\n * Grouped by what they'd be used for, because the list is only auditable if\n * you can see what each entry is keeping out. Adding a browser API here is\n * cheap; leaving one out is the bug.\n *\n * This engine's `Registry` only ever evaluates a dynamic node inside a\n * browser-realm page (a real browser tab, or headless's own Playwright page —\n * never bare Node), so this list is scoped to that one realm rather than also\n * covering Node globals (`process`, `require`, `global`) that never apply\n * here.\n */\nexport const DENIED_GLOBALS: readonly string[] = [\n // Reaching the global object, and from it everything else.\n \"globalThis\",\n \"window\",\n \"self\",\n \"top\",\n \"parent\",\n \"frames\",\n\n // Evaluating more code.\n //\n // `eval` is missing on purpose and cannot be added: strict mode forbids it\n // as a binding name, so naming it here makes `new Function` throw\n // \"Unexpected eval or arguments in strict mode\" and *every* dynamic node\n // stops linking. It stays reachable, which is one more reason this file is\n // not the security boundary — see the module note above.\n \"Function\",\n \"importScripts\",\n\n // The DOM: reading the page, and `document.cookie`.\n \"document\",\n \"navigator\",\n \"location\",\n \"history\",\n \"screen\",\n \"customElements\",\n\n // Anywhere to send what was found. (`navigator.sendBeacon` needs\n // `navigator`, which is already denied above.)\n \"fetch\",\n \"XMLHttpRequest\",\n \"WebSocket\",\n \"EventSource\",\n \"Request\",\n \"Response\",\n \"Headers\",\n\n // Anywhere to read a credential from.\n \"localStorage\",\n \"sessionStorage\",\n \"indexedDB\",\n \"caches\",\n \"cookieStore\",\n \"crypto\",\n\n // Other threads and other documents.\n \"Worker\",\n \"SharedWorker\",\n \"ServiceWorker\",\n \"MessageChannel\",\n \"BroadcastChannel\",\n \"postMessage\",\n\n // Things that ask the user for something, or leave the page.\n \"alert\",\n \"confirm\",\n \"prompt\",\n \"open\",\n \"print\",\n \"Notification\",\n];\n\n/**\n * Names strict mode refuses to bind, and which would therefore break linking\n * for every dynamic node rather than protecting anything.\n *\n * Checked rather than trusted: adding one to the list above is an easy\n * mistake that fails at *evaluation* time, on whichever node happens to\n * compile first, with an error naming neither the list nor the culprit.\n */\nconst UNBINDABLE = new Set([\"eval\", \"arguments\"]);\n\nconst illegal = DENIED_GLOBALS.filter((name) => UNBINDABLE.has(name));\nif (illegal.length > 0) {\n throw new Error(\n `DENIED_GLOBALS cannot contain ${illegal.join(\", \")}: strict mode forbids ` +\n `binding those names, so no dynamic node would link at all. See the note in this file.`,\n );\n}\n", "import type { Node, NodeDimension } from \"@/components/trees/node/node\";\nimport type { Command, CommandArgs } from \"@/tween/command\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport { getPropertyMeta, type PropertyEditor } from \"@/attributes/properties/decorator\";\nimport { getCommandMeta, type CommandArg, type CommandArgDescriptor } from \"@/tween/command-decorator\";\nimport {\n normalizeShaderPack,\n type EffectShader,\n type FillShader,\n type Shader,\n} from \"@/attributes/shape/shaders/pack\";\nimport { installBuiltins } from \"./builtins\";\nimport { DENIED_GLOBALS } from \"./deny-globals\";\nimport { getNodeDescriptor } from \"./node-decorator\";\nimport { applyPropEvolution, propEvolutionOf } from \"./prop-evolution\";\nimport type { NodePropertyDescriptor, NodeTypeDescriptor } from \"./node-descriptor\";\nimport type { NodeSpec } from \"./types\";\n\n/**\n * The specifiers a dynamic node's `require()` resolves to the host's sdk\n * barrel. The published\n * name comes first; the two after it are the package's earlier unscoped names,\n * kept so a script authored under either still compiles.\n */\nconst SDK_SPECIFIERS: readonly string[] = [\"@motionscript/sdk\", \"motionscript\", \"motion-script\"];\n\n/**\n * The **code** half of the document model, as one object an engine owns.\n *\n * A document names a node type, a command, a lerp and a shader with a string.\n * Something has to turn `\"rect\"` into a class and `\"fillTo\"` into an animation,\n * and that something is deliberately a registry rather than a table in the\n * database: node types are code — a class with `property` declarations, a\n * `renderSelf`, and `command()` methods — and code is versioned with the\n * library, not with the document.\n *\n * **It is an instance, not a module.** Every table here used to be a\n * module-scope `Map` behind a dozen free functions, which made a registration\n * a fact about the *process*: two engines in one process shared one vocabulary,\n * a declared class was registered by the mere act of being imported, whichever\n * host loaded first won a contested key, and a test had to remember to call a\n * `clearRegistries()` that reached into three modules. A registry is now a value\n * with an owner — an `Engine`'s own, reached through `registerNode`/`registerShader`\n * rather than a public `registry` field — so what a document can name is a\n * property of the engine opening it, and two engines disagree about it freely.\n *\n * ```ts\n * const registry = new Registry({ nodes: [Blob], shaders: { swirl: SWIRL } });\n * registry.commandKeys(\"blob\"); // [\"fadeTo\", \"moveTo\", …, \"wobbleTo\"]\n * ```\n *\n * **Commands are per node type, and that is the point.** They used to share one\n * flat table with the node types, which made a command key a global claim: the\n * first package to register `reveal` owned the word, and a second node type\n * wanting it — with different arguments — could not have it. Nothing about a\n * command is global, though: it is a method on a class, dispatched against an\n * instance the document already names. Only the handful that must resolve\n * *without* a node — the variable-scoped ones and the generic prop writers — sit\n * in a table of their own.\n */\n\n/** Constructs a node from its authored props. Every built-in node class matches this. */\nexport type NodeConstructor = new (props?: Record<string, unknown>) => Node;\n\n/** Node types a registry makes available, by the key a document names them with. */\nexport type NodeTypeMap = Record<string, NodeConstructor>;\n\n/** Shader packs a registry makes available, by document key. A pack is plain JSON. */\nexport type ShaderPackMap = Record<string, unknown>;\n\n/**\n * Builds the {@link Command} a `CommandSpec` stands for.\n *\n * Called **once per compile**, in timeline order, with `target` already in the\n * state the previous command left it — that is what fixes the command's `from`\n * value and makes the returned `Command.at(t)` pure thereafter. See\n * `tween/command.ts` and `document/timeline.ts`.\n *\n * @param target The node the command acts on (the scene root for `targetId: null`).\n * @param args The spec's `args`, verbatim.\n * @param duration Seconds, already defaulted by the caller.\n * @param easing Resolved from the spec's `EaseSpec`, or `undefined`.\n */\nexport type CommandFactory = (\n target: Node,\n args: Record<string, unknown>,\n duration: number,\n easing?: EasingFunction,\n) => Command<Record<string, unknown>>;\n\n/**\n * The variable a variable command writes.\n *\n * A handle rather than the cell itself, so a command cannot subscribe to it,\n * rebind it, or hold it past the build that made it — the three ways a command\n * could stop being a pure function of `t`.\n */\nexport interface VariableTarget {\n /** The id an expression names with `[id]`. */\n readonly id: string;\n /** What it holds right now. */\n get(): unknown;\n set(value: unknown): void;\n /**\n * The lerp its `VariableSpec.lerp` resolved to. A command is free to use a\n * different one when its args ask for it — `variableTo` does.\n */\n readonly lerp: VariableLerp;\n}\n\n/**\n * Builds the {@link Command} a variable-scoped `CommandSpec` stands for.\n *\n * Same contract as {@link CommandFactory} — called once per compile, in timeline\n * order, against a variable already holding what its predecessors left — with a\n * {@link VariableTarget} in place of a node.\n */\nexport type VariableCommandFactory = (\n target: VariableTarget,\n args: Record<string, unknown>,\n duration: number,\n easing?: EasingFunction,\n) => Command<Record<string, unknown>>;\n\n/**\n * How a variable's value interpolates between two states.\n *\n * The same shape every `property` tween already has, widened to `unknown`\n * because a variable's type is a fact of the document rather than of a class:\n * one holds a number, the next a colour string, the next a whole fill object.\n */\nexport type VariableLerp = (from: unknown, to: unknown, t: number) => unknown;\n\n/**\n * One command that resolves without a node.\n *\n * `scope` says which table `CommandSpec.targetId` is looked up in, and is what\n * lets a variable command reuse the same field a node command uses instead of\n * inventing a second one every host's timeline would then have to special-case.\n */\nexport type CommandTypeEntry =\n | {\n key: string;\n scope: \"node\";\n factory: CommandFactory;\n /**\n * Its leading parameters, as {@link NodeCommandEntry.args} describes a\n * node command's — declared by the paint commands, which read one key\n * each. Absent for `to`/`set`, whose args *are* the props diff.\n */\n args?: readonly CommandArgDescriptor[];\n /**\n * This command **writes props declaratively**, so an expression in its\n * args compiles to a binding rather than being passed through as a\n * string. `set` is the only built-in that does.\n *\n * A flag rather than a name check, because the distinction is real: `to`\n * tweens *towards* a value and a formula is not a value, so binding one\n * as a tween destination would interpolate towards `NaN` and look like a\n * renderer bug. A command opting in is saying its args reach `set()`.\n */\n binds?: boolean;\n /**\n * The method it runs on its target, where it runs one: the paint\n * commands call the node's own `fillTo`, `strokeTo`, …. A node type\n * without it, or one that withdrew it, does not take the command\n * ({@link Registry.takesCommand}).\n */\n method?: string;\n }\n | {\n key: string;\n scope: \"variable\";\n factory: VariableCommandFactory;\n };\n\n/**\n * One node type's own command table.\n *\n * Built from the class's `command()` methods — the **whole** prototype chain,\n * not just its own — because the table is per type. A `Card` extending `Rect`\n * answers to `fadeTo` for the same reason it answers to `.fadeTo()`: it has the\n * method. There is nothing here for two node types to collide over, so\n * inherited entries can simply be copied into each.\n */\nexport interface NodeTypeRecord {\n /** The document key, matching `NodeSpec.type`. */\n key: string;\n /** The class to construct. */\n ctor: NodeConstructor;\n /** Its commands, by the key a document names them with. */\n commands: ReadonlyMap<string, NodeCommandEntry>;\n /**\n * What the type declares about itself — see {@link NodeTypeDescriptor}.\n *\n * Always present, so a host reads one shape whether the type was registered\n * with a bare key, a full descriptor, or a component.\n */\n descriptor: NodeTypeDescriptor;\n}\n\n/** One command on one node type. */\nexport interface NodeCommandEntry {\n /** The method to call. */\n method: string;\n /**\n * Its leading parameters, from `command({ args })`, always as descriptors.\n *\n * A bare name normalises to `{ key, kind: \"unknown\" }`, so a host reads one\n * shape whether the method bothered to describe its arguments or not.\n */\n args: readonly CommandArgDescriptor[];\n /** Present and true for an entrance (`CommandMeta.entrance`), so a host can offer one when the node is added. */\n entrance?: true;\n}\n\n/**\n * How a registry compiles and links a node authored as a TS source string\n * that default-exports a component, via {@link Registry.addNodeFromSource}.\n *\n * Entirely host-supplied — `core` has no compiler dependency and cannot\n * import the published `@motionscript/sdk` barrel itself (that package\n * depends on `core`, so the reverse direction would be circular).\n */\nexport interface DynamicNodeConfig {\n /**\n * What `require(\"@motionscript/sdk\")` resolves to inside a compiled\n * script — the host's own already-loaded sdk barrel instance. Must be the\n * same module instance the rest of the app uses, or `instanceof` silently\n * fails against it. The earlier unscoped specifiers, `\"motionscript\"` and\n * the dashed `\"motion-script\"`, resolve to the same object, so a node\n * script authored under either name keeps compiling unmodified.\n */\n sdk: Record<string, unknown>;\n /**\n * Further modules a script may `require`, by exact specifier — what a\n * forked component imports beyond the sdk barrel:\n * `@motionscript/sdk/component`, its package's kit. Consulted after the\n * two above, so neither can be shadowed. Each value has to be the host's\n * own loaded instance, for the same `instanceof` reason as `sdk`.\n */\n modules?: Readonly<Record<string, unknown>>;\n /**\n * TS source → JS text (CommonJS). Host-injected, never bundled —\n * `core` has no compiler dependency of its own.\n */\n compile: (source: string) => Promise<string>;\n}\n\n/** What a registry is seeded with, on top of the builtin vocabulary. */\nexport interface RegistryOptions {\n /**\n * Custom node types — components, or explicit keys.\n *\n * An array reads each class's `node()` declaration; a record names the key\n * outright, which is also an assertion that the two agree (a rename on\n * either side throws here rather than surfacing as an unknown type at\n * render).\n */\n nodes?: NodeTypeMap | readonly NodeConstructor[];\n /** Shader packs, by document key. Plain JSON — normalised on the way in. */\n shaders?: ShaderPackMap;\n /** Extra variable interpolations, on top of `number`/`vector2`/`vector3`/`color`/`step`. */\n lerps?: Record<string, VariableLerp>;\n /** Custom eases, referenced from a document as `{ kind: \"custom\", args: key }`. */\n eases?: Record<string, EasingFunction>;\n /** Enables {@link Registry.addNodeFromSource} — see {@link DynamicNodeConfig}. */\n dynamicNodes?: DynamicNodeConfig;\n /**\n * Fail a track's build on a node type or command this registry lacks, as\n * builds did before placeholders. Off, the build stands an inert\n * placeholder in for the node, skips the command, and records each in\n * `buildErrors`. For a render whose output nobody inspects.\n */\n strict?: boolean;\n /**\n * Leave out everything the library itself ships. Only useful to a test\n * asserting on the seeding, or a host building a deliberately tiny\n * vocabulary — a document naming `\"rect\"` will not compile without it.\n */\n builtins?: boolean;\n}\n\n/** See the module docblock. */\nexport class Registry {\n /** Ceiling, so an import cannot evict a workspace's own shaders by volume. */\n static readonly MAX_SHADERS = 512;\n\n /** See {@link RegistryOptions.strict}. */\n readonly strict: boolean;\n\n constructor(options: RegistryOptions = {}) {\n this._dynamicNodes = options.dynamicNodes;\n this.strict = options.strict === true;\n if (options.builtins !== false) installBuiltins(this);\n if (Array.isArray(options.nodes)) {\n for (const ctor of options.nodes) this.addNode(ctor);\n } else {\n for (const [key, ctor] of Object.entries(options.nodes ?? {})) this.addNode(key, ctor);\n }\n for (const [key, lerp] of Object.entries(options.lerps ?? {})) this.addLerp(key, lerp);\n for (const [key, ease] of Object.entries(options.eases ?? {})) this.addEase(key, ease);\n for (const [key, pack] of Object.entries(options.shaders ?? {})) this.addShader(key, pack);\n }\n\n // ─── Node types ──────────────────────────────────────────────────────────\n\n /**\n * Register a node class, with its commands and whatever else it declares.\n *\n * Takes a component (or a class carrying a `node()` declaration) on its own, or a bare key / full\n * {@link NodeTypeDescriptor} plus the class. The descriptor is the code half\n * of what a component package used to restate in a `manifest.json` —\n * carried, never interpreted, so a host has one place to ask and no second\n * file to disagree with the class.\n *\n * The commands come off the class, so `command()` is the only place a\n * node's animations are written down. Nothing is constructed to read them:\n * `command` records onto the prototype, so an object *over* the prototype\n * reaches the whole chain without running a constructor that may expect\n * props, build children, or touch a clock.\n *\n * Re-registering the same class under the same key is a no-op, so a hot\n * reload or a duplicated dependency is harmless. Re-registering a\n * *different* class throws: two classes answering to one key means a\n * document renders differently depending on registration order, which is not\n * a failure anyone would find by looking at the document.\n *\n * Pass `{ replace: true }` to opt out of that throw — the one case it's\n * wrong for is a node whose source has genuinely been edited and\n * recompiled (see {@link addNodeFromSource}), where re-registering under\n * the same key with a new class is the whole point. The default stays a\n * throw; this is deliberately not the common path.\n */\n addNode(ctor: NodeConstructor, options?: { replace?: boolean }): this;\n addNode(type: string | NodeTypeDescriptor, ctor: NodeConstructor, options?: { replace?: boolean }): this;\n addNode(\n type: string | NodeTypeDescriptor | NodeConstructor,\n ctorOrOptions?: NodeConstructor | { replace?: boolean },\n maybeOptions?: { replace?: boolean },\n ): this {\n const isTwoArgForm = typeof ctorOrOptions === \"function\";\n // A component (`component2d(...)`) registers as the node class it generated.\n const given = (isTwoArgForm ? ctorOrOptions : type) as NodeConstructor & { node?: NodeConstructor };\n const cls = typeof given.node === \"function\" ? given.node : given;\n const options = isTwoArgForm ? maybeOptions : ctorOrOptions as { replace?: boolean } | undefined;\n const declared = isTwoArgForm ? type as string | NodeTypeDescriptor : getNodeDescriptor(cls);\n if (declared === undefined) {\n throw new Error(\n `${cls.name || \"The class\"} is no component, so it has no document key. ` +\n `Make it with component2d({ key }), or register it explicitly: addNode(\"myKey\", TheClass).`,\n );\n }\n const descriptor: NodeTypeDescriptor = typeof declared === \"string\" ? { key: declared } : declared;\n const key = descriptor.key;\n\n const existing = this._nodes.get(key);\n if (existing) {\n if (existing.ctor === cls) return this;\n if (!options?.replace) {\n throw new Error(\n `Node type \"${key}\" is already registered to a different class ` +\n `(${existing.ctor.name} vs ${cls.name}). Keys must be unique — a document ` +\n `naming this type would otherwise resolve differently depending on registration order.`,\n );\n }\n }\n\n const commands = new Map<string, NodeCommandEntry>();\n for (const meta of getCommandMeta(Object.create(cls.prototype) as object)) {\n commands.set(meta.key, {\n method: meta.method,\n args: this._describeArgs(meta.args),\n ...(meta.entrance ? { entrance: true as const } : {}),\n });\n }\n\n this._nodes.set(key, {\n key,\n ctor: cls,\n commands,\n // Derived, never declared: see `NodeTypeDescriptor.properties`.\n descriptor: this._describeEvolution(cls, {\n ...descriptor,\n dimension: this._describeDimension(cls),\n holds: this._describeHolds(cls),\n properties: this._describeProperties(cls),\n }),\n });\n return this;\n }\n\n /**\n * Compile a TS source string into a live node type and register it.\n *\n * The script must `export default` a component (`component2d({ key, … })`),\n * whose `key` supplies the registry key, exactly as {@link addNode}\n * already reads it off a statically-imported one. There is no separate\n * `key` parameter: one way to name a dynamic node's key, not two that\n * could disagree.\n *\n * Requires `dynamicNodes` to have been passed to the constructor — see\n * {@link DynamicNodeConfig}. `core` never compiles anything itself; this\n * only calls the host-supplied `compile` and links its result.\n */\n async addNodeFromSource(source: string, options?: { replace?: boolean }): Promise<NodeConstructor> {\n if (!this._dynamicNodes) {\n throw new Error(\n \"addNodeFromSource needs `dynamicNodes: { sdk, compile }` on the Registry constructor.\",\n );\n }\n const js = await this._dynamicNodes.compile(source);\n const ctor = this._evalNodeModule(js);\n this.addNode(ctor, options);\n return ctor;\n }\n\n /** Everything registered under `key`, or `undefined`. */\n node(key: string): NodeTypeRecord | undefined {\n return this._nodes.get(key);\n }\n\n /** Whether a document naming `key` can be compiled against this registry. */\n hasNode(key: string): boolean {\n return this._nodes.has(key);\n }\n\n /** Every registered node key, for a host offering a palette. Sorted, so the order is stable. */\n nodeKeys(): string[] {\n return [...this._nodes.keys()].sort();\n }\n\n /** What `key` declares about itself, or `undefined` if it is not registered. */\n describe(key: string): NodeTypeDescriptor | undefined {\n return this._nodes.get(key)?.descriptor;\n }\n\n /**\n * Build a node from its spec. Throws on an unknown type.\n *\n * The props pass through the type's own evolution first (`migrateNodeProps`),\n * so a row written before a prop was renamed still sets it.\n *\n * `props` overrides the spec's own, which is how the timeline keeps an\n * expression out of a constructor: an expression-bound prop is left out of\n * what is passed here and written afterwards with `set()`. Constructors read\n * their raw props to decide things like a default size, and a `() => number`\n * is not an answer to that question. The spec's `id` outranks both, so\n * {@link Node.id} is the document's own identity rather than a per-instance\n * UUID — without it a host could never resolve a node it addressed by id.\n *\n * `key` rides along the same way, and only when the row carries one:\n * `applyEditorStates` keys the whole editor-state record on {@link Node.key},\n * so a row whose key never reached the node is a node a host cannot hide or\n * lock — and overwriting one passed in `props` with an absent row-level key\n * would take that away from a caller who had it working.\n */\n instantiate(spec: NodeSpec, props?: Record<string, unknown>): Node {\n const record = this._nodes.get(spec.type);\n if (!record) {\n throw new Error(\n `Unknown node type \"${spec.type}\" (node ${spec.id}). ` +\n `This registry knows: ${this.nodeKeys().join(\", \") || \"nothing\"}.`,\n );\n }\n const evolution = propEvolutionOf(record.ctor);\n const given = props ?? spec.props;\n return new record.ctor({\n ...(evolution ? applyPropEvolution(evolution, given).props : given),\n id: spec.id,\n ...(spec.key !== undefined && { key: spec.key }),\n });\n }\n\n // ─── Commands ────────────────────────────────────────────────────────────\n\n /**\n * Register a command that resolves **without** a node — see\n * {@link CommandTypeEntry}. Same uniqueness rule as {@link addNode}.\n */\n addCommand(\n key: string,\n factory: CommandFactory,\n options?: { binds?: boolean; args?: readonly CommandArg[]; method?: string },\n ): this {\n if (this._claimed(key, factory)) return this;\n this._commands.set(key, {\n key,\n scope: \"node\",\n factory,\n ...(options?.args ? { args: this._describeArgs(options.args) } : {}),\n binds: options?.binds,\n ...(options?.method ? { method: options.method } : {}),\n });\n return this;\n }\n\n /**\n * Register a command that writes a **variable** rather than a node.\n *\n * The seam a host reaches for to add its own — a spring, a wiggle, a\n * sample-and-hold — without touching the timeline. `CommandSpec.targetId`\n * names the variable, and the {@link Command} that comes back must be a pure\n * function of `t` like any other.\n */\n addVariableCommand(key: string, factory: VariableCommandFactory): this {\n if (this._claimed(key, factory)) return this;\n this._commands.set(key, { key, scope: \"variable\", factory });\n return this;\n }\n\n /** The node-less command registered under `key`, or `undefined`. */\n command(key: string): CommandTypeEntry | undefined {\n return this._commands.get(key);\n }\n\n /**\n * A factory for `commandKey` on `nodeTypeKey`, or `undefined` if that type\n * does not publish it.\n *\n * Dispatches by **calling the named method**, never by testing the target\n * against a class: a forked component is a different class carrying the same\n * source, and an `instanceof` against the original is false for it.\n */\n nodeCommand(nodeTypeKey: string, commandKey: string): CommandFactory | undefined {\n const record = this._nodes.get(nodeTypeKey);\n const entry = record?.commands.get(commandKey);\n if (!entry) return undefined;\n return (target, args, duration, easing) => {\n const fn = (target as unknown as Record<string, unknown>)[entry.method];\n if (typeof fn !== \"function\") {\n throw new Error(\n `Command \"${commandKey}\" needs a \"${entry.method}\" method on ` +\n `${target.constructor.name}, which has none.`,\n );\n }\n const data: Record<string, unknown> = {};\n for (const arg of entry.args) data[arg.key] = args[arg.key];\n return (fn as (args: CommandArgs) => Command<Record<string, unknown>>)\n .call(target, { data, duration, easing });\n };\n }\n\n /**\n * Whether a node of `nodeTypeKey` takes `commandKey`: one its own table\n * publishes, or a node-less one that acts on a node (`to`, `fillTo`) unless\n * the method it runs is one the type lacks. What a host offers a\n * node is its table and the node-less commands it takes.\n */\n takesCommand(nodeTypeKey: string, commandKey: string): boolean {\n const record = this._nodes.get(nodeTypeKey);\n if (!record) return false;\n if (record.commands.has(commandKey)) return true;\n const global = this._commands.get(commandKey);\n if (global?.scope !== \"node\") return false;\n if (global.method === undefined) return true;\n return typeof (record.ctor.prototype as Record<string, unknown>)[global.method] === \"function\";\n }\n\n /**\n * Every command key available. With a node type, that type's own table;\n * without one, the node-less commands. Sorted, so the order is stable.\n */\n commandKeys(nodeTypeKey?: string): string[] {\n const keys = nodeTypeKey === undefined\n ? this._commands.keys()\n : this._nodes.get(nodeTypeKey)?.commands.keys() ?? [];\n return [...keys].sort();\n }\n\n // ─── Variable lerps ──────────────────────────────────────────────────────\n\n /**\n * Register an interpolation under a document key.\n *\n * The **code** half of a variable, exactly as a node class is the code half\n * of a node: `{\"lerp\": \"color\"}` in a document is a string, and something\n * has to turn it into the function that blends two colours. Same uniqueness\n * rule as {@link addNode}.\n */\n addLerp(key: string, lerp: VariableLerp): this {\n const existing = this._lerps.get(key);\n if (existing && existing !== lerp) {\n throw new Error(\n `Variable lerp \"${key}\" is already registered to a different function. Keys must be unique.`,\n );\n }\n this._lerps.set(key, lerp);\n return this;\n }\n\n /** The lerp registered under `key`, or `undefined`. */\n lerp(key: string): VariableLerp | undefined {\n return this._lerps.get(key);\n }\n\n /** Every registered lerp key. Sorted, so the order is stable. */\n lerpKeys(): string[] {\n return [...this._lerps.keys()].sort();\n }\n\n /**\n * The lerp a `VariableSpec` resolves to, defaulting from its value.\n *\n * A numeric variable with no declared lerp interpolates; anything else snaps\n * at the end. That is less a fallback than the only honest default —\n * guessing a structural lerp off one sample would blend two objects that\n * merely share an `x` key into something neither of them is.\n */\n requireLerp(key: string | undefined, value: unknown, where: string): VariableLerp {\n const resolved = key ?? (typeof value === \"number\" ? \"number\" : \"step\");\n const lerp = this._lerps.get(resolved);\n if (!lerp) {\n throw new Error(\n `Unknown variable lerp \"${resolved}\" (${where}). ` +\n `Registered: ${this.lerpKeys().join(\", \") || \"none\"}.`,\n );\n }\n return lerp;\n }\n\n // ─── Custom eases ────────────────────────────────────────────────────────\n\n /**\n * Register a custom ease under a document key, referenced as\n * `{ kind: \"custom\", args: key }`. Same uniqueness rule as {@link addNode}.\n */\n addEase(key: string, ease: EasingFunction): this {\n const existing = this._eases.get(key);\n if (existing && existing !== ease) {\n throw new Error(\n `Ease \"${key}\" is already registered to a different function. Keys must be unique.`,\n );\n }\n this._eases.set(key, ease);\n return this;\n }\n\n /** The ease registered under `key`, or `undefined`. */\n ease(key: string): EasingFunction | undefined {\n return this._eases.get(key);\n }\n\n /** Every registered ease key. Sorted, so the order is stable. */\n easeKeys(): string[] {\n return [...this._eases.keys()].sort();\n }\n\n // ─── Shaders ─────────────────────────────────────────────────────────────\n\n /**\n * Register a shader pack under a document key.\n *\n * The key is an argument rather than a field of the pack — the same shape\n * {@link addNode} has — so one file can be registered under whatever name a\n * project wants and stays portable between them. A pack's own `id`, when it\n * has one, is provenance.\n *\n * The pack is normalised on the way in, so what comes back out of\n * {@link shader} is always the current shape whatever the file looked like.\n * Re-registering an equal pack is a no-op — the common case is the *same\n * file* imported twice, which produces two structurally identical objects,\n * and throwing on that would make the uniqueness rule fire on the one case\n * it is meant to tolerate.\n *\n * Pass `{ replace: true }` to overwrite a key with a genuinely different\n * pack — the same opt-in `addNode` takes, for the same reason: a live-edited\n * shader re-registering under its existing key.\n */\n addShader(key: string, pack: unknown, options?: { replace?: boolean }): Shader {\n const normalized = normalizeShaderPack(pack);\n const existing = this._shaders.get(key);\n if (existing) {\n if (\n existing.scope === normalized.scope\n && existing.source === normalized.source\n && existing.name === normalized.name\n ) return existing;\n if (!options?.replace) {\n throw new Error(\n `Shader \"${key}\" is already registered to a different pack ` +\n `(\"${existing.name}\" vs \"${normalized.name}\"). Keys must be unique — a document ` +\n `naming this shader would otherwise resolve differently depending on registration order.`,\n );\n }\n } else if (this._shaders.size >= Registry.MAX_SHADERS) {\n throw new Error(\n `Cannot register shader \"${key}\": the ${Registry.MAX_SHADERS}-shader ceiling is reached.`,\n );\n }\n this._shaders.set(key, normalized);\n return normalized;\n }\n\n /** The pack registered under `key`, or `undefined`. */\n shader(key: string): Shader | undefined {\n return this._shaders.get(key);\n }\n\n /**\n * The pack registered under `key`, if it is a **fill** shader.\n *\n * The typed accessors are what actually deliver the compile error the union\n * promises: {@link shader} hands back `Shader`, and a call site that never\n * narrows could still pass an effect pack to `Fills.shader`.\n */\n fillShader(key: string): FillShader | undefined {\n const pack = this._shaders.get(key);\n return pack?.scope === \"fill\" ? pack : undefined;\n }\n\n /** The pack registered under `key`, if it is an **effect** shader. */\n effectShader(key: string): EffectShader | undefined {\n const pack = this._shaders.get(key);\n return pack?.scope === \"effect\" ? pack : undefined;\n }\n\n /** Every registered shader key, for a host offering a picker. Sorted. */\n shaderKeys(): string[] {\n return [...this._shaders.keys()].sort();\n }\n\n // ─── Internals ───────────────────────────────────────────────────────────\n\n private readonly _nodes = new Map<string, NodeTypeRecord>();\n private readonly _commands = new Map<string, CommandTypeEntry>();\n private readonly _lerps = new Map<string, VariableLerp>();\n private readonly _eases = new Map<string, EasingFunction>();\n private readonly _shaders = new Map<string, Shader>();\n private readonly _dynamicNodes?: DynamicNodeConfig;\n\n /**\n * Evaluates one compiled (CommonJS) dynamic-node module in the current\n * realm and returns its default export.\n *\n * `new Function` in-realm, never a blob module or a worker — see\n * {@link DynamicNodeConfig} and `deny-globals.ts` for why. `require()` is\n * locked to exactly `\"@motionscript/sdk\"` (plus the earlier unscoped `\"motionscript\"` and `\"motion-script\"`\n * spellings, so a script written under either name still compiles) and\n * the host's `modules`, own keys only so `require(\"constructor\")` cannot\n * reach `Object`. No relative\n * imports, since a dynamic node is one script, not a package.\n */\n private _evalNodeModule(js: string): NodeConstructor {\n const { sdk, modules } = this._dynamicNodes!;\n const require = (specifier: string): unknown => {\n if (SDK_SPECIFIERS.includes(specifier)) return sdk;\n if (modules && Object.hasOwn(modules, specifier)) return modules[specifier];\n const available = [\"@motionscript/sdk\", ...Object.keys(modules ?? {})];\n throw new Error(\n `\"${specifier}\" isn't available to a custom node. It can require ` +\n `${available.map((s) => `\"${s}\"`).join(\", \")}; a host supplies more through \\`dynamicNodes.modules\\`.`,\n );\n };\n const mod = { exports: {} as Record<string, unknown> };\n // The script runs one function in from the parameters that deny the\n // globals, so its own top-level `const frames` shadows a denied name\n // instead of redeclaring a parameter. A body that closes that function\n // early is still inside the outer one, which denies the same names.\n const factory = new Function(\n \"exports\", \"require\", \"module\", ...DENIED_GLOBALS,\n `\"use strict\";\\nreturn function () {\\n${js}\\n};`,\n );\n factory(mod.exports, require, mod)();\n\n const ctor = mod.exports.default as (NodeConstructor & { node?: NodeConstructor }) | undefined;\n if (typeof ctor !== \"function\" || getNodeDescriptor(typeof ctor.node === \"function\" ? ctor.node : ctor) === undefined) {\n throw new Error(\"This script must `export default` a component: `component2d({ key: \\\"…\\\", … })`.\");\n }\n return ctor;\n }\n\n /** One key, one factory — see {@link addNode} for why. */\n private _claimed(key: string, factory: CommandFactory | VariableCommandFactory): boolean {\n const existing = this._commands.get(key);\n if (!existing) return false;\n if (existing.factory === factory) return true;\n throw new Error(\n `Command type \"${key}\" is already registered to a different factory. Keys must be unique.`,\n );\n }\n\n /**\n * A class's editable properties, read off its `property` declarations.\n *\n * The whole prototype chain, so a component publishes the box its tree's\n * base declares as well as its own entries — a host editing one edits every\n * control it actually has.\n */\n private _describeProperties(ctor: NodeConstructor): Record<string, NodePropertyDescriptor> {\n const out: Record<string, NodePropertyDescriptor> = {};\n for (const meta of getPropertyMeta(Object.create(ctor.prototype) as object)) {\n const editor: PropertyEditor = meta.editor ?? {};\n out[meta.key] = {\n ...editor,\n kind: editor.kind ?? this._inferKind(meta.default),\n ...(meta.default !== undefined ? { default: meta.default } : {}),\n };\n }\n return out;\n }\n\n /** A component's `renamed` and `deprecated`, where a host reading the descriptor sees them. */\n private _describeEvolution(ctor: NodeConstructor, descriptor: NodeTypeDescriptor): NodeTypeDescriptor {\n const evolution = propEvolutionOf(ctor);\n if (!evolution) return descriptor;\n const properties = { ...descriptor.properties };\n for (const [key, message] of Object.entries(evolution.deprecated)) {\n if (properties[key]) properties[key] = { ...properties[key], deprecated: message };\n }\n const renamed = Object.keys(evolution.renamed).length > 0 ? { renamed: { ...evolution.renamed } } : {};\n return { ...descriptor, ...renamed, properties };\n }\n\n /**\n * A type's dimension, read off the prototype without constructing one.\n *\n * `Node.dimension` is a getter rather than a field for exactly this reason —\n * it answers from the prototype, before any field initializer has run.\n */\n private _describeDimension(ctor: NodeConstructor): NodeDimension | undefined {\n const dimension = (Object.create(ctor.prototype) as Node).dimension;\n return typeof dimension === \"string\" ? dimension : undefined;\n }\n\n /** The trees a type takes children from, off the prototype as its dimension is. */\n private _describeHolds(ctor: NodeConstructor): readonly NodeDimension[] | undefined {\n const trees = (Object.create(ctor.prototype) as Partial<Node>)._childTrees;\n return Array.isArray(trees) ? [...trees] : undefined;\n }\n\n /**\n * The control a value's own type implies. Only ever a fallback: a typed\n * property states its kind, and a plain `property` may too.\n *\n * A function default is a *reactive binding*, not a value, so it says nothing\n * about the control; those declare their kind or take \"unknown\", which a host\n * draws as read-only rather than guessing.\n */\n private _inferKind(value: unknown): string {\n switch (typeof value) {\n case \"number\": return \"number\";\n case \"string\": return \"text\";\n case \"boolean\": return \"boolean\";\n case \"object\":\n if (value === null) return \"unknown\";\n return Array.isArray(value) && value.every(v => typeof v === \"number\")\n ? \"vector\"\n : \"object\";\n default: return \"unknown\";\n }\n }\n\n /** A command's arguments as descriptors, whichever shorthand they were written in. */\n private _describeArgs(args: readonly CommandArg[] | undefined): CommandArgDescriptor[] {\n return (args ?? []).map((arg) =>\n typeof arg === \"string\" ? { key: arg, kind: \"unknown\" } : { kind: \"unknown\", ...arg });\n }\n}\n", "import type { Registry } from \"./registry\";\nimport { ROOT_NODE_ID, type NodeSpec } from \"./types\";\n\n/**\n * Where a node type may go, read off the registry without building anything:\n * the answer a host needs before it offers a type under a parent, accepts a\n * drop, or lets an assistant create a row.\n *\n * Four things decide it. A parent that takes no children takes none. The two\n * trees do not mix: a `Node3D` lives under a Canvas 3D or another 3D node, and\n * nothing else does. A type that names where it goes ({@link\n * NodeTypeDescriptor.within}) goes only there, and a {@link\n * NodeTypeDescriptor.closed} parent takes only the types that name it. Those\n * are about the parent; {@link NodeTypeDescriptor.beside} is about the\n * siblings, and is kept apart because a host can meet it by adding one.\n *\n * Only a leaf is enforced when a document is built: a component declaring\n * `allowedChildren: []` throws on a child. A node in any other wrong place\n * builds and, as a rule, draws nothing; this says why.\n */\n\n/** Why a node of a type is not where it can work. */\nexport type PlacementIssue =\n /** The parent takes no children. */\n | { kind: \"leaf\"; parent: string }\n /** A 3D node outside a 3D tree, or anything else inside one. */\n | { kind: \"dimension\"; parent: string | null }\n /** It goes inside one of `within`, and the parent is none of them. */\n | { kind: \"within\"; within: readonly string[] }\n /** The parent takes only the types that name it. */\n | { kind: \"closed\"; parent: string }\n /** It needs one of `beside` under the same parent, and there is none. */\n | { kind: \"beside\"; beside: readonly string[] };\n\nexport interface PlacementOptions {\n /**\n * A host's own sense of one type standing for another, beside the\n * registry's: a copy of a component it made under a new key is still that\n * component to whatever goes inside it.\n */\n isA?: (type: string, name: string) => boolean;\n}\n\n/** The one core type whose children are of the other dimension. */\nconst CANVAS_3D = \"canvas3d\";\n\n/** Whether `type` is `name`, or is built on it through `parentKey`. */\nexport function nodeTypeIsA(registry: Registry, type: string, name: string): boolean {\n const seen = new Set<string>();\n for (let at: string | undefined = type; at !== undefined && !seen.has(at); at = registry.describe(at)?.parentKey) {\n if (at === name) return true;\n seen.add(at);\n }\n return false;\n}\n\nfunction among(registry: Registry, type: string, names: readonly string[], options: PlacementOptions): boolean {\n return names.some((name) => nodeTypeIsA(registry, type, name) || options.isA?.(type, name) === true);\n}\n\n/**\n * Why a node of `child` cannot go directly inside one of `parent`, or `null`\n * when it can. A `null` parent is the document's own root, which is 2D and\n * names nothing.\n */\nexport function parentIssue(\n registry: Registry,\n child: string,\n parent: string | null,\n options: PlacementOptions = {},\n): PlacementIssue | null {\n const own = registry.describe(child);\n const holder = parent === null ? undefined : registry.describe(parent);\n if (parent !== null && (holder?.layout?.acceptsChildren === false || holder?.holds?.length === 0)) return { kind: \"leaf\", parent };\n\n const within = own?.within ?? [];\n if (within.length > 0 && (parent === null || !among(registry, parent, within, options))) {\n return { kind: \"within\", within };\n }\n if (parent !== null && holder?.closed === true && !among(registry, parent, within, options)) {\n return { kind: \"closed\", parent };\n }\n\n const inThree = parent !== null && (holder?.dimension === \"3d\" || holder?.holds?.includes(\"3d\") === true || among(registry, parent, [CANVAS_3D], options));\n if ((own?.dimension === \"3d\") !== inThree) return { kind: \"dimension\", parent };\n return null;\n}\n\n/** The sibling `child` needs that `siblings`, the types already under its parent, do not include; `null` when it needs none or has one. */\nexport function siblingIssue(\n registry: Registry,\n child: string,\n siblings: readonly string[],\n options: PlacementOptions = {},\n): PlacementIssue | null {\n const beside = registry.describe(child)?.beside ?? [];\n if (beside.length === 0 || siblings.some((type) => among(registry, type, beside, options))) return null;\n return { kind: \"beside\", beside };\n}\n\n/**\n * Every node of `nodes` that is not where its type says it goes, by id, with\n * the first reason. A node of an unregistered type is left out: that is a build\n * error, and says so itself.\n */\nexport function placementIssues(\n registry: Registry,\n nodes: readonly Pick<NodeSpec, \"id\" | \"type\" | \"parentId\">[],\n options: PlacementOptions = {},\n): Map<string, PlacementIssue> {\n // A document may write its stage as a row or leave it out: either way its children's parent is the root.\n const parentOf = (node: Pick<NodeSpec, \"parentId\">) => (node.parentId === ROOT_NODE_ID ? null : node.parentId);\n const byId = new Map(nodes.map((node) => [node.id, node]));\n const children = new Map<string | null, string[]>();\n for (const node of nodes) {\n if (node.id === ROOT_NODE_ID) continue;\n const under = children.get(parentOf(node));\n if (under) under.push(node.type);\n else children.set(parentOf(node), [node.type]);\n }\n const issues = new Map<string, PlacementIssue>();\n for (const node of nodes) {\n if (node.id === ROOT_NODE_ID || !registry.hasNode(node.type)) continue;\n const parentId = parentOf(node);\n const parentType = parentId === null ? null : (byId.get(parentId)?.type ?? null);\n const issue =\n parentIssue(registry, node.type, parentType, options) ??\n siblingIssue(registry, node.type, without(children.get(parentId) ?? [], node.type), options);\n if (issue) issues.set(node.id, issue);\n }\n return issues;\n}\n\n// The node's own type once: a second area is a sibling of the first, the first is not its own.\nfunction without(types: readonly string[], own: string): string[] {\n const at = types.indexOf(own);\n return at === -1 ? [...types] : [...types.slice(0, at), ...types.slice(at + 1)];\n}\n", "import type { AudioDocument, ClipDocument, CommandSpec, CompositionDocument, NodeSpec, TimedNodeSpec, VisualDocument } from \"./types\";\nimport { isAudioDocument, isStillDocument, nodeSpan } from \"./types\";\n\n/**\n * The id the authored root bus is rewritten to.\n *\n * Namespaced like every other synthesized id in the document layer, so it can\n * never collide with one a document authored itself.\n */\nconst AUDIO_ROOT_ID = \"@bus\";\n\n/** The root bus when an audio document doesn't author one explicitly. */\nfunction defaultRootBus(): NodeSpec {\n return { id: AUDIO_ROOT_ID, type: \"audioBus\", parentId: null, layerOrder: 0, props: {} };\n}\n\n/** The root a lowered audio clip hangs from. Draws nothing; lays out once. */\nfunction clipRoot(): NodeSpec {\n return { id: \"\", type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} };\n}\n\n/**\n * An audio document, as the composition it already is.\n *\n * There is no second evaluator for sound, and this is what keeps it that way:\n * an audio clip is compiled, seeked and restored by `ClipTimeline` like any\n * other, so a bus fade and a rectangle's fade cannot drift because there is only\n * one machine running them.\n *\n * The only thing that has to be arranged is the root. An audio document's own\n * root is a bus, but a clip's root is always a `Canvas2D` — so the bus\n * becomes that canvas's single audio child under {@link AUDIO_ROOT_ID}, and\n * every `targetId: null` / `parentId: null` is rewritten to name it. The canvas\n * draws nothing and lays out an empty box once, which is the whole cost of a\n * clip that is only sound.\n */\nexport function loweredAudioDocument(doc: AudioDocument): CompositionDocument {\n const nodes: TimedNodeSpec[] = [clipRoot()];\n if (!doc.nodes.some(isRootBus)) nodes.push(defaultRootBus());\n for (const spec of doc.nodes) nodes.push(reparent(spec));\n\n return {\n kind: \"composition\",\n duration: doc.duration,\n variables: doc.variables,\n nodes,\n commands: doc.commands.map(retarget),\n };\n}\n\n/** The row an audio document means as its root bus. */\nfunction isRootBus(spec: NodeSpec): boolean {\n return spec.id === \"\" && spec.type === \"audioBus\";\n}\n\n/** A node spec with the implicit root resolved to {@link AUDIO_ROOT_ID}. */\nfunction reparent(spec: TimedNodeSpec): TimedNodeSpec {\n if (isRootBus(spec)) return { ...spec, id: AUDIO_ROOT_ID, parentId: null };\n // `null` is the document's own convention for \"the root\"; `\"\"` is the same\n // row named by id, which `checkTree` also resolves. Both mean the bus.\n if (spec.parentId === null || spec.parentId === \"\") return { ...spec, parentId: AUDIO_ROOT_ID };\n return spec;\n}\n\n/** A command with the implicit root resolved to {@link AUDIO_ROOT_ID}. */\nfunction retarget(command: CommandSpec): CommandSpec {\n if (command.targetId === null || command.targetId === \"\") {\n return { ...command, targetId: AUDIO_ROOT_ID };\n }\n return command;\n}\n\nexport { AUDIO_ROOT_ID };\n\n/**\n * A `sound` or `video` row with no `play` command of its own plays as it did\n * before sound came only from commands: a sound over its span (open-ended, to\n * its own end), a video once per segment, or over its span while it plays.\n */\nexport function withPlayedSounds(doc: CompositionDocument): CompositionDocument {\n const played = new Set(doc.commands.filter((c) => c.type === \"play\").map((c) => c.targetId));\n const added: CommandSpec[] = [];\n for (const spec of doc.nodes) {\n if ((spec.type !== \"sound\" && spec.type !== \"video\") || played.has(spec.id)) continue;\n const { start, end } = nodeSpan(spec);\n const segments = spec.type === \"video\" ? (spec.props as { segments?: unknown }).segments : undefined;\n if (Array.isArray(segments) && segments.length > 0) {\n (segments as { at: number; from: number; duration: number; speed?: number; volume?: number }[]).forEach((segment, i) => {\n added.push({\n // An endless segment plays to the source's end: a command has no endless length.\n id: `@play:${spec.id}:${i}`, type: \"play\", targetId: spec.id, at: start + segment.at,\n duration: Number.isFinite(segment.duration) ? segment.duration : 0,\n args: {\n from: segment.from,\n ...(segment.speed !== undefined && { speed: segment.speed }),\n ...(segment.volume !== undefined && { volume: segment.volume }),\n },\n });\n });\n continue;\n }\n added.push({\n id: `@play:${spec.id}`, type: \"play\", targetId: spec.id, at: start,\n duration: Number.isFinite(end) ? end - start : 0, args: {},\n });\n }\n return added.length === 0 ? doc : { ...doc, commands: [...doc.commands, ...added] };\n}\n\n/** A clip as its timeline builds it: an audio document lowered to the composition it is, its sounds played. */\nexport function clipDocument(doc: ClipDocument): VisualDocument {\n const lowered = isAudioDocument(doc) ? loweredAudioDocument(doc) : doc;\n return isStillDocument(lowered) ? lowered : withPlayedSounds(lowered);\n}\n", "import { Node } from \"@/components/trees/node/node\";\nimport { expressionOps } from \"./expression/ops\";\nimport { Registry, type NodeConstructor } from \"./registry\";\nimport type { CommandSpec, NodeSpec } from \"./types\";\nimport { ROOT_NODE_ID } from \"./types\";\n\n/**\n * What a command can do to the tree around it, read off the document and the\n * registry without building anything.\n *\n * Only the library's own implementations are described: a command resolving to a\n * component's method could do anything, so it is `known: false` and assumed to\n * read and write layout.\n */\nexport interface CommandTraits {\n scope: \"node\" | \"variable\";\n /** Resolves to the library's own implementation, so the rules below hold for it. */\n known: boolean;\n lifecycle: boolean;\n /** Building it can read a laid-out box, so it must be built against a settled tree. */\n readsLayout: boolean;\n /** Running it can change what layout computes. */\n writesLayout: boolean;\n}\n\n/** The nine named alignment props, which position a node against its own laid-out box. */\nexport const ALIGNMENT_KEYS: readonly string[] = [\n \"center\", \"topLeft\", \"topRight\", \"bottomLeft\", \"bottomRight\",\n \"topCenter\", \"bottomCenter\", \"centerLeft\", \"centerRight\",\n];\n\nconst SKIPPED: CommandTraits = { scope: \"node\", known: true, lifecycle: false, readsLayout: false, writesLayout: false };\n\n/**\n * How a document command resolves, as `ClipTimeline._buildPlaced` resolves it,\n * and what it does — or `null` when it resolves to nothing (compiling it throws).\n * One the build skips — aimed at a placeholder, or unpublished by its target's\n * type — writes nothing, which is known.\n * `target` is the command's target row; for `targetId: null` a document with no\n * explicit root row may pass `undefined`.\n */\nexport function commandTraits(registry: Registry, spec: CommandSpec, target: NodeSpec | undefined): CommandTraits | null {\n const lifecycle = LIFECYCLE.has(spec.type);\n const global = registry.command(spec.type);\n if (global?.scope === \"variable\") {\n const known = VARIABLE_COMMANDS.has(spec.type);\n return { scope: \"variable\", known, lifecycle, readsLayout: !known, writesLayout: false };\n }\n\n const row = target ?? (spec.targetId === null ? DEFAULT_ROOT : undefined);\n const record = row ? registry.node(row.type) : undefined;\n if (!row) return null;\n if (!record) return registry.strict ? null : SKIPPED;\n\n let chain: readonly string[] | undefined;\n if (global) {\n chain = GLOBAL_NODE_COMMANDS[spec.type];\n if (chain && typeof methodOf(record.ctor, chain[0]) !== \"function\") return null;\n } else {\n const entry = record.commands.get(spec.type);\n if (!entry) return registry.strict ? null : SKIPPED;\n // A method published under a core command's key is not the core command.\n chain = entry.method === spec.type ? NODE_COMMANDS[spec.type] : undefined;\n }\n\n const known = !lifecycle && chain !== undefined && implementsCore(record.ctor, chain);\n if (!known) return { scope: \"node\", known, lifecycle, readsLayout: true, writesLayout: true };\n\n const args = spec.args ?? {};\n const props = row.props ?? {};\n const written = writtenKeys(spec.type, args);\n return {\n scope: \"node\",\n known,\n lifecycle,\n readsLayout: readsLayout(spec.type, args, props, written),\n writesLayout: written === undefined || written.some((key) => !isLayoutNeutralProp(registry, row.type, key)),\n };\n}\n\n/**\n * Whether a command with these traits, built, may be held at its end values once\n * finished instead of run (`settled-index.ts`): the library's own implementation\n * of a command whose `at` reads only what it captured when built. Expression args\n * bind live values, so they keep it running. A component's own commands are\n * marked by the factory instead, from their pieces.\n */\nexport function holdsWhenFinished(traits: CommandTraits | null, spec: CommandSpec): boolean {\n return traits !== null && traits.known && !traits.lifecycle && HELD.has(spec.type)\n && expressionOps.collect(spec.args ?? {}, \"\").length === 0;\n}\n\n/**\n * The node ids a command's args name through a `nodeRef` argument — the nodes\n * whose boxes it may read when it is built, beside its own target.\n */\nexport function commandNodeRefs(registry: Registry, spec: CommandSpec, target: NodeSpec | undefined): string[] {\n const global = registry.command(spec.type);\n const row = target ?? (spec.targetId === null ? DEFAULT_ROOT : undefined);\n const descriptors = global\n ? (global.scope === \"node\" ? global.args : undefined)\n : row ? registry.node(row.type)?.commands.get(spec.type)?.args : undefined;\n const refs: string[] = [];\n for (const descriptor of descriptors ?? []) {\n const value = spec.args?.[descriptor.key];\n if (descriptor.kind === \"nodeRef\" && typeof value === \"string\" && value !== \"\") refs.push(value);\n }\n return refs;\n}\n\n/** Whether `type` hands its descendants a context of its own. */\nexport function isContextProvider(registry: Registry, type: string): boolean {\n const ctor = registry.node(type)?.ctor;\n return ctor !== undefined && methodOf(ctor, \"provideContext\") !== methodOf(Node, \"provideContext\");\n}\n\n/**\n * Whether an authored value holds an expression reading another node's prop\n * (`[card.x]`), at any depth. An unparsable one counts: it fails the build anyway.\n */\nexport function hasNodeRef(value: unknown): boolean {\n for (const site of expressionOps.collect(value, \"\")) {\n const parsed = expressionOps.tryParse(site.source);\n if (\"error\" in parsed || parsed.expression.refs.some((ref) => ref.includes(\".\"))) return true;\n }\n return false;\n}\n\n/**\n * Whether writing `key` on a node of `type` leaves every laid-out box unchanged.\n *\n * Every node's placement is applied after layout; past that, answered only for\n * the library's own classes, since a custom node may lay itself out from anything.\n */\nexport function isLayoutNeutralProp(registry: Registry, type: string, key: string): boolean {\n const record = registry.node(type);\n if (!record) return false;\n // Sound has no box, and the 2D walk skips an audio child.\n if (record.descriptor.dimension === \"audio\") return true;\n if (isPlacementProp(registry, type, key)) return true;\n return coreLibrary().ctors.has(record.ctor) && NEUTRAL_KEYS.has(key);\n}\n\n/** Whether `key` is placement every node of `type` holds as a plain slot, read only once a frame is drawn. */\nexport function isPlacementProp(registry: Registry, type: string, key: string): boolean {\n const dimension = registry.node(type)?.descriptor.dimension;\n return dimension === \"3d\" ? PLACEMENT_3D.has(key) : dimension === \"2d\" && PLACEMENT_2D.has(key);\n}\n\n/**\n * Whether a new `key` on `row` can be written onto its live node as a fresh\n * build would set it: placement, on a row with no prop its node turns into\n * placement when built (`topLeft` binds `x` and `y`).\n */\nexport function writesPlacementInPlace(registry: Registry, row: NodeSpec, key: string): boolean {\n const dimension = registry.node(row.type)?.descriptor.dimension;\n const sugar = dimension === \"3d\" ? PLACEMENT_SUGAR_3D : PLACEMENT_SUGAR_2D;\n return isPlacementProp(registry, row.type, key) && !Object.keys(row.props).some((prop) => sugar.has(prop));\n}\n\nconst LIFECYCLE = new Set([\"removeChildAt\", \"addChildAt\", \"reparent\"]);\n\nconst VARIABLE_COMMANDS = new Set([\"variableTo\", \"variableSet\"]);\n\n// Known commands that are pure functions of `t`. A new one joins once `held-class-commands.test.ts` covers it.\nconst HELD = new Set([\n \"to\", \"set\", \"moveTo\", \"fadeTo\", \"rotateTo\", \"scaleTo\", \"layoutTo\", \"effectTo\", \"pulse\", \"wiggle\",\n \"fillTo\", \"strokeTo\", \"shadowTo\", \"overlayTo\", \"progressTo\", \"zoomTo\", \"panTo\", \"headingTo\",\n \"variableTo\", \"variableSet\",\n]);\n\nconst NEUTRAL_KEYS = new Set([\n \"x\", \"y\", \"rotation\", \"scale\", \"opacity\", \"fill\", \"stroke\", \"shadow\", \"overlay\",\n \"effects\", \"blend\", \"transformOrigin\", \"zoom\", \"lookAt\", \"heading\",\n]);\n\nconst PLACEMENT_2D = new Set([\"x\", \"y\", \"rotation\", \"scale\", \"opacity\"]);\n\nconst PLACEMENT_3D = new Set([\"x\", \"y\", \"z\", \"rotationX\", \"rotationY\", \"rotationZ\", \"scaleX\", \"scaleY\", \"scaleZ\"]);\n\nconst PLACEMENT_SUGAR_2D = new Set([\n \"center\", \"topLeft\", \"topRight\", \"bottomLeft\", \"bottomRight\", \"topCenter\", \"bottomCenter\", \"centerLeft\", \"centerRight\",\n]);\n\nconst PLACEMENT_SUGAR_3D = new Set([\"position\", \"rotation\", \"scale\"]);\n\nconst DEFAULT_ROOT: NodeSpec = { id: ROOT_NODE_ID, type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} };\n\n// Each command's behaviour, as the methods on its target it runs through. A class\n// overriding any of them is running something else under the command's name.\nconst TO = [\"to\", \"_prepareStep\", \"_writeProp\"];\nconst PAINT = [\"command\", \"set\", \"_writeProp\"];\n\nconst GLOBAL_NODE_COMMANDS: Readonly<Record<string, readonly string[]>> = {\n to: TO,\n set: [\"set\", \"_writeProp\"],\n save: [\"save\"],\n fillTo: [\"fillTo\", ...PAINT],\n overlayTo: [\"overlayTo\", ...PAINT],\n strokeTo: [\"strokeTo\", ...PAINT],\n shadowTo: [\"shadowTo\", ...PAINT],\n};\n\nconst NODE_COMMANDS: Readonly<Record<string, readonly string[]>> = {\n ...GLOBAL_NODE_COMMANDS,\n restore: [\"restore\", \"_prepareStep\", \"_writeProp\"],\n fadeTo: [\"fadeTo\", ...TO],\n rotateTo: [\"rotateTo\", ...TO],\n scaleTo: [\"scaleTo\", ...TO],\n layoutTo: [\"layoutTo\", ...TO],\n effectTo: [\"effectTo\", ...TO],\n progressTo: [\"progressTo\", ...TO],\n pulse: [\"pulse\", ...PAINT],\n wiggle: [\"wiggle\", ...PAINT],\n flash: [\"flash\", ...PAINT],\n moveTo: [\"moveTo\", ...TO, \"command\", \"set\"],\n zoomTo: [\"zoomTo\", ...TO],\n panTo: [\"panTo\", ...TO],\n headingTo: [\"headingTo\", ...TO],\n countTo: [\"countTo\", ...TO],\n append: [\"append\", ...TO],\n prepend: [\"prepend\", ...TO],\n // Plays its node's sound: scheduled ahead of time, writing nothing.\n play: [\"play\"],\n};\n\n/** Named commands' writes. `to`/`set` write their args; absent means \"anything\". */\nconst WRITES: Readonly<Record<string, readonly string[]>> = {\n fadeTo: [\"opacity\"],\n rotateTo: [\"rotation\"],\n scaleTo: [\"scale\"],\n layoutTo: [\"width\", \"height\", \"padding\"],\n effectTo: [\"effects\"],\n progressTo: [\"start\", \"end\"],\n pulse: [\"scale\"],\n wiggle: [\"rotation\"],\n flash: [\"start\", \"end\"],\n moveTo: [\"x\", \"y\"],\n zoomTo: [\"zoom\"],\n panTo: [\"lookAt\"],\n headingTo: [\"heading\"],\n fillTo: [\"fill\"],\n overlayTo: [\"overlay\"],\n strokeTo: [\"stroke\"],\n shadowTo: [\"shadow\"],\n play: [],\n};\n\n/** What a known command reads `from` — every command but the stamps. */\nconst READS_FROM = new Set(Object.keys(NODE_COMMANDS).filter((type) => type !== \"set\" && type !== \"save\"));\n\nfunction readsLayout(\n type: string,\n args: Record<string, unknown>,\n props: Record<string, unknown>,\n written: readonly string[] | undefined,\n): boolean {\n // Resolved against the node's own box the moment the step is prepared.\n if (hasAlignmentKey(args)) return true;\n // Aimed at another node's box.\n if (type === \"moveTo\" && typeof args.target === \"string\" && args.target !== \"\") return true;\n // An alignment-authored node's x/y are bindings over its box, and a node-ref\n // expression may read another node's (`[card.x]` on an aligned card); taking a\n // `from`, or a snapshot, evaluates them.\n const aligned = hasAlignmentKey(props);\n const refBound = nodeRefKeys(props);\n if (type === \"save\" || type === \"restore\") return aligned || refBound.size > 0;\n if (!READS_FROM.has(type)) return false;\n const touched = type === \"append\" || type === \"prepend\" ? [\"text\"] : type === \"countTo\" ? [\"value\"] : written ?? [];\n return touched.some((key) => refBound.has(key) || (aligned && (key === \"x\" || key === \"y\")));\n}\n\nfunction writtenKeys(type: string, args: Record<string, unknown>): readonly string[] | undefined {\n const named = WRITES[type];\n if (named) return named;\n if (type !== \"to\" && type !== \"set\") return undefined;\n const keys: string[] = [];\n for (const key of Object.keys(args)) {\n if (key === \"size\") keys.push(\"width\", \"height\");\n else if (type === \"to\" && key === \"pivot\") keys.push(\"transformOrigin\");\n else if (type === \"to\" && ALIGNMENT_KEYS.includes(key)) keys.push(\"x\", \"y\", \"transformOrigin\");\n else keys.push(key);\n }\n return keys;\n}\n\nfunction hasAlignmentKey(values: Record<string, unknown>): boolean {\n return ALIGNMENT_KEYS.some((key) => values[key] !== undefined);\n}\n\nconst REF_KEYS = new WeakMap<object, ReadonlySet<string>>();\n\n/** The top-level props of a row whose authored value reads another node. */\nfunction nodeRefKeys(props: Record<string, unknown>): ReadonlySet<string> {\n let keys = REF_KEYS.get(props);\n if (!keys) {\n const found = new Set<string>();\n for (const key of Object.keys(props)) {\n if (hasNodeRef(props[key])) found.add(key);\n }\n REF_KEYS.set(props, (keys = found));\n }\n return keys;\n}\n\nfunction methodOf(ctor: abstract new (...args: never[]) => unknown, name: string): unknown {\n return (ctor.prototype as Record<string, unknown>)[name];\n}\n\nconst KNOWN = new WeakMap<object, Map<readonly string[], boolean>>();\n\nfunction implementsCore(ctor: NodeConstructor, chain: readonly string[]): boolean {\n let byChain = KNOWN.get(ctor);\n if (!byChain) KNOWN.set(ctor, (byChain = new Map()));\n let known = byChain.get(chain);\n if (known === undefined) {\n // A method the class lacks entirely is not an override of one.\n known = chain.every((name) => {\n const impl = methodOf(ctor, name);\n return impl === undefined || coreImplementations(name).has(impl);\n });\n byChain.set(chain, known);\n }\n return known;\n}\n\ninterface CoreLibrary {\n ctors: ReadonlySet<NodeConstructor>;\n methods: Map<string, ReadonlySet<unknown>>;\n}\n\nlet core: CoreLibrary | null = null;\n\nfunction coreLibrary(): CoreLibrary {\n if (!core) {\n // A registry seeds itself with exactly what the library ships, so a fresh one is that list.\n const seeded = new Registry();\n core = { ctors: new Set(seeded.nodeKeys().map((key) => seeded.node(key)!.ctor)), methods: new Map() };\n }\n return core;\n}\n\n/** Every body the library's classes give `name`, base classes included. */\nfunction coreImplementations(name: string): ReadonlySet<unknown> {\n const library = coreLibrary();\n let impls = library.methods.get(name);\n if (!impls) {\n const found = new Set<unknown>();\n for (const ctor of library.ctors) {\n for (let proto = ctor.prototype; proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {\n const own = Object.getOwnPropertyDescriptor(proto, name);\n if (own && typeof own.value === \"function\") found.add(own.value);\n }\n }\n library.methods.set(name, (impls = found));\n }\n return impls;\n}\n", "import { clipDocument } from \"./audio\";\nimport {\n documentDuration,\n nodeSpan,\n ROOT_NODE_ID,\n type ClipDocument,\n type CommandSpec,\n type NodeSpec,\n type VisualDocument,\n type TimedNodeSpec,\n type VariableSpec,\n} from \"./types\";\n\n/**\n * Deep equality over JSON values: key order is irrelevant, an `undefined`-valued\n * key equals an absent one (neither survives serialization), arrays are ordered.\n */\nexport function jsonEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) {\n return a !== a && b !== b;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!jsonEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (Array.isArray(b)) return false;\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n let defined = 0;\n for (const key of Object.keys(ao)) {\n const value = ao[key];\n if (value === undefined) continue;\n defined++;\n if (!jsonEqual(value, bo[key])) return false;\n }\n for (const key of Object.keys(bo)) {\n if (bo[key] !== undefined) defined--;\n }\n return defined === 0;\n}\n\nexport interface RowChanges {\n added: Set<string>;\n removed: Set<string>;\n /** Present on both sides with any semantic field different. */\n changed: Set<string>;\n}\n\nexport interface ClipDiff {\n /** Nothing semantic differs — the two documents build the same clip. */\n identical: boolean;\n kindChanged: boolean;\n themeChanged: boolean;\n rootChanged: boolean;\n duration: boolean;\n nodes: RowChanges & {\n /** `type`, `key` or `props` differ. */\n respec: Set<string>;\n /** `parentId` differs. */\n moved: Set<string>;\n /** `startAt` or `endAt` differ, as spans. */\n span: Set<string>;\n /** Parents (`\"\"` for top level) whose kept children sit in a different sibling order. */\n reorderedParents: Set<string>;\n };\n commands: RowChanges & {\n /** `at` values whose kept commands appear in a different relative array order. */\n reorderedAts: Set<number>;\n };\n /** `changed` is `value` or `lerp`; a `name` is a label and never counts. */\n variables: RowChanges;\n /** Keys present on both sides that name a different node id. */\n remappedKeys: Set<string>;\n}\n\nfunction emptyDiff(): ClipDiff {\n return {\n identical: true,\n kindChanged: false,\n themeChanged: false,\n rootChanged: false,\n duration: false,\n nodes: {\n added: new Set(), removed: new Set(), changed: new Set(),\n respec: new Set(), moved: new Set(), span: new Set(), reorderedParents: new Set(),\n },\n commands: { added: new Set(), removed: new Set(), changed: new Set(), reorderedAts: new Set() },\n variables: { added: new Set(), removed: new Set(), changed: new Set() },\n remappedKeys: new Set(),\n };\n}\n\n/**\n * What differs between two versions of one clip, by row id.\n *\n * Only semantic fields are compared, so an edit that cannot change what the\n * clip builds (a variable's `name`, key order inside `props`, `startAt: 0`\n * against an absent one) is not a change. Audio documents are compared as the\n * compositions they lower to, which is what the timeline builds.\n */\nexport function diffClip(prev: ClipDocument, next: ClipDocument): ClipDiff {\n const diff = emptyDiff();\n if (prev === next) return diff;\n\n if (prev.kind !== next.kind) {\n diff.kindChanged = true;\n diff.identical = false;\n return diff;\n }\n\n const p = lowered(prev);\n const n = lowered(next);\n\n diff.themeChanged = !jsonEqual((prev as { theme?: unknown }).theme, (next as { theme?: unknown }).theme);\n diff.duration = documentDuration(p) !== documentDuration(n);\n\n if (prev.nodes !== next.nodes) diffNodes(p.nodes, n.nodes, diff);\n if (prev.variables !== next.variables) diffVariables(p.variables ?? [], n.variables ?? [], diff);\n const prevCommands = p.kind === \"composition\" ? p.commands : [];\n const nextCommands = n.kind === \"composition\" ? n.commands : [];\n if ((prev as { commands?: unknown }).commands !== (next as { commands?: unknown }).commands) {\n diffCommands(prevCommands, nextCommands, diff);\n }\n\n diff.identical = !diff.themeChanged && !diff.rootChanged && !diff.duration\n && diff.remappedKeys.size === 0\n && rowsEmpty(diff.nodes) && diff.nodes.reorderedParents.size === 0\n && rowsEmpty(diff.commands) && diff.commands.reorderedAts.size === 0\n && rowsEmpty(diff.variables);\n return diff;\n}\n\nfunction lowered(doc: ClipDocument): VisualDocument {\n return clipDocument(doc);\n}\n\nfunction rowsEmpty(rows: RowChanges): boolean {\n return rows.added.size === 0 && rows.removed.size === 0 && rows.changed.size === 0;\n}\n\nconst DEFAULT_ROOT: NodeSpec = { id: ROOT_NODE_ID, type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} };\n\nfunction diffNodes(prevRows: readonly TimedNodeSpec[], nextRows: readonly TimedNodeSpec[], diff: ClipDiff): void {\n const prev = byId(prevRows);\n const next = byId(nextRows);\n const changes = diff.nodes;\n\n const prevRoot = prev.get(ROOT_NODE_ID) ?? DEFAULT_ROOT;\n const nextRoot = next.get(ROOT_NODE_ID) ?? DEFAULT_ROOT;\n diff.rootChanged = prevRoot !== nextRoot && !sameNode(prevRoot, nextRoot);\n\n for (const [id, a] of prev) {\n if (id === ROOT_NODE_ID) continue;\n const b = next.get(id);\n if (!b) {\n changes.removed.add(id);\n continue;\n }\n if (a === b) continue;\n let changed = false;\n if (a.type !== b.type || a.key !== b.key || !jsonEqual(a.props, b.props)) {\n changes.respec.add(id);\n changed = true;\n }\n if (a.parentId !== b.parentId) {\n changes.moved.add(id);\n changed = true;\n }\n if (!sameSpan(a, b)) {\n changes.span.add(id);\n changed = true;\n }\n if (changed || a.layerOrder !== b.layerOrder) changes.changed.add(id);\n }\n for (const id of next.keys()) {\n if (id !== ROOT_NODE_ID && !prev.has(id)) changes.added.add(id);\n }\n\n const prevKeys = keyed(prevRows);\n for (const [key, id] of keyed(nextRows)) {\n const was = prevKeys.get(key);\n if (was !== undefined && was !== id) diff.remappedKeys.add(key);\n }\n\n const prevOrder = siblingOrder(prevRows);\n const nextOrder = siblingOrder(nextRows);\n for (const [parent, before] of prevOrder) {\n const after = nextOrder.get(parent);\n if (after && !sameRelativeOrder(before, after)) changes.reorderedParents.add(parent);\n }\n}\n\nfunction sameNode(a: NodeSpec, b: NodeSpec): boolean {\n return a.type === b.type\n && a.key === b.key\n && a.parentId === b.parentId\n && a.layerOrder === b.layerOrder\n && jsonEqual(a.props, b.props)\n && sameSpan(a, b);\n}\n\nfunction sameSpan(a: NodeSpec, b: NodeSpec): boolean {\n const sa = nodeSpan(a);\n const sb = nodeSpan(b);\n return sa.start === sb.start && sa.end === sb.end;\n}\n\nfunction diffCommands(prevRows: readonly CommandSpec[], nextRows: readonly CommandSpec[], diff: ClipDiff): void {\n const prev = byId(prevRows);\n const next = byId(nextRows);\n const changes = diff.commands;\n\n for (const [id, a] of prev) {\n const b = next.get(id);\n if (!b) {\n changes.removed.add(id);\n continue;\n }\n if (a === b) continue;\n if (\n a.type !== b.type\n || a.targetId !== b.targetId\n || a.at !== b.at\n || (a.duration ?? 0) !== (b.duration ?? 0)\n || !jsonEqual(a.easing, b.easing)\n || !jsonEqual(a.loop, b.loop)\n || !jsonEqual(a.args, b.args)\n ) {\n changes.changed.add(id);\n }\n }\n for (const id of next.keys()) {\n if (!prev.has(id)) changes.added.add(id);\n }\n\n const prevAts = groupByAt(prevRows);\n const nextAts = groupByAt(nextRows);\n for (const [at, before] of prevAts) {\n const after = nextAts.get(at);\n if (after && !sameRelativeOrder(before, after)) changes.reorderedAts.add(at);\n }\n}\n\nfunction diffVariables(prevRows: readonly VariableSpec[], nextRows: readonly VariableSpec[], diff: ClipDiff): void {\n const prev = byId(prevRows);\n const next = byId(nextRows);\n const changes = diff.variables;\n for (const [id, a] of prev) {\n const b = next.get(id);\n if (!b) {\n changes.removed.add(id);\n continue;\n }\n if (a !== b && (a.lerp !== b.lerp || !jsonEqual(a.value, b.value))) changes.changed.add(id);\n }\n for (const id of next.keys()) {\n if (!prev.has(id)) changes.added.add(id);\n }\n}\n\nfunction byId<T extends { id: string }>(rows: readonly T[]): Map<string, T> {\n const out = new Map<string, T>();\n for (const row of rows) out.set(row.id, row);\n return out;\n}\n\nfunction keyed(rows: readonly NodeSpec[]): Map<string, string> {\n const out = new Map<string, string>();\n for (const row of rows) if (row.key) out.set(row.key, row.id);\n return out;\n}\n\n/** Child ids per parent, in the order `syncPresence` inserts them: `layerOrder`, ties by array index. */\nfunction siblingOrder(rows: readonly NodeSpec[]): Map<string, string[]> {\n const groups = new Map<string, Array<{ id: string; order: number; index: number }>>();\n rows.forEach((row, index) => {\n if (row.id === ROOT_NODE_ID) return;\n const parent = row.parentId ?? ROOT_NODE_ID;\n let list = groups.get(parent);\n if (!list) groups.set(parent, list = []);\n list.push({ id: row.id, order: row.layerOrder, index });\n });\n const out = new Map<string, string[]>();\n for (const [parent, list] of groups) {\n list.sort((a, b) => (a.order - b.order) || (a.index - b.index));\n out.set(parent, list.map((e) => e.id));\n }\n return out;\n}\n\n/** Command ids per exact `at`, in array order — the tiebreak `inTimelineOrder` uses. */\nfunction groupByAt(rows: readonly CommandSpec[]): Map<number, string[]> {\n const out = new Map<number, string[]>();\n for (const row of rows) {\n let list = out.get(row.at);\n if (!list) out.set(row.at, list = []);\n list.push(row.id);\n }\n return out;\n}\n\n/** Whether the ids both lists hold appear in the same relative order in each. */\nfunction sameRelativeOrder(a: readonly string[], b: readonly string[]): boolean {\n const inB = new Set(b);\n const inA = new Set(a);\n const sharedA = a.filter((id) => inB.has(id));\n const sharedB = b.filter((id) => inA.has(id));\n if (sharedA.length !== sharedB.length) return false;\n for (let i = 0; i < sharedA.length; i++) {\n if (sharedA[i] !== sharedB[i]) return false;\n }\n return true;\n}\n", "import { expressionOps } from \"./ops\";\n\n/**\n * A reference split into the node key and prop it names, or `undefined` when it\n * has no dot and so names a variable instead.\n *\n * The dot is the whole discriminator, in the parser (which hands the bracket's\n * contents over as one opaque name), the validator, and `ClipTimeline`.\n */\nexport function splitNodeRef(ref: string): { key: string; prop: string } | undefined {\n const dot = ref.indexOf(\".\");\n return dot < 0 ? undefined : { key: ref.slice(0, dot), prop: ref.slice(dot + 1) };\n}\n\nexport interface ExpressionRefs {\n /** Variable ids read, de-duplicated, in first-seen order. */\n vars: string[];\n /** `[key, prop]` pairs read, de-duplicated, in first-seen order. */\n keys: Array<[key: string, prop: string]>;\n /** Expressions that failed to parse; their references are not in the lists above. */\n unparsable: number;\n}\n\n/** Every reference inside every expression in an authored value, at any depth. */\nexport function expressionRefs(value: unknown, path = \"\"): ExpressionRefs {\n const vars: string[] = [];\n const keys: Array<[string, string]> = [];\n let unparsable = 0;\n const seen = new Set<string>();\n for (const site of expressionOps.collect(value, path)) {\n const parsed = expressionOps.tryParse(site.source);\n if (\"error\" in parsed) {\n unparsable++;\n continue;\n }\n for (const ref of parsed.expression.refs) {\n if (seen.has(ref)) continue;\n seen.add(ref);\n const node = splitNodeRef(ref);\n if (node) keys.push([node.key, node.prop]);\n else vars.push(ref);\n }\n }\n return { vars, keys, unparsable };\n}\n", "import { clipDocument } from \"./audio\";\nimport { expressionRefs, type ExpressionRefs } from \"./expression/refs\";\nimport {\n documentDuration,\n nodeSpan,\n ROOT_NODE_ID,\n type ClipDocument,\n type CommandSpec,\n type NodeSpan,\n type VisualDocument,\n type TimedNodeSpec,\n type VariableSpec,\n} from \"./types\";\n\n/** Whether a node is in the tree at t=0, and if so whether it is mounted there. */\nexport type InitialKey = \"mounted\" | \"unmounted\" | \"absent\";\n\n/**\n * When compile baselines a node that is not present at t=0: at the first command\n * `at` inside its own span, mounted or not at that moment.\n */\nexport type CaptureKey = \"none\" | \"arrival-mounted\" | \"arrival-unmounted\";\n\n/** Structural faults an incremental update cannot reason about; any one means rebuild. */\nexport interface DocIndexIssues {\n /** A node, command or variable id claimed twice, or a node id a variable also claims. */\n duplicateIds: boolean;\n duplicateKeys: boolean;\n unresolvedParent: boolean;\n cycle: boolean;\n /** A row with id `\"\"` that is not an unparented `canvas2d`. */\n invalidRoot: boolean;\n unparsable: boolean;\n /** An expression naming a variable or node key the document does not declare. */\n unresolvedRefs: boolean;\n}\n\nexport interface DocIndex {\n /** Audio documents are indexed as the composition they lower to. */\n readonly doc: VisualDocument;\n /** Every node by id, the root under `\"\"` (synthesized when the document omits it). */\n readonly nodes: ReadonlyMap<string, TimedNodeSpec>;\n /** Nodes other than the root. */\n readonly nodeCount: number;\n readonly variables: ReadonlyMap<string, VariableSpec>;\n readonly commands: ReadonlyMap<string, CommandSpec>;\n /** Commands in timeline order: `at`, ties by array index. */\n readonly ordered: readonly CommandSpec[];\n /** Command ids per target in timeline order; the root's under `\"\"`. */\n readonly byTarget: ReadonlyMap<string, readonly string[]>;\n readonly keyed: ReadonlyMap<string, string>;\n /** Nodes whose props (or `set` args) read a variable, or a keyed node's prop. */\n readonly dependents: {\n byVar: ReadonlyMap<string, ReadonlySet<string>>;\n byKey: ReadonlyMap<string, ReadonlySet<string>>;\n };\n readonly duration: number;\n readonly issues: DocIndexIssues;\n\n /** Child ids in sibling order: `layerOrder`, ties by array index. */\n children(parentId: string): readonly string[];\n /** Every document descendant of `id`, not including it. */\n descendants(id: string): string[];\n ownSpan(id: string): NodeSpan | undefined;\n /** Own span intersected with every ancestor's — when the node is mounted. Half-open. */\n effSpan(id: string): NodeSpan | undefined;\n /** The id a command acts on: its `targetId`, or `\"\"` for the root. */\n targetOf(spec: CommandSpec): string;\n commandsAt(at: number): readonly CommandSpec[];\n /** References per top-level prop, from the row's props and every `set` targeting it. */\n bindings(id: string): ReadonlyMap<string, ExpressionRefs>;\n refs(id: string): ExpressionRefs;\n initialKey(id: string): InitialKey;\n captureKey(id: string): CaptureKey;\n captureTime(id: string): number | undefined;\n}\n\nexport function indexDocument(doc: ClipDocument): DocIndex {\n return new DocumentIndex(clipDocument(doc));\n}\n\nconst NO_REFS: ExpressionRefs = Object.freeze({ vars: [], keys: [], unparsable: 0 }) as ExpressionRefs;\nconst NO_BINDINGS: ReadonlyMap<string, ExpressionRefs> = new Map();\nconst EMPTY: readonly never[] = [];\n\nfunction contains(span: NodeSpan | undefined, t: number): boolean {\n return span !== undefined && t >= span.start && t < span.end;\n}\n\nclass DocumentIndex implements DocIndex {\n readonly nodes = new Map<string, TimedNodeSpec>();\n readonly nodeCount: number;\n readonly variables = new Map<string, VariableSpec>();\n readonly commands = new Map<string, CommandSpec>();\n readonly ordered: readonly CommandSpec[];\n readonly byTarget = new Map<string, string[]>();\n readonly keyed = new Map<string, string>();\n readonly dependents = { byVar: new Map<string, Set<string>>(), byKey: new Map<string, Set<string>>() };\n readonly duration: number;\n readonly issues: DocIndexIssues = {\n duplicateIds: false,\n duplicateKeys: false,\n unresolvedParent: false,\n cycle: false,\n invalidRoot: false,\n unparsable: false,\n unresolvedRefs: false,\n };\n\n constructor(readonly doc: VisualDocument) {\n this.duration = documentDuration(doc);\n const commandRows = doc.kind === \"composition\" ? doc.commands : [];\n\n this._indexNodes(doc.nodes);\n this.nodeCount = this.nodes.size - 1;\n for (const spec of doc.variables ?? []) {\n if (this.variables.has(spec.id) || this.nodes.has(spec.id)) this.issues.duplicateIds = true;\n this.variables.set(spec.id, spec);\n }\n\n this.ordered = commandRows\n .map((spec, index) => ({ spec, index }))\n .sort((a, b) => (a.spec.at - b.spec.at) || (a.index - b.index))\n .map((e) => e.spec);\n for (const spec of this.ordered) {\n if (this.commands.has(spec.id)) this.issues.duplicateIds = true;\n this.commands.set(spec.id, spec);\n const target = this.targetOf(spec);\n let list = this.byTarget.get(target);\n if (!list) this.byTarget.set(target, list = []);\n list.push(spec.id);\n let atList = this._byAt.get(spec.at);\n if (!atList) this._byAt.set(spec.at, atList = []);\n atList.push(spec);\n }\n this._ats = [...this._byAt.keys()];\n\n this._indexRefs(commandRows);\n }\n\n children(parentId: string): readonly string[] {\n return this._children.get(parentId) ?? EMPTY;\n }\n\n descendants(id: string): string[] {\n const out: string[] = [];\n const seen = new Set<string>([id]);\n const stack = [...this.children(id)].reverse();\n while (stack.length > 0) {\n const child = stack.pop()!;\n if (seen.has(child)) continue;\n seen.add(child);\n out.push(child);\n const grand = this.children(child);\n for (let i = grand.length - 1; i >= 0; i--) stack.push(grand[i]);\n }\n return out;\n }\n\n ownSpan(id: string): NodeSpan | undefined {\n const spec = this.nodes.get(id);\n return spec ? nodeSpan(spec) : undefined;\n }\n\n effSpan(id: string): NodeSpan | undefined {\n const memo = this._eff.get(id);\n if (memo) return memo;\n if (!this.nodes.has(id)) return undefined;\n\n const chain: TimedNodeSpec[] = [];\n const seen = new Set<string>();\n let base: NodeSpan = { start: 0, end: Infinity };\n let cursor = this.nodes.get(id);\n while (cursor) {\n const known = this._eff.get(cursor.id);\n if (known) {\n base = known;\n break;\n }\n if (seen.has(cursor.id)) break;\n seen.add(cursor.id);\n chain.push(cursor);\n if (cursor.id === ROOT_NODE_ID || cursor.parentId === null) break;\n cursor = this.nodes.get(cursor.parentId);\n }\n for (let i = chain.length - 1; i >= 0; i--) {\n const own = nodeSpan(chain[i]);\n base = { start: Math.max(base.start, own.start), end: Math.min(base.end, own.end) };\n this._eff.set(chain[i].id, base);\n }\n return this._eff.get(id);\n }\n\n targetOf(spec: CommandSpec): string {\n return spec.targetId ?? ROOT_NODE_ID;\n }\n\n commandsAt(at: number): readonly CommandSpec[] {\n return this._byAt.get(at) ?? EMPTY;\n }\n\n bindings(id: string): ReadonlyMap<string, ExpressionRefs> {\n return this._bindings.get(id) ?? NO_BINDINGS;\n }\n\n refs(id: string): ExpressionRefs {\n return this._refs.get(id) ?? NO_REFS;\n }\n\n initialKey(id: string): InitialKey {\n if (!contains(this.ownSpan(id), 0)) return \"absent\";\n return contains(this.effSpan(id), 0) ? \"mounted\" : \"unmounted\";\n }\n\n captureKey(id: string): CaptureKey {\n const at = this.captureTime(id);\n if (at === undefined) return \"none\";\n return contains(this.effSpan(id), at) ? \"arrival-mounted\" : \"arrival-unmounted\";\n }\n\n captureTime(id: string): number | undefined {\n const own = this.ownSpan(id);\n if (!own || contains(own, 0)) return undefined;\n let lo = 0;\n let hi = this._ats.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (this._ats[mid] < own.start) lo = mid + 1;\n else hi = mid;\n }\n const at = this._ats[lo];\n return at !== undefined && at < own.end ? at : undefined;\n }\n\n private readonly _children = new Map<string, string[]>();\n private readonly _eff = new Map<string, NodeSpan>();\n private readonly _byAt = new Map<number, CommandSpec[]>();\n /** Distinct command `at`s, ascending (inherited from {@link ordered}). */\n private _ats: number[] = [];\n private readonly _bindings = new Map<string, Map<string, ExpressionRefs>>();\n private readonly _refs = new Map<string, ExpressionRefs>();\n\n private _indexNodes(rows: readonly TimedNodeSpec[]): void {\n const siblings = new Map<string, Array<{ id: string; order: number; index: number }>>();\n rows.forEach((spec, index) => {\n if (this.nodes.has(spec.id)) this.issues.duplicateIds = true;\n this.nodes.set(spec.id, spec);\n if (spec.key) {\n if (this.keyed.has(spec.key)) this.issues.duplicateKeys = true;\n this.keyed.set(spec.key, spec.id);\n }\n if (spec.id === ROOT_NODE_ID) {\n if (spec.type !== \"canvas2d\" || spec.parentId !== null) this.issues.invalidRoot = true;\n return;\n }\n const parent = spec.parentId ?? ROOT_NODE_ID;\n let list = siblings.get(parent);\n if (!list) siblings.set(parent, list = []);\n list.push({ id: spec.id, order: spec.layerOrder, index });\n });\n if (!this.nodes.has(ROOT_NODE_ID)) {\n this.nodes.set(ROOT_NODE_ID, { id: ROOT_NODE_ID, type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} });\n }\n for (const [parent, list] of siblings) {\n list.sort((a, b) => (a.order - b.order) || (a.index - b.index));\n this._children.set(parent, list.map((e) => e.id));\n }\n\n const settled = new Set<string>([ROOT_NODE_ID]);\n for (const spec of this.nodes.values()) {\n if (spec.parentId !== null && !this.nodes.has(spec.parentId)) this.issues.unresolvedParent = true;\n const seen = new Set<string>();\n let cursor: TimedNodeSpec | undefined = spec;\n while (cursor && !settled.has(cursor.id)) {\n if (seen.has(cursor.id)) {\n this.issues.cycle = true;\n break;\n }\n seen.add(cursor.id);\n cursor = cursor.parentId === null ? undefined : this.nodes.get(cursor.parentId);\n }\n for (const id of seen) settled.add(id);\n }\n }\n\n private _indexRefs(commandRows: readonly CommandSpec[]): void {\n for (const spec of this.nodes.values()) this._bind(spec.id, spec.props);\n for (const command of commandRows) {\n if (command.type === \"set\") {\n const target = this.targetOf(command);\n if (this.nodes.has(target)) {\n this._bind(target, command.args);\n continue;\n }\n }\n if (expressionRefs(command.args).unparsable > 0) this.issues.unparsable = true;\n }\n\n for (const [id, props] of this._bindings) {\n const vars = new Set<string>();\n const keys = new Map<string, [string, string]>();\n let unparsable = 0;\n for (const refs of props.values()) {\n for (const v of refs.vars) vars.add(v);\n for (const pair of refs.keys) keys.set(`${pair[0]}.${pair[1]}`, pair);\n unparsable += refs.unparsable;\n }\n this._refs.set(id, { vars: [...vars], keys: [...keys.values()], unparsable });\n\n for (const v of vars) {\n if (!this.variables.has(v)) this.issues.unresolvedRefs = true;\n let readers = this.dependents.byVar.get(v);\n if (!readers) this.dependents.byVar.set(v, readers = new Set());\n readers.add(id);\n }\n for (const [key] of keys.values()) {\n if (!this.keyed.has(key)) this.issues.unresolvedRefs = true;\n let readers = this.dependents.byKey.get(key);\n if (!readers) this.dependents.byKey.set(key, readers = new Set());\n readers.add(id);\n }\n }\n }\n\n /** Merge one props bag's references into a node's per-prop table. */\n private _bind(id: string, props: Record<string, unknown> | undefined): void {\n if (!props) return;\n for (const prop of Object.keys(props)) {\n const found = expressionRefs(props[prop]);\n if (found.unparsable > 0) this.issues.unparsable = true;\n if (found.vars.length === 0 && found.keys.length === 0) continue;\n let table = this._bindings.get(id);\n if (!table) this._bindings.set(id, table = new Map());\n const existing = table.get(prop);\n if (!existing) {\n table.set(prop, found);\n continue;\n }\n const vars = new Set([...existing.vars, ...found.vars]);\n const keys = new Map([...existing.keys, ...found.keys].map((p) => [`${p[0]}.${p[1]}`, p] as const));\n table.set(prop, { vars: [...vars], keys: [...keys.values()], unparsable: existing.unparsable + found.unparsable });\n }\n }\n}\n", "import { clamp01 } from \"@/util/clamp\";\nimport { observeSlots } from \"@/props/observer\";\nimport type { PropSlot, PropSnapshot } from \"@/props/slot\";\nimport { settles, type Command } from \"@/tween/command\";\n\n/** What the index reads of a placed command. */\nexport interface SettlePlaced {\n readonly start: number;\n /** When it starts writing, if earlier than `start`: an entrance holds `at(0)` from here. */\n readonly holdFrom?: number;\n readonly duration: number;\n readonly command: Command<Record<string, unknown>>;\n readonly writes: ReadonlySet<PropSlot<unknown>>;\n /** What it read while built, when it is unmarked: what it may read while it runs. */\n readonly reads?: ReadonlySet<PropSlot<unknown>>;\n}\n\n/**\n * Evaluation that holds finished commands instead of running them.\n *\n * A timeline evaluates `t` by restoring baselines and running every command\n * started by `t` in placement order, so the later one wins a slot both write.\n * That costs every command placed so far, finished or not. A command marked\n * {@link settling} leaves fixed end values, so once finished it is a stored\n * write per slot: for each slot, only the latest-placed finished writer counts.\n * A frame then costs a lookup per written slot plus the commands still running,\n * and the length of the timeline drops out.\n *\n * Unmarked commands, and marked ones still running, are run as before, in\n * placement order. After each, a slot it writes whose held writer was placed\n * later gets that writer's value back: placement order still decides. This\n * relies on what the timeline's restore already does, that a command writes\n * nothing while running that it did not write while being built.\n *\n * A held end value is in place before every command runs, so one an earlier\n * unmarked command reads (a `save`) would reach it early: a marked command\n * writing a slot an earlier unmarked one read is run instead, as if unmarked.\n */\nexport class SettledIndex {\n /** `null` when nothing is marked: the timeline runs everything, as before. */\n static build(placed: readonly SettlePlaced[]): SettledIndex | null {\n const finish = new Float64Array(placed.length).fill(NaN);\n const writers = new Map<PropSlot<unknown>, Writer[]>();\n const replayed: number[] = [];\n const running: number[] = [];\n const read = new Set<PropSlot<unknown>>();\n for (let i = 0; i < placed.length; i++) {\n const p = placed[i];\n const marked = settles(p.command);\n const end = marked && !readEarlier(p.writes, read) ? finishTime(p.start, p.duration) : NaN;\n if (Number.isNaN(end)) {\n if (!marked && p.reads) for (const slot of p.reads) read.add(slot);\n replayed.push(i);\n continue;\n }\n finish[i] = end;\n if (end > (p.holdFrom ?? p.start)) running.push(i);\n // Only what `at(1)` writes is an end value; a slot written only while\n // building is not held.\n const written = new Set<PropSlot<unknown>>();\n observeSlots({ read: () => { }, write: (slot) => written.add(slot) }, () => p.command.at(1));\n for (const slot of written) {\n const list = writers.get(slot);\n const writer = { order: i, finish: end, end: slot.snapshot() };\n if (list) list.push(writer);\n else writers.set(slot, [writer]);\n }\n }\n if (replayed.length === placed.length) return null;\n return new SettledIndex(placed, finish, [...writers].map(([slot, list]) => new Track(slot, list)), replayed, running);\n }\n\n /** Whether the command at `index` is held once finished, rather than run on every evaluation. */\n holds(index: number): boolean {\n return !Number.isNaN(this._finish[index]);\n }\n\n /** Bring what the placed commands write to `seconds`. Baselines must be restored first. */\n evaluate(placed: readonly SettlePlaced[], seconds: number): void {\n const tracks = this._tracks;\n const held = this._held;\n for (let k = 0; k < tracks.length; k++) {\n const w = (held[k] = tracks[k].at(seconds));\n if (w >= 0) tracks[k].slot.restoreFrom(tracks[k].ends[w]);\n }\n\n // Three lists, each in placement order, merged.\n const replayed = this._replayed;\n const long = this._long;\n const bin = this._binOf(seconds);\n const binEnd = this._binStart[bin + 1];\n let a = 0;\n let b = this._binStart[bin];\n let c = 0;\n for (; ;) {\n const ia = a < replayed.length ? replayed[a] : NONE;\n const ib = b < binEnd ? this._binItems[b] : NONE;\n const ic = c < long.length ? long[c] : NONE;\n let i: number;\n if (ia < ib && ia < ic) {\n i = ia;\n a++;\n } else if (ib < ic) {\n i = ib;\n b++;\n } else if (ic !== NONE) {\n i = ic;\n c++;\n } else {\n break;\n }\n\n const p = placed[i];\n // An unmarked finish is NaN, which no time reaches.\n if (seconds < (p.holdFrom ?? p.start) || this._finish[i] <= seconds) continue;\n p.command.at(seconds < p.start ? 0 : clamp01(p.duration > 0 ? (seconds - p.start) / p.duration : 1));\n for (let f = this._fixStart[i]; f < this._fixStart[i + 1]; f++) {\n const k = this._fixTracks[f];\n const w = held[k];\n if (w >= 0 && tracks[k].order[w] > i) tracks[k].slot.restoreFrom(tracks[k].ends[w]);\n }\n }\n }\n\n private constructor(\n placed: readonly SettlePlaced[],\n private readonly _finish: Float64Array,\n private readonly _tracks: readonly Track[],\n private readonly _replayed: readonly number[],\n running: readonly number[],\n ) {\n this._held = new Int32Array(_tracks.length);\n\n // Marked commands that can be running, by the time bins their run overlaps.\n // One spanning many bins is checked on every evaluation instead.\n let from = Infinity;\n let to = -Infinity;\n for (const i of running) {\n from = Math.min(from, placed[i].holdFrom ?? placed[i].start);\n to = Math.max(to, _finish[i]);\n }\n const bins = Math.max(1, Math.min(MAX_BINS, running.length));\n this._from = Number.isFinite(from) ? from : 0;\n this._width = to > from ? (to - from) / bins : 1;\n this._bins = bins;\n const items: number[][] = Array.from({ length: bins }, () => []);\n const long: number[] = [];\n for (const i of running) {\n const first = this._binOf(placed[i].holdFrom ?? placed[i].start);\n const last = this._binOf(_finish[i]);\n if (last - first > MAX_SPAN) long.push(i);\n else for (let bin = first; bin <= last; bin++) items[bin].push(i);\n }\n this._long = long;\n this._binStart = new Int32Array(bins + 1);\n for (let bin = 0; bin < bins; bin++) this._binStart[bin + 1] = this._binStart[bin] + items[bin].length;\n this._binItems = Int32Array.from(items.flat());\n\n // For every command, the tracks of the slots it writes.\n const trackOf = new Map<PropSlot<unknown>, number>(_tracks.map((track, k) => [track.slot, k]));\n const fixes: number[] = [];\n this._fixStart = new Int32Array(placed.length + 1);\n for (let i = 0; i < placed.length; i++) {\n for (const slot of placed[i].writes) {\n const k = trackOf.get(slot);\n if (k !== undefined) fixes.push(k);\n }\n this._fixStart[i + 1] = fixes.length;\n }\n this._fixTracks = Int32Array.from(fixes);\n }\n\n private readonly _held: Int32Array;\n private readonly _from: number;\n private readonly _width: number;\n private readonly _bins: number;\n private readonly _binStart: Int32Array;\n private readonly _binItems: Int32Array;\n private readonly _long: readonly number[];\n private readonly _fixStart: Int32Array;\n private readonly _fixTracks: Int32Array;\n\n private _binOf(seconds: number): number {\n const bin = Math.floor((seconds - this._from) / this._width);\n return bin < 0 ? 0 : bin >= this._bins ? this._bins - 1 : bin;\n }\n}\n\nfunction readEarlier(writes: ReadonlySet<PropSlot<unknown>>, read: ReadonlySet<PropSlot<unknown>>): boolean {\n if (read.size === 0) return false;\n for (const slot of writes) if (read.has(slot)) return true;\n return false;\n}\n\nconst NONE = 0x7fffffff;\nconst MAX_BINS = 1024;\nconst MAX_SPAN = 32;\n\ninterface Writer {\n order: number;\n finish: number;\n end: PropSnapshot<unknown>;\n}\n\n/** One written slot: its marked writers by finish time, and the latest-placed one finished by each. */\nclass Track {\n readonly finish: Float64Array;\n readonly order: Int32Array;\n readonly ends: PropSnapshot<unknown>[];\n private readonly _best: Int32Array;\n\n constructor(readonly slot: PropSlot<unknown>, writers: Writer[]) {\n writers.sort((x, y) => x.finish - y.finish || x.order - y.order);\n this.finish = Float64Array.from(writers, (w) => w.finish);\n this.order = Int32Array.from(writers, (w) => w.order);\n this.ends = writers.map((w) => w.end);\n this._best = new Int32Array(writers.length);\n let best = 0;\n for (let i = 0; i < writers.length; i++) {\n if (this.order[i] > this.order[best]) best = i;\n this._best[i] = best;\n }\n }\n\n /** The writer whose end value the slot holds at `seconds`, or -1 when none has finished. */\n at(seconds: number): number {\n let lo = 0;\n let hi = this.finish.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (this.finish[mid] <= seconds) lo = mid + 1;\n else hi = mid;\n }\n return lo === 0 ? -1 : this._best[lo - 1];\n }\n}\n\n/**\n * The first time a command placed at `start` for `duration` runs at its end, by\n * the timeline's own arithmetic, `(t - start) / duration >= 1`. `start + duration`\n * can miss it by a rounding step either way. NaN when it can't be pinned down,\n * which leaves the command to run every evaluation.\n */\nfunction finishTime(start: number, duration: number): number {\n if (!(duration > 0)) return start;\n const done = (t: number) => (t - start) / duration >= 1;\n let t = start + duration;\n if (!Number.isFinite(t)) return NaN;\n for (let i = 0; !done(t); i++) {\n if (i === 8) return NaN;\n t = step(t, true);\n }\n for (let i = 0; i < 8; i++) {\n const down = step(t, false);\n if (!done(down)) return t;\n t = down;\n }\n return NaN;\n}\n\nconst BITS = new Float64Array(1);\nconst INTS = new BigInt64Array(BITS.buffer);\n\n/** The adjacent double above or below `x`. */\nfunction step(x: number, up: boolean): number {\n if (x === 0) return up ? Number.MIN_VALUE : -Number.MIN_VALUE;\n BITS[0] = x;\n INTS[0] += (x > 0) === up ? 1n : -1n;\n return BITS[0];\n}\n", "import type { CommandTraits } from \"./command-traits\";\nimport { jsonEqual, type ClipDiff } from \"./diff\";\nimport type { DocIndex } from \"./doc-index\";\nimport type { ExpressionRefs } from \"./expression/refs\";\nimport { nodeSpan, ROOT_NODE_ID, type CommandSpec, type NodeSpan, type NodeSpec } from \"./types\";\n\n/** What the planner needs to know about code, so it can be exercised without a registry. */\nexport interface PatchEnvironment {\n traits(spec: CommandSpec, target: NodeSpec | undefined): CommandTraits | null;\n /** Node ids the command's args name (`moveTo`'s `target`). Absent names none. */\n nodeRefs?(spec: CommandSpec, target: NodeSpec | undefined): readonly string[];\n isContextProvider(type: string): boolean;\n isLayoutNeutralProp(type: string, key: string): boolean;\n /** Whether a new `key` on `row` is written onto its live node rather than a new one. Absent writes none in place. */\n writesInPlace?(row: NodeSpec, key: string): boolean;\n /** The live instance's constructor, or `undefined` when there is none to compare. */\n ctorOf(id: string): unknown;\n registeredCtor(type: string): unknown;\n /** A type's tree; `\"audio\"` rows are left out of layout decisions. Absent treats every type as laid out. */\n dimensionOf?(type: string): string | undefined;\n}\n\nexport interface TimelinePatch {\n prev: DocIndex;\n next: DocIndex;\n diff: ClipDiff;\n added: ReadonlySet<string>;\n removed: ReadonlySet<string>;\n /** Kept ids that get a new instance. */\n reinstantiate: ReadonlySet<string>;\n /** Kept ids whose changed props are all placement, written onto the live instance instead. */\n inPlace: ReadonlySet<string>;\n detach: ReadonlySet<string>;\n /** Nodes whose command chains are rebuilt; may include the root `\"\"`. */\n dirtyNodes: ReadonlySet<string>;\n dirtyVariables: ReadonlySet<string>;\n /** Clean chains that must run for dirty ones to build against the right values; empty means none. */\n replay: ReadonlySet<string> | \"all\";\n /** Arrival baselines to take during the walk, ascending by `at`. */\n captures: ReadonlyArray<{ at: number; id: string }>;\n layoutChanged: boolean;\n}\n\nexport interface PatchOptions {\n /** Rebuild instead once more than this fraction of nodes would be re-instantiated. Default 0.5. */\n rebuildFraction?: number;\n /** Patch whenever at most this many nodes would be re-instantiated, whatever the fraction. Default {@link MIN_REBUILD_NODES}. */\n minRebuildNodes?: number;\n}\n\n/**\n * A rebuild of a small clip is not cheaper than patching it: the runtime also\n * throws away the track's asset index, sweeps it again and republishes it.\n */\nexport const MIN_REBUILD_NODES = 16;\n\n/**\n * Plan an in-place update of a built clip from `prev` to `next`, or `null` when\n * only a rebuild is sound.\n *\n * Every rule errs towards doing more: a node marked dirty that did not need it\n * costs one chain rebuild, while one missed renders a frame that disagrees with\n * a fresh build of the same document.\n */\nexport function planTimelinePatch(\n prev: DocIndex,\n next: DocIndex,\n diff: ClipDiff,\n env: PatchEnvironment,\n options: PatchOptions = {},\n): TimelinePatch | null {\n if (diff.kindChanged || diff.themeChanged) return null;\n if (structurallyFaulty(prev) || structurallyFaulty(next)) return null;\n const prevRoot = prev.nodes.get(ROOT_NODE_ID)!;\n const nextRoot = next.nodes.get(ROOT_NODE_ID)!;\n // The canvas is never re-instantiated, so only props it can be reset and re-set to are patched.\n if (diff.rootChanged && !onlyPropsDiffer(prevRoot, nextRoot)) return null;\n if (next.issues.unparsable || next.issues.unresolvedRefs) return null;\n if (diff.remappedKeys.size > 0) return null;\n\n const prevTraits = traitsOf(prev, env);\n const nextTraits = prevTraits && traitsOf(next, env);\n if (!prevTraits || !nextTraits) return null;\n\n const { added, removed, respec, moved, span, reorderedParents } = diff.nodes;\n const targeted = (id: string): boolean => (next.byTarget.get(id)?.length ?? 0) > 0;\n const anyCommand = (index: DocIndex, traits: Map<string, CommandTraits>, id: string, test: (t: CommandTraits) => boolean) =>\n index.byTarget.get(id)?.some((cid) => test(traits.get(cid)!)) ?? false;\n const unknownEither = (id: string) =>\n anyCommand(prev, prevTraits, id, (t) => !t.known) || anyCommand(next, nextTraits, id, (t) => !t.known);\n const laidOut = (index: DocIndex, id: string) => {\n const type = index.nodes.get(id)?.type;\n return type === undefined || env.dimensionOf?.(type) !== \"audio\";\n };\n const laidOutEither = (id: string) => laidOut(prev, id) || laidOut(next, id);\n const kept: string[] = [];\n for (const id of next.nodes.keys()) {\n if (id !== ROOT_NODE_ID && prev.nodes.has(id)) kept.push(id);\n }\n\n // ── Re-instantiation ────────────────────────────────────────────────────\n const R = new Set<string>();\n const isProvider = (id: string) => {\n const a = prev.nodes.get(id)?.type;\n const b = next.nodes.get(id)?.type;\n return (a !== undefined && env.isContextProvider(a)) || (b !== undefined && env.isContextProvider(b));\n };\n const reinstantiate = (id: string) => {\n if (R.has(id)) return;\n R.add(id);\n // A provider among the descendants needs no recursion: its subtree is already in this one.\n if (isProvider(id)) for (const d of next.descendants(id)) R.add(d);\n };\n\n const inPlace = new Set<string>();\n for (const id of respec) {\n if (placementOnly(prev, next, id, env)) inPlace.add(id);\n else reinstantiate(id);\n }\n for (const id of moved) {\n reinstantiate(id);\n if (providerAbove(prev, id, env) || providerAbove(next, id, env)) {\n for (const d of next.descendants(id)) R.add(d);\n }\n }\n for (const id of [...added, ...removed]) {\n if (isProvider(id)) for (const d of next.descendants(id)) R.add(d);\n }\n let reregistered = false;\n for (const id of kept) {\n const live = env.ctorOf(id);\n if (live !== undefined && env.registeredCtor(next.nodes.get(id)!.type) !== live) {\n reinstantiate(id);\n if (laidOutEither(id)) reregistered = true;\n }\n if (targeted(id) && prev.initialKey(id) !== next.initialKey(id)) reinstantiate(id);\n }\n\n // ── Dirty chains ────────────────────────────────────────────────────────\n const DN = new Set<string>();\n const DV = new Set<string>();\n const mark = (id: string) => {\n if (next.variables.has(id)) DV.add(id);\n else if (next.nodes.has(id)) DN.add(id);\n };\n\n for (const cid of diff.commands.added) mark(next.targetOf(next.commands.get(cid)!));\n for (const cid of diff.commands.removed) mark(prev.targetOf(prev.commands.get(cid)!));\n for (const cid of diff.commands.changed) {\n mark(prev.targetOf(prev.commands.get(cid)!));\n mark(next.targetOf(next.commands.get(cid)!));\n }\n for (const id of new Set([...prev.byTarget.keys(), ...next.byTarget.keys()])) {\n if (!sameList(prev.byTarget.get(id), next.byTarget.get(id))) mark(id);\n }\n for (const at of diff.commands.reorderedAts) {\n for (const spec of prev.commandsAt(at)) mark(prev.targetOf(spec));\n for (const spec of next.commandsAt(at)) mark(next.targetOf(spec));\n }\n // An unlimited loop is built to fill the clip it found, so a clip that grew\n // or shrank rebuilds it — nothing on the command itself changed.\n if (diff.duration) {\n for (const spec of next.commands.values()) {\n if (spec.loop?.count === null) mark(next.targetOf(spec));\n }\n }\n for (const id of diff.variables.added) DV.add(id);\n for (const id of diff.variables.changed) DV.add(id);\n\n const presenceChanged = new Set<string>();\n for (const id of kept) {\n if (!sameSpan(prev.effSpan(id), next.effSpan(id))) {\n presenceChanged.add(id);\n if (targeted(id)) DN.add(id);\n } else if (\n targeted(id)\n && (prev.captureKey(id) !== next.captureKey(id) || prev.captureTime(id) !== next.captureTime(id))\n ) {\n DN.add(id);\n }\n }\n\n let L = reorderedParents.size > 0 || reregistered\n || [...added].some((id) => laidOut(next, id))\n || [...removed].some((id) => laidOut(prev, id))\n || [...moved].some(laidOutEither)\n || [...span].some(laidOutEither)\n || [...respec].some((id) => laidOutEither(id) && respecTouchesLayout(prev.nodes.get(id)!, next.nodes.get(id)!, env))\n || (diff.rootChanged && respecTouchesLayout(prevRoot, nextRoot, env));\n\n // Nodes whose prop values over time may differ from the live build: anything\n // reading one of them through `[key.prop]` builds its chain from different values.\n const valueChanged = new Set<string>([...added, ...removed, ...presenceChanged, ...inPlace]);\n if (diff.rootChanged) valueChanged.add(ROOT_NODE_ID);\n const aimed = [...nodeReaders(prev, env), ...nodeReaders(next, env)];\n const bindsLayout = (reader: string, reads: (refs: ExpressionRefs) => boolean) => {\n const type = next.nodes.get(reader)?.type;\n if (type === undefined || env.dimensionOf?.(type) === \"audio\") return false;\n for (const [prop, refs] of next.bindings(reader)) {\n if (reads(refs) && !env.isLayoutNeutralProp(type, prop)) return true;\n }\n return false;\n };\n\n let size = -1;\n while (size !== DN.size + DV.size + R.size + valueChanged.size + (L ? 1 : 0)) {\n size = DN.size + DV.size + R.size + valueChanged.size + (L ? 1 : 0);\n\n for (const id of R) if (targeted(id)) DN.add(id);\n for (const id of R) valueChanged.add(id);\n for (const id of DN) valueChanged.add(id);\n\n for (const v of DV) {\n for (const reader of next.dependents.byVar.get(v) ?? []) {\n valueChanged.add(reader);\n if (!L && bindsLayout(reader, (refs) => refs.vars.includes(v))) L = true;\n }\n }\n for (const id of valueChanged) {\n for (const key of keysOf(prev, next, id)) {\n for (const reader of next.dependents.byKey.get(key) ?? []) {\n valueChanged.add(reader);\n if (!L && bindsLayout(reader, (refs) => refs.keys.some(([k]) => k === key))) L = true;\n }\n }\n }\n // Where a named node is depends on every ancestor too.\n for (const { reader, ref } of aimed) {\n if (lineageIn(prev, ref, valueChanged) || lineageIn(next, ref, valueChanged)) valueChanged.add(reader);\n }\n for (const id of valueChanged) if (next.nodes.has(id) && targeted(id)) DN.add(id);\n\n for (const id of DN) {\n if (id !== ROOT_NODE_ID && unknownEither(id)) reinstantiate(id);\n }\n\n if (!L) {\n for (const id of [...DN, ...DV]) {\n if (anyCommand(prev, prevTraits, id, (t) => t.writesLayout) || anyCommand(next, nextTraits, id, (t) => t.writesLayout)) {\n L = true;\n break;\n }\n }\n }\n if (L) {\n for (const id of next.byTarget.keys()) {\n if (next.nodes.has(id) && anyCommand(next, nextTraits, id, (t) => t.readsLayout)) DN.add(id);\n }\n }\n }\n\n if (DN.has(ROOT_NODE_ID) && unknownEither(ROOT_NODE_ID)) return null;\n const limit = Math.max((options.rebuildFraction ?? 0.5) * next.nodeCount, options.minRebuildNodes ?? MIN_REBUILD_NODES);\n if (R.size > limit) return null;\n for (const id of R) inPlace.delete(id);\n\n // ── Replay ──────────────────────────────────────────────────────────────\n let replay: Set<string> | \"all\";\n const dirtyTargets = [...DN, ...DV];\n if (dirtyTargets.some((id) => anyCommand(next, nextTraits, id, (t) => t.readsLayout || !t.known))) {\n replay = \"all\";\n } else {\n replay = new Set<string>();\n const queue: string[] = [];\n const visited = new Set<string>();\n for (const id of DN) {\n const refs = next.refs(id);\n if (refs.vars.length === 0 && refs.keys.length === 0) continue;\n if (!(next.byTarget.get(id) ?? []).some((cid) => next.commands.get(cid)!.type !== \"set\")) continue;\n visited.add(id);\n queue.push(id);\n }\n while (queue.length > 0) {\n const refs = next.refs(queue.pop()!);\n for (const v of refs.vars) {\n if (!DV.has(v) && targeted(v)) replay.add(v);\n }\n for (const [key] of refs.keys) {\n const id = next.keyed.get(key);\n if (id === undefined) continue;\n if (!DN.has(id) && targeted(id)) replay.add(id);\n if (!visited.has(id)) {\n visited.add(id);\n queue.push(id);\n }\n }\n }\n }\n\n // ── Structure ───────────────────────────────────────────────────────────\n const detach = new Set<string>([...removed, ...R]);\n for (const parent of reorderedParents) {\n for (const child of next.children(parent)) if (prev.nodes.has(child)) detach.add(child);\n }\n for (const id of R) {\n for (const child of next.children(id)) detach.add(child);\n }\n\n const captures: Array<{ at: number; id: string }> = [];\n for (const id of new Set([...DN, ...R, ...added])) {\n if (!targeted(id)) continue;\n const at = next.captureTime(id);\n if (at !== undefined) captures.push({ at, id });\n }\n captures.sort((a, b) => a.at - b.at);\n\n return {\n prev,\n next,\n diff,\n added,\n removed,\n reinstantiate: R,\n inPlace,\n detach,\n dirtyNodes: DN,\n dirtyVariables: DV,\n replay,\n captures,\n layoutChanged: L,\n };\n}\n\nfunction structurallyFaulty(index: DocIndex): boolean {\n const { duplicateIds, duplicateKeys, unresolvedParent, cycle, invalidRoot } = index.issues;\n return duplicateIds || duplicateKeys || unresolvedParent || cycle || invalidRoot;\n}\n\n/**\n * Every command's traits, or `null` when one cannot be patched at all: it does\n * not resolve, it changes structure, or its target is not the kind its scope names.\n */\nfunction traitsOf(index: DocIndex, env: PatchEnvironment): Map<string, CommandTraits> | null {\n const out = new Map<string, CommandTraits>();\n for (const spec of index.ordered) {\n const targetId = index.targetOf(spec);\n const target = index.nodes.get(targetId);\n const traits = env.traits(spec, target);\n if (!traits || traits.lifecycle) return null;\n if (traits.scope === \"variable\" ? !index.variables.has(targetId) : !target) return null;\n out.set(spec.id, traits);\n }\n return out;\n}\n\n/** Each command target paired with a node its args name. */\nfunction nodeReaders(index: DocIndex, env: PatchEnvironment): Array<{ reader: string; ref: string }> {\n if (!env.nodeRefs) return [];\n const out: Array<{ reader: string; ref: string }> = [];\n for (const spec of index.ordered) {\n const reader = index.targetOf(spec);\n for (const ref of env.nodeRefs(spec, index.nodes.get(reader))) out.push({ reader, ref });\n }\n return out;\n}\n\n/** Whether `id` or any ancestor of it is in `set`. */\nfunction lineageIn(index: DocIndex, id: string, set: ReadonlySet<string>): boolean {\n const seen = new Set<string>();\n let cursor: string | undefined = id;\n while (cursor !== undefined && !seen.has(cursor)) {\n if (set.has(cursor)) return true;\n seen.add(cursor);\n const spec = index.nodes.get(cursor);\n if (!spec || cursor === ROOT_NODE_ID) return false;\n cursor = spec.parentId ?? ROOT_NODE_ID;\n }\n return false;\n}\n\nfunction providerAbove(index: DocIndex, id: string, env: PatchEnvironment): boolean {\n const seen = new Set<string>([id]);\n let cursor = index.nodes.get(id);\n while (cursor && cursor.id !== ROOT_NODE_ID) {\n const parentId: string = cursor.parentId ?? ROOT_NODE_ID;\n if (seen.has(parentId)) return false;\n seen.add(parentId);\n cursor = index.nodes.get(parentId);\n if (cursor && env.isContextProvider(cursor.type)) return true;\n }\n return false;\n}\n\nfunction onlyPropsDiffer(a: NodeSpec, b: NodeSpec): boolean {\n const sa = nodeSpan(a);\n const sb = nodeSpan(b);\n return a.type === b.type && a.key === b.key && a.parentId === b.parentId && a.layerOrder === b.layerOrder\n && sa.start === sb.start && sa.end === sb.end;\n}\n\n/** Whether every prop the row changed is a literal placement value it still sets. */\nfunction placementOnly(prev: DocIndex, next: DocIndex, id: string, env: PatchEnvironment): boolean {\n const a = prev.nodes.get(id)!;\n const b = next.nodes.get(id)!;\n if (!env.writesInPlace || a.type !== b.type || a.key !== b.key) return false;\n const was = prev.bindings(id);\n const is = next.bindings(id);\n for (const key of new Set([...Object.keys(a.props), ...Object.keys(b.props)])) {\n if (jsonEqual(a.props[key], b.props[key])) continue;\n // A prop taken out would go back to its default, which only a new instance knows.\n if (b.props[key] === undefined || was.has(key) || is.has(key) || !env.writesInPlace(b, key)) return false;\n }\n return true;\n}\n\nfunction respecTouchesLayout(a: NodeSpec, b: NodeSpec, env: PatchEnvironment): boolean {\n if (a.type !== b.type || a.key !== b.key) return true;\n for (const key of new Set([...Object.keys(a.props), ...Object.keys(b.props)])) {\n if (!jsonEqual(a.props[key], b.props[key]) && !env.isLayoutNeutralProp(b.type, key)) return true;\n }\n return false;\n}\n\nfunction keysOf(prev: DocIndex, next: DocIndex, id: string): string[] {\n const out: string[] = [];\n const a = prev.nodes.get(id)?.key;\n const b = next.nodes.get(id)?.key;\n if (a) out.push(a);\n if (b && b !== a) out.push(b);\n return out;\n}\n\nfunction sameSpan(a: NodeSpan | undefined, b: NodeSpan | undefined): boolean {\n return a?.start === b?.start && a?.end === b?.end;\n}\n\nfunction sameList(a: readonly string[] | undefined, b: readonly string[] | undefined): boolean {\n if (a === b) return true;\n if (!a || !b || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n", "import { clamp01 } from \"@/util/clamp\";\nimport { applySnapshotLayer, captureLayer, type PropLayer, type ReactiveHost } from \"@/components/trees/node/node-reactive\";\nimport type { Node, NodeDimension } from \"@/components/trees/node/node\";\nimport type { Canvas2D } from \"@/components/trees/root/canvas2d-node\";\nimport { _observer, PropSlot, type PropSnapshot } from \"@/props/slot\";\nimport { LAYOUT_SLOT, observeSlots, PRESENCE_PREFIX, unobserved, VAR_PREFIX, type SlotObserver } from \"@/props/observer\";\nimport { driveCommand, loopCommand, settles, settling, type Command } from \"@/tween/command\";\nimport { loopRepeats } from \"@/tween/loop\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport { easeOfSpec } from \"@/tween/ease/spec\";\nimport { commandNodeRefs, commandTraits, hasNodeRef, holdsWhenFinished, isContextProvider, isLayoutNeutralProp, writesPlacementInPlace } from \"./command-traits\";\nimport { diffClip, jsonEqual } from \"./diff\";\nimport { indexDocument, type DocIndex } from \"./doc-index\";\nimport { expressionOps } from \"./expression/ops\";\nimport { MISSING_TYPE, missingNode, missingNodeOf, placeholderProps } from \"./missing-node\";\nimport { migrateNodeProps } from \"./prop-evolution\";\nimport type { VariableResolver } from \"./expression/types\";\nimport type { Registry, VariableTarget } from \"./registry\";\nimport { SettledIndex } from \"./settled-index\";\nimport { commandSoundsOf } from \"@/components/factory/timeline\";\nimport type { SoundOptions } from \"@/components/factory/api\";\nimport { planTimelinePatch, type PatchEnvironment, type TimelinePatch } from \"./timeline-patch\";\nimport type { CommandSpec, EaseSpec, NodeSpec, NodeSpan, VisualDocument, VariableSpec } from \"./types\";\nimport { documentDuration, effectiveSpanIn, isStillDocument, nodeSpan, ROOT_NODE_ID } from \"./types\";\n\n/**\n * A compiled clip document: the thing that answers \"what does this look like\n * at `t`\" without having rendered `t - 1`.\n *\n * This is the whole reason the document model exists. A generator could\n * only be *advanced*, so a backward seek meant tearing the tree down and\n * replaying from frame 0, and a clip's duration was unknowable without running\n * it to the end. A timeline is built once and evaluated in any order, at any\n * time, as many times as you like — which is what makes scrubbing cheap, export\n * parallelizable, and a frame reproducible.\n *\n * ### The two phases, and why `from` needs both\n *\n * **Build** instantiates every node the document mentions and parents it.\n *\n * **Compile** then walks the commands in `at` order and asks each one's factory\n * for a {@link Command}. That order is load-bearing: a command's *start* value\n * is read from the node at the moment it is constructed (`node.to({x: 100})`\n * snapshots whatever `x` is now), so each command has to be built with the node\n * in the state its predecessors left. Compile therefore runs every command to\n * `at(1)` before building the next — see {@link compile}. Once built, a\n * `Command.at(t)` is pure, and the mutations compile caused are undone by\n * restoring the baseline.\n *\n * Building is O(commands) and happens once. Evaluating is what happens per\n * frame, and is O(commands) with no allocation, except that a command marked\n * settling is held at its end values once finished — see `settled-index.ts`.\n *\n * ### Variables and expressions\n *\n * A third thing gets built alongside the tree: one {@link PropSlot} per declared\n * {@link VariableSpec}, and a binding on every prop whose authored value is an\n * expression (`\"=4[g]+3\"` — see `document/expression.ts`). Those two together\n * are how one command drives many nodes.\n *\n * A binding is a thunk that reads the variable, and a bound prop recomputes on\n * every read — so `variableTo` writing the slot is visible to every prop that\n * names it, with nothing to invalidate and no edge to declare. A node driven\n * only by expressions is not in the animated list at all: there is no baseline\n * to restore, because nothing overwrote it.\n *\n * A reference spelled with a dot (`\"=[card.x]+20\"`) reads another node's prop\n * instead, through the same machinery — see `ClipTimeline._resolveVariable`\n * for why that one resolves at read time rather than at compile time.\n */\n\n/** A sound a placed command plays: from `at` to `until` in clip seconds, or to its own end. */\nexport interface PlacedSound {\n readonly node: Node;\n readonly at: number;\n readonly until: number | undefined;\n readonly src: string;\n readonly options: SoundOptions;\n}\n\n/**\n * Something a build stepped around instead of failing on: a row of a type the\n * registry lacks, built as a placeholder, or a command no one could run, left out.\n */\nexport interface TimelineIssue {\n code: \"unknown-node-type\" | \"unknown-command\";\n message: string;\n /** The row built as a placeholder, or the node a skipped command targets. */\n nodeId?: string;\n commandId?: string;\n /** The node type or command type that is unknown. */\n type: string;\n}\n\n/** A placed command as the runtime outside the timeline sees it. */\nexport interface PlacedCommandInfo {\n readonly spec: CommandSpec;\n /** Seconds from clip start. */\n readonly start: number;\n /** Seconds. Zero is a stamp — it applies in full from `start` onward. */\n readonly duration: number;\n /**\n * Seconds from which it writes: `start`, or for an entrance the earlier time\n * its first frame is held from (see {@link ClipTimeline._holdEntrances}).\n */\n readonly holdFrom: number;\n /** Every slot building it and running it to its end wrote. */\n readonly writes: ReadonlySet<PropSlot<unknown>>;\n readonly readsLayout: boolean;\n}\n\ninterface PlacedCommand extends PlacedCommandInfo {\n readonly command: Command<Record<string, unknown>>;\n readonly writes: Set<PropSlot<unknown>>;\n /** What an unmarked one may read while it runs: its owner's slots and what it read while built. Empty for a marked one. */\n readonly reads: ReadonlySet<PropSlot<unknown>>;\n /** Its neighbours decide it, so it is worked out again after every compile and update. */\n holdFrom: number;\n readonly entrance: boolean;\n /** What it acts on, so the animated lists can be rebuilt without resolving it again. */\n readonly owner: LiveNode | LiveVariable;\n}\n\n/**\n * A live variable: a slot nothing draws, that props read through an expression.\n *\n * A plain {@link PropSlot} rather than a node, because that is all a variable\n * needs to be. A prop bound to `() => slot.get()` re-reads it every time it is\n * read, so a `variableTo` writing this slot is picked up by every prop naming it\n * — with nothing in the node layer, the layout pass or the renderer knowing\n * variables exist.\n */\ninterface LiveVariable {\n spec: VariableSpec;\n /** Kept across an update: every binding compiled against it captured {@link read}, which reads this. */\n cell: PropSlot<unknown>;\n /** What an expression calls. Stable across the life of the build. */\n read: () => unknown;\n /** Handed to a variable command's factory. */\n target: VariableTarget;\n /** The declared value, restored before every evaluation. */\n baseline: unknown;\n}\n\n/** What `build` records about one node so evaluation can find and reset it. */\ninterface LiveNode {\n spec: NodeSpec;\n node: Node;\n /** Every reactive cell as the build left it, before any command or arrival touched it. */\n initial: PropLayer;\n initialStackDepth: number;\n /** What evaluation restores: {@link initial}, or the node as it arrived when it enters later. */\n baseline: PropLayer;\n /** Depth of the node's save stack at the baseline — see {@link ClipTimeline._restoreBaselines}. */\n baseStackDepth: number;\n /**\n * Whether the row is in the tree, as a slot, so a `[key.prop]` read taken under\n * an observer depends on it — the node answering can come and go.\n */\n presence: PropSlot<boolean>;\n}\n\n/** One stop of an update's walk: a command to build or replay, or an arrival baseline to take. */\ninterface WalkStep {\n at: number;\n spec?: CommandSpec;\n capture?: string;\n}\n\n/** Resolve an {@link EaseSpec} to the function the tween actually calls. */\nfunction resolveEase(ease: EaseSpec | undefined, registry: Registry): EasingFunction | undefined {\n if (!ease) return undefined;\n return easeOfSpec(ease, (key) => registry.ease(key), () => registry.easeKeys());\n}\n\n/**\n * Order commands for compilation and evaluation.\n *\n * By `at`, then by the order they appear in the document. The tiebreak matters:\n * two commands sharing an `at` is how the model spells \"in parallel\", and when\n * both write the same prop the later one in the array wins — the same\n * last-writer rule `commandParallel` already uses, so the two compose\n * predictably.\n */\nfunction inTimelineOrder(commands: readonly CommandSpec[]): CommandSpec[] {\n return commands\n .map((spec, index) => ({ spec, index }))\n .sort((a, b) => (a.spec.at - b.spec.at) || (a.index - b.index))\n .map((e) => e.spec);\n}\n\nconst NO_SLOTS: ReadonlySet<PropSlot<unknown>> = new Set();\n\n/**\n * Only an unmarked command can read live state while it runs, so only its reads are kept. A slot\n * snapshot (`save`) reads without reporting it, so everything it acts on counts as read.\n */\nfunction readsOf(command: Command<Record<string, unknown>>, recorder: WriteRecorder, owned: Iterable<PropSlot<unknown>>): ReadonlySet<PropSlot<unknown>> {\n if (settles(command)) return NO_SLOTS;\n for (const slot of owned) recorder.reads.add(slot);\n return recorder.reads;\n}\n\n/** Marks the command `settling` when `held`; a looped one is wrapped after, and runs. */\nfunction heldIf(held: boolean, made: Command<Record<string, unknown>> | void): Command<Record<string, unknown>> | void {\n return held && made ? settling(made) : made;\n}\n\n/** The scene root when a document doesn't author one explicitly. */\nfunction defaultRootSpec(): NodeSpec {\n return { id: ROOT_NODE_ID, type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} };\n}\n\n/**\n * Split the scene root — the row with {@link ROOT_NODE_ID} and `type: \"canvas2d\"`\n * — out of the document's nodes.\n *\n * The root is an ordinary row, not a special field, but it is not an ordinary\n * *child*: it is the canvas itself, not something `build` instantiates or\n * `syncPresence` parents. Every other place that walks the nodes needs it removed\n * first; this is the one place that removal happens, synthesizing the default\n * when the document left it out.\n */\nfunction splitRoot(specs: NodeSpec[]): { root: NodeSpec; rest: NodeSpec[] } {\n const rest: NodeSpec[] = [];\n let root: NodeSpec | undefined;\n for (const spec of specs) {\n if (spec.id === ROOT_NODE_ID && spec.type === \"canvas2d\") {\n root = spec;\n continue;\n }\n rest.push(spec);\n }\n return { root: root ?? defaultRootSpec(), rest };\n}\n\n/**\n * When each node is in the tree.\n *\n * Read off the document rather than accumulated during playback: a span of\n * `[2, 5)` says the node is present at every seek in it, whether the playhead\n * arrived from 1s or from 9s. A still's nodes carry no span, so they are present\n * always.\n */\nfunction presenceOf(doc: VisualDocument): Map<string, NodeSpan> {\n const spans = new Map<string, NodeSpan>();\n for (const node of doc.nodes) spans.set(node.id, nodeSpan(node));\n // The root is always present; it is not synced like an ordinary child.\n spans.delete(ROOT_NODE_ID);\n return spans;\n}\n\n/**\n * The clip document, compiled and evaluable, over the one canvas it builds\n * into — its live nodes, presence and baselines all belong to that tree.\n */\nexport class ClipTimeline {\n constructor(doc: VisualDocument, registry: Registry, private readonly canvas: Canvas2D) {\n this._doc = doc;\n this._registry = registry;\n const { root, rest } = splitRoot(doc.nodes);\n this._rootSpec = root;\n this._specs = rest;\n this._varSpecs = doc.variables ?? [];\n // Built from the rows rather than from the tree: an expression resolves its\n // references the moment it compiles, which is before most nodes exist.\n this._keyed = new Map(\n [root, ...rest]\n .filter((spec): spec is NodeSpec & { key: string } => !!spec.key)\n .map((spec) => [spec.key, spec.id]),\n );\n this._spans = presenceOf(doc);\n // Declared, not measured, so it is known before anything is built.\n this._duration = documentDuration(doc);\n }\n\n /** How long the scene runs. Read by the runtime after {@link build}. */\n get duration(): number {\n return this._duration;\n }\n\n /** Instantiate the tree into the canvas. Once per timeline: the nodes it makes belong to that canvas. */\n build(): void {\n // Variables first: everything below may compile an expression, and an\n // expression resolves its `[id]`s the moment it is compiled.\n this._buildVariables();\n\n this._pristineRoot = captureLayer(this.canvas as unknown as ReactiveHost);\n this._applyRootProps();\n\n for (const spec of this._specs) {\n this._live.set(spec.id, {\n spec,\n node: this._instantiate(spec),\n initial: NO_LAYER,\n initialStackDepth: 0,\n baseline: NO_LAYER,\n baseStackDepth: 0,\n presence: new PropSlot<boolean>(false, null, PRESENCE_PREFIX + spec.id),\n });\n }\n\n // Record what each parent built for itself *before* any document child\n // lands, so a composite node's own children keep their indices. A\n // document child is always placed after them.\n this._baseChildCount.set(ROOT_NODE_ID, this.canvas._allChildren.length);\n for (const [id, entry] of this._live) {\n this._baseChildCount.set(id, entry.node._allChildren.length);\n }\n\n this.syncPresence(0);\n\n // The root's baseline is captured too: `targetId: null` commands animate\n // the camera and the scene fill, and those need resetting like anything\n // else.\n this._root = {\n spec: this._rootSpec,\n node: this.canvas,\n initial: NO_LAYER,\n initialStackDepth: 0,\n baseline: NO_LAYER,\n baseStackDepth: 0,\n presence: new PropSlot<boolean>(true, null, PRESENCE_PREFIX + ROOT_NODE_ID),\n };\n for (const entry of this._live.values()) captureInitial(entry);\n captureInitial(this._root);\n this._baselined = new Set(this._present);\n for (const id of this._present) {\n if (this._live.get(id)?.node.mounted === false) {\n this._baselined.delete(id);\n this._unmounted.add(id);\n }\n }\n }\n\n /**\n * Build every command against the laid-out tree, then put the tree back.\n *\n * Separate from {@link build} because a command may read post-layout state to\n * decide what it animates *from*: an animated `removeChildAt` pins the\n * departing child to its rendered width, which is zero until layout runs.\n *\n * `settle` re-lays the tree out. It runs whenever the walk brings a node in or\n * takes one out, so a command is built against the tree as it stands at its\n * own `at` — see {@link _compileCommands}.\n */\n compile(settle: () => void = () => { }): void {\n this._settled = null;\n this._compileCommands(settle);\n this._restoreBaselines();\n const moved = this.syncPresence(0);\n if (this._restoreDisplaced(this._collectDisplaced()) || moved) settle();\n this._holdEntrances();\n this._indexSettled();\n }\n\n /** What a variable holds at the last evaluated time. For a host's inspector. */\n variableValue(id: string): unknown {\n return this._vars.get(id)?.cell.get();\n }\n\n /** Every variable this document declares, in declaration order. */\n variables(): readonly VariableSpec[] {\n return this._varSpecs;\n }\n\n /** The time the tree's presence was last synced to. */\n get presenceTime(): number {\n return this._presenceIndex().time;\n }\n\n /** Every sound a placed command plays, in clip seconds, with the node that plays it. */\n commandSounds(): PlacedSound[] {\n const out: PlacedSound[] = [];\n for (const placed of this._placed) {\n const played = commandSoundsOf(placed.command);\n if (!played) continue;\n for (const sound of played.sounds) {\n out.push({\n node: played.host,\n at: placed.start + sound.at,\n until: sound.until === undefined ? undefined : placed.start + sound.until,\n src: sound.src,\n options: sound.options,\n });\n }\n }\n return out;\n }\n\n /** Every compiled command, in timeline order — the indices {@link evaluateAt} reports writes under. */\n placedCommands(): readonly PlacedCommandInfo[] {\n return this._placed;\n }\n\n /** What the build stepped around — see {@link TimelineIssue}. Placeholders first, in row order. */\n issues(): TimelineIssue[] {\n const out: TimelineIssue[] = [];\n for (const { spec, node } of this._live.values()) {\n const missing = missingNodeOf(node);\n if (!missing) continue;\n out.push({\n code: \"unknown-node-type\",\n nodeId: spec.id,\n type: missing.type,\n message: `Unknown node type \"${missing.type}\" (node ${spec.id}): it builds as an empty placeholder, keeping its children.`,\n });\n }\n out.push(...this._skipped.values());\n return out;\n }\n\n /**\n * Put every node into the state it holds at `seconds`.\n *\n * A pure function of `seconds`: called in any order, repeatedly, and with\n * time going backwards. Restoring the baseline first is what makes it so —\n * without it a prop written by a command that has *not started yet* would\n * keep whatever the last evaluation left, and the same frame would look\n * different depending on how the playhead reached it.\n *\n * `onWrite` reports each slot a command writes, with its index in\n * {@link placedCommands}; the baseline restore is not reported.\n */\n evaluateAt(seconds: number, onWrite?: (index: number, slot: PropSlot<unknown>) => void): void {\n if (onWrite) {\n // Unobserved: a baseline holds prop cells, never presence or structure, so\n // an observer watching for those learns nothing from a write per cell.\n unobserved(() => this._restoreBaselines());\n this._evaluateObserved(seconds, onWrite);\n return;\n }\n\n if (this._settled) {\n this._restoreBaselines(this._wholeRestore);\n for (const { slot, baseline } of this._slotRestore) slot.restoreFrom(baseline);\n this._settled.evaluate(this._placed, seconds);\n return;\n }\n this._restoreBaselines();\n for (const placed of this._placed) {\n if (seconds < placed.holdFrom) continue;\n const local = seconds < placed.start ? 0\n : placed.duration > 0 ? (seconds - placed.start) / placed.duration\n : 1;\n // A finished command is held at `at(1)` rather than dropped, so a prop\n // written early and never touched again keeps its value — the same\n // rule `commandSequence` uses.\n placed.command.at(clamp01(local));\n }\n }\n\n /**\n * Add and remove document nodes so the tree matches `seconds`. Returns whether\n * anything moved.\n *\n * Separate from {@link evaluateAt} because it is structural: it changes what\n * layout walks, not what a prop holds. Called ahead of the evaluation for\n * the same time.\n */\n syncPresence(seconds: number): boolean {\n const rows = this._presenceIndex().crossed(seconds);\n // Nothing to do on the overwhelming majority of frames.\n if (rows.length === 0) return false;\n\n const arrivals: PresenceRow[] = [];\n const departures: PresenceRow[] = [];\n for (const row of rows) {\n const wanted = within(row, seconds);\n if (wanted !== this._present.has(row.id)) (wanted ? arrivals : departures).push(row);\n }\n this._arrived = arrivals;\n if (arrivals.length === 0 && departures.length === 0) return false;\n\n // Detach first: `remove` unmounts the whole subtree, so a node moving\n // parents is never briefly in two places.\n departures.sort(byDocumentOrder);\n for (const row of departures) {\n this._present.delete(row.id);\n row.siblings.add(row.slot, -1);\n const entry = this._live.get(row.id);\n if (!entry) continue;\n entry.presence.set(false);\n this._parentNodeOf(entry.spec)?.remove(entry.node);\n }\n\n // Insert after whatever the parent built for itself, at the row's place\n // among the siblings present, so `layerOrder` really is sibling order and a\n // composite's own children keep their indices. Ascending per parent, so\n // every sibling before a row is already in place when it lands.\n arrivals.sort(byDocumentOrder);\n const byParent = new Map<SiblingCounts, PresenceRow[]>();\n for (const row of arrivals) {\n const group = byParent.get(row.siblings);\n if (group) group.push(row);\n else byParent.set(row.siblings, [row]);\n }\n for (const [siblings, group] of byParent) {\n group.sort((a, b) => a.slot - b.slot);\n const parent = siblings.parentId === ROOT_NODE_ID ? this.canvas : this._live.get(siblings.parentId)?.node;\n const base = this._baseChildCount.get(siblings.parentId) ?? 0;\n for (const row of group) {\n this._present.add(row.id);\n const index = base + siblings.before(row.slot);\n siblings.add(row.slot, 1);\n const child = this._live.get(row.id);\n if (!child) continue;\n child.presence.set(true);\n parent?.addChildAt({ data: { child: child.node, index } });\n }\n }\n return true;\n }\n\n /** The node a row built, mounted or not; the canvas for the root. */\n liveNode(id: string): Node | undefined {\n return id === ROOT_NODE_ID ? this.canvas : this._live.get(id)?.node;\n }\n\n /**\n * What a row holds before any command has acted on it: its props as it\n * arrived, or as built for one that has not arrived yet. The same at every\n * time, which is what tells it from the node's live props. A bound prop is\n * read through its binding, so it answers for the tree as it stands.\n */\n baselineProps(id: string): Record<string, unknown> | undefined {\n const entry = id === ROOT_NODE_ID ? this._root : this._live.get(id);\n if (!entry) return undefined;\n const layer = entry.baseline === NO_LAYER ? entry.initial : entry.baseline;\n const props: Record<string, unknown> = {};\n for (const [key, snap] of layer) props[key] = snap.fn ? snap.fn() : snap.value;\n return props;\n }\n\n presenceSlot(id: string): PropSlot<boolean> | undefined {\n return id === ROOT_NODE_ID ? this._root?.presence : this._live.get(id)?.presence;\n }\n\n variableSlot(id: string): PropSlot<unknown> | undefined {\n return this._vars.get(id)?.cell;\n }\n\n /**\n * How to bring this built timeline to `next` in place, or `null` when only a\n * fresh build is sound. An audio document must be lowered by the caller first.\n */\n planUpdate(next: VisualDocument): TimelinePatch | null {\n const prev = this._docIndex ??= indexDocument(this._doc);\n return planTimelinePatch(prev, indexDocument(next), diffClip(this._doc, next), this._patchEnvironment());\n }\n\n /**\n * Apply a {@link planUpdate} result. The canvas must be attached at time 0\n * first, as for {@link build}; `prepare` samples and lays out like the step\n * between build and compile, `settle` like compile's. A throw leaves the\n * timeline unusable — dispose it and build fresh.\n */\n applyUpdate(patch: TimelinePatch, settle: () => void, prepare: () => void): void {\n if (!this._root) throw new Error(\"ClipTimeline.applyUpdate needs a built timeline.\");\n if (patch.prev !== this._docIndex) {\n throw new Error(\"This patch was planned against a different version of the document.\");\n }\n\n this._settled = null;\n this._restoreBaselines();\n this.syncPresence(0);\n\n this._updateVariables(patch);\n this._keyed.clear();\n for (const [key, id] of patch.next.keyed) this._keyed.set(key, id);\n\n const fresh = this._updateStructure(patch);\n\n for (const entry of fresh) {\n captureInitial(entry);\n const id = entry.spec.id;\n if (!this._present.has(id)) continue;\n if (entry.node.mounted) this._baselined.add(id);\n else this._unmounted.add(id);\n }\n for (const id of patch.inPlace) {\n const entry = this._live.get(id);\n if (entry) this._writeInPlace(entry, patch.prev.nodes.get(id)!);\n }\n if (patch.diff.rootChanged) {\n const host = this.canvas as unknown as ReactiveHost;\n applySnapshotLayer(host, this._pristineRoot);\n host._stateStack.length = 0;\n this._applyRootProps();\n captureInitial(this._root);\n }\n for (const id of patch.dirtyNodes) {\n const entry = id === ROOT_NODE_ID ? this._root : this._live.get(id);\n if (entry && !fresh.has(entry)) resetToInitial(entry);\n }\n prepare();\n\n const previous = new Map<string, PlacedCommand>();\n for (const placed of this._placed) previous.set(placed.spec.id, placed);\n const rebuilt = this._walkPatch(patch, previous, settle);\n\n const dirty = (id: string) => patch.dirtyNodes.has(id) || patch.dirtyVariables.has(id);\n const placed: PlacedCommand[] = [];\n const touched = new Set<TouchedOwner>();\n this._animated = [];\n this._animatedVars = [];\n this._animatedParts = [];\n if (!isStillDocument(this._doc)) {\n for (const spec of patch.next.ordered) {\n let entry = rebuilt.get(spec.id);\n if (!entry && !dirty(patch.next.targetOf(spec))) {\n const old = previous.get(spec.id);\n if (old) entry = old.spec === spec ? old : { ...old, spec };\n }\n if (!entry) continue;\n placed.push(entry);\n this._touch(entry, touched);\n }\n }\n this._placed = placed;\n for (const id of this._skipped.keys()) if (!patch.next.commands.has(id)) this._skipped.delete(id);\n\n this._restoreBaselines();\n const moved = this.syncPresence(0);\n if (this._restoreDisplaced(this._collectDisplaced()) || moved) settle();\n this._holdEntrances();\n this._indexSettled();\n }\n\n private _doc: VisualDocument;\n /** The vocabulary this document is compiled against — see `document/registry.ts`. */\n private readonly _registry: Registry;\n /** The scene root row — see {@link splitRoot}. */\n private _rootSpec: NodeSpec;\n private _specs: NodeSpec[];\n private _varSpecs: readonly VariableSpec[];\n private _spans: Map<string, NodeSpan>;\n private _duration: number;\n /** The current document's index, built on the first {@link planUpdate}. */\n private _docIndex: DocIndex | null = null;\n /** The canvas's cells before the root row was applied — what a patched root row resets to. */\n private _pristineRoot: PropLayer = NO_LAYER;\n\n /** Live nodes by id, valid between {@link build} and the next rebuild. */\n private readonly _live = new Map<string, LiveNode>();\n /** Live variables by id, same lifetime as {@link _live}. */\n private readonly _vars = new Map<string, LiveVariable>();\n /** Node ids by {@link NodeSpec.key}. Read off the document, so it needs no build. */\n private readonly _keyed: Map<string, string>;\n private _placed: PlacedCommand[] = [];\n /** Commands left out of {@link _placed}, by id — see {@link issues}. */\n private readonly _skipped = new Map<string, TimelineIssue>();\n /** Built after every compile and update, when any placed command is marked settling (`tween/command`). */\n private _settled: SettledIndex | null = null;\n /** With {@link _settled}: the animated nodes an unmarked command writes, put back whole… */\n private _wholeRestore: LiveNode[] = [];\n /** …and, on every other animated node, the baseline of each slot a marked command writes. */\n private _slotRestore: SlotBaseline[] = [];\n /** The scene root (`targetId: null`), plus its baseline. */\n private _root: LiveNode | null = null;\n /**\n * Only the nodes some command writes to. Everything else keeps its authored\n * props for the life of the scene, so restoring it every frame would be pure\n * waste — and on a large static scene that waste is most of the frame.\n *\n * A prop bound to a variable needs no restoring at all, which falls out of\n * this for free: the binding *is* the per-frame recompute, so a node driven\n * only by expressions never enters this list.\n */\n private _animated: LiveNode[] = [];\n /** Only the variables some command writes to. Same reasoning. */\n private _animatedVars: LiveVariable[] = [];\n /**\n * Slots on a part a node built for itself that some command writes, restored\n * alongside {@link _animated}. A part is no document row, so its baseline is\n * the slot's state the first time a command wrote it — see {@link _notePartWrite}.\n */\n private _animatedParts: PropSlot<unknown>[] = [];\n private readonly _partBaselines = new WeakMap<PropSlot<unknown>, PropSnapshot<unknown>>();\n /** Children each parent built for itself, which the document must not disturb. */\n private readonly _baseChildCount = new Map<string, number>();\n /** Node ids currently in the tree, so presence only churns when it changes. */\n private readonly _present = new Set<string>();\n /** Node ids whose baseline was taken while mounted — see {@link _compileCommands}. */\n private _baselined = new Set<string>();\n /**\n * Rows present at time 0 that a lifecycle command (`removeChildAt`,\n * `reparent`) took out of the parent their row names, as compile left them.\n * Presence only moves a row across its own span, so nothing else would put\n * one back before its command starts.\n */\n private _displaced: LiveNode[] = [];\n /** Rows that arrived, or were built, while an ancestor was out of the tree and wait for it — see {@link _baselineArrival}. */\n private readonly _unmounted = new Set<string>();\n private _presence: PresenceIndex | null = null;\n /** The rows the last {@link syncPresence} brought in, in document order. */\n private _arrived: readonly PresenceRow[] = [];\n\n /**\n * What a compiled expression resolves a reference against: a variable, or —\n * spelled with a dot — another node's prop.\n *\n * The dot is the whole discriminator, and it has to be: a node is not a value,\n * so `[card]` could never mean one, while a variable reference never carries a\n * prop. `document/validate.ts` reads the same split.\n *\n * A node reference resolves **late**. Nothing about the node is looked up here:\n * `build` binds in document order, so the node named may not exist yet, and\n * `syncPresence` adds and removes nodes as time moves, so one that exists can\n * still be legitimately absent at *t*. The thunk therefore does the lookup on\n * every read and answers `undefined` for a node that is not there — which is\n * `NaN` through arithmetic, loud in the first frame, and an unset prop on its\n * own. Throwing instead would make an `add` at 2s a crash at 0s.\n */\n private readonly _resolveVariable: VariableResolver = (name) => {\n const dot = name.indexOf(\".\");\n if (dot > 0) {\n const id = this._keyed.get(name.slice(0, dot));\n if (id === undefined) return undefined;\n const prop = name.slice(dot + 1);\n return () => (this._nodeById(id) as unknown as Record<string, unknown> | undefined)?.[prop];\n }\n return this._vars.get(name)?.read;\n };\n\n /**\n * The live node `id` names, or `undefined` while it is unbuilt or out of the\n * tree.\n *\n * Gated on `mounted` rather than on {@link _present}, which is only settled at\n * the end of {@link syncPresence} — so a prop read *during* the insertion walk\n * would see an out-of-date answer.\n */\n private _nodeById(id: string): Node | undefined {\n if (id === ROOT_NODE_ID) return this.canvas;\n const entry = this._live.get(id);\n if (!entry) return undefined;\n if (_observer !== null) this._readPresence(entry);\n return entry.node.mounted ? entry.node : undefined;\n }\n\n /** The row's presence and every document ancestor's — an ancestor leaving unmounts it too. */\n private _readPresence(entry: LiveNode): void {\n let at: LiveNode | undefined = entry;\n for (let depth = 0; at && depth <= this._live.size; depth++) {\n at.presence.get();\n at = at.spec.parentId === null ? undefined : this._live.get(at.spec.parentId);\n }\n }\n\n private _applyRootProps(): void {\n const { literal, bindings } = expressionOps.bindProps(this._rootSpec.props, this._resolveVariable);\n this.canvas.set({ ...literal, ...bindings } as never);\n }\n\n /** A row's node with its literal props passed to the constructor and its expressions bound after. */\n private _instantiate(spec: NodeSpec, rows: readonly NodeSpec[] = this._specs): Node {\n const props = migrateNodeProps(this._registry, spec.type, spec.props).props;\n const { literal, bindings, hasBindings } = expressionOps.bindProps(props, this._resolveVariable);\n if (!this._registry.strict && !this._registry.hasNode(spec.type)) {\n const dimension = this._placeholderDimension(spec, rows);\n const node = missingNode(dimension, spec, literal);\n const bound = placeholderProps(dimension, bindings);\n if (Object.keys(bound).length > 0) node.set(bound as never);\n return node;\n }\n const node = this._registry.instantiate(spec, literal);\n // Applied after construction rather than through it: see `instantiate`.\n if (hasBindings) node.set(bindings as never);\n return node;\n }\n\n /**\n * Create a slot per declared variable.\n *\n * The slot is created once per build and lives for the whole scene: a\n * variable has no presence span (see {@link VariableSpec}), so there is\n * nothing to sync and nothing that can be missing when an expression\n * compiled against it runs.\n */\n private _buildVariables(): void {\n for (const spec of this._varSpecs) {\n if (this._vars.has(spec.id)) {\n throw new Error(\n `Duplicate variable id \"${spec.id}\". Ids must be unique — an expression ` +\n `writing \"[${spec.id}]\" would otherwise name whichever declaration was read last.`,\n );\n }\n this._vars.set(spec.id, this._liveVariable(spec));\n }\n }\n\n private _liveVariable(spec: VariableSpec): LiveVariable {\n const cell = new PropSlot<unknown>(spec.value, null, VAR_PREFIX + spec.id);\n return {\n spec,\n cell,\n read: () => cell.get(),\n target: this._variableTarget(spec, cell),\n baseline: spec.value,\n };\n }\n\n private _variableTarget(spec: VariableSpec, cell: PropSlot<unknown>): VariableTarget {\n const lerp = this._registry.requireLerp(spec.lerp, spec.value, `variable \"${spec.id}\"`);\n return { id: spec.id, get: () => cell.get(), set: (v) => cell.set(v), lerp };\n }\n\n /**\n * Put every animated node back to its authored state.\n *\n * The save stack is truncated alongside the props, and that is not\n * housekeeping. `save`/`restore` are commands, so a `save` re-runs on every\n * evaluation of a frame after it — without the truncation the stack would\n * grow by one layer per frame forever, and a later `restore` would pop a\n * layer pushed by some *other* seek instead of the one its own `save` made.\n * Truncating is what keeps the pair a function of the chain rather than of\n * how the playhead got here.\n */\n private _restoreBaselines(nodes: readonly LiveNode[] = this._animated): void {\n // Structure before props: a node put back is attached, and the baseline is\n // what it holds once attached.\n this._restoreDisplaced(this._displaced);\n\n // Variables first, so a prop bound to one recomputes against the restored\n // value rather than a stale one.\n for (const entry of this._animatedVars) entry.cell.set(entry.baseline);\n\n for (const entry of nodes) {\n const host = entry.node as unknown as ReactiveHost;\n applySnapshotLayer(host, entry.baseline);\n if (host._stateStack.length > entry.baseStackDepth) {\n host._stateStack.length = entry.baseStackDepth;\n }\n }\n\n for (const slot of this._animatedParts) slot.restoreFrom(this._partBaselines.get(slot)!);\n }\n\n /**\n * Build every command, in timeline order, against a node already holding\n * what its predecessors left.\n *\n * The tree is moved to each command's `at` before it is built: an unmounted\n * node hands back an inert stepper and the command caches it, so a tween on a\n * node that enters at 2s built against the t=0 tree would never move. A node\n * entering here is baselined on arrival, before anything has touched it.\n *\n * The tree is re-laid-out only where something reads it — see\n * {@link _settleWindows}.\n */\n private _compileCommands(settle: () => void): void {\n if (isStillDocument(this._doc)) return;\n\n const touched = new Set<TouchedOwner>();\n const ordered = inTimelineOrder(this._doc.commands);\n const refBound = this._refBound(ordered);\n const settles = this._settleWindows(ordered, (i) => this._readsLayout(ordered[i], refBound));\n\n for (let i = 0; i < ordered.length; i++) {\n const spec = ordered[i];\n if (this.syncPresence(spec.at)) {\n // Every node present but not yet baselined arrived in this sync:\n // one that left and came back was baselined the first time.\n for (const row of this._arrived) {\n if (!this._baselined.has(row.id)) this._baselineArrival(row.id);\n }\n this._baselineMounted();\n if (settles[i]) settle();\n }\n\n const placed = this._buildPlaced(spec);\n if (!placed) continue;\n this._placed.push(placed);\n this._touch(placed, touched);\n }\n }\n\n /**\n * Building runs every marked command to its end, which the restore then undoes.\n * A node only marked commands write keeps every other slot at its baseline from\n * here on, so an evaluation puts back only the slots they write.\n */\n private _indexSettled(): void {\n const index = (this._settled = SettledIndex.build(this._placed));\n if (!index) return;\n this._restoreBaselines();\n\n const whole = new Set<LiveNode | LiveVariable>();\n const written = new Map<LiveNode, Set<PropSlot<unknown>>>();\n this._placed.forEach((placed, i) => {\n const held = index.holds(i);\n if (!held) whole.add(placed.owner);\n for (const slot of placed.writes) {\n const host = slot._host;\n const entry = host === null ? undefined : host.id === ROOT_NODE_ID ? this._root! : this._live.get(host.id);\n if (!entry) continue;\n if (!held) whole.add(entry);\n else if (written.has(entry)) written.get(entry)!.add(slot);\n else written.set(entry, new Set([slot]));\n }\n });\n this._wholeRestore = [];\n this._slotRestore = [];\n for (const entry of this._animated) {\n const slots = whole.has(entry) ? null : slotBaselines(entry, written.get(entry));\n if (slots) this._slotRestore.push(...slots);\n else this._wholeRestore.push(entry);\n }\n }\n\n /** The present rows whose node is no longer under the parent its row names. */\n private _collectDisplaced(): LiveNode[] {\n const out: LiveNode[] = [];\n for (const id of this._present) {\n const entry = this._live.get(id);\n const parent = entry && this._declaredParent(id);\n if (entry && parent && entry.node.parent !== parent) out.push(entry);\n }\n out.sort((a, b) => this._presenceIndex().row(a.spec.id)!.slot - this._presenceIndex().row(b.spec.id)!.slot);\n return (this._displaced = out);\n }\n\n /**\n * Put displaced rows back where {@link syncPresence} would have inserted them.\n * Returns whether any moved.\n */\n private _restoreDisplaced(entries: readonly LiveNode[]): boolean {\n let moved = false;\n for (const entry of entries) {\n const id = entry.spec.id;\n const row = this._presenceIndex().row(id);\n const parent = this._declaredParent(id);\n if (!row || !parent || !this._present.has(id) || entry.node.parent === parent) continue;\n entry.node.parent?.remove(entry.node);\n const base = this._baseChildCount.get(row.siblings.parentId) ?? 0;\n parent.addChildAt({ data: { child: entry.node, index: base + row.siblings.before(row.slot) } });\n moved = true;\n }\n return moved;\n }\n\n /** The node a row's `parentId` names: the canvas for the root, `undefined` while that row is unbuilt. */\n private _declaredParent(id: string): Node | undefined {\n const parentId = this._presenceIndex().row(id)?.siblings.parentId;\n if (parentId === undefined) return undefined;\n return parentId === ROOT_NODE_ID ? this.canvas : this._live.get(parentId)?.node;\n }\n\n /**\n * Take the baseline of a row that has just arrived, if it is mounted.\n *\n * A baseline is the node as it stands once attached: an unmounted node's cells\n * hold pre-attach values, without what it inherits from its ancestors. A row\n * can arrive while an ancestor is still out of the tree (a child entering\n * before its parent), so its baseline waits in {@link _unmounted} until\n * {@link _baselineMounted} finds it mounted.\n */\n private _baselineArrival(id: string): void {\n const entry = this._live.get(id);\n if (entry && !entry.node.mounted) {\n this._unmounted.add(id);\n return;\n }\n if (entry) captureBaseline(entry);\n this._baselined.add(id);\n this._unmounted.delete(id);\n }\n\n /** Baseline the rows that arrived unmounted and have since been mounted by an ancestor arriving. */\n private _baselineMounted(): void {\n for (const id of this._unmounted) {\n const entry = this._live.get(id);\n if (!entry) {\n this._unmounted.delete(id);\n } else if (entry.node.mounted) {\n captureBaseline(entry);\n this._baselined.add(id);\n this._unmounted.delete(id);\n }\n }\n }\n\n /**\n * Build one command against the tree as it stands and run it to its end —\n * which is what leaves its target where the next command's `from` must start.\n * Undone wholesale by {@link _restoreBaselines}. Throws when its target names\n * no row, for a node-scoped command of any kind. A command its target's type\n * does not publish, or any aimed at a placeholder, is skipped and recorded\n * (`null`) unless the registry is strict.\n *\n * The running-to-`at(1)` cannot be skipped: `node.to({ x: 100 })` reads `x`\n * when the command is *constructed*, so a chain built against the untouched\n * tree would give every step the same `from` and each would jump back to the\n * start.\n */\n private _buildPlaced(spec: CommandSpec): PlacedCommand | null {\n // Resolved in two tiers. The global table holds only what must resolve\n // *without* a node — the variable-scoped commands, whose target is not a\n // node at all, and the generic prop writers. That is why it is consulted\n // first: `scope` is what decides whether there is a node to look anything\n // up on. Everything else is a method on the target's own type, where it\n // cannot collide with another type's command of the same name.\n let entry = this._registry.command(spec.type);\n if (entry?.scope !== \"variable\") {\n const missing = missingNodeOf(this._targetOrThrow(spec).node);\n if (missing) {\n return this._skip(spec, `Command ${spec.id} (\"${spec.type}\") targets \"${spec.targetId}\", a placeholder for unknown node type \"${missing.type}\"; it is skipped.`, spec.type);\n }\n }\n if (!entry) {\n const typeKey = this._targetOrThrow(spec).entry.spec.type;\n const factory = this._registry.nodeCommand(typeKey, spec.type);\n if (!factory) {\n const message = `Node type \"${typeKey}\" has no command \"${spec.type}\" ` +\n `(command ${spec.id}). It publishes: ` +\n `${this._registry.commandKeys(typeKey).join(\", \") || \"none\"}.` +\n (LEGACY_COMMAND_HINTS[spec.type] ? ` ${LEGACY_COMMAND_HINTS[spec.type]}` : \"\");\n if (this._registry.strict) throw new Error(message);\n return this._skip(spec, `${message} It is skipped.`, spec.type);\n }\n entry = { key: spec.type, scope: \"node\", factory };\n }\n this._skipped.delete(spec.id);\n\n const duration = spec.duration ?? 0;\n const easing = resolveEase(spec.easing, this._registry);\n const recorder = new WriteRecorder(this._notePartWrite);\n // Applied inside `buildToEnd`, so the `at(1)` that leaves the target where\n // the next command's `from` starts is the *loop's* end — which for an odd\n // number of `alternate` passes is back where it began. A looped command\n // then carries the span of every pass, which is what the placed duration\n // has to be for a seek into the fourth repetition to land in it.\n const loop = loopRepeats(spec.loop) ? spec.loop : undefined;\n const repeat = (made: Command<Record<string, unknown>> | void) =>\n (made && loop ? loopCommand(made, loop, this._unlimitedFill(spec.at)) : made);\n\n if (entry.scope === \"variable\") {\n const variable = spec.targetId === null ? undefined : this._vars.get(spec.targetId);\n if (!variable) {\n throw new Error(\n `Command ${spec.id} (\"${spec.type}\") targets variable \"${spec.targetId}\", ` +\n `which this document does not declare.`,\n );\n }\n this._assertNoExpressions(spec);\n const { factory } = entry;\n const held = holdsWhenFinished(commandTraits(this._registry, spec, undefined), spec);\n const command = observeSlots(recorder, () =>\n buildToEnd(() => repeat(heldIf(held, factory(variable.target, spec.args, duration, easing)))));\n return { spec, start: spec.at, holdFrom: spec.at, entrance: false, duration: loop ? command.duration : duration, command, writes: recorder.writes, reads: readsOf(command, recorder, [variable.cell]), readsLayout: recorder.readsLayout, owner: variable };\n }\n\n const target = this._targetOrThrow(spec);\n // `to` and `set` carry a props diff, so a renamed prop is renamed there too.\n const given = PROP_DIFF_COMMANDS.has(spec.type)\n ? migrateNodeProps(this._registry, target.entry.spec.type, spec.args).props\n : spec.args;\n const args = entry.binds ? this._bindArgs(given) : (this._assertNoExpressions(spec), given);\n const { factory } = entry;\n const held = holdsWhenFinished(commandTraits(this._registry, spec, target.entry.spec), spec);\n const command = observeSlots(recorder, () =>\n buildToEnd(() => repeat(heldIf(held, factory(target.node, args, duration, easing)))));\n const entrance = entry.scope === \"node\" && this._registry.node(target.entry.spec.type)?.commands.get(spec.type)?.entrance === true;\n return { spec, start: spec.at, holdFrom: spec.at, entrance, duration: loop ? command.duration : duration, command, writes: recorder.writes, reads: readsOf(command, recorder, (target.node as unknown as ReactiveHost).__cells?.slots.values() ?? []), readsLayout: recorder.readsLayout, owner: target.entry };\n }\n\n /**\n * Hold each entrance's first frame back from its `at`, so the node it brings in\n * never shows at rest ahead of it.\n *\n * Back to the later of the moment its target arrives and the latest end of an\n * earlier command writing any slot it writes. Stopping there keeps placement\n * order honest: a command the entrance would otherwise overwrite still shows,\n * and an entrance after an exit keeps the node gone in between. A command on\n * the same node that writes other slots (a `moveTo` while it waits) does not\n * stop it.\n */\n private _holdEntrances(): void {\n const ended = new Map<PropSlot<unknown>, number>();\n let byId: Map<string, NodeSpec> | undefined;\n for (const placed of this._placed) {\n placed.holdFrom = placed.start;\n if (placed.entrance) {\n const id = placed.owner.spec.id;\n byId ??= new Map(this._specs.map((s) => [s.id, s]));\n let from = id === ROOT_NODE_ID ? 0 : effectiveSpanIn(byId, id)?.start ?? placed.start;\n for (const slot of placed.writes) from = Math.max(from, ended.get(slot) ?? -Infinity);\n if (from < placed.start) placed.holdFrom = Math.max(0, from);\n }\n const end = placed.start + placed.duration;\n for (const slot of placed.writes) {\n if (!(end <= (ended.get(slot) ?? -Infinity))) ended.set(slot, end);\n }\n }\n }\n\n /**\n * Seconds an unlimited loop starting at `at` has to fill.\n *\n * The clip's own length, which `documentDuration` answers counting one pass\n * of every unlimited loop — so a scene made of nothing but a spinner is one\n * turn long, and that same spinner in a ten-second scene turns for ten\n * seconds rather than stretching the scene to forever.\n */\n private _unlimitedFill(at: number): number {\n return Math.max(0, this._duration - at);\n }\n\n /**\n * Put everything a command writes into the restore lists — its target, and\n * any *other* node it wrote.\n *\n * A command is not confined to its target: `Cursor.click` names a control and\n * throws it, the way the lifecycle commands tween the child they move. Only\n * the target used to be restored, which left the other node holding whatever\n * the last evaluation happened to leave — a frame that depends on how the\n * playhead reached it, which is the one thing the whole design forbids.\n *\n * `writes` is already recorded (see {@link WriteRecorder}) and a slot carries\n * its owner, so this needs no declaration from the command. A variable's slot\n * arrives as {@link PlacedCommand.owner}. A slot on a part a node built for\n * itself has no row to be restored through, so it is restored on its own, to\n * the state {@link _notePartWrite} saw before any command wrote it.\n */\n private _touch(placed: PlacedCommand, touched: Set<TouchedOwner>): void {\n this._touchOwner(placed.owner, touched);\n for (const slot of placed.writes) {\n const host = slot._host;\n if (host === null) continue;\n const entry = host.id === ROOT_NODE_ID ? this._root : this._live.get(host.id);\n if (entry) {\n this._touchOwner(entry, touched);\n } else if (this._partBaselines.has(slot) && !touched.has(slot)) {\n touched.add(slot);\n this._animatedParts.push(slot);\n }\n }\n }\n\n private _touchOwner(owner: LiveNode | LiveVariable, touched: Set<TouchedOwner>): void {\n if (touched.has(owner)) return;\n touched.add(owner);\n if (\"cell\" in owner) this._animatedVars.push(owner);\n else this._animated.push(owner);\n }\n\n /**\n * Save a part's slot the first time a command is about to write it.\n *\n * Called by the observer *before* the write lands, while a command is built:\n * every earlier command has run to its end by then, but none of them wrote\n * this slot, so what it holds is what the part was built with (plus whatever\n * the command's own factory primed, which is part of the command, not of the\n * part).\n */\n private readonly _notePartWrite = (slot: PropSlot<unknown>): void => {\n const host = slot._host;\n if (host === null || this._partBaselines.has(slot)) return;\n if (host.id === ROOT_NODE_ID || this._live.has(host.id)) return;\n this._partBaselines.set(slot, slot.snapshot());\n };\n\n /**\n * Compile the expressions in a binding command's args.\n *\n * A command declaring `binds` is saying its args *are* a props diff that\n * reaches `node.set()` — `set` is the only built-in that does — where a\n * function is a binding.\n */\n private _bindArgs(args: Record<string, unknown>): Record<string, unknown> {\n const { literal, bindings } = expressionOps.bindProps(args, this._resolveVariable, \"args\");\n return { ...literal, ...bindings };\n }\n\n /**\n * Refuse an expression in a command that cannot bind one.\n *\n * An expression is a *binding*: it says a prop follows a variable for as\n * long as it is set. A tween's destination is a **value** — `to` reads it\n * once, when the command compiles, to work out what it is interpolating\n * towards — so a formula there could only ever mean \"the value this happened\n * to have at build time\", which is never what anyone writing it meant.\n * Failing here rather than coercing is the same call `NodeSpec.type` makes:\n * a document that half-renders is worse than one that refuses to.\n */\n private _assertNoExpressions(spec: CommandSpec): void {\n const found = expressionOps.collect(spec.args, \"args\");\n if (found.length === 0) return;\n const { path, source } = found[0];\n throw new Error(\n `Command ${spec.id} (\"${spec.type}\") carries an expression at ${path}: ${JSON.stringify(source)}. ` +\n `Expressions bind a prop to a variable; they are not tween destinations. ` +\n `Bind the prop where the node is authored (or with a \"set\" command) and animate the variable ` +\n `with \"variableTo\" instead.`,\n );\n }\n\n private _skip(spec: CommandSpec, message: string, type: string): null {\n this._skipped.set(spec.id, {\n code: \"unknown-command\",\n commandId: spec.id,\n ...(spec.targetId !== null && { nodeId: spec.targetId }),\n type,\n message,\n });\n return null;\n }\n\n /**\n * The tree a placeholder for `spec` belongs to: its children's, else the one\n * its parent holds — a viewport holding two trees gives the one it adds.\n */\n private _placeholderDimension(spec: NodeSpec, rows: readonly NodeSpec[]): NodeDimension {\n const byId = new Map(rows.map((row) => [row.id, row]));\n const seen = new Set<string>();\n const of = (row: NodeSpec): NodeDimension => {\n seen.add(row.id);\n for (const child of rows) {\n if (child.parentId !== row.id) continue;\n const dimension = this._registry.describe(child.type)?.dimension;\n if (dimension) return dimension;\n }\n const parent = row.parentId === null ? undefined : byId.get(row.parentId);\n if (!parent) return \"2d\";\n const described = this._registry.describe(parent.type);\n if (!described) return seen.has(parent.id) ? \"2d\" : of(parent);\n const holds = (described.holds ?? []).filter((d) => d !== \"audio\");\n if (holds.length === 0) return described.holds?.includes(\"audio\") ? \"audio\" : described.dimension ?? \"2d\";\n return holds.find((d) => d !== described.dimension) ?? holds[0];\n };\n return of(spec);\n }\n\n /** The live node a node-scoped command targets; one error, naming the `targetId`, when no row has it. */\n private _targetOrThrow(spec: CommandSpec): { id: string; node: Node; entry: LiveNode } {\n const target = this._targetOf(spec);\n if (!target) {\n throw new Error(\n `Command ${spec.id} (\"${spec.type}\") targets node \"${spec.targetId}\", ` +\n `which this document does not declare.`,\n );\n }\n return target;\n }\n\n /** Resolve a command's `targetId` to a live node, or `null` if it names nothing. */\n private _targetOf(spec: CommandSpec): { id: string; node: Node; entry: LiveNode } | null {\n if (spec.targetId === null) {\n return this._root ? { id: ROOT_NODE_ID, node: this._root.node, entry: this._root } : null;\n }\n const entry = this._live.get(spec.targetId);\n return entry ? { id: spec.targetId, node: entry.node, entry } : null;\n }\n\n private _evaluateObserved(seconds: number, onWrite: (index: number, slot: PropSlot<unknown>) => void): void {\n let index = 0;\n const observer: SlotObserver = { read: () => { }, write: (slot) => onWrite(index, slot) };\n observeSlots(observer, () => {\n for (; index < this._placed.length; index++) {\n const placed = this._placed[index];\n if (seconds < placed.holdFrom) continue;\n const local = seconds < placed.start ? 0 : placed.duration > 0 ? (seconds - placed.start) / placed.duration : 1;\n placed.command.at(clamp01(local));\n }\n });\n }\n\n /**\n * Mark the steps that open a presence window needing a settle: a window is\n * the run of steps between two changes to the tree, and it needs one only\n * when a step in it reads layout.\n *\n * At the window's start rather than just before its first reader, because a\n * reader must see the boxes as they stood when the window opened — a size tween\n * built earlier in the same window has already run to its end by then, and a\n * settle after it would hand the reader that end state instead.\n */\n private _settleWindows(steps: readonly { at: number }[], reads: (index: number) => boolean): Uint8Array {\n const index = this._presenceIndex();\n const settles = new Uint8Array(steps.length);\n // -1 is the window the tree was already laid out for.\n let opener = -1;\n let previous = index.time;\n for (let i = 0; i < steps.length; i++) {\n const { at } = steps[i];\n if (index.differs(previous, at)) opener = i;\n previous = at;\n if (opener < 0 || settles[opener]) continue;\n if (reads(i)) settles[opener] = 1;\n }\n return settles;\n }\n\n private _readsLayout(spec: CommandSpec, refBound: ReadonlySet<string>): boolean {\n const id = spec.targetId ?? ROOT_NODE_ID;\n const target = spec.targetId === null ? this._rootSpec : this._live.get(spec.targetId)?.spec;\n const traits = commandTraits(this._registry, spec, target);\n return traits === null || traits.readsLayout || refBound.has(id);\n }\n\n /**\n * Targets of a binding command carrying a node reference: a binding a `set`\n * installs mid-scene can read another node's box, and a `from` taken over it\n * later evaluates it.\n */\n private _refBound(commands: readonly CommandSpec[]): Set<string> {\n const out = new Set<string>();\n for (const spec of commands) {\n const entry = this._registry.command(spec.type);\n if (entry?.scope === \"node\" && entry.binds && hasNodeRef(spec.args)) out.add(spec.targetId ?? ROOT_NODE_ID);\n }\n return out;\n }\n\n /** Built on first use, from the rows as they stand. */\n private _presenceIndex(): PresenceIndex {\n return this._presence ??= new PresenceIndex(this._specs, this._spans);\n }\n\n /** The live node a spec's `parentId` names, or the scene root. */\n private _parentNodeOf(spec: NodeSpec): Node | undefined {\n if (spec.parentId === null) return this.canvas;\n return this._live.get(spec.parentId)?.node;\n }\n\n private _patchEnvironment(): PatchEnvironment {\n const registry = this._registry;\n return {\n traits: (spec, target) => commandTraits(registry, spec, target),\n nodeRefs: (spec, target) => commandNodeRefs(registry, spec, target),\n isContextProvider: (type) => isContextProvider(registry, type),\n isLayoutNeutralProp: (type, key) => isLayoutNeutralProp(registry, type, key),\n writesInPlace: (row, key) => writesPlacementInPlace(registry, row, key),\n ctorOf: (id) => {\n const node = this._live.get(id)?.node;\n return node && missingNodeOf(node) ? MISSING_TYPE : node?.constructor;\n },\n registeredCtor: (type) => registry.node(type)?.ctor ?? (registry.strict ? undefined : MISSING_TYPE),\n dimensionOf: (type) => registry.node(type)?.descriptor.dimension,\n };\n }\n\n /** Write the props `entry`'s row changed since `was` as its new initial values. */\n private _writeInPlace(entry: LiveNode, was: NodeSpec): void {\n const changed: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(entry.spec.props)) {\n if (!jsonEqual(was.props[key], value)) changed[key] = value;\n }\n resetToInitial(entry);\n const { literal, bindings } = expressionOps.bindProps(changed, this._resolveVariable);\n entry.node.set({ ...literal, ...bindings } as never);\n captureInitial(entry);\n }\n\n private _updateVariables(patch: TimelinePatch): void {\n const { added, removed, changed } = patch.diff.variables;\n for (const id of removed) this._vars.delete(id);\n for (const id of added) this._vars.set(id, this._liveVariable(patch.next.variables.get(id)!));\n for (const id of changed) {\n const spec = patch.next.variables.get(id)!;\n const entry = this._vars.get(id);\n if (!entry) {\n this._vars.set(id, this._liveVariable(spec));\n continue;\n }\n entry.baseline = spec.value;\n entry.target = this._variableTarget(spec, entry.cell);\n }\n for (const spec of patch.next.variables.values()) {\n const entry = this._vars.get(spec.id);\n if (entry) entry.spec = spec;\n }\n // Restoring only resets animated variables, so a changed value nothing animates would never land.\n for (const id of patch.dirtyVariables) {\n const entry = this._vars.get(id);\n if (entry) entry.cell.set(entry.baseline);\n }\n }\n\n /**\n * Take detached rows out of the tree, replace and add instances, swap in the\n * next document's rows, and re-insert whatever is present at 0. Returns the\n * entries holding a new instance.\n */\n private _updateStructure(patch: TimelinePatch): Set<LiveNode> {\n const { next } = patch;\n\n for (const id of patch.detach) {\n const entry = this._live.get(id);\n if (!entry) continue;\n entry.node.parent?.remove(entry.node);\n entry.presence.set(false);\n this._present.delete(id);\n }\n\n const isDocumentNode = (node: Node) => this._live.get(node.id)?.node === node;\n for (const id of patch.removed) {\n const entry = this._live.get(id);\n if (!entry) continue;\n disposeBuilt(entry.node, isDocumentNode);\n this._live.delete(id);\n this._baseChildCount.delete(id);\n this._baselined.delete(id);\n this._unmounted.delete(id);\n }\n for (const id of patch.reinstantiate) {\n const entry = this._live.get(id);\n if (entry) disposeBuilt(entry.node, isDocumentNode);\n }\n\n const { root, rest } = splitRoot(next.doc.nodes);\n const fresh = new Set<LiveNode>();\n for (const spec of rest) {\n let entry = this._live.get(spec.id);\n if (entry && !patch.reinstantiate.has(spec.id)) {\n entry.spec = spec;\n continue;\n }\n const node = this._instantiate(spec, rest);\n if (entry) {\n entry.spec = spec;\n entry.node = node;\n this._baselined.delete(spec.id);\n this._unmounted.delete(spec.id);\n } else {\n entry = {\n spec,\n node,\n initial: NO_LAYER,\n initialStackDepth: 0,\n baseline: NO_LAYER,\n baseStackDepth: 0,\n presence: new PropSlot<boolean>(false, null, PRESENCE_PREFIX + spec.id),\n };\n this._live.set(spec.id, entry);\n }\n this._baseChildCount.set(spec.id, node._allChildren.length);\n fresh.add(entry);\n }\n\n this._doc = next.doc;\n this._docIndex = next;\n this._rootSpec = root;\n this._root!.spec = root;\n this._specs = rest;\n this._varSpecs = next.doc.variables ?? [];\n this._spans = presenceOf(next.doc);\n this._duration = documentDuration(next.doc);\n\n // A fresh index knows nothing is in the tree, so seed it with what still is.\n const index = this._presence = new PresenceIndex(this._specs, this._spans);\n for (const id of [...this._present]) {\n const row = index.row(id);\n if (row && within(row, 0)) {\n row.siblings.add(row.slot, 1);\n continue;\n }\n this._present.delete(id);\n const entry = this._live.get(id);\n if (!entry) continue;\n entry.presence.set(false);\n entry.node.parent?.remove(entry.node);\n }\n this.syncPresence(0);\n return fresh;\n }\n\n /**\n * Rebuild the dirty chains in the next document's timeline order, replaying the\n * clean chains they build against and taking arrival baselines where compile\n * would have. Returns the rebuilt commands by id.\n */\n private _walkPatch(\n patch: TimelinePatch,\n previous: ReadonlyMap<string, PlacedCommand>,\n settle: () => void,\n ): Map<string, PlacedCommand> {\n const rebuilt = new Map<string, PlacedCommand>();\n if (isStillDocument(this._doc)) return rebuilt;\n\n const { next } = patch;\n const dirty = (id: string) => patch.dirtyNodes.has(id) || patch.dirtyVariables.has(id);\n const refBound = this._refBound(next.ordered);\n let replay = patch.replay;\n // A settle for a binding over another node's box has to see every chain at its `at`.\n if (replay !== \"all\" && [...refBound].some(dirty)) replay = \"all\";\n\n const steps: WalkStep[] = [];\n const { captures } = patch;\n let c = 0;\n for (const spec of next.ordered) {\n while (c < captures.length && captures[c].at <= spec.at) steps.push({ at: captures[c].at, capture: captures[c++].id });\n const id = next.targetOf(spec);\n if (replay === \"all\" || dirty(id) || replay.has(id)) steps.push({ at: spec.at, spec });\n }\n for (; c < captures.length; c++) steps.push({ at: captures[c].at, capture: captures[c].id });\n\n const settles = this._settleWindows(steps, (i) => {\n const spec = steps[i].spec;\n return spec !== undefined && dirty(next.targetOf(spec)) && this._readsLayout(spec, refBound);\n });\n\n let pending = false;\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i];\n if (settles[i]) pending = true;\n if (this.syncPresence(step.at)) this._baselineMounted();\n if (step.capture !== undefined) {\n this._baselined.delete(step.capture);\n this._baselineArrival(step.capture);\n continue;\n }\n // After this `at`'s captures, as compile baselines arrivals before it settles.\n if (pending) {\n settle();\n pending = false;\n }\n const spec = step.spec!;\n const old = previous.get(spec.id);\n if (old && !dirty(next.targetOf(spec))) {\n old.command.at(1);\n continue;\n }\n const placed = this._buildPlaced(spec);\n if (placed) rebuilt.set(spec.id, placed);\n }\n return rebuilt;\n }\n}\n\n/**\n * What to say when a command type the format no longer has fails to resolve.\n * A document written before nodes carried their own spans is otherwise a\n * \"no command\" error that names nothing it could be fixed with.\n */\nconst LEGACY_COMMAND_HINTS: Readonly<Record<string, string>> = {\n add: \"A node is a row in `nodes`, entering at its `startAt`.\",\n remove: \"A node leaves at its `endAt`.\",\n variable: \"A variable is declared in `variables`.\",\n};\n\nconst NO_LAYER: PropLayer = new Map();\n\nconst PROP_DIFF_COMMANDS: ReadonlySet<string> = new Set([\"to\", \"set\"]);\n\n/** What {@link ClipTimeline._touch} dedupes: an owner, or a part's slot. */\ntype TouchedOwner = LiveNode | LiveVariable | PropSlot<unknown>;\n\n/** Records what building one command wrote, and whether it read a laid-out box. */\nclass WriteRecorder implements SlotObserver {\n readonly writes = new Set<PropSlot<unknown>>();\n readonly reads = new Set<PropSlot<unknown>>();\n readsLayout = false;\n\n /** `firstWrite` runs the first time a slot is written, before the write lands. */\n constructor(private readonly firstWrite: (slot: PropSlot<unknown>) => void) { }\n\n read(slot: PropSlot<unknown>): void {\n if (slot._name === LAYOUT_SLOT) this.readsLayout = true;\n this.reads.add(slot);\n }\n\n write(slot: PropSlot<unknown>): void {\n if (this.writes.has(slot)) return;\n this.firstWrite(slot);\n this.writes.add(slot);\n }\n}\n\n/**\n * Build a command and run it to its end. A factory that acts at once and returns\n * nothing (`restore` with no duration) has already done this build's `at(1)`, so\n * it becomes a stamp that acts again on every later evaluation.\n */\nfunction buildToEnd(make: () => Command<Record<string, unknown>> | void): Command<Record<string, unknown>> {\n const made = make();\n if (made) {\n made.at(1);\n return made;\n }\n return driveCommand(0, () => {\n make();\n }) as unknown as Command<Record<string, unknown>>;\n}\n\n/**\n * Snapshot a node's prop slots at its authored state. Taken while it is mounted:\n * an unmounted node's cells hold pre-attach values.\n */\nfunction captureBaseline(entry: LiveNode): void {\n const host = entry.node as unknown as ReactiveHost;\n entry.baseline = captureLayer(host);\n entry.baseStackDepth = host._stateStack.length;\n}\n\ninterface SlotBaseline {\n slot: PropSlot<unknown>;\n baseline: PropSnapshot<unknown>;\n}\n\n/** The baseline of each of `slots`, or `null` when one isn't among the node's props. */\nfunction slotBaselines(entry: LiveNode, slots: ReadonlySet<PropSlot<unknown>> | undefined): SlotBaseline[] | null {\n if (!slots) return [];\n const cells = (entry.node as unknown as ReactiveHost).__cells?.slots;\n if (!cells) return null;\n const out: SlotBaseline[] = [];\n for (const [key, slot] of cells) {\n const baseline = slots.has(slot) ? entry.baseline.get(key) : undefined;\n if (baseline) out.push({ slot, baseline });\n }\n return out.length === slots.size ? out : null;\n}\n\nfunction captureInitial(entry: LiveNode): void {\n captureBaseline(entry);\n entry.initial = entry.baseline;\n entry.initialStackDepth = entry.baseStackDepth;\n}\n\nfunction resetToInitial(entry: LiveNode): void {\n const host = entry.node as unknown as ReactiveHost;\n applySnapshotLayer(host, entry.initial);\n if (host._stateStack.length > entry.initialStackDepth) host._stateStack.length = entry.initialStackDepth;\n entry.baseline = entry.initial;\n entry.baseStackDepth = entry.initialStackDepth;\n}\n\n/** Dispose `node` and whatever it built for itself; a document child it still holds is left alone. */\nfunction disposeBuilt(node: Node, isDocumentNode: (node: Node) => boolean): void {\n for (const child of node._allChildren) {\n if (!isDocumentNode(child)) disposeBuilt(child, isDocumentNode);\n }\n node.dispose();\n}\n\n/** One document row's place in a {@link PresenceIndex}. */\ninterface PresenceRow {\n id: string;\n start: number;\n end: number;\n /** Position in the document's rows. */\n order: number;\n /** Position among its parent's document children, in `layerOrder` order. */\n slot: number;\n siblings: SiblingCounts;\n /** The last {@link PresenceIndex.crossed} pass that collected this row. */\n pass: number;\n}\n\nfunction within(row: PresenceRow, seconds: number): boolean {\n return seconds >= row.start && seconds < row.end;\n}\n\nfunction byDocumentOrder(a: PresenceRow, b: PresenceRow): number {\n return a.order - b.order;\n}\n\n/**\n * How many of one parent's document children are present before a given slot — a\n * Fenwick tree, so an insert index costs O(log siblings) rather than a walk over\n * every sibling.\n */\nclass SiblingCounts {\n constructor(readonly parentId: string, size: number) {\n this._tree = new Int32Array(size + 1);\n }\n\n add(slot: number, delta: number): void {\n for (let i = slot + 1; i < this._tree.length; i += i & -i) this._tree[i] += delta;\n }\n\n before(slot: number): number {\n let count = 0;\n for (let i = slot; i > 0; i -= i & -i) count += this._tree[i];\n return count;\n }\n\n private readonly _tree: Int32Array;\n}\n\n/**\n * Every span boundary, sorted by time, and a cursor at the last time synced.\n *\n * Moving to another time visits only the rows with a boundary between the two, in\n * either direction and however far — which is what keeps a scrub, and a compile\n * walking its commands, from rescanning every node per step.\n */\nclass PresenceIndex {\n /** The last time {@link crossed} was asked for. Nothing is present before the first. */\n time = -Infinity;\n\n constructor(specs: readonly NodeSpec[], spans: ReadonlyMap<string, NodeSpan>) {\n const byParent = new Map<string, { spec: NodeSpec; order: number }[]>();\n specs.forEach((spec, order) => {\n if (!spans.has(spec.id)) return;\n const parentId = spec.parentId ?? ROOT_NODE_ID;\n const group = byParent.get(parentId);\n if (group) group.push({ spec, order });\n else byParent.set(parentId, [{ spec, order }]);\n });\n for (const [parentId, group] of byParent) {\n // Stable, so a `layerOrder` tie keeps document order.\n group.sort((a, b) => a.spec.layerOrder - b.spec.layerOrder);\n const siblings = new SiblingCounts(parentId, group.length);\n group.forEach(({ spec, order }, slot) => {\n const { start, end } = spans.get(spec.id)!;\n const row: PresenceRow = { id: spec.id, start, end, order, slot, siblings, pass: 0 };\n this._rows.set(spec.id, row);\n this._events.push({ time: start, row });\n if (Number.isFinite(end)) this._events.push({ time: end, row });\n });\n }\n this._events.sort((a, b) => a.time - b.time);\n }\n\n /** Each row with a boundary between the last time synced and `seconds`, once. Moves the cursor. */\n crossed(seconds: number): readonly PresenceRow[] {\n this.time = seconds;\n const target = this._upperBound(seconds);\n if (target === this._cursor) return NO_ROWS;\n const from = Math.min(target, this._cursor);\n const to = Math.max(target, this._cursor);\n this._cursor = target;\n const pass = ++this._pass;\n const rows: PresenceRow[] = [];\n for (let k = from; k < to; k++) {\n const { row } = this._events[k];\n if (row.pass === pass) continue;\n row.pass = pass;\n rows.push(row);\n }\n return rows;\n }\n\n /** Whether any row is present at one of `a`, `b` and not the other. Moves nothing. */\n differs(a: number, b: number): boolean {\n const from = this._upperBound(Math.min(a, b));\n const to = this._upperBound(Math.max(a, b));\n for (let k = from; k < to; k++) {\n const { row } = this._events[k];\n if (within(row, a) !== within(row, b)) return true;\n }\n return false;\n }\n\n row(id: string): PresenceRow | undefined {\n return this._rows.get(id);\n }\n\n private readonly _events: { time: number; row: PresenceRow }[] = [];\n private readonly _rows = new Map<string, PresenceRow>();\n /** How many events are at or before {@link time}. */\n private _cursor = 0;\n private _pass = 0;\n\n /** The first event after `seconds` — every event before it has happened by then. */\n private _upperBound(seconds: number): number {\n let lo = 0;\n let hi = this._events.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (this._events[mid].time <= seconds) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n}\n\nconst NO_ROWS: readonly PresenceRow[] = [];\n", "import type { ResolvedTextSpan, TextAlign } from \"@/attributes/text/types\";\nimport { ShapeAlignmentInput, ShapeState, resolveShapeAlignment, resolveShapePivot, stripShapeAlignmentKeys } from \"./shape\";\n\nexport interface RichTextState extends ShapeState {\n spans: ResolvedTextSpan[];\n /** A named typography preset — see {@link TextState.variant}. Applied per span. */\n variant?: string;\n lineHeight: number;\n textAlign: TextAlign;\n width: number;\n height: number;\n}\n\nexport function withRichTextDescriptor(descriptor: Partial<RichTextState> & ShapeAlignmentInput): RichTextState {\n const width = descriptor.width ?? 0;\n const height = descriptor.height ?? 0;\n const { x, y, pivot } = resolveShapeAlignment(descriptor, width, height);\n return {\n ...stripShapeAlignmentKeys(descriptor),\n opacity: descriptor.opacity ?? 1,\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x,\n y,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n pivot: resolveShapePivot(pivot),\n spans: descriptor.spans ?? [],\n lineHeight: descriptor.lineHeight ?? 1.2,\n textAlign: descriptor.textAlign ?? 'center',\n width,\n height,\n };\n}\n", "import { NodeEffect } from \"@/attributes/shape/effects/union\";\nimport { NodeBlendMode } from \"@/attributes/shape/fill/blend\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { Matrix2D } from \"@/attributes/layout/matrix2d\";\n\nexport interface TransformState {\n x: number;\n y: number;\n width: number;\n height: number;\n opacity: number;\n /** Layer blend mode. `'pass-through'` (the default) does not isolate the node; any other mode isolates it and blends its flattened result against the backdrop. Optional so per-shape descriptors that extend this state needn't carry it. */\n blend?: NodeBlendMode;\n rotation: number;\n scale: number;\n effects: NodeEffect[];\n /** Pivot point for rotation and scale, in normalised node space. (0,0)=center, (-1,1)=top-left, (1,-1)=bottom-right. */\n pivot: Vector2;\n /**\n * The node's whole local transform, precomposed — present only when the\n * decomposed fields above cannot express it, which today means a node that\n * mirrors or tilts out of its own plane (`flipHorizontal`, `rotationX`,\n * `perspective`, …). A backend that finds one **concats it instead of**\n * applying `x`/`y`/`rotation`/`scale`/`pivot`, not as well as.\n *\n * Handed over precomposed rather than as six more fields for each backend to\n * rebuild from: the projection is defined once, in `nodeProjectedMatrix`, and\n * every backend gets the same answer rather than each growing its own\n * arithmetic from the same inputs. It may carry a perspective row, so it is a\n * full 3×3 — see {@link Matrix2D}.\n *\n * Note this is deliberately *more* than `Node2D._localMatrix` reports: the\n * out-of-plane transform is paint rather than geometry, so it reaches the\n * canvas and nothing else. See `Node2D._localMatrix` for why.\n */\n matrix?: Matrix2D;\n}\n\n\nexport function withTransformDescriptor(descriptor: Partial<TransformState>): TransformState {\n return {\n x: descriptor.x ?? 0,\n y: descriptor.y ?? 0,\n width: descriptor.width ?? 0,\n height: descriptor.height ?? 0,\n opacity: descriptor.opacity ?? 1,\n blend: descriptor.blend ?? 'pass-through',\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n effects: descriptor.effects ?? [],\n pivot: descriptor.pivot ?? { x: 0, y: 0 },\n // No default: absent means \"the decomposed fields say it all\", which is\n // every node that stays in its own plane.\n matrix: descriptor.matrix,\n };\n}", "import { ShapeState, resolveShapePivot } from \"./shape\";\n\nexport type PathCommand =\n | { type: \"M\"; x: number; y: number }\n | { type: \"m\"; x: number; y: number }\n | { type: \"L\"; x: number; y: number }\n | { type: \"l\"; x: number; y: number }\n | { type: \"H\"; x: number }\n | { type: \"h\"; x: number }\n | { type: \"V\"; y: number }\n | { type: \"v\"; y: number }\n | { type: \"C\"; x1: number; y1: number; x2: number; y2: number; x: number; y: number }\n | { type: \"c\"; x1: number; y1: number; x2: number; y2: number; x: number; y: number }\n | { type: \"S\"; x2: number; y2: number; x: number; y: number }\n | { type: \"s\"; x2: number; y2: number; x: number; y: number }\n | { type: \"Q\"; x1: number; y1: number; x: number; y: number }\n | { type: \"q\"; x1: number; y1: number; x: number; y: number }\n | { type: \"T\"; x: number; y: number }\n | { type: \"t\"; x: number; y: number }\n | { type: \"A\"; rx: number; ry: number; rotation: number; largeArc: 0 | 1; sweep: 0 | 1; x: number; y: number }\n | { type: \"a\"; rx: number; ry: number; rotation: number; largeArc: 0 | 1; sweep: 0 | 1; x: number; y: number }\n | { type: \"Z\" | \"z\" };\n\n\n\nexport type PathData = string | PathCommand[];\n\nexport function toPathString(d: PathData): string {\n if (typeof d === \"string\") return d;\n return d.map(cmd => {\n switch (cmd.type) {\n case \"M\": case \"m\": return `${cmd.type} ${cmd.x} ${cmd.y}`;\n case \"L\": case \"l\": return `${cmd.type} ${cmd.x} ${cmd.y}`;\n case \"T\": case \"t\": return `${cmd.type} ${cmd.x} ${cmd.y}`;\n case \"H\": case \"h\": return `${cmd.type} ${cmd.x}`;\n case \"V\": case \"v\": return `${cmd.type} ${cmd.y}`;\n case \"C\": case \"c\": return `${cmd.type} ${cmd.x1} ${cmd.y1} ${cmd.x2} ${cmd.y2} ${cmd.x} ${cmd.y}`;\n case \"S\": case \"s\": return `${cmd.type} ${cmd.x2} ${cmd.y2} ${cmd.x} ${cmd.y}`;\n case \"Q\": case \"q\": return `${cmd.type} ${cmd.x1} ${cmd.y1} ${cmd.x} ${cmd.y}`;\n case \"A\": case \"a\": return `${cmd.type} ${cmd.rx} ${cmd.ry} ${cmd.rotation} ${cmd.largeArc} ${cmd.sweep} ${cmd.x} ${cmd.y}`;\n case \"Z\": case \"z\": return cmd.type;\n }\n }).join(\" \");\n}\n\n/** An axis-aligned bounding box in path coordinates: [minX, minY, maxX, maxY]. */\nexport type PathBounds = readonly [number, number, number, number];\n\nexport interface PathState extends ShapeState {\n data: PathData;\n /**\n * Explicit frame to center the path against, as [minX, minY, maxX, maxY] in\n * the path's own coordinate space. When set, the path is shifted so this\n * box's center lands on the local origin — instead of the path centering on\n * its *own* bbox.\n *\n * Use this when several paths share one layout frame (e.g. per-glyph LaTeX\n * tokens). Passing the same whole-shape bounds to every path keeps their\n * relative positions intact, where per-path self-centering would collapse\n * them onto a single point. When unset, the path centers on its own bbox.\n */\n centerBounds?: PathBounds;\n}\n\nexport function withPathDescriptor(descriptor: Partial<PathState>): PathState {\n return {\n opacity: descriptor.opacity ?? 1,\n\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x: descriptor.x ?? 0,\n y: descriptor.y ?? 0,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n width: descriptor.width ?? 0,\n height: descriptor.height ?? 0,\n pivot: resolveShapePivot(descriptor.pivot),\n\n data: descriptor.data ?? \"\",\n centerBounds: descriptor.centerBounds,\n };\n}\n", "import type { TextState } from \"./descriptors/text\";\n\n/**\n * Where a laid-out run of text put its characters — the measurement an editor\n * needs in order to draw its own caret and selection over rendered glyphs.\n *\n * **Space.** Block-local canvas pixels: origin at the centre of the text block,\n * **y down**, before the node's own transform. That is exactly the space the\n * backend shapes into when handed origin `(0, 0)`, so a caret at x = 0 sits on\n * the block's centre line and nothing here has to know where the node is.\n * {@link nodeTextLayout} is what lifts it into viewport space.\n *\n * **Why carets rather than glyph boxes.** A text cursor lives *between*\n * characters, so a run of n characters has n + 1 positions — and the two extra\n * facts an editor needs (where the run starts, where it ends) are precisely the\n * ones a list of glyph boxes leaves implicit. Reporting the slots directly also\n * means the host never has to reason about advance widths, kerning or trailing\n * whitespace to place a cursor.\n */\n\n/** One laid-out line of a text block. */\nexport interface TextBlockLine {\n /**\n * Character range this line covers, `[start, end)`, as offsets into the\n * block's whole string. A hard line break is *not* part of either line.\n */\n start: number;\n end: number;\n /** Top and bottom of the line box, block-local. */\n top: number;\n bottom: number;\n /**\n * The x of every caret slot on this line, block-local, in offset order:\n * `carets[i]` is the slot at character `start + i`, so there are\n * `end - start + 1` of them — one before each character plus one after the\n * last. Ordered left-to-right; bidirectional text is not modelled in v1.\n */\n carets: number[];\n}\n\n/**\n * A shaped text block: its lines, and the size the shaping produced.\n *\n * `width`/`height` are the block's own extent, which is what a hugging node\n * measures to — not the box it may have been aligned within.\n */\nexport interface TextBlockLayout {\n lines: TextBlockLine[];\n width: number;\n height: number;\n}\n\n/**\n * The caret slot count implied by a layout — i.e. one past the last character.\n *\n * Lines exclude their line break, so summing their slots would count the breaks\n * twice and lose the final position; this reads it off the last line instead.\n */\nexport function caretCount(layout: TextBlockLayout): number {\n const last = layout.lines[layout.lines.length - 1];\n return last ? last.end + 1 : 1;\n}\n\n/**\n * Something that can report where a shaped text block put its characters.\n *\n * Narrower than {@link RenderContext2D}, which is the only real implementation:\n * `nodeTextLayout` needs exactly this one call, and typing it against the whole\n * render context would make a caret measurement look like it required a\n * renderer. It does not — it requires a shaper.\n */\nexport interface TextBlockSource {\n layoutTextBlock(state: Partial<TextState>): TextBlockLayout | null;\n}\n\n/**\n * Narrow `value` to a {@link TextBlockSource}, or `null` when it cannot report\n * glyph positions.\n *\n * A capability check rather than a cast, because it really is one: a\n * {@link MeasureContext2D} answers how *wide* text comes out, which every backend can\n * do, while reporting where each character *landed* needs a shaper that keeps\n * its line boxes. A host handed a measurer that has no such shaper should get\n * \"no caret model here\", not a crash.\n */\nexport function asTextBlockSource(value: unknown): TextBlockSource | null {\n return typeof (value as TextBlockSource | null)?.layoutTextBlock === \"function\"\n ? value as TextBlockSource\n : null;\n}\n", "/**\n * What a render issue is about:\n *\n * - `missing`: a feature the backend does not draw (`feature` names it).\n * - `shader`: a user shader that does not compile, or one that is not WGSL (an SkSL shader from an old document).\n * - `params`: a shader's uniforms and its `struct Params` disagree (a value with no member, a member with no value).\n * - `gpu`: a WebGPU validation or out-of-memory error.\n * - `device-lost`: the GPU device was lost; the backend is drawing on a new one.\n * - `crashed`: the backend itself failed and draws nothing more on this page.\n */\nexport type RenderIssueKind = \"missing\" | \"shader\" | \"params\" | \"gpu\" | \"device-lost\" | \"crashed\";\n\n/** Something a frame drew without throwing but not as the document says. */\nexport interface RenderIssue {\n kind: RenderIssueKind;\n message: string;\n /** What is affected, as the backend names it (`blend:color-dodge`, `text:path`, `fill:shader`). */\n feature?: string;\n /** The node it was found on, when the backend knows. */\n nodeId?: string;\n}\n\n/** A backend's issue as a typed one; a bare string is the shader message backends reported before issues were typed. */\nexport function toRenderIssue(issue: RenderIssue | string): RenderIssue {\n return typeof issue === \"string\" ? { kind: \"shader\", message: issue } : issue;\n}\n\n/** One key per kind, feature and node: what an issue list is deduplicated by. */\nexport function renderIssueKey(issue: RenderIssue): string {\n return `${issue.kind}|${issue.feature ?? \"\"}|${issue.nodeId ?? \"\"}|${issue.feature ? \"\" : issue.message}`;\n}\n\n/**\n * The backend lost what it draws with while a render was under way, so the\n * frames already drawn cannot be trusted. Thrown by exports and stills on a\n * `device-lost` or `crashed` issue; `retryable` says whether the same render\n * can simply run again (the backend recovered on a new device).\n */\nexport class RenderBackendError extends Error {\n override readonly name = \"RenderBackendError\";\n readonly retryable: boolean;\n\n constructor(readonly issue: RenderIssue) {\n super(issue.message);\n this.retryable = issue.kind === \"device-lost\";\n }\n}\n\n/** Whether an issue means the frames drawn around it are not to be trusted. */\nexport function isFatalRenderIssue(issue: RenderIssue): boolean {\n return issue.kind === \"device-lost\" || issue.kind === \"crashed\";\n}\n", "import type {\n BoxGeometry3D, BufferGeometry3D, CapsuleGeometry3D, CircleGeometry3D,\n ConeGeometry3D, CylinderGeometry3D, EdgesGeometry3D, ExtrudeGeometry3D,\n Geometry3D, LatheGeometry3D, ModelGeometry3D, ParametricGeometry3D,\n PlaneGeometry3D, PolyhedronGeometry3D, RingGeometry3D, SphereGeometry3D,\n TorusGeometry3D, TorusKnotGeometry3D, TubeGeometry3D, WireframeGeometry3D,\n} from \"./geometry\";\nimport type {\n BasicMaterial3D, DepthMaterial3D, LambertMaterial3D, LineBasicMaterial3D,\n LineDashedMaterial3D, MatcapMaterial3D, NormalMaterial3D, PhongMaterial3D,\n PhysicalMaterial3D, PointsMaterial3D, ShaderMaterial3D, ShadowMaterial3D,\n SpriteMaterial3D, StandardMaterial3D, ToonMaterial3D,\n} from \"./material\";\nimport type { DataTexture3D, ImageTexture3D, SurfaceSource3D, SurfaceTexture3D, TextureOptions3D } from \"./texture\";\n\n/** A descriptor's own params, with the `type` discriminant removed. */\ntype ParamsOf<T> = Omit<T, \"type\">;\n\n/**\n * Geometry descriptors.\n *\n * These are plain values, so hoist one out of the builder and share it across\n * meshes — the renderer dedupes by identity, so a shared geometry is uploaded to\n * the GPU once no matter how many meshes reference it.\n *\n * const brick = Geo.box({ width: 1, height: 0.5, depth: 0.5 });\n * g.mesh(brick, red, { position: [0, 0, 0] })\n * .mesh(brick, red, { position: [1, 0, 0] }); // same GPU buffer\n */\nexport const Geo = {\n box: (o?: ParamsOf<BoxGeometry3D>): BoxGeometry3D => ({ type: \"box\", ...o }),\n sphere: (o?: ParamsOf<SphereGeometry3D>): SphereGeometry3D => ({ type: \"sphere\", ...o }),\n plane: (o?: ParamsOf<PlaneGeometry3D>): PlaneGeometry3D => ({ type: \"plane\", ...o }),\n cylinder: (o?: ParamsOf<CylinderGeometry3D>): CylinderGeometry3D => ({ type: \"cylinder\", ...o }),\n cone: (o?: ParamsOf<ConeGeometry3D>): ConeGeometry3D => ({ type: \"cone\", ...o }),\n torus: (o?: ParamsOf<TorusGeometry3D>): TorusGeometry3D => ({ type: \"torus\", ...o }),\n torusKnot: (o?: ParamsOf<TorusKnotGeometry3D>): TorusKnotGeometry3D => ({ type: \"torusKnot\", ...o }),\n circle: (o?: ParamsOf<CircleGeometry3D>): CircleGeometry3D => ({ type: \"circle\", ...o }),\n ring: (o?: ParamsOf<RingGeometry3D>): RingGeometry3D => ({ type: \"ring\", ...o }),\n capsule: (o?: ParamsOf<CapsuleGeometry3D>): CapsuleGeometry3D => ({ type: \"capsule\", ...o }),\n\n tetrahedron: (o?: Omit<ParamsOf<PolyhedronGeometry3D>, \"shape\">): PolyhedronGeometry3D =>\n ({ type: \"polyhedron\", shape: \"tetrahedron\", ...o }),\n octahedron: (o?: Omit<ParamsOf<PolyhedronGeometry3D>, \"shape\">): PolyhedronGeometry3D =>\n ({ type: \"polyhedron\", shape: \"octahedron\", ...o }),\n icosahedron: (o?: Omit<ParamsOf<PolyhedronGeometry3D>, \"shape\">): PolyhedronGeometry3D =>\n ({ type: \"polyhedron\", shape: \"icosahedron\", ...o }),\n dodecahedron: (o?: Omit<ParamsOf<PolyhedronGeometry3D>, \"shape\">): PolyhedronGeometry3D =>\n ({ type: \"polyhedron\", shape: \"dodecahedron\", ...o }),\n\n extrude: (o: ParamsOf<ExtrudeGeometry3D>): ExtrudeGeometry3D => ({ type: \"extrude\", ...o }),\n lathe: (o: ParamsOf<LatheGeometry3D>): LatheGeometry3D => ({ type: \"lathe\", ...o }),\n tube: (o: ParamsOf<TubeGeometry3D>): TubeGeometry3D => ({ type: \"tube\", ...o }),\n\n /** Raw vertex buffers — any mesh you can compute. */\n buffer: (o: ParamsOf<BufferGeometry3D>): BufferGeometry3D => ({ type: \"buffer\", ...o }),\n /** A surface sampled over a `[0,1]²` grid. Sugar over {@link Geo.buffer}. */\n parametric: (o: ParamsOf<ParametricGeometry3D>): ParametricGeometry3D => ({ type: \"parametric\", ...o }),\n\n /** The hard edges of another geometry — a clean outline, no triangulation diagonals. */\n edges: (source: Geometry3D, o?: Omit<ParamsOf<EdgesGeometry3D>, \"source\">): EdgesGeometry3D =>\n ({ type: \"edges\", source, ...o }),\n /** Every triangle edge of another geometry. */\n wireframe: (source: Geometry3D): WireframeGeometry3D => ({ type: \"wireframe\", source }),\n\n model: (src: string, o?: Omit<ParamsOf<ModelGeometry3D>, \"src\">): ModelGeometry3D =>\n ({ type: \"modelGeometry\", src, ...o }),\n} as const;\n\n/**\n * Material descriptors.\n *\n * Like geometries these are shareable values — one hoisted material across many\n * meshes compiles one shader program instead of N.\n *\n * Reach for {@link Mat.standard} by default; {@link Mat.physical} only when a\n * surface actually needs clearcoat, transmission, sheen or iridescence, since\n * those cost more per pixel. {@link Mat.shader} is the full-control escape hatch.\n */\nexport const Mat = {\n basic: (o?: ParamsOf<BasicMaterial3D>): BasicMaterial3D => ({ type: \"basic\", ...o }),\n standard: (o?: ParamsOf<StandardMaterial3D>): StandardMaterial3D => ({ type: \"standard\", ...o }),\n physical: (o?: ParamsOf<PhysicalMaterial3D>): PhysicalMaterial3D => ({ type: \"physical\", ...o }),\n phong: (o?: ParamsOf<PhongMaterial3D>): PhongMaterial3D => ({ type: \"phong\", ...o }),\n lambert: (o?: ParamsOf<LambertMaterial3D>): LambertMaterial3D => ({ type: \"lambert\", ...o }),\n toon: (o?: ParamsOf<ToonMaterial3D>): ToonMaterial3D => ({ type: \"toon\", ...o }),\n normal: (o?: ParamsOf<NormalMaterial3D>): NormalMaterial3D => ({ type: \"normal\", ...o }),\n depth: (o?: ParamsOf<DepthMaterial3D>): DepthMaterial3D => ({ type: \"depth\", ...o }),\n matcap: (o?: ParamsOf<MatcapMaterial3D>): MatcapMaterial3D => ({ type: \"matcap\", ...o }),\n points: (o?: ParamsOf<PointsMaterial3D>): PointsMaterial3D => ({ type: \"points\", ...o }),\n lineBasic: (o?: ParamsOf<LineBasicMaterial3D>): LineBasicMaterial3D => ({ type: \"lineBasic\", ...o }),\n lineDashed: (o?: ParamsOf<LineDashedMaterial3D>): LineDashedMaterial3D => ({ type: \"lineDashed\", ...o }),\n sprite: (o?: ParamsOf<SpriteMaterial3D>): SpriteMaterial3D => ({ type: \"sprite\", ...o }),\n shadow: (o?: ParamsOf<ShadowMaterial3D>): ShadowMaterial3D => ({ type: \"shadow\", ...o }),\n /** Raw GLSL. Uniform *values* are free to animate; source changes recompile. */\n shader: (o: ParamsOf<ShaderMaterial3D>): ShaderMaterial3D => ({ type: \"shader\", ...o }),\n} as const;\n\n/**\n * Texture descriptors.\n *\n * {@link Tex.image} takes a manifest path and is loaded through core's ordinary\n * image pipeline, so the pixels are resident before the frame that needs them\n * draws. A bare string works anywhere a texture is expected, so `Tex.image` is\n * only needed when passing sampler options.\n */\nexport const Tex = {\n image: (src: string, o?: TextureOptions3D): ImageTexture3D => ({ src, ...o }),\n /** A texture from raw RGBA8888 bytes — gradient ramps, noise, LUTs. */\n data: (\n data: ArrayLike<number>,\n width: number,\n height: number,\n o?: TextureOptions3D & { revision?: number },\n ): DataTexture3D => ({ data, width, height, ...o }),\n /**\n * A texture painted from Motion Script's own 2D output — the bridge from 2D\n * onto 3D geometry.\n *\n * `source` is a **value**: a built `Graphics2D` command list, or a `Node2D`\n * subtree for anything needing real layout, shaped `Text` or a loaded\n * `Image`. Both are passed directly; there is no name to match and nothing\n * has to be mounted anywhere in particular.\n *\n * const scope = new Graphics2D().line({ points: trace(phase()) }).stroke(…);\n * g3.plane({ fill: scope }); // sized for you\n *\n * const stats = new Rect({ flow: \"vertical\", padding: 48, children: [Text({ text: \"CPU\" })] });\n * g3.plane({ fill: Tex.surface(stats, { width: 1024, height: 640 }) });\n *\n * `width`/`height` are the buffer's resolution and default to 512. A source\n * handed straight to `fill` gets exactly this treatment with those defaults,\n * so the builder is only needed to pin a resolution or a sampler option.\n * **Hoist the source** rather than rebuilding it each frame — see\n * {@link SurfaceTexture3D}.\n */\n surface: (\n source: SurfaceSource3D,\n o?: TextureOptions3D & { width?: number; height?: number; maxPixelRatio?: number },\n ): SurfaceTexture3D => ({\n width: 512,\n height: 512,\n ...o,\n source,\n }),\n} as const;\n", "/**\n * Subdivision counts, as one name.\n *\n * three spells this ten different ways — `widthSegments`, `heightSegments`,\n * `depthSegments`, `radialSegments`, `tubularSegments`, `thetaSegments`,\n * `phiSegments`, `capSegments`, `curveSegments`, `detail` — and which one a given\n * shape wants is a thing an author has to look up every time. Every geometry here\n * takes one {@link Segments3D} instead, and the per-axis meaning is documented on\n * the shape rather than encoded in a name.\n *\n * A scalar applies to every axis, which is what you want when you are just\n * turning the resolution up. A tuple is per-axis, in the order the shape's own\n * docs give.\n */\nexport type Segments3D =\n | number\n | readonly [number]\n | readonly [number, number]\n | readonly [number, number, number];\n\n/**\n * Resolve a {@link Segments3D} against a shape's per-axis defaults.\n *\n * A scalar broadcasts, a tuple fills what it names and leaves the rest at the\n * default, and `undefined` is entirely defaults — so an unset `segments` never\n * pins a shape to a resolution invented at a call site.\n *\n * Values are floored and clamped to at least 1, because a fractional or zero\n * subdivision count reaches three as a degenerate geometry rather than as an\n * error.\n */\nexport function segmentsOf(\n value: Segments3D | undefined,\n defaults: readonly number[],\n): number[] {\n if (value === undefined) return defaults.map(clampSegment);\n if (typeof value === \"number\") return defaults.map(() => clampSegment(value));\n return defaults.map((fallback, index) => clampSegment(value[index] ?? fallback));\n}\n\nfunction clampSegment(value: number): number {\n return Math.max(1, Math.floor(value));\n}\n", "import type { BufferGeometry3D } from \"./geometry\";\n\n/**\n * A box with rounded edges and corners, evaluated into vertex buffers.\n *\n * `Rect` has had `cornerRadius` since the beginning and it is most of what makes\n * 2D content read as designed rather than as debug output; the same is true in\n * 3D, and it is the one thing a Spline scene has that a bare three scene does\n * not. three has no rounded box in core — its `RoundedBoxGeometry` is an addon,\n * and importing addons would defeat the lazy `import(\"three\")` boundary — so the\n * surface is built here: in core, as plain data, backend-agnostic and testable\n * without a GPU, exactly like `evaluateParametric`.\n *\n * The surface is the Minkowski sum of an inner box (each half-extent reduced by\n * `radius`) and a sphere of that radius, which decomposes into 26 patches: 6 flat\n * faces, 12 quarter-cylinder edges and 8 spherical-octant corners. Each patch is\n * a grid of `core + radius * direction`, where `direction` is also the vertex\n * normal — so lighting is exact rather than interpolated off a deformed box.\n */\nexport interface RoundedBoxOptions {\n width: number;\n height: number;\n depth: number;\n radius: number;\n /** Face subdivision per axis, as `[x, y, z]`. */\n segments: readonly [number, number, number];\n}\n\ntype Vec3 = readonly [number, number, number];\n\n/** A patch grid, before it is tessellated into the output buffers. */\ninterface Grid {\n /** Position at grid coordinate `(u, v)`, both in `[0, 1]`. */\n position: (u: number, v: number) => Vec3;\n /** Unit normal at `(u, v)`. */\n normal: (u: number, v: number) => Vec3;\n uSteps: number;\n vSteps: number;\n}\n\n/**\n * Arc resolution for the rounded regions, derived from how round the box\n * actually is rather than exposed as a knob.\n *\n * `segments` means face subdivision on every other shape and has to keep meaning\n * that here; a second count just for the arcs would be a field whose right value\n * is always \"enough that it looks smooth\". That is a function of the radius\n * relative to the box, so it is computed — a barely-rounded edge gets the\n * minimum, a nearly-spherical one gets a full sweep.\n */\nfunction arcSegmentsFor(radius: number, maxHalf: number): number {\n if (maxHalf <= 0) return 3;\n return Math.max(3, Math.min(16, Math.round((radius / maxHalf) * 40)));\n}\n\n/**\n * Build the rounded box's vertex buffers.\n *\n * Returns a plain {@link BufferGeometry3D}, so the renderer's existing buffer\n * path uploads it with no new code, and `Geo.edges`/`Geo.wireframe` derive from\n * it like any other geometry.\n */\nexport function evaluateRoundedBox(options: RoundedBoxOptions): BufferGeometry3D {\n const half: Vec3 = [options.width / 2, options.height / 2, options.depth / 2];\n const maxHalf = Math.max(half[0], half[1], half[2]);\n const radius = Math.max(0, Math.min(options.radius, half[0], half[1], half[2]));\n\n // The inner box the sphere is swept around. Clamped at zero so a radius equal\n // to a half-extent (a fully rounded axis) degenerates to a line rather than\n // folding the surface inside out.\n const box: Vec3 = [\n Math.max(0, half[0] - radius),\n Math.max(0, half[1] - radius),\n Math.max(0, half[2] - radius),\n ];\n\n const arc = arcSegmentsFor(radius, maxHalf);\n\n const position: number[] = [];\n const normal: number[] = [];\n const uv: number[] = [];\n const index: number[] = [];\n\n for (const grid of patches(half, box, radius, options.segments, arc)) {\n emit(grid, half, position, normal, uv, index);\n }\n\n return {\n type: \"buffer\",\n position: new Float32Array(position),\n normal: new Float32Array(normal),\n uv: new Float32Array(uv),\n index: new Uint32Array(index),\n staticData: true,\n };\n}\n\n/** The 26 patches, in face then edge then corner order. */\nfunction* patches(\n half: Vec3,\n box: Vec3,\n radius: number,\n segments: readonly [number, number, number],\n arc: number,\n): Generator<Grid> {\n const AXES = [0, 1, 2] as const;\n const SIGNS = [-1, 1] as const;\n\n // 6 faces: flat, spanning the inner box on the two free axes and pinned at\n // the full half-extent on its own. Subdivided by `segments`, which is what a\n // displacement map reads.\n for (const axis of AXES) {\n const u = (axis + 1) % 3;\n const v = (axis + 2) % 3;\n for (const sign of SIGNS) {\n const face = axisVector(axis, sign);\n yield {\n uSteps: segments[u],\n vSteps: segments[v],\n normal: () => face,\n position: (a, b) => {\n const point: number[] = [0, 0, 0];\n point[axis] = sign * half[axis];\n point[u] = lerp(-box[u], box[u], a);\n point[v] = lerp(-box[v], box[v], b);\n return point as unknown as Vec3;\n },\n };\n }\n }\n\n if (radius <= 0) return;\n\n // 12 edges: a quarter cylinder. The direction sweeps 90 degrees in the plane\n // of the two pinned axes while the core slides along the third.\n for (const axis of AXES) {\n const a = (axis + 1) % 3;\n const b = (axis + 2) % 3;\n for (const signA of SIGNS) {\n for (const signB of SIGNS) {\n yield {\n uSteps: arc,\n vSteps: segments[axis],\n normal: (t) => {\n const angle = (t * Math.PI) / 2;\n const dir: number[] = [0, 0, 0];\n dir[a] = signA * Math.cos(angle);\n dir[b] = signB * Math.sin(angle);\n return dir as unknown as Vec3;\n },\n position: (t, s) => {\n const angle = (t * Math.PI) / 2;\n const point: number[] = [0, 0, 0];\n point[a] = signA * (box[a] + radius * Math.cos(angle));\n point[b] = signB * (box[b] + radius * Math.sin(angle));\n point[axis] = lerp(-box[axis], box[axis], s);\n return point as unknown as Vec3;\n },\n };\n }\n }\n }\n\n // 8 corners: a spherical octant around a fixed corner of the inner box.\n for (const signX of SIGNS) {\n for (const signY of SIGNS) {\n for (const signZ of SIGNS) {\n const corner: Vec3 = [signX * box[0], signY * box[1], signZ * box[2]];\n const direction = (u: number, v: number): Vec3 => {\n const polar = (u * Math.PI) / 2;\n const azimuth = (v * Math.PI) / 2;\n return [\n signX * Math.sin(polar) * Math.cos(azimuth),\n signY * Math.cos(polar),\n signZ * Math.sin(polar) * Math.sin(azimuth),\n ];\n };\n yield {\n uSteps: arc,\n vSteps: arc,\n normal: direction,\n position: (u, v) => {\n const dir = direction(u, v);\n return [\n corner[0] + radius * dir[0],\n corner[1] + radius * dir[1],\n corner[2] + radius * dir[2],\n ];\n },\n };\n }\n }\n }\n}\n\n/**\n * Tessellate one patch into the output buffers.\n *\n * Winding is decided per triangle by comparing its own normal against the\n * surface normal at that vertex, rather than by reasoning about the sign\n * combination that produced the patch: 26 patches is 26 chances to get a\n * handedness backwards, and one inverted face on a `faces: \"front\"` mesh is a\n * hole you can see through. Degenerate triangles — the pole of a corner octant,\n * and every quad of a patch whose extent collapsed to zero — are dropped rather\n * than emitted with an undefined normal.\n */\nfunction emit(\n grid: Grid,\n half: Vec3,\n position: number[],\n normal: number[],\n uv: number[],\n index: number[],\n): void {\n const base = position.length / 3;\n const uCount = grid.uSteps + 1;\n const vCount = grid.vSteps + 1;\n\n for (let vi = 0; vi < vCount; vi++) {\n for (let ui = 0; ui < uCount; ui++) {\n const u = grid.uSteps === 0 ? 0 : ui / grid.uSteps;\n const v = grid.vSteps === 0 ? 0 : vi / grid.vSteps;\n const point = grid.position(u, v);\n const dir = grid.normal(u, v);\n position.push(point[0], point[1], point[2]);\n normal.push(dir[0], dir[1], dir[2]);\n const [s, t] = planarUv(point, dir, half);\n uv.push(s, t);\n }\n }\n\n for (let vi = 0; vi < grid.vSteps; vi++) {\n for (let ui = 0; ui < grid.uSteps; ui++) {\n const a = base + vi * uCount + ui;\n const b = a + 1;\n const c = a + uCount;\n const d = c + 1;\n pushTriangle(position, normal, index, a, c, b);\n pushTriangle(position, normal, index, b, c, d);\n }\n }\n}\n\n/** Emit one triangle, flipped if its winding faces away from the surface normal. */\nfunction pushTriangle(\n position: number[],\n normal: number[],\n index: number[],\n a: number,\n b: number,\n c: number,\n): void {\n const ax = position[a * 3], ay = position[a * 3 + 1], az = position[a * 3 + 2];\n const bx = position[b * 3], by = position[b * 3 + 1], bz = position[b * 3 + 2];\n const cx = position[c * 3], cy = position[c * 3 + 1], cz = position[c * 3 + 2];\n\n const ux = bx - ax, uy = by - ay, uz = bz - az;\n const vx = cx - ax, vy = cy - ay, vz = cz - az;\n\n const nx = uy * vz - uz * vy;\n const ny = uz * vx - ux * vz;\n const nz = ux * vy - uy * vx;\n\n // A collapsed quad — a pole, or a patch with no extent. No orientation to\n // decide and no area to shade.\n if (nx * nx + ny * ny + nz * nz < 1e-20) return;\n\n const facing = nx * normal[a * 3] + ny * normal[a * 3 + 1] + nz * normal[a * 3 + 2];\n\n if (facing >= 0) index.push(a, b, c);\n else index.push(a, c, b);\n}\n\n/**\n * A planar UV, projected along whichever axis the normal points most strongly\n * down.\n *\n * Deliberately approximate, and documented as such: the faces get an exact\n * box-projected UV, which is what a texture on a rounded box is almost always\n * for, and the arcs get a continuous projection that meets those faces without a\n * seam. An exact arc-length unwrap would need a per-patch atlas, which is a\n * texturing feature rather than a shape one.\n */\nfunction planarUv(point: Vec3, dir: Vec3, half: Vec3): [number, number] {\n const ax = Math.abs(dir[0]);\n const ay = Math.abs(dir[1]);\n const az = Math.abs(dir[2]);\n\n const axis = ax >= ay && ax >= az ? 0 : ay >= az ? 1 : 2;\n const u = (axis + 1) % 3;\n const v = (axis + 2) % 3;\n\n return [\n half[u] === 0 ? 0.5 : 0.5 + point[u] / (2 * half[u]),\n half[v] === 0 ? 0.5 : 0.5 + point[v] / (2 * half[v]),\n ];\n}\n\nfunction axisVector(axis: number, sign: number): Vec3 {\n const out: number[] = [0, 0, 0];\n out[axis] = sign;\n return out as unknown as Vec3;\n}\n\nfunction lerp(from: number, to: number, t: number): number {\n return from + (to - from) * t;\n}\n", "import type { Euler3, Quaternion, Vector3Input } from \"./vector3\";\n\n/**\n * Tuning for the shadow a *light* casts.\n *\n * Two knobs where three has seven: `mapSize`, `near`, `far`, `bias` and\n * `normalBias` are all derived by the renderer. `bias` in particular existed only\n * to fight shadow acne, its right value is a function of the scene's scale, and\n * `-0.0005` is not a number any author should be asked to discover.\n * {@link params} is applied straight onto the light's own `shadow` object for the\n * rare scene that needs to override one.\n */\nexport interface ShadowOptions3D {\n /** 0 hard-edged → 1 very soft. Default 0.5. */\n softness?: number;\n /**\n * Half-extent of a directional light's orthographic shadow frustum, in world\n * units. Sized to the scene's own bounds when omitted — too large and the\n * shadow is blocky, too small and it clips.\n */\n extent?: number;\n /** Escape hatch, assigned onto the renderer's shadow object. */\n params?: Record<string, unknown>;\n}\n\n/**\n * A node's relationship to shadows.\n *\n * One control rather than the two booleans three has, because for an *object*\n * \"casts\" and \"receives\" are almost never wanted apart, and defaulting both to\n * `false` (as three does) means a scene with shadows enabled and a light casting\n * them still renders nothing until every mesh is tagged. Here the default is\n * `true` and the viewport's own `shadows` switch is what decides — so turning\n * shadows on turns shadows on.\n *\n * For a *light* the same prop says whether it casts a shadow map, and the object\n * form carries that map's tuning. One name, because it is one question — \"what\n * does this node do about shadows\" — asked of two kinds of node.\n *\n * Note that every light casting by default is a real cost once shadows are on: a\n * point light needs a six-face cube map. Turn the fill lights off with\n * `shadow={false}` and leave the key light casting, which is what a lighting\n * setup does anyway.\n */\nexport type Shadow3D = boolean | \"cast\" | \"receive\" | ShadowOptions3D;\n\n/** True when this mode casts. */\nexport function shadowCasts(mode: Shadow3D | undefined): boolean {\n if (mode === undefined || mode === true) return true;\n if (mode === false) return false;\n return mode === \"cast\" || typeof mode === \"object\";\n}\n\n/** True when this mode receives. */\nexport function shadowReceives(mode: Shadow3D | undefined): boolean {\n if (mode === undefined || mode === true) return true;\n if (mode === false) return false;\n return mode === \"receive\" || typeof mode === \"object\";\n}\n\n/** A light's shadow tuning, or `null` when it casts none. */\nexport function resolveShadowOptions3D(mode: Shadow3D | undefined): ShadowOptions3D | null {\n if (!shadowCasts(mode)) return null;\n return typeof mode === \"object\" ? mode : {};\n}\n\n/**\n * Placement of a single 3D object. Every field is optional; an omitted field\n * means identity, so `{}` is a valid no-op transform.\n *\n * Rotation is in **degrees** — the engine's 2D `rotation` is degrees, so 3D\n * matches and authors never write `Math.PI`. The renderer converts.\n *\n * There is no `key` here. Reconciler identity is derived: a node stamps its own\n * id on the scope it opens, and a drawable is keyed by that id plus a content\n * signature, so a builder that emits ops conditionally reuses the right cache\n * entry without anything being written by hand. See the reconciler.\n */\nexport interface Transform3D {\n /** Position in the parent's local space. Default origin. */\n position?: Vector3Input;\n /**\n * Euler rotation in **degrees**, applied in `order` (default `\"XYZ\"`).\n * Ignored when {@link quaternion} is set.\n */\n rotation?: Vector3Input | Euler3;\n /**\n * Rotation as a unit quaternion. Wins over {@link rotation} — use it (with\n * `slerpQuaternion`) for tumbles where Euler interpolation would gimbal.\n */\n quaternion?: Quaternion;\n /** Per-axis scale; a scalar scales uniformly. Default 1. */\n scale?: Vector3Input;\n /**\n * World-space point to orient toward, applied after {@link position}.\n * Wins over both {@link rotation} and {@link quaternion}.\n */\n lookAt?: Vector3Input;\n /** Hide without removing (keeps the cached object alive). Default true. */\n visible?: boolean;\n /** Shadow participation. Default `true` — see {@link Shadow3D}. */\n shadow?: Shadow3D;\n /** Draw-order override, for tuning transparent sorting. */\n renderOrder?: number;\n /**\n * Node identity, stamped by the scene recorder rather than by an author.\n *\n * `Scene3D.begin` writes the recording node's id here so the renderer caches\n * a group against the node that opened it. Nothing an author writes goes in\n * this field.\n *\n * @internal\n */\n key?: string;\n}\n\n/** Which faces of a surface are rasterized. */\nexport type Faces3D = \"front\" | \"back\" | \"both\";\n\n/** How a drawn colour combines with what is already in the framebuffer. */\nexport type Blend3D = \"normal\" | \"additive\" | \"subtractive\" | \"multiply\" | \"none\";\n", "import type { PathData } from \"@/render/descriptors/path\";\nimport type { PathBuilder } from \"@/render/descriptors/path-builder\";\nimport { type Color, parseColor } from \"@/attributes/shape/fill/color/parser\";\nimport type { Vector3, Vector3Input } from \"./vector3\";\nimport type { Segments3D } from \"./segments\";\n\n/**\n * Anything not modelled by a named field, assigned straight onto the constructed\n * object. The documented last resort — unsafe by construction (it bypasses the\n * type system, and the renderer treats any change to it as a full rebuild since\n * it cannot know what a given key affects), but it means no author is ever\n * blocked waiting for a field to be modelled here.\n *\n * **Where it is applied**: materials, lights (and a light's `shadow`) and\n * cameras. **Where it is not**: geometries, the environment and post effects. A\n * `params` there is recorded and nothing reads it (probe: `box({ params: { name:\n * \"x\" } })` leaves the built geometry's `name` empty), and in development the\n * first one warns. Set a geometry's own fields instead.\n */\nexport interface Passthrough3D {\n params?: Record<string, unknown>;\n}\n\n/**\n * A partial revolution, shared by every shape that has one.\n *\n * `Ellipse` has said `startAngle` / `sweep` in degrees since the beginning, so 3D\n * says it too. It replaces three's five spellings of the same idea —\n * `thetaStart`, `thetaLength`, `phiStart`, `phiLength` and `arc` — which differ\n * per shape for reasons that are about three's own history rather than about\n * anything an author is trying to draw.\n */\nexport interface Sweep3D {\n /** Where the revolution begins, in **degrees**. Default 0. */\n startAngle?: number;\n /** How far it runs, in **degrees**. Default 360 (or 180 for a half sweep). */\n sweep?: number;\n}\n\n// ─── Primitives ──────────────────────────────────────────────────────────────\n\n/**\n * A box.\n *\n * `cornerRadius` is the same control `Rect` carries in 2D and rounds all twelve\n * edges; it is most of the difference between a scene that reads as designed and\n * one that reads as a renderer test. See `evaluateRoundedBox` for how the\n * surface is built.\n */\nexport interface BoxGeometry3D extends Passthrough3D {\n type: \"box\";\n width?: number;\n height?: number;\n depth?: number;\n /** Rounds every edge and corner. Clamped to the smallest half-extent. */\n cornerRadius?: number;\n /** Face subdivision, as `[x, y, z]`. Default 1. */\n segments?: Segments3D;\n}\n\n/** A sphere, or a wedge/band of one via {@link Sweep3D} and the latitude pair. */\nexport interface SphereGeometry3D extends Passthrough3D, Sweep3D {\n type: \"sphere\";\n radius?: number;\n /** `[longitude, latitude]`. Default `[32, 16]`. */\n segments?: Segments3D;\n /** Vertical band start, in **degrees** from the north pole. Default 0. */\n startLatitude?: number;\n /** Vertical band extent, in **degrees**. Default 180 (pole to pole). */\n latitudeSweep?: number;\n}\n\nexport interface PlaneGeometry3D extends Passthrough3D {\n type: \"plane\";\n width?: number;\n height?: number;\n /** `[width, height]`. Raise to subdivide for per-vertex displacement. */\n segments?: Segments3D;\n}\n\n/**\n * A cylinder, or any tapered tube.\n *\n * `radius` takes `[top, bottom]` for a taper, which is what `radiusTop` and\n * `radiusBottom` were — one field, and the pair reads as the thing it describes.\n */\nexport interface CylinderGeometry3D extends Passthrough3D, Sweep3D {\n type: \"cylinder\";\n /** A scalar, or `[top, bottom]` to taper. Default 1. */\n radius?: number | readonly [number, number];\n height?: number;\n /** `[radial, height]`. Default `[32, 1]`. */\n segments?: Segments3D;\n /** Draw the end caps. Default true. */\n capped?: boolean;\n}\n\nexport interface ConeGeometry3D extends Passthrough3D, Sweep3D {\n type: \"cone\";\n radius?: number;\n height?: number;\n /** `[radial, height]`. Default `[32, 1]`. */\n segments?: Segments3D;\n /** Draw the base cap. Default true. */\n capped?: boolean;\n}\n\nexport interface TorusGeometry3D extends Passthrough3D, Sweep3D {\n type: \"torus\";\n /** Distance from the centre to the middle of the ring. */\n radius?: number;\n /** Thickness of the ring itself. Default 0.4. */\n thickness?: number;\n /** `[radial, tubular]`. Default `[16, 48]`. */\n segments?: Segments3D;\n}\n\nexport interface TorusKnotGeometry3D extends Passthrough3D {\n type: \"torusKnot\";\n radius?: number;\n /** Thickness of the strand. Default 0.4. */\n thickness?: number;\n /** `[tubular, radial]`. Default `[64, 8]`. */\n segments?: Segments3D;\n /** Winding counts as `[around the axis, around the torus]`. Default `[2, 3]`. */\n windings?: readonly [number, number];\n}\n\nexport interface CircleGeometry3D extends Passthrough3D, Sweep3D {\n type: \"circle\";\n radius?: number;\n /** Default 32. */\n segments?: Segments3D;\n}\n\n/** A flat annulus — a disc with a hole. */\nexport interface RingGeometry3D extends Passthrough3D, Sweep3D {\n type: \"ring\";\n /** Outer radius. Default 1. */\n radius?: number;\n /** Inner radius — the size of the hole. Default 0.5. */\n innerRadius?: number;\n /** `[around, radial]`. Default `[32, 1]`. */\n segments?: Segments3D;\n}\n\nexport interface CapsuleGeometry3D extends Passthrough3D {\n type: \"capsule\";\n /** Default 0.5. */\n radius?: number;\n /** Length of the straight mid-section, excluding the caps. Default 1. */\n height?: number;\n /** `[radial, cap]`. Default `[16, 8]`. */\n segments?: Segments3D;\n}\n\nexport interface PolyhedronGeometry3D extends Passthrough3D {\n type: \"polyhedron\";\n shape: \"tetrahedron\" | \"octahedron\" | \"icosahedron\" | \"dodecahedron\";\n radius?: number;\n /** Subdivision. Raising this on an icosahedron approximates a sphere. */\n segments?: Segments3D;\n}\n\n// ─── Path-derived (reuses core's own 2D path vocabulary) ─────────────────────\n\n/** How an extrusion's edge is chamfered. A bare number is the bevel's size. */\nexport interface Bevel3D {\n size?: number;\n thickness?: number;\n offset?: number;\n segments?: number;\n}\n\n/**\n * A 2D outline swept into a solid. `path` accepts the same `PathData` (SVG\n * string or command list) or {@link PathBuilder} the 2D `Path` node takes — same\n * name, same value — so an existing 2D outline becomes an extruded solid with no\n * new vocabulary.\n */\nexport interface ExtrudeGeometry3D extends Passthrough3D {\n type: \"extrude\";\n path: PathData | PathBuilder;\n depth?: number;\n /** Curve flattening resolution. Default 12. */\n segments?: Segments3D;\n /** A number is the bevel size; an object tunes the rest. Omit for no bevel. */\n bevel?: number | Bevel3D;\n}\n\n/** A profile revolved about the Y axis — vases, bowls, turned shapes. */\nexport interface LatheGeometry3D extends Passthrough3D, Sweep3D {\n type: \"lathe\";\n /** Profile points in the XY plane; `x` is the radius, `y` the height. */\n points: readonly Vector3Input[];\n /** Default 12. */\n segments?: Segments3D;\n}\n\n/** A circular cross-section swept along a 3D curve. */\nexport interface TubeGeometry3D extends Passthrough3D {\n type: \"tube\";\n points: readonly Vector3Input[];\n radius?: number;\n /** `[along the curve, around it]`. Default `[64, 8]`. */\n segments?: Segments3D;\n closed?: boolean;\n}\n\n// ─── Arbitrary vertex data ───────────────────────────────────────────────────\n\n/**\n * Raw vertex buffers — the general escape hatch that makes *any* computable mesh\n * expressible without leaving pure data.\n *\n * `position` is required and holds `[x, y, z, x, y, z, …]`. `index` lets vertices\n * be shared between faces. Omit `normal` and set {@link computeNormals} to have\n * them derived.\n */\nexport interface BufferGeometry3D extends Passthrough3D {\n type: \"buffer\";\n /** Flat `xyz` triples. */\n position: ArrayLike<number>;\n /** Flat `xyz` triples. Omit and set {@link computeNormals} to derive them. */\n normal?: ArrayLike<number>;\n /** Flat `uv` pairs. */\n uv?: ArrayLike<number>;\n /** Flat linear `rgb` triples. Needs `vertexColors: true` on the material. */\n color?: ArrayLike<number>;\n /** Triangle indices into the arrays above. */\n index?: ArrayLike<number>;\n /** Derive vertex normals after upload — needed for correct lighting. */\n computeNormals?: boolean;\n /**\n * Bump after mutating an array **in place** to force a re-upload.\n *\n * Reusing one `Float32Array` across frames and writing into it is the fast\n * way to animate a mesh, but it defeats identity comparison — the renderer\n * sees the same array object and cannot tell the contents changed. Bumping\n * `revision` tells it explicitly.\n *\n * With `revision` omitted the renderer re-uploads every frame, which is\n * correct-by-default for a buffer you built deliberately. Set\n * {@link staticData} once the data stops changing.\n */\n revision?: number;\n /**\n * Declare the arrays immutable, so the renderer compares by identity alone\n * and skips the per-frame re-upload. Only safe when you never mutate in place.\n */\n staticData?: boolean;\n}\n\n/** One evaluated vertex of a {@link ParametricGeometry3D} surface. */\nexport type ParametricVertex3D = Vector3 | readonly [number, number, number];\n\n/**\n * A surface sampled over a `[0,1] × [0,1]` grid — the ergonomic form of\n * {@link BufferGeometry3D} for procedural meshes (waves, terrain, ribbons).\n *\n * Core evaluates the callbacks into vertex buffers at record time, so the\n * descriptor handed to the renderer is still plain data. Re-evaluated every\n * frame, so read the node's props and the frame time inside `vertex`.\n *\n * Geo.parametric({\n * segments: [70, 70],\n * vertex: (u, v) => ({ x: (u - 0.5) * 20, y: wave(u, v, t), z: (v - 0.5) * 20 }),\n * computeNormals: true,\n * })\n */\nexport interface ParametricGeometry3D extends Passthrough3D {\n type: \"parametric\";\n /** Grid resolution as `[u, v]`, or one number for both. */\n segments: Segments3D;\n /** Position for grid coordinate `(u, v)`, both in `[0, 1]`. */\n vertex: (u: number, v: number) => ParametricVertex3D;\n /** Optional per-vertex colour. Needs `vertexColors: true` on the material. */\n color?: (u: number, v: number, position: Vector3) => Color;\n /** Derive vertex normals. Almost always wanted for a lit surface. */\n computeNormals?: boolean;\n /**\n * A value that changes exactly when {@link vertex} would return something\n * different — supply it and the surface is re-evaluated only when it moves.\n *\n * Omitted (the default) the surface is re-evaluated **every frame**, which is\n * what makes the `read the node's props and the frame time inside vertex` contract\n * above work without any bookkeeping. It is also expensive: `segments: 80` is\n * ~6.6k calls to `vertex`, plus normals and a full buffer re-upload, and a\n * frame draws for any reason at all — an unrelated node being dragged, the\n * camera orbiting, a tween elsewhere in the scene. A surface whose shape did\n * not change pays all of that for an identical result.\n *\n * `vertex` is a closure, so the renderer cannot inspect what it captured;\n * only the author knows. Derive this from exactly those captures — the\n * domain, the amplitude, the identity of the function being plotted — and\n * leave it out for a surface that genuinely varies with time.\n *\n * Same name and same role as {@link BufferGeometry3D.revision}: the explicit\n * \"this is what changed\" marker. `segments` needs no help here, being plain\n * data the renderer already compares.\n */\n revision?: number;\n}\n\n// ─── Derived ─────────────────────────────────────────────────────────────────\n\n/**\n * The hard edges of another geometry, as line segments — a clean wireframe\n * outline without the diagonals of a triangulated one. Draw it with\n * `Graphics3D.line({ segments: true })`.\n */\nexport interface EdgesGeometry3D extends Passthrough3D {\n type: \"edges\";\n source: Geometry3D;\n /** Minimum dihedral angle in **degrees** for an edge to count. Default 1. */\n thresholdAngle?: number;\n}\n\n/** Every triangle edge of another geometry, as line segments. */\nexport interface WireframeGeometry3D extends Passthrough3D {\n type: \"wireframe\";\n source: Geometry3D;\n}\n\n/** Geometry taken from a loaded model file, by node name. */\nexport interface ModelGeometry3D extends Passthrough3D {\n type: \"modelGeometry\";\n src: string;\n /** Which node of the model to take. Defaults to the first mesh found. */\n node?: string;\n}\n\n/** Normalize {@link CylinderGeometry3D.radius} to its `[top, bottom]` pair. */\nexport function cylinderRadii(\n radius: number | readonly [number, number] | undefined,\n): [number, number] {\n if (radius === undefined) return [1, 1];\n if (typeof radius === \"number\") return [radius, radius];\n return [radius[0] ?? 1, radius[1] ?? radius[0] ?? 1];\n}\n\n/** Normalize {@link ExtrudeGeometry3D.bevel} to its full option set, or `null`. */\nexport function resolveBevel3D(bevel: number | Bevel3D | undefined): Required<Bevel3D> | null {\n if (bevel === undefined) return null;\n const options = typeof bevel === \"number\" ? { size: bevel } : bevel;\n const size = options.size ?? 0.1;\n return {\n size,\n // Scaled off `size` rather than defaulted independently, so the one-number\n // form produces a bevel with sane proportions instead of a sliver.\n thickness: options.thickness ?? size * 2,\n offset: options.offset ?? 0,\n segments: options.segments ?? 3,\n };\n}\n\n/**\n * Evaluate a {@link ParametricGeometry3D} into concrete vertex buffers.\n *\n * Lives in core rather than the renderer so the grid/winding maths is\n * backend-agnostic and unit-testable without a GPU. Called by the renderer at\n * draw time (not at record time) so the cost is only paid when the frame is\n * actually rasterized, and never during the asset-tracking replay.\n *\n * The grid is `(segments + 1)²` vertices wound counter-clockwise, so front faces\n * point along +Y for a surface authored in the XZ plane.\n */\nexport function evaluateParametric(geometry: ParametricGeometry3D): BufferGeometry3D {\n const resolved = geometry.segments;\n const [uSegments, vSegments] = typeof resolved === \"number\"\n ? [resolved, resolved]\n : [resolved[0] ?? 1, resolved[1] ?? resolved[0] ?? 1];\n\n const uCount = Math.max(1, Math.floor(uSegments)) + 1;\n const vCount = Math.max(1, Math.floor(vSegments)) + 1;\n\n const position = new Float32Array(uCount * vCount * 3);\n const uv = new Float32Array(uCount * vCount * 2);\n const color = geometry.color ? new Float32Array(uCount * vCount * 3) : undefined;\n\n const scratch: Vector3 = { x: 0, y: 0, z: 0 };\n\n for (let vi = 0; vi < vCount; vi++) {\n const v = vi / (vCount - 1);\n for (let ui = 0; ui < uCount; ui++) {\n const u = ui / (uCount - 1);\n const index = vi * uCount + ui;\n\n const vertex = geometry.vertex(u, v);\n if (Array.isArray(vertex)) {\n scratch.x = vertex[0]; scratch.y = vertex[1]; scratch.z = vertex[2];\n } else {\n const p = vertex as Vector3;\n scratch.x = p.x; scratch.y = p.y; scratch.z = p.z;\n }\n\n position[index * 3] = scratch.x;\n position[index * 3 + 1] = scratch.y;\n position[index * 3 + 2] = scratch.z;\n\n uv[index * 2] = u;\n uv[index * 2 + 1] = v;\n\n if (color && geometry.color) {\n const rgba = resolveLinearRgb(geometry.color(u, v, scratch));\n color[index * 3] = rgba[0];\n color[index * 3 + 1] = rgba[1];\n color[index * 3 + 2] = rgba[2];\n }\n }\n }\n\n // Two triangles per cell. Uint32 because a 256² grid already exceeds Uint16.\n const index = new Uint32Array((uCount - 1) * (vCount - 1) * 6);\n let cursor = 0;\n for (let vi = 0; vi < vCount - 1; vi++) {\n for (let ui = 0; ui < uCount - 1; ui++) {\n const a = vi * uCount + ui;\n const b = a + 1;\n const c = a + uCount;\n const d = c + 1;\n index[cursor++] = a; index[cursor++] = c; index[cursor++] = b;\n index[cursor++] = b; index[cursor++] = c; index[cursor++] = d;\n }\n }\n\n return {\n type: \"buffer\",\n position,\n uv,\n color,\n index,\n computeNormals: geometry.computeNormals,\n params: geometry.params,\n };\n}\n\n/**\n * A {@link Color} as **linear-light** RGB, which is what a vertex-colour buffer\n * must hold: a renderer samples that attribute directly into its linear working\n * space, with no decode step of its own.\n *\n * `parseColor` returns gamma-encoded sRGB (hex is `byte / 255`), so the sRGB\n * transfer function has to be inverted here. Skipping this renders vertex-coloured\n * surfaces visibly washed out.\n */\nfunction resolveLinearRgb(color: Color): readonly [number, number, number] {\n const [r, g, b] = typeof color === \"string\" ? parseColor(color) : color;\n return [srgbToLinear(r), srgbToLinear(g), srgbToLinear(b)];\n}\n\n/** Inverse sRGB transfer function (IEC 61966-2-1), per channel. */\nfunction srgbToLinear(channel: number): number {\n return channel <= 0.04045\n ? channel / 12.92\n : Math.pow((channel + 0.055) / 1.055, 2.4);\n}\n\n/**\n * Every geometry a mesh can be built from. Discriminated on `type`, so new\n * shapes are additive.\n */\nexport type Geometry3D =\n | BoxGeometry3D\n | SphereGeometry3D\n | PlaneGeometry3D\n | CylinderGeometry3D\n | ConeGeometry3D\n | TorusGeometry3D\n | TorusKnotGeometry3D\n | CircleGeometry3D\n | RingGeometry3D\n | CapsuleGeometry3D\n | PolyhedronGeometry3D\n | ExtrudeGeometry3D\n | LatheGeometry3D\n | TubeGeometry3D\n | BufferGeometry3D\n | ParametricGeometry3D\n | EdgesGeometry3D\n | WireframeGeometry3D\n | ModelGeometry3D;\n", "import { quaternionFromEuler, resolveVector3, type Euler3, type Quaternion, type Vector3, type Vector3Input } from \"./vector3\";\nimport type { Transform3D } from \"./transform\";\n\n/**\n * 4×4 matrix maths, in **column-major order** — the same layout three uses, so a\n * matrix built here and one read off a `THREE.Object3D` are the same sixteen\n * numbers in the same slots.\n *\n * ```\n * | m0 m4 m8 m12 |\n * | m1 m5 m9 m13 |\n * | m2 m6 m10 m14 |\n * | m3 m7 m11 m15 |\n * ```\n *\n * This exists for one caller — {@link projectNode3D}, the walk that says where a\n * 3D node's pixels landed — and it is deliberately the *whole* of the maths that\n * walk needs rather than a general linear-algebra library. Every function here\n * mirrors a specific three behaviour it has to agree with (`Object3D.lookAt`'s\n * two orientations, `PerspectiveCamera.updateProjectionMatrix`'s zoom, the\n * frustum an `OrthographicCamera` derives from `frustumHeight`); where the two\n * could drift the docblock says which three method is being matched, because a\n * selection box that disagrees with the render by a few pixels is worse than one\n * that isn't drawn.\n *\n * Kept in `render3d` beside the descriptors rather than in a `math` directory\n * for the reason the rest of this folder gives: nothing here imports a renderer,\n * so `three` stays inside `@motionscript/browser`.\n */\n\n/** A 4×4 matrix as sixteen numbers, column-major. See the module note. */\n/** @internal */\nexport type Matrix4 = readonly number[];\n\n/** A homogeneous point — what {@link applyMatrix4} returns before the divide. */\n/** @internal */\nexport interface Vector4 extends Vector3 {\n w: number;\n}\n\n/** @internal The identity matrix. */\nexport function identity4(): Matrix4 {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n}\n\n/**\n * `a · b` — the transform that applies `b` first, then `a`. Composing a parent\n * with a child (`parent.multiply(child)`) yields the child's world transform,\n * the same convention {@link import(\"@/attributes/layout/matrix2d\").multiply}\n * uses one dimension down.\n */\n/** @internal */\nexport function multiply4(a: Matrix4, b: Matrix4): Matrix4 {\n const out = new Array<number>(16);\n for (let col = 0; col < 4; col++) {\n const b0 = b[col * 4], b1 = b[col * 4 + 1], b2 = b[col * 4 + 2], b3 = b[col * 4 + 3];\n out[col * 4] = a[0] * b0 + a[4] * b1 + a[8] * b2 + a[12] * b3;\n out[col * 4 + 1] = a[1] * b0 + a[5] * b1 + a[9] * b2 + a[13] * b3;\n out[col * 4 + 2] = a[2] * b0 + a[6] * b1 + a[10] * b2 + a[14] * b3;\n out[col * 4 + 3] = a[3] * b0 + a[7] * b1 + a[11] * b2 + a[15] * b3;\n }\n return out;\n}\n\n/**\n * The inverse, or `null` when `m` is singular — which a zero scale on any axis\n * makes it. A camera whose matrix cannot be inverted has no view, so the caller\n * draws no boxes rather than dividing by zero into `NaN`.\n */\n/** @internal */\nexport function invert4(m: Matrix4): Matrix4 | null {\n const [\n n11, n21, n31, n41,\n n12, n22, n32, n42,\n n13, n23, n33, n43,\n n14, n24, n34, n44,\n ] = m;\n\n const t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;\n const t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;\n const t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;\n const t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;\n\n const determinant = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;\n if (determinant === 0) return null;\n const d = 1 / determinant;\n\n return [\n t11 * d,\n (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * d,\n (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * d,\n (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * d,\n\n t12 * d,\n (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * d,\n (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * d,\n (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * d,\n\n t13 * d,\n (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * d,\n (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * d,\n (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * d,\n\n t14 * d,\n (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * d,\n (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * d,\n (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * d,\n ];\n}\n\n/** @internal Map a point through `m`, keeping `w` — the caller does the divide. */\nexport function applyMatrix4(m: Matrix4, p: Vector3): Vector4 {\n const { x, y, z } = p;\n return {\n x: m[0] * x + m[4] * y + m[8] * z + m[12],\n y: m[1] * x + m[5] * y + m[9] * z + m[13],\n z: m[2] * x + m[6] * y + m[10] * z + m[14],\n w: m[3] * x + m[7] * y + m[11] * z + m[15],\n };\n}\n\n/** @internal Translation, rotation and scale composed into one matrix. */\nexport function compose4(position: Vector3, rotation: Quaternion, scale: Vector3): Matrix4 {\n const { x, y, z, w } = rotation;\n const x2 = x + x, y2 = y + y, z2 = z + z;\n const xx = x * x2, xy = x * y2, xz = x * z2;\n const yy = y * y2, yz = y * z2, zz = z * z2;\n const wx = w * x2, wy = w * y2, wz = w * z2;\n\n return [\n (1 - (yy + zz)) * scale.x, (xy + wz) * scale.x, (xz - wy) * scale.x, 0,\n (xy - wz) * scale.y, (1 - (xx + zz)) * scale.y, (yz + wx) * scale.y, 0,\n (xz + wy) * scale.z, (yz - wx) * scale.z, (1 - (xx + yy)) * scale.z, 0,\n position.x, position.y, position.z, 1,\n ];\n}\n\n/**\n * The rotation that aims `eye`'s **−Z** at `target`, as three's\n * `Matrix4.lookAt(eye, target, up)` builds it.\n *\n * Callers reproduce `Object3D.lookAt`'s two cases by choosing which way round\n * they pass the pair: a camera (and a light) aims its −Z, so it passes\n * `(position, target)`; everything else aims its **+Z**, which is the same\n * function called `(target, position)`. That asymmetry is three's, not ours —\n * see `applyTransform` in the renderer, which calls `Object3D.lookAt` and\n * inherits it.\n *\n * A degenerate pair — eye on target, or an up vector parallel to the view — has\n * no defined orientation; three nudges `z` by `1e-4` in that case and so does\n * this, so the two agree rather than one of them producing `NaN`.\n */\n/** @internal */\nexport function lookAtRotation4(eye: Vector3, target: Vector3, up: Vector3 = UP): Matrix4 {\n let zx = eye.x - target.x, zy = eye.y - target.y, zz = eye.z - target.z;\n let length = Math.hypot(zx, zy, zz);\n if (length === 0) {\n zz = 1;\n length = 1;\n }\n zx /= length; zy /= length; zz /= length;\n\n let xx = up.y * zz - up.z * zy;\n let xy = up.z * zx - up.x * zz;\n let xz = up.x * zy - up.y * zx;\n let xLength = Math.hypot(xx, xy, xz);\n if (xLength === 0) {\n // up is parallel to the view direction — three's own nudge, so the two\n // pick the same arbitrary roll rather than disagreeing about it.\n if (Math.abs(up.z) === 1) zx += 1e-4;\n else zz += 1e-4;\n length = Math.hypot(zx, zy, zz);\n zx /= length; zy /= length; zz /= length;\n xx = up.y * zz - up.z * zy;\n xy = up.z * zx - up.x * zz;\n xz = up.x * zy - up.y * zx;\n xLength = Math.hypot(xx, xy, xz);\n }\n xx /= xLength; xy /= xLength; xz /= xLength;\n\n const yx = zy * xz - zz * xy;\n const yy = zz * xx - zx * xz;\n const yz = zx * xy - zy * xx;\n\n return [xx, xy, xz, 0, yx, yy, yz, 0, zx, zy, zz, 0, 0, 0, 0, 1];\n}\n\n/** three's default up vector, which nothing in the descriptors overrides yet. */\nconst UP: Vector3 = { x: 0, y: 1, z: 0 };\n\n/**\n * A {@link Transform3D} as a matrix, in the parent's space.\n *\n * The precedence is the renderer's — `lookAt` > `quaternion` > `rotation`, each\n * a complete statement about orientation rather than something to combine — and\n * `lookAt` is resolved against `parentWorld` for the same reason `Object3D.lookAt`\n * is: it names a point in **world** space, so a node inside a rotated group has\n * to undo that rotation to end up pointing at it. Pass `null` for a transform at\n * the scene root, where there is nothing to undo.\n */\n/** @internal */\nexport function transformMatrix4(transform: Transform3D | undefined, parentWorld: Matrix4 | null): Matrix4 {\n if (!transform) return identity4();\n\n const position = resolveVector3(transform.position);\n const scale = resolveVector3(transform.scale === undefined ? 1 : transform.scale);\n\n if (transform.lookAt !== undefined) {\n const target = resolveVector3(transform.lookAt);\n // Where this node sits in world space — `lookAt` is measured from there,\n // not from its local origin.\n const world = parentWorld\n ? applyMatrix4(parentWorld, position)\n : { ...position, w: 1 };\n const origin = { x: world.x, y: world.y, z: world.z };\n // +Z at the target: the non-camera branch of `Object3D.lookAt`. Cameras\n // never come through here — see `cameraMatrix4`.\n let rotation = lookAtRotation4(target, origin);\n if (parentWorld) {\n const inverseParent = invert4(rotationOf4(parentWorld));\n if (inverseParent) rotation = multiply4(inverseParent, rotation);\n }\n // T · R · S, the same order {@link compose4} produces — spelled out here\n // because the rotation arrived as a matrix rather than as a quaternion.\n return multiply4(multiply4(translation4(position), rotation), scale4(scale));\n }\n\n const quaternion = transform.quaternion ?? quaternionFromEuler(eulerOf(transform.rotation));\n return compose4(position, quaternion, scale);\n}\n\n/** A `Vector3Input | Euler3` as an {@link Euler3}, defaulting to no rotation. */\nfunction eulerOf(rotation: Vector3Input | Euler3 | undefined): Euler3 {\n const angles = resolveVector3(rotation as Vector3Input | undefined);\n return { ...angles, order: (rotation as Euler3 | undefined)?.order };\n}\n\n/** @internal Pure translation. */\nexport function translation4(position: Vector3): Matrix4 {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, position.x, position.y, position.z, 1];\n}\n\n/** Pure per-axis scale. */\nfunction scale4(scale: Vector3): Matrix4 {\n return [scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1];\n}\n\n/**\n * `m`'s rotation with its translation and scale divided out — three's\n * `Matrix4.extractRotation`. Used to undo a parent's orientation when resolving\n * a `lookAt`; a zero-length basis vector leaves that column as identity rather\n * than dividing by zero.\n */\n/** @internal */\nexport function rotationOf4(m: Matrix4): Matrix4 {\n const sx = Math.hypot(m[0], m[1], m[2]) || 1;\n const sy = Math.hypot(m[4], m[5], m[6]) || 1;\n const sz = Math.hypot(m[8], m[9], m[10]) || 1;\n return [\n m[0] / sx, m[1] / sx, m[2] / sx, 0,\n m[4] / sy, m[5] / sy, m[6] / sy, 0,\n m[8] / sz, m[9] / sz, m[10] / sz, 0,\n 0, 0, 0, 1,\n ];\n}\n\n/**\n * A perspective projection, matching `PerspectiveCamera.updateProjectionMatrix`\n * — including `zoom`, which three applies by *narrowing the frustum* rather than\n * by scaling the result, so it has to be folded in here rather than afterwards.\n */\n/** @internal */\nexport function perspective4(fov: number, aspect: number, near: number, far: number, zoom: number): Matrix4 {\n const top = near * Math.tan((fov * Math.PI) / 360) / zoom;\n const height = 2 * top;\n const width = aspect * height;\n const left = -0.5 * width;\n return frustum4(left, left + width, top, top - height, near, far);\n}\n\n/** three's `Matrix4.makePerspective`, with its reversed-`bottom` convention. */\nfunction frustum4(left: number, right: number, top: number, bottom: number, near: number, far: number): Matrix4 {\n const x = (2 * near) / (right - left);\n const y = (2 * near) / (top - bottom);\n const a = (right + left) / (right - left);\n const b = (top + bottom) / (top - bottom);\n const c = -(far + near) / (far - near);\n const d = (-2 * far * near) / (far - near);\n return [x, 0, 0, 0, 0, y, 0, 0, a, b, c, -1, 0, 0, d, 0];\n}\n\n/**\n * An orthographic projection, matching\n * `OrthographicCamera.updateProjectionMatrix` — where `zoom` widens the frustum\n * about its centre rather than scaling the projected result.\n */\n/** @internal */\nexport function orthographic4(left: number, right: number, top: number, bottom: number, near: number, far: number, zoom: number): Matrix4 {\n const dx = (right - left) / (2 * zoom);\n const dy = (top - bottom) / (2 * zoom);\n const cx = (right + left) / 2;\n const cy = (top + bottom) / 2;\n\n const l = cx - dx, r = cx + dx, t = cy + dy, b = cy - dy;\n const w = 1 / (r - l);\n const h = 1 / (t - b);\n const p = 1 / (far - near);\n return [\n 2 * w, 0, 0, 0,\n 0, 2 * h, 0, 0,\n 0, 0, -2 * p, 0,\n -(r + l) * w, -(t + b) * h, -(far + near) * p, 1,\n ];\n}\n", "import { cylinderRadii, type Geometry3D } from \"./geometry\";\nimport { applyMatrix4, type Matrix4 } from \"./matrix4\";\nimport { resolveVector3, type Vector3 } from \"./vector3\";\n\n/**\n * Axis-aligned bounds for the 3D descriptors — the \"how big is it, and where\" an\n * editor needs in order to put a box round a mesh it did not build.\n *\n * **Analytic, not sampled.** Every primitive's extent falls straight out of its\n * parameters, so this is a table of formulas rather than a walk over vertices,\n * and it costs nothing to ask per pointer move. The defaults each one falls back\n * to are *three's* defaults, not invented here, because a descriptor that omits\n * `radius` renders at three's 1 and a box drawn round a different number would\n * be a box in the wrong place — see the note on each.\n *\n * **Conservative where it is not exact.** A partial sweep (`thetaLength` on a\n * sphere, `arc` on a torus) is bounded by the full figure rather than by the\n * wedge actually drawn: the exact answer is an arc-endpoint problem per shape\n * per axis, and the cost of getting it wrong is a selection box that *cuts\n * through* the mesh, where the cost of over-reporting is one that sits a little\n * loose. Over-reporting is the safe direction, and it is the direction taken\n * everywhere here.\n *\n * **`null` means \"no answer\", not \"empty\".** Three descriptors genuinely cannot\n * be measured without something this package does not have: a loaded model file,\n * a rasterized path, or a user callback that may read the frame clock. A caller\n * that gets `null` draws no box, which is the honest outcome — a wrong box is\n * worse than none.\n */\n\n/** An axis-aligned box. `min` is corner-wise minimum, not a point on the mesh. */\nexport interface Box3 {\n min: Vector3;\n max: Vector3;\n}\n\n/** @internal A box centred on the origin with the given half-extents. */\nexport function centeredBox3(hx: number, hy: number, hz: number): Box3 {\n return { min: { x: -hx, y: -hy, z: -hz }, max: { x: hx, y: hy, z: hz } };\n}\n\n/** @internal The union of two boxes; either may be `null`. */\nexport function unionBox3(a: Box3 | null, b: Box3 | null): Box3 | null {\n if (!a) return b;\n if (!b) return a;\n return {\n min: { x: Math.min(a.min.x, b.min.x), y: Math.min(a.min.y, b.min.y), z: Math.min(a.min.z, b.min.z) },\n max: { x: Math.max(a.max.x, b.max.x), y: Math.max(a.max.y, b.max.y), z: Math.max(a.max.z, b.max.z) },\n };\n}\n\n/** @internal The box's eight corners, in no particular order. */\nexport function corners3(box: Box3): Vector3[] {\n const { min, max } = box;\n return [\n { x: min.x, y: min.y, z: min.z },\n { x: max.x, y: min.y, z: min.z },\n { x: min.x, y: max.y, z: min.z },\n { x: max.x, y: max.y, z: min.z },\n { x: min.x, y: min.y, z: max.z },\n { x: max.x, y: min.y, z: max.z },\n { x: min.x, y: max.y, z: max.z },\n { x: max.x, y: max.y, z: max.z },\n ];\n}\n\n/**\n * `box` mapped through `m` and re-bounded — the AABB of the transformed AABB.\n *\n * Not the AABB of the transformed *mesh*: a rotated box's corner-bounds are\n * larger than the shape inside them. That slack is the price of not carrying\n * vertex data around, and it errs in the safe direction (see the module note).\n */\n/** @internal */\nexport function transformBox3(box: Box3, m: Matrix4): Box3 {\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n for (const corner of corners3(box)) {\n const p = applyMatrix4(m, corner);\n if (p.x < minX) minX = p.x;\n if (p.y < minY) minY = p.y;\n if (p.z < minZ) minZ = p.z;\n if (p.x > maxX) maxX = p.x;\n if (p.y > maxY) maxY = p.y;\n if (p.z > maxZ) maxZ = p.z;\n }\n return { min: { x: minX, y: minY, z: minZ }, max: { x: maxX, y: maxY, z: maxZ } };\n}\n\n/**\n * The local-space bounds of a geometry descriptor, or `null` when it cannot be\n * measured from the descriptor alone. See the module note for both halves of\n * that sentence.\n */\nexport function geometryBounds3D(geometry: Geometry3D | undefined): Box3 | null {\n if (!geometry) return null;\n\n switch (geometry.type) {\n // three centres a box on its origin; the defaults are 1 on every axis.\n case \"box\":\n return centeredBox3(\n (geometry.width ?? 1) / 2,\n (geometry.height ?? 1) / 2,\n (geometry.depth ?? 1) / 2,\n );\n\n // Full sphere even for a wedge — see the module note on partial sweeps.\n case \"sphere\":\n return centeredBox3(geometry.radius ?? 1, geometry.radius ?? 1, geometry.radius ?? 1);\n\n // Flat in XY, facing +Z. Zero depth is correct rather than degenerate:\n // the projected box of a plane seen edge-on genuinely is a line.\n case \"plane\":\n return centeredBox3((geometry.width ?? 1) / 2, (geometry.height ?? 1) / 2, 0);\n\n // A cone is a cylinder with one radius zeroed, and three models it as its\n // own type — so the two share nothing here but the shape of the answer.\n case \"cylinder\": {\n const [top, bottom] = cylinderRadii(geometry.radius);\n const radius = Math.max(top, bottom);\n return centeredBox3(radius, (geometry.height ?? 1) / 2, radius);\n }\n case \"cone\": {\n const radius = geometry.radius ?? 1;\n return centeredBox3(radius, (geometry.height ?? 1) / 2, radius);\n }\n\n // The ring lies in XY and the tube swells it in Z by its own radius.\n case \"torus\": {\n const radius = geometry.radius ?? 1;\n const tube = geometry.thickness ?? 0.4;\n return centeredBox3(radius + tube, radius + tube, tube);\n }\n\n // three's knot curve is `radius * (2 + cos(qu/p)) / 2` in XY and\n // `radius * sin(qu/p) / 2` in Z, so it reaches 1.5·radius across and\n // 0.5·radius deep before the tube is added.\n case \"torusKnot\": {\n const radius = geometry.radius ?? 1;\n const tube = geometry.thickness ?? 0.4;\n return centeredBox3(radius * 1.5 + tube, radius * 1.5 + tube, radius * 0.5 + tube);\n }\n\n case \"circle\":\n return centeredBox3(geometry.radius ?? 1, geometry.radius ?? 1, 0);\n\n case \"ring\": {\n const outer = geometry.radius ?? 1;\n return centeredBox3(outer, outer, 0);\n }\n\n // `height` is the straight mid-section only, so the caps add a radius at\n // each end — the one place three's naming would mislead a reader here. Its\n // default radius is 0.5, not three's 1: the renderer builds core's default,\n // so a box drawn round three's would be twice too wide.\n case \"capsule\": {\n const radius = geometry.radius ?? 0.5;\n return centeredBox3(radius, (geometry.height ?? 1) / 2 + radius, radius);\n }\n\n // Every platonic solid is inscribed in its radius, so the sphere bounds\n // it — loosely for a tetrahedron, exactly for a subdivided icosahedron.\n case \"polyhedron\": {\n const radius = geometry.radius ?? 1;\n return centeredBox3(radius, radius, radius);\n }\n\n // A profile revolved about Y: the widest |x| becomes the radius in both\n // ground axes, and the profile's own y range carries straight over.\n case \"lathe\": {\n let radius = 0;\n let minY = Infinity;\n let maxY = -Infinity;\n for (const point of geometry.points) {\n const p = resolveVector3(point);\n radius = Math.max(radius, Math.abs(p.x));\n minY = Math.min(minY, p.y);\n maxY = Math.max(maxY, p.y);\n }\n if (!Number.isFinite(minY)) return null;\n return { min: { x: -radius, y: minY, z: -radius }, max: { x: radius, y: maxY, z: radius } };\n }\n\n // The path's own extent, swollen by the tube radius on every axis. The\n // curve bulges outside its control points, so this is a lower bound made\n // safe by the radius rather than an exact one.\n case \"tube\": {\n const points = geometry.points.map((point) => resolveVector3(point));\n const box = pointsBounds3(points);\n if (!box) return null;\n return expandBox3(box, geometry.radius ?? 1);\n }\n\n // Raw vertex data — the one case that is a walk, because there is nothing\n // else to read it off.\n case \"buffer\":\n return positionBounds3(geometry.position);\n\n // A derived geometry has its source's extent: an outline of a shape is\n // the same size as the shape.\n case \"edges\":\n case \"wireframe\":\n return geometryBounds3D(geometry.source);\n\n // Three that need what this package hasn't got: a rasterized 2D path, a\n // callback that may read the clock, and a file off the network.\n case \"extrude\":\n case \"parametric\":\n case \"modelGeometry\":\n default:\n return null;\n }\n}\n\n/** Bounds of a point list, or `null` when it is empty. */\nfunction pointsBounds3(points: readonly Vector3[]): Box3 | null {\n if (points.length === 0) return null;\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n for (const p of points) {\n if (p.x < minX) minX = p.x;\n if (p.y < minY) minY = p.y;\n if (p.z < minZ) minZ = p.z;\n if (p.x > maxX) maxX = p.x;\n if (p.y > maxY) maxY = p.y;\n if (p.z > maxZ) maxZ = p.z;\n }\n return { min: { x: minX, y: minY, z: minZ }, max: { x: maxX, y: maxY, z: maxZ } };\n}\n\n/** Bounds of a flat `[x, y, z, …]` position buffer. */\nfunction positionBounds3(position: ArrayLike<number>): Box3 | null {\n if (position.length < 3) return null;\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n for (let i = 0; i + 2 < position.length; i += 3) {\n const x = position[i], y = position[i + 1], z = position[i + 2];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (z < minZ) minZ = z;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n if (z > maxZ) maxZ = z;\n }\n return { min: { x: minX, y: minY, z: minZ }, max: { x: maxX, y: maxY, z: maxZ } };\n}\n\n/** `box` grown by `by` on every axis. */\nfunction expandBox3(box: Box3, by: number): Box3 {\n return {\n min: { x: box.min.x - by, y: box.min.y - by, z: box.min.z - by },\n max: { x: box.max.x + by, y: box.max.y + by, z: box.max.z + by },\n };\n}\n", "import type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { Vector3 } from \"./vector3\";\nimport type { Passthrough3D } from \"./geometry\";\nimport type { Blend3D, Faces3D } from \"./transform\";\nimport type { Texture3D } from \"./texture\";\n\n/** Facet or smooth shading. `\"flat\"` gives one normal per triangle. */\nexport type Shading3D = \"smooth\" | \"flat\";\n\n/**\n * State every material shares, regardless of shading model.\n *\n * A note on cost, because it is not obvious: the fields in the first block are\n * plain uniform writes the renderer can mutate in place every frame, so they are\n * free to animate. The fields marked **structural** change the compiled shader\n * program, so changing one mid-timeline forces a recompile — set them once and\n * leave them alone rather than tweening them.\n */\nexport interface MaterialCommon3D extends Passthrough3D {\n /** 0–1. Free to animate; blending is turned on for you below 1. */\n opacity?: number;\n /** Hide without removing. Free to animate. */\n visible?: boolean;\n\n /**\n * **Structural, and normally derived rather than written.**\n *\n * The renderer turns alpha blending on whenever anything about the material\n * actually needs it — `opacity` below 1, a colour carrying alpha, an\n * `alphaMap`, or transmission — so an author never has to pair a fade with a\n * second flag, and `opacity: 0.5` can no longer silently do nothing (which is\n * exactly what it did when this defaulted to `false`).\n *\n * Set it explicitly only to *force* blending on a fully opaque material, which\n * is occasionally wanted for draw-order reasons. Setting it `false` does not\n * turn off blending a lower alpha requires; there is no useful meaning for\n * that, and it only ever expressed a bug.\n */\n transparent?: boolean;\n /** **Structural.** Discard fragments below this alpha. Cheap cutout transparency. */\n alphaTest?: number;\n /** **Structural.** Which faces to rasterize. Default `\"front\"`. */\n faces?: Faces3D;\n /** **Structural.** Draw edges only. */\n wireframe?: boolean;\n /** **Structural.** How the colour combines with the framebuffer. */\n blend?: Blend3D;\n /** **Structural.** Read per-vertex colours from the geometry's `color` buffer. */\n vertexColors?: boolean;\n /** **Structural.** Apply the scene's tone mapping. Default true. */\n toneMapped?: boolean;\n\n /**\n * Write to the depth buffer.\n *\n * **Derived unless stated**: a blended surface stops writing depth, and an\n * opaque one writes it. three defaults this to `true` for everything, so a\n * translucent mesh occluded whatever was drawn after it — a surface at 5%\n * opacity rendering as a near-invisible cut-out through the things behind\n * it. Set it explicitly for a translucent surface that genuinely should\n * occlude.\n */\n depthWrite?: boolean;\n /** Test against the depth buffer. Turn off to force draw-on-top. */\n depthTest?: boolean;\n /** Nudge depth to break z-fighting between coplanar surfaces. */\n polygonOffset?: boolean;\n polygonOffsetFactor?: number;\n polygonOffsetUnits?: number;\n /** Smooth gradient banding. */\n dithering?: boolean;\n}\n\n/** Maps shared by the lit shading models. */\ninterface CommonMaps3D {\n /** Base colour (albedo). Sampled as sRGB. */\n map?: Texture3D;\n /** Per-pixel opacity, read from the red channel. */\n alphaMap?: Texture3D;\n /** Ambient occlusion, read from the red channel. Needs a second UV set. */\n aoMap?: Texture3D;\n aoMapIntensity?: number;\n /** Tangent-space normals. Sampled as linear data, not colour. */\n normalMap?: Texture3D;\n /** Normal strength, per axis. A number applies to both. */\n normalScale?: number | Vector2;\n /** Displaces vertices along their normals. Needs a subdivided geometry. */\n displacementMap?: Texture3D;\n displacementScale?: number;\n displacementBias?: number;\n /** Reflected environment. Usually inherited from the scene's environment. */\n envMap?: Texture3D;\n /** Multiplies light received from the environment. */\n envMapIntensity?: number;\n /** Baked light added on top, unaffected by scene lights. */\n lightMap?: Texture3D;\n lightMapIntensity?: number;\n}\n\n/** Emission shared by the lit shading models. */\ninterface Emissive3D {\n /** Self-illumination colour. Does not light other objects (see `post` bloom). */\n emission?: Color;\n emissionStrength?: number;\n emissionMap?: Texture3D;\n}\n\n/** Unlit — a flat colour, ignoring every light. The cheapest material. */\nexport interface BasicMaterial3D extends MaterialCommon3D, CommonMaps3D {\n type: \"basic\";\n color?: Color;\n}\n\n/**\n * Physically based metal/rough shading. The sensible default for most surfaces:\n * `roughness` and `metalness` cover the majority of real materials, and both are\n * free to animate.\n */\nexport interface StandardMaterial3D extends MaterialCommon3D, CommonMaps3D, Emissive3D {\n type: \"standard\";\n color?: Color;\n /** 0 mirror-smooth → 1 fully diffuse. */\n roughness?: number;\n /** 0 dielectric → 1 metal. Metals tint their reflections by `color`. */\n metalness?: number;\n roughnessMap?: Texture3D;\n metalnessMap?: Texture3D;\n /** **Structural.** Facet or smooth shading. Default `\"smooth\"`. */\n shading?: Shading3D;\n}\n\n/**\n * Everything {@link StandardMaterial3D} has plus the expensive extras: clearcoat,\n * transmission (real refraction), sheen and iridescence. Costs more per pixel, so\n * reach for `standard` unless a surface needs these.\n */\nexport interface PhysicalMaterial3D extends Omit<StandardMaterial3D, \"type\"> {\n type: \"physical\";\n /** A second specular lobe over the base — car paint, lacquer, varnish. */\n clearcoat?: number;\n clearcoatRoughness?: number;\n clearcoatMap?: Texture3D;\n clearcoatNormalMap?: Texture3D;\n clearcoatRoughnessMap?: Texture3D;\n /** Light transmitted *through* the surface — glass, water. Blends for you. */\n transmission?: number;\n transmissionMap?: Texture3D;\n /** Wall thickness for transmission tinting. */\n thickness?: number;\n thicknessMap?: Texture3D;\n /** Volumetric absorption colour at {@link attenuationDistance}. */\n attenuationColor?: Color;\n attenuationDistance?: number;\n /** Index of refraction. 1.5 glass, 1.33 water, 2.42 diamond. */\n ior?: number;\n /** Retroreflective sheen — cloth, velvet, dust. */\n sheen?: number;\n sheenColor?: Color;\n sheenRoughness?: number;\n /** Thin-film interference — soap bubbles, oil slicks, beetle shells. */\n iridescence?: number;\n iridescenceIOR?: number;\n iridescenceThicknessRange?: readonly [number, number];\n /** Strength/tint of the dielectric specular highlight. */\n specularIntensity?: number;\n specularColor?: Color;\n /** Anisotropic (brushed-metal) highlight stretching. */\n anisotropy?: number;\n /** Degrees. */\n anisotropyRotation?: number;\n}\n\n/** Classic Blinn-Phong: a diffuse term plus a tight specular highlight. */\nexport interface PhongMaterial3D extends MaterialCommon3D, CommonMaps3D, Emissive3D {\n type: \"phong\";\n color?: Color;\n specular?: Color;\n /** Highlight tightness. Higher is smaller and sharper. */\n shininess?: number;\n specularMap?: Texture3D;\n /** **Structural.** */\n shading?: Shading3D;\n}\n\n/** Diffuse-only Lambertian shading. Cheap; good for matte and unlit-ish looks. */\nexport interface LambertMaterial3D extends MaterialCommon3D, CommonMaps3D, Emissive3D {\n type: \"lambert\";\n color?: Color;\n /** **Structural.** */\n shading?: Shading3D;\n}\n\n/** Banded cel shading. `gradientMap` controls the steps. */\nexport interface ToonMaterial3D extends MaterialCommon3D, CommonMaps3D, Emissive3D {\n type: \"toon\";\n color?: Color;\n gradientMap?: Texture3D;\n}\n\n/** Surface normals as RGB. A debugging workhorse. */\nexport interface NormalMaterial3D extends MaterialCommon3D {\n type: \"normal\";\n /** **Structural.** */\n shading?: Shading3D;\n}\n\n/** Depth as greyscale. For debugging and custom depth passes. */\nexport interface DepthMaterial3D extends MaterialCommon3D {\n type: \"depth\";\n}\n\n/** Lit by a pre-baked sphere image. Very cheap, very stylizable. */\nexport interface MatcapMaterial3D extends MaterialCommon3D {\n type: \"matcap\";\n color?: Color;\n matcap?: Texture3D;\n map?: Texture3D;\n normalMap?: Texture3D;\n normalScale?: number | Vector2;\n}\n\n/** Shading for a `points` cloud. */\nexport interface PointsMaterial3D extends MaterialCommon3D {\n type: \"points\";\n color?: Color;\n size?: number;\n /** Shrink distant points with perspective. Default true. */\n sizeAttenuation?: boolean;\n map?: Texture3D;\n alphaMap?: Texture3D;\n}\n\n/**\n * Shading for a `line`. Note `width` is capped at 1px by most WebGL\n * implementations regardless of what you set, and **nothing substitutes a\n * mesh-backed line** for a larger one: it is written to `linewidth` and that is\n * all. For a genuinely thick line draw a `tube`.\n */\nexport interface LineBasicMaterial3D extends MaterialCommon3D {\n type: \"lineBasic\";\n color?: Color;\n width?: number;\n}\n\n/** A dashed line. Requires computed line distances, which the renderer handles. */\nexport interface LineDashedMaterial3D extends MaterialCommon3D {\n type: \"lineDashed\";\n color?: Color;\n width?: number;\n dashSize?: number;\n gapSize?: number;\n /** Offset along the line — animate for a marching-ants effect. */\n scale?: number;\n}\n\n/** Shading for a camera-facing `sprite`. */\nexport interface SpriteMaterial3D extends MaterialCommon3D {\n type: \"sprite\";\n color?: Color;\n map?: Texture3D;\n /** Degrees. */\n rotation?: number;\n}\n\n/** Receives shadows onto an otherwise invisible surface. For AR-style grounding. */\nexport interface ShadowMaterial3D extends MaterialCommon3D {\n type: \"shadow\";\n color?: Color;\n}\n\n/**\n * A shader uniform value. Deliberately narrow: everything here is plain,\n * inspectable data that can be interpolated, which is what keeps a shader-driven\n * scene seekable.\n */\nexport type Uniform3D =\n | number\n | boolean\n | Color\n | Vector2\n | Vector3\n | { x: number; y: number; z: number; w: number }\n | readonly number[]\n | Texture3D;\n\n/**\n * Raw GLSL — total control over both stages.\n *\n * Uniform **values** are cheap: the renderer writes them in place each frame, so\n * driving them from tweened props costs nothing. Uniform *names* and the shader\n * **source** are structural — changing either recompiles the program.\n *\n * {@link extends} is declared to patch three's built-in lit shader instead of\n * replacing it, but **it is not read yet**: a shader always replaces the model, so\n * scene lighting, shadows and fog do not reach it. The first material that sets\n * it warns in development. Write the lighting you need in the shader.\n */\nexport interface ShaderMaterial3D extends MaterialCommon3D {\n type: \"shader\";\n /** Vertex stage source. */\n vertex: string;\n /** Fragment stage source. */\n fragment: string;\n uniforms?: Readonly<Record<string, Uniform3D>>;\n /** `#define`s injected ahead of both stages. **Structural.** */\n defines?: Readonly<Record<string, string | number | boolean>>;\n /**\n * Wrap a built-in shading model rather than replacing it, so scene lighting,\n * shadows and fog still apply. Null (the default) is a raw shader.\n *\n * **Not implemented**: no backend reads it, so every shader is a plain\n * replacement whatever this says.\n */\n extends?: \"standard\" | \"basic\" | \"phong\" | null;\n /** Skip three's automatic attribute/uniform prelude (a raw shader). */\n raw?: boolean;\n}\n\n/** Every material a drawable can be shaded with. Discriminated on `type`. */\nexport type Material3D =\n | BasicMaterial3D\n | StandardMaterial3D\n | PhysicalMaterial3D\n | PhongMaterial3D\n | LambertMaterial3D\n | ToonMaterial3D\n | NormalMaterial3D\n | DepthMaterial3D\n | MatcapMaterial3D\n | PointsMaterial3D\n | LineBasicMaterial3D\n | LineDashedMaterial3D\n | SpriteMaterial3D\n | ShadowMaterial3D\n | ShaderMaterial3D;\n\n/**\n * Material fields whose value the renderer can write in place, without\n * recompiling. Everything *not* listed here is structural: changing it rebuilds\n * the material. Shared by the reconciler and the `MeshShorthand` desugarer so the\n * two can't disagree about what is cheap.\n */\nexport const MUTABLE_MATERIAL_KEYS: readonly string[] = [\n \"color\", \"opacity\", \"visible\", \"emission\", \"emissionStrength\",\n \"roughness\", \"metalness\", \"shininess\", \"specular\", \"reflectivity\",\n \"clearcoat\", \"clearcoatRoughness\", \"transmission\", \"thickness\", \"ior\",\n \"sheen\", \"sheenColor\", \"sheenRoughness\", \"iridescence\", \"iridescenceIOR\",\n \"specularIntensity\", \"specularColor\", \"anisotropy\", \"anisotropyRotation\",\n \"attenuationColor\", \"attenuationDistance\",\n \"aoMapIntensity\", \"lightMapIntensity\", \"envMapIntensity\",\n \"normalScale\", \"displacementScale\", \"displacementBias\",\n \"size\", \"width\", \"dashSize\", \"gapSize\", \"scale\", \"rotation\",\n \"depthWrite\", \"depthTest\", \"polygonOffsetFactor\", \"polygonOffsetUnits\",\n];\n\n/**\n * Material fields that change the compiled shader program. Changing one forces a\n * rebuild, so they must never be tweened — the renderer warns when it sees one\n * change repeatedly.\n *\n * `transparent` is here and is also *derived*, which is only a contradiction\n * until you look at when it moves: it flips at most once per material, on the\n * first frame a fade leaves full opacity, and the renderer latches it there. See\n * `needsBlending` in the material handler.\n */\nexport const STRUCTURAL_MATERIAL_KEYS: readonly string[] = [\n \"transparent\", \"alphaTest\", \"faces\", \"wireframe\", \"blend\",\n \"vertexColors\", \"toneMapped\", \"shading\", \"dithering\",\n \"polygonOffset\", \"raw\", \"extends\", \"defines\",\n];\n", "import { AudioRequest, busStopKey } from \"@/attributes/audio/request\";\nimport { effectsKey } from \"@/attributes/audio/effects/union\";\nimport { paramKey } from \"@/attributes/audio/ramp\";\nimport { transitionKey } from \"@/attributes/audio/transition\";\nimport { AssetRecord, Disposer, LoaderFn } from \"@/assets/record\";\nimport { AudioSink } from \"@/platform/audio-sink\";\nimport { StorageAdapter } from \"@/platform/storage-adapter\";\nimport { AssetTrack, AssetTimelineResult } from \"@/runtime/asset-timeline\";\n\n/**\n * Coordinates asset loading and audio synchronization during playback.\n * Wraps a {@link AssetTimelineResult} and delegates storage/audio work to platform adapters.\n */\nexport class AssetManager {\n private precomp: AssetTimelineResult;\n private readonly storageAdapter: StorageAdapter;\n private readonly audioDevice: AudioSink;\n\n /** `null` after a swap: whatever the device holds belongs to the previous precomp. */\n private lastAudioRequestKey: string | null = \"\";\n private lastAudioSrcs: ReadonlySet<string> | null = new Set();\n private audioFetching = new Map<string, Promise<void>>();\n /**\n * Sources whose fetch or decode failed, with why, so they are not fetched\n * again every sync. A source leaves when no request in the window names it\n * any more — and, once it has been reported, when a new precomp arrives —\n * so the next time it is wanted it is tried afresh. One that failed quietly\n * (see {@link AudioRequest.optional}) is kept across a precomp: a video with\n * no audio track would otherwise be fetched whole on every edit.\n */\n private audioFailed = new Map<string, unknown>();\n /** The failed sources already reported to {@link onError}. */\n private audioReported = new Set<string>();\n /** Sources a request in the last window asked for by name, not as a picture's own sound. */\n private audioRequired: ReadonlySet<string> = new Set();\n /** Keys of the loaders a track measures against, which no window may evict. */\n private layoutGateKeys: ReadonlySet<string>;\n private disposed = false;\n\n /** Disposers for loaders whose load has resolved, keyed by loader key. */\n private loaderDisposers = new Map<string, Disposer>();\n /** In-flight loader runs, keyed by loader key, to dedupe concurrent calls. */\n private loaderInFlight = new Map<string, Promise<void>>();\n\n /**\n * @param onError Told once per source when audio a request asked for cannot\n * be fetched or decoded. Defaults to `console.error`.\n */\n constructor(\n precomp: AssetTimelineResult,\n storageAdapter: StorageAdapter,\n audioDevice: AudioSink,\n private readonly onError: (error: Error) => void = (error) => console.error(`[AssetManager] ${error.message}`),\n ) {\n this.precomp = precomp;\n this.layoutGateKeys = layoutGatesOf(precomp);\n this.storageAdapter = storageAdapter;\n this.audioDevice = audioDevice;\n }\n\n // ─── Public surface ───────────────────────────────────────────────────────\n\n /**\n * Swap in a new precomp result (a document swap). The manager keeps its\n * warm loader disposers and in-flight audio fetches so a single-track edit\n * doesn't re-fetch unchanged assets; the next loadAt/syncAudio picks up the\n * new asset windows. Resetting the audio signature forces a reschedule so a\n * changed track's audio is re-evaluated against the new timeline — including\n * into an empty window, which is how removed audio stops.\n */\n setPrecomp(precomp: AssetTimelineResult): void {\n this.precomp = precomp;\n this.layoutGateKeys = layoutGatesOf(precomp);\n for (const src of this.audioReported) this.audioFailed.delete(src);\n this.audioReported.clear();\n this.lastAudioRequestKey = null;\n this.lastAudioSrcs = null;\n }\n\n /**\n * Blocking load for seek and initial render. Waits for every asset whose\n * cacheAt <= frame and endFrame >= frame to be ready, then schedules audio.\n */\n async loadAt(frame: number): Promise<void> {\n const jobs: Promise<void>[] = [];\n\n for (const [key, track] of this.precomp.assets) {\n if (track.record.type === 'loader') {\n const job = this.syncLoader(key, track, frame);\n if (job) jobs.push(job);\n continue;\n }\n if (track.cacheAt <= frame && track.record.endFrame >= frame) {\n jobs.push(this.storageAdapter.loadAsset(key, track.record));\n }\n }\n\n await Promise.all(jobs);\n if (this.audioDevice.schedulesAudio) this.syncAudio(frame);\n }\n\n /** Whether `key` — a loader key or a stored asset's — is resident now. */\n isReady(key: string): boolean {\n return this.loaderDisposers.has(key) || this.storageAdapter.isLoaded(key);\n }\n\n /**\n * Load `records` whatever their windows say — for layout gates, which must be\n * resident before a track measures regardless of the frame being drawn.\n */\n async loadRecords(records: readonly AssetRecord[]): Promise<void> {\n await Promise.all(records.map((record) => record.type === 'loader'\n ? this.runLoader(record.src, record.load)\n : this.storageAdapter.loadAsset(record.src, record)));\n }\n\n /**\n * Non-blocking incremental prefetch called after each render tick. Fires\n * loads for assets whose cacheAt window has been reached without blocking.\n */\n prefetch(frame: number): void {\n for (const [key, track] of this.precomp.assets) {\n if (track.record.type === 'loader') {\n this.syncLoader(key, track, frame)?.catch(err => {\n console.error(`[AssetManager] loader failed for ${key}:`, err);\n });\n continue;\n }\n if (track.cacheAt <= frame && track.record.endFrame >= frame) {\n this.storageAdapter.loadAsset(key, track.record).catch(err => {\n console.error(`[AssetManager] prefetch failed for ${key}:`, err);\n });\n }\n }\n }\n\n /**\n * Drive a single loader track toward the state `frame` requires. If `frame`\n * is inside the loader's `[cacheAt, discardAt]` window, run its callback\n * (deduped — at most one in-flight run, skipped once loaded) and return the\n * pending job, if any. If `frame` is outside the window and the loader was\n * loaded, dispose it. Returns the in-flight load promise so a blocking\n * caller can await it; `undefined` when there's nothing to wait for.\n */\n private syncLoader(key: string, track: AssetTrack, frame: number): Promise<void> | undefined {\n if (track.record.type !== 'loader') return undefined;\n const discardAt = track.discardAt ?? Infinity;\n const inWindow = track.cacheAt <= frame && frame <= discardAt;\n\n if (!inWindow) {\n // A layout gate is loaded by `loadRecords` whatever frame is drawn, so\n // its window says nothing about when it may go: disposing it here made\n // `isReady` false and the next frame load it again.\n if (this.layoutGateKeys.has(key)) return undefined;\n const dispose = this.loaderDisposers.get(key);\n if (dispose) {\n this.loaderDisposers.delete(key);\n dispose();\n }\n return undefined;\n }\n\n return this.runLoader(key, track.record.load);\n }\n\n /** Run a loader unless it is resident or already running. */\n private runLoader(key: string, load: LoaderFn): Promise<void> | undefined {\n // Already loaded for this window, or a run is already in flight.\n if (this.loaderDisposers.has(key)) return undefined;\n const existing = this.loaderInFlight.get(key);\n if (existing) return existing;\n\n const job = load()\n .then(disposer => {\n // A loader that resolves nothing is keeping its result resident on\n // purpose (see `LoaderFn`). Recording a no-op disposer rather than\n // skipping the entry is what keeps `loaderDisposers.has(key)` the\n // single \"already loaded\" test for both kinds.\n this.loaderDisposers.set(key, disposer ?? NO_DISPOSE);\n })\n .finally(() => {\n this.loaderInFlight.delete(key);\n });\n this.loaderInFlight.set(key, job);\n return job;\n }\n\n /** Run every outstanding loader disposer and clear loader state. */\n dispose(): void {\n for (const dispose of this.loaderDisposers.values()) dispose();\n this.loaderDisposers.clear();\n this.loaderInFlight.clear();\n this.disposed = true;\n }\n\n /**\n * Push the current audio working set to the AudioSink. Called after each\n * render tick so the device stays in sync with the tracks' audio requests.\n */\n syncAudio(frame: number): void {\n const currentTime = frame / this.precomp.fps;\n\n const inWindow: AudioRequest[] = [];\n const srcs = new Set<string>();\n const required = new Set<string>();\n const seen = new Set<string>();\n\n /** Admit `req` if it overlaps the scheduling window, shifted by its owner's offset. */\n const consider = (req: AudioRequest, offsetSecs: number): void => {\n const globalStart = offsetSecs + req.startAt;\n const globalEnd = offsetSecs + req.endAt;\n\n if (globalEnd < currentTime || globalStart > currentTime + 10) return;\n // Ahead of the dedupe: the flag is not part of a request's identity.\n if (!req.optional) required.add(req.src);\n\n const stableId = stableKey(req, offsetSecs);\n if (seen.has(stableId)) return;\n seen.add(stableId);\n\n inWindow.push({\n ...req,\n id: stableId,\n startAt: globalStart,\n endAt: globalEnd,\n // A bus's span is in its request's seconds, so it moves with it.\n ...(req.bus && {\n bus: req.bus.map((s) => ({ ...s, startAt: offsetSecs + s.startAt, endAt: offsetSecs + s.endAt })),\n }),\n });\n srcs.add(req.src);\n };\n\n for (const track of this.precomp.tracks) {\n const offsetSecs = track.startFrame / this.precomp.fps;\n for (const req of track.audioRequests) consider(req, offsetSecs);\n }\n\n this.audioRequired = required;\n for (const src of srcs) {\n if (!this.audioDevice.has(src) && !this.audioFetching.has(src) && !this.audioFailed.has(src)) {\n const job = this.storageAdapter.fetchAudioData(src)\n .then(data => this.audioDevice.append(src, data))\n .catch(cause => this.failAudio(src, cause))\n .finally(() => this.audioFetching.delete(src));\n this.audioFetching.set(src, job);\n }\n }\n // A failed source nothing asks for any more is forgotten, so wanting it\n // again later tries it afresh; one that failed quietly is reported when\n // a request that asks for its sound arrives.\n for (const [src, cause] of this.audioFailed) {\n if (!srcs.has(src)) {\n this.audioFailed.delete(src);\n this.audioReported.delete(src);\n } else if (required.has(src)) {\n this.reportAudio(src, cause);\n }\n }\n\n const requestKey = audioSignature(inWindow);\n if (requestKey !== this.lastAudioRequestKey) {\n this.audioDevice.schedule(inWindow);\n this.lastAudioRequestKey = requestKey;\n }\n if (this.lastAudioSrcs === null || !setsEqual(this.lastAudioSrcs, srcs)) {\n this.audioDevice.retain(srcs);\n this.lastAudioSrcs = srcs;\n }\n }\n\n /** Record that `src` could not be loaded, and say so if a request asked for its sound. */\n private failAudio(src: string, cause: unknown): void {\n if (this.disposed) return;\n this.audioFailed.set(src, cause);\n if (this.audioRequired.has(src)) this.reportAudio(src, cause);\n }\n\n /** Say that `src` could not be loaded, once, until it is wanted afresh. */\n private reportAudio(src: string, cause: unknown): void {\n if (this.audioReported.has(src)) return;\n this.audioReported.add(src);\n const message = cause instanceof Error ? cause.message : String(cause);\n this.onError(new Error(`audio \"${src}\" could not be loaded: ${message}`, { cause }));\n }\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\n/** Every layout-gate key any track of `precomp` declares. */\nfunction layoutGatesOf(precomp: AssetTimelineResult): ReadonlySet<string> {\n const keys = new Set<string>();\n for (const track of precomp.tracks) for (const key of track.layoutGates ?? []) keys.add(key);\n return keys;\n}\n\n/** Stand-in for a loader that resolved nothing — see the note in {@link AssetManager.syncLoader}. */\nconst NO_DISPOSE: Disposer = () => { };\n\n/**\n * Produce a deterministic string key that uniquely identifies an audio request's\n * playback identity. Includes the effect chain, the ramps and the transitions so\n * editing any of them changes the id — the device then stops the stale source and\n * rebuilds the graph instead of reusing the old one.\n *\n * The bus chain is in for the same reason: re-routing a clip to a different bus,\n * or changing a bus's level or its span, changes what it sounds like without\n * changing anything else here — so leaving it out would keep the stale graph.\n */\nfunction stableKey(req: AudioRequest, clipOffsetSecs: number): string {\n return `${req.src}|${clipOffsetSecs + req.startAt}|${clipOffsetSecs + req.endAt}|${req.trimStart}|${req.trimEnd ?? \"_\"}|${req.loop ? 1 : 0}|${paramKey(req.volume)}|${paramKey(req.speed)}|${req.sourceLength ?? \"_\"}|${effectsKey(req.effects)}|${transitionKey(req.transitionIn)}|${transitionKey(req.transitionOut)}|${busKey(req.bus)}`;\n}\n\n/** The bus chain's contribution to {@link stableKey}. */\nfunction busKey(bus: AudioRequest[\"bus\"]): string {\n if (!bus || bus.length === 0) return \"\";\n return bus.map(busStopKey).join(\">\");\n}\n\n/** Produce a stable hash of the active audio request set to detect scheduling changes. */\nfunction audioSignature(reqs: readonly AudioRequest[]): string {\n if (reqs.length === 0) return \"\";\n return reqs.map(r => r.id).sort().join(\"\\n\");\n}\n\n/** Shallow equality check for two string sets (order-independent). */\nfunction setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {\n if (a.size !== b.size) return false;\n for (const v of a) if (!b.has(v)) return false;\n return true;\n}\n", "import type { AssetCatalog } from \"./catalog\";\nimport type { LoaderFn } from \"./record\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport type { NodeEffect } from \"@/attributes/shape/effects/union\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport { declareFill } from \"@/attributes/shape/fill/registry\";\nimport { declareEffect } from \"@/attributes/shape/effects/registry\";\nimport { declareTree } from \"@/components/trees/node/node-walk\";\n\n/** Whether an asset has to be resident before layout measures, or only before a frame draws. */\nexport type AssetGate = \"layout\" | \"render\";\n\nexport type AssetDecl =\n | { type: \"image\"; src: string }\n | { type: \"video\"; src: string; trimStart: number; trimEnd: number }\n | { type: \"font\"; family: string; weight: number }\n | { type: \"loader\"; key: string; load: LoaderFn; gate: AssetGate };\n\n/**\n * What a node's `declareAssets` states its needs into.\n *\n * A declaration must be a pure function of the props and context it reads — never\n * `layoutBounds`, never `time`, no writes — because the runtime re-runs it only\n * when something it read changes. Declarations dedupe by {@link assetKey}.\n */\nexport interface AssetScope {\n readonly catalog: AssetCatalog;\n image(src: string): void;\n video(src: string, trim?: { start?: number; end?: number }): void;\n /** Gates layout: text is measured against the face. */\n font(family: string, weight?: number | string): void;\n /** `gate` defaults to `\"render\"`; pass `\"layout\"` for a load measurement depends on. */\n loader(key: string, load: LoaderFn, options?: { gate?: AssetGate }): void;\n fill(fills: FillResolved | readonly FillResolved[]): void;\n effects(effects: readonly NodeEffect[]): void;\n /** A detached subtree this node draws (a `Tex.surface` node source), declared as part of this node. */\n subtree(node: Node): void;\n}\n\n/**\n * Fonts key by family alone: `loadFont` registers every weight of a family at once\n * and a variable weight renders through `fontVariations`, so a weight in the key\n * would mint an entry per frame of a weight tween.\n */\nexport function assetKey(decl: AssetDecl): string {\n switch (decl.type) {\n case \"image\":\n case \"video\":\n return decl.src;\n case \"font\":\n return decl.family;\n case \"loader\":\n return decl.key;\n }\n}\n\n/** Anything unparseable lands on 400, which is what an unspecified weight means anyway. */\nexport function normalizeWeight(weight: number | string | undefined): number {\n if (typeof weight === \"number\") return Number.isFinite(weight) ? weight : 400;\n if (typeof weight === \"string\") return parseInt(weight, 10) || 400;\n return 400;\n}\n\nexport interface AssetDeclarationOptions {\n /** Binds a detached subtree (catalog, context, clock) before it declares. */\n bindSubtree?: (node: Node) => void;\n /** Replaces the default {@link declareTree} walk over a subtree. */\n onSubtree?: (node: Node, scope: AssetScope) => void;\n}\n\n/**\n * The {@link AssetScope} that collects: one declaration pass, keyed and validated.\n *\n * Unknown images and videos throw here, so a typo surfaces against the node that\n * declared it rather than as a picture that never paints.\n */\nexport class AssetDeclaration implements AssetScope {\n readonly catalog: AssetCatalog;\n\n constructor(catalog: AssetCatalog, options: AssetDeclarationOptions = {}) {\n this.catalog = catalog;\n this._options = options;\n }\n\n get declarations(): ReadonlyMap<string, AssetDecl> {\n return this._decls;\n }\n\n // An empty `src` is an unset media slot — it paints the checkerboard, not a\n // missing asset — so it declares nothing.\n image(src: string): void {\n if (!src || this._decls.has(src)) return;\n this.catalog.getImageMeta(src);\n this._decls.set(src, { type: \"image\", src });\n }\n\n video(src: string, trim?: { start?: number; end?: number }): void {\n if (!src || this._decls.has(src)) return;\n this.catalog.getVideoMeta(src);\n this._decls.set(src, {\n type: \"video\",\n src,\n trimStart: trim?.start ?? 0,\n trimEnd: trim?.end ?? this.catalog.getVideoDuration(src),\n });\n }\n\n font(family: string, weight?: number | string): void {\n if (!family || this._decls.has(family)) return;\n this._decls.set(family, { type: \"font\", family, weight: normalizeWeight(weight) });\n }\n\n loader(key: string, load: LoaderFn, options?: { gate?: AssetGate }): void {\n const gate = options?.gate ?? \"render\";\n const existing = this._decls.get(key);\n if (existing === undefined) {\n this._decls.set(key, { type: \"loader\", key, load, gate });\n return;\n }\n if (existing.type !== \"loader\") return;\n if (existing.load !== load && process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[assets] Loader \"${key}\" was declared with a different load function; the first is kept. ` +\n `Hoist the function so every declaration of the key hands over the same one.`,\n );\n }\n // Layout is the stricter gate, so it wins whichever declaration asked first.\n if (gate === \"layout\" && existing.gate !== \"layout\") {\n this._decls.set(key, { ...existing, gate });\n }\n }\n\n fill(fills: FillResolved | readonly FillResolved[]): void {\n if (!fills) return;\n if (!Array.isArray(fills)) {\n declareFill(fills as FillResolved, this);\n return;\n }\n for (const fill of fills as readonly FillResolved[]) declareFill(fill, this);\n }\n\n effects(effects: readonly NodeEffect[]): void {\n if (!effects) return;\n for (const effect of effects) declareEffect(effect, this);\n }\n\n subtree(node: Node): void {\n this._subtrees ??= new Set();\n if (this._subtrees.has(node)) return;\n this._subtrees.add(node);\n this._options.bindSubtree?.(node);\n if (this._options.onSubtree) this._options.onSubtree(node, this);\n else declareTree(node, this);\n }\n\n private readonly _options: AssetDeclarationOptions;\n private readonly _decls = new Map<string, AssetDecl>();\n private _subtrees: Set<Node> | undefined;\n}\n", "/**\n * Event-loop yielding, for work that must stay interruptible.\n *\n * A long synchronous loop on the main thread cannot be cancelled: nothing else\n * can run to *ask* it to stop. `StateEvaluator`'s backward-seek replay is\n * exactly that shape, so it yields periodically through {@link yieldToScheduler}\n * — which is what lets a newer seek supersede one already in flight.\n *\n * Core is backend-agnostic (no DOM), so every mechanism here is feature-detected\n * and the module works unchanged in a browser, in Node, and under vitest.\n */\n\n/** Monotonic-ish clock in milliseconds. `performance` is absent in some hosts. */\nexport function now(): number {\n return typeof performance !== \"undefined\" && typeof performance.now === \"function\"\n ? performance.now()\n : Date.now();\n}\n\ntype SchedulerWithYield = { yield?: () => Promise<void> };\n\n/** `scheduler.yield()` when the host has it (Chrome 129+), else undefined. */\nfunction nativeYield(): (() => Promise<void>) | undefined {\n const s = (globalThis as { scheduler?: SchedulerWithYield }).scheduler;\n return typeof s?.yield === \"function\" ? s.yield.bind(s) : undefined;\n}\n\n/**\n * A single shared `MessageChannel`, because a yield-per-channel would allocate\n * (and leak until GC) thousands of ports over one scrub. Callbacks queue in FIFO\n * order and each posted message drains exactly one, so resolution order matches\n * call order.\n */\nlet channel: MessageChannel | null = null;\nconst queue: (() => void)[] = [];\n\nfunction messageChannelYield(): Promise<void> | null {\n if (typeof MessageChannel !== \"function\") return null;\n if (!channel) {\n channel = new MessageChannel();\n channel.port1.onmessage = () => queue.shift()?.();\n // Node2D keeps the event loop alive for an open port, which would hang\n // vitest on exit. Browsers have no unref and don't need one.\n (channel.port1 as unknown as { unref?: () => void }).unref?.();\n (channel.port2 as unknown as { unref?: () => void }).unref?.();\n }\n return new Promise<void>(resolve => {\n queue.push(resolve);\n channel!.port2.postMessage(null);\n });\n}\n\n/**\n * Yield to the event loop, letting pending input, timers and rendering run\n * before the caller resumes.\n *\n * Deliberately a **macrotask**, not a microtask: `await Promise.resolve()`\n * drains within the same task and would starve exactly the work we're yielding\n * for. `requestAnimationFrame` is also wrong here — it caps throughput to the\n * display rate and stops entirely in a background tab, which would stall\n * headless export and tests.\n *\n * Preference order:\n * 1. `scheduler.yield()` — resumes at continuation priority, so a sliced task\n * isn't starved behind unrelated work queued while it was parked.\n * 2. `MessageChannel` — a true macrotask with no clamping, in browsers and\n * Node2D ≥ 15.\n * 3. `setTimeout(0)` — last resort; clamps to ~4 ms once nested, capping the\n * slice rate, but always available.\n */\nexport function yieldToScheduler(): Promise<void> {\n const native = nativeYield();\n if (native) return native();\n return messageChannelYield() ?? new Promise<void>(resolve => setTimeout(resolve, 0));\n}\n\n/** Drop the shared channel. Tests only — the next yield lazily rebuilds it. */\nexport function __resetSchedulerForTests(): void {\n channel?.port1.close();\n channel?.port2.close();\n channel = null;\n queue.length = 0;\n}\n", "/**\n * Which frame a still addresses: an explicit project frame index, the\n * timeline's first frame, or its last.\n */\nexport type FrameSpec =\n | { kind: 'frame'; frame: number }\n | { kind: 'first' }\n | { kind: 'last' };\n\n/** How far a product may sit from a whole frame and still count as on it — a few ulps at any frame count a clip can reach. */\nconst FRAME_TOLERANCE = 1e-9;\n\n/**\n * The clip time of `frame`, in seconds.\n *\n * `frame * (1 / fps)`, not `frame / fps`: the two disagree in the last bit, and\n * every frame-to-time conversion has to be this one, so a span boundary falls on\n * the same side of a frame wherever it is asked.\n */\nexport function clipFrameToTime(frame: number, fps: number): number {\n return frame * (1 / fps);\n}\n\n/**\n * The (fractional) frame at `seconds`.\n *\n * A time that lands within float error of a whole frame is that frame:\n * `123 * (1 / 60)` times `60` is `122.99999999999999`, and a floor or a ceil of\n * that is a frame off. Anything further from a frame boundary is left as it is.\n */\nexport function clipTimeToFrame(seconds: number, fps: number): number {\n const frame = seconds * fps;\n const nearest = Math.round(frame);\n return Math.abs(frame - nearest) <= FRAME_TOLERANCE * Math.max(1, Math.abs(frame)) ? nearest : frame;\n}\n\n/** The {@link FrameSpec} for the whole frame nearest `seconds`. */\nexport function frameSpecAtTime(seconds: number, fps: number): FrameSpec {\n return { kind: 'frame', frame: Math.round(clipTimeToFrame(seconds, fps)) };\n}\n", "import type { Track } from \"@/document/project\";\nimport type { NodeSpan } from \"@/document/types\";\nimport { clipFrameToTime, clipTimeToFrame } from \"./frame-time\";\n\n/** One track's span on the project timeline. `endFrame` is inclusive. */\nexport interface TrackSpan {\n id: string;\n /** Position in `ProjectDocument.tracks`, which is also paint order: first is at the back. */\n index: number;\n startFrame: number;\n endFrame: number;\n}\n\n/**\n * Frames a clip occupies. Rounded up, so a length off a frame boundary still\n * covers its last partial frame, and never less than one, so a still is drawn.\n */\nexport function trackFrameCount(seconds: number, fps: number): number {\n if (typeof seconds !== \"number\" || !Number.isFinite(seconds)) return 1;\n return Math.max(1, Math.ceil(clipTimeToFrame(seconds, fps)));\n}\n\n/**\n * Where each track sits, from nothing but what the document declares.\n *\n * A start rounds to the nearest frame while a length rounds up: a start is a\n * point, and flooring it would put every track a frame early.\n */\nexport function placeTracks(tracks: readonly Track[], fps: number): TrackSpan[] {\n return tracks.map((track, index) => {\n const startFrame = Math.max(0, Math.round(clipTimeToFrame(track.startAt ?? 0, fps)));\n return { id: track.id, index, startFrame, endFrame: startFrame + trackFrameCount(track.duration, fps) - 1 };\n });\n}\n\n/** The furthest any track reaches — not the sum of their lengths, since gaps and overlaps are both legal. */\nexport function totalFramesOf(spans: readonly { endFrame: number }[]): number {\n let total = 0;\n for (const span of spans) total = Math.max(total, span.endFrame + 1);\n return total;\n}\n\n/** The spans covering `frame`, back to front. */\nexport function spansCovering(spans: readonly TrackSpan[], frame: number): TrackSpan[] {\n return spans.filter(span => frame >= span.startFrame && frame <= span.endFrame);\n}\n\n/**\n * The clip time a track shows at its local `frame`. Clamped, so a frame held past\n * the end shows where the track stops — a track can cut its clip short.\n */\nexport function frameTime(frame: number, fps: number, duration: number): number {\n return Math.min(clipFrameToTime(frame, fps), duration);\n}\n\n/**\n * The clip-local frames a node present over `span` is drawn on: the first whose\n * time reaches its start and the last before its end. `null` when it covers none.\n */\nexport function spanFrames(\n span: Readonly<NodeSpan>,\n fps: number,\n frameCount: number,\n): { startFrame: number; endFrame: number } | null {\n const last = frameCount - 1;\n const at = (frame: number) => frameTime(frame, fps, Infinity);\n\n let startFrame = Math.min(last + 1, Math.max(0, Math.ceil(span.start * fps)));\n while (startFrame > 0 && at(startFrame - 1) >= span.start) startFrame--;\n while (startFrame <= last && at(startFrame) < span.start) startFrame++;\n\n let endFrame = last;\n if (span.end !== Infinity) {\n endFrame = Math.max(-1, Math.min(last, Math.ceil(span.end * fps)));\n while (endFrame >= 0 && at(endFrame) >= span.end) endFrame--;\n while (endFrame < last && at(endFrame + 1) < span.end) endFrame++;\n }\n return startFrame <= endFrame ? { startFrame, endFrame } : null;\n}\n", "import type { AssetCatalog } from \"@/assets/catalog\";\nimport type { Size2D } from \"@/attributes/layout/size\";\nimport { clipDocument } from \"@/document/audio\";\nimport type { Registry } from \"@/document/registry\";\nimport { ClipTimeline, type PlacedCommandInfo, type PlacedSound, type TimelineIssue } from \"@/document/timeline\";\nimport type { TimelinePatch } from \"@/document/timeline-patch\";\nimport type { PropSlot } from \"@/props/slot\";\nimport {\n effectiveSpans,\n ROOT_NODE_ID,\n type ClipDocument,\n type NodeSpan,\n type VisualDocument,\n} from \"@/document/types\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport { applyEditorStates, type NodeEditorStates } from \"@/components/trees/node/node-editor-state\";\nimport { primeMotionTree, sampleTree } from \"@/components/trees/node/node-walk\";\nimport { Canvas2D } from \"@/components/trees/root/canvas2d-node\";\nimport { nodePath } from \"@/project/tree\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { RenderPass2D } from \"@/render/render-context2d\";\nimport { ContextMap } from \"@/util/context\";\n\n/** What a clip is built and measured against — the same for every track in a session. */\nexport interface RuntimeScope {\n registry: Registry;\n viewport: Size2D;\n fps: number;\n assets: AssetCatalog;\n measurer: MeasureContext2D;\n}\n\n/**\n * One track's clip, live: the viewport-sized {@link Canvas2D} it builds into and\n * the timeline compiled over it.\n *\n * Built once, then asked for a time. Nothing resets one — a caller that needs a\n * fresh tree builds a new instance — which is what lets the measuring pass and\n * the evaluator each hold their own instead of taking turns with one.\n */\nexport class ClipInstance {\n readonly canvas: Canvas2D;\n\n constructor(clip: ClipDocument, duration: number, private readonly _scope: RuntimeScope) {\n this._clip = clip;\n this._duration = duration;\n this._doc = lowered(clip);\n const { width, height } = _scope.viewport;\n // Seeded here because this canvas *is* the document's root row, yet it is\n // the one node no `Registry.instantiate` makes: `ClipTimeline` applies\n // that row's props with `set()`, which writes property fields only, so\n // an unseeded root would report a UUID no document row mentions.\n this.canvas = new Canvas2D({ id: ROOT_NODE_ID, width, height, flow: \"freeform\" });\n this._timeline = new ClipTimeline(this._doc, _scope.registry, this.canvas);\n this._indexRows();\n }\n\n get duration(): number {\n return this._duration;\n }\n\n /** The clip document this instance plays, as handed in — before audio lowering. */\n get clip(): ClipDocument {\n return this._clip;\n }\n\n /**\n * Build the tree, then fix every command against it laid out — see `ClipTimeline.compile`.\n * `measurer` stands in for the scope's during the build only.\n */\n build(measurer: MeasureContext2D = this._scope.measurer): void {\n this.attach(0);\n this._timeline.build();\n this.sample();\n this.layout(measurer);\n this._timeline.compile(() => {\n this.sample();\n this.layout(measurer);\n });\n this.layout(measurer);\n }\n\n /**\n * Patch the built tree to play `next`, re-instantiating and recompiling only\n * what the difference touches. `false` means the change needs a fresh instance\n * (see `planTimelinePatch`); the tree is untouched then. A throw leaves the tree\n * unusable — the caller disposes it and builds fresh.\n */\n update(next: ClipDocument, duration: number): boolean {\n if (next === this._clip) {\n this._duration = duration;\n return true;\n }\n const patch = this.planUpdate(next);\n if (!patch) return false;\n this.applyUpdate(patch, next, duration);\n return true;\n }\n\n /** {@link update}'s plan, for a caller that has to look at the tree before it changes. */\n planUpdate(next: ClipDocument): TimelinePatch | null {\n return this._timeline.planUpdate(lowered(next));\n }\n\n applyUpdate(\n patch: TimelinePatch,\n next: ClipDocument,\n duration: number,\n measurer: MeasureContext2D = this._scope.measurer,\n ): void {\n this.attach(0);\n const relayout = () => {\n this.sample();\n this.layout(measurer);\n };\n this._timeline.applyUpdate(patch, relayout, relayout);\n this.layout(measurer);\n this._clip = next;\n this._doc = patch.next.doc;\n this._duration = duration;\n this._indexRows();\n }\n\n /** Every command as compiled, with what each writes — see `ClipTimeline.placedCommands`. */\n placedCommands(): readonly PlacedCommandInfo[] {\n return this._timeline.placedCommands();\n }\n\n /** What the build stepped around instead of failing — see `ClipTimeline.issues`. */\n issues(): TimelineIssue[] {\n return this._timeline.issues();\n }\n\n commandSounds(): PlacedSound[] {\n return this._timeline.commandSounds();\n }\n\n /** `read`, with the tree's presence as it stands at `seconds`; the presence is put back after. */\n atPresence<T>(seconds: number, read: () => T): T {\n const was = this._timeline.presenceTime;\n this._timeline.syncPresence(seconds);\n try {\n return read();\n } finally {\n this._timeline.syncPresence(was);\n }\n }\n\n evaluateAt(seconds: number, onWrite?: (index: number, slot: PropSlot<unknown>) => void): void {\n this._timeline.syncPresence(seconds);\n this._timeline.evaluateAt(seconds, onWrite);\n }\n\n attach(seconds: number, editor?: NodeEditorStates): void {\n this.canvas.attach({ assets: this._scope.assets, context: ContextMap.EMPTY, time: seconds });\n // Before layout, so a node that appeared this frame gets its editor state\n // on the frame it appears — and a hidden one is out of the flow before it\n // is measured.\n applyEditorStates(this.canvas, editor);\n }\n\n layout(measurer: MeasureContext2D = this._scope.measurer): void {\n const { width, height } = this._scope.viewport;\n this.canvas.layout({ x: 0, y: 0, width, height }, measurer);\n }\n\n render(pass: RenderPass2D): void {\n this.canvas.render(pass);\n }\n\n sample(): void {\n sampleTree(this.canvas);\n }\n\n primeMotion(at: number): void {\n primeMotionTree(this.canvas, at);\n }\n\n /** The node a document row built, mounted or not; the canvas for the root. */\n node(rowId: string): Node | undefined {\n return this._timeline.liveNode(rowId);\n }\n\n /** What a document row holds before any command acts on it — see `ClipTimeline.baselineProps`. */\n baselineProps(rowId: string): Record<string, unknown> | undefined {\n return this._timeline.baselineProps(rowId);\n }\n\n /** Every document row's effective span, the root's excepted. */\n rowSpans(): NodeSpan[] {\n return [...this._rows.values()].map((row) => row.span);\n }\n\n /** One row's effective span — `undefined` for the root, which spans the clip, and for an id no row has. */\n rowSpan(id: string): NodeSpan | undefined {\n return this._rows.get(id)?.span;\n }\n\n /**\n * `node`'s owner key as {@link forEachOwner} spells it, mounted or not —\n * `undefined` for a node no row built.\n */\n ownerKeyOf(node: Node): string | undefined {\n let below = \"\";\n for (let current: Node = node; ;) {\n if (current === this.canvas || this._timeline.liveNode(current.id) === current) {\n const row = current === this.canvas ? ROOT_NODE_ID : current.id;\n return below === \"\" ? row : `${row}/${below}`;\n }\n const parent = current.parent;\n if (!parent) return undefined;\n const index = parent._allChildren.indexOf(current);\n below = below === \"\" ? String(index) : `${index}.${below}`;\n current = parent;\n }\n }\n\n /**\n * When `node` is in the tree, in clip seconds: its document row's effective\n * span, or the nearest row ancestor's for a node a composite built. The canvas\n * spans the clip. `undefined` for a node outside this tree.\n */\n spanOf(node: Node): NodeSpan | undefined {\n for (let current: Node | null = node; current; current = current.parent) {\n if (current === this.canvas) return { start: 0, end: this.duration };\n const span = this._rowSpan(current);\n if (span) return { ...span };\n }\n return undefined;\n }\n\n /**\n * Visit every mounted node, parents first, with its span, its structural path\n * and its **owner key** — the nearest row's id, plus the path below that row for\n * a node a composite built. A UUID changes on every build and a path from the\n * root changes whenever an earlier sibling enters or leaves; this does neither.\n */\n forEachOwner(visit: (node: Node, ownerKey: string, span: NodeSpan, path: string) => void): void {\n const walk = (node: Node, row: string, below: string, span: NodeSpan, path: string): void => {\n if (!node.mounted) return;\n const own = node === this.canvas ? undefined : this._rowSpan(node);\n if (own) {\n row = node.id;\n below = \"\";\n span = own;\n }\n visit(node, below === \"\" ? row : `${row}/${below}`, span, path);\n const children = node._allChildren;\n for (let i = 0; i < children.length; i++) {\n walk(children[i], row, below === \"\" ? String(i) : `${below}.${i}`, span, nodePath(path, i));\n }\n };\n walk(this.canvas, ROOT_NODE_ID, \"\", { start: 0, end: this.duration }, \"\");\n }\n\n dispose(): void {\n for (const child of this.canvas.children) child.dispose();\n this.canvas.dispose();\n }\n\n private _clip: ClipDocument;\n private _doc: VisualDocument;\n private _duration: number;\n private readonly _timeline: ClipTimeline;\n private readonly _rows = new Map<string, { parentId: string | null; span: NodeSpan }>();\n\n private _indexRows(): void {\n this._rows.clear();\n const spans = effectiveSpans(this._doc.nodes);\n for (const spec of this._doc.nodes) {\n if (spec.id === ROOT_NODE_ID) continue;\n this._rows.set(spec.id, { parentId: spec.parentId, span: spans.get(spec.id)! });\n }\n }\n\n /**\n * `node`'s row span when a document row built it. The parent is checked as well\n * as the id, because a composite can hand its own id down to a child it builds.\n */\n private _rowSpan(node: Node): NodeSpan | undefined {\n const row = this._rows.get(node.id);\n if (!row) return undefined;\n const parent = node.parent;\n const placed = row.parentId === null || row.parentId === ROOT_NODE_ID\n ? parent === this.canvas\n : parent !== null && parent.id === row.parentId;\n return placed ? row.span : undefined;\n }\n}\n\nfunction lowered(clip: ClipDocument): VisualDocument {\n return clipDocument(clip);\n}\n", "import type { AssetRecord } from \"./record\";\nimport { assetKey, type AssetDecl } from \"./scope\";\n\nexport interface AssetSegment {\n key: string;\n decl: AssetDecl;\n startFrame: number;\n /** Inclusive. `Infinity` runs to the clip's end. */\n endFrame: number;\n}\n\nexport interface AssetDelta {\n /** Keys whose record appeared, disappeared, or changed window or content. */\n readonly keys: ReadonlySet<string>;\n}\n\ninterface OwnerSegments {\n declared: Map<string, AssetSegment[]>;\n /** Found missing at draw time rather than declared; cleared by the owner's next `setOwner`. */\n learned: Map<string, AssetSegment[]>;\n}\n\ninterface KeyEntry {\n record: AssetRecord;\n layout: boolean;\n}\n\nconst NO_OWNERS: ReadonlySet<string> = new Set();\n\n/**\n * One clip's asset windows, per owner, in clip-local frames.\n *\n * Owners replace their segments wholesale, and a key's record — the union window\n * over every owner that needs it — is recomputed only for the keys an update\n * touched. The records keep today's {@link AssetRecord} shape so the manager,\n * exporter and mixer read them unchanged.\n */\nexport class AssetIndex {\n constructor(frameCount: number) {\n this._frameCount = Math.max(0, frameCount);\n }\n\n setOwner(ownerKey: string, segments: readonly AssetSegment[]): AssetDelta {\n const touched = new Set<string>();\n const previous = this._owners.get(ownerKey);\n if (previous) this._unlink(ownerKey, previous, touched);\n\n const next: OwnerSegments = { declared: new Map(), learned: new Map() };\n for (const segment of segments) {\n if (!(segment.endFrame >= segment.startFrame)) continue;\n appendSegment(next.declared, { ...segment });\n }\n if (next.declared.size > 0) {\n this._owners.set(ownerKey, next);\n this._link(ownerKey, next, touched);\n } else {\n this._owners.delete(ownerKey);\n }\n return this._refresh(touched);\n }\n\n removeOwner(ownerKey: string): AssetDelta {\n const previous = this._owners.get(ownerKey);\n if (!previous) return { keys: new Set() };\n const touched = new Set<string>();\n this._unlink(ownerKey, previous, touched);\n this._owners.delete(ownerKey);\n return this._refresh(touched);\n }\n\n learn(ownerKey: string, decl: AssetDecl, frame: number): AssetDelta {\n const key = assetKey(decl);\n let owner = this._owners.get(ownerKey);\n if (!owner) {\n owner = { declared: new Map(), learned: new Map() };\n this._owners.set(ownerKey, owner);\n }\n const list = owner.learned.get(key) ?? [];\n const at = list.findIndex((s) => frame >= s.startFrame - 1 && frame <= s.endFrame + 1);\n if (at < 0) {\n list.push({ key, decl, startFrame: frame, endFrame: frame });\n } else {\n // Replaced rather than widened in place: `segmentsOf` hands these out.\n const hit = list[at];\n list[at] = {\n ...hit,\n startFrame: Math.min(hit.startFrame, frame),\n endFrame: Math.max(hit.endFrame, frame),\n };\n }\n owner.learned.set(key, list);\n let owners = this._byKey.get(key);\n if (!owners) this._byKey.set(key, (owners = new Set()));\n owners.add(ownerKey);\n return this._refresh(new Set([key]));\n }\n\n setFrameCount(frameCount: number): AssetDelta {\n const next = Math.max(0, frameCount);\n if (next === this._frameCount) return { keys: new Set() };\n this._frameCount = next;\n return this._refresh(new Set(this._byKey.keys()));\n }\n\n owners(key: string): ReadonlySet<string> {\n return this._byKey.get(key) ?? NO_OWNERS;\n }\n\n /** Declared segments, then learned ones. */\n segmentsOf(ownerKey: string): readonly AssetSegment[] {\n const owner = this._owners.get(ownerKey);\n if (!owner) return [];\n const out: AssetSegment[] = [];\n for (const list of owner.declared.values()) out.push(...list);\n for (const list of owner.learned.values()) out.push(...list);\n return out;\n }\n\n /** Declared segments only — what a partial re-declaration keeps the front of. */\n declaredSegmentsOf(ownerKey: string): readonly AssetSegment[] {\n const owner = this._owners.get(ownerKey);\n if (!owner) return [];\n const out: AssetSegment[] = [];\n for (const list of owner.declared.values()) out.push(...list);\n return out;\n }\n\n ownerKeys(): IterableIterator<string> {\n return this._owners.keys();\n }\n\n records(): ReadonlyMap<string, AssetRecord> {\n return this._records;\n }\n\n /** Fonts, and loaders any owner declared with `gate: \"layout\"`. */\n layoutGates(): readonly AssetRecord[] {\n if (this._layoutGates === null) {\n const gates: AssetRecord[] = [];\n for (const entry of this._entries.values()) {\n if (entry.layout) gates.push(entry.record);\n }\n this._layoutGates = gates;\n }\n return this._layoutGates;\n }\n\n private _frameCount: number;\n private readonly _owners = new Map<string, OwnerSegments>();\n private readonly _byKey = new Map<string, Set<string>>();\n private readonly _entries = new Map<string, KeyEntry>();\n private readonly _records = new Map<string, AssetRecord>();\n private _layoutGates: AssetRecord[] | null = null;\n\n private _link(ownerKey: string, owner: OwnerSegments, touched: Set<string>): void {\n for (const key of owner.declared.keys()) {\n let owners = this._byKey.get(key);\n if (!owners) this._byKey.set(key, (owners = new Set()));\n owners.add(ownerKey);\n touched.add(key);\n }\n }\n\n private _unlink(ownerKey: string, owner: OwnerSegments, touched: Set<string>): void {\n for (const map of [owner.declared, owner.learned]) {\n for (const key of map.keys()) {\n const owners = this._byKey.get(key);\n if (owners) {\n owners.delete(ownerKey);\n if (owners.size === 0) this._byKey.delete(key);\n }\n touched.add(key);\n }\n }\n }\n\n private _refresh(keys: ReadonlySet<string>): AssetDelta {\n const changed = new Set<string>();\n for (const key of keys) {\n const previous = this._entries.get(key);\n const next = this._compute(key);\n if (next === undefined) {\n if (previous === undefined) continue;\n this._entries.delete(key);\n this._records.delete(key);\n } else if (previous !== undefined && previous.layout === next.layout && sameRecord(previous.record, next.record)) {\n continue;\n } else {\n this._entries.set(key, next);\n this._records.set(key, next.record);\n }\n changed.add(key);\n }\n if (changed.size > 0) this._layoutGates = null;\n return { keys: changed };\n }\n\n private _compute(key: string): KeyEntry | undefined {\n const owners = this._byKey.get(key);\n if (!owners) return undefined;\n const last = this._frameCount - 1;\n let first: AssetSegment | undefined;\n let start = Infinity;\n let end = -Infinity;\n let layoutLoader = false;\n\n const visit = (list: AssetSegment[] | undefined): void => {\n if (!list) return;\n for (const segment of list) {\n const from = Math.max(0, segment.startFrame);\n const to = Math.min(last, segment.endFrame);\n if (to < from) continue;\n // The earliest segment speaks for the key.\n if (from < start) {\n start = from;\n first = segment;\n }\n if (to > end) end = to;\n if (segment.decl.type === \"loader\" && segment.decl.gate === \"layout\") layoutLoader = true;\n }\n };\n for (const ownerKey of owners) {\n const owner = this._owners.get(ownerKey);\n if (!owner) continue;\n visit(owner.declared.get(key));\n visit(owner.learned.get(key));\n }\n\n if (first === undefined) return undefined;\n return {\n record: recordOf(first.decl, start, end),\n layout: first.decl.type === \"font\" || layoutLoader,\n };\n }\n}\n\nfunction appendSegment(map: Map<string, AssetSegment[]>, segment: AssetSegment): void {\n const list = map.get(segment.key);\n if (list) list.push(segment);\n else map.set(segment.key, [segment]);\n}\n\nfunction recordOf(decl: AssetDecl, startFrame: number, endFrame: number): AssetRecord {\n switch (decl.type) {\n case \"image\":\n return { type: \"image\", startFrame, endFrame, src: decl.src };\n case \"video\":\n return {\n type: \"video\", startFrame, endFrame, src: decl.src,\n trimStart: decl.trimStart, trimEnd: decl.trimEnd,\n };\n case \"font\":\n return { type: \"font\", startFrame, endFrame, fontWeight: decl.weight, fontFamily: decl.family, src: decl.family };\n case \"loader\":\n return { type: \"loader\", src: decl.key, startFrame, endFrame, load: decl.load };\n }\n}\n\nfunction sameRecord(a: AssetRecord, b: AssetRecord): boolean {\n if (a.type !== b.type || a.src !== b.src || a.startFrame !== b.startFrame || a.endFrame !== b.endFrame) return false;\n switch (a.type) {\n case \"video\": {\n const v = b as typeof a;\n return a.trimStart === v.trimStart && a.trimEnd === v.trimEnd;\n }\n case \"font\":\n return a.fontWeight === (b as typeof a).fontWeight;\n case \"loader\":\n return a.load === (b as typeof a).load;\n default:\n return true;\n }\n}\n", "import type { AssetSegment } from \"@/assets/asset-index\";\nimport type { AssetCatalog } from \"@/assets/catalog\";\nimport { AssetDeclaration, type AssetDecl } from \"@/assets/scope\";\nimport type { NodeSpan } from \"@/document/types\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport { bindDetached, declareNode } from \"@/components/trees/node/node-walk\";\nimport {\n LAYOUT_SLOT,\n observeSlots,\n PRESENCE_PREFIX,\n slotLabel,\n STRUCTURE_SLOT,\n unobserved,\n type SlotObserver,\n} from \"@/props/observer\";\nimport type { PropSlot } from \"@/props/slot\";\nimport type { ClipInstance } from \"./clip-instance\";\nimport { frameTime, spanFrames } from \"./placement\";\n\nexport interface RefineOptions {\n fps: number;\n frameCount: number;\n catalog: AssetCatalog;\n /**\n * Limit the sweep to these owners, each from its frame on. A limited owner's\n * segments start no earlier than its frame: the caller keeps what it had before.\n */\n owners?: ReadonlyMap<string, number>;\n /** Like {@link owners}, for every owner a composite built below each row — keys a caller cannot know ahead. */\n below?: ReadonlyMap<string, number>;\n /** False only watches owners arrive, declaring nothing — for a caller that wants `onArrive` alone. */\n declare?: boolean;\n /** Binds a `Tex.surface` source before it declares. Defaults to the declaring node's scope. */\n bindSubtree?: (node: Node) => void;\n /** Once per owner, with the tree in the state the owner arrives in. */\n onArrive?: (node: Node, ownerKey: string, span: NodeSpan, frame: number) => void;\n onPhase?: (phase: \"evaluate\" | \"declare\") => void;\n}\n\nexport interface OwnerResult {\n ownerKey: string;\n nodeId: string | undefined;\n segments: AssetSegment[];\n /** Every slot any of its declarations read. */\n deps: ReadonlySet<PropSlot<unknown>>;\n /** A throwing declaration: the owner keeps no segments, and `prop` names the last slot it read. */\n error?: { message: string; stack?: string; prop?: string };\n}\n\nexport interface RefineResult {\n owners: Map<string, OwnerResult>;\n /** Dependency slot → the owners that read it. */\n readers: Map<PropSlot<unknown>, Set<string>>;\n}\n\n/**\n * Find each owner's asset segments, frame-exactly, without declaring every frame.\n *\n * A declaration is a pure function of the slots it reads, so an owner is declared\n * at arrival and again only on frames where something could have changed one of\n * those slots: every frame a command that writes one is active (which is what\n * catches a swap part-way through a command, and overlapping writers, since the\n * evaluation applies all of them), the first frame after it ends, and any frame\n * the tree's presence or structure changed under a read. A redeclaration whose\n * dependencies all hold the values they held last time reuses its result.\n *\n * Yields after each frame it evaluates. The instance must be built; the sweep\n * leaves it at an arbitrary time.\n */\nexport function* refineAssets(instance: ClipInstance, options: RefineOptions): Generator<void, RefineResult, void> {\n const sweep = new Sweep(instance, options);\n while (sweep.step()) yield;\n return sweep.result();\n}\n\n// ─── Sweep ────────────────────────────────────────────────────────────────────\n\ninterface Placed {\n id: string;\n /** The first frame the command is active on, and the last (`to < from` when it lands between frames). */\n from: number;\n to: number;\n writes: Set<PropSlot<unknown>>;\n}\n\ninterface Declared {\n frame: number;\n decls: ReadonlyMap<string, AssetDecl>;\n}\n\ninterface OwnerState {\n key: string;\n node: Node;\n span: NodeSpan;\n /** The first frame this sweep may declare the owner on. */\n from: number;\n present: boolean;\n arrivedAt: number;\n arrived: boolean;\n /** Closed presence intervals, inclusive. */\n intervals: [number, number][];\n history: Declared[];\n deps: PropSlot<unknown>[] | null;\n values: unknown[];\n /** A presence or structure slot it read was written: the values cannot tell. */\n stale: boolean;\n allDeps: Set<PropSlot<unknown>>;\n /** Indices of the placed commands whose frames are already queued for it. */\n scheduled: Set<number>;\n rounds: number;\n error?: OwnerResult[\"error\"];\n}\n\nconst MAX_REQUEUES = 3;\n\nclass Sweep {\n constructor(private readonly _instance: ClipInstance, private readonly _options: RefineOptions) {\n this._last = _options.frameCount - 1;\n\n const { owners, below } = _options;\n const limited = owners !== undefined || below !== undefined;\n if (this._last < 0 || (limited && (owners?.size ?? 0) + (below?.size ?? 0) === 0)) return;\n if (limited) {\n this._start = Infinity;\n for (const from of [...owners?.values() ?? [], ...below?.values() ?? []]) {\n this._start = Math.min(this._start, Math.max(0, from));\n }\n }\n if (this._start > this._last) return;\n this._walked = this._start - 1;\n\n this._placed = _instance.placedCommands().map((p) => ({\n id: p.spec.id,\n // An entrance writes its first frame from `holdFrom`, ahead of its start.\n ...this._activeFrames(p.holdFrom, p.start - p.holdFrom + p.duration),\n writes: new Set(p.writes),\n }));\n for (let i = 0; i < this._placed.length; i++) {\n for (const slot of this._placed[i].writes) this._addWriter(slot, i);\n }\n\n this._enqueue(this._start);\n for (const span of this._structureSpans()) {\n const frames = spanFrames(span, _options.fps, _options.frameCount);\n if (!frames) continue;\n this._structureFrame(frames.startFrame);\n this._structureFrame(frames.endFrame + 1);\n }\n for (const placed of this._placed) {\n if (![...placed.writes].some(isPseudo)) continue;\n this._forEachDueFrame(placed, this._start, (frame) => this._structureFrame(frame));\n }\n }\n\n /** Evaluate and declare the next due frame. False once nothing is left. */\n step(): boolean {\n const frame = heapPop(this._heap);\n if (frame === undefined) return false;\n this._queued.delete(frame);\n this._frame = frame;\n this._dueTaken = false;\n this._evaluate(frame);\n this._declareDue(frame);\n return this._heap.length > 0;\n }\n\n result(): RefineResult {\n const owners = new Map<string, OwnerResult>();\n const readers = new Map<PropSlot<unknown>, Set<string>>();\n for (const owner of this._owners.values()) {\n const intervals = owner.present\n ? [...owner.intervals, [owner.arrivedAt, Infinity] as [number, number]]\n : owner.intervals;\n owners.set(owner.key, {\n ownerKey: owner.key,\n nodeId: owner.node.id,\n segments: owner.error ? [] : segmentsOf(owner.history, intervals),\n deps: owner.allDeps,\n ...(owner.error && { error: owner.error }),\n });\n for (const slot of owner.allDeps) {\n let keys = readers.get(slot);\n if (!keys) readers.set(slot, (keys = new Set()));\n keys.add(owner.key);\n }\n }\n for (const key of this._options.owners?.keys() ?? []) {\n if (!owners.has(key)) owners.set(key, { ownerKey: key, nodeId: undefined, segments: [], deps: new Set() });\n }\n return { owners, readers };\n }\n\n private readonly _last: number;\n private _start = 0;\n /** Frames up to here have had their presence and structure reconciled. */\n private _walked = -1;\n private _placed: Placed[] = [];\n private readonly _writers = new Map<PropSlot<unknown>, number[]>();\n private readonly _heap: number[] = [];\n private readonly _queued = new Set<number>();\n private readonly _due = new Map<number, Set<OwnerState>>();\n private readonly _structureFrames = new Set<number>();\n private readonly _owners = new Map<string, OwnerState>();\n private readonly _readers = new Map<PropSlot<unknown>, Set<OwnerState>>();\n private readonly _pseudo = new Set<PropSlot<unknown>>();\n /** Owners re-queued from before the frame being processed. */\n private readonly _rewound = new Set<OwnerState>();\n private _frame = -1;\n /** Whether the frame being processed has handed out its due owners yet. */\n private _dueTaken = false;\n /** Read once: in Node, `process.env` is a lookup per access, and it sat on every declaration. */\n private readonly _dev = isDev();\n\n private readonly _presenceObserver: SlotObserver = {\n read: () => { },\n write: (slot) => { if (isPseudo(slot)) this._pseudo.add(slot); },\n };\n\n /**\n * The spans whose edges can move an owner in or out. Limited to named owners,\n * only their rows' — an effective span already folds in every ancestor's, and\n * visiting every row's edges would make one edited node cost a walk of the clip.\n */\n private _structureSpans(): NodeSpan[] {\n const { owners, below } = this._options;\n if (owners === undefined && below === undefined) return this._instance.rowSpans();\n const rows = new Set<string>(below?.keys());\n for (const key of owners?.keys() ?? []) {\n const slash = key.indexOf(\"/\");\n rows.add(slash < 0 ? key : key.slice(0, slash));\n }\n const spans: NodeSpan[] = [];\n for (const row of rows) {\n const span = this._instance.rowSpan(row);\n if (span) spans.push(span);\n }\n return spans;\n }\n\n private _activeFrames(start: number, duration: number): { from: number; to: number } {\n const { fps } = this._options;\n const end = start + Math.max(0, duration);\n let from = Math.max(0, Math.ceil(start * fps));\n while (from > 0 && frameTime(from - 1, fps, Infinity) >= start) from--;\n while (frameTime(from, fps, Infinity) < start) from++;\n let to = Math.max(-1, Math.floor(end * fps));\n while (frameTime(to + 1, fps, Infinity) <= end) to++;\n while (to >= 0 && frameTime(to, fps, Infinity) > end) to--;\n return { from, to };\n }\n\n private _evaluate(frame: number): void {\n this._options.onPhase?.(\"evaluate\");\n const seconds = frameTime(frame, this._options.fps, this._instance.duration);\n // Clocks move only where the tree can change, and before it does, so a node\n // is attached in the state it arrives in. Declarations must not read them.\n if (frame > this._walked && (frame === this._start || this._structureFrames.has(frame))) {\n this._instance.attach(seconds);\n }\n this._pseudo.clear();\n // Presence moves before the commands run, outside the observer `onWrite` reports through.\n observeSlots(this._presenceObserver, () => this._instance.evaluateAt(seconds, (index, slot) => {\n if (isPseudo(slot)) this._pseudo.add(slot);\n this._commandWrote(index, slot);\n }));\n\n // Presence only moves forward: a frame revisited for a re-queued owner reads\n // what it recorded the first time through.\n if (frame <= this._walked) return;\n if (frame === this._start || this._pseudo.size > 0) this._reconcile(frame);\n for (const slot of this._pseudo) {\n for (const owner of this._readers.get(slot) ?? []) {\n owner.stale = true;\n this._queueOwner(owner, frame);\n }\n }\n this._walked = frame;\n }\n\n /** Seed owners that are now mounted, and close the ones that are not. */\n private _reconcile(frame: number): void {\n const seen = new Set<OwnerState>();\n this._instance.forEachOwner((node, key, span) => {\n const from = this._limitOf(key);\n if (from === undefined) return;\n let owner = this._owners.get(key);\n if (!owner) {\n owner = {\n key, node, span, from,\n present: false, arrivedAt: -1, arrived: false,\n intervals: [], history: [], deps: null, values: [], stale: true,\n allDeps: new Set(), scheduled: new Set(), rounds: 0,\n };\n this._owners.set(key, owner);\n }\n seen.add(owner);\n if (owner.node !== node) {\n owner.node = node;\n owner.stale = true;\n if (owner.present) this._queueOwner(owner, Math.max(frame, owner.from));\n }\n if (owner.present) return;\n owner.present = true;\n owner.arrivedAt = Math.max(frame, owner.from);\n owner.stale = true;\n this._queueOwner(owner, owner.arrivedAt);\n if (!owner.arrived) {\n owner.arrived = true;\n this._options.onArrive?.(node, key, span, frame);\n }\n });\n for (const owner of this._owners.values()) {\n if (!owner.present || seen.has(owner)) continue;\n if (frame - 1 >= owner.arrivedAt) owner.intervals.push([owner.arrivedAt, frame - 1]);\n owner.present = false;\n }\n }\n\n /** The first frame `key` may be declared on, or `undefined` when the sweep is limited to others. */\n private _limitOf(key: string): number | undefined {\n const { owners, below } = this._options;\n if (owners === undefined && below === undefined) return this._start;\n let from = owners?.get(key);\n if (below) {\n for (let slash = key.indexOf(\"/\"); slash >= 0; slash = key.indexOf(\"/\", slash + 1)) {\n const row = below.get(key.slice(0, slash));\n if (row !== undefined && (from === undefined || row < from)) from = row;\n }\n }\n return from;\n }\n\n private _declareDue(frame: number): void {\n this._dueTaken = true;\n const owners = this._due.get(frame);\n this._due.delete(frame);\n if (this._options.declare === false) return;\n for (const owner of owners ?? []) {\n if (owner.error || this._rewound.has(owner) || !presentAt(owner, frame)) continue;\n if (!owner.stale && unchanged(owner)) continue;\n this._declare(owner, frame);\n }\n // A rewound owner comes back to this frame after the ones it missed, so its history stays in frame order.\n for (const owner of this._rewound) this._queueOwner(owner, frame);\n this._rewound.clear();\n }\n\n private _declare(owner: OwnerState, frame: number): void {\n this._options.onPhase?.(\"declare\");\n const node = owner.node;\n const reads = new Set<PropSlot<unknown>>();\n const writes: PropSlot<unknown>[] = [];\n let lastRead: PropSlot<unknown> | undefined;\n let readLayout = false;\n let readClock = false;\n const bind = this._options.bindSubtree ?? ((sub: Node) => bindDetached(node, sub));\n const declaration = new AssetDeclaration(this._options.catalog, {\n bindSubtree: (sub) => unobserved(() => bind(sub)),\n });\n\n try {\n observeSlots({\n read: (slot) => {\n reads.add(slot);\n lastRead = slot;\n if (slot._name === LAYOUT_SLOT) readLayout = true;\n },\n write: (slot) => { writes.push(slot); },\n clock: () => { readClock = true; },\n }, () => declareNode(node, declaration));\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n owner.error = { message: e.message, stack: e.stack, ...(lastRead && { prop: slotLabel(lastRead) }) };\n return;\n }\n\n if (this._dev) {\n const type = node.constructor.name;\n if (writes.length > 0) {\n const labels = [...new Set(writes.map(slotLabel))].join(\", \");\n warnOnce(`${type}:write:${labels}`,\n `[assets] ${type} wrote ${labels} while declaring its assets. A declaration is re-run only ` +\n `when something it read changes, so a write there is a frame-order dependency.`);\n }\n if (readLayout) {\n warnOnce(`${type}:layout`,\n `[assets] ${type}.declareAssets read layoutBounds. Declarations run without layout; ` +\n `decode size follows the draw, so declare the asset without a size.`);\n }\n if (readClock) {\n warnOnce(`${type}:clock`,\n `[assets] ${type}.declareAssets read time. Declarations are re-run only when a prop ` +\n `they read changes, so anything following the clock is missed between those frames.`);\n }\n }\n\n owner.stale = false;\n owner.deps = [...reads];\n owner.values = owner.deps.map((slot) => slot.get());\n for (const slot of reads) {\n if (owner.allDeps.has(slot)) continue;\n owner.allDeps.add(slot);\n let set = this._readers.get(slot);\n if (!set) this._readers.set(slot, (set = new Set()));\n set.add(owner);\n }\n\n const decls = declaration.declarations;\n const previous = owner.history[owner.history.length - 1];\n if (!previous || previous.frame < owner.arrivedAt || !sameDecls(previous.decls, decls)) {\n owner.history.push({ frame, decls });\n }\n this._scheduleWriters(owner, frame + 1);\n }\n\n private _scheduleWriters(owner: OwnerState, from: number): void {\n for (const slot of owner.deps ?? []) {\n const writers = this._writers.get(slot);\n if (!writers) continue;\n for (const index of writers) {\n if (owner.scheduled.has(index)) continue;\n owner.scheduled.add(index);\n this._forEachDueFrame(this._placed[index], from, (frame) => this._queueOwner(owner, frame));\n }\n }\n }\n\n /** Every frame a command is active on from `from`, and the first after it ends. */\n private _forEachDueFrame(placed: Placed, from: number, visit: (frame: number) => void): void {\n const first = Math.max(from, placed.from);\n const last = Math.min(this._last, placed.to);\n for (let frame = first; frame <= last; frame++) visit(frame);\n const after = Math.max(placed.to + 1, placed.from);\n if (after >= from && after <= this._last) visit(after);\n }\n\n /**\n * A command wrote a slot compile did not see it write. Its readers may have\n * missed every frame of it, so each is re-queued from where the command starts.\n */\n private _commandWrote(index: number, slot: PropSlot<unknown>): void {\n const placed = this._placed[index];\n if (!placed || placed.writes.has(slot)) return;\n placed.writes.add(slot);\n this._addWriter(slot, index);\n\n if (this._dev) {\n warnOnce(`command:${placed.id}:${slotLabel(slot)}`,\n `[assets] Command ${placed.id} wrote ${slotLabel(slot)} at frame ${this._frame}, which compile did not ` +\n `record it writing. Owners reading it are re-declared over the command's span.`);\n }\n for (const owner of this._readers.get(slot) ?? []) this._requeue(owner, Math.max(placed.from, owner.from), placed.id);\n }\n\n private _requeue(owner: OwnerState, from: number, commandId: string): void {\n if (owner.error) return;\n if (from > this._frame) {\n this._scheduleWriters(owner, from);\n return;\n }\n if (from === this._frame) {\n this._queueOwner(owner, from);\n return;\n }\n if (owner.rounds >= MAX_REQUEUES) {\n if (this._dev) {\n warnOnce(`requeue:${owner.key}`,\n `[assets] ${owner.key} was re-queued ${MAX_REQUEUES} times (last by command ${commandId}); ` +\n `its asset windows may be incomplete.`);\n }\n return;\n }\n owner.rounds++;\n owner.history = owner.history.filter((entry) => entry.frame < from);\n owner.stale = true;\n owner.scheduled.clear();\n // Every presence interval that starts in reach lost its arrival declaration too.\n this._queueOwner(owner, from);\n for (const [start] of owner.intervals) if (start > from) this._queueOwner(owner, start);\n if (owner.present && owner.arrivedAt > from) this._queueOwner(owner, owner.arrivedAt);\n // Presence and structure were only watched going forward; revisit their frames in reach.\n if (owner.deps?.some(isPseudo)) {\n for (const frame of this._structureFrames) {\n if (frame >= from && frame <= this._walked) this._queueOwner(owner, frame);\n }\n }\n this._rewound.add(owner);\n }\n\n private _addWriter(slot: PropSlot<unknown>, index: number): void {\n const list = this._writers.get(slot);\n if (list) list.push(index);\n else this._writers.set(slot, [index]);\n }\n\n private _structureFrame(frame: number): void {\n if (frame <= this._start || frame > this._last) return;\n this._structureFrames.add(frame);\n this._enqueue(frame);\n }\n\n private _queueOwner(owner: OwnerState, frame: number): void {\n if (frame > this._last) return;\n let set = this._due.get(frame);\n if (!set) this._due.set(frame, (set = new Set()));\n set.add(owner);\n this._enqueue(frame);\n }\n\n private _enqueue(frame: number): void {\n if (this._queued.has(frame) || (frame === this._frame && !this._dueTaken)) return;\n this._queued.add(frame);\n heapPush(this._heap, frame);\n }\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction isPseudo(slot: PropSlot<unknown>): boolean {\n return slot._name === STRUCTURE_SLOT || slot._name.startsWith(PRESENCE_PREFIX);\n}\n\nfunction presentAt(owner: OwnerState, frame: number): boolean {\n if (owner.present && frame >= owner.arrivedAt) return true;\n for (const [start, end] of owner.intervals) if (frame >= start && frame <= end) return true;\n return false;\n}\n\nfunction unchanged(owner: OwnerState): boolean {\n const deps = owner.deps;\n if (deps === null) return false;\n for (let i = 0; i < deps.length; i++) {\n if (!Object.is(deps[i].get(), owner.values[i])) return false;\n }\n return true;\n}\n\nfunction sameDecls(a: ReadonlyMap<string, AssetDecl>, b: ReadonlyMap<string, AssetDecl>): boolean {\n if (a.size !== b.size) return false;\n for (const [key, decl] of a) {\n const other = b.get(key);\n if (!other || !sameDecl(decl, other)) return false;\n }\n return true;\n}\n\n/** A font is its family: the record keeps the first weight, so a weight tween is one segment. */\nfunction sameDecl(a: AssetDecl, b: AssetDecl): boolean {\n switch (a.type) {\n case \"image\": return b.type === \"image\" && a.src === b.src;\n case \"video\": return b.type === \"video\" && a.src === b.src && a.trimStart === b.trimStart && a.trimEnd === b.trimEnd;\n case \"font\": return b.type === \"font\" && a.family === b.family;\n case \"loader\": return b.type === \"loader\" && a.key === b.key && a.load === b.load && a.gate === b.gate;\n }\n}\n\n/** An owner's declarations laid over its presence: each key open from the entry that declares it to the one that drops it. */\nfunction segmentsOf(history: readonly Declared[], intervals: readonly [number, number][]): AssetSegment[] {\n const out: AssetSegment[] = [];\n for (const [start, end] of intervals) {\n const open = new Map<string, AssetSegment>();\n for (const entry of history) {\n if (entry.frame < start || entry.frame > end) continue;\n for (const [key, segment] of open) {\n const next = entry.decls.get(key);\n if (next && sameDecl(segment.decl, next)) continue;\n out.push({ ...segment, endFrame: entry.frame - 1 });\n open.delete(key);\n }\n for (const [key, decl] of entry.decls) {\n if (!open.has(key)) open.set(key, { key, decl, startFrame: entry.frame, endFrame: end });\n }\n }\n for (const segment of open.values()) out.push({ ...segment, endFrame: end });\n }\n return out;\n}\n\nfunction isDev(): boolean {\n return process.env.NODE_ENV !== \"production\";\n}\n\nconst warned = new Set<string>();\n\nfunction warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n console.warn(message);\n}\n\nfunction heapPush(heap: number[], value: number): void {\n let i = heap.length;\n heap.push(value);\n while (i > 0) {\n const parent = (i - 1) >> 1;\n if (heap[parent] <= value) break;\n heap[i] = heap[parent];\n i = parent;\n }\n heap[i] = value;\n}\n\nfunction heapPop(heap: number[]): number | undefined {\n if (heap.length === 0) return undefined;\n const top = heap[0];\n const tail = heap.pop()!;\n if (heap.length === 0) return top;\n let i = 0;\n for (;;) {\n const left = 2 * i + 1;\n if (left >= heap.length) break;\n const right = left + 1;\n const child = right < heap.length && heap[right] < heap[left] ? right : left;\n if (heap[child] >= tail) break;\n heap[i] = heap[child];\n i = child;\n }\n heap[i] = tail;\n return top;\n}\n", "import { jsonEqual } from \"@/document/diff\";\nimport type { DocIndex } from \"@/document/doc-index\";\nimport type { TimelinePatch } from \"@/document/timeline-patch\";\nimport { ROOT_NODE_ID, type NodeSpec } from \"@/document/types\";\nimport { Node } from \"@/components/trees/node/node\";\nimport { LAYOUT_SLOT, PRESENCE_PREFIX, STRUCTURE_SLOT, VAR_PREFIX } from \"@/props/observer\";\nimport type { PropSlot } from \"@/props/slot\";\nimport type { ClipInstance } from \"./clip-instance\";\nimport { frameTime } from \"./placement\";\n\n/**\n * A slot named by what a rebuild of the clip reproduces — the owner key of the\n * node holding it and the prop's name — so what a declaration read survives the\n * instance it was read on.\n */\nexport type SlotId = string;\n\nconst HOSTED = \"\\u001f\";\nconst HOSTLESS = \"\\u001e\";\n/** A host no document row built: a detached `Tex.surface` source, say. */\nconst DETACHED = \"\\u001d\";\n\nexport function hostSlotId(ownerKey: string, name: string): SlotId {\n return ownerKey + HOSTED + name;\n}\n\nexport function hostlessSlotId(name: string): SlotId {\n return HOSTLESS + name;\n}\n\nfunction hostOf(id: SlotId): string | undefined {\n if (id.startsWith(HOSTLESS) || id.startsWith(DETACHED)) return undefined;\n return id.slice(0, id.lastIndexOf(HOSTED));\n}\n\nfunction nameOf(id: SlotId): string {\n if (id.startsWith(HOSTLESS) || id.startsWith(DETACHED)) return id.slice(1);\n return id.slice(id.lastIndexOf(HOSTED) + 1);\n}\n\n/** Names slots against one instance. */\nexport class SlotNamer {\n constructor(private readonly _instance: ClipInstance) { }\n\n idOf(slot: PropSlot<unknown>): SlotId {\n const host = slot._host;\n if (host === null) return HOSTLESS + slot._name;\n let key = this._keys.get(host);\n if (key === undefined) {\n key = host instanceof Node ? this._instance.ownerKeyOf(host) ?? null : null;\n this._keys.set(host, key);\n }\n return key === null ? DETACHED + slot._name : hostSlotId(key, slot._name);\n }\n\n idsOf(slots: Iterable<PropSlot<unknown>>): SlotId[] {\n const out: SlotId[] = [];\n for (const slot of slots) out.push(this.idOf(slot));\n return out;\n }\n\n private readonly _keys = new Map<object, string | null>();\n}\n\n/** Every row prefix of an owner key: `a/0.1` is below `a`. A row id may itself hold a slash. */\nfunction rowsAbove(key: string): string[] {\n const out: string[] = [];\n for (let slash = key.indexOf(\"/\"); slash >= 0; slash = key.indexOf(\"/\", slash + 1)) out.push(key.slice(0, slash));\n return out;\n}\n\nfunction addTo<K, V>(map: Map<K, Set<V>>, key: K, value: V): void {\n let set = map.get(key);\n if (!set) map.set(key, (set = new Set()));\n set.add(value);\n}\n\nfunction removeFrom<K, V>(map: Map<K, Set<V>>, key: K, value: V): boolean {\n const set = map.get(key);\n if (!set) return false;\n set.delete(value);\n if (set.size > 0) return false;\n map.delete(key);\n return true;\n}\n\nconst NONE: ReadonlySet<never> = new Set();\n\n/** What each owner's declarations read, and the reverse: who reads each slot. */\nexport class OwnerDependencies {\n set(ownerKey: string, slots: Iterable<SlotId>): void {\n this.remove(ownerKey);\n const own = new Set(slots);\n this._deps.set(ownerKey, own);\n for (const row of rowsAbove(ownerKey)) addTo(this._ownersBelow, row, ownerKey);\n for (const id of own) {\n if (!this._readers.has(id)) this._index(id);\n addTo(this._readers, id, ownerKey);\n }\n }\n\n remove(ownerKey: string): void {\n const own = this._deps.get(ownerKey);\n if (!own) return;\n this._deps.delete(ownerKey);\n for (const row of rowsAbove(ownerKey)) removeFrom(this._ownersBelow, row, ownerKey);\n for (const id of own) {\n if (removeFrom(this._readers, id, ownerKey)) this._unindex(id);\n }\n }\n\n has(ownerKey: string): boolean {\n return this._deps.has(ownerKey);\n }\n\n depsOf(ownerKey: string): ReadonlySet<SlotId> {\n return this._deps.get(ownerKey) ?? NONE;\n }\n\n readersOf(id: SlotId): ReadonlySet<string> {\n return this._readers.get(id) ?? NONE;\n }\n\n /** Owners a composite built below `row`. */\n ownersBelow(row: string): ReadonlySet<string> {\n return this._ownersBelow.get(row) ?? NONE;\n }\n\n /** Read slots `ownerKey`'s node holds. */\n slotsHostedBy(ownerKey: string): ReadonlySet<SlotId> {\n return this._byHost.get(ownerKey) ?? NONE;\n }\n\n /** Read slots held by anything a composite built below `row`. */\n *slotsHostedBelow(row: string): Generator<SlotId> {\n for (const host of this._hostsBelow.get(row) ?? NONE) yield* this.slotsHostedBy(host);\n }\n\n slotsNamed(name: string): ReadonlySet<SlotId> {\n return this._byName.get(name) ?? NONE;\n }\n\n private readonly _deps = new Map<string, Set<SlotId>>();\n private readonly _readers = new Map<SlotId, Set<string>>();\n private readonly _ownersBelow = new Map<string, Set<string>>();\n private readonly _byHost = new Map<string, Set<SlotId>>();\n private readonly _hostsBelow = new Map<string, Set<string>>();\n private readonly _byName = new Map<string, Set<SlotId>>();\n\n private _index(id: SlotId): void {\n addTo(this._byName, nameOf(id), id);\n const host = hostOf(id);\n if (host === undefined) return;\n addTo(this._byHost, host, id);\n for (const row of rowsAbove(host)) addTo(this._hostsBelow, row, host);\n }\n\n private _unindex(id: SlotId): void {\n removeFrom(this._byName, nameOf(id), id);\n const host = hostOf(id);\n if (host === undefined) return;\n if (removeFrom(this._byHost, host, id)) {\n for (const row of rowsAbove(host)) removeFrom(this._hostsBelow, row, host);\n }\n }\n}\n\n/** A placed command's start and what it writes, by slot id. */\nexport interface PlacedWrites {\n start: number;\n writes: readonly SlotId[];\n}\n\nexport interface DirtyInput {\n patch: TimelinePatch;\n deps: OwnerDependencies;\n /**\n * Placed commands before the patch and after it, keyed by their recorded write\n * set — a set on both sides belongs to a command the patch did not rebuild.\n */\n before: ReadonlyMap<object, PlacedWrites>;\n after: ReadonlyMap<object, PlacedWrites>;\n fps: number;\n /** The prop names the row's node registers, after the patch. */\n propsOf(rowId: string): ReadonlySet<string> | undefined;\n /** Whether the row's node, after the patch, holds children it built for itself. */\n buildsChildren(rowId: string): boolean;\n isContextProvider(type: string): boolean;\n}\n\nexport interface DirtyOwners {\n /** Owners to declare again, each from its frame. */\n owners: Map<string, number>;\n /** Rows whose composite-built owners are all declared again, from the frame. */\n below: Map<string, number>;\n /** Rows gone from the clip; they and everything below them leave the index. */\n removed: Set<string>;\n /** Of the above, owners and rows declared from no later than they arrive — their audio is redone too. */\n arrivalOwners: Set<string>;\n arrivalBelow: Set<string>;\n}\n\n/**\n * The owners an applied patch can have changed the declarations of, each from\n * the first frame it can differ on.\n *\n * Every rule reads the recorded dependencies, so an edit no declaration read —\n * a position, a size, a tween of either — names nobody. Rules err towards naming\n * an owner: one named needlessly costs its declarations over its frames, one\n * missed keeps a window a fresh build would not have.\n */\nexport function dirtyOwners(input: DirtyInput): DirtyOwners {\n const { patch, deps, fps } = input;\n const { prev, next, diff } = patch;\n const out: DirtyOwners = {\n owners: new Map(),\n below: new Map(),\n removed: new Set(),\n arrivalOwners: new Set(),\n arrivalBelow: new Set(),\n };\n\n const lower = (map: Map<string, number>, key: string, frame: number) => {\n const at = map.get(key);\n if (at === undefined || frame < at) map.set(key, frame);\n };\n const owner = (key: string, frame: number, arrival: boolean) => {\n lower(out.owners, key, frame);\n if (arrival) out.arrivalOwners.add(key);\n };\n const readers = (id: SlotId, frame: number, arrival: boolean) => {\n for (const key of deps.readersOf(id)) owner(key, frame, arrival);\n };\n const below = (row: string, frame: number) => {\n if (!input.buildsChildren(row) && deps.ownersBelow(row).size === 0) return;\n lower(out.below, row, frame);\n out.arrivalBelow.add(row);\n };\n const startOf = (index: DocIndex, id: string): number => {\n const span = index.effSpan(id);\n return span ? firstFrameAt(span.start, fps) : Infinity;\n };\n const placement = (id: string, frame: number) => {\n readers(hostlessSlotId(PRESENCE_PREFIX + id), frame, true);\n readers(hostSlotId(id, STRUCTURE_SLOT), frame, true);\n for (const index of [prev, next]) {\n const spec = index.nodes.get(id);\n if (spec) readers(hostSlotId(spec.parentId ?? ROOT_NODE_ID, STRUCTURE_SLOT), frame, true);\n }\n };\n const hosted = (row: string, frame: number, names: ReadonlySet<string> | null) => {\n for (const id of deps.slotsHostedBy(row)) {\n const name = nameOf(id);\n if (names === null || names.has(name) || name === STRUCTURE_SLOT) readers(id, frame, true);\n }\n for (const id of deps.slotsHostedBelow(row)) readers(id, frame, true);\n };\n\n for (const [writes, placed] of input.before) {\n if (input.after.has(writes)) continue;\n const frame = firstFrameAt(placed.start, fps);\n for (const id of placed.writes) readers(id, frame, false);\n }\n for (const [writes, placed] of input.after) {\n if (input.before.has(writes)) continue;\n const frame = firstFrameAt(placed.start, fps);\n for (const id of placed.writes) readers(id, frame, false);\n }\n\n for (const id of diff.variables.changed) readers(hostlessSlotId(VAR_PREFIX + id), 0, true);\n if (patch.layoutChanged) {\n for (const id of deps.slotsNamed(LAYOUT_SLOT)) readers(id, 0, true);\n }\n for (const parent of diff.nodes.reorderedParents) readers(hostSlotId(parent, STRUCTURE_SLOT), 0, true);\n\n for (const id of diff.nodes.removed) {\n const from = startOf(prev, id);\n out.removed.add(id);\n placement(id, from);\n hosted(id, from, null);\n }\n for (const id of diff.nodes.added) {\n const from = startOf(next, id);\n if (from === Infinity) continue;\n owner(id, from, true);\n below(id, from);\n placement(id, from);\n }\n for (const id of next.nodes.keys()) {\n if (id === ROOT_NODE_ID || !prev.nodes.has(id)) continue;\n const a = prev.effSpan(id);\n const b = next.effSpan(id);\n if (a?.start === b?.start && a?.end === b?.end) continue;\n const from = Math.min(startOf(prev, id), startOf(next, id));\n if (from === Infinity) continue;\n owner(id, from, true);\n below(id, from);\n placement(id, from);\n }\n\n const changedRows = new Set([...patch.reinstantiate, ...diff.nodes.added, ...diff.nodes.removed]);\n for (const id of patch.reinstantiate) {\n const names = changedProps(id, input, changedRows);\n hosted(id, 0, names);\n below(id, 0);\n for (const key of [id, ...deps.ownersBelow(id)]) {\n for (const dep of deps.depsOf(key)) {\n if (!dep.startsWith(DETACHED)) continue;\n owner(key, 0, true);\n break;\n }\n }\n if (diff.nodes.moved.has(id)) placement(id, 0);\n }\n for (const id of patch.inPlace) {\n const names = changedSlots(prev.nodes.get(id)!, next.nodes.get(id)!, input.propsOf(id) ?? new Set());\n for (const slot of deps.slotsHostedBy(id)) {\n if (names === null || names.has(nameOf(slot))) readers(slot, 0, true);\n }\n }\n if (diff.rootChanged) {\n const props = input.propsOf(ROOT_NODE_ID);\n hosted(ROOT_NODE_ID, 0, props ? changedSlots(prev.nodes.get(ROOT_NODE_ID)!, next.nodes.get(ROOT_NODE_ID)!, props) : null);\n }\n return out;\n}\n\n/**\n * The props a re-instantiated row's edit changed, or `null` when every slot it\n * holds must be taken as changed: a new type, a new place, a new context above\n * it, or a prop that is not a slot of its own and so reaches its state some\n * other way.\n */\nfunction changedProps(id: string, input: DirtyInput, changedRows: ReadonlySet<string>): ReadonlySet<string> | null {\n const { prev, next, diff } = input.patch;\n const a = prev.nodes.get(id);\n const b = next.nodes.get(id);\n if (!a || !b || !diff.nodes.respec.has(id) || diff.nodes.moved.has(id) || a.type !== b.type || a.key !== b.key) return null;\n for (const index of [prev, next]) {\n if (providerChangedAbove(index, id, changedRows, input)) return null;\n }\n const props = input.propsOf(id);\n return props ? changedSlots(a, b, props) : null;\n}\n\n/** The props that differ between two rows, or `null` when one of them is not a slot of `slots`. */\nfunction changedSlots(a: NodeSpec, b: NodeSpec, slots: ReadonlySet<string>): ReadonlySet<string> | null {\n const names = new Set<string>();\n for (const key of new Set([...Object.keys(a.props), ...Object.keys(b.props)])) {\n if (jsonEqual(a.props[key], b.props[key])) continue;\n if (!slots.has(key)) return null;\n names.add(key);\n }\n return names;\n}\n\nfunction providerChangedAbove(index: DocIndex, id: string, changed: ReadonlySet<string>, input: DirtyInput): boolean {\n const seen = new Set<string>([id]);\n let parentId = index.nodes.get(id)?.parentId ?? null;\n while (parentId !== null && parentId !== ROOT_NODE_ID && !seen.has(parentId)) {\n seen.add(parentId);\n const spec = index.nodes.get(parentId);\n if (!spec) return false;\n if (changed.has(parentId) && input.isContextProvider(spec.type)) return true;\n parentId = spec.parentId;\n }\n return false;\n}\n\n/** The first frame whose time reaches `seconds`. */\nexport function firstFrameAt(seconds: number, fps: number): number {\n if (!(seconds > 0)) return 0;\n if (!Number.isFinite(seconds)) return Infinity;\n let frame = Math.max(0, Math.ceil(seconds * fps));\n while (frame > 0 && frameTime(frame - 1, fps, Infinity) >= seconds) frame--;\n while (frameTime(frame, fps, Infinity) < seconds) frame++;\n return frame;\n}\n", "import type { AudioRequest } from \"@/attributes/audio/request\";\n\n/** Every owner's declared audio, kept apart so one owner can change without redeclaring the rest. */\nexport class AudioIndex {\n /** Replace `ownerKey`'s requests. Returns whether that changed anything. */\n setOwner(ownerKey: string, requests: AudioRequest[]): boolean {\n if (requests.length === 0) return this.removeOwner(ownerKey);\n const prior = this._owners.get(ownerKey);\n if (prior && sameValue(prior, requests)) return false;\n this._owners.set(ownerKey, requests);\n return true;\n }\n\n removeOwner(ownerKey: string): boolean {\n return this._owners.delete(ownerKey);\n }\n\n /** Every request, owner by owner in the order each was first declared. */\n requests(): AudioRequest[] {\n const out: AudioRequest[] = [];\n for (const requests of this._owners.values()) out.push(...requests);\n return out;\n }\n\n private readonly _owners = new Map<string, AudioRequest[]>();\n}\n\nfunction sameValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key of keys) {\n if (!sameValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n }\n return true;\n}\n", "import { AssetIndex, type AssetSegment } from \"@/assets/asset-index\";\nimport type { AssetRecord } from \"@/assets/record\";\nimport type { AssetDecl } from \"@/assets/scope\";\nimport type { AudioBusStop, AudioRequest } from \"@/attributes/audio/request\";\nimport { isContextProvider } from \"@/document/command-traits\";\nimport { diffClip, jsonEqual } from \"@/document/diff\";\nimport type { ProjectDocument, Track } from \"@/document/project\";\nimport type { TimelinePatch } from \"@/document/timeline-patch\";\nimport type { NodeSpan } from \"@/document/types\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport type { PropHost } from \"@/props/host\";\nimport type { PropSlot } from \"@/props/slot\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport { now, yieldToScheduler } from \"@/util/scheduler\";\nimport { refineAssets, type OwnerResult, type RefineResult } from \"./asset-refine\";\nimport { dirtyOwners, OwnerDependencies, SlotNamer, type DirtyOwners, type PlacedWrites, type SlotId } from \"./asset-update\";\nimport { AudioIndex } from \"./audio-index\";\nimport { requestOf } from \"@/attributes/audio/schedule\";\nimport { busPathOf, busPathTo, findBusById, NodeAudio } from \"@/components/trees/audio/node-audio\";\n\n/** The owner key the placed commands' sounds go under. */\nconst COMMAND_AUDIO = \"@commands\";\nimport { ClipInstance, type RuntimeScope } from \"./clip-instance\";\nimport type { PlacedSound } from \"@/document/timeline\";\nimport { placeTracks, spanFrames, trackFrameCount, type TrackSpan } from \"./placement\";\nimport type { BuildError, AssetTimelineProfile, TrackAssets, TrackAssetsProfile } from \"./asset-timeline\";\n\n/** Half a 60 Hz frame, leaving the other half for input handling and paint. */\nexport const DEFAULT_PRECOMP_BUDGET_MS = 8;\n\nexport interface ClipStoreOptions {\n profile?: AssetTimelineProfile;\n /** False declares no assets: owners are only watched arriving, for their audio. */\n assets?: boolean;\n /** False, with `assets` false too, refines nothing — the store only builds. */\n audio?: boolean;\n /** False disposes an instance as soon as its refinement lands, for a caller that never draws. */\n keepInstances?: boolean;\n /** Whether a layout gate is resident. Absent takes every gate as resident. */\n isReady?: (key: string) => boolean;\n}\n\nexport interface StoreRunOptions {\n /** Wall-clock ms before yielding; `0` yields between every frame evaluated. */\n budgetMs?: number;\n /** Polled after every yield; true leaves the build parked where it is. */\n isCancelled?: () => boolean;\n /** Called each time a track's refinement lands. */\n onProgress?: () => void;\n}\n\n/** What one {@link ClipStore.setProject} did to the tracks it kept. */\nexport interface StoreUpdate {\n /** Asset keys whose clip-local record changed, per track refined in place. */\n deltas: Map<string, ReadonlySet<string>>;\n /** Tracks whose built state was thrown away and starts again. */\n rebuilt: string[];\n}\n\ntype Refinement = \"assets\" | \"audio\" | \"none\";\n\ninterface Entry {\n track: Track;\n frameCount: number;\n instance: ClipInstance | null;\n /** A build or refinement parked between slices. */\n steps: Generator<void, void, void> | null;\n running: boolean;\n /** Replaced or disposed while it was running; torn down once it returns. */\n discarded: boolean;\n profile: TrackAssetsProfile | undefined;\n /** The refinement for this clip and duration, once it has landed. */\n discovered: TrackAssets | null;\n errors: BuildError[];\n index: AssetIndex;\n audio: AudioIndex;\n /** The owners the placed commands' sounds last went under. */\n commandAudio: Set<string>;\n /** The placed commands' sounds by owner, for one refinement; dropped when the track's audio is published. */\n commandSounds: Map<string, PlacedSound[]> | null;\n deps: OwnerDependencies;\n assetDeps: Map<string, readonly SlotId[]>;\n audioDeps: Map<string, readonly SlotId[]>;\n ownerErrors: Map<string, BuildError>;\n audioErrors: Map<string, BuildError>;\n /** What the last build or patch stepped around: placeholders and skipped commands. */\n issues: BuildError[];\n /** Building threw: nothing draws until the clip changes or the track is rebuilt. */\n failure: BuildError | null;\n refineError: BuildError | null;\n /** Bumped whenever something other than an evaluator moved the instance. */\n generation: number;\n writes: WeakMap<ReadonlySet<PropSlot<unknown>>, PlacedWrites>;\n /** Gate keys compile measured, or refinement found, before they were resident. */\n unready: Set<string>;\n}\n\n/**\n * One build per track: the instance a track's clip compiles to, the asset index\n * its refinement produced, and its audio — shared by whoever needs them, so the\n * evaluator draws the tree discovery refined rather than building one of its own.\n *\n * A build runs as a generator so a background driver can park it between slices;\n * whoever needs the track sooner drains the parked build instead of starting\n * another. Dependencies are kept by {@link SlotId}, which a rebuild reproduces,\n * so an instance can be thrown away and built again without refining.\n */\nexport class ClipStore {\n constructor(project: ProjectDocument, private readonly _scope: RuntimeScope, options: ClipStoreOptions = {}) {\n this._options = options;\n this._refine = options.assets !== false ? \"assets\" : options.audio !== false ? \"audio\" : \"none\";\n this._project = project;\n for (const track of project.tracks) this._entries.set(track.id, this._fresh(track));\n this._spans = placeTracks(project.tracks, _scope.fps);\n }\n\n get project(): ProjectDocument {\n return this._project;\n }\n\n get tracks(): readonly Track[] {\n return this._project.tracks;\n }\n\n get spans(): readonly TrackSpan[] {\n return this._spans;\n }\n\n /** Bumped by every change a published result could show. */\n get version(): number {\n return this._version;\n }\n\n get profile(): AssetTimelineProfile | undefined {\n return this._options.profile;\n }\n\n /**\n * Take a new document. A track holding the same clip keeps everything; a changed\n * clip whose built tree patches in place re-declares only the owners the patch\n * can have changed; anything else starts again. A theme change starts every\n * track again, since colours resolve against it as props are written.\n */\n setProject(next: ProjectDocument): StoreUpdate {\n const update: StoreUpdate = { deltas: new Map(), rebuilt: [] };\n if (this._disposed || next === this._project) return update;\n const themeChanged = !jsonEqual(this._project.theme, next.theme);\n this._project = next;\n\n const previous = this._entries;\n this._entries = new Map();\n for (const track of next.tracks) {\n const old = previous.get(track.id);\n const entry = old && !themeChanged ? this._reconcile(old, track, update) : this._fresh(track);\n if (old && entry !== old) update.rebuilt.push(track.id);\n this._entries.set(track.id, entry);\n }\n let changed = update.rebuilt.length > 0 || previous.size !== this._entries.size;\n for (const [id, old] of previous) {\n if (this._entries.get(id) === old) continue;\n this._discard(old);\n changed = true;\n }\n const spans = placeTracks(next.tracks, this._scope.fps);\n if (changed || !sameSpans(spans, this._spans)) this._version++;\n this._spans = spans;\n return update;\n }\n\n /**\n * Start every track again against the same document.\n *\n * For a change the document does not carry: the catalog these clips build\n * against gained an entry, so a track that failed for want of it, or measured\n * against the old size, has to be built again. {@link setProject} cannot say\n * so, since it compares documents and this one has not changed.\n */\n reset(): void {\n if (this._disposed) return;\n const previous = this._entries;\n this._entries = new Map();\n for (const track of this._project.tracks) this._entries.set(track.id, this._fresh(track));\n for (const old of previous.values()) this._discard(old);\n this._version++;\n }\n\n /** `trackId`'s built tree, building it — or draining its parked build — first. `null` when building throws. */\n ensureBuilt(trackId: string): ClipInstance | null {\n const entry = this._entries.get(trackId);\n if (!entry || entry.running || this._disposed) return null;\n if (entry.steps) this._drain(entry);\n if (!entry.instance && !entry.failure) {\n this._start(entry, true, this._refine !== \"none\" && !entry.discovered);\n this._drain(entry);\n }\n return entry.instance;\n }\n\n /** Build and refine `trackId` now, unless it already has been. */\n discover(trackId: string): void {\n const entry = this._entries.get(trackId);\n if (!entry || entry.running || this._disposed) return;\n if (this._refine === \"none\") {\n this.ensureBuilt(trackId);\n return;\n }\n if (entry.discovered) return;\n if (!entry.steps) this._start(entry, !entry.instance, true);\n this._drain(entry);\n }\n\n /**\n * Discover every undiscovered track, earliest start first, yielding between\n * slices. A build whose track changed while it was parked is dropped; a\n * cancelled one stays parked for whoever needs the track next.\n */\n async runAsync(options: StoreRunOptions = {}): Promise<void> {\n const { budgetMs = DEFAULT_PRECOMP_BUDGET_MS, isCancelled, onProgress } = options;\n if (this._refine === \"none\") return;\n for (;;) {\n if (this._disposed || isCancelled?.()) return;\n const entry = this._nextUndiscovered();\n if (!entry) return;\n if (!entry.steps) this._start(entry, !entry.instance, true);\n\n let deadline = now() + budgetMs;\n let finished = this._step(entry);\n while (!finished) {\n if (now() >= deadline) {\n entry.profile?.suspend();\n await yieldToScheduler();\n if (this._disposed || isCancelled?.()) return;\n if (entry.discarded || !entry.steps) break;\n entry.profile?.resume();\n deadline = now() + budgetMs;\n }\n finished = this._step(entry);\n }\n if (!entry.discarded && entry.discovered) onProgress?.();\n }\n }\n\n /** The built tree, if there is one that is not mid-build. */\n instanceOf(trackId: string): ClipInstance | null {\n const entry = this._entries.get(trackId);\n return entry && !entry.steps ? entry.instance : null;\n }\n\n generationOf(trackId: string): number {\n return this._entries.get(trackId)?.generation ?? -1;\n }\n\n failed(trackId: string): boolean {\n return !!this._entries.get(trackId)?.failure;\n }\n\n isDiscovered(trackId: string): boolean {\n return !!this._entries.get(trackId)?.discovered;\n }\n\n /** What refinement found, in clip-local frames; `undefined` until it has. */\n trackAssets(trackId: string): TrackAssets | undefined {\n return this._entries.get(trackId)?.discovered ?? undefined;\n }\n\n errorsOf(trackId: string): readonly BuildError[] {\n const entry = this._entries.get(trackId);\n return entry?.discovered ? entry.errors : [];\n }\n\n /** Owners whose segments hold `key`. */\n ownersOf(trackId: string, key: string): ReadonlySet<string> {\n return this._entries.get(trackId)?.index.owners(key) ?? new Set();\n }\n\n /** Records that must be resident before `trackId` measures. */\n layoutGates(trackId: string): readonly AssetRecord[] {\n const entry = this._entries.get(trackId);\n return entry?.discovered ? entry.index.layoutGates() : [];\n }\n\n /** Record a segment the draw found missing. Whether that changed the track's records. */\n learn(trackId: string, ownerKey: string, decl: AssetDecl, localFrame: number): boolean {\n const entry = this._entries.get(trackId);\n if (!entry?.discovered) return false;\n if (entry.index.learn(ownerKey, decl, localFrame).keys.size === 0) return false;\n return this._refresh(entry);\n }\n\n /**\n * Rebuild every listed track whose compile measured a layout gate before it was\n * resident, now that one of those gates is. A gate becomes resident once, so a\n * track rebuilds at most once per gate. Whether anything was rebuilt.\n *\n * Every such track, not only one with a layout-reading command: a node may keep\n * what it measured (`code` caches its token advances and layouts), and nothing\n * but a fresh tree drops metrics taken against the fallback face.\n */\n settleGates(trackIds: Iterable<string>): boolean {\n const isReady = this._options.isReady;\n if (!isReady) return false;\n let rebuilt = false;\n for (const id of trackIds) {\n const entry = this._entries.get(id);\n if (!entry || entry.unready.size === 0 || !entry.instance || entry.steps || entry.running) continue;\n const gates = entry.discovered ? new Set(entry.index.layoutGates().map((record) => record.src)) : null;\n let arrived = false;\n for (const key of [...entry.unready]) {\n if (gates && !gates.has(key)) {\n // Nothing loads a face no owner declared, so waiting on it is waiting forever.\n entry.unready.delete(key);\n } else if (isReady(key)) {\n arrived = true;\n }\n }\n if (!arrived) continue;\n this._rebuildInstance(entry);\n rebuilt = true;\n }\n return rebuilt;\n }\n\n /**\n * Throw `trackId`'s tree away so the next {@link ensureBuilt} builds it fresh,\n * keeping what refinement found — for an editor override written straight onto\n * a live prop, which the timeline would never restore.\n */\n rebuild(trackId: string): void {\n const entry = this._entries.get(trackId);\n if (!entry || entry.running || entry.steps) return;\n entry.instance?.dispose();\n entry.instance = null;\n entry.unready.clear();\n entry.generation++;\n if (entry.failure) {\n entry.failure = null;\n entry.discovered = null;\n this._version++;\n }\n }\n\n /** Dispose `trackId`'s tree, keeping its index and audio; a later {@link ensureBuilt} builds it without refining. */\n release(trackId: string): void {\n const entry = this._entries.get(trackId);\n if (!entry || !entry.instance || entry.running || entry.steps || !entry.discovered) return;\n entry.instance.dispose();\n entry.instance = null;\n entry.generation++;\n }\n\n /** Release every track further than `horizon` frames from `frame`. */\n trim(frame: number, horizon: number): void {\n for (let i = 0; i < this._spans.length; i++) {\n const span = this._spans[i];\n if (span.endFrame >= frame - horizon && span.startFrame <= frame + horizon) continue;\n this.release(span.id);\n }\n }\n\n dispose(): void {\n this._disposed = true;\n for (const entry of this._entries.values()) this._discard(entry);\n }\n\n private readonly _options: ClipStoreOptions;\n private readonly _refine: Refinement;\n private _project: ProjectDocument;\n private _entries = new Map<string, Entry>();\n private _spans: TrackSpan[];\n private _version = 0;\n private _disposed = false;\n\n private _fresh(track: Track): Entry {\n const frameCount = trackFrameCount(track.duration, this._scope.fps);\n return {\n track,\n frameCount,\n instance: null,\n steps: null,\n running: false,\n discarded: false,\n profile: undefined,\n discovered: null,\n errors: [],\n index: new AssetIndex(frameCount),\n audio: new AudioIndex(),\n commandAudio: new Set(),\n commandSounds: null,\n deps: new OwnerDependencies(),\n assetDeps: new Map(),\n audioDeps: new Map(),\n ownerErrors: new Map(),\n audioErrors: new Map(),\n issues: [],\n failure: null,\n refineError: null,\n generation: 0,\n writes: new WeakMap(),\n unready: new Set(),\n };\n }\n\n private _reconcile(entry: Entry, track: Track, update: StoreUpdate): Entry {\n const frameCount = trackFrameCount(track.duration, this._scope.fps);\n if (entry.track.clip === track.clip) return this._resize(entry, track, frameCount);\n if (entry.steps || entry.failure) return this._fresh(track);\n if (!entry.instance) {\n return entry.discovered && diffClip(entry.track.clip, track.clip).identical\n ? this._resize(entry, track, frameCount)\n : this._fresh(track);\n }\n\n const instance = entry.instance;\n let patch: TimelinePatch | null;\n try {\n patch = instance.planUpdate(track.clip);\n } catch {\n patch = null;\n }\n if (!patch) return this._fresh(track);\n // Nothing to apply; the tree keeps the document it was built from, which diffs the same.\n if (patch.diff.identical) return this._resize(entry, track, frameCount);\n\n const refined = entry.discovered !== null && this._refine !== \"none\";\n const before = refined ? this._placedWrites(entry) : undefined;\n try {\n this._compile(entry, (measurer) => instance.applyUpdate(patch, track.clip, track.duration, measurer));\n } catch {\n return this._fresh(track);\n }\n entry.issues = issuesOf(track.id, instance);\n entry.generation++;\n entry.track = track;\n if (!refined) {\n entry.frameCount = frameCount;\n return entry;\n }\n if (frameCount > entry.frameCount) {\n // The frames past the old end were never swept.\n this._undiscover(entry, frameCount);\n return entry;\n }\n\n const dirty = dirtyOwners({\n patch,\n deps: entry.deps,\n before: before!,\n after: this._placedWrites(entry),\n fps: this._scope.fps,\n propsOf: (id) => {\n const node = instance.node(id) as (Node & PropHost) | undefined;\n return node ? new Set(node.__cells?.slots.keys() ?? []) : undefined;\n },\n buildsChildren: (id) => {\n const node = instance.node(id);\n return !!node && node._allChildren.some((child) => instance.node(child.id) !== child);\n },\n isContextProvider: (type) => isContextProvider(this._scope.registry, type),\n });\n const keys = this._applyDirty(entry, dirty, frameCount);\n if (frameCount !== entry.frameCount) {\n entry.frameCount = frameCount;\n for (const key of entry.index.setFrameCount(frameCount).keys) keys.add(key);\n }\n if (this._refresh(entry)) update.deltas.set(track.id, keys);\n return entry;\n }\n\n /** The same clip over a different length: a shorter one clips the index, a longer one was never swept past its old end. */\n private _resize(entry: Entry, track: Track, frameCount: number): Entry {\n const duration = entry.track.duration;\n entry.track = track;\n if (track.duration === duration) return entry;\n if (entry.steps) return this._fresh(track);\n entry.instance?.update(entry.instance.clip, track.duration);\n if (this._refine === \"none\" || !entry.discovered) {\n entry.frameCount = frameCount;\n } else if (frameCount > entry.frameCount) {\n this._undiscover(entry, frameCount);\n } else if (frameCount !== entry.frameCount) {\n entry.frameCount = frameCount;\n entry.index.setFrameCount(frameCount);\n this._refresh(entry);\n }\n return entry;\n }\n\n private _undiscover(entry: Entry, frameCount: number): void {\n entry.frameCount = frameCount;\n entry.discovered = null;\n this._version++;\n }\n\n private _discard(entry: Entry): void {\n entry.discarded = true;\n if (entry.running) return;\n entry.steps?.return(undefined);\n entry.steps = null;\n entry.instance?.dispose();\n entry.instance = null;\n }\n\n private _nextUndiscovered(): Entry | undefined {\n let best: Entry | undefined;\n let bestStart = Infinity;\n for (const span of this._spans) {\n const entry = this._entries.get(span.id);\n if (!entry || entry.discovered || entry.running) continue;\n if (!best || span.startFrame < bestStart) {\n best = entry;\n bestStart = span.startFrame;\n }\n }\n return best;\n }\n\n private _start(entry: Entry, build: boolean, refine: boolean): void {\n const index = this._project.tracks.findIndex((track) => track.id === entry.track.id);\n entry.profile = refine ? this._options.profile?.track(index, entry.track.id) : undefined;\n entry.steps = this._steps(entry, build, refine);\n }\n\n private _drain(entry: Entry): void {\n while (entry.steps && !this._step(entry)) { /* drained */ }\n }\n\n /** One slice. True once the build has finished or been abandoned. */\n private _step(entry: Entry): boolean {\n const steps = entry.steps;\n if (!steps) return true;\n entry.running = true;\n let result: IteratorResult<void, void>;\n try {\n result = steps.next();\n } finally {\n entry.running = false;\n }\n entry.generation++;\n if (entry.discarded || this._disposed) {\n if (!result.done) steps.return(undefined);\n entry.steps = null;\n entry.instance?.dispose();\n entry.instance = null;\n return true;\n }\n if (!result.done) return false;\n entry.steps = null;\n return true;\n }\n\n /**\n * Build one track's clip, then refine what its nodes declare over the frames\n * that can change it. Yields only between frames, where the tree is consistent.\n */\n private *_steps(entry: Entry, build: boolean, refine: boolean): Generator<void, void, void> {\n const profile = entry.profile;\n const { fps, assets: catalog } = this._scope;\n if (build) {\n profile?.enter(\"build\");\n entry.unready.clear();\n try {\n const instance = new ClipInstance(entry.track.clip, entry.track.duration, this._scope);\n entry.instance = instance;\n this._compile(entry, (measurer) => instance.build(measurer));\n entry.issues = issuesOf(entry.track.id, instance);\n } catch (err) {\n entry.instance?.dispose();\n entry.instance = null;\n entry.failure = buildErrorOf(entry.track.id, err);\n entry.issues = [];\n if (refine) {\n this._resetAssets(entry);\n this._refresh(entry, true);\n profile?.done(entry.frameCount);\n }\n return;\n }\n if (!refine) return;\n yield;\n }\n\n const instance = entry.instance!;\n const frameCount = entry.frameCount;\n this._resetAssets(entry);\n const audioSlots = new Map<string, PropSlot<unknown>[]>();\n try {\n const refined = yield* refineAssets(instance, {\n fps,\n frameCount,\n catalog,\n declare: this._refine === \"assets\",\n onPhase: (phase) => profile?.enter(phase),\n onArrive: (_node, ownerKey) => {\n profile?.enter(\"audio\");\n this._declareAudio(entry, ownerKey, audioSlots);\n },\n });\n this._commit(entry, refined, audioSlots);\n } catch (err) {\n entry.refineError = buildErrorOf(entry.track.id, err);\n }\n const isReady = this._options.isReady;\n if (isReady) {\n for (const record of entry.index.layoutGates()) {\n if (record.type === \"loader\" && !isReady(record.src)) entry.unready.add(record.src);\n }\n }\n this._refresh(entry, true);\n profile?.done(frameCount);\n if (this._options.keepInstances === false) {\n instance.dispose();\n entry.instance = null;\n }\n }\n\n private _resetAssets(entry: Entry): void {\n entry.index = new AssetIndex(entry.frameCount);\n entry.audio = new AudioIndex();\n entry.commandAudio = new Set();\n entry.commandSounds = null;\n entry.deps = new OwnerDependencies();\n entry.assetDeps.clear();\n entry.audioDeps.clear();\n entry.ownerErrors.clear();\n entry.audioErrors.clear();\n entry.refineError = null;\n }\n\n private _commit(entry: Entry, refined: RefineResult, audioSlots: ReadonlyMap<string, PropSlot<unknown>[]>): void {\n const namer = new SlotNamer(entry.instance!);\n for (const owner of refined.owners.values()) {\n const key = owner.ownerKey;\n if (owner.error) entry.ownerErrors.set(key, this._ownerError(entry, owner));\n else entry.index.setOwner(key, owner.segments);\n entry.assetDeps.set(key, namer.idsOf(owner.deps));\n }\n for (const [key, slots] of audioSlots) entry.audioDeps.set(key, namer.idsOf(slots));\n for (const key of new Set([...entry.assetDeps.keys(), ...entry.audioDeps.keys()])) this._link(entry, key);\n }\n\n /** Re-declare what a patch can have changed, splicing each owner's new segments onto what it kept. */\n private _applyDirty(entry: Entry, dirty: DirtyOwners, frameCount: number): Set<string> {\n const keys = new Set<string>();\n const collect = (delta: { keys: ReadonlySet<string> }) => {\n for (const key of delta.keys) keys.add(key);\n };\n for (const row of dirty.removed) {\n for (const key of [row, ...entry.deps.ownersBelow(row)]) this._drop(entry, key, collect);\n }\n if (dirty.owners.size === 0 && dirty.below.size === 0) return keys;\n\n const instance = entry.instance!;\n const { fps, assets: catalog } = this._scope;\n const seen = new Set<string>();\n const audioSlots = new Map<string, PropSlot<unknown>[]>();\n const sweep = refineAssets(instance, {\n fps,\n frameCount,\n catalog,\n owners: dirty.owners,\n below: dirty.below,\n declare: this._refine === \"assets\",\n onArrive: (_node, ownerKey, span, frame) => {\n seen.add(ownerKey);\n // Audio is declared as an owner arrives, which a sweep starting later never sees.\n if (frame === spanFrames(span, fps, frameCount)?.startFrame) {\n this._declareAudio(entry, ownerKey, audioSlots);\n }\n },\n });\n let step = sweep.next();\n while (!step.done) step = sweep.next();\n entry.generation++;\n const refined = step.value;\n\n const fromOf = (key: string): number => {\n let from = dirty.owners.get(key);\n for (let slash = key.indexOf(\"/\"); slash >= 0; slash = key.indexOf(\"/\", slash + 1)) {\n const row = dirty.below.get(key.slice(0, slash));\n if (row !== undefined && (from === undefined || row < from)) from = row;\n }\n return from ?? 0;\n };\n const fromArrival = (key: string): boolean => {\n if (dirty.arrivalOwners.has(key)) return true;\n for (let slash = key.indexOf(\"/\"); slash >= 0; slash = key.indexOf(\"/\", slash + 1)) {\n if (dirty.arrivalBelow.has(key.slice(0, slash))) return true;\n }\n return false;\n };\n\n const candidates = new Set(refined.owners.keys());\n for (const row of dirty.below.keys()) for (const key of entry.deps.ownersBelow(row)) candidates.add(key);\n const namer = new SlotNamer(instance);\n for (const key of candidates) {\n const from = fromOf(key);\n const owner = refined.owners.get(key);\n if (!owner && from === 0) {\n this._drop(entry, key, collect);\n continue;\n }\n const kept = from > 0 ? keptBefore(entry.index.declaredSegmentsOf(key), from) : [];\n if (owner?.error) entry.ownerErrors.set(key, this._ownerError(entry, owner));\n else entry.ownerErrors.delete(key);\n collect(entry.index.setOwner(key, owner && !owner.error ? [...kept, ...owner.segments] : kept));\n if (owner) {\n const ids = namer.idsOf(owner.deps);\n entry.assetDeps.set(key, from > 0 ? [...new Set([...entry.assetDeps.get(key) ?? [], ...ids])] : ids);\n }\n if (fromArrival(key) && !seen.has(key)) {\n entry.audio.removeOwner(key);\n entry.audioDeps.delete(key);\n entry.audioErrors.delete(key);\n }\n this._link(entry, key);\n }\n for (const [key, slots] of audioSlots) {\n entry.audioDeps.set(key, namer.idsOf(slots));\n this._link(entry, key);\n }\n return keys;\n }\n\n private _drop(entry: Entry, key: string, collect: (delta: { keys: ReadonlySet<string> }) => void): void {\n collect(entry.index.removeOwner(key));\n entry.audio.removeOwner(key);\n entry.assetDeps.delete(key);\n entry.audioDeps.delete(key);\n entry.ownerErrors.delete(key);\n entry.audioErrors.delete(key);\n entry.deps.remove(key);\n }\n\n private _link(entry: Entry, key: string): void {\n const assets = entry.assetDeps.get(key);\n const audio = entry.audioDeps.get(key);\n if (assets === undefined && audio === undefined) entry.deps.remove(key);\n else entry.deps.set(key, [...assets ?? [], ...audio ?? []]);\n }\n\n /**\n * Declare an arriving owner's audio: the sounds its placed commands play.\n * It reads no slots, but is linked for audio like every arrival.\n */\n private _declareAudio(entry: Entry, ownerKey: string, slots: Map<string, PropSlot<unknown>[]>): void {\n slots.set(ownerKey, []);\n const sounds = entry.instance ? this._commandSoundsOf(entry, entry.instance).get(ownerKey) : undefined;\n if (sounds) return this._setCommandAudio(entry, entry.instance!, ownerKey, sounds);\n entry.audio.removeOwner(ownerKey);\n entry.audioErrors.delete(ownerKey);\n }\n\n /**\n * What the placed commands play, as one owner: a sound is scheduled ahead of\n * time from where its command sits, not written per frame. Rebuilt whenever\n * the track's audio is published, so a moved or edited command moves its sound.\n */\n private _declareCommandAudio(entry: Entry): void {\n const instance = entry.instance;\n entry.commandSounds = null;\n if (!instance || this._refine === \"none\") return;\n const byOwner = this._commandSoundsOf(entry, instance);\n for (const key of entry.commandAudio) {\n if (byOwner.has(key)) continue;\n entry.audio.removeOwner(key);\n entry.audioErrors.delete(key);\n }\n entry.commandAudio = new Set(byOwner.keys());\n for (const [key, sounds] of byOwner) this._setCommandAudio(entry, instance, key, sounds);\n entry.commandSounds = null;\n }\n\n /** The placed commands' sounds, under the row that plays each, so a request keeps its id and its waveform its row. */\n private _commandSoundsOf(entry: Entry, instance: ClipInstance): Map<string, PlacedSound[]> {\n if (entry.commandSounds) return entry.commandSounds;\n const byOwner = new Map<string, PlacedSound[]>();\n for (const sound of instance.commandSounds()) {\n const key = instance.ownerKeyOf(sound.node) ?? COMMAND_AUDIO;\n const list = byOwner.get(key);\n if (list) list.push(sound);\n else byOwner.set(key, [sound]);\n }\n return (entry.commandSounds = byOwner);\n }\n\n private _setCommandAudio(entry: Entry, instance: ClipInstance, key: string, sounds: readonly PlacedSound[]): void {\n const catalog = this._scope.assets;\n const spanOf = (node: Node): NodeSpan => {\n const found = instance.spanOf(node);\n if (!found) throw new Error(`${node.className} is not in the tree, so it has no span.`);\n return found;\n };\n try {\n const requests = sounds.map((sound, n) => {\n const { bus: busId, closed, ...options } = sound.options;\n // The buses as they stand when the sound starts: a bus may since have left.\n const bus = instance.atPresence(sound.at, () => {\n const target = busId ? findBusById(sound.node, busId) : null;\n return target ? busPathTo(target, spanOf) : sound.node instanceof NodeAudio ? busPathOf(sound.node, spanOf) : undefined;\n });\n const trimEnd = options.trimEnd ?? (closed ? catalog.getMediaDuration(sound.src) : undefined);\n return requestOf({ ...options, trimEnd, src: sound.src, at: sound.at, until: sound.until, bus }, catalog, key, n);\n });\n entry.audio.setOwner(key, requests);\n entry.audioErrors.delete(key);\n entry.commandAudio.add(key);\n } catch (err) {\n entry.audio.removeOwner(key);\n entry.audioErrors.set(key, { ...buildErrorOf(entry.track.id, err), nodeId: sounds[0].node.id });\n }\n }\n\n private _ownerError(entry: Entry, owner: OwnerResult): BuildError {\n const error = owner.error!;\n return {\n trackId: entry.track.id,\n message: error.message,\n ...(error.stack !== undefined && { stack: error.stack }),\n ...(owner.nodeId !== undefined && { nodeId: owner.nodeId }),\n ...(error.prop !== undefined && { prop: error.prop }),\n };\n }\n\n /**\n * Republish what the track's indices hold. A snapshot, so a result already\n * handed out does not change; the prior one is kept, and nothing bumps, when\n * nothing in it would differ. Whether it changed.\n */\n private _refresh(entry: Entry, landed = false): boolean {\n this._declareCommandAudio(entry);\n const prior = entry.discovered;\n const { fps } = this._scope;\n const records = prior && sameRecords(prior.assetRecords, entry.index.records())\n ? prior.assetRecords\n : new Map(entry.index.records());\n const audioRequests = clampAudioToClip(entry.audio.requests(), entry.frameCount / fps);\n const layoutGates = entry.index.layoutGates().map((record) => record.src);\n const errors = [\n ...entry.issues,\n ...entry.audioErrors.values(),\n ...entry.ownerErrors.values(),\n ...(entry.failure ? [entry.failure] : []),\n ...(entry.refineError ? [entry.refineError] : []),\n ];\n if (!landed && prior && records === prior.assetRecords && prior.frameCount === entry.frameCount\n && sameValue(prior.audioRequests, audioRequests) && sameValue(prior.layoutGates, layoutGates)\n && sameValue(entry.errors, errors)) {\n return false;\n }\n entry.discovered = {\n id: entry.track.id,\n discovered: true,\n frameCount: entry.frameCount,\n startFrame: 0,\n audioRequests,\n assetRecords: records,\n layoutGates,\n };\n entry.errors = errors;\n this._version++;\n return true;\n }\n\n /** Placed commands by their recorded write sets, named once per set. */\n private _placedWrites(entry: Entry): Map<object, PlacedWrites> {\n const instance = entry.instance!;\n const out = new Map<object, PlacedWrites>();\n let namer: SlotNamer | undefined;\n for (const placed of instance.placedCommands()) {\n let named = entry.writes.get(placed.writes);\n // An entrance's hold moves with its neighbours while its write set stays.\n if (!named || named.start !== placed.holdFrom) {\n namer ??= new SlotNamer(instance);\n named = { start: placed.holdFrom, writes: namer.idsOf(placed.writes) };\n entry.writes.set(placed.writes, named);\n }\n out.set(placed.writes, named);\n }\n return out;\n }\n\n /**\n * Run a compile, noting every face it measured that was not resident: a\n * layout-reading command built then captured the fallback's metrics.\n */\n private _compile(entry: Entry, run: (measurer: MeasureContext2D) => void): void {\n const isReady = this._options.isReady;\n const inner = this._scope.measurer;\n if (!isReady) {\n run(inner);\n return;\n }\n const families = new Set<string>();\n run({\n measureText(text, fontSize, fontFamily, fontWeight, letterSpacing, fontStyle) {\n families.add(fontFamily);\n return inner.measureText(text, fontSize, fontFamily, fontWeight, letterSpacing, fontStyle);\n },\n });\n for (const family of families) {\n if (!isReady(family)) entry.unready.add(family);\n }\n }\n\n private _rebuildInstance(entry: Entry): void {\n entry.instance?.dispose();\n entry.instance = null;\n entry.generation++;\n this._start(entry, true, false);\n this._drain(entry);\n if (entry.failure && entry.discovered) this._refresh(entry);\n }\n}\n\nfunction issuesOf(trackId: string, instance: ClipInstance): BuildError[] {\n return instance.issues().map(({ code, message, nodeId, commandId }) => ({\n trackId,\n message,\n code,\n ...(nodeId !== undefined && { nodeId }),\n ...(commandId !== undefined && { commandId }),\n }));\n}\n\nfunction buildErrorOf(trackId: string, err: unknown): BuildError {\n const e = err instanceof Error ? err : new Error(String(err));\n return { trackId, message: e.message, stack: e.stack };\n}\n\nfunction keptBefore(segments: readonly AssetSegment[], from: number): AssetSegment[] {\n const out: AssetSegment[] = [];\n for (const segment of segments) {\n if (segment.startFrame >= from) continue;\n out.push(segment.endFrame >= from ? { ...segment, endFrame: from - 1 } : segment);\n }\n return out;\n}\n\n/**\n * Confine a clip's **bounded** audio to its own `[0, clipDuration)`, so a source\n * outlasting the track does not sound past its cut. Open requests pass through,\n * to be resolved against the project total on assembly.\n *\n * Every bus is confined, open request or not: a bus is a node of this clip, so\n * one nothing removes is present until the clip ends, and that is the span its\n * curves run over.\n */\nfunction clampAudioToClip(requests: readonly AudioRequest[], clipDuration: number): AudioRequest[] {\n const out: AudioRequest[] = [];\n for (const req of requests) {\n const bus = req.bus && clampBusToClip(req.bus, clipDuration);\n const clamped = bus === req.bus ? { ...req } : { ...req, bus };\n if (req.open) {\n out.push(clamped);\n continue;\n }\n if (req.startAt >= clipDuration) continue;\n const endAt = Math.min(req.endAt, clipDuration);\n if (endAt <= req.startAt) continue;\n out.push(endAt === req.endAt ? clamped : { ...clamped, endAt });\n }\n return out;\n}\n\nfunction clampBusToClip(bus: readonly AudioBusStop[], clipDuration: number): readonly AudioBusStop[] {\n if (bus.every((stop) => stop.endAt <= clipDuration)) return bus;\n return bus.map((stop) => (stop.endAt <= clipDuration ? stop : { ...stop, endAt: clipDuration }));\n}\n\nfunction sameRecords(a: ReadonlyMap<string, AssetRecord>, b: ReadonlyMap<string, AssetRecord>): boolean {\n if (a.size !== b.size) return false;\n for (const [key, record] of a) {\n const other = b.get(key);\n if (!other || !sameValue(record, other)) return false;\n }\n return true;\n}\n\nfunction sameSpans(a: readonly TrackSpan[], b: readonly TrackSpan[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].id !== b[i].id || a[i].startFrame !== b[i].startFrame || a[i].endFrame !== b[i].endFrame) return false;\n }\n return true;\n}\n\nfunction sameValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key of keys) {\n if (!sameValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n }\n return true;\n}\n", "import type { ProjectDocument, Track } from \"@/document/project\";\nimport { isAudioDocument } from \"@/document/types\";\nimport type { NodeEditorStates } from \"@/components/trees/node/node-editor-state\";\nimport type { Canvas2D } from \"@/components/trees/root/canvas2d-node\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { RenderPass2D } from \"@/render/render-context2d\";\nimport type { ClipInstance, RuntimeScope } from \"./clip-instance\";\nimport { ClipStore } from \"./clip-store\";\nimport { clipFrameToTime } from \"./frame-time\";\nimport { frameTime, placeTracks, spansCovering, type TrackSpan } from \"./placement\";\n\n/** One track, and the tree it was last evaluated on. */\ninterface Slot {\n track: Track;\n span: TrackSpan;\n instance: ClipInstance | null;\n /** The store's generation for the track when {@link instance} was last evaluated. */\n generation: number;\n}\n\n/**\n * Puts a project's tracks into the state for a frame, then lays out and draws\n * the ones covering it, back to front.\n *\n * Trees come from a {@link ClipStore}: a track's is built the first time it\n * covers a frame — or taken as discovery left it — and thereafter only asked for\n * times, so a seek costs the same in either direction and however far. The store\n * owns them; anything it does to one (a refinement, a patch, a rebuild) moves\n * its generation, and this evaluates again. Nothing isolates overlapping\n * tracks: they composite by draw order alone, which is what lets a translucent\n * track show the one beneath it.\n */\nexport class StateEvaluator {\n /** Without `store`, the evaluator builds into one of its own. */\n constructor(project: ProjectDocument, private readonly _scope: RuntimeScope, store?: ClipStore) {\n this._owned = store === undefined;\n this._store = store ?? new ClipStore(project, _scope, { assets: false, audio: false });\n this._slots = this._slotsFor(project.tracks, new Map());\n this._currentTrackId = firstVisual(this._slots)?.track.id ?? null;\n }\n\n /** The frame on screen. {@link invalidate} drops the memo, not the position. */\n get currentFrame(): number {\n return this._currentFrame;\n }\n\n /**\n * The topmost visual track on screen — or, over a hole, the last one there\n * was. An audio clip is a canvas drawing nothing, so it is never what an\n * editor picks from.\n */\n get currentTrackId(): string | null {\n return this._currentTrackId;\n }\n\n /** {@link currentTrackId}'s tree, once built. */\n get currentCanvas(): Canvas2D | null {\n return this.currentInstance?.canvas ?? null;\n }\n\n /** {@link currentTrackId}'s clip instance, once built. */\n get currentInstance(): ClipInstance | null {\n const slot = this._slotOf(this._currentTrackId);\n if (!slot?.instance) return null;\n return slot.instance === this._store.instanceOf(slot.track.id) ? slot.instance : null;\n }\n\n /** Every track on screen, back to front. Empty over a hole. */\n get activeTrackIds(): string[] {\n return this._active.map(slot => slot.track.id);\n }\n\n /** Put every track covering `frame` into its state, building any that never has been. */\n stateAt(frame: number): void {\n if (this._disposed) return;\n const target = Math.max(0, Math.floor(frame));\n const active = this._slotsToDraw(target);\n\n // Evaluation is idempotent, so a repeat would only cost. Compared by slot\n // rather than by count: a swap can change which tracks are on screen\n // without changing how many.\n if (!this._stale && target === this._currentFrame && sameSlots(active, this._active)\n && active.every(slot => this._settled(slot))) {\n return;\n }\n\n this._active = active;\n const topmost = firstVisual([...active].reverse());\n if (topmost) this._currentTrackId = topmost.track.id;\n\n for (const slot of active) slot.instance = this._store.ensureBuilt(slot.track.id);\n for (const slot of active) {\n if (!slot.instance) continue;\n this._evaluate(slot, target - slot.span.startFrame);\n slot.generation = this._store.generationOf(slot.track.id);\n }\n\n this._currentFrame = target;\n this._stale = false;\n }\n\n layout(measurer: MeasureContext2D = this._scope.measurer): void {\n for (const slot of this._active) this._live(slot)?.layout(measurer);\n }\n\n render(pass: RenderPass2D): void {\n for (const slot of this._active) this._live(slot)?.render(pass);\n }\n\n /** Evaluate the current frame afresh on the next {@link stateAt}. */\n invalidate(): void {\n this._stale = true;\n }\n\n /**\n * Throw a track's tree away so the next {@link stateAt} builds it fresh.\n *\n * The way back to what the document says for a node nothing animates: the\n * timeline restores only what its commands write, so a value written straight\n * onto a live prop — an editor's override — survives re-evaluation.\n */\n rebuild(trackId: string | null = this._currentTrackId): void {\n if (trackId === null) return;\n this._store.rebuild(trackId);\n this._stale = true;\n }\n\n /**\n * Take a new document. The store decides what each track keeps — see\n * {@link ClipStore.setProject}; a store shared with a precomp has already\n * taken it, and taking it twice is a no-op.\n */\n setProject(next: ProjectDocument): void {\n if (this._disposed) return;\n this._store.setProject(next);\n const prior = new Map(this._slots.map(slot => [slot.track.id, slot]));\n this._slots = this._slotsFor(next.tracks, prior);\n\n const kept = new Set(this._slots);\n for (const id of this._editorStates.keys()) {\n if (!this._slotOf(id)) this._editorStates.delete(id);\n }\n\n // Keep drawing what survived until the next evaluation: a repaint can land\n // in between, and an emptied set would paint a blank frame over an edit.\n this._active = this._active.filter(slot => kept.has(slot));\n if (!this._slotOf(this._currentTrackId)) {\n this._currentTrackId = firstVisual(this._slots)?.track.id ?? null;\n }\n this._stale = true;\n }\n\n /** Hidden/locked state for one track's nodes — editor state, not authored, so it rides beside the document. */\n setEditorStates(trackId: string, states: NodeEditorStates | undefined): void {\n if (states) this._editorStates.set(trackId, states);\n else this._editorStates.delete(trackId);\n this._stale = true;\n }\n\n dispose(): void {\n this._disposed = true;\n this._active = [];\n for (const slot of this._slots) slot.instance = null;\n if (this._owned) this._store.dispose();\n }\n\n private readonly _store: ClipStore;\n private readonly _owned: boolean;\n private _slots: Slot[];\n private _active: Slot[] = [];\n private _currentFrame = 0;\n private _currentTrackId: string | null;\n /** Kept apart from the frame, so \"evaluate again\" never reads as \"frame -1\". */\n private _stale = false;\n private _disposed = false;\n private readonly _editorStates = new Map<string, NodeEditorStates>();\n\n private _slotsFor(tracks: readonly Track[], prior: ReadonlyMap<string, Slot>): Slot[] {\n const spans = placeTracks(tracks, this._scope.fps);\n return tracks.map((track, i) => {\n const old = prior.get(track.id);\n if (old) {\n old.track = track;\n old.span = spans[i];\n return old;\n }\n return { track, span: spans[i], instance: null, generation: -1 };\n });\n }\n\n private _slotOf(trackId: string | null): Slot | undefined {\n return trackId === null ? undefined : this._slots.find(slot => slot.track.id === trackId);\n }\n\n /** Whether `slot` still holds the tree the store has, in the state it was evaluated to. */\n private _settled(slot: Slot): boolean {\n const id = slot.track.id;\n if (!slot.instance) return this._store.failed(id);\n return slot.instance === this._store.instanceOf(id) && slot.generation === this._store.generationOf(id);\n }\n\n /** `slot`'s tree while the store still holds it — a released one must not be drawn. */\n private _live(slot: Slot): ClipInstance | null {\n return slot.instance && slot.instance === this._store.instanceOf(slot.track.id) ? slot.instance : null;\n }\n\n /**\n * The slots to draw at `frame`, holding the final stack past the end of the\n * project — a frame parked beyond the last one keeps showing the picture —\n * while a gap in the middle is a real hole and draws nothing.\n */\n private _slotsToDraw(frame: number): Slot[] {\n const spans = this._slots.map(slot => slot.span);\n let covering = spansCovering(spans, frame);\n if (covering.length === 0) {\n const last = Math.max(-1, ...spans.map(span => span.endFrame));\n if (frame > last && last >= 0) covering = spansCovering(spans, last);\n }\n return covering.map(span => this._slots[span.index]);\n }\n\n /**\n * Put `slot` into the state for `localFrame`.\n *\n * The track runs on its own clock, so where it sits never changes what it\n * draws. The frame before is evaluated too and stamped as motion history:\n * motion is a property of the frame, not of the seek that reached it.\n */\n private _evaluate(slot: Slot, localFrame: number): void {\n const instance = slot.instance!;\n const dt = clipFrameToTime(1, this._scope.fps);\n // Clamped so a frame held past the end shows where the track stops — a\n // track can cut its clip short, and the clip goes on past the cut.\n const time = frameTime(localFrame, this._scope.fps, slot.track.duration);\n instance.attach(time, this._editorStates.get(slot.track.id));\n\n const previous = Math.max(0, time - dt);\n instance.evaluateAt(previous);\n instance.layout();\n instance.primeMotion(previous);\n\n instance.evaluateAt(time);\n instance.layout();\n instance.sample();\n }\n}\n\nfunction firstVisual(slots: readonly Slot[]): Slot | undefined {\n return slots.find(slot => !isAudioDocument(slot.track.clip));\n}\n\nfunction sameSlots(a: readonly Slot[], b: readonly Slot[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n", "import type { StorageAdapter } from \"@/platform/storage-adapter\";\n\n/**\n * Renders a blocking frame is allowed before it gives up on being exact.\n *\n * Bounded because a broken asset must degrade a frame rather than hang an\n * export; four covers the longest real chain (three runtime → its resources →\n * a video frame → an exact image level discovered by that frame's draw).\n */\nexport const SETTLE_PASSES = 4;\n\nexport type SettleOutcome = \"settled\" | \"exhausted\" | \"superseded\";\n\n/**\n * Render, settle what the render asked for, and render again until nothing is\n * pending.\n *\n * `isCurrent` is checked before every render and after every await, so a seek\n * overtaken by a newer one stops drawing a frame nobody wants.\n */\nexport async function renderSettled(\n render: () => void,\n adapter: Pick<StorageAdapter, \"warmPendingDecodes\">,\n isCurrent: () => boolean,\n): Promise<SettleOutcome> {\n for (let pass = 0; pass < SETTLE_PASSES; pass++) {\n if (!isCurrent()) return \"superseded\";\n render();\n const warmed = await adapter.warmPendingDecodes();\n if (!warmed) return \"settled\";\n if (!isCurrent()) return \"superseded\";\n }\n return \"exhausted\";\n}\n", "import type { AssetCatalog } from \"@/assets/catalog\";\nimport type { AssetRecord, ImageRecord, VideoRecord } from \"@/assets/record\";\n\n/**\n * A single asset's position on the project timeline together with the\n * load/evict windows the asset manager uses to keep memory bounded.\n */\nexport interface AssetTrack {\n record: AssetRecord;\n /** Frame at which loading should begin; larger decodes get more lead time. Always <= startFrame. */\n cacheAt: number;\n /** Frame after which it may be evicted, or null to keep it (fonts). Always >= endFrame when set. */\n discardAt: number | null;\n}\n\n/** What one track contributes: its clip-local records, and where the track starts. */\nexport interface TrackRecords {\n id: string;\n startFrame: number;\n records: ReadonlyMap<string, AssetRecord>;\n}\n\n/**\n * Every track's asset records merged onto the project timeline, kept up to date\n * key by key.\n *\n * An edit to one track touches the keys that track's records changed, so the\n * cost of republishing follows the edit rather than the project. The map handed\n * out is replaced, never mutated, so a result already published stays as it was.\n */\nexport class ProjectAssets {\n constructor(private readonly _fps: number, private readonly _catalog: AssetCatalog) { }\n\n /** The merged map for `tracks` — the same object as last time when nothing in it changed. */\n update(tracks: readonly TrackRecords[]): ReadonlyMap<string, AssetTrack> {\n const touched = new Set<string>();\n const live = new Set<string>();\n for (const track of tracks) {\n live.add(track.id);\n const prior = this._tracks.get(track.id);\n if (prior && prior.records === track.records && prior.startFrame === track.startFrame) continue;\n const moved = !prior || prior.startFrame !== track.startFrame;\n for (const [key, record] of track.records) {\n const before = prior?.records.get(key);\n if (moved || !before || !sameRecord(before, record)) touched.add(key);\n this._holders(key).add(track.id);\n }\n if (prior) {\n for (const key of prior.records.keys()) {\n if (track.records.has(key)) continue;\n touched.add(key);\n this._release(key, track.id);\n }\n }\n this._tracks.set(track.id, { id: track.id, startFrame: track.startFrame, records: track.records });\n }\n for (const [id, prior] of this._tracks) {\n if (live.has(id)) continue;\n this._tracks.delete(id);\n for (const key of prior.records.keys()) {\n touched.add(key);\n this._release(key, id);\n }\n }\n\n let next: Map<string, AssetTrack> | undefined;\n for (const key of touched) {\n const entry = this._entryOf(key);\n const current = this._map.get(key);\n if (entry === undefined) {\n if (current === undefined) continue;\n next ??= new Map(this._map);\n next.delete(key);\n } else if (current === undefined || !sameTrack(current, entry)) {\n next ??= new Map(this._map);\n next.set(key, entry);\n }\n }\n if (next) this._map = next;\n return this._map;\n }\n\n private readonly _tracks = new Map<string, TrackRecords>();\n private readonly _byKey = new Map<string, Set<string>>();\n private _map: ReadonlyMap<string, AssetTrack> = new Map();\n\n private _holders(key: string): Set<string> {\n let holders = this._byKey.get(key);\n if (!holders) this._byKey.set(key, (holders = new Set()));\n return holders;\n }\n\n private _release(key: string, trackId: string): void {\n const holders = this._byKey.get(key);\n if (!holders) return;\n holders.delete(trackId);\n if (holders.size === 0) this._byKey.delete(key);\n }\n\n private _entryOf(key: string): AssetTrack | undefined {\n const holders = this._byKey.get(key);\n if (!holders) return undefined;\n let merged: AssetRecord | undefined;\n for (const id of holders) {\n const track = this._tracks.get(id)!;\n const record = track.records.get(key);\n if (record) merged = mergeRecord(merged, shiftRecord(record, track.startFrame));\n }\n return merged && assetTrackOf(merged, this._fps, this._catalog);\n }\n}\n\n/** Shift an asset record's frame range onto the project timeline by `offset`. */\nfunction shiftRecord(record: AssetRecord, offset: number): AssetRecord {\n if (offset === 0) return record;\n return { ...record, startFrame: record.startFrame + offset, endFrame: record.endFrame + offset };\n}\n\n/** Union two records of one key, so an asset several tracks use resolves to one window over all of it. */\nfunction mergeRecord(existing: AssetRecord | undefined, record: AssetRecord): AssetRecord {\n if (!existing) return record;\n return {\n ...existing,\n startFrame: Math.min(existing.startFrame, record.startFrame),\n endFrame: Math.max(existing.endFrame, record.endFrame),\n } as AssetRecord;\n}\n\n/**\n * The source's intrinsic decode, off the catalog: what a full decode costs, which\n * is what lead time scales with. Nothing for a source the catalog cannot size.\n */\nfunction intrinsicMB(record: ImageRecord | VideoRecord, catalog: AssetCatalog): number {\n let size: { width: number; height: number };\n try {\n size = record.type === \"image\" ? catalog.getImageMeta(record.src) : catalog.getVideoMeta(record.src);\n } catch {\n return 0;\n }\n if (!(size.width > 0) && !(size.height > 0)) return 0;\n return decodedMB(size.width, size.height);\n}\n\n/** Frames of lead time per decoded megabyte, clamped — a 4K image gets ~64, a thumbnail the minimum. */\nconst LEADS_PER_MB = 2;\nconst MIN_LEAD = 2;\nconst MAX_LEAD = 120;\n/** Frames an asset outlives its last use, for backward-scrub headroom. */\nconst TAIL_FRAMES = 30;\n\nfunction decodedMB(width: number, height: number): number {\n return (width * height * 4) / (1024 * 1024);\n}\n\nfunction leadFrames(mb: number): number {\n return Math.min(MAX_LEAD, Math.max(MIN_LEAD, Math.round(mb * LEADS_PER_MB)));\n}\n\n/** Size-proportional lead time for images and video; fonts pinned from frame 0 and never evicted. */\nfunction assetTrackOf(entry: AssetRecord, fps: number, catalog: AssetCatalog): AssetTrack | undefined {\n switch (entry.type) {\n case \"image\": {\n const lead = leadFrames(intrinsicMB(entry, catalog));\n return { record: entry, cacheAt: Math.max(0, entry.startFrame - lead), discardAt: entry.endFrame + TAIL_FRAMES };\n }\n case \"video\": {\n // Heavier to decode than an image: double the lead, plus a second\n // so a short clip still gets real headroom.\n const lead = Math.min(MAX_LEAD, leadFrames(intrinsicMB(entry, catalog)) * 2 + Math.round(fps));\n return { record: entry, cacheAt: Math.max(0, entry.startFrame - lead), discardAt: entry.endFrame + TAIL_FRAMES };\n }\n case \"font\":\n return { record: entry, cacheAt: 0, discardAt: null };\n case \"loader\":\n // Cheap and needed for the whole span it is requested over.\n return { record: entry, cacheAt: Math.max(0, entry.startFrame - MAX_LEAD), discardAt: entry.endFrame + TAIL_FRAMES };\n default:\n return undefined;\n }\n}\n\nfunction sameTrack(a: AssetTrack, b: AssetTrack): boolean {\n return a.cacheAt === b.cacheAt && a.discardAt === b.discardAt && sameRecord(a.record, b.record);\n}\n\nexport function sameRecord(a: AssetRecord, b: AssetRecord): boolean {\n if (a === b) return true;\n if (a.type !== b.type || a.src !== b.src || a.startFrame !== b.startFrame || a.endFrame !== b.endFrame) return false;\n switch (a.type) {\n case \"video\": {\n const v = b as typeof a;\n return a.trimStart === v.trimStart && a.trimEnd === v.trimEnd;\n }\n case \"font\": {\n const v = b as typeof a;\n return a.fontWeight === v.fontWeight && a.fontFamily === v.fontFamily;\n }\n case \"loader\":\n return a.load === (b as typeof a).load;\n default:\n return true;\n }\n}\n", "import { AudioRequest } from \"@/attributes/audio/request\";\nimport { AssetRecord } from \"@/assets/record\";\nimport type { AssetDecl } from \"@/assets/scope\";\nimport type { ProjectDocument } from \"@/document/project\";\nimport type { RenderIssue } from \"@/render/render-issue\";\nimport { now } from \"@/util/scheduler\";\nimport type { RuntimeScope } from \"./clip-instance\";\nimport { ClipStore, DEFAULT_PRECOMP_BUDGET_MS } from \"./clip-store\";\nimport { spansCovering, totalFramesOf } from \"./placement\";\nimport { ProjectAssets, type AssetTrack } from \"./project-assets\";\n\nexport type { AssetTrack } from \"./project-assets\";\n\nexport interface BuildError {\n /** The track whose clip threw. */\n trackId: string;\n message: string;\n stack?: string;\n /** The node whose declaration threw, when one owner failed rather than the whole clip. */\n nodeId?: string;\n /** The last prop that declaration read, as `slotLabel` spells it. */\n prop?: string;\n /**\n * Present when the build stepped around the problem rather than failing: a\n * row of an unregistered type built as an empty placeholder (`nodeId`), or a\n * command no node publishes, skipped (`commandId`). The rest of the clip draws.\n */\n code?: \"unknown-node-type\" | \"unknown-command\";\n commandId?: string;\n /** Set when the error is a renderer's issue rather than something that threw. */\n issue?: RenderIssue;\n}\n\n/**\n * What discovering one track's clip learned, in **clip-local** frames — so a pass\n * survives its track moving, and only `startFrame` depends on where it sits.\n */\nexport interface TrackAssets {\n id: string;\n /** Whether the pass has run. An undiscovered track has its span but no assets or audio yet. */\n discovered: boolean;\n frameCount: number;\n /** Where the track starts on the project timeline. */\n startFrame: number;\n /** Audio its nodes emit, in clip-local seconds. */\n audioRequests: AudioRequest[];\n /** Asset usage in clip-local frames, keyed by stable asset key (src; family for a font). */\n assetRecords: ReadonlyMap<string, AssetRecord>;\n /** Keys that must be resident before layout measures: fonts, and loaders declared with `gate: \"layout\"`. */\n layoutGates?: string[];\n}\n\n// ─── Profiling ────────────────────────────────────────────────────────────────\n\n/** The distinct pieces of work a pass performs. */\nexport type AssetTimelinePhase =\n | \"build\"\n | \"declare\"\n | \"evaluate\"\n | \"audio\";\n\nconst ASSET_TIMELINE_PHASES: readonly AssetTimelinePhase[] = [\"build\", \"declare\", \"evaluate\", \"audio\"];\n\n/** Wall-clock breakdown of one track's pass, in milliseconds. */\nexport interface TrackAssetsTiming {\n trackId: string;\n trackIndex: number;\n frameCount: number;\n /** Total ms spent inside the pass, excluding time parked on a yield. */\n totalMs: number;\n /** Ms attributed to each phase, summed over the pass. */\n phases: Record<AssetTimelinePhase, number>;\n}\n\n/** Per-track timings, in document order. Sparse until every track has run. */\nexport type AssetTimelineTimings = (TrackAssetsTiming | undefined)[];\n\n/**\n * Timing sink for one track's pass. `enter` closes whichever phase was open and\n * starts the named one; `suspend`/`resume` bracket a yield so parked time isn't\n * billed to the open phase.\n */\nexport interface TrackAssetsProfile {\n enter(phase: AssetTimelinePhase): void;\n suspend(): void;\n resume(): void;\n done(frameCount: number): void;\n}\n\n/** Optional profiler injected into {@link AssetTimeline} — a seam, so core carries no environment assumption. */\nexport interface AssetTimelineProfile {\n track(trackIndex: number, trackId: string): TrackAssetsProfile;\n}\n\n/** A {@link AssetTimelineProfile} accumulating into {@link AssetTimelineTimings}; read them off `AssetTimelineResult.timings`. */\nexport function createAssetTimelineProfile(): AssetTimelineProfile & { timings: AssetTimelineTimings } {\n const timings: AssetTimelineTimings = [];\n return {\n timings,\n track(trackIndex: number, trackId: string): TrackAssetsProfile {\n const phases = Object.fromEntries(\n ASSET_TIMELINE_PHASES.map(p => [p, 0]),\n ) as Record<AssetTimelinePhase, number>;\n let open: AssetTimelinePhase | null = null;\n let since = now();\n let totalMs = 0;\n const close = () => {\n const elapsed = now() - since;\n if (open) phases[open] += elapsed;\n totalMs += elapsed;\n };\n return {\n enter(phase) {\n close();\n open = phase;\n since = now();\n },\n suspend() {\n close();\n open = null;\n },\n resume() {\n since = now();\n },\n done(frameCount) {\n close();\n open = null;\n timings[trackIndex] = { trackId, trackIndex, frameCount, totalMs, phases };\n },\n };\n },\n };\n}\n\n// ─── Result ───────────────────────────────────────────────────────────────────\n\nexport interface AssetTimelineResult {\n fps: number;\n /** Every track, in document order, discovered or not. */\n tracks: TrackAssets[];\n totalFrames: number;\n totalDuration: number;\n /** Every track's asset usage merged into one timeline, in project frames. */\n assets: ReadonlyMap<string, AssetTrack>;\n buildErrors: BuildError[];\n /** True once every track has been discovered. Spans and totals are exact either way. */\n complete: boolean;\n /** Present only when a {@link AssetTimelineProfile} was injected. */\n timings?: AssetTimelineTimings;\n}\n\nexport interface AssetTimelineOptions {\n profile?: AssetTimelineProfile;\n /** @deprecated Ignored: a node's bar is its document span, read off the live tree. */\n lifespans?: boolean;\n /**\n * The store to read and drive, shared with an evaluator so each track builds\n * once. Absent, the view owns a store of its own that drops each tree once it\n * is refined — nothing it builds is ever drawn.\n */\n store?: ClipStore;\n /** False declares audio alone, at arrival — for a caller that only mixes. Ignored with `store`. */\n assets?: boolean;\n}\n\nexport interface RunAsyncOptions {\n /** Wall-clock ms before yielding. Defaults to {@link DEFAULT_PRECOMP_BUDGET_MS}; `0` yields between every frame evaluated. */\n budgetMs?: number;\n /** Polled after every yield; true abandons the pass. */\n isCancelled?: () => boolean;\n /** Called with a fresh result each time a track is discovered. */\n onProgress?: (result: AssetTimelineResult) => void;\n}\n\n/**\n * Discovers what each track's clip needs over its span — asset windows and\n * audio — and publishes it as one result over the project timeline.\n *\n * A view: the builds, indices and audio live in a {@link ClipStore}, and this\n * assembles them. Spans come from the document, so this decides which assets a\n * frame needs, never where a track sits; moving a track only changes where its\n * records are shifted to. A result is the same object until something in it\n * changes, so a caller can tell a republish from a no-op by identity.\n */\nexport class AssetTimeline {\n constructor(project: ProjectDocument, private readonly _scope: RuntimeScope, options: AssetTimelineOptions = {}) {\n this._owned = options.store === undefined;\n this._store = options.store ?? new ClipStore(project, _scope, {\n profile: options.profile,\n assets: options.assets,\n keepInstances: false,\n });\n this._assets = new ProjectAssets(_scope.fps, _scope.assets);\n }\n\n get store(): ClipStore {\n return this._store;\n }\n\n /** How many tracks are discovered — a cheap change check for a caller on the seek path. */\n get discoveredCount(): number {\n let n = 0;\n for (const track of this._store.tracks) if (this._store.isDiscovered(track.id)) n++;\n return n;\n }\n\n /** The result as it stands, discovering nothing. */\n result(): AssetTimelineResult {\n return this._assemble();\n }\n\n /** Discover every track covering `frame` — what that frame needs before it can paint. */\n ensureCovering(frame: number): AssetTimelineResult {\n for (const span of spansCovering(this._store.spans, frame)) this._store.discover(span.id);\n return this._assemble();\n }\n\n /** Discover every track, synchronously. */\n run(): AssetTimelineResult {\n for (const track of this._store.tracks) this._store.discover(track.id);\n return this._assemble();\n }\n\n /**\n * Discover every track in start order, yielding between the frames a pass evaluates and\n * publishing a result as each lands. A pass whose track changed while it was\n * parked is dropped, and the scan picks again from the document as it is now.\n */\n async runAsync(options: RunAsyncOptions = {}): Promise<AssetTimelineResult> {\n const { budgetMs = DEFAULT_PRECOMP_BUDGET_MS, isCancelled, onProgress } = options;\n await this._store.runAsync({\n budgetMs,\n isCancelled,\n onProgress: onProgress && (() => onProgress(this._assemble())),\n });\n return this._assemble();\n }\n\n /** Take a new document — see {@link ClipStore.setProject}. */\n setProject(next: ProjectDocument): AssetTimelineResult {\n this._store.setProject(next);\n return this._assemble();\n }\n\n /**\n * Record that `ownerKey` needed `decl` at clip-local `localFrame` without\n * having declared it — the draw found it missing. A track not discovered yet\n * is left alone: its pass will declare for itself.\n */\n learn(trackId: string, ownerKey: string, decl: AssetDecl, localFrame: number): AssetTimelineResult {\n this._store.learn(trackId, ownerKey, decl, localFrame);\n return this._assemble();\n }\n\n /** Dispose the store this view owns; a shared one is its owner's to dispose. */\n dispose(): void {\n if (this._owned) this._store.dispose();\n }\n\n private readonly _store: ClipStore;\n private readonly _owned: boolean;\n private readonly _assets: ProjectAssets;\n private _result: AssetTimelineResult | null = null;\n private _version = -1;\n\n private _assemble(): AssetTimelineResult {\n const store = this._store;\n if (this._result && this._version === store.version) return this._result;\n const { fps } = this._scope;\n const spans = store.spans;\n const totalFrames = totalFramesOf(spans);\n const totalDuration = totalFrames / fps;\n const tracks: TrackAssets[] = [];\n const buildErrors: BuildError[] = [];\n let complete = true;\n\n const local: TrackAssets[] = spans.map((span) => {\n const found = store.trackAssets(span.id);\n if (!found) complete = false;\n buildErrors.push(...store.errorsOf(span.id));\n return found ?? undiscovered(span.id, span.endFrame - span.startFrame + 1);\n });\n const assets = this._assets.update(local.map((track, i) => ({\n id: track.id,\n startFrame: spans[i].startFrame,\n records: track.assetRecords,\n })));\n for (let i = 0; i < local.length; i++) {\n tracks.push(resolveOpenAudio({ ...local[i], startFrame: spans[i].startFrame }, fps, totalDuration));\n }\n\n const profiled = store.profile as (AssetTimelineProfile & { timings?: AssetTimelineTimings }) | undefined;\n this._version = store.version;\n return this._result = {\n fps,\n tracks,\n totalFrames,\n totalDuration,\n assets,\n buildErrors,\n complete,\n timings: profiled?.timings?.slice(),\n };\n }\n}\n\n/** A track nothing has discovered yet: its span, and nothing else. */\nfunction undiscovered(id: string, frameCount: number): TrackAssets {\n return {\n id,\n discovered: false,\n frameCount,\n startFrame: 0,\n audioRequests: [],\n assetRecords: new Map(),\n layoutGates: [],\n };\n}\n\n/**\n * A copy of `track` with every open audio request's `endAt` resolved against the\n * project total. The `open` marker is kept, so the next assembly re-resolves it.\n */\nfunction resolveOpenAudio(track: TrackAssets, fps: number, totalDuration: number): TrackAssets {\n if (!track.audioRequests.some((r) => r.open)) return track;\n\n const offset = track.startFrame / fps;\n const audioRequests = track.audioRequests.map((req) => {\n if (!req.open) return req;\n const absStart = offset + req.startAt;\n const naturalEnd = req.loop\n ? totalDuration\n : Math.min(absStart + (req.mediaDuration ?? 0), totalDuration);\n return { ...req, endAt: Math.max(req.startAt, naturalEnd - offset) };\n });\n return { ...track, audioRequests };\n}\n", "import { Node } from \"@/components/trees/node/node\";\nimport { Node3D, parentSpaceOf } from \"@/components/trees/three/node3d\";\nimport type { Node2D } from \"@/components/trees/2d/node2d\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport { applyToPoint, invert, type Matrix2D } from \"@/attributes/layout/matrix2d\";\nimport { resolveCameraPlacement, type CameraData3D } from \"@/render3d/camera\";\nimport type { Scene3D, Scene3DOp } from \"@/render3d/scene3d\";\nimport type { Transform3D } from \"@/render3d/transform\";\nimport {\n geometryBounds3D, transformBox3, unionBox3, centeredBox3, corners3, type Box3,\n} from \"@/render3d/bounds3d\";\nimport {\n applyMatrix4, identity4, invert4, lookAtRotation4, multiply4, orthographic4,\n perspective4, transformMatrix4, translation4, type Matrix4,\n} from \"@/render3d/matrix4\";\nimport type { Vector3 } from \"@/render3d/vector3\";\nimport { nodePath } from \"@/project/tree\";\nimport type { NodeBox } from \"./node-picking\";\n\n/**\n * Where a `Node3D`'s pixels landed — the 3D half of `node-picking.ts`, and the\n * reason an editor can put a selection box round a cube at all.\n *\n * **The answer is a 2D box, deliberately.** A mesh has no rectangle in it: what\n * it has is an extent in three dimensions, seen through a camera. So this\n * projects the node's world-space AABB into the `Canvas3D`'s own plane and takes\n * the **screen-space AABB of the result** — the box that encloses the shape as\n * drawn, from wherever the camera happens to be. That is the same box every 3D\n * editor draws for the same reason: an oriented box in 3D read as a hexagon on\n * screen, and nothing you could grab on it would mean anything in two\n * dimensions.\n *\n * Because it is a 2D box in the canvas's plane, it composes with everything the\n * 2D side already does — the canvas's own rotation, its ancestors', a camera\n * scope above it — by being handed the canvas's `renderMatrix` and mapped\n * through it exactly as {@link nodeBox} maps a node's corners. Nothing here has\n * to know what is above the canvas.\n *\n * **Two walks, joined on the node id.** Bounds come from the recorded\n * {@link Scene3D} rather than from the node tree, because the scene is the seam\n * everything else goes through (the render and the asset pass both build it) and\n * a node that draws through a custom `renderSelf` is measured correctly for\n * free. Paths come from the tree, because a path is a child *index* and ops\n * don't carry one. The two meet on `Node3D.id`, which the scene records as the\n * `key` on every `push`.\n *\n * **Nothing here imports `node-picking.ts` at runtime.** The canvas's own box\n * and CTM arrive as a {@link Canvas3DFrame} parameter instead, so the dependency\n * runs one way — the 2D walk reaches into this file and never the reverse. The\n * `NodeBox` import is type-only and erased.\n *\n * Two things a caller should know about what it gets back. A box is **not\n * clipped to the viewport**: a mesh that has drifted off the side of its canvas\n * reports where it went, even though the 3D pass is confined to the rect and no\n * pixels of it are drawn. That is the honest answer for an overlay saying where\n * a node is, and it costs the picker nothing — {@link pickIn} only consults this\n * file for a point already inside the rect.\n *\n * And the cost: every entry point here records the scene afresh, so a pick or a\n * box walk pays one scene build per viewport it touches. That is the same\n * pass the render and the asset declaration each make every frame, and 3D scene\n * trees are small, so it is fine at pointer rate — but a host calling\n * {@link collectBoxes} on every pointer move over a document full of viewports\n * is paying it per viewport per move.\n */\n\n/** What the 2D walk already knows about the canvas, handed down. */\n/** @internal */\n/** A 2D node over a 3D scene (a `Canvas3D`): its 3D children are picked through the scene it builds. */\nexport interface Viewport3D extends Node2D {\n _isViewport3D(): boolean;\n _scene3D(): Scene3D | null;\n}\n\nexport function isViewport3D(node: unknown): node is Viewport3D {\n return typeof (node as Partial<Viewport3D> | null)?._isViewport3D === \"function\" && (node as Viewport3D)._isViewport3D();\n}\n\nexport interface Canvas3DFrame {\n /**\n * The canvas's own box. Its folded `rotation`/`scale`/`opacity` carry to\n * every 3D node inside it — a mesh has none of its own, and what an editor\n * needs those for (cursor angles, pixels-per-unit) is a question about the\n * plane the box is drawn in.\n */\n box: NodeBox;\n /** `renderMatrix(canvas)` — the canvas's CTM, canvas y-down. */\n matrix: Matrix2D;\n}\n\n/**\n * Every 3D node's box inside `canvas`, **nearest camera first**.\n *\n * Depth order rather than draw order, which is the one place this diverges from\n * {@link collectBoxes}: a 3D scene has no draw order to speak of (the renderer\n * sorts by depth and the depth buffer settles the rest), so \"topmost\" means\n * \"nearest\", and a picker walking this list front-to-back gets the node you can\n * actually see.\n *\n * Empty when the scene has no camera that resolves, when the canvas has no size,\n * or when nothing in it can be measured — see {@link geometryBounds3D} for the\n * last of those.\n */\n/** @internal */\nexport function collectBoxes3D(canvas: Viewport3D, frame: Canvas3DFrame, path: string): NodeBox[] {\n const projection = canvas3DProjection(canvas);\n if (!projection) return [];\n\n const out: { box: NodeBox; depth: number }[] = [];\n for (const entry of nodes3DOf(canvas, path)) {\n const world = projection.boxes.get(entry.node.id);\n if (!world) continue;\n const projected = projectBox3(world, projection);\n if (!projected) continue;\n out.push({\n box: toNodeBox(entry.node, entry.path, projected.rect, frame),\n depth: projected.depth,\n });\n }\n // View space looks down −Z, so a nearer node has the larger (less negative)\n // z — descending puts the front of the scene first.\n out.sort((a, b) => b.depth - a.depth);\n return out.map((entry) => entry.box);\n}\n\n/**\n * Where a handful of arbitrary points around one `Node3D` land on screen — the\n * ingredient a box can't supply for a gizmo.\n *\n * `origin`, `parentPoints` and `localPoints` all come back in the **same\n * viewport space** {@link NodeBox} does, so a caller drawing both together\n * (a box for the outline, this for the handles) never has two coordinate\n * systems to reconcile. A `null` entry means that point sits behind the\n * camera — mirrors {@link projectBox3}'s own eye-plane guard, just per point\n * instead of per clipped edge, since there's no box to keep in shape here.\n *\n * Not `@internal`, unlike {@link projectNode3D} itself: this is what a host\n * gets back from `projectNode3DAt`/`PlaybackController.projectNode3D`, the\n * same public tier as {@link NodeBox}.\n */\nexport interface Node3DFrame {\n /** The node's own position, projected — a gizmo's pivot. */\n origin: Vector2 | null;\n /**\n * `parentPoints` transformed by the node's **parent's** world matrix, then\n * projected, through the parent's own coordinates where it places its\n * children by them. The frame `Node3DProps.position` is itself expressed in, so\n * this is the space a move or scale handle belongs in: a point named\n * `{ ...position, x: position.x + 1 }` projects to where nudging `x` by\n * one unit would actually land, with no need to know whether \"one unit\"\n * means local or world space at the point of asking.\n */\n parentPoints: (Vector2 | null)[];\n /**\n * `localPoints` transformed by the node's **own** world matrix, then\n * projected. For geometry that has to track the node's current\n * orientation — a rotation ring wrapping the mesh as it's actually\n * turned, not as it started.\n */\n localPoints: (Vector2 | null)[];\n}\n\nconst ORIGIN_3D: Vector3 = { x: 0, y: 0, z: 0 };\n\n/**\n * Project `parentPoints`/`localPoints` for the `Node3D` at `targetPath`\n * inside `canvas`, or `null` when the canvas has no projection (see\n * {@link canvas3DProjection}) or the path doesn't resolve to a node in it.\n *\n * `canvasPath` is the canvas's own structural path — the same root\n * {@link collectBoxes3D} and {@link pickNode3D} are handed — and `targetPath`\n * the node being projected, found the same way {@link nodeBoxAt} finds one\n * (`node-picking.ts`, one level up).\n */\n/** @internal */\nexport function projectNode3D(\n canvas: Viewport3D,\n frame: Canvas3DFrame,\n canvasPath: string,\n targetPath: string,\n parentPoints: readonly Vector3[],\n localPoints: readonly Vector3[],\n): Node3DFrame | null {\n const projection = canvas3DProjection(canvas);\n if (!projection) return null;\n\n const entry = nodes3DOf(canvas, canvasPath).find((e) => e.path === targetPath);\n if (!entry) return null;\n\n const own = projection.matrices.get(entry.node.id);\n const parent = projection.parentMatrices.get(entry.node.id);\n if (!own || !parent) return null;\n\n const project = (matrix: Matrix4, points: readonly Vector3[]): (Vector2 | null)[] =>\n points.map((point) => projectPoint3(matrix, point, projection, frame));\n\n // A parent with coordinates of its own places the node by them, so that is the frame its position is in.\n const space = parentSpaceOf(entry.node);\n const placed = space ? parentPoints.map((point) => space.toLocal(point.x, point.y, point.z)) : parentPoints;\n\n return {\n origin: projectPoint3(own, ORIGIN_3D, projection, frame),\n parentPoints: project(parent, placed),\n localPoints: project(own, localPoints),\n };\n}\n\n/**\n * `point` (in whatever space `matrix` maps to world space) projected into\n * `frame`'s viewport space, or `null` when it lands behind the camera.\n *\n * The single-point sibling of {@link projectBox3}: no edges to clip, so a\n * point either has a clip-space `w` in front of the eye or it doesn't.\n */\nfunction projectPoint3(\n matrix: Matrix4,\n point: Vector3,\n projection: Canvas3DProjection,\n frame: Canvas3DFrame,\n): Vector2 | null {\n const world = applyMatrix4(matrix, point);\n const clip = applyMatrix4(projection.clip, { x: world.x, y: world.y, z: world.z });\n if (clip.w <= MIN_CLIP_W) return null;\n\n const ndcX = clip.x / clip.w;\n const ndcY = clip.y / clip.w;\n const rectX = projection.centerX + ndcX * (projection.width / 2);\n const rectY = projection.centerY + ndcY * (projection.height / 2);\n\n const p = applyToPoint(frame.matrix, { x: rectX, y: -rectY });\n return { x: p.x, y: -p.y };\n}\n\n/**\n * The nearest 3D node in `canvas` whose box contains `point` (viewport space,\n * y-up), or `null`.\n *\n * The box, not the mesh — the module note says why there is no mesh-accurate\n * answer to give. `tolerance` is grab-slop in scene units, applied in the\n * canvas's own plane so it stays the constant on-screen distance the caller\n * quoted it as.\n */\n/** @internal */\nexport function pickNode3D(\n canvas: Viewport3D,\n frame: Canvas3DFrame,\n point: Vector2,\n tolerance: number,\n path: string,\n): NodeBox | null {\n const projection = canvas3DProjection(canvas);\n if (!projection) return null;\n\n // Into the canvas's own plane, undoing everything above it in one step —\n // the same inverse `containsPoint` takes, with the same y-flips in and out.\n const inverse = invert(frame.matrix);\n if (!inverse) return null;\n const mapped = applyToPoint(inverse, { x: point.x, y: -point.y });\n const local = { x: mapped.x, y: -mapped.y };\n\n let best: { node: Node3D; path: string; rect: Rect2D } | null = null;\n let bestDepth = -Infinity;\n for (const entry of nodes3DOf(canvas, path)) {\n const world = projection.boxes.get(entry.node.id);\n if (!world) continue;\n const projected = projectBox3(world, projection);\n if (!projected) continue;\n if (!rectContains(projected.rect, local, tolerance)) continue;\n if (projected.depth <= bestDepth) continue;\n bestDepth = projected.depth;\n best = { node: entry.node, path: entry.path, rect: projected.rect };\n }\n return best ? toNodeBox(best.node, best.path, best.rect, frame) : null;\n}\n\n// ─── The tree walk: which node is at which path ──────────────────────────────\n\ninterface Node3DEntry {\n node: Node3D;\n path: string;\n}\n\n/**\n * Every `Node3D` under `canvas`, with the structural path it sits at.\n *\n * Indexed against {@link Node._allChildren} rather than `children`, so a mesh\n * and a HUD label under the same viewport are numbered the way the author wrote\n * them — see the accessor's own note for what goes wrong otherwise.\n */\nfunction nodes3DOf(canvas: Viewport3D, path: string): Node3DEntry[] {\n const out: Node3DEntry[] = [];\n walk3D(canvas._allChildren, path, out);\n return out;\n}\n\nfunction walk3D(children: readonly Node[], parentPath: string, out: Node3DEntry[]): void {\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (!(child instanceof Node3D)) continue;\n const path = nodePath(parentPath, i);\n out.push({ node: child, path });\n walk3D(child._allChildren, path, out);\n }\n}\n\n// ─── The op walk: how big each node is, and where it is looked at from ───────\n\n/** Everything the projection needs, resolved once per call. */\ninterface Canvas3DProjection {\n /** World-space bounds per `Node3D.id`, each including its subtree. */\n boxes: Map<string, Box3>;\n /** Each node's own world matrix, per `Node3D.id` — see {@link Node3DFrame}. */\n matrices: Map<string, Matrix4>;\n /** Each node's *parent's* world matrix, keyed by the node's own id. */\n parentMatrices: Map<string, Matrix4>;\n /** `projection · view` — world space straight to clip space. */\n clip: Matrix4;\n /** The view matrix alone, for the depth sort. */\n view: Matrix4;\n /** The canvas's local rect, which the 3D buffer is stretched onto. */\n width: number;\n height: number;\n centerX: number;\n centerY: number;\n}\n\nfunction canvas3DProjection(canvas: Viewport3D): Canvas3DProjection | null {\n const bounds = canvas._localBounds();\n if (!(bounds.width > 0) || !(bounds.height > 0)) return null;\n\n const scene = canvas._scene3D();\n if (!scene) return null;\n const walked = walkScene3D(scene);\n if (walked.boxes.size === 0) return null;\n\n const view = invert4(walked.camera);\n if (!view) return null;\n\n const aspect = bounds.width / bounds.height;\n return {\n boxes: walked.boxes,\n matrices: walked.matrices,\n parentMatrices: walked.parentMatrices,\n clip: multiply4(projectionMatrix(walked.descriptor, aspect), view),\n view,\n width: bounds.width,\n height: bounds.height,\n centerX: bounds.x,\n centerY: bounds.y,\n };\n}\n\n/** One open `push` scope: where it is, whether it draws, and what it has drawn. */\ninterface Scope3D {\n key: string | undefined;\n matrix: Matrix4;\n visible: boolean;\n box: Box3 | null;\n}\n\ninterface WalkedScene3D {\n boxes: Map<string, Box3>;\n /** Each node's own world matrix, per `Node3D.id` — captured at `push`,\n * unlike `boxes`, which needs children merged in first at `pop`. */\n matrices: Map<string, Matrix4>;\n /** Each node's *parent's* world matrix, keyed by the node's own id. */\n parentMatrices: Map<string, Matrix4>;\n /** The camera's world matrix, or the renderer's own framing when none was set. */\n camera: Matrix4;\n descriptor: CameraData3D | null;\n}\n\n/**\n * Replay the recorded scene, accumulating a world-space box per node.\n *\n * A node's box is the union of everything it drew and everything its children\n * drew, which is what makes a `Group3D` — which draws nothing itself — still\n * selectable as the thing it contains.\n *\n * An invisible scope contributes nothing and is recorded for nobody: `visible:\n * false` is a live object the renderer skips, so there are no pixels to put a\n * box round, and letting one inflate its parent's box would put that parent's\n * box round empty space. The 2D walk skips `opacity: 0` nodes on the same\n * grounds.\n */\nfunction walkScene3D(scene: Scene3D): WalkedScene3D {\n const boxes = new Map<string, Box3>();\n const matrices = new Map<string, Matrix4>();\n const parentMatrices = new Map<string, Matrix4>();\n const root: Scope3D = { key: undefined, matrix: identity4(), visible: true, box: null };\n const stack: Scope3D[] = [root];\n let camera: Matrix4 | null = null;\n let descriptor: CameraData3D | null = null;\n\n const top = (): Scope3D => stack[stack.length - 1];\n\n for (const op of scene.ops()) {\n const scope = top();\n switch (op.kind) {\n case \"push\": {\n const matrix = scopeMatrix(scope.matrix, op.transform);\n if (op.transform?.key !== undefined) {\n matrices.set(op.transform.key, matrix);\n parentMatrices.set(op.transform.key, scope.matrix);\n }\n stack.push({\n key: op.transform?.key,\n matrix,\n visible: scope.visible && op.transform?.visible !== false,\n box: null,\n });\n break;\n }\n case \"pop\": {\n // The root frame is never popped: `Node3D.render` brackets its own\n // begin/end, and `Scene3D.assertBalanced` catches a hand-built\n // scene that doesn't. Guarding anyway keeps a malformed op list\n // from reading past the bottom of the stack.\n if (stack.length === 1) break;\n const closed = stack.pop() as Scope3D;\n if (!closed.visible || !closed.box) break;\n if (closed.key !== undefined) boxes.set(closed.key, closed.box);\n const parent = top();\n parent.box = unionBox3(parent.box, closed.box);\n break;\n }\n case \"camera\": {\n descriptor = op.camera;\n camera = cameraMatrix4(op.camera, scope.matrix);\n break;\n }\n case \"light\":\n // A light has no extent. A node that is only a light therefore\n // gets no box and cannot be picked on the canvas, which is the\n // honest answer — there is nothing on screen at its position.\n break;\n default: {\n if (!scope.visible) break;\n const drawn = drawableBox3(op, scope.matrix);\n if (drawn) scope.box = unionBox3(scope.box, drawn);\n break;\n }\n }\n }\n\n return {\n boxes,\n matrices,\n parentMatrices,\n camera: camera ?? DEFAULT_CAMERA_MATRIX,\n descriptor,\n };\n}\n\n/** A scope's world matrix: the parent's, composed with the node's own placement. */\nfunction scopeMatrix(parent: Matrix4, transform: Transform3D | undefined): Matrix4 {\n return multiply4(parent, transformMatrix4(transform, parent));\n}\n\n/** The world box a single drawable op contributes, or `null` when it has none. */\nfunction drawableBox3(op: Scene3DOp, parent: Matrix4): Box3 | null {\n if (op.kind === \"model\") return null; // its extent arrives with the file\n if (!(\"transform\" in op)) return null;\n\n const matrix = scopeMatrix(parent, op.transform);\n\n if (op.kind === \"sprite\") {\n // A sprite is a camera-facing unit quad scaled by its transform — three's\n // `Sprite` has no geometry to ask, so this is the one place the extent is\n // assumed rather than read.\n return transformBox3(centeredBox3(0.5, 0.5, 0), matrix);\n }\n\n if (!(\"geometry\" in op)) return null;\n const local = geometryBounds3D(op.geometry);\n if (!local) return null;\n\n if (op.kind === \"instances\") {\n // Every instance is placed inside the op's own transform, so the union is\n // taken in that space and mapped out once.\n let box: Box3 | null = null;\n for (const instance of op.instances) {\n box = unionBox3(box, transformBox3(local, transformMatrix4(instance, null)));\n }\n return box ? transformBox3(box, matrix) : null;\n }\n\n return transformBox3(local, matrix);\n}\n\n// ─── The camera ──────────────────────────────────────────────────────────────\n\n/**\n * The camera's world matrix.\n *\n * `lookAt` takes the camera branch of three's `Object3D.lookAt` — **−Z** at the\n * target, where every other node aims its +Z — and is resolved against the\n * camera's *world* position, so a camera riding inside an animated rig points\n * where the author said rather than where its group happens to face. See\n * {@link lookAtRotation4}, which the two branches share.\n *\n * The polar placement (`target`/`orbit`/`elevation`/`distance`) is resolved by\n * core's own {@link resolveCameraPlacement} — the same call the renderer makes.\n * Two places deriving \"where is the camera\" from one descriptor is two chances to\n * disagree about what the author is looking at, and a gizmo drawn against a\n * camera nobody renders is worse than no gizmo at all.\n */\nfunction cameraMatrix4(descriptor: CameraData3D, parent: Matrix4): Matrix4 {\n const placement = resolveCameraPlacement(descriptor);\n\n if (placement.lookAt === undefined) {\n return multiply4(parent, transformMatrix4({ ...descriptor, position: placement.position }, parent));\n }\n const placed = applyMatrix4(parent, placement.position);\n const origin: Vector3 = { x: placed.x, y: placed.y, z: placed.z };\n return multiply4(translation4(origin), lookAtRotation4(origin, placement.lookAt));\n}\n\n/**\n * Where the renderer looks from when a scene declares no camera: pulled back\n * along +Z, aimed at the origin. Mirrors `applyCamera`'s own fallback, which is\n * what makes a bare `g.box()` render something rather than a black frame — and\n * therefore what makes it pickable here.\n */\nconst DEFAULT_CAMERA_MATRIX: Matrix4 = multiply4(\n translation4({ x: 0, y: 0, z: 5 }),\n lookAtRotation4({ x: 0, y: 0, z: 5 }, { x: 0, y: 0, z: 0 }),\n);\n\n/** three's default fov when a perspective descriptor omits one. */\nconst DEFAULT_FOV = 50;\nconst DEFAULT_NEAR = 0.1;\nconst DEFAULT_FAR = 1000;\n\n/** The projection a descriptor asks for, framed to the canvas's aspect. */\nfunction projectionMatrix(descriptor: CameraData3D | null, aspect: number): Matrix4 {\n if (descriptor === null) {\n return perspective4(DEFAULT_FOV, aspect, DEFAULT_NEAR, DEFAULT_FAR, 1);\n }\n if (descriptor.type === \"perspective\") {\n return perspective4(\n descriptor.fov ?? DEFAULT_FOV,\n // Always the node's own aspect. There is no override any more: it was\n // a field whose documentation said not to set it, and setting it\n // stretched the render — so a gizmo can only ever have been wrong by\n // agreeing with one.\n aspect,\n descriptor.near ?? DEFAULT_NEAR,\n descriptor.far ?? DEFAULT_FAR,\n descriptor.zoom ?? 1,\n );\n }\n // `frustumHeight` sets the visible world height and the width follows the\n // node's aspect — the same rule `applyCamera` applies, restated rather than\n // shared because that one lives in the renderer, which core cannot import.\n const halfHeight = (descriptor.frustumHeight ?? 10) / 2;\n return orthographic4(\n -halfHeight * aspect,\n halfHeight * aspect,\n halfHeight,\n -halfHeight,\n descriptor.near ?? DEFAULT_NEAR,\n descriptor.far ?? DEFAULT_FAR,\n descriptor.zoom ?? 1,\n );\n}\n\n// ─── Projection ──────────────────────────────────────────────────────────────\n\n/** An axis-aligned rect in the canvas's own plane, y-up. */\ninterface Rect2D {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\n\n/** The twelve edges of {@link corners3}'s eight corners, as index pairs. */\nconst BOX_EDGES: readonly (readonly [number, number])[] = [\n [0, 1], [2, 3], [4, 5], [6, 7],\n [0, 2], [1, 3], [4, 6], [5, 7],\n [0, 4], [1, 5], [2, 6], [3, 7],\n];\n\n/**\n * Smallest `w` a projected point may have before it counts as behind the camera.\n * A point at `w = 0` is on the plane through the eye and projects to infinity.\n */\nconst MIN_CLIP_W = 1e-4;\n\n/**\n * How far outside the canvas a projected box is allowed to reach, as a multiple\n * of the canvas's own size.\n *\n * A box straddling the eye plane genuinely does extend to the horizon, and the\n * arithmetic says so — a corner a millimetre in front of the camera projects\n * thousands of units out. That is the right answer and a useless one: the host\n * draws this, and an overlay rectangle a million pixels wide is a rendering\n * problem rather than a selection. Clamping keeps the box pointing the right way\n * while it is mostly off-screen, and it is only ever reached in the case where\n * the box is already unusable as a target.\n */\nconst OFFSCREEN_LIMIT = 8;\n\n/**\n * The world box projected into the canvas's plane, plus its view-space depth.\n *\n * The **edges** are clipped rather than the corners being clamped: a box with\n * one corner behind the eye has that corner's projection reflected through the\n * origin, so bounding the raw eight would produce a box on the wrong side of the\n * screen. Clipping each edge where it crosses the eye plane gives the visible\n * span and nothing else. Entirely-behind boxes drop out with no edges surviving,\n * which is how a node behind the camera stops being selectable.\n */\nfunction projectBox3(\n world: Box3,\n projection: Canvas3DProjection,\n): { rect: Rect2D; depth: number } | null {\n const corners = corners3(world);\n const clip = corners.map((corner) => applyMatrix4(projection.clip, corner));\n\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n let any = false;\n\n const include = (x: number, y: number, w: number) => {\n const ndcX = x / w;\n const ndcY = y / w;\n if (ndcX < minX) minX = ndcX;\n if (ndcY < minY) minY = ndcY;\n if (ndcX > maxX) maxX = ndcX;\n if (ndcY > maxY) maxY = ndcY;\n any = true;\n };\n\n for (const [a, b] of BOX_EDGES) {\n const p = clip[a];\n const q = clip[b];\n const pIn = p.w > MIN_CLIP_W;\n const qIn = q.w > MIN_CLIP_W;\n if (!pIn && !qIn) continue;\n if (pIn) include(p.x, p.y, p.w);\n if (qIn) include(q.x, q.y, q.w);\n if (pIn === qIn) continue;\n // Exactly one end is in front: cut the edge where `w` reaches the plane.\n const t = (MIN_CLIP_W - p.w) / (q.w - p.w);\n include(p.x + (q.x - p.x) * t, p.y + (q.y - p.y) * t, MIN_CLIP_W);\n }\n\n if (!any) return null;\n\n const halfWidth = projection.width / 2;\n const halfHeight = projection.height / 2;\n const limitX = halfWidth * OFFSCREEN_LIMIT;\n const limitY = halfHeight * OFFSCREEN_LIMIT;\n\n const rect: Rect2D = {\n minX: clamp(projection.centerX + minX * halfWidth, projection.centerX - limitX, projection.centerX + limitX),\n maxX: clamp(projection.centerX + maxX * halfWidth, projection.centerX - limitX, projection.centerX + limitX),\n minY: clamp(projection.centerY + minY * halfHeight, projection.centerY - limitY, projection.centerY + limitY),\n maxY: clamp(projection.centerY + maxY * halfHeight, projection.centerY - limitY, projection.centerY + limitY),\n };\n\n // Depth is taken at the box centre in view space, where the camera looks down\n // −Z: a nearer node has the larger value. One point rather than eight,\n // because what this orders is \"which of two overlapping nodes did you mean\",\n // and their centres answer that as well as their nearest corners would.\n const centre: Vector3 = {\n x: (world.min.x + world.max.x) / 2,\n y: (world.min.y + world.max.y) / 2,\n z: (world.min.z + world.max.z) / 2,\n };\n const viewed = applyMatrix4(projection.view, centre);\n\n return { rect, depth: viewed.z };\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return value < low ? low : value > high ? high : value;\n}\n\n/** Whether `point` (canvas-local, y-up) lands in `rect`, widened by `slop`. */\nfunction rectContains(rect: Rect2D, point: Vector2, slop: number): boolean {\n return point.x >= rect.minX - slop\n && point.x <= rect.maxX + slop\n && point.y >= rect.minY - slop\n && point.y <= rect.maxY + slop;\n}\n\n/**\n * The projected rect as a {@link NodeBox}, in viewport space.\n *\n * The corner mapping is {@link worldAnchors}' — y flipped on the way in and back\n * out, because the CTM is canvas y-down while everything either side of it is\n * y-up. Doing it here rather than reusing `worldAnchors` is what lets the rect\n * keep its own centre: the box is axis-aligned in the canvas's plane but not\n * centred on the canvas's origin, and `worldAnchors` maps offsets from wherever\n * the matrix already is.\n *\n * `rotation`, `scale` and `opacity` are the **canvas's**. A mesh has none of its\n * own that mean anything in two dimensions — its `rotation` is three angles and\n * its opacity is its material's — and what a host reads these for is the plane\n * the box was drawn in, which is exactly what the canvas describes.\n */\nfunction toNodeBox(node: Node3D, path: string, rect: Rect2D, frame: Canvas3DFrame): NodeBox {\n const at = (x: number, y: number): Vector2 => {\n const p = applyToPoint(frame.matrix, { x, y: -y });\n return { x: p.x, y: -p.y };\n };\n return {\n id: node.id,\n path,\n type: node.className,\n topLeft: at(rect.minX, rect.maxY),\n topRight: at(rect.maxX, rect.maxY),\n bottomRight: at(rect.maxX, rect.minY),\n bottomLeft: at(rect.minX, rect.minY),\n center: at((rect.minX + rect.maxX) / 2, (rect.minY + rect.maxY) / 2),\n width: rect.maxX - rect.minX,\n height: rect.maxY - rect.minY,\n rotation: frame.box.rotation,\n scale: frame.box.scale,\n opacity: frame.box.opacity,\n // A mesh locks on its own account, not the viewport's — a locked Canvas3D\n // is already unpickable above, so reaching here means the viewport is free.\n locked: node.locked,\n };\n}\n", "import { Node } from \"@/components/trees/node/node\";\nimport { Node2D, type NodeHandle } from \"@/components/trees/2d/node2d\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { Matrix2D, multiply, invert, applyToPoint, cameraMatrix, translation, isProjective } from \"@/attributes/layout/matrix2d\";\nimport { worldAnchors } from \"@/components/trees/2d/node-transform\";\nimport { spaceChildFrame, spaceChildOrder, spaceFrameForChildren, spaceFrameOf, spaceRootFrame } from \"@/components/trees/2d/node-space\";\nimport { multiplyAffine3, spaceScreenMatrix } from \"@/attributes/layout/space3d\";\nimport { nodePath } from \"@/project/tree\";\nimport { collectBoxes3D, isViewport3D, pickNode3D, projectNode3D, type Canvas3DFrame, type Node3DFrame, type Viewport3D } from \"./node-picking3d\";\nimport type { Vector3 } from \"@/render3d/vector3\";\n\n/**\n * Pure geometry for editor-style direct manipulation: where a node's pixels\n * landed, and which node is under a point. No controller state, so it can be\n * exercised against hand-built node trees.\n *\n * **Space.** Everything here is in *viewport space*: origin at the viewport\n * centre, y-up, units = the viewport pixels the player was given. That is the\n * same space `Node2D.global` reports, plus the camera — see {@link renderMatrix}.\n */\n\n/**\n * A node's on-screen box at the current frame, in viewport space (origin at the\n * viewport centre, y-up).\n *\n * Unlike {@link Node2D.global} this folds in any active camera scope, so it\n * describes where the node's pixels actually landed — which is what an editor\n * overlay needs in order to draw a selection box over them.\n */\nexport interface NodeBox {\n /** Per-instance id — changes on every rebuild. Use {@link path} to key across rebuilds. */\n id: string;\n /** Structural path from the scene root (`\"\"` is the root); stable across rebuilds. */\n path: string;\n /** Node2D class name, e.g. `Rect`, `Text`. */\n type: string;\n /** Corners in draw order, viewport space. Rotated/scaled — not axis-aligned. */\n topLeft: Vector2;\n topRight: Vector2;\n bottomRight: Vector2;\n bottomLeft: Vector2;\n center: Vector2;\n /**\n * Size of the box before rotation/scale, in scene units — the node's layout\n * size for everything whose drawing fills its cell, and the ink's own extent\n * where the two differ (see {@link Node2D._localBounds}; a boolean group\n * reports the extent of its children's ink, not its layout rect).\n */\n width: number;\n height: number;\n /** Folded rotation (degrees clockwise) and uniform scale, camera included. */\n rotation: number;\n scale: number;\n /** Effective alpha; `0` means the node is present but invisible. */\n opacity: number;\n /**\n * The editor's padlock — see {@link NodeEditorState.locked}.\n *\n * Carried here rather than left for the host to look up, because the two\n * things that need it are a marquee sweep and a gizmo's handles, and both are\n * already holding the box. A locked node is never returned by\n * {@link pickNode}; it appears in {@link collectBoxes} so a host can still\n * outline one selected from its layer tree.\n */\n locked: boolean;\n}\n\n/**\n * The renderer's CTM at `node` — every ancestor's local matrix from the scene\n * root down, with a camera scope inserted wherever an ancestor pushes one\n * ({@link Node2D._cameraScope}; `Canvas2D`/`Camera` call `beginCamera` between\n * their own transform and their children's).\n *\n * A node inside a 2.5D space is placed by its frame instead — the whole\n * projection from its own plane to the space root's, built by the same\n * `node-space.ts` the renderer uses — so it is a homography, and `nodeBox`\n * reports the projected corners.\n *\n * Mirrors the render walk exactly, including the camera's `translate(rect.x,\n * -rect.y)` — if a box ever disagrees with the pixels, the divergence is here.\n *\n * `@internal`, and shared with `text-geometry.ts`: a caret drawn over a node has\n * to land in the same space as the box drawn around it, so both must come from\n * this one walk rather than two that agree by inspection.\n */\n/** @internal */\nexport function renderMatrix(node: Node2D): Matrix2D {\n const frame = spaceFrameOf(node);\n if (frame) return multiply(renderMatrix(frame.root), frame.screen);\n const parent = node.parent;\n return parent ? multiply(childrenMatrix(parent), node._localMatrix()) : node._localMatrix();\n}\n\n/**\n * The CTM `parent`'s children are placed under, before their own transform: its\n * render matrix, then whatever camera it opens. For a space root that is the\n * camera over its own plane; inside a space it is the parent's own frame, since\n * a child's place is measured in its parent's plane.\n */\nfunction childrenMatrix(parent: Node2D): Matrix2D {\n const m = renderMatrix(parent);\n const camera = parent._spaceCamera();\n if (camera) return multiply(m, spaceRootFrame(parent, camera).screen);\n const cam = parent._cameraScope();\n if (!cam) return m;\n const r = parent.layoutBounds;\n return multiply(m, cameraMatrix(r.x, -r.y, cam.lookAt, cam.zoom, cam.heading));\n}\n\n/**\n * Where `point` (viewport space) lands on the plane the node at `path` moves in\n * when its `x`/`y` change — its parent's, through any camera in between, pushed\n * out to the node's own `depth` in a space — in its parent's frame: centred on\n * the parent (on its slot, for a node a parent places — see `ChildPlacement`),\n * y-up. `null` when the path does not name a 2D node below the\n * root, or that plane cannot be reached at that point (edge-on, or the point is\n * behind the camera).\n *\n * Two answers differ by exactly the change of `x`/`y` that carries the node from\n * one point to the other — what a move handle needs once a node can sit in\n * depth, where a screen delta is no longer a parent delta.\n *\n * Under a parent with coordinates of its own (`Node2D._planeOf`) the answer is\n * in them, and is the `x`/`y` that centres the node on `point`.\n */\nexport function parentPlanePointAt(root: Node2D, path: string, point: Vector2): Vector2 | null {\n if (path === \"\") return null;\n const node = nodeAt(root, path);\n const parent = node instanceof Node2D ? node.parent : null;\n if (!(node instanceof Node2D) || !parent) return null;\n const m = movePlaneMatrix(node, parent);\n const inv = invert(m);\n if (!inv) return null;\n const p = applyToPoint(inv, { x: point.x, y: -point.y });\n if (behindCamera(m, p)) return null;\n const plane = parent._planeOf(node);\n if (!plane) return { x: p.x, y: -p.y };\n // A slot's frame is already centred on the node's box; the parent's is not.\n const box = node._placement() ? null : node.layoutBounds;\n return plane.toCoords(p.x - (box?.x ?? 0), (box?.y ?? 0) - p.y);\n}\n\n/**\n * Where `point` (viewport space) lands in the coordinates the node at `path`\n * positions its children in ({@link Node2D._planeOf}): the `x`/`y` a child takes\n * to be centred there, before it exists. `null` when that node's children are\n * positioned in pixels, which is how a host tells the two apart.\n */\nexport function childPlanePointAt(root: Node2D, path: string, point: Vector2): Vector2 | null {\n const parent = nodeAt(root, path);\n if (!(parent instanceof Node2D)) return null;\n const plane = parent._planeOf(null);\n if (!plane) return null;\n const inv = invert(childrenMatrix(parent));\n if (!inv) return null;\n const p = applyToPoint(inv, { x: point.x, y: -point.y });\n return plane.toCoords(p.x, -p.y);\n}\n\n/**\n * What keeps the node at `path` looking exactly as it does once it moves under\n * the node at `parentPath`, as a design tool does: each of `offsets` (an\n * `x`/`y` it takes under its parent now: its own, or where a move takes it)\n * carried to the one that puts its centre at the same place there, and the\n * `turn` to add to its rotation and the `scale` to multiply its scale by so\n * the parents' own turn and scale, cameras included, are undone. `null` when\n * that parent arranges its children in a run or a grid, sits inside the node,\n * or either is not here.\n */\nexport function reparentPlacementAt(\n root: Node2D, path: string, parentPath: string, offsets: readonly Vector2[],\n): ReparentPlacement | null {\n const node = nodeAt(root, path);\n const to = nodeAt(root, parentPath);\n const from = node instanceof Node2D ? node.parent : null;\n if (!(node instanceof Node2D) || !(from instanceof Node2D) || !(to instanceof Node2D)) return null;\n for (let at: Node | null = to; at; at = at.parent) if (at === node) return null;\n const box = node.layoutBounds;\n const plane = to._planeOf(null);\n const slot = plane ? null : to._slotFor({ width: box?.width ?? 0, height: box?.height ?? 0 });\n if (!plane && !slot) return null;\n const along = movePlaneMatrix(node, from);\n const back = invert(along);\n const into = invert(childrenMatrix(to));\n if (!back || !into) return null;\n\n const placed = node._placement();\n const was = childFold(from);\n const will = childFold(to);\n const turn = was.rotation + (placed?.rotation ?? 0) - will.rotation;\n const scale = will.scale === 0 ? 1 : (was.scale * (placed?.scale ?? 1)) / will.scale;\n const shift = node._centreShift(node.rotation + turn, node.scale * scale);\n\n // The plane the node's x/y move it on, where its centre is drawn now.\n const here = applyToPoint(back, applyToPoint(renderMatrix(node), { x: 0, y: 0 }));\n const own = from._planeOf(node);\n const pixels = (offset: Vector2): Vector2 => (own ? { ...own.toOffset(offset.x, offset.y) } : offset);\n const now = pixels({ x: node.x, y: node.y });\n const moved = offsets.map((offset) => {\n const o = pixels(offset);\n const drawn = applyToPoint(along, { x: here.x + o.x - now.x, y: here.y - (o.y - now.y) });\n const centre = applyToPoint(into, drawn);\n const x = centre.x - shift.x;\n const y = centre.y - shift.y;\n return plane ? plane.toCoords(x, -y) : { x: x - slot!.x, y: slot!.y - y };\n });\n return { offsets: moved, turn, scale };\n}\n\n/** What {@link reparentPlacementAt} answers. */\nexport interface ReparentPlacement {\n /** Each offset asked about, under the new parent. */\n offsets: Vector2[];\n /** Degrees (clockwise) to add to the node's rotation, and to where its turns end. */\n turn: number;\n /** The factor to multiply the node's scale by, and where its scalings end. */\n scale: number;\n}\n\n/** The rotation and scale a child of `parent` is drawn under: its fold, then the camera it opens. */\nfunction childFold(parent: Node2D): { rotation: number; scale: number } {\n const folded = foldedTransform(parent);\n const cam = parent._cameraScope();\n return cam ? { rotation: folded.rotation - cam.heading, scale: folded.scale * cam.zoom } : folded;\n}\n\n/**\n * The node at `path`'s {@link NodeHandle}s with `at` in viewport space, where the\n * pixels put them; `null` when the path names no 2D node.\n */\nexport function nodeHandlesAt(root: Node2D, path: string): NodeHandle[] | null {\n const node = nodeAt(root, path);\n if (!(node instanceof Node2D)) return null;\n const m = renderMatrix(node);\n return node._handles().map(({ prop, at }) => {\n const p = applyToPoint(m, { x: at.x, y: -at.y });\n return { prop, at: { x: p.x, y: -p.y } };\n });\n}\n\n/**\n * The value of `prop` that puts its handle on the node at `path` under `point`\n * (viewport space), or `null` when there is no such handle or the point is off\n * the node's plane.\n */\nexport function handleValueAt(root: Node2D, path: string, prop: string, point: Vector2): Vector2 | null {\n const node = nodeAt(root, path);\n if (!(node instanceof Node2D)) return null;\n const m = renderMatrix(node);\n const inv = invert(m);\n if (!inv) return null;\n const p = applyToPoint(inv, { x: point.x, y: -point.y });\n if (behindCamera(m, p)) return null;\n return node._handleValue(prop, { x: p.x, y: -p.y });\n}\n\n/** The parent's frame at the node's depth, onto the screen: the plane its `x`/`y` slide it across. */\nfunction movePlaneMatrix(node: Node2D, parent: Node2D): Matrix2D {\n const frame = spaceFrameOf(node) ? spaceFrameForChildren(parent) : null;\n if (!frame) {\n // A slotted node's `x`/`y` move it within its slot, which may be turned.\n const slot = node._slotMatrix();\n return slot ? multiply(childrenMatrix(parent), slot) : childrenMatrix(parent);\n }\n const slot = node._slotAffine();\n const plane = slot ? multiplyAffine3(frame.view, slot) : frame.view;\n const atDepth = multiplyAffine3(plane, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, node.depth]);\n return multiply(renderMatrix(frame.root), spaceScreenMatrix(frame.camera, atDepth));\n}\n\n/**\n * Under a perspective the inverse also answers for the plane's reflection behind\n * the camera: a point there projects to the same pixel with a negative `w`, and\n * is not on screen at all.\n */\nfunction behindCamera(m: Matrix2D, local: Vector2): boolean {\n return isProjective(m) && (m.g ?? 0) * local.x + (m.h ?? 0) * local.y + (m.i ?? 1) <= 0;\n}\n\n/**\n * Folded rotation / scale / opacity from the scene root down to `node`, matching\n * the renderer's nested transforms and its pass-through alpha fold. The same\n * accumulation {@link Node2D.global} does, extended with the camera scopes: a\n * camera multiplies the scale by its `zoom` and adds `-heading` to the rotation\n * (the renderer applies `rotate(-heading)`).\n */\nfunction foldedTransform(node: Node2D): { rotation: number; scale: number; opacity: number } {\n let rotation = 0;\n let scale = 1;\n let opacity = 1;\n for (let n: Node2D | null = node; n; n = n.parent) {\n const slot = n._placement();\n rotation += n.rotation + (slot?.rotation ?? 0);\n scale *= n.scale * (slot?.scale ?? 1);\n opacity *= n.opacity * (slot?.opacity ?? 1);\n // Skip the node's own camera: it scopes its children, not itself.\n const cam = n !== node ? n._cameraScope() : null;\n if (cam) {\n rotation -= cam.heading;\n scale *= cam.zoom;\n }\n }\n return { rotation, scale, opacity };\n}\n\n/** Build the viewport-space box for `node` at the current frame. */\nexport function nodeBox(node: Node2D, path: string): NodeBox {\n const b = node._localBounds();\n // `worldAnchors` maps offsets centred on the matrix's origin, so shift the\n // matrix onto the bounds' own centre first — that is what lets a node whose\n // ink is off-centre report a box that actually sits on the ink.\n // The matrix is canvas y-down; the bounds are y-up, hence the sign on y.\n const m = b.x === 0 && b.y === 0\n ? renderMatrix(node)\n : multiply(renderMatrix(node), translation(b.x, -b.y));\n const anchors = worldAnchors(m, b.width / 2, b.height / 2);\n const folded = foldedTransform(node);\n return {\n id: node.id,\n path,\n type: node.className,\n topLeft: anchors.topLeft,\n topRight: anchors.topRight,\n bottomRight: anchors.bottomRight,\n bottomLeft: anchors.bottomLeft,\n center: anchors.center,\n width: b.width,\n height: b.height,\n rotation: folded.rotation,\n scale: folded.scale,\n opacity: folded.opacity,\n locked: node.locked,\n };\n}\n\n/**\n * The box at a structural path, in either dimension, or `null` when the path\n * doesn't resolve.\n *\n * The one entry point that answers for a 3D node as well as a 2D one, which a\n * bare {@link nodeBox} cannot: a mesh is not a `Node2D` and has no box of its\n * own — what it has is a projection into the viewport that holds it, and finding\n * that viewport is part of resolving the path (see `node-picking3d.ts`).\n *\n * Walks {@link Node._allChildren}, so the paths it accepts are the ones every\n * other structural walk in the engine produces.\n */\nexport function nodeBoxAt(root: Node2D, path: string): NodeBox | null {\n if (path === \"\") return nodeBox(root, path);\n\n let node: Node = root;\n let canvas: { node: Viewport3D; path: string } | null = null;\n const segments = path.split(\".\");\n for (let i = 0; i < segments.length; i++) {\n if (isViewport3D(node)) canvas = { node, path: prefixPath(segments, i) };\n const next = node._allChildren[Number(segments[i])];\n if (!next) return null;\n node = next;\n }\n\n if (node instanceof Node2D) return nodeBox(node, path);\n // A 3D node: ask the viewport that holds it. There is always one — a `Node3D`\n // cannot be parented anywhere else (the engine throws rather than allowing\n // it) — so a `null` here is a malformed tree rather than a missing case.\n if (!canvas) return null;\n const frame = canvas3DFrame(canvas.node, canvas.path);\n return collectBoxes3D(canvas.node, frame, canvas.path).find((box) => box.path === path) ?? null;\n}\n\n/**\n * The node at a structural path, in either dimension, or `null` when the path\n * doesn't resolve.\n *\n * The resolution half of {@link nodeBoxAt}, split out for callers that want the\n * node rather than its box — `PlaybackController.getNodePropsAt`, which reads a\n * node's own props in its own space. Walks {@link Node._allChildren}, so it\n * accepts the same paths every other structural walk in the engine produces.\n */\nexport function nodeAt(root: Node2D, path: string): Node | null {\n if (path === \"\") return root;\n let node: Node = root;\n for (const segment of path.split(\".\")) {\n const next = node._allChildren[Number(segment)];\n if (!next) return null;\n node = next;\n }\n return node;\n}\n\n/** The first `count` segments of a split path, rejoined. */\nfunction prefixPath(segments: readonly string[], count: number): string {\n return segments.slice(0, count).join(\".\");\n}\n\n/**\n * Project a handful of points around the `Node3D` at `path`, or `null` when\n * the path doesn't resolve to a 3D node — a gizmo's counterpart to\n * {@link nodeBoxAt}, for the one thing a box can't answer: where would an\n * arbitrary point *near* the node, not just its extent, land on screen. See\n * {@link Node3DFrame} for the two point sets and the space each is in.\n *\n * `null` for a 2D path too, unlike `nodeBoxAt` — a `Node2D` has no matrix a\n * caller would ask this for; {@link nodeBox} already answers everything a 2D\n * handle needs directly in viewport space.\n */\nexport function projectNode3DAt(\n root: Node2D,\n path: string,\n parentPoints: readonly Vector3[],\n localPoints: readonly Vector3[],\n): Node3DFrame | null {\n if (path === \"\") return null;\n\n let node: Node = root;\n let canvas: { node: Viewport3D; path: string } | null = null;\n const segments = path.split(\".\");\n for (let i = 0; i < segments.length; i++) {\n if (isViewport3D(node)) canvas = { node, path: prefixPath(segments, i) };\n const next = node._allChildren[Number(segments[i])];\n if (!next) return null;\n node = next;\n }\n\n if (node instanceof Node2D || !canvas) return null;\n const frame = canvas3DFrame(canvas.node, canvas.path);\n return projectNode3D(canvas.node, frame, canvas.path, path, parentPoints, localPoints);\n}\n\n/**\n * The topmost node whose hit region contains `point` (viewport space, y-up,\n * origin at the viewport centre), or `null`. Children paint over their parent and\n * later siblings over earlier ones, so the walk tests children last-to-first\n * before falling back to the node itself.\n *\n * Skips fully transparent nodes — a scene built with spawn delays keeps\n * not-yet-visible nodes in the tree at `opacity: 0`, and those must not be\n * selectable. A node that clips (or pushes a camera, which clips to its viewport)\n * confines its subtree: a point outside its box cannot hit anything inside it.\n * The scene root is never returned; it is the stage, not a selectable node.\n *\n * The hit region is {@link Node2D.hitTestSelf} — the rotated layout box by default,\n * narrowed to the declared outline for shapes. A click in the corner of a rect's\n * box selects it; a click in the empty notch of a star's box does not.\n *\n * `tolerance` is grab-slop in scene units, applied outward from the ink. A host\n * passes its zoom-corrected pixel slop so the grab area stays constant on screen.\n * It is what makes thin shapes reachable.\n *\n * Cost: {@link renderMatrix} walks to the root per node, making a pick O(depth²).\n * Scene trees here are shallow (tens of nodes, depth < 10), so this is fine at\n * pointer rate. If it ever matters, thread the parent's accumulated matrix down\n * through the walk instead of recomputing — a change confined to this file.\n */\nexport function pickNode(root: Node2D, point: Vector2, tolerance = 0): NodeBox | null {\n return pickIn(root, \"\", point, tolerance, true);\n}\n\nfunction pickIn(node: Node2D, path: string, point: Vector2, tolerance: number, isRoot: boolean): NodeBox | null {\n if (node.opacity === 0 || node.hidden) return null;\n const drawn = spaceVisibility(node, isRoot);\n if (drawn === \"none\") return null;\n\n const inside = drawn === \"all\" && containsPoint(node, point, tolerance);\n // A clipping node (or one that opens a camera viewport) gates its subtree —\n // unless it is drawing nothing of its own, when it clips nothing either.\n if (!inside && drawn === \"all\" && node._confinesChildren()) return null;\n\n // A `Canvas3D`'s children come in both dimensions, and its 2D ones are\n // indexed against the *whole* list — see {@link childSlots}.\n const children = childSlots(node);\n const order = paintOrder(node, children);\n for (let k = order.length - 1; k >= 0; k--) {\n const i = order[k];\n const slot = children[i];\n if (slot === null) continue;\n const hit = pickIn(slot, nodePath(path, i), point, tolerance, false);\n if (hit) return hit;\n }\n\n // The 3D scene draws under the 2D children and over the canvas's own fill, so\n // it is tested in that order too: a HUD label wins over the mesh behind it,\n // and the mesh wins over the viewport it sits in.\n if (isViewport3D(node) && inside) {\n const hit = pickNode3D(node, canvas3DFrame(node, path), point, tolerance, path);\n if (hit) return hit;\n }\n\n if (isRoot) return null;\n // A locked node declines to *be* the answer while still having gated its\n // subtree above — so a click inside a locked group lands on nothing rather\n // than falling through to whatever is behind the group.\n if (node.locked) return null;\n return inside ? nodeBox(node, path) : null;\n}\n\n/**\n * Collect every visible node's box in draw order (parents before children, so a\n * host can paint them in the order the renderer did). Skips `opacity: 0` nodes\n * and the scene root, matching {@link pickNode}.\n *\n * A `Canvas3D` also contributes a box per `Node3D` inside it, projected into its\n * plane — see `node-picking3d.ts`. They sit after the viewport's own box and\n * before its 2D children's, which is where the 3D pass is painted; among\n * themselves they are ordered **near camera first**, because a 3D scene has no\n * draw order of its own for them to be in.\n */\nexport function collectBoxes(node: Node2D, path: string, out: NodeBox[], isRoot: boolean): void {\n if (node.opacity === 0 || node.hidden) return;\n const drawn = spaceVisibility(node, isRoot);\n if (drawn === \"none\") return;\n // Locked nodes keep their box — a host still has to draw a selection outline\n // around one picked from its layer tree. What the box carries is the flag, so\n // a marquee can leave it out without a second walk.\n if (!isRoot && drawn === \"all\") out.push(nodeBox(node, path));\n\n if (isViewport3D(node)) {\n for (const box of collectBoxes3D(node, canvas3DFrame(node, path), path)) out.push(box);\n }\n\n const children = childSlots(node);\n for (const i of paintOrder(node, children)) {\n const slot = children[i];\n if (slot !== null) collectBoxes(slot, nodePath(path, i), out, false);\n }\n}\n\n/**\n * How much of `node` a space lets the renderer draw: `\"all\"` outside a space and\n * for a node facing the camera in front of it; `\"children\"` for one edge-on or\n * behind the lens, whose own paint is skipped while its children, placed by\n * frames of their own, are not; `\"none\"` for one the renderer skips outright — a\n * hidden back face, or a flattening node with nothing on screen.\n */\nfunction spaceVisibility(node: Node2D, isRoot: boolean): \"all\" | \"children\" | \"none\" {\n if (isRoot) return \"all\";\n const frame = spaceFrameOf(node);\n if (!frame) return \"all\";\n if (!node.backfaceVisible && frame.facesAway) return \"none\";\n if (frame.paints) return \"all\";\n return node._rendersChildrenInSpace() ? \"children\" : \"none\";\n}\n\n/**\n * The slots of `children` in the order the renderer paints them: authored\n * order, except among siblings in a space, which paint far to near.\n */\nfunction paintOrder(node: Node2D, children: readonly (Node2D | null)[]): number[] {\n const natural = children.map((_, i) => i);\n const frame = spaceFrameForChildren(node);\n if (!frame) return natural;\n const slots = natural.filter((i) => children[i] !== null);\n const frames = slots.map((i) => spaceChildFrame(frame, children[i]!));\n return spaceChildOrder(frames).map((k) => slots[k]);\n}\n\n/**\n * The node's children as **index slots**, with a `null` wherever the slot holds\n * something this walk doesn't descend into.\n *\n * Everywhere but a `Canvas3D` this is just `children`, and the array is returned\n * untouched. A `Canvas3D` is the one node holding both dimensions, and its\n * `Node2D.children` drops the meshes — which would renumber its HUD children and\n * hand every one of them the path of an earlier sibling. So its slots are taken\n * from the authored list with the 3D ones blanked out: same indices as the\n * document, and the meshes reached through their own walk instead.\n */\nfunction childSlots(node: Node2D): readonly (Node2D | null)[] {\n if (!(isViewport3D(node))) return node.children;\n return node._allChildren.map((child) => (child instanceof Node2D ? child : null));\n}\n\n/** What the 3D walk needs to know about the viewport it is projecting into. */\nfunction canvas3DFrame(canvas: Viewport3D, path: string): Canvas3DFrame {\n return { box: nodeBox(canvas, path), matrix: renderMatrix(canvas) };\n}\n\n/** Map `point` into `node`'s local space and ask the node whether it was hit. */\nfunction containsPoint(node: Node2D, point: Vector2, tolerance: number): boolean {\n const m = renderMatrix(node);\n const inv = invert(m);\n if (!inv) return false; // zero scale — nothing to hit\n // The render matrix works in canvas (y-down) space; `worldAnchors` flips y in\n // and back out, so the inverse does the same to land in the node's centred,\n // y-up local frame — the space `hitTestSelf` and the clip descriptors use.\n const p = applyToPoint(inv, { x: point.x, y: -point.y });\n if (behindCamera(m, p)) return false;\n return node._hitTestSelf({ x: p.x, y: -p.y }, tolerance);\n}\n", "import { Node2D } from \"@/components/trees/2d/node2d\";\nimport { Text } from \"@/components/builtins/text/text\";\nimport { textStateOf } from \"@/components/modules/text-layout\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { applyToPoint } from \"@/attributes/layout/matrix2d\";\nimport { caretCount, type TextBlockSource } from \"@/render/text-layout\";\nimport { renderMatrix } from \"./node-picking\";\n\n/**\n * Where a Text node's caret slots landed on screen — the measurement a host\n * needs to draw its own text cursor and selection over the rendered glyphs.\n *\n * **Space.** Viewport space, exactly as {@link NodeBox}: origin at the viewport\n * centre, y-up, viewport units, camera folded in. A caret and the selection box\n * around it therefore come out of the same walk and cannot disagree.\n *\n * **Why the host draws it.** Anything approximating glyph positions outside the\n * shaper — a DOM input laid over the canvas, say — drifts from the render the\n * moment the font, the line height or the wrapping does, and CSS `line-height`\n * and the renderer's height multiplier are not the same quantity to begin with. Handing\n * over the real slots means the rendered text stays the thing being edited.\n */\nexport interface NodeTextLayout {\n /** Structural path of the node measured, as {@link NodeBox.path}. */\n path: string;\n /** The string the slots describe. */\n text: string;\n /**\n * Every caret slot, in offset order: `carets[i]` sits before character `i`,\n * and the last sits after the final character — so there are `text.length + 1`\n * of them, and a caret offset is always a valid index.\n *\n * Each is a *segment*, not a point, because a rotated node's cursor is a\n * rotated line: draw from `top` to `bottom`.\n */\n carets: TextCaret[];\n /**\n * Line ranges over caret offsets, for Home/End and vertical arrow keys. A\n * hard line break belongs to neither line, so `lines[n].end` and\n * `lines[n + 1].start` differ by one where the break is.\n */\n lines: { start: number; end: number }[];\n}\n\n/** One caret slot: the line an editor would draw for a cursor at this offset. */\nexport interface TextCaret {\n /** Character offset this slot sits before. */\n offset: number;\n /** Top and bottom of the cursor, viewport space. */\n top: Vector2;\n bottom: Vector2;\n}\n\n/** One line's worth of a selected range, as a quad in viewport space. */\nexport interface TextRangeQuad {\n topLeft: Vector2;\n topRight: Vector2;\n bottomRight: Vector2;\n bottomLeft: Vector2;\n}\n\n/**\n * Measure `node`'s caret slots in viewport space, or `null` when it has none to\n * report — not a {@link Text}, nothing shaped yet, or a shape the caret model\n * doesn't cover (see {@link RenderContext2D.layoutTextBlock}).\n *\n * The block-local layout comes from the backend, because that is where glyphs\n * are actually positioned; everything below is the same mapping\n * {@link nodeBox} applies to a node's corners.\n */\nexport function nodeTextLayout(\n node: Node2D,\n path: string,\n source: TextBlockSource,\n): NodeTextLayout | null {\n // A text's state is what it last drew.\n const state = node instanceof Text ? textStateOf(node) : null;\n if (!state) return null;\n const block = source.layoutTextBlock(state);\n if (!block) return null;\n\n const m = renderMatrix(node);\n // The block is laid out about the node's own origin — which is also where\n // `_localBounds` centres the box, and what `verticalAlign` offsets it from —\n // so a block-local offset is a node-local one, unshifted. Block coordinates are already canvas (y-down), which is\n // the space the matrix works in, so unlike `worldAnchors` (which takes y-up\n // corner offsets) only the *result* is flipped back to y-up viewport space.\n const at = (x: number, y: number): Vector2 => {\n const p = applyToPoint(m, { x, y });\n return { x: p.x, y: -p.y };\n };\n\n const carets: TextCaret[] = new Array(caretCount(block));\n const lines: { start: number; end: number }[] = [];\n for (const line of block.lines) {\n lines.push({ start: line.start, end: line.end });\n for (let i = 0; i < line.carets.length; i++) {\n const x = line.carets[i];\n carets[line.start + i] = {\n offset: line.start + i,\n top: at(x, line.top),\n bottom: at(x, line.bottom),\n };\n }\n }\n\n return { path, text: (node as unknown as { text: string }).text, carets, lines };\n}\n\n/**\n * The caret offset nearest `point` (viewport space) — what a click or a drag\n * over the rendered text should place the cursor at.\n *\n * Nearest *slot*, by distance to the caret segment rather than to its midpoint:\n * a click below a short first line should land on that line's nearest slot, and\n * midpoints would pull it toward whichever line's centre happened to be closer.\n * Segment distance also keeps this correct for rotated and scaled text without\n * needing a separate case, since the slots arrive already transformed.\n */\nexport function caretOffsetAt(layout: NodeTextLayout, point: Vector2): number {\n let best = 0;\n let bestDistance = Infinity;\n for (const caret of layout.carets) {\n const d = distanceToSegment(point, caret.top, caret.bottom);\n if (d < bestDistance) {\n bestDistance = d;\n best = caret.offset;\n }\n }\n return best;\n}\n\n/**\n * The quads covering `[start, end)`, one per line the range touches — what a\n * host fills to draw a selection highlight.\n *\n * Per line rather than one box for the whole range, because a range spanning a\n * line break covers two disjoint areas and a single enclosing box would paint\n * over the gap between them.\n */\nexport function caretRangeQuads(\n layout: NodeTextLayout,\n start: number,\n end: number,\n): TextRangeQuad[] {\n const from = Math.max(0, Math.min(start, end));\n const to = Math.min(layout.carets.length - 1, Math.max(start, end));\n const quads: TextRangeQuad[] = [];\n for (const line of layout.lines) {\n const a = Math.max(from, line.start);\n const b = Math.min(to, line.end);\n if (a >= b) continue; // empty on this line\n const left = layout.carets[a];\n const right = layout.carets[b];\n quads.push({\n topLeft: left.top,\n topRight: right.top,\n bottomRight: right.bottom,\n bottomLeft: left.bottom,\n });\n }\n return quads;\n}\n\n/** Distance from `p` to the segment `a`–`b`. */\nfunction distanceToSegment(p: Vector2, a: Vector2, b: Vector2): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lengthSq = dx * dx + dy * dy;\n // A degenerate segment (a zero-height line box) is just a point.\n const t = lengthSq === 0\n ? 0\n : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSq));\n return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));\n}\n", "import { AssetManager } from \"../assets/manager\";\nimport { MeasureContext2D } from \"../render/measure-context\";\nimport { CanvasRenderContext2D } from \"../render/canvas-render-context2d\";\nimport { asTextBlockSource } from \"../render/text-layout\";\nimport { renderIssueKey, toRenderIssue, type RenderIssue } from \"../render/render-issue\";\nimport { StateEvaluator } from \"./state-evaluator\";\nimport { renderSettled, SETTLE_PASSES, type SettleOutcome } from \"./settle\";\nimport { NodeState, TreeState, WaveformInfo, nodePath } from \"@/project/tree\";\nimport { AudioRequest } from \"@/attributes/audio/request\";\nimport { StorageAdapter } from \"../platform/storage-adapter\";\nimport { BuildError, AssetTimeline, AssetTimelineResult, type AssetTimelineProfile } from \"./asset-timeline\";\nimport { ClipStore, DEFAULT_PRECOMP_BUDGET_MS } from \"./clip-store\";\nimport type { AssetDecl } from \"@/assets/scope\";\nimport { yieldToScheduler } from \"@/util/scheduler\";\nimport { Ticker, TimeCallback } from \"@/platform/ticker\";\nimport { AudioSink } from \"@/platform/audio-sink\";\nimport { AssetCatalog } from \"@/assets/catalog\";\nimport { AssetNotLoadedError } from \"@/assets/errors\";\nimport type { AssetRecord } from \"@/assets/record\";\nimport { Size2D } from \"@/attributes/layout/size\";\nimport { Node } from \"@/components/trees/node/node\";\nimport { Node2D, type NodeHandle } from \"@/components/trees/2d/node2d\";\nimport type { NodeEditorStates } from \"@/components/trees/node/node-editor-state\";\nimport type { ProjectDocument } from \"@/document/project\";\nimport type { Registry } from \"@/document/registry\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { NodeBox, childPlanePointAt, collectBoxes, handleValueAt, nodeAt, nodeBoxAt, nodeHandlesAt, parentPlanePointAt, pickNode, projectNode3DAt, reparentPlacementAt, type ReparentPlacement } from \"./node-picking\";\nimport type { Node3DFrame } from \"./node-picking3d\";\nimport type { Vector3 } from \"@/render3d/vector3\";\nimport { NodeTextLayout, nodeTextLayout } from \"./text-geometry\";\nimport { spanFrames, spansCovering, trackFrameCount, type TrackSpan } from \"./placement\";\nimport { clipFrameToTime, clipTimeToFrame } from \"./frame-time\";\n\n/**\n * Transient prop values layered over a node's evaluated state — see\n * {@link PlaybackController.setNodeOverride}. Keys are prop names the node\n * accepts (`x`, `y`, `rotation`, `width`, …).\n */\nexport type NodeOverride = Record<string, unknown>;\n\n/** Dependencies injected into `PlaybackController` at construction time. */\nexport type ControllerParams = {\n /** The project to play, its fps and viewport resolved — see `Session`. */\n project: ProjectDocument;\n /** The vocabulary its clips compile against. */\n registry: Registry;\n renderContext: CanvasRenderContext2D;\n measurer: MeasureContext2D;\n storageAdapter: StorageAdapter;\n masterClock: Ticker;\n audioDevice: AudioSink;\n assets: AssetCatalog;\n /**\n * Wall-clock ms the background discovery may run before yielding. Defaults\n * to {@link DEFAULT_PRECOMP_BUDGET_MS}; `0` in tests yields between every\n * sample interval, making preemption deterministic.\n */\n precompBudgetMs?: number;\n precompProfile?: AssetTimelineProfile;\n /**\n * Called each time background discovery lands another track. Passed at\n * construction so a fast first track can't publish before the caller attaches.\n */\n onPrecompProgress?: (result: AssetTimelineResult) => void;\n};\n\n/**\n * Orchestrates playback of a project document.\n *\n * On construction it discovers what frame 0 needs, then streams the rest of the\n * project's asset timeline in behind the first paint. Every clock tick:\n *\n * 1. Loads assets required at the current frame (`AssetManager.loadAt`).\n * 2. Evaluates the tracks on screen and lays them out (`StateEvaluator`).\n * 3. Renders the frame to the render context.\n * 4. Prefetches assets for upcoming frames.\n */\nexport class PlaybackController {\n private renderContext: CanvasRenderContext2D;\n private measurer: MeasureContext2D;\n private storageAdapter: StorageAdapter;\n private masterClock: Ticker;\n private stateEvaluator: StateEvaluator;\n private assetManager: AssetManager;\n private audioDevice: AudioSink;\n /**\n * Held rather than merely handed on, because {@link recoverMissingAsset} has\n * to build a record for a source no pass declared, from what the catalog\n * knows of it.\n */\n private readonly assetCatalog: AssetCatalog;\n /**\n * Called synchronously at the end of every frame this controller paints, on\n * the same task as the draw — for a host drawing *over* the canvas (a\n * selection box, a caret) that must measure the tree for the frame just\n * drawn rather than poll and trail a fast scrub. Called after the draw, so a\n * throwing listener is never mistaken for a render failure.\n */\n onFramePainted?: (frame: number) => void;\n\n /** Set by dispose(); once true the controller must never touch its (now-freed) render context again. */\n private disposed = false;\n /** One background pass at a time — see {@link startBackgroundPrecomp}. */\n private precompRunning = false;\n /**\n * Whether a frame has ever been drawn. Every render pass but {@link repaint}\n * loads the frame's assets first, so this is what `repaint` waits on before\n * it will draw one of its own.\n */\n private hasPainted = false;\n /**\n * Monotonic token bumped by every seek / tick / swap. A render pass captures\n * it at entry and bails before painting if a newer pass has begun, so a\n * superseded seek never stamps its stale frame over a newer one.\n */\n private seekGeneration = 0;\n private readonly precompBudgetMs: number;\n private readonly onPrecompProgress?: (result: AssetTimelineResult) => void;\n readonly fps: number;\n readonly viewport: Size2D;\n private readonly precomper: AssetTimeline;\n /** The one build per track that discovery, the evaluator and the editor API share. */\n private readonly store: ClipStore;\n /**\n * Transient prop values re-applied after every state evaluation, keyed by\n * structural path so they survive a rebuild. See {@link setNodeOverride}.\n */\n private readonly overrides = new Map<string, NodeOverride>();\n /** Latest assembled precomp result. */\n precomp: AssetTimelineResult;\n\n /** Every track's span on the project timeline, in document order. */\n get spans(): readonly TrackSpan[] {\n return this.precomp.tracks.map((track, index) => ({\n id: track.id,\n index,\n startFrame: track.startFrame,\n endFrame: track.startFrame + track.frameCount - 1,\n }));\n }\n\n get totalFrames(): number {\n return this.precomp.totalFrames;\n }\n\n /** Total playback duration in seconds. */\n get totalDuration(): number {\n return this.precomp.totalDuration;\n }\n\n /** The track the editor API reads from — see `StateEvaluator.currentTrackId`. */\n get currentTrackId(): string | null {\n return this.stateEvaluator.currentTrackId;\n }\n\n /**\n * Errors collected while discovering tracks, plus any thrown while\n * *drawing* — one list, because a consumer showing them has the same thing\n * to say about both: this frame is not what the document says.\n */\n get buildErrors(): BuildError[] {\n if (this.renderErrors.length === 0) return this.precomp.buildErrors;\n return [...this.precomp.buildErrors, ...this.renderErrors];\n }\n\n /**\n * Errors thrown by a render pass, deduplicated by message. A render throwing\n * happens per frame, at pointer rate while scrubbing, and left to propagate\n * it was an unhandled rejection and a canvas that simply stopped drawing.\n */\n private readonly renderErrors: BuildError[] = [];\n\n /** Called when {@link renderErrors} gains an entry. Set by the host. */\n onRenderError?: (errors: BuildError[]) => void;\n\n /**\n * Record a draw-time failure and tell the host, once per distinct message.\n * Swallowing it is the point: one bad frame must not take down the clock loop.\n */\n private captureRenderError(error: unknown, frame?: number, issue?: RenderIssue): void {\n const e = error instanceof Error ? error : new Error(String(error));\n // A frame can reach for an asset no pass declared — an override previewing\n // an edit puts a picture on a node the rebuild that would declare it has\n // not run yet. The error names the source, so load it and paint again.\n if (frame !== undefined && this.recoverMissingAsset(e, frame)) return;\n if (issue) {\n const key = renderIssueKey(issue);\n if (this.renderErrors.some((prior) => prior.issue && renderIssueKey(prior.issue) === key)) return;\n } else if (this.renderErrors.some((prior) => !prior.issue && prior.message === e.message)) return;\n this.renderErrors.push({\n trackId: this.stateEvaluator.currentTrackId ?? \"\",\n message: e.message,\n ...(issue ? { issue, ...(issue.nodeId !== undefined && { nodeId: issue.nodeId }) } : { stack: e.stack }),\n });\n this.onRenderError?.(this.buildErrors);\n }\n\n /**\n * Widen the drawing track's index by what the draw found missing, so the next\n * visit to this frame loads it ahead. The owner is the node the error names,\n * or else whoever declared the source elsewhere in the clip.\n */\n private learnMissingAsset(error: AssetNotLoadedError, frame: number): void {\n const decl = declOf(error, this.assetCatalog);\n if (!decl) return;\n for (const trackId of [...this.stateEvaluator.activeTrackIds].reverse()) {\n const instance = this.store.instanceOf(trackId);\n const track = this.precomp.tracks.find((t) => t.id === trackId);\n if (!instance || !track) continue;\n let ownerKey: string | undefined;\n if (error.nodeId !== undefined) {\n instance.forEachOwner((node, key) => {\n if (ownerKey === undefined && node.id === error.nodeId) ownerKey = key;\n });\n }\n ownerKey ??= this.store.ownersOf(trackId, error.src).values().next().value;\n if (ownerKey === undefined) continue;\n const next = this.precomper.learn(trackId, ownerKey, decl, Math.floor(frame) - track.startFrame);\n if (next !== this.precomp) this.adoptPrecomp(next);\n return;\n }\n }\n\n /**\n * Sources already tried by {@link recoverMissingAsset}, so a picture that\n * genuinely cannot be fetched is reported rather than re-fetched every frame\n * of a drag. Cleared by {@link clearRenderErrors}.\n */\n private readonly rescuedAssets = new Set<string>();\n\n /**\n * Load an asset a frame reached for but nothing had declared, then paint that\n * frame again. Deliberately narrow: only {@link AssetNotLoadedError}, only a\n * source the catalog can describe, and only once per source.\n */\n private recoverMissingAsset(error: Error, frame: number): boolean {\n if (!(error instanceof AssetNotLoadedError)) return false;\n // Audio is fetched on demand by the audio device, not through the storage adapter.\n if (error.assetType === \"audio\") return false;\n const token = `${error.assetType}:${error.src}`;\n if (this.rescuedAssets.has(token)) return false;\n this.rescuedAssets.add(token);\n // Once per source, like the rescue: a source that never loads would otherwise republish every frame.\n this.learnMissingAsset(error, frame);\n\n const record = this.recordFor(error.assetType, error.src, frame);\n if (!record) return false;\n\n void this.storageAdapter.loadAsset(error.src, record)\n .then(() => {\n if (this.disposed) return;\n this.renderAt(this.stateEvaluator.currentFrame);\n this.settleTrailing();\n })\n .catch((cause) => {\n if (this.disposed) return;\n // No `frame`, so it cannot come back through here a second time.\n this.captureRenderError(\n new Error(`${error.message}\\n\\nLoading it directly also failed: ${String(cause)}`),\n );\n });\n return true;\n }\n\n /**\n * A one-frame record describing `src` well enough to load it, from the\n * catalog's own metadata — or `null` when the catalog has never heard of it.\n */\n private recordFor(type: AssetNotLoadedError[\"assetType\"], src: string, frame: number): AssetRecord | null {\n try {\n if (type === \"font\") {\n // 400 is what an unsuffixed font key assumes.\n return {\n type: \"font\", src, startFrame: frame, endFrame: frame,\n fontFamily: src, fontWeight: 400,\n };\n }\n if (type === \"image\") {\n // Throws for a source the catalog has never heard of.\n this.assetCatalog.getImageMeta(src);\n return { type: \"image\", src, startFrame: frame, endFrame: frame };\n }\n this.assetCatalog.getVideoMeta(src);\n return {\n type: \"video\", src, startFrame: frame, endFrame: frame,\n trimStart: 0, trimEnd: this.assetCatalog.getVideoDuration(src),\n };\n } catch {\n return null;\n }\n }\n\n /** Forget draw-time errors — called when what they were about is replaced. */\n clearRenderErrors(): void {\n this.rescuedAssets.clear();\n if (this.renderErrors.length === 0) return;\n this.renderErrors.length = 0;\n this.onRenderError?.(this.buildErrors);\n }\n\n constructor(params: ControllerParams) {\n const { project } = params;\n if (project.fps === undefined || project.viewport === undefined) {\n throw new Error(\"PlaybackController takes a project whose fps and viewport are resolved — see Session.\");\n }\n this.renderContext = params.renderContext;\n this.measurer = params.measurer;\n this.masterClock = params.masterClock;\n this.storageAdapter = params.storageAdapter;\n this.audioDevice = params.audioDevice;\n this.fps = project.fps;\n this.viewport = project.viewport;\n this.precompBudgetMs = params.precompBudgetMs ?? DEFAULT_PRECOMP_BUDGET_MS;\n this.onPrecompProgress = params.onPrecompProgress;\n this.assetCatalog = params.assets;\n\n const scope = {\n registry: params.registry,\n viewport: this.viewport,\n fps: this.fps,\n assets: params.assets,\n measurer: this.measurer,\n };\n this.store = new ClipStore(project, scope, {\n profile: params.precompProfile,\n // Nothing is resident before the manager exists, which is what the first build should see.\n isReady: (key) => this.assetManager?.isReady(key) ?? false,\n });\n this.precomper = new AssetTimeline(project, scope, { store: this.store });\n // Only what frame 0 needs — the rest streams in behind the first paint,\n // so time-to-first-frame is O(the tracks on screen), not O(the project).\n this.precomp = this.precomper.ensureCovering(0);\n this.stateEvaluator = new StateEvaluator(project, scope, this.store);\n this.assetManager = new AssetManager(\n this.precomp, this.storageAdapter, this.audioDevice,\n (error) => this.captureRenderError(error),\n );\n\n this.masterClock.setDuration(this.totalDuration);\n\n this.masterClock.onPlay((t, speed, reverse) => {\n this.audioDevice.play(t, speed, reverse);\n this.storageAdapter.setPlaying(true);\n });\n this.masterClock.onPause(() => {\n this.audioDevice.stop();\n this.storageAdapter.setPlaying(false);\n });\n this.masterClock.onTick(async (currentTime: number) => {\n // A tick is also a render pass: claim a generation so a stale paused\n // seek can't paint after the clock has moved on (and vice-versa).\n const gen = ++this.seekGeneration;\n const frame = clipTimeToFrame(currentTime, this.fps);\n if (frame >= this.totalFrames) this.masterClock.pause();\n this.discoverThrough(frame);\n await this.loadFrame(frame);\n if (!this.isCurrent(gen)) return;\n this.audioDevice.syncTo(currentTime);\n this.renderAt(frame);\n this.assetManager.prefetch(frame);\n this.trimAround(frame);\n });\n\n this.startBackgroundPrecomp();\n }\n\n /**\n * Discover the remaining tracks off the critical path, republishing the\n * asset timeline as each one lands. Deferred behind a yield so the first\n * frame paints before this starts competing for the main thread.\n */\n private startBackgroundPrecomp(): void {\n if (this.precompRunning || this.disposed || this.precomp.complete) return;\n this.precompRunning = true;\n void (async () => {\n try {\n await yieldToScheduler();\n // Looped: a document swapped in during the pass's last step has\n // no yield left for the pass to notice it by.\n while (!this.disposed && !this.precomp.complete) {\n const final = await this.precomper.runAsync({\n budgetMs: this.precompBudgetMs,\n isCancelled: () => this.disposed,\n onProgress: result => this.adoptPrecomp(result),\n });\n if (this.disposed) return;\n if (!this.precomp.complete) this.adoptPrecomp(final);\n }\n } finally {\n this.precompRunning = false;\n }\n })();\n }\n\n /**\n * Swap in a newly assembled result. `setPrecomp` resets the asset manager's\n * audio signature, which is what reschedules audio a new result changed.\n */\n private adoptPrecomp(next: AssetTimelineResult): void {\n if (this.disposed) return;\n this.precomp = next;\n this.assetManager.setPrecomp(next);\n this.masterClock.setDuration(this.totalDuration);\n this.onPrecompProgress?.(next);\n }\n\n /**\n * Discover the tracks covering `frame` before anything loads or draws it — a\n * track nobody discovered has no asset windows, so its frame would reach for\n * decodes nothing loaded. Cheap once they are: this runs on every tick.\n */\n private discoverThrough(frame: number): void {\n const next = this.precomper.ensureCovering(Math.floor(frame));\n if (next !== this.precomp) this.adoptPrecomp(next);\n }\n\n /**\n * Load `frame`'s assets and the layout gates of every track covering it —\n * a face must be resident before text measures, whatever its window says.\n */\n private async loadFrame(frame: number): Promise<void> {\n const gates: AssetRecord[] = [];\n for (const span of spansCovering(this.store.spans, Math.floor(frame))) {\n for (const record of this.store.layoutGates(span.id)) {\n if (!this.assetManager.isReady(record.src)) gates.push(record);\n }\n }\n if (gates.length === 0) {\n await this.assetManager.loadAt(frame);\n return;\n }\n await Promise.all([this.assetManager.loadAt(frame), this.assetManager.loadRecords(gates)]);\n }\n\n /** Keep built trees near the playhead only; a released track keeps what discovery found. */\n private trimAround(frame: number): void {\n if (Math.abs(frame - this.lastTrimFrame) < this.fps) return;\n this.lastTrimFrame = frame;\n this.store.trim(Math.floor(frame), Math.ceil(TRIM_HORIZON_SECONDS * this.fps));\n }\n\n private lastTrimFrame = 0;\n\n get isPlaying(): boolean {\n return this.masterClock.isPlaying;\n }\n\n /** Current playback position in seconds. */\n get currentTime(): number {\n return this.masterClock.currentTime;\n }\n\n /** Current playback position in frames (float). */\n get currentFrame(): number {\n return clipTimeToFrame(this.masterClock.currentTime, this.fps);\n }\n\n /** Register a callback that fires on every clock tick with the current time. */\n onTime(cb: TimeCallback): void {\n this.masterClock.onTime(cb);\n }\n\n /** Register a callback that fires when playback starts. */\n onPlay(cb: () => void): void {\n this.masterClock.onPlay(() => cb());\n }\n\n /** Register a callback that fires when playback pauses. */\n onPause(cb: () => void): void {\n this.masterClock.onPause(cb);\n }\n\n /** True while `gen` is still the latest seek/tick and the controller is alive. */\n private isCurrent(gen: number): boolean {\n return !this.disposed && gen === this.seekGeneration;\n }\n\n /** Evaluate the tracks on screen, lay them out, and render `frame`. */\n private renderAt(frame: number): void {\n // A disposed controller's surface is freed; an in-flight seek\n // (StrictMode double-mount, HMR) can resolve after dispose().\n if (this.disposed) return;\n this.hasPainted = true;\n this.renders++;\n try {\n // A track whose compile measured a face before it loaded builds again, now that it has.\n this.store.settleGates(spansCovering(this.store.spans, Math.floor(frame)).map((span) => span.id));\n // Evaluation and layout are inside the guard too: a command can throw\n // at a time, and a missing font throws while measuring.\n this.stateEvaluator.stateAt(frame);\n // After evaluation, before layout: an override beats what the document\n // evaluated to, and the layout pass that follows sees it.\n this.applyOverrides();\n this.stateEvaluator.layout(this.measurer);\n this.renderContext.execute(() => {\n this.stateEvaluator.render(this.renderContext);\n });\n for (const raw of this.renderContext.takeRenderIssues()) {\n const issue = toRenderIssue(raw);\n this.captureRenderError(new Error(issue.message), undefined, issue);\n }\n } catch (error) {\n this.captureRenderError(error, frame);\n }\n this.announcePaint(frame);\n }\n\n /** Tell {@link onFramePainted} a frame has landed, without letting a listener take the render loop down. */\n private announcePaint(frame: number): void {\n if (!this.onFramePainted) return;\n try {\n this.onFramePainted(Math.floor(frame));\n } catch (error) {\n console.error(\"[PlaybackController] onFramePainted listener threw:\", error);\n }\n }\n\n /**\n * Jump to `frame`, pausing playback first. Waits for required assets to\n * load before rendering, then prefetches upcoming frames.\n */\n async seek(frame: number): Promise<void> {\n if (this.disposed) return;\n const gen = ++this.seekGeneration;\n this.paintInFlight = gen;\n try {\n const clamped = Math.max(0, Math.min(frame, this.totalFrames));\n this.masterClock.pause();\n this.discoverThrough(clamped);\n this.masterClock.seek(clipFrameToTime(clamped, this.fps));\n await this.loadFrame(clamped);\n if (!this.isCurrent(gen)) return;\n // A cold seek can land on a video frame or an image no draw has asked\n // for yet: the render asks, the adapter warms, the frame paints again.\n if (await this.settle(() => this.renderAt(clamped), gen) === \"superseded\") return;\n this.assetManager.prefetch(clamped);\n this.trimAround(clamped);\n } finally {\n this.paintLanded(gen);\n }\n }\n\n /**\n * Swap in a new document without rebuilding the backend.\n *\n * A track whose clip is unchanged keeps its tree and its discovery; one whose\n * clip patches in place re-declares only the owners the edit can reach, and\n * republishes the asset timeline only when that changed it. **The swap does not\n * paint**: it loads the frame's assets first, and the canvas keeps the last\n * complete frame until then — strictly better than a current frame with a\n * hole where an added picture has not arrived. See {@link pendingSwap}.\n */\n setProject(next: ProjectDocument): void {\n if (this.disposed) return;\n // Claimed before anything is touched, so a seek parked on a yield unwinds\n // rather than painting into a timeline that moved under it.\n const gen = ++this.seekGeneration;\n\n this.precomper.setProject(next);\n this.stateEvaluator.setProject(next);\n // Adopts only when the swap changed what is published — an edit no declaration read changes nothing.\n this.discoverThrough(this.currentFrame);\n this.clearRenderErrors();\n this.masterClock.setDuration(this.totalDuration);\n\n // The timeline may now be shorter than where the playhead sat.\n const frame = Math.min(this.currentFrame, Math.max(0, this.totalFrames - 1));\n this.pendingSwap = gen;\n this.paintInFlight = gen;\n this.lastReplacePaint = this.loadAndRepaint(frame, gen);\n this.startBackgroundPrecomp();\n }\n\n /**\n * The catalog this controller builds against changed in place: build every\n * track again and repaint, as a swap to the same document would if it could\n * tell. A clip that failed for want of an entry the catalog now has builds,\n * and one measured against an old size is measured again.\n */\n reconcileCatalog(): void {\n if (this.disposed) return;\n this.store.reset();\n this.setProject(this.store.project);\n }\n\n /** Resolves when the paint {@link setProject} scheduled has landed — for a caller that swaps in order to read the result. */\n whenReplaced(): Promise<void> {\n return this.lastReplacePaint;\n }\n\n private lastReplacePaint: Promise<void> = Promise.resolve();\n\n /**\n * The generation claimed by the swap whose paint has not landed yet, or `0`.\n *\n * {@link repaint} stands down while this names the current generation: the\n * swap is loading the frame's assets and owes a paint that reads every\n * override as it stands when it lands. A generation rather than a flag,\n * because a seek can supersede the swap, and a flag nobody cleared would\n * leave `repaint` disabled for the rest of the session.\n */\n private pendingSwap = 0;\n\n /** Load `frame`'s assets, then paint — abandoning both if a newer pass began. */\n private async loadAndRepaint(frame: number, gen: number): Promise<void> {\n try {\n try {\n await this.loadFrame(frame);\n } catch (err) {\n console.error(\"[PlaybackController] swap asset load failed:\", err);\n return;\n }\n await this.settle(() => this.renderAt(frame), gen);\n } finally {\n // Only this swap's claim is released: a newer one has written its own.\n if (this.pendingSwap === gen) this.pendingSwap = 0;\n this.paintLanded(gen);\n }\n }\n\n /** Reposition the clock to `frame` without interrupting playback. */\n seekWhilePlaying(frame: number): void {\n // Invalidate any in-flight paused seek so its late render can't paint over\n // the live playback position.\n ++this.seekGeneration;\n const clamped = Math.max(0, Math.min(frame, this.totalFrames));\n this.masterClock.seek(clipFrameToTime(clamped, this.fps));\n }\n\n /**\n * Capture the current frame as a base-64 PNG data URL. Renders afresh — the\n * drawing buffer may have been cleared since the last tick — and loads the\n * frame's assets first, so the capture is right whatever the caller did\n * before it.\n */\n async screenshot(): Promise<string | undefined> {\n const frame = this.stateEvaluator.currentFrame;\n const gen = ++this.seekGeneration;\n this.paintInFlight = gen;\n try {\n await this.loadFrame(frame);\n if (!this.isCurrent(gen)) return undefined;\n // A capture is kept, not glanced at, so it waits for the upgrades a preview paints behind.\n if (await this.settle(() => this.renderAt(frame), gen, true) === \"superseded\") return undefined;\n return this.renderContext.screenshot();\n } finally {\n this.paintLanded(gen);\n }\n }\n\n /** {@link renderSettled} against this controller's generation, warning when a frame never settles. */\n private async settle(render: () => void, gen: number, upgrades = false): Promise<SettleOutcome> {\n const adapter = upgrades ? settlingUpgrades(this.storageAdapter) : this.storageAdapter;\n const outcome = await renderSettled(render, adapter, () => this.isCurrent(gen));\n if (outcome === \"exhausted\") {\n console.warn(`[PlaybackController] frame ${this.stateEvaluator.currentFrame} still had decodes pending after ${SETTLE_PASSES} passes`);\n }\n return outcome;\n }\n\n /**\n * The generation of the seek, swap or screenshot still on its way to its\n * paint, or `0`. A repaint behind decodes leaves that paint to it — see\n * {@link settleTrailing}.\n */\n private paintInFlight = 0;\n\n /** Bumped by every render, so a repaint owed to a landed upgrade can tell whether one has happened since. */\n private renders = 0;\n\n /** {@link renders} when an upgrade landed with a paint in flight, or `null`. */\n private repaintOwedSince: number | null = null;\n\n /** Release `gen`'s claim — unless a newer paint has claimed since — and repaint behind what it drew. */\n private paintLanded(gen: number): void {\n if (this.paintInFlight !== gen || this.disposed) return;\n this.paintInFlight = 0;\n if (this.repaintOwedSince !== null) {\n const stale = this.renders === this.repaintOwedSince;\n this.repaintOwedSince = null;\n if (stale && !this.isPlaying) this.renderAt(this.stateEvaluator.currentFrame);\n }\n this.settleTrailing();\n }\n\n /**\n * The current track's node tree, with each node's frame range on the project\n * timeline and its waveforms attached. Used by the timeline UI. `null` before\n * any track is built.\n */\n getTreeState(): TreeState | null {\n const instance = this.stateEvaluator.currentInstance;\n if (!instance) return null;\n const track = this.precomp.tracks.find(t => t.id === this.stateEvaluator.currentTrackId);\n const trackStart = track?.startFrame ?? 0;\n const frameCount = track?.frameCount ?? trackFrameCount(instance.duration, this.fps);\n\n const bars = new Map<string, { startFrame: number; endFrame: number }>();\n const pathOfOwner = new Map<string, string>();\n instance.forEachOwner((_node, ownerKey, span, path) => {\n pathOfOwner.set(ownerKey, path);\n const frames = spanFrames(span, this.fps, frameCount);\n if (frames) {\n bars.set(path, { startFrame: trackStart + frames.startFrame, endFrame: trackStart + frames.endFrame });\n }\n });\n const waveformsByPath = waveformsByOwner(track?.audioRequests ?? [], pathOfOwner);\n return nodeToTreeState(instance.canvas, \"\", bars, waveformsByPath);\n }\n\n getNodeState(nodeId: string): NodeState | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n const node = findNode(canvas, nodeId);\n if (!node) return null;\n return { id: node.id, type: node.className, properties: node.properties };\n }\n\n /**\n * What a document node of the current track holds before any command has\n * acted on it, whatever frame is showing and whether or not it is on screen:\n * the props an editor shows for the node itself, where {@link getNodeState}\n * is the node at this frame. `null` when the track holds no such row.\n */\n getNodeInitialProps(nodeId: string): NodeState[\"properties\"] | null {\n return this.stateEvaluator.currentInstance?.baselineProps(nodeId) ?? null;\n }\n\n // ---- Direct manipulation ----------------------------------------------\n // Where a node's pixels are, what is under a point, and a write path fast\n // enough for a drag. See `runtime/node-picking.ts` for the geometry.\n\n /**\n * The on-screen box of one node at the current frame, or `null` when the path\n * does not resolve. See {@link NodeBox}.\n *\n * @param path Structural path from {@link TreeState.path}.\n */\n getNodeBox(path: string): NodeBox | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n // Through `nodeBoxAt`, so a path naming a mesh inside a `Canvas3D`\n // resolves too — see `node-picking3d.ts`.\n return nodeBoxAt(canvas, path);\n }\n\n /**\n * The node's **own** props at a structural path — what it holds right now,\n * in its own coordinate space, the space {@link setNodeOverride} writes into —\n * or `null` when the path doesn't resolve.\n */\n getNodePropsAt(path: string): NodeState[\"properties\"] | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n const node = nodeAt(canvas, path);\n return node ? node.properties : null;\n }\n\n /** Every visible node's box in draw order — one tree walk instead of N {@link getNodeBox} calls. */\n getNodeBoxes(): NodeBox[] {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return [];\n const out: NodeBox[] = [];\n collectBoxes(canvas, \"\", out, true);\n return out;\n }\n\n /**\n * Project points around the `Node3D` at `path`, or `null` when the path\n * doesn't resolve to one. See {@link Node3DFrame}.\n */\n projectNode3D(\n path: string,\n parentPoints: readonly Vector3[],\n localPoints: readonly Vector3[],\n ): Node3DFrame | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return projectNode3DAt(canvas, path, parentPoints, localPoints);\n }\n\n /**\n * Where a viewport point lands on the plane the node at `path` is positioned\n * in, in that plane's own y-up frame — see {@link parentPlanePointAt}.\n */\n parentPlanePoint(path: string, point: Vector2): Vector2 | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return parentPlanePointAt(canvas, path, point);\n }\n\n /**\n * Where a viewport point lands in the coordinates the node at `path`\n * positions its children in, or `null` when those are pixels — see\n * {@link childPlanePointAt}.\n */\n childPlanePoint(path: string, point: Vector2): Vector2 | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return childPlanePointAt(canvas, path, point);\n }\n\n /**\n * What keeps the node at `path` looking as it does once it moves under the\n * node at `parentPath` — see {@link reparentPlacementAt}.\n */\n reparentPlacement(path: string, parentPath: string, offsets: readonly Vector2[]): ReparentPlacement | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return reparentPlacementAt(canvas, path, parentPath, offsets);\n }\n\n /** The points an editor may drag on the node at `path`, in viewport space — see {@link nodeHandlesAt}. */\n nodeHandles(path: string): NodeHandle[] | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return nodeHandlesAt(canvas, path);\n }\n\n /** The value of `prop` that puts its handle under a viewport point — see {@link handleValueAt}. */\n handleValue(path: string, prop: string, point: Vector2): Vector2 | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return handleValueAt(canvas, path, prop, point);\n }\n\n /**\n * Where a Text node's caret slots landed on screen, or `null` when the path\n * doesn't resolve, the node isn't text, or the measurer has no caret model.\n * See {@link NodeTextLayout}.\n */\n getTextLayout(path: string): NodeTextLayout | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n const node = findNodeByPath(canvas, path);\n return node instanceof Node2D\n ? this.textLayoutOf(node, path)\n : null;\n }\n\n /** `node`'s caret slots in viewport space, or `null` when this controller's measurer keeps no glyph positions. */\n private textLayoutOf(node: Node2D, path: string): NodeTextLayout | null {\n const source = asTextBlockSource(this.measurer);\n return source ? nodeTextLayout(node, path, source) : null;\n }\n\n /**\n * The topmost node under a viewport-space point (origin at the viewport\n * centre, y-up), or `null`. `tolerance` is grab-slop in **scene units** —\n * the host's pixel slop divided by its preview zoom. See {@link pickNode}.\n */\n pickNode(point: Vector2, tolerance = 0): NodeBox | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return pickNode(canvas, point, tolerance);\n }\n\n /**\n * Layer transient prop values over a node, on top of whatever the document\n * evaluates to, re-applied after every evaluation until cleared — for an\n * editor dragging a node at pointer rate without rebuilding anything. Not\n * persistence: the host commits the value to its document on drop and\n * clears the override.\n *\n * @param path Structural path from {@link TreeState.path}.\n * @param props Props the node accepts. Merged over any existing override.\n */\n setNodeOverride(path: string, props: NodeOverride): void {\n const existing = this.overrides.get(path);\n this.overrides.set(path, existing ? { ...existing, ...props } : { ...props });\n this.applyOverrides();\n }\n\n /**\n * Drop one node's overrides, or all of them when `path` is omitted, and\n * repaint so the node snaps back to what the document says.\n *\n * Rebuilds the current track's tree to do it: an override was written\n * straight onto a live prop, and the timeline only restores what its own\n * commands write. Cheap enough for a pointer-up, which is the only place it\n * belongs.\n *\n * @param path Structural path, as {@link setNodeOverride} takes — not an id,\n * since a node a composite built for itself has no authored one to name.\n */\n clearNodeOverrides(path?: string): void {\n const cleared = path === undefined\n ? (this.overrides.size > 0 && (this.overrides.clear(), true))\n : this.overrides.delete(path);\n if (!cleared) return;\n this.stateEvaluator.rebuild();\n // Through `repaint` for both of its guards — see there.\n this.repaint();\n }\n\n /** Hidden/locked state for one track's nodes. Not authored, so it rides beside the document. */\n setEditorStates(trackId: string, states: NodeEditorStates | undefined): void {\n this.stateEvaluator.setEditorStates(trackId, states);\n this.repaint();\n }\n\n /**\n * Re-lay-out and repaint the current frame. Cheap enough for a pointer-rate\n * drag loop: `stateAt` early-returns for the frame already current.\n *\n * Does nothing **before the first frame has been drawn** — its assets have\n * not been loaded, and the last complete frame is a blank surface, which is\n * what should stay up — **nor between a swap and its paint**, which owes a\n * paint of its own. See {@link pendingSwap}.\n */\n repaint(): void {\n if (!this.hasPainted) return;\n if (this.pendingSwap !== 0 && this.isCurrent(this.pendingSwap)) return;\n this.renderAt(this.stateEvaluator.currentFrame);\n this.settleTrailing();\n }\n\n /**\n * Repaint a paused frame as the decodes its draw asked for land — one it could\n * not draw at all, and an upgrade of one it drew below demand, which no paint\n * waits for. Never while playing: the next tick picks them up. A seek, swap or\n * screenshot still on its way paints for itself, and once more when it lands\n * if an upgrade arrived after its render.\n */\n private settleTrailing(): void {\n if (this.trailingSettle || this.disposed || this.isPlaying || !this.hasBackgroundDecodes()) return;\n void this.repaintBehindDecodes().catch((error) => {\n console.error(\"[PlaybackController] background decode failed:\", error);\n });\n }\n\n private trailingSettle = false;\n\n private hasBackgroundDecodes(): boolean {\n return this.storageAdapter.hasPendingDecodes() || this.storageAdapter.hasPendingUpgrades();\n }\n\n private async repaintBehindDecodes(): Promise<void> {\n // Released in `finally` on the same turn as the return, so a paint landing\n // right after this gives up can start the next one.\n this.trailingSettle = true;\n try {\n for (let pass = 0; pass < SETTLE_PASSES && this.hasBackgroundDecodes(); pass++) {\n const [decoded, upgraded] = await Promise.all([\n this.storageAdapter.warmPendingDecodes(),\n this.storageAdapter.warmPendingUpgrades(),\n ]);\n if (!(decoded || upgraded) || this.disposed || this.isPlaying) return;\n if (this.paintInFlight !== 0) {\n this.repaintOwedSince = this.renders;\n return;\n }\n this.renderAt(this.stateEvaluator.currentFrame);\n }\n } finally {\n this.trailingSettle = false;\n }\n }\n\n /** Write every held override onto its node. No-op when none are set. */\n private applyOverrides(): void {\n if (this.overrides.size === 0) return;\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return;\n for (const [path, props] of this.overrides) {\n findNodeByPath(canvas, path)?.set(props as never);\n }\n }\n\n play(speed: number = 1, reverse: boolean = false): void {\n if (this.currentFrame >= this.totalFrames) {\n this.seek(0).then(() => this.masterClock.play(speed, reverse)).catch(() => { });\n return;\n }\n this.masterClock.play(speed, reverse);\n }\n\n pause(): void {\n this.masterClock.pause();\n }\n\n setMuted(muted: boolean): void {\n this.audioDevice.setMuted(muted);\n }\n\n dispose(): void {\n this.disposed = true;\n this.masterClock.dispose();\n this.audioDevice.dispose();\n this.stateEvaluator.dispose();\n this.store.dispose();\n this.assetManager.dispose();\n }\n}\n\n/** How far from the playhead a built tree is kept, in seconds. */\nconst TRIM_HORIZON_SECONDS = 30;\n\n/** `adapter`, settling upgrades alongside what a frame needs — for a paint that is kept rather than shown. */\nfunction settlingUpgrades(adapter: StorageAdapter): Pick<StorageAdapter, \"warmPendingDecodes\"> {\n return {\n async warmPendingDecodes() {\n const [decoded, upgraded] = await Promise.all([adapter.warmPendingDecodes(), adapter.warmPendingUpgrades()]);\n return decoded || upgraded;\n },\n };\n}\n\n/** What a missing-asset error says was needed, as a declaration. */\nfunction declOf(error: AssetNotLoadedError, catalog: AssetCatalog): AssetDecl | undefined {\n switch (error.assetType) {\n case \"image\":\n return { type: \"image\", src: error.src };\n case \"font\":\n return { type: \"font\", family: error.src, weight: 400 };\n case \"video\":\n try {\n return { type: \"video\", src: error.src, trimStart: 0, trimEnd: catalog.getVideoDuration(error.src) };\n } catch {\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\n// Every Node2D is a container (children may be empty); kept for callers that\n// want an explicit \"has children\" check.\nexport function isParentNode(node: Node2D): boolean {\n return node.children.length > 0;\n}\n\n/**\n * `node` and its subtree as {@link TreeState}, indexed over the authored child\n * list — the same one every other structural-path walk reads, so selection,\n * bars and `getNodeBox` share one set of paths.\n */\nfunction nodeToTreeState(\n node: Node,\n path: string,\n bars: ReadonlyMap<string, { startFrame: number; endFrame: number }>,\n waveformsByPath: ReadonlyMap<string, WaveformInfo[]>,\n): TreeState {\n const state: TreeState = {\n id: node.id,\n path,\n type: node.className,\n children: node._allChildren.map((c, i) => nodeToTreeState(c, nodePath(path, i), bars, waveformsByPath)),\n };\n const waveform = waveformsByPath.get(path);\n if (waveform && waveform.length > 0) state.waveform = waveform;\n const bar = bars.get(path);\n if (bar) {\n state.startFrame = bar.startFrame;\n state.endFrame = bar.endFrame;\n }\n return state;\n}\n\n/**\n * Group a track's audio requests into per-node waveform entries, keyed by the\n * structural path their owner has in the tree right now. A request whose owner\n * is not in the tree has no bar to land on.\n */\nfunction waveformsByOwner(\n requests: readonly AudioRequest[],\n pathOfOwner: ReadonlyMap<string, string>,\n): Map<string, WaveformInfo[]> {\n const byPath = new Map<string, WaveformInfo[]>();\n for (const req of requests) {\n const path = req.ownerId !== undefined ? pathOfOwner.get(req.ownerId) : \"\";\n if (path === undefined) continue;\n const info: WaveformInfo = {\n src: req.src,\n startTime: req.startAt,\n endTime: Number.isFinite(req.endAt) ? req.endAt : null,\n };\n const list = byPath.get(path);\n if (list) list.push(info);\n else byPath.set(path, [info]);\n }\n return byPath;\n}\n\n/** The node at a structural path (`\"\"` = root, `\"0.2\"` = third child of the first), walking the authored list. */\nfunction findNodeByPath(root: Node2D, path: string): Node | null {\n if (path === \"\") return root;\n let node: Node = root;\n for (const seg of path.split(\".\")) {\n const next = node._allChildren[Number(seg)];\n if (!next) return null;\n node = next;\n }\n return node;\n}\n\nfunction findNode(root: Node, id: string): Node | null {\n if (root.id === id) return root;\n\n for (const child of root._allChildren) {\n const found = findNode(child, id);\n if (found) return found;\n }\n\n return null;\n}\n", "import { type AudioMeta, type FontMeta, type ImageMeta, AssetManifest, type VideoMeta } from \"./manifest\";\n\n/**\n * What a scene can ask about the assets available to it.\n *\n * Strictly read-only, and strictly about *metadata*: dimensions, durations, and\n * the font faces a family resolves to. Nothing here loads anything — that is\n * the {@link AssetManager}'s job, driven by what nodes declare into an\n * {@link AssetScope}. Reachable from any node as `node.assets` and from a\n * scene generator as `stage.assets`.\n *\n * **Every lookup throws on a miss rather than returning `undefined`.** A missing\n * asset is a typo or a deleted file, and it is worth finding out during the\n * precomp pass (where it surfaces as a `BuildError` in the errors panel) rather\n * than at playback as a shape that silently fails to paint.\n *\n * An interface so a host can supply its own — a test double, or a catalog\n * backed by something other than a static manifest. {@link ManifestAssetCatalog}\n * is the implementation the runtime builds from the project's asset manifest.\n */\nexport interface AssetCatalog {\n /**\n * Metadata for an image.\n * @throws If the image is not in the manifest.\n */\n getImageMeta(src: string): ImageMeta;\n\n /**\n * Metadata for a video.\n * @throws If the video is not in the manifest.\n */\n getVideoMeta(src: string): VideoMeta;\n\n /**\n * Metadata for an audio track.\n * @throws If the audio file is not in the manifest.\n */\n getAudioMeta(src: string): AudioMeta;\n\n /**\n * Metadata for a single font face, by its `family@weight` lookup key.\n * @throws If the key is not in the manifest.\n */\n getFontMeta(key: string): FontMeta;\n\n /**\n * Every face registered for a family, across all weights and slants — what\n * the renderer registers so its font matcher can resolve any requested\n * weight to the nearest available file. Empty if the family is unknown.\n */\n getFontFamilyMetas(fontFamily: string): FontMeta[];\n\n /** Playback duration of a video, in seconds. */\n getVideoDuration(src: string): number;\n\n /** Playback duration of an audio file, in seconds. */\n getAudioDuration(src: string): number;\n\n /**\n * Duration of any *playable* source — an audio file, or a video whose audio\n * track is being played. Resolves against audio first and falls back to\n * video, so a video `src` can drive a `Sound` without a duplicate audio-only\n * manifest entry.\n * @throws If `src` is in neither manifest.\n */\n getMediaDuration(src: string): number;\n\n /** An image's intrinsic pixel dimensions. */\n getImageSize(src: string): { width: number; height: number };\n}\n\n/**\n * The {@link AssetCatalog} the runtime builds: a query engine over a static\n * {@link AssetManifest}.\n *\n * @example\n * ```ts\n * const catalog = new ManifestAssetCatalog(manifest);\n * catalog.getImageSize(\"hero-banner.png\"); // { width: 1920, height: 1080 }\n * ```\n */\nexport class ManifestAssetCatalog implements AssetCatalog {\n constructor(private manifest: AssetManifest) { }\n\n /**\n * Point this catalog at `manifest`, in place.\n *\n * A session hands one catalog to the controller, the clip store and every\n * node's `assets`, so replacing the catalog object would leave all of them on\n * the old one. Reconciling the manifest it reads keeps a manifest change\n * visible to everything already built.\n */\n reconcile(manifest: AssetManifest): void {\n this.manifest = manifest;\n }\n\n /**\n * Normalize a caller-supplied asset `src` into the manifest's lookup key.\n * The manifest stores image/video/audio keys as the file's path relative\n * to the scanned public folder, using forward slashes with no leading\n * `./` or `/`.\n * Scene authors write `src` in whichever equivalent form is natural — a\n * bare filename, `\"./sub/file.png\"`, `\"/sub/file.png\"`, or a\n * Windows-authored backslash path — so normalize all of them to the same\n * key. Font lookups are keyed by `family@weight`, not a path, so they\n * don't go through this.\n */\n private normalizeKey(src: string): string {\n return src.replace(/\\\\/g, '/').replace(/^\\.\\//, '').replace(/^\\/+/, '');\n }\n\n getImageMeta(src: string): ImageMeta {\n const meta = this.manifest.image[this.normalizeKey(src)];\n if (!meta) throw new Error(`Image asset not found: \"${src}\". Check the file exists in your public folder and the src matches its filename.`);\n return meta;\n }\n\n getVideoMeta(src: string): VideoMeta {\n const meta = this.manifest.video[this.normalizeKey(src)];\n if (!meta) throw new Error(`Video asset not found: \"${src}\". Check the file exists in your public folder and the src matches its filename.`);\n return meta;\n }\n\n getAudioMeta(src: string): AudioMeta {\n const meta = this.manifest.audio[this.normalizeKey(src)];\n if (!meta) throw new Error(`No audio metadata for src: ${src}`);\n return meta;\n }\n\n getFontMeta(key: string): FontMeta {\n const meta = this.manifest.font[key];\n if (!meta) throw new Error(`No font metadata for key: ${key}`);\n return meta;\n }\n\n getFontFamilyMetas(fontFamily: string): FontMeta[] {\n return Object.values(this.manifest.font).filter(meta => meta.fontFamily === fontFamily);\n }\n\n getVideoDuration(src: string): number {\n return this.getVideoMeta(src).duration;\n }\n\n getAudioDuration(src: string): number {\n return this.getAudioMeta(src).duration;\n }\n\n getMediaDuration(src: string): number {\n const key = this.normalizeKey(src);\n const audio = this.manifest.audio[key];\n if (audio) return audio.duration;\n const video = this.manifest.video[key];\n if (video) return video.duration;\n throw new Error(`Audio asset not found: \"${src}\". Check the file exists in your public folder and the src matches its filename.`);\n }\n\n getImageSize(src: string): { width: number; height: number } {\n const { width, height } = this.getImageMeta(src);\n return { width, height };\n }\n}\n", "import { TimeCallback } from \"@/platform/ticker\";\nimport { PlaybackController } from \"./playback-controller\";\n\n/**\n * Realtime transport over a `Session`.\n *\n * Reached as `session.playback`, and **`null` when the environment has no\n * clock** — a headless export has no wall clock to sync to. That is deliberately\n * an absence rather than a no-op: a UI wants to ask whether a transport exists\n * (and hide its scrub bar if not) rather than call `play()` into a void.\n *\n * Thin on purpose. Everything here is `PlaybackController`'s; this exists so\n * that \"what a session is\" and \"what is currently playing it\" are separable, and\n * so the transport half can simply not exist where it makes no sense.\n */\nexport class Playback {\n /** @internal — constructed by `Session`, never directly. */\n constructor(private readonly controller: PlaybackController) { }\n\n get isPlaying(): boolean {\n return this.controller.isPlaying;\n }\n\n /** The playhead, in frames. */\n get frame(): number {\n return this.controller.currentFrame;\n }\n\n play(speed = 1, reverse = false): void {\n this.controller.play(speed, reverse);\n }\n\n pause(): void {\n this.controller.pause();\n }\n\n /**\n * Move the playhead while playing, without the await a paused scrub needs.\n * Use `Session.seekFrame` when paused — it resolves once the frame is drawn.\n */\n seekFrame(frame: number): void {\n this.controller.seekWhilePlaying(frame);\n }\n\n setMuted(muted: boolean): void {\n this.controller.setMuted(muted);\n }\n\n /** Fires as the playhead moves, in seconds. */\n onTime(callback: TimeCallback): void {\n this.controller.onTime(callback);\n }\n\n onPlay(callback: () => void): void {\n this.controller.onPlay(callback);\n }\n\n onPause(callback: () => void): void {\n this.controller.onPause(callback);\n }\n}\n", "/** Called every animation frame with the current playhead time (seconds). Must return a Promise so the clock can await all renderers before advancing. */\nexport type TickCallback = (time: number) => Promise<void>;\n\n/** Fired when playback starts. Receives the time at which playback began, the playback speed multiplier, and whether playback is reversed. */\nexport type PlayCallback = (time: number, speed: number, reverse: boolean) => void;\n\n/**\n * Fired when the playhead reaches a new frame.\n *\n * Once per frame, not once per animation frame — see\n * {@link Ticker.setCurrentTime}. A subclass advancing its clock faster than\n * the project's frame rate (which every rAF-driven one does on a high-refresh\n * display) keeps the extra positions to itself.\n */\nexport type TimeCallback = (time: number) => void;\n\n/**\n * Platform-agnostic base class for driving animation playback.\n *\n * Subclasses implement the actual frame loop (e.g. requestAnimationFrame in the\n * browser, a setInterval loop in Node) and call `setCurrentTime` / `tick` each\n * frame. `Ticker` owns the subscriber lists and the shared playback state\n * so that renderers and UI controls can coordinate without knowing about each\n * other.\n *\n * Lifecycle:\n * 1. Set total duration with `setDuration`.\n * 2. Register listeners via `onTick` / `onPlay` / `onPause` / `onTime`.\n * 3. Call `play`, `pause`, or `seek` to control playback.\n * 4. Call `dispose` when the clock is no longer needed to prevent leaks.\n *\n * `play`, `pause` and `seek` take effect before they return, so any order of them\n * in one turn leaves the clock where the last one put it. A time listener or tick\n * callback may `seek` (a host looping wraps to the start when it hears the end), and\n * a subclass must read the end of a run again afterwards. At the end of a run it\n * reports a final tick and pauses.\n */\nexport abstract class Ticker {\n private _isPlaying: boolean = false;\n private _currentTime: number = 0;\n protected _duration: number = 0;\n\n get isPlaying(): boolean {\n return this._isPlaying;\n }\n\n /** Current playhead position in seconds. */\n get currentTime(): number {\n return this._currentTime;\n }\n\n /** Total animation duration in seconds. */\n get duration(): number {\n return this._duration;\n }\n\n setDuration(duration: number): void {\n this._duration = duration;\n }\n\n /**\n * Updates the playhead and notifies time listeners. No-ops if the time hasn't\n * changed.\n *\n * `notify` exists because the two halves of that sentence want different\n * rates. The playhead itself has to be exact — `pause` and `play` anchor\n * their elapsed-time maths on it, so it is advanced on every frame of the\n * subclass's loop — while a *listener* is a host drawing a timecode or\n * seeking a renderer, and neither can do anything with a position that has\n * not reached the next frame yet.\n *\n * Passing `false` therefore keeps the clock exact and the subscribers quiet.\n * A subclass that knows its frame rate uses it to fire {@link onTime} once\n * per frame rather than once per animation frame; on a 144Hz display those\n * are not the same number, and the difference was landing on hosts as a React\n * render per refresh to drive a 60fps render.\n */\n protected setCurrentTime(t: number, notify: boolean = true): void {\n if (this._currentTime === t) return;\n this._currentTime = t;\n if (!notify) return;\n for (const cb of this.timeCallbacks) cb(t);\n }\n\n protected setPlaying(playing: boolean): void {\n this._isPlaying = playing;\n }\n\n /** Starts playback at the given speed and direction, notifying all play listeners. */\n play(speed: number, reverse: boolean): void {\n this._isPlaying = true;\n for (const cb of this.playCallbacks) cb(this._currentTime, speed, reverse);\n }\n\n /** Awaits all tick callbacks in parallel. Subclasses call this once per frame after updating `currentTime`. */\n protected async tick(): Promise<void> {\n await Promise.all(this.tickCallbacks.map(c => c(this._currentTime)));\n }\n\n /** Pauses playback and notifies all pause listeners. */\n pause(): void {\n this._isPlaying = false;\n for (const cb of this.pauseCallbacks) cb();\n }\n\n /** Moves the playhead to `t` (seconds). Subclasses decide whether this also triggers a tick. */\n abstract seek(t: number): void;\n\n protected tickCallbacks: TickCallback[] = [];\n protected playCallbacks: PlayCallback[] = [];\n protected pauseCallbacks: (() => void)[] = [];\n protected timeCallbacks: TimeCallback[] = [];\n\n /** Clears all registered callbacks. Call when tearing down a scene to avoid memory leaks. */\n dispose() {\n this.tickCallbacks.length = 0;\n this.playCallbacks.length = 0;\n this.pauseCallbacks.length = 0;\n this.timeCallbacks.length = 0;\n }\n\n onTick(callback: TickCallback) {\n this.tickCallbacks.push(callback);\n }\n\n onPlay(callback: PlayCallback) {\n this.playCallbacks.push(callback);\n }\n\n onPause(callback: () => void) {\n this.pauseCallbacks.push(callback);\n }\n\n onTime(callback: TimeCallback) {\n this.timeCallbacks.push(callback);\n }\n}\n", "import { Ticker } from \"./ticker\";\n\n/**\n * A clock with no wall clock behind it: the playhead is wherever it was last put.\n *\n * What a headless session runs on. `PlaybackController` needs *a* clock to seek\n * against, but an export has no realtime to sync to — and must not have one,\n * because a wall-clock export drifts. So the platform reports `null` from\n * `createTicker` to say \"no realtime transport here\", and a session stands\n * this in so everything that is not transport — seeking, node picking, reading a\n * node's box, drawing a frame — works exactly as it does in a browser.\n *\n * `play()` is deliberately not overridden into a no-op: nothing reaches it,\n * because a session with no realtime clock exposes `playback === null` and there\n * is no other route to it.\n *\n * @internal\n */\nexport class SteppedClock extends Ticker {\n seek(t: number): void {\n this.setCurrentTime(t);\n }\n}\n", "import { Size2D } from \"@/attributes/layout/size\";\nimport { AssetManifest } from \"@/assets/manifest\";\nimport { ManifestAssetCatalog } from \"@/assets/catalog\";\nimport { setTheme } from \"@/attributes/shape/fill/color/parser\";\nimport { asProjectDocument, type ProjectDocument } from \"@/document/project\";\nimport type { VisualDocument } from \"@/document/types\";\nimport { assertValidProjectDocument } from \"@/document/validate\";\nimport { migrateDocument } from \"@/document/migrate\";\nimport { ExportStillRequest, ExportVideoRequest, ExportedStill } from \"@/platform/exporter\";\nimport { Engine, EngineRenderContext } from \"./engine\";\nimport { Playback } from \"./playback\";\nimport { clipTimeToFrame } from \"./frame-time\";\nimport { PlaybackController } from \"./playback-controller\";\nimport { AssetTimelineResult } from \"./asset-timeline\";\nimport { StorageAdapter } from \"@/platform/storage-adapter\";\nimport { SteppedClock } from \"@/platform/stepped-clock\";\n\n/** What to open: a project, or a lone still or composition as the one track of a project around it. */\nexport interface SessionSource {\n document: ProjectDocument | VisualDocument;\n /** The output's size and rate. A lone clip document carries neither; these also win over a project's own. */\n viewport?: Size2D;\n fps?: number;\n}\n\nexport interface OpenOptions extends SessionSource {\n /**\n * Where pixels land. A canvas in a browser, a size headlessly — the platform's\n * render context narrows it. Omit to open without mounting, for a session that\n * only ever exports.\n */\n target?: unknown;\n onPrecompProgress?: (result: AssetTimelineResult) => void;\n}\n\n/**\n * One document, bound to one engine and one surface.\n *\n * Cheap relative to its engine — it holds a surface and a playhead, while the\n * caches it draws on belong to the engine — so many sessions over one engine is\n * the intended shape: a preview, a filmstrip of thumbnails, an export.\n *\n * The theme is still applied through a process-global registry (`setTheme`), so\n * it is re-applied immediately before anything draws; concurrent sessions with\n * different themes would contend. Isolating that means threading a context\n * through every colour parse, which is its own change.\n */\nexport class Session {\n readonly viewport: Size2D;\n readonly fps: number;\n\n /** @internal — created by `Engine.open`, never directly. */\n constructor(\n private readonly engine: Engine,\n options: OpenOptions,\n ) {\n this._override = { viewport: options.viewport, fps: options.fps };\n this._project = resolveProjectDocument(options.document, options, engine);\n this.viewport = this._project.viewport!;\n this.fps = this._project.fps!;\n\n this._catalog = new ManifestAssetCatalog(engine.manifest);\n // One catalog for the session's life, reconciled in place: the controller,\n // its clip store and every node's `assets` hold this object, so a new one\n // would reach only the storage adapter.\n this._unsubscribe = engine._onManifestChange((manifest: AssetManifest) => {\n this._catalog.reconcile(manifest);\n this._storage.setCatalog(this._catalog);\n this._controller.reconcileCatalog();\n });\n\n const deps = { catalog: this._catalog, viewport: this.viewport, fps: this.fps };\n this._storage = engine.platform.createStorageAdapter(deps);\n this._renderContext = engine.platform.createRenderContext(this._storage);\n const measurer = engine.platform.createMeasureContext(this._storage);\n const audioDevice = engine.platform.createAudioSink();\n const masterClock = engine.platform.createTicker(this.fps, audioDevice);\n\n // Before the first measuring pass, which resolves theme tokens.\n this.applyGlobals();\n\n if (options.target !== undefined) this._renderContext.mount(options.target);\n\n // A platform answering `null` means \"no *realtime* transport here\", not\n // \"nothing works\": seeking, picking and drawing are the same headlessly,\n // so a stepped clock stands in and only `playback` reports the absence.\n this._controller = new PlaybackController({\n project: this._project,\n registry: engine._registry,\n renderContext: this._renderContext,\n measurer,\n storageAdapter: this._storage,\n masterClock: masterClock ?? new SteppedClock(),\n audioDevice,\n assets: this._catalog,\n onPrecompProgress: options.onPrecompProgress,\n });\n this._playback = masterClock === null ? null : new Playback(this._controller);\n }\n\n /** The project this session plays, its fps and viewport resolved. */\n get document(): ProjectDocument {\n return this._project;\n }\n\n /** Realtime transport, or `null` when this engine has no clock. */\n get playback(): Playback | null {\n return this._playback;\n }\n\n /**\n * The editor-facing surface: node picking, node boxes, text layout, prop\n * overrides, tree state, build errors.\n *\n * Exposed rather than proxied: `Session` covers the *document* — what is\n * open, where it draws, how it encodes — and the controller covers\n * inspecting and manipulating a live frame, a different job with a surface\n * of its own. Always present, including headlessly (see `SteppedClock`).\n */\n get controller(): PlaybackController {\n return this._controller;\n }\n\n /** Where this session draws. A host reads it to resize or re-frame the view. */\n get surface(): EngineRenderContext {\n return this._renderContext;\n }\n\n get duration(): number {\n return this._controller.totalDuration;\n }\n\n get totalFrames(): number {\n return this._controller.totalFrames;\n }\n\n /** Move the playhead, in seconds. Resolves once the frame is drawn. */\n async seek(seconds: number): Promise<void> {\n await this.seekFrame(Math.round(clipTimeToFrame(seconds, this.fps)));\n }\n\n async seekFrame(frame: number): Promise<void> {\n this.applyGlobals();\n await this._controller.seek(frame);\n }\n\n /**\n * Swap what is playing, keeping the surface, audio device and clock. The new\n * document is diffed against the playing one and each built tree patched in\n * place; a track is rebuilt only when its change cannot be patched, and a\n * theme change rebuilds every track. Documents are compared by content with\n * identity as the fast path, so treat them as immutable.\n *\n * The output's size and rate cannot change under a live surface; a document\n * that asks for different ones needs a session of its own.\n */\n replace(document: ProjectDocument | VisualDocument): void {\n const next = resolveProjectDocument(document, this._override, this);\n if (next.fps !== this.fps || next.viewport!.width !== this.viewport.width\n || next.viewport!.height !== this.viewport.height) {\n throw new Error(\n `Cannot replace a ${this.viewport.width}×${this.viewport.height} @ ${this.fps}fps document with a ` +\n `${next.viewport!.width}×${next.viewport!.height} @ ${next.fps}fps one — open a new session.`,\n );\n }\n this._project = next;\n this.applyGlobals();\n this._controller.setProject(next);\n }\n\n /** Encode one frame. */\n image(options: Partial<Omit<ExportStillRequest, \"project\" | \"registry\">> = {}): Promise<ExportedStill> {\n this.applyGlobals();\n return this.engine.exporter.exportStill({\n ...options,\n frame: options.frame ?? { kind: \"last\" },\n project: this._project,\n registry: this.engine._registry,\n manifest: options.manifest ?? this.engine.manifest,\n });\n }\n\n /** Encode the timeline, or the `frames` of it a request names. */\n export(options: Omit<ExportVideoRequest, \"project\" | \"registry\"> = {}): Promise<Uint8Array | void> {\n this.applyGlobals();\n return this.engine.exporter.exportVideo({\n ...options,\n project: this._project,\n registry: this.engine._registry,\n manifest: options.manifest ?? this.engine.manifest,\n });\n }\n\n dispose(): void {\n this._unsubscribe();\n this._controller.dispose();\n this._renderContext.dispose();\n }\n\n /** Called before anything that measures or paints, because another session may have written it since. */\n private applyGlobals(): void {\n setTheme(this._project.theme);\n }\n\n /** The output settings this session was opened with, which win over any document it plays. */\n private readonly _override: { viewport?: Size2D; fps?: number };\n private _project: ProjectDocument;\n private readonly _catalog: ManifestAssetCatalog;\n private readonly _storage: StorageAdapter;\n private readonly _renderContext: EngineRenderContext;\n private readonly _controller: PlaybackController;\n private readonly _playback: Playback | null;\n private readonly _unsubscribe: () => void;\n}\n\n/**\n * The project a document plays as, its output settings resolved: `override`\n * first, then the document's own, then `fallback`. Migrated to the current\n * format and validated once, here, so nothing downstream has to — every host\n * that renders a document goes through this, so they cannot disagree about which\n * size wins. Throws `DocumentTooNewError` for a format this engine cannot read.\n *\n * A migration that changed nothing but the version stamp plays the document as\n * given, so a host replacing the same object keeps the identity fast path.\n */\nexport function resolveProjectDocument(\n document: ProjectDocument | VisualDocument,\n override: { viewport?: Size2D; fps?: number },\n fallback: { viewport: Size2D; fps: number },\n): ProjectDocument {\n const opened = asProjectDocument(document);\n const migrated = migrateDocument(opened);\n const project = migrated.changes.length > 0 ? migrated.document : opened;\n const resolved: ProjectDocument = {\n ...project,\n viewport: override.viewport ?? project.viewport ?? fallback.viewport,\n fps: override.fps ?? project.fps ?? fallback.fps,\n };\n assertValidProjectDocument(resolved);\n return resolved;\n}\n", "/** One parsed data record: column name → cell value (string, or number/boolean\n * when the column auto-coerces — see {@link ParseCSVOptions.numeric} and\n * {@link ParseCSVOptions.boolean}). */\nexport type DataRecord = Record<string, string | number | boolean>;\n\nexport interface ParseCSVOptions {\n /** Field separator. Default: ','. */\n delimiter?: string;\n /**\n * Which columns to coerce to `number`. An explicit list forces just those\n * columns; `false` disables coercion entirely (every cell stays a string).\n * Default (omitted/`true`): auto-detect — a column becomes numeric only if\n * every non-empty cell in it parses as a finite number, so a text column\n * that happens to contain a numeric-looking value here and there is left\n * alone rather than partially coerced.\n */\n numeric?: string[] | boolean;\n /**\n * Which columns to coerce to `boolean`, same shape/semantics as\n * {@link numeric}. Default (omitted/`true`): auto-detect — a column\n * becomes boolean only if every non-empty cell is exactly `\"true\"` or\n * `\"false\"`. Never applied to a column already coerced to numeric.\n */\n boolean?: string[] | boolean;\n}\n\n/**\n * Parse CSV text into an array of row records keyed by the header row.\n * Handles quoted fields (embedded delimiters, newlines, and `\"\"` escapes) and\n * both CRLF/LF line endings. Synchronous and dependency-free, so it's safe to\n * call at module-eval time on text pulled in via a `?raw` import.\n */\nexport function parseCSV(text: string, options: ParseCSVOptions = {}): DataRecord[] {\n const delimiter = options.delimiter ?? ',';\n const rows = splitRows(text, delimiter);\n if (rows.length === 0) return [];\n\n const header = rows[0].map(cell => cell.trim());\n const body = rows.slice(1);\n\n const records: Record<string, string>[] = body.map(row => {\n const record: Record<string, string> = {};\n header.forEach((key, i) => { record[key] = row[i] ?? ''; });\n return record;\n });\n\n const numericCols = resolveNumericColumns(header, records, options.numeric);\n const booleanCols = resolveBooleanColumns(header, records, numericCols, options.boolean);\n if (numericCols.length === 0 && booleanCols.length === 0) return records;\n\n return records.map(record => {\n const out: DataRecord = { ...record };\n for (const col of numericCols) {\n const raw = record[col];\n if (raw === '') continue;\n out[col] = Number(raw);\n }\n for (const col of booleanCols) {\n const raw = record[col];\n if (raw === '') continue;\n out[col] = raw === 'true';\n }\n return out;\n });\n}\n\n/**\n * `parseData` only ever runs as an inlined literal — the\n * `@motionscript/vite-plugin` build-time macro replaces\n * `parseData(\"file.csv\")` call sites with the already-parsed rows before this\n * body ever executes. This implementation exists purely so the call\n * type-checks and so an unresolved call site (missing plugin, or a\n * non-literal argument the macro couldn't statically inline) fails loudly\n * instead of silently returning nothing.\n */\nexport function parseData(file: string, _options?: ParseCSVOptions): DataRecord[] {\n throw new Error(\n `parseData(\"${file}\") must be called with a static string literal so the ` +\n `@motionscript/vite-plugin macro can inline it at build time. If you're seeing ` +\n `this error at runtime, either the plugin isn't installed/registered, or this ` +\n `call's argument isn't a plain string literal.`\n );\n}\n\n/** Decide which columns to coerce, per {@link ParseCSVOptions.numeric}. */\nfunction resolveNumericColumns(\n header: string[],\n records: Record<string, string>[],\n numeric: string[] | boolean | undefined,\n): string[] {\n if (numeric === false) return [];\n if (Array.isArray(numeric)) return numeric;\n\n return header.filter(col => {\n let sawValue = false;\n for (const record of records) {\n const raw = record[col];\n if (raw === '') continue;\n if (!Number.isFinite(Number(raw))) return false;\n sawValue = true;\n }\n return sawValue;\n });\n}\n\n/** Decide which columns to coerce, per {@link ParseCSVOptions.boolean}. */\nfunction resolveBooleanColumns(\n header: string[],\n records: Record<string, string>[],\n numericCols: string[],\n bool: string[] | boolean | undefined,\n): string[] {\n if (bool === false) return [];\n if (Array.isArray(bool)) return bool;\n\n const numericSet = new Set(numericCols);\n return header.filter(col => {\n if (numericSet.has(col)) return false;\n let sawValue = false;\n for (const record of records) {\n const raw = record[col];\n if (raw === '') continue;\n if (raw !== 'true' && raw !== 'false') return false;\n sawValue = true;\n }\n return sawValue;\n });\n}\n\n/**\n * Split raw CSV text into rows of raw (unquoted) string cells. A minimal\n * hand-rolled scanner rather than a `split(',')`/`split('\\n')` pair so quoted\n * fields can safely contain the delimiter, newlines, and escaped (`\"\"`) quotes.\n */\nfunction splitRows(text: string, delimiter: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = '';\n let inQuotes = false;\n let sawAnyField = false;\n\n const pushField = () => { row.push(field); field = ''; };\n const pushRow = () => { pushField(); rows.push(row); row = []; sawAnyField = false; };\n\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n\n if (inQuotes) {\n if (ch === '\"') {\n if (text[i + 1] === '\"') { field += '\"'; i++; }\n else inQuotes = false;\n } else {\n field += ch;\n }\n continue;\n }\n\n if (ch === '\"') { inQuotes = true; sawAnyField = true; continue; }\n if (ch === delimiter) { sawAnyField = true; pushField(); continue; }\n if (ch === '\\r') continue;\n if (ch === '\\n') { if (sawAnyField || field) pushRow(); continue; }\n field += ch;\n sawAnyField = true;\n }\n // Flush a final row left over when the text has no trailing newline.\n if (sawAnyField || field) pushRow();\n\n return rows;\n}\n", "/**\n * Generates an array of size `n` populated by a generator function.\n * Mirrored after Dart's List.generate.\n */\nexport const generateList = <T>(n: number, generator: (index: number) => T): T[] => {\n // Use a traditional loop for maximum performance inside animation/render cycles\n const result = new Array(n);\n for (let i = 0; i < n; i++) {\n result[i] = generator(i);\n }\n return result;\n};\n", "/**\n * A callable reference that acts as both getter and setter.\n * - `ref()` → returns the current value (throws if not yet assigned)\n * - `ref(value)` → sets the current value\n */\nexport interface Reference<T> {\n (): T;\n (node: T | null): void;\n /**\n * Phantom — never assigned at runtime, and never called. It exists so that\n * `T` appears in a *contravariant* position, which is what makes\n * {@link RefTarget} safe. The call signatures alone can't decide it: the\n * zero-arg getter `(): T` is assignable to any `(x) => void`, so a slot\n * typed as just the setter would silently accept a `Reference` of an\n * unrelated node type.\n * @internal\n */\n readonly __accepts?: (node: T) => void;\n}\n\n/**\n * A slot that can *receive* a `T` — a `Reference<T>`, or one declared as any\n * **supertype** of `T`.\n *\n * This is the type a node's `ref` prop takes, and the widening is deliberate:\n * the framework only ever writes into a ref (`props.ref(this)` in the `Node2D`\n * constructor) and the author only ever reads, so handing a `Rect` to a\n * `Reference<Node2D>` is sound in both directions — the write stores a\n * subtype, the read yields the supertype the author asked for. That is what\n * lets one ref hold whichever shape a factory happened to build:\n *\n * ```ts\n * const ref = createRef<Node2D>();\n * Rect({ ref }); // ✔ Rect is a Node2D\n * Ellipse({ ref }); // ✔ so is Ellipse\n * ```\n *\n * The opposite direction stays an error, because it is the unsound one: a\n * `Reference<Rect>` on a `Text` would be handed a `Text` at runtime while\n * still typing every read as a `Rect`.\n *\n * A plain setter function is accepted too, which makes React-style callback\n * refs (`ref={n => …}`) work without a separate type.\n */\nexport type RefTarget<T> = {\n (node: T | null): void;\n readonly __accepts?: (node: T) => void;\n};\n\n/**\n * Creates a typed reference holder — analogous to React's `createRef`,\n * but expressed as a single overloaded function rather than a `{ current }` object.\n */\nexport function createRef<T>(): Reference<T> {\n let current: T | null = null;\n\n function ref(): T;\n function ref(node: T | null): void;\n function ref(node?: T | null): T | void {\n if (node !== undefined) {\n current = node;\n } else {\n if (current === null) {\n throw new Error(\"Reference not assigned yet\");\n }\n return current;\n }\n }\n\n return ref;\n}\n", "/**\n * Deterministic pseudo-random number generator based on the mulberry32 algorithm.\n * Produces the same sequence for the same seed, making animations reproducible.\n *\n * This is the low-level engine. Scene authors use the higher-level {@link Random}\n * facade (handed out by `stage.random(seed)`), which wraps a `SeedGenerator` and\n * adds typed draws (`nextFloat`/`nextInt`/`gauss`/arrays) plus seeded `noise`.\n */\nexport class SeedGenerator {\n private state: number = 0;\n\n constructor(seed: string | number) {\n this.setSeed(seed);\n }\n\n /**\n * Resets the generator to a new seed.\n * String seeds are hashed via djb2 into a 32-bit integer.\n */\n setSeed(seed: string | number) {\n this.state = typeof seed === 'string'\n ? seed.split('').reduce((a, b) => { a = ((a << 5) - a) + b.charCodeAt(0); return a & a; }, 0)\n : seed;\n }\n\n /** Returns the next pseudo-random float in [0, 1). */\n next() {\n this.state |= 0; this.state = this.state + 0x6D2B79F5 | 0;\n var t = Math.imul(this.state ^ this.state >>> 15, 1 | this.state);\n t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;\n return ((t ^ t >>> 14) >>> 0) / 4294967296;\n }\n}\n\n/** Upper bound of {@link Random.nextInt} / {@link Random.intArray} (2^32). */\nconst UINT32_RANGE = 4294967296;\n\n/**\n * A seeded random source handed to scene generators by `stage.random(seed)`.\n *\n * Wraps a {@link SeedGenerator} (mulberry32) and exposes the author-facing draw\n * surface. Because the seed lives on the `Random` instance, determinism is\n * scoped per source: two scenes can each `stage.random(\"name\")` and get their\n * own reproducible stream without touching a shared stage-level seed.\n *\n * const random = stage.random(\"sparkle\");\n * const xs = random.floatArray(40, -100, 100); // 40 reproducible offsets\n * const drift = random.noise(t, 6); // smooth field over time\n *\n * Two families live here, and they are NOT interchangeable:\n * - **Independent draws** — `nextFloat`/`nextInt`/`gauss` and their array\n * forms. Successive calls are uncorrelated; `gauss` only changes the\n * *distribution* (bell curve vs flat), not the independence.\n * - **Correlated field** — `noise(t)`. Nearby inputs return nearby values, so\n * it is the right tool for smooth motion over time/space (drift, shake,\n * waves). No distribution draw can reproduce that smoothness.\n */\nexport class Random {\n /** The seed this source rewinds to; reassign via {@link seed} or\n * {@link reset}. Set by {@link adopt} (definitely assigned via the\n * constructor's `adopt` call). */\n private _seed!: string | number;\n\n /** Numeric form of {@link _seed}, used to mix `noise`'s lattice. Kept in\n * lockstep with `_seed` through {@link adopt}. */\n private numericSeed!: number;\n\n private readonly gen: SeedGenerator;\n\n /** A spare gaussian sample from the last Box–Muller pair (see {@link gauss}). */\n private spareGauss: number | null = null;\n\n constructor(seed: string | number) {\n this.gen = new SeedGenerator(seed);\n this.adopt(seed);\n }\n\n /** The seed this source rewinds to. Assigning a new value re-anchors the\n * source (same effect as `reset(seed)`): the next draws reproduce the\n * sequence for that seed, and `noise`'s lattice shifts to match. */\n get seed(): string | number {\n return this._seed;\n }\n set seed(seed: string | number) {\n this.adopt(seed);\n }\n\n /** Numeric form of a seed: string seeds are hashed (the same djb2-style mix\n * the generator uses), numbers pass through. Shared so the constructor, the\n * {@link seed} setter, and {@link reset} all derive `numericSeed` identically. */\n private static toNumeric(seed: string | number): number {\n return typeof seed === 'string'\n ? seed.split('').reduce((a, b) => (a << 5) - a + b.charCodeAt(0), 0)\n : seed;\n }\n\n /** Take `seed` as the new origin and rewind to it: store it, recompute the\n * `noise` lattice anchor, reset the generator, and drop any spare gauss. The\n * single seed-adoption path behind the constructor, {@link seed}, and a\n * seeded {@link reset}. */\n private adopt(seed: string | number): void {\n this._seed = seed;\n this.numericSeed = Random.toNumeric(seed);\n this.gen.setSeed(seed);\n this.spareGauss = null;\n }\n\n /**\n * The next pseudo-random float in `[from, to)`. Defaults to `[0, 1)`.\n */\n nextFloat(from: number = 0, to: number = 1): number {\n return this.gen.next() * (to - from) + from;\n }\n\n /**\n * The next pseudo-random integer in `[from, to)`. Defaults to the full\n * unsigned 32-bit range `[0, 2^32)`.\n */\n nextInt(from: number = 0, to: number = UINT32_RANGE): number {\n return Math.floor(this.gen.next() * (to - from)) + from;\n }\n\n /** `size` independent floats in `[from, to)`. */\n floatArray(size: number, from: number = 0, to: number = 1): number[] {\n const out = new Array<number>(size);\n for (let i = 0; i < size; i++) out[i] = this.nextFloat(from, to);\n return out;\n }\n\n /** `size` independent integers in `[from, to)`. */\n intArray(size: number, from: number = 0, to: number = UINT32_RANGE): number[] {\n const out = new Array<number>(size);\n for (let i = 0; i < size; i++) out[i] = this.nextInt(from, to);\n return out;\n }\n\n /**\n * A normally-distributed sample with the given `mean` and `stdev` (default\n * standard normal). Values cluster near the mean and tail off — useful for\n * natural-looking scatter where most draws stay central with occasional\n * outliers.\n *\n * Uses the polar Box–Muller transform, which yields two independent normals\n * per pair of uniforms; the spare is cached and returned on the next call.\n */\n gauss(mean: number = 0, stdev: number = 1): number {\n if (this.spareGauss !== null) {\n const z = this.spareGauss;\n this.spareGauss = null;\n return mean + stdev * z;\n }\n // Rejection-sample a point in the unit circle, then map to two normals.\n let u: number, v: number, s: number;\n do {\n u = this.gen.next() * 2 - 1;\n v = this.gen.next() * 2 - 1;\n s = u * u + v * v;\n } while (s >= 1 || s === 0);\n const mul = Math.sqrt(-2 * Math.log(s) / s);\n this.spareGauss = v * mul;\n return mean + stdev * (u * mul);\n }\n\n /**\n * Smooth 1-D value noise in `[0, 1]`.\n *\n * Samples two adjacent lattice points around `time * frequency`, then\n * interpolates with a smoothstep curve (`3t² - 2t³`) to avoid the linear\n * kinks of plain lerp. Unlike {@link nextFloat}/{@link gauss}, nearby\n * `time` inputs return nearby values — this is the correlated field used for\n * organic, continuously varying motion (camera shake, drift, waves).\n *\n * @param time Sample position (e.g. normalized timeline `[0, 1]`, or a\n * spatial index).\n * @param frequency Scales `time` before sampling; higher = faster\n * oscillation / more crests across the same span.\n */\n noise(time: number, frequency: number = 1): number {\n const t = time * frequency;\n const i = Math.floor(t);\n const f = t - i;\n // Smoothstep: maps f through 3f²-2f³ to ease in/out between lattice points.\n const curve = f * f * (3 - 2 * f);\n const r1 = this.latticeValue(i);\n const r2 = this.latticeValue(i + 1);\n return r1 + (r2 - r1) * curve;\n }\n\n /**\n * Rewind this source so the next draws reproduce a sequence from the start.\n *\n * With no argument, rewinds to the current {@link seed} — what authors call to\n * repeat a sequence within a scene. Pass a `seed` to adopt it as the new origin\n * first (equivalent to assigning {@link seed}), so the source both re-seeds and\n * rewinds in one call — e.g. in a node's constructor to give it a distinct\n * reproducible stream.\n */\n reset(seed: string | number = this._seed): void {\n this.adopt(seed);\n }\n\n /**\n * Deterministic value in `[0, 1)` for a given integer lattice point `x`,\n * mixed with this source's seed via `sin`. Pure in `x` (no generator state),\n * so {@link noise} is stable regardless of how many draws preceded it.\n */\n private latticeValue(x: number): number {\n const h = Math.sin(x + this.numericSeed) * 10000;\n return h - Math.floor(h);\n }\n}\n", "/**\n * A flat animation driver. `advance(dt)` moves the animation forward by `dt`\n * seconds and returns `true` once it has completed (and applied its final\n * value). It must be primed at t=0 before the first `advance` so the starting\n * frame is correct — callers apply the initial value via `seek(0)`.\n *\n * `seek(elapsed)` is the absolute-time half, and is what a {@link Command}'s\n * `at` is built on: a stepper can be asked for any time, in any order, which is\n * what lets a timeline evaluate a frame without having played the ones before\n * it.\n */\n/** @internal */\nexport interface TweenStepper {\n /**\n * Jump to the value corresponding to `elapsed` seconds from the start.\n * Call with `0` to prime the stepper before the first {@link advance}.\n */\n seek(elapsed: number): void;\n /**\n * Advance the animation by `dt` seconds.\n * @returns `true` when the animation has finished and its final value has\n * been applied; `false` if it is still running.\n */\n advance(dt: number): boolean;\n}\n\n/**\n * Implemented by anything that can produce a {@link TweenStepper} — a\n * {@link Command}, and anything a host drives directly.\n */\nexport interface Steppable {\n /** Return a fresh stepper for a single playthrough of this animation. */\n _stepper(): TweenStepper;\n}\n\nexport function isSteppable(x: unknown): x is Steppable {\n return typeof (x as Steppable)?._stepper === \"function\";\n}\n"],
5
- "mappings": "g7CA8BA,SAASA,GAAYC,EAAa,CAC9B,OAAO,OAAO,SAASA,CAAK,GAAKA,EAAQ,EAAIA,EAAQ,CACzD,CAOM,SAAUC,GAAiBD,EAAcE,EAAsBC,EAAwBD,EAAY,CACrG,OAAIE,GAAOJ,CAAK,EAAUK,GAAyBL,EAAOE,EAAcC,CAAa,EAC9E,KAAK,IAAI,EAAG,KAAK,IAAIA,EAAeD,CAAY,CAAC,EAAIH,GAAYC,CAAK,CACjF,CAGM,SAAUM,GAAiBN,EAAcE,EAAsBK,EAAmB,CACpF,OAAIH,GAAOJ,CAAK,EAAUQ,GAAwBR,EAAOE,EAAcK,CAAW,EAC3E,KAAK,IAAI,EAAG,KAAK,IAAIL,EAAcK,EAAcR,GAAYC,CAAK,CAAC,CA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MR,CAAC,EAChBkB,EAAIlB,EAAIQ,EAERW,EAAQD,EAAIA,GAAK,EAAI,EAAIA,GACzBE,EAAK,KAAK,aAAaZ,CAAC,EACxBa,EAAK,KAAK,aAAab,EAAI,CAAC,EAClC,OAAOY,GAAMC,EAAKD,GAAMD,CAC5B,CAWA,MAAMtB,EAAwB,KAAK,MAAK,CACpC,KAAK,MAAMA,CAAI,CACnB,CAOQ,aAAayB,EAAS,CAC1B,IAAMC,EAAI,KAAK,IAAID,EAAI,KAAK,WAAW,EAAI,IAC3C,OAAOC,EAAI,KAAK,MAAMA,CAAC,CAC3B,GC9KE,SAAUC,GAAYC,EAAU,CAClC,OAAO,OAAQA,GAAiB,UAAa,UACjD",
6
- "names": ["scalarSpeed", "speed", "clipTimeAtSource", "sourceLength", "sourceElapsed", "isRamp", "integrateSpeedToClipTime", "sourceTimeAtClip", "clipElapsed", "sourceTimeAtClipElapsed", "clipDurationOf", "clip", "mediaDuration", "length", "requestOf", "catalog", "ownerKey", "n", "at", "until", "trimStart", "trimEnd", "loop", "effects", "resolveAudioEffects", "staticValue", "request", "natural", "Sound", "props", "resolveAudioEffects", "trimmedSourceLength", "clipTimeAtSource", "effectsKey", "effects", "f", "paramKey", "EQUAL_POWER", "x", "shapes", "shapeOf", "transition", "curve", "shape", "easeOfSpec", "transitionSpans", "length", "transitionIn", "transitionOut", "wanted", "total", "scale", "transitionGainAt", "t", "spans", "gain", "transitionKey", "busStopKey", "stop", "paramKey", "effectsKey", "transitionKey", "KNOWN_KINDS", "isKnownShaderProperty", "property", "MAX_SHADER_PROPERTIES", "MAX_SHADER_SOURCE", "normalizeShaderPack", "input", "raw", "scope", "source", "base", "isRecord", "normalizeProperties", "textures", "t", "where", "out", "claimed", "id", "value", "warn", "inputs", "conflict", "uniform", "prior", "warned", "message", "nodePath", "parentPath", "childIndex", "declareNode", "node", "scope", "declareTree", "root", "children", "i", "bindDetached", "host", "node", "sampleTree", "child", "primeMotionTree", "at", "applyEditorStates", "root", "states", "walk", "node", "state", "child", "Canvas2D", "Node2D", "props", "args", "from", "target", "fillOps", "lerp", "t", "Graphics2D", "draw", "fill", "ctx", "overlay", "child", "c", "NodeAudio", "assets", "Clip", "rect", "NO_PROJECTION_3D", "camera", "spaceRootFrame", "w", "h", "cx", "cy", "declareMembers", "fillProperty", "flowProperty", "property", "alignmentProperty", "lerpLookAt", "command", "scalarCorners", "Types", "lerpCornerScalarStyle", "Rect", "component2d", "state", "commands", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "draw", "rect", "Ellipse", "ellipse", "Polygon", "polygon", "Polygram", "polygram", "PathShape", "unitPath", "Path", "_measurer", "intrinsic", "pathOps", "pad", "facePath", "boundsShape", "key", "kind", "outline", "Triangle", "RightTriangle", "Pentagon", "Hexagon", "Octagon", "Star", "STAR_DEFAULT_POINTS", "STAR_DEFAULT_RATIO", "BooleanGroup", "component2d", "state", "Types", "commands", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "MaskGroup", "Camera", "component2d", "state", "commands", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "draw", "rect", "camera", "orbit", "Types", "lerpLookAt", "OrbitCamera", "commandsFor", "RotatedBox", "cos", "sin", "turn", "w", "h", "ortho", "room", "width", "height", "child", "size", "turned", "angle", "rad", "_overlay", "glyphPaint", "state", "_overlayTo", "glyphCommands", "commands", "autofits", "NO_RUNS", "resolvePath", "value", "PathBuilder", "resolveRuns", "fill", "stroke", "run", "fillOps", "strokeOps", "textState", "Types", "textSource", "Text", "component2d", "timeline", "loader", "load", "measurer", "measure", "ctx", "draw", "numberState", "numberSource", "formatNumber", "numberNodePattern", "NumberNode", "_v", "_d", "_c", "_m", "richStyle", "RichText", "inherit", "v", "loadRichText", "measureRichText", "drawRichText", "DefaultTextStyle", "provided", "inherited", "provide", "current", "Provider", "component2d", "Types", "state", "provides", "ThemeProvider", "inherited", "out", "ThemeToken", "DataToken", "SeedToken", "SoundNode", "componentAudio", "Types", "lerpParam", "timeline", "state", "AudioBus", "video", "Types", "v", "resolveChainAdjustments", "lerpFilterArray", "resolveAudioEffects", "playedAt", "s", "elapsed", "played", "segment", "scheduledTimestamp", "start", "first", "sourceTimeFor", "pictures", "pictureOf", "host", "scheduled", "crop", "anchor", "key", "kept", "prop", "fill", "resolveFill", "Video", "component2d", "state", "commands", "timeline", "speed", "loop", "loader", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "picture", "internalsOf", "outline", "draw", "rect", "UNSET_MEDIA_FILL", "Graphics2D", "ORBIT_CAMERA_DEFAULTS", "isOrbitCamera3D", "camera", "resolveCameraPlacement", "target", "resolveVector3", "aim", "distance", "azimuth", "elevation", "clamp", "horizontal", "value", "low", "high", "Group3D", "component3d", "mesh", "optional", "state", "Mesh3D", "ctx", "s", "sweep", "SWEEP_KEYS", "shape3d", "key", "type", "own", "keys", "stated", "Box3D", "Sphere3D", "Plane3D", "Cylinder3D", "Cone3D", "Torus3D", "TorusKnot3D", "Circle3D", "Ring3D", "Capsule3D", "Polyhedron3D", "Types", "Extrude3D", "Lathe3D", "Tube3D", "Instances3D", "Graphics3D", "single", "Points3D", "points", "Line3D", "Sprite3D", "lerpFill3D", "Model3D", "ModelView3D", "modelClip", "clip", "trimmed", "index", "castsNoShadow", "AmbientLight3D", "optionalColor", "HemisphereLight3D", "DirectionalLight3D", "optionalVector3", "PointLight3D", "SpotLight3D", "AreaLight3D", "CAMERA_KEYS", "ORBIT_KEYS", "Camera3D", "optionalNumber", "timeline", "from", "ORBIT_CAMERA_DEFAULTS", "t", "out", "end", "data", "Fog3D", "Environment3D", "defined", "Canvas3D", "component2d", "state", "commands", "loader", "load", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "draw", "isStillDocument", "doc", "isCompositionDocument", "isAudioDocument", "hasTimeline", "ROOT_NODE_ID", "nodeSpan", "spec", "timed", "effectiveSpan", "nodes", "id", "effectiveSpanIn", "n", "effectiveSpans", "byId", "spans", "chain", "inChain", "start", "above", "known", "member", "i", "span", "seen", "parent", "own", "untimed", "_startAt", "_endAt", "rest", "commandSpan", "command", "duration", "loopPasses", "documentDuration", "end", "node", "isProjectDocument", "doc", "asProjectDocument", "output", "documentDuration", "DOCUMENT_FORMAT_VERSION", "DocumentTooNewError", "version", "supported", "DOCUMENT_MIGRATIONS", "clip", "note", "constants", "rest", "variables", "row", "_kind", "variable", "retireSkSL", "SKSL_SOURCE", "isObject", "value", "path", "out", "item", "next", "key", "retireShader", "shader", "legacyKey", "moved", "sksl", "stamped", "hadCoords", "documentFormatVersion", "doc", "migrateDocument", "migrateDocumentWith", "migrations", "target", "from", "changes", "json", "migrateProject", "migrateClip", "stepsBetween", "to", "steps", "step", "m", "noteInto", "prefix", "message", "stamp", "project", "tracksChanged", "tracks", "track", "i", "own", "LOOP_DIRECTIONS", "isPlainObject", "v", "isTime", "checkEase", "ease", "path", "issues", "kind", "args", "EASE_KINDS", "isEaseCurve", "checkAudioEase", "checkParam", "value", "expressionOps", "key", "i", "at", "TRANSITION_KEYS", "checkTransition", "transition", "checkAudioProps", "type", "props", "name", "effects", "effect", "field", "checkLoop", "loop", "direction", "count", "checkNodeSpec", "node", "ok", "id", "parentId", "layerOrder", "checkNodeKeys", "sites", "byKey", "site", "existing", "checkRootShape", "spec", "rootType", "checkCommandSpec", "cmd", "targetId", "duration", "checkVariableSpec", "lerp", "variableRows", "rows", "checkVariables", "byId", "splitNodeRef", "ref", "dot", "checkExpressions", "declared", "keyed", "parsed", "k", "boundProps", "out", "prop", "reads", "checkExpressionCycles", "bound", "b", "settled", "stack", "reported", "walk", "entry", "cycle", "member", "next", "checkTree", "bySite", "parent", "seen", "cursor", "checkIdSpace", "nodes", "variables", "clash", "checkRetiredFields", "doc", "checkFormatVersion", "version", "RETIRED_PROJECT_FIELDS", "checkVocabulary", "commands", "registry", "typeOf", "checkNodes", "n", "checkSpan", "startAt", "endAt", "validateStill", "s", "keys", "validateComposition", "validateTimedDocument", "validateAudio", "RETIRED_COMMANDS", "nodeSites", "valid", "ids", "c", "retired", "span", "effectiveSpanIn", "validateDocument", "options", "validateProjectDocument", "project", "message", "raw", "track", "issue", "clipIssuesOf", "CLIP_ISSUES", "clip", "assertValidProjectDocument", "detail", "assertValidDocument", "MissingNode2D", "component2d", "MissingNode3D", "component3d", "MissingNodeAudio", "componentAudio", "PLACEHOLDERS", "DRAWS", "KEPT", "dimension", "ctor", "getPropertyMeta", "m", "key", "MISSING", "MISSING_TYPE", "missingNode", "spec", "props", "node", "placeholderProps", "kept", "out", "value", "missingNodeOf", "registryVocabulary", "registry", "nodes", "key", "properties", "prop", "described", "vocabularyBreaks", "prev", "next", "out", "command", "type", "was", "now", "before", "after", "NODE_TYPES", "Canvas2D", "Provider", "ThemeProvider", "DefaultTextStyle", "Rect", "Ellipse", "PathShape", "Polygon", "Polygram", "BooleanGroup", "MaskGroup", "Camera", "OrbitCamera", "RotatedBox", "Text", "RichText", "NumberNode", "Video", "AudioBus", "SoundNode", "Canvas3D", "Group3D", "Mesh3D", "Box3D", "Sphere3D", "Plane3D", "Circle3D", "Cylinder3D", "Cone3D", "Capsule3D", "Torus3D", "TorusKnot3D", "Tube3D", "Lathe3D", "Extrude3D", "Ring3D", "Polyhedron3D", "Points3D", "Line3D", "Sprite3D", "Instances3D", "Model3D", "Camera3D", "AmbientLight3D", "DirectionalLight3D", "PointLight3D", "SpotLight3D", "HemisphereLight3D", "AreaLight3D", "Fog3D", "Environment3D", "paintCommand", "method", "argKey", "target", "args", "duration", "easing", "fn", "VARIABLE_LERPS", "lerpNumber", "lerpVector2", "lerpVector3", "from", "to", "r", "g", "b", "a", "lerpColor", "parseColor", "channel", "v", "installBuiltins", "registry", "key", "ctor", "lerp", "props", "driveCommand", "lerpKey", "override", "captured", "t", "DENIED_GLOBALS", "UNBINDABLE", "illegal", "name", "SDK_SPECIFIERS", "Registry", "_Registry", "options", "installBuiltins", "ctor", "key", "lerp", "ease", "pack", "type", "ctorOrOptions", "maybeOptions", "isTwoArgForm", "given", "cls", "declared", "getNodeDescriptor", "descriptor", "existing", "commands", "meta", "getCommandMeta", "source", "js", "spec", "props", "record", "evolution", "propEvolutionOf", "applyPropEvolution", "factory", "nodeTypeKey", "commandKey", "entry", "target", "args", "duration", "easing", "fn", "data", "arg", "global", "value", "where", "resolved", "normalized", "normalizeShaderPack", "sdk", "modules", "require", "specifier", "available", "s", "mod", "DENIED_GLOBALS", "out", "getPropertyMeta", "editor", "properties", "message", "renamed", "dimension", "trees", "v", "CANVAS_3D", "nodeTypeIsA", "registry", "type", "name", "seen", "at", "among", "names", "options", "parentIssue", "child", "parent", "own", "holder", "within", "inThree", "siblingIssue", "siblings", "beside", "placementIssues", "nodes", "parentOf", "node", "ROOT_NODE_ID", "byId", "children", "under", "issues", "parentId", "parentType", "issue", "without", "types", "AUDIO_ROOT_ID", "defaultRootBus", "clipRoot", "loweredAudioDocument", "doc", "nodes", "isRootBus", "spec", "reparent", "retarget", "command", "withPlayedSounds", "doc", "played", "c", "added", "spec", "start", "end", "nodeSpan", "segments", "segment", "i", "clipDocument", "lowered", "isAudioDocument", "loweredAudioDocument", "isStillDocument", "ALIGNMENT_KEYS", "SKIPPED", "commandTraits", "registry", "spec", "target", "lifecycle", "LIFECYCLE", "global", "known", "VARIABLE_COMMANDS", "row", "DEFAULT_ROOT", "record", "chain", "GLOBAL_NODE_COMMANDS", "methodOf", "entry", "NODE_COMMANDS", "implementsCore", "args", "props", "written", "writtenKeys", "readsLayout", "key", "isLayoutNeutralProp", "holdsWhenFinished", "traits", "HELD", "expressionOps", "commandNodeRefs", "descriptors", "refs", "descriptor", "value", "isContextProvider", "type", "ctor", "Node", "hasNodeRef", "site", "parsed", "ref", "isPlacementProp", "coreLibrary", "NEUTRAL_KEYS", "dimension", "PLACEMENT_3D", "PLACEMENT_2D", "writesPlacementInPlace", "sugar", "PLACEMENT_SUGAR_3D", "PLACEMENT_SUGAR_2D", "prop", "ROOT_NODE_ID", "TO", "PAINT", "WRITES", "READS_FROM", "hasAlignmentKey", "aligned", "refBound", "nodeRefKeys", "named", "keys", "values", "REF_KEYS", "found", "name", "KNOWN", "byChain", "impl", "coreImplementations", "core", "seeded", "Registry", "library", "impls", "proto", "own", "jsonEqual", "a", "b", "i", "ao", "bo", "defined", "key", "value", "emptyDiff", "diffClip", "prev", "next", "diff", "p", "lowered", "n", "documentDuration", "diffNodes", "diffVariables", "prevCommands", "nextCommands", "diffCommands", "rowsEmpty", "doc", "clipDocument", "rows", "DEFAULT_ROOT", "ROOT_NODE_ID", "prevRows", "nextRows", "byId", "changes", "prevRoot", "nextRoot", "sameNode", "id", "changed", "sameSpan", "prevKeys", "keyed", "was", "prevOrder", "siblingOrder", "nextOrder", "parent", "before", "after", "sameRelativeOrder", "sa", "nodeSpan", "sb", "prevAts", "groupByAt", "nextAts", "at", "out", "row", "groups", "index", "list", "e", "inB", "inA", "sharedA", "sharedB", "splitNodeRef", "ref", "dot", "expressionRefs", "value", "path", "vars", "keys", "unparsable", "seen", "site", "expressionOps", "parsed", "node", "indexDocument", "doc", "DocumentIndex", "clipDocument", "NO_REFS", "NO_BINDINGS", "EMPTY", "contains", "span", "t", "documentDuration", "commandRows", "spec", "index", "a", "b", "e", "target", "list", "atList", "parentId", "id", "out", "seen", "stack", "child", "grand", "i", "nodeSpan", "memo", "chain", "base", "cursor", "known", "ROOT_NODE_ID", "own", "at", "lo", "hi", "mid", "rows", "siblings", "parent", "settled", "command", "expressionRefs", "props", "vars", "keys", "unparsable", "refs", "v", "pair", "readers", "key", "prop", "found", "table", "existing", "p", "SettledIndex", "_SettledIndex", "placed", "finish", "writers", "replayed", "running", "read", "i", "p", "marked", "settles", "end", "readEarlier", "finishTime", "slot", "written", "observeSlots", "list", "writer", "Track", "index", "seconds", "tracks", "held", "k", "w", "long", "bin", "binEnd", "a", "b", "c", "ia", "NONE", "ib", "ic", "clamp01", "f", "_finish", "_tracks", "_replayed", "from", "to", "bins", "MAX_BINS", "items", "first", "last", "MAX_SPAN", "trackOf", "track", "fixes", "writes", "x", "y", "best", "lo", "hi", "mid", "start", "duration", "done", "t", "step", "down", "BITS", "INTS", "up", "MIN_REBUILD_NODES", "planTimelinePatch", "prev", "next", "diff", "env", "options", "structurallyFaulty", "prevRoot", "ROOT_NODE_ID", "nextRoot", "onlyPropsDiffer", "prevTraits", "traitsOf", "nextTraits", "added", "removed", "respec", "moved", "span", "reorderedParents", "targeted", "id", "anyCommand", "index", "traits", "test", "cid", "unknownEither", "t", "laidOut", "type", "laidOutEither", "kept", "R", "isProvider", "a", "b", "reinstantiate", "d", "inPlace", "placementOnly", "providerAbove", "reregistered", "live", "DN", "DV", "mark", "sameList", "at", "spec", "presenceChanged", "sameSpan", "L", "respecTouchesLayout", "valueChanged", "aimed", "nodeReaders", "bindsLayout", "reader", "reads", "prop", "refs", "size", "v", "key", "keysOf", "k", "ref", "lineageIn", "limit", "replay", "queue", "visited", "detach", "parent", "child", "captures", "duplicateIds", "duplicateKeys", "unresolvedParent", "cycle", "invalidRoot", "out", "targetId", "target", "set", "seen", "cursor", "parentId", "sa", "nodeSpan", "sb", "was", "is", "jsonEqual", "i", "resolveEase", "ease", "registry", "easeOfSpec", "key", "inTimelineOrder", "commands", "spec", "index", "a", "b", "NO_SLOTS", "readsOf", "command", "recorder", "owned", "settles", "slot", "heldIf", "held", "made", "settling", "defaultRootSpec", "ROOT_NODE_ID", "splitRoot", "specs", "rest", "root", "presenceOf", "doc", "spans", "node", "nodeSpan", "ClipTimeline", "canvas", "documentDuration", "captureLayer", "NO_LAYER", "PropSlot", "PRESENCE_PREFIX", "id", "entry", "captureInitial", "settle", "moved", "out", "placed", "played", "commandSoundsOf", "sound", "missing", "missingNodeOf", "seconds", "onWrite", "unobserved", "baseline", "local", "clamp01", "rows", "arrivals", "departures", "row", "wanted", "within", "byDocumentOrder", "byParent", "group", "siblings", "parent", "base", "child", "layer", "props", "snap", "next", "prev", "indexDocument", "planTimelinePatch", "diffClip", "patch", "prepare", "fresh", "host", "applySnapshotLayer", "resetToInitial", "previous", "rebuilt", "dirty", "touched", "isStillDocument", "old", "name", "dot", "prop", "_observer", "at", "depth", "literal", "bindings", "expressionOps", "migrateNodeProps", "hasBindings", "dimension", "missingNode", "bound", "placeholderProps", "cell", "VAR_PREFIX", "lerp", "v", "nodes", "ordered", "refBound", "SettledIndex", "whole", "written", "i", "slots", "slotBaselines", "entries", "parentId", "captureBaseline", "typeKey", "factory", "message", "LEGACY_COMMAND_HINTS", "duration", "easing", "WriteRecorder", "loop", "loopRepeats", "repeat", "loopCommand", "variable", "holdsWhenFinished", "commandTraits", "observeSlots", "buildToEnd", "target", "given", "PROP_DIFF_COMMANDS", "args", "entrance", "ended", "byId", "s", "from", "effectiveSpanIn", "end", "owner", "found", "path", "source", "type", "seen", "of", "described", "holds", "d", "steps", "reads", "opener", "traits", "hasNodeRef", "PresenceIndex", "commandNodeRefs", "isContextProvider", "isLayoutNeutralProp", "writesPlacementInPlace", "MISSING_TYPE", "was", "changed", "value", "jsonEqual", "added", "removed", "isDocumentNode", "disposeBuilt", "replay", "captures", "c", "pending", "step", "firstWrite", "LAYOUT_SLOT", "make", "driveCommand", "cells", "SiblingCounts", "size", "delta", "count", "order", "start", "NO_ROWS", "to", "pass", "k", "lo", "hi", "mid", "withRichTextDescriptor", "descriptor", "width", "height", "x", "y", "pivot", "resolveShapeAlignment", "stripShapeAlignmentKeys", "resolveShapePivot", "withTransformDescriptor", "descriptor", "toPathString", "d", "cmd", "withPathDescriptor", "descriptor", "resolveShapePivot", "caretCount", "layout", "last", "asTextBlockSource", "value", "toRenderIssue", "issue", "renderIssueKey", "RenderBackendError", "isFatalRenderIssue", "Geo", "o", "source", "src", "Mat", "Tex", "data", "width", "height", "segmentsOf", "value", "defaults", "clampSegment", "fallback", "index", "arcSegmentsFor", "radius", "maxHalf", "evaluateRoundedBox", "options", "half", "box", "arc", "position", "normal", "uv", "index", "grid", "patches", "emit", "segments", "AXES", "SIGNS", "axis", "u", "v", "sign", "face", "axisVector", "a", "b", "point", "lerp", "signA", "signB", "t", "angle", "dir", "s", "signX", "signY", "signZ", "corner", "direction", "polar", "azimuth", "base", "uCount", "vCount", "vi", "ui", "planarUv", "c", "d", "pushTriangle", "ax", "ay", "az", "bx", "by", "bz", "cx", "cy", "cz", "ux", "uy", "uz", "vx", "vy", "vz", "nx", "ny", "nz", "out", "from", "to", "shadowCasts", "mode", "shadowReceives", "resolveShadowOptions3D", "cylinderRadii", "radius", "resolveBevel3D", "bevel", "options", "size", "evaluateParametric", "geometry", "resolved", "uSegments", "vSegments", "uCount", "vCount", "position", "uv", "color", "scratch", "vi", "v", "ui", "u", "index", "vertex", "p", "rgba", "resolveLinearRgb", "cursor", "a", "b", "c", "d", "r", "g", "parseColor", "srgbToLinear", "channel", "identity4", "multiply4", "a", "b", "out", "col", "b0", "b1", "b2", "b3", "invert4", "m", "n11", "n21", "n31", "n41", "n12", "n22", "n32", "n42", "n13", "n23", "n33", "n43", "n14", "n24", "n34", "n44", "t11", "t12", "t13", "t14", "determinant", "d", "applyMatrix4", "p", "x", "y", "z", "compose4", "position", "rotation", "scale", "w", "x2", "y2", "z2", "xx", "xy", "xz", "yy", "yz", "zz", "wx", "wy", "wz", "lookAtRotation4", "eye", "target", "up", "UP", "zx", "zy", "length", "xLength", "yx", "transformMatrix4", "transform", "parentWorld", "resolveVector3", "world", "origin", "inverseParent", "rotationOf4", "translation4", "scale4", "quaternion", "quaternionFromEuler", "eulerOf", "sx", "sy", "sz", "perspective4", "fov", "aspect", "near", "far", "zoom", "top", "height", "width", "left", "frustum4", "right", "bottom", "c", "orthographic4", "dx", "dy", "cx", "cy", "r", "t", "h", "centeredBox3", "hx", "hy", "hz", "unionBox3", "a", "b", "corners3", "box", "min", "max", "transformBox3", "m", "minX", "minY", "minZ", "maxX", "maxY", "maxZ", "corner", "p", "applyMatrix4", "geometryBounds3D", "geometry", "top", "bottom", "cylinderRadii", "radius", "tube", "outer", "point", "resolveVector3", "points", "pointsBounds3", "expandBox3", "positionBounds3", "position", "i", "x", "y", "z", "by", "MUTABLE_MATERIAL_KEYS", "STRUCTURAL_MATERIAL_KEYS", "AssetManager", "precomp", "storageAdapter", "audioDevice", "onError", "error", "layoutGatesOf", "src", "frame", "jobs", "key", "track", "job", "records", "record", "err", "discardAt", "dispose", "load", "existing", "disposer", "NO_DISPOSE", "currentTime", "inWindow", "srcs", "required", "seen", "consider", "req", "offsetSecs", "globalStart", "globalEnd", "stableId", "stableKey", "s", "data", "cause", "requestKey", "audioSignature", "setsEqual", "message", "keys", "clipOffsetSecs", "paramKey", "effectsKey", "transitionKey", "busKey", "bus", "busStopKey", "reqs", "r", "a", "b", "v", "assetKey", "decl", "normalizeWeight", "weight", "AssetDeclaration", "catalog", "options", "src", "trim", "family", "key", "load", "gate", "existing", "fills", "declareFill", "fill", "effects", "effect", "declareEffect", "node", "declareTree", "now", "nativeYield", "s", "channel", "queue", "messageChannelYield", "resolve", "yieldToScheduler", "native", "__resetSchedulerForTests", "clipFrameToTime", "frame", "fps", "clipTimeToFrame", "seconds", "nearest", "frameSpecAtTime", "trackFrameCount", "seconds", "fps", "clipTimeToFrame", "placeTracks", "tracks", "track", "index", "startFrame", "totalFramesOf", "spans", "total", "span", "spansCovering", "frame", "frameTime", "duration", "clipFrameToTime", "spanFrames", "frameCount", "last", "at", "endFrame", "ClipInstance", "clip", "duration", "_scope", "lowered", "width", "height", "Canvas2D", "ROOT_NODE_ID", "ClipTimeline", "measurer", "next", "patch", "relayout", "seconds", "read", "was", "onWrite", "editor", "ContextMap", "applyEditorStates", "pass", "sampleTree", "at", "primeMotionTree", "rowId", "row", "id", "node", "below", "current", "parent", "index", "span", "visit", "walk", "path", "own", "children", "i", "nodePath", "child", "spans", "effectiveSpans", "spec", "clipDocument", "NO_OWNERS", "AssetIndex", "frameCount", "ownerKey", "segments", "touched", "previous", "next", "segment", "appendSegment", "decl", "frame", "key", "assetKey", "owner", "list", "at", "s", "hit", "owners", "out", "gates", "entry", "map", "keys", "changed", "sameRecord", "last", "first", "start", "end", "layoutLoader", "visit", "from", "to", "recordOf", "startFrame", "endFrame", "a", "b", "v", "refineAssets", "instance", "options", "sweep", "Sweep", "MAX_REQUEUES", "_instance", "_options", "owners", "below", "limited", "from", "p", "slot", "span", "frames", "spanFrames", "placed", "isPseudo", "frame", "heapPop", "readers", "owner", "intervals", "segmentsOf", "keys", "key", "isDev", "rows", "slash", "spans", "row", "start", "duration", "fps", "end", "frameTime", "to", "seconds", "observeSlots", "index", "seen", "node", "presentAt", "unchanged", "reads", "writes", "lastRead", "readLayout", "readClock", "bind", "sub", "bindDetached", "declaration", "AssetDeclaration", "unobserved", "LAYOUT_SLOT", "declareNode", "err", "e", "slotLabel", "type", "labels", "warnOnce", "set", "decls", "previous", "sameDecls", "writers", "visit", "first", "last", "after", "commandId", "entry", "list", "heapPush", "STRUCTURE_SLOT", "PRESENCE_PREFIX", "deps", "i", "a", "b", "decl", "other", "sameDecl", "history", "out", "open", "segment", "next", "warned", "message", "heap", "value", "parent", "top", "tail", "left", "right", "child", "HOSTED", "HOSTLESS", "DETACHED", "hostSlotId", "ownerKey", "name", "hostlessSlotId", "hostOf", "id", "nameOf", "SlotNamer", "_instance", "slot", "host", "key", "Node", "slots", "out", "rowsAbove", "slash", "addTo", "map", "value", "set", "removeFrom", "NONE", "OwnerDependencies", "own", "row", "dirtyOwners", "input", "patch", "deps", "fps", "prev", "next", "diff", "lower", "frame", "at", "owner", "arrival", "readers", "below", "startOf", "index", "span", "firstFrameAt", "placement", "PRESENCE_PREFIX", "STRUCTURE_SLOT", "spec", "ROOT_NODE_ID", "hosted", "names", "writes", "placed", "VAR_PREFIX", "LAYOUT_SLOT", "parent", "from", "a", "b", "changedRows", "changedProps", "dep", "changedSlots", "props", "providerChangedAbove", "jsonEqual", "changed", "seen", "parentId", "seconds", "frameTime", "AudioIndex", "ownerKey", "requests", "prior", "sameValue", "out", "a", "b", "keys", "key", "COMMAND_AUDIO", "DEFAULT_PRECOMP_BUDGET_MS", "ClipStore", "project", "_scope", "options", "track", "placeTracks", "next", "update", "themeChanged", "jsonEqual", "previous", "old", "entry", "changed", "id", "spans", "sameSpans", "trackId", "budgetMs", "isCancelled", "onProgress", "deadline", "now", "finished", "yieldToScheduler", "key", "ownerKey", "decl", "localFrame", "trackIds", "isReady", "rebuilt", "gates", "record", "arrived", "frame", "horizon", "i", "span", "frameCount", "trackFrameCount", "AssetIndex", "AudioIndex", "OwnerDependencies", "diffClip", "instance", "patch", "refined", "before", "measurer", "issuesOf", "dirty", "dirtyOwners", "node", "child", "type", "isContextProvider", "keys", "duration", "best", "bestStart", "build", "refine", "index", "steps", "result", "profile", "fps", "catalog", "ClipInstance", "err", "buildErrorOf", "audioSlots", "refineAssets", "phase", "_node", "namer", "SlotNamer", "owner", "slots", "collect", "delta", "row", "seen", "sweep", "spanFrames", "step", "fromOf", "from", "slash", "fromArrival", "candidates", "kept", "keptBefore", "ids", "assets", "audio", "sounds", "byOwner", "sound", "list", "spanOf", "found", "requests", "n", "busId", "closed", "bus", "target", "findBusById", "busPathTo", "NodeAudio", "busPathOf", "trimEnd", "requestOf", "error", "landed", "prior", "records", "sameRecords", "audioRequests", "clampAudioToClip", "layoutGates", "errors", "sameValue", "out", "placed", "named", "run", "inner", "families", "text", "fontSize", "fontFamily", "fontWeight", "letterSpacing", "fontStyle", "family", "code", "message", "nodeId", "commandId", "e", "segments", "segment", "clipDuration", "req", "clampBusToClip", "clamped", "endAt", "stop", "a", "b", "other", "StateEvaluator", "project", "_scope", "store", "ClipStore", "firstVisual", "slot", "frame", "target", "active", "sameSlots", "topmost", "measurer", "pass", "trackId", "next", "prior", "kept", "id", "states", "tracks", "spans", "placeTracks", "track", "i", "old", "covering", "spansCovering", "last", "span", "localFrame", "instance", "dt", "clipFrameToTime", "time", "frameTime", "previous", "slots", "isAudioDocument", "a", "b", "SETTLE_PASSES", "renderSettled", "render", "adapter", "isCurrent", "pass", "ProjectAssets", "_fps", "_catalog", "tracks", "touched", "live", "track", "prior", "moved", "key", "record", "before", "sameRecord", "id", "next", "entry", "current", "sameTrack", "holders", "trackId", "merged", "mergeRecord", "shiftRecord", "assetTrackOf", "offset", "existing", "intrinsicMB", "catalog", "size", "decodedMB", "LEADS_PER_MB", "MIN_LEAD", "MAX_LEAD", "TAIL_FRAMES", "width", "height", "leadFrames", "mb", "fps", "lead", "a", "b", "v", "ASSET_TIMELINE_PHASES", "createAssetTimelineProfile", "timings", "trackIndex", "trackId", "phases", "p", "open", "since", "now", "totalMs", "close", "elapsed", "phase", "frameCount", "AssetTimeline", "project", "_scope", "options", "ClipStore", "ProjectAssets", "n", "track", "frame", "span", "spansCovering", "budgetMs", "DEFAULT_PRECOMP_BUDGET_MS", "isCancelled", "onProgress", "next", "ownerKey", "decl", "localFrame", "store", "fps", "spans", "totalFrames", "totalFramesOf", "totalDuration", "tracks", "buildErrors", "complete", "local", "found", "undiscovered", "assets", "i", "resolveOpenAudio", "profiled", "id", "r", "offset", "audioRequests", "req", "absStart", "naturalEnd", "isViewport3D", "node", "collectBoxes3D", "canvas", "frame", "path", "projection", "canvas3DProjection", "out", "entry", "nodes3DOf", "world", "projected", "projectBox3", "toNodeBox", "a", "b", "ORIGIN_3D", "projectNode3D", "canvasPath", "targetPath", "parentPoints", "localPoints", "e", "own", "parent", "project", "matrix", "points", "point", "projectPoint3", "space", "parentSpaceOf", "placed", "applyMatrix4", "clip", "MIN_CLIP_W", "ndcX", "ndcY", "rectX", "rectY", "p", "applyToPoint", "pickNode3D", "tolerance", "inverse", "invert", "mapped", "local", "best", "bestDepth", "rectContains", "walk3D", "children", "parentPath", "i", "child", "Node3D", "nodePath", "bounds", "scene", "walked", "walkScene3D", "view", "invert4", "aspect", "multiply4", "projectionMatrix", "boxes", "matrices", "parentMatrices", "stack", "identity4", "camera", "descriptor", "top", "op", "scope", "scopeMatrix", "closed", "unionBox3", "cameraMatrix4", "drawn", "drawableBox3", "DEFAULT_CAMERA_MATRIX", "transform", "transformMatrix4", "transformBox3", "centeredBox3", "geometryBounds3D", "box", "instance", "placement", "resolveCameraPlacement", "origin", "translation4", "lookAtRotation4", "DEFAULT_FOV", "DEFAULT_NEAR", "DEFAULT_FAR", "perspective4", "halfHeight", "orthographic4", "BOX_EDGES", "OFFSCREEN_LIMIT", "corners3", "corner", "minX", "minY", "maxX", "maxY", "any", "include", "y", "w", "q", "pIn", "qIn", "t", "halfWidth", "limitX", "limitY", "rect", "clamp", "centre", "viewed", "value", "low", "high", "slop", "at", "x", "renderMatrix", "node", "frame", "spaceFrameOf", "multiply", "parent", "childrenMatrix", "m", "camera", "spaceRootFrame", "cam", "cameraMatrix", "parentPlanePointAt", "root", "path", "point", "nodeAt", "Node2D", "movePlaneMatrix", "inv", "invert", "p", "applyToPoint", "behindCamera", "plane", "box", "childPlanePointAt", "reparentPlacementAt", "parentPath", "offsets", "to", "from", "at", "slot", "along", "back", "into", "placed", "was", "childFold", "will", "turn", "scale", "shift", "here", "own", "pixels", "offset", "now", "o", "drawn", "centre", "x", "y", "folded", "foldedTransform", "nodeHandlesAt", "prop", "handleValueAt", "spaceFrameForChildren", "multiplyAffine3", "atDepth", "spaceScreenMatrix", "local", "isProjective", "rotation", "opacity", "n", "nodeBox", "b", "translation", "anchors", "worldAnchors", "nodeBoxAt", "canvas", "segments", "isViewport3D", "prefixPath", "next", "canvas3DFrame", "collectBoxes3D", "segment", "count", "projectNode3DAt", "parentPoints", "localPoints", "i", "projectNode3D", "pickNode", "tolerance", "pickIn", "isRoot", "spaceVisibility", "inside", "containsPoint", "children", "childSlots", "order", "paintOrder", "k", "hit", "nodePath", "pickNode3D", "collectBoxes", "out", "natural", "_", "slots", "frames", "spaceChildFrame", "spaceChildOrder", "child", "nodeTextLayout", "node", "path", "source", "state", "Text", "textStateOf", "block", "m", "renderMatrix", "at", "x", "y", "p", "applyToPoint", "carets", "caretCount", "lines", "line", "i", "caretOffsetAt", "layout", "point", "best", "bestDistance", "caret", "d", "distanceToSegment", "caretRangeQuads", "start", "end", "from", "to", "quads", "b", "left", "right", "a", "dx", "dy", "lengthSq", "t", "PlaybackController", "track", "index", "error", "frame", "issue", "e", "key", "renderIssueKey", "prior", "decl", "declOf", "trackId", "instance", "t", "ownerKey", "node", "next", "AssetNotLoadedError", "token", "record", "cause", "type", "src", "params", "project", "DEFAULT_PRECOMP_BUDGET_MS", "scope", "ClipStore", "AssetTimeline", "StateEvaluator", "AssetManager", "speed", "reverse", "currentTime", "gen", "clipTimeToFrame", "yieldToScheduler", "final", "result", "gates", "span", "spansCovering", "TRIM_HORIZON_SECONDS", "cb", "raw", "toRenderIssue", "clamped", "clipFrameToTime", "err", "render", "upgrades", "adapter", "settlingUpgrades", "outcome", "renderSettled", "stale", "trackStart", "frameCount", "trackFrameCount", "bars", "pathOfOwner", "_node", "path", "frames", "spanFrames", "waveformsByPath", "waveformsByOwner", "nodeToTreeState", "nodeId", "canvas", "findNode", "nodeBoxAt", "nodeAt", "out", "collectBoxes", "parentPoints", "localPoints", "projectNode3DAt", "point", "parentPlanePointAt", "childPlanePointAt", "parentPath", "offsets", "reparentPlacementAt", "nodeHandlesAt", "prop", "handleValueAt", "findNodeByPath", "Node2D", "source", "asTextBlockSource", "nodeTextLayout", "tolerance", "pickNode", "props", "existing", "states", "pass", "decoded", "upgraded", "muted", "catalog", "isParentNode", "state", "c", "i", "nodePath", "waveform", "bar", "requests", "byPath", "req", "info", "list", "root", "seg", "id", "child", "found", "ManifestAssetCatalog", "manifest", "src", "meta", "key", "fontFamily", "audio", "video", "width", "height", "Playback", "controller", "speed", "reverse", "frame", "muted", "callback", "Ticker", "duration", "t", "notify", "cb", "playing", "speed", "reverse", "c", "callback", "SteppedClock", "Ticker", "t", "Session", "engine", "options", "resolveProjectDocument", "ManifestAssetCatalog", "manifest", "deps", "measurer", "audioDevice", "masterClock", "PlaybackController", "SteppedClock", "Playback", "seconds", "clipTimeToFrame", "frame", "document", "next", "setTheme", "override", "fallback", "opened", "asProjectDocument", "migrated", "migrateDocument", "project", "resolved", "assertValidProjectDocument", "parseCSV", "text", "options", "delimiter", "rows", "splitRows", "header", "cell", "records", "row", "record", "key", "i", "numericCols", "resolveNumericColumns", "booleanCols", "resolveBooleanColumns", "out", "col", "raw", "parseData", "file", "_options", "numeric", "sawValue", "bool", "numericSet", "field", "inQuotes", "sawAnyField", "pushField", "pushRow", "ch", "generateList", "generator", "result", "i", "createRef", "current", "ref", "node", "SeedGenerator", "seed", "a", "b", "t", "UINT32_RANGE", "Random", "_Random", "from", "to", "size", "out", "i", "mean", "stdev", "z", "u", "v", "s", "mul", "time", "frequency", "f", "curve", "r1", "r2", "x", "h", "isSteppable", "x"]
7
- }