semiotic 3.8.6 → 3.8.8

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 (302) hide show
  1. package/CLAUDE.md +34 -8
  2. package/README.md +93 -56
  3. package/ai/behaviorContracts.cjs +86 -1
  4. package/ai/componentMetadata.cjs +4 -9
  5. package/ai/dist/mcp-server.js +125 -12
  6. package/ai/examples.md +154 -7
  7. package/ai/schema.json +1742 -156
  8. package/ai/surface-manifest.json +12 -10
  9. package/ai/system-prompt.md +9 -3
  10. package/dist/{chunk-chartContainerDataAudit-FEOD5GTQ.module.min.js → chunk-chartContainerDataAudit-IQ3NBN3Q.module.min.js} +1 -1
  11. package/dist/chunk-chunk-2B3AIKUZ.module.min.js +2 -0
  12. package/dist/chunk-chunk-2NVFEB7P.module.min.js +2 -0
  13. package/dist/chunk-chunk-3GCILWPB.module.min.js +2 -0
  14. package/dist/chunk-chunk-46KRGJQP.module.min.js +1 -0
  15. package/dist/{chunk-chunk-G7WFWHAD.module.min.js → chunk-chunk-4ITOQRXM.module.min.js} +1 -1
  16. package/dist/chunk-chunk-4MLLQUGW.module.min.js +2 -0
  17. package/dist/chunk-chunk-57RBPDBQ.module.min.js +2 -0
  18. package/dist/chunk-chunk-5VVNW5AZ.module.min.js +1 -0
  19. package/dist/chunk-chunk-66PCWJUG.module.min.js +1 -0
  20. package/dist/chunk-chunk-6V5VQVCT.module.min.js +2 -0
  21. package/dist/chunk-chunk-7LE56WAE.module.min.js +2 -0
  22. package/dist/chunk-chunk-7T25U75Z.module.min.js +2 -0
  23. package/dist/chunk-chunk-AF53TBSN.module.min.js +2 -0
  24. package/dist/chunk-chunk-BTZYH2IE.module.min.js +1 -0
  25. package/dist/chunk-chunk-BWV55BZK.module.min.js +2 -0
  26. package/dist/chunk-chunk-BZNOAHJV.module.min.js +2 -0
  27. package/dist/chunk-chunk-CD6PVVS3.module.min.js +2 -0
  28. package/dist/chunk-chunk-DTSNLGRK.module.min.js +2 -0
  29. package/dist/chunk-chunk-FC3NZWYR.module.min.js +2 -0
  30. package/dist/chunk-chunk-FEPXDKJP.module.min.js +1 -0
  31. package/dist/chunk-chunk-FJ76HWQZ.module.min.js +1 -0
  32. package/dist/chunk-chunk-FQPKOAIH.module.min.js +2 -0
  33. package/dist/chunk-chunk-FRGBMTZR.module.min.js +1 -0
  34. package/dist/chunk-chunk-G75OPF5N.module.min.js +2 -0
  35. package/dist/chunk-chunk-H5IFO6CU.module.min.js +2 -0
  36. package/dist/chunk-chunk-HADHLMY5.module.min.js +1 -0
  37. package/dist/chunk-chunk-HBFA4NN6.module.min.js +1 -0
  38. package/dist/chunk-chunk-HCNDE26Q.module.min.js +2 -0
  39. package/dist/chunk-chunk-J5QD4RAM.module.min.js +2 -0
  40. package/dist/chunk-chunk-JJ4BSUYL.module.min.js +2 -0
  41. package/dist/chunk-chunk-JRHXQGEV.module.min.js +2 -0
  42. package/dist/chunk-chunk-L6FFYGYS.module.min.js +1 -0
  43. package/dist/chunk-chunk-LJDH3WV3.module.min.js +2 -0
  44. package/dist/chunk-chunk-LSJUXBMF.module.min.js +1 -0
  45. package/dist/chunk-chunk-N3Q33XCB.module.min.js +2 -0
  46. package/dist/chunk-chunk-NWIGA3UK.module.min.js +1 -0
  47. package/dist/chunk-chunk-OG3TTJGJ.module.min.js +2 -0
  48. package/dist/{chunk-chunk-XEVJDUTH.module.min.js → chunk-chunk-OZK46A5U.module.min.js} +1 -1
  49. package/dist/chunk-chunk-PMR47KRY.module.min.js +2 -0
  50. package/dist/chunk-chunk-QQJNG23C.module.min.js +2 -0
  51. package/dist/chunk-chunk-RGJ6TKAH.module.min.js +2 -0
  52. package/dist/{chunk-chunk-RA7JCG7D.module.min.js → chunk-chunk-SFLUSZ73.module.min.js} +1 -1
  53. package/dist/chunk-chunk-SV4XAZ3Q.module.min.js +1 -0
  54. package/dist/chunk-chunk-TCMHJWFJ.module.min.js +1 -0
  55. package/dist/chunk-chunk-TSCFL235.module.min.js +1 -0
  56. package/dist/{chunk-chunk-XP3OHHFX.module.min.js → chunk-chunk-UEZ6SHW5.module.min.js} +1 -1
  57. package/dist/chunk-chunk-UOQRPGPK.module.min.js +2 -0
  58. package/dist/chunk-chunk-VUWYT7DY.module.min.js +2 -0
  59. package/dist/{chunk-chunk-GFTVACTO.module.min.js → chunk-chunk-W5HWGQMD.module.min.js} +1 -1
  60. package/dist/chunk-chunk-WFHZHWT7.module.min.js +1 -0
  61. package/dist/chunk-chunk-WGROBM3I.module.min.js +2 -0
  62. package/dist/chunk-chunk-WSDJFBKX.module.min.js +2 -0
  63. package/dist/chunk-statisticalOverlays-HMYYSGPE.module.min.js +2 -0
  64. package/dist/components/ai/SemioticVACPBridge.d.ts +22 -0
  65. package/dist/components/ai/chartCapabilities.d.ts +4 -3
  66. package/dist/components/ai/conversationArc.d.ts +2 -176
  67. package/dist/components/ai/conversationArcTypes.d.ts +202 -0
  68. package/dist/components/ai/readerGrounding.d.ts +12 -0
  69. package/dist/components/ai/vacpAdapter.d.ts +13 -0
  70. package/dist/components/ai/vacpAdapterActions.d.ts +2 -0
  71. package/dist/components/ai/vacpAdapterModel.d.ts +7 -0
  72. package/dist/components/ai/vacpAdapterRuntime.d.ts +26 -0
  73. package/dist/components/ai/vacpAdapterState.d.ts +3 -0
  74. package/dist/components/ai/vacpAdapterTypes.d.ts +169 -0
  75. package/dist/components/ai/vacpTypes.d.ts +160 -0
  76. package/dist/components/charts/index.d.ts +6 -6
  77. package/dist/components/charts/network/ProcessSankey.d.ts +105 -74
  78. package/dist/components/charts/network/processSankey/accessors.d.ts +7 -0
  79. package/dist/components/charts/network/processSankey/algorithm.d.ts +14 -193
  80. package/dist/components/charts/network/processSankey/axisChrome.d.ts +31 -0
  81. package/dist/components/charts/network/processSankey/bandPaths.d.ts +45 -0
  82. package/dist/components/charts/network/processSankey/buildScenes.d.ts +41 -3
  83. package/dist/components/charts/network/processSankey/fixtures.d.ts +17 -0
  84. package/dist/components/charts/network/processSankey/frameMargins.d.ts +11 -0
  85. package/dist/components/charts/network/processSankey/groupBonding.d.ts +13 -0
  86. package/dist/components/charts/network/processSankey/inventoryAtTime.d.ts +41 -0
  87. package/dist/components/charts/network/processSankey/labelPlacement.d.ts +34 -0
  88. package/dist/components/charts/network/processSankey/layoutGeometry.d.ts +47 -0
  89. package/dist/components/charts/network/processSankey/layoutOrchestrator.d.ts +44 -0
  90. package/dist/components/charts/network/processSankey/layoutQualityProduct.d.ts +27 -0
  91. package/dist/components/charts/network/processSankey/massSimulation.d.ts +16 -0
  92. package/dist/components/charts/network/processSankey/ordering.d.ts +55 -0
  93. package/dist/components/charts/network/processSankey/orderingBond.d.ts +33 -0
  94. package/dist/components/charts/network/processSankey/orientation.d.ts +5 -0
  95. package/dist/components/charts/network/processSankey/packing.d.ts +8 -0
  96. package/dist/components/charts/network/processSankey/packingCache.d.ts +23 -0
  97. package/dist/components/charts/network/processSankey/processSankeyLayoutAsync.d.ts +27 -0
  98. package/dist/components/charts/network/processSankey/processSankeyLayoutWorkerClient.d.ts +72 -0
  99. package/dist/components/charts/network/processSankey/processSankeyTooltip.d.ts +26 -0
  100. package/dist/components/charts/network/processSankey/processSankeyTypes.d.ts +163 -0
  101. package/dist/components/charts/network/processSankey/ribbonInputs.d.ts +26 -2
  102. package/dist/components/charts/network/processSankey/ribbonRunway.d.ts +45 -0
  103. package/dist/components/charts/network/processSankey/streamingLayout.d.ts +23 -0
  104. package/dist/components/charts/network/processSankey/time.d.ts +11 -0
  105. package/dist/components/charts/network/processSankey/useProcessSankeyPush.d.ts +29 -0
  106. package/dist/components/charts/network/processSankey/useProcessSankeyScenes.d.ts +26 -0
  107. package/dist/components/charts/network/processSankey/validation.d.ts +33 -0
  108. package/dist/components/charts/physics/ChainReactionChart.capability.d.ts +9 -0
  109. package/dist/components/charts/physics/ChainReactionChart.d.ts +29 -0
  110. package/dist/components/charts/physics/CollisionSwarmChart.d.ts +1 -1
  111. package/dist/components/charts/physics/EventDropChart.d.ts +7 -2
  112. package/dist/components/charts/physics/GaltonBoardChart.d.ts +1 -1
  113. package/dist/components/charts/physics/{PhysicsPileChart.capability.d.ts → PacketFlowChart.capability.d.ts} +1 -1
  114. package/dist/components/charts/physics/{PhysicalFlowChart.d.ts → PacketFlowChart.d.ts} +22 -6
  115. package/dist/components/charts/physics/PhysicsCustomChart.d.ts +1 -1
  116. package/dist/components/charts/physics/ProcessFlowChart.d.ts +7 -4
  117. package/dist/components/charts/physics/{PhysicalFlowChart.capability.d.ts → UnitPileChart.capability.d.ts} +1 -1
  118. package/dist/components/charts/physics/{PhysicsPileChart.d.ts → UnitPileChart.d.ts} +19 -6
  119. package/dist/components/charts/physics/crucibleChartProps.d.ts +1 -1
  120. package/dist/components/charts/physics/crucibleChartUtils.d.ts +9 -0
  121. package/dist/components/charts/physics/gauntletChartProps.d.ts +6 -1
  122. package/dist/components/charts/physics/gauntletTerminal.d.ts +61 -0
  123. package/dist/components/charts/physics/packetFlowSemantics.d.ts +6 -0
  124. package/dist/components/charts/physics/physicsHocUtils.d.ts +45 -2
  125. package/dist/components/charts/shared/auditAccessibilityStyles.d.ts +9 -0
  126. package/dist/components/charts/shared/chartFamilySets.d.ts +1 -0
  127. package/dist/components/charts/shared/formatUtils.d.ts +12 -1
  128. package/dist/components/charts/shared/hatchFill.d.ts +2 -0
  129. package/dist/components/charts/shared/hooks.d.ts +1 -1
  130. package/dist/components/charts/shared/knownChartComponents.d.ts +1 -1
  131. package/dist/components/charts/shared/leastSquaresRegression.d.ts +31 -0
  132. package/dist/components/charts/shared/styleRules.d.ts +5 -1
  133. package/dist/components/charts/shared/useChartLegend.d.ts +14 -1
  134. package/dist/components/charts/shared/useChartSetup.d.ts +8 -1
  135. package/dist/components/charts/shared/validateProps.d.ts +2 -2
  136. package/dist/components/charts/shared/withChartWrapper.d.ts +0 -6
  137. package/dist/components/data/numericFieldProfiler.d.ts +2 -0
  138. package/dist/components/data/portability/capabilityBinding.d.ts +41 -0
  139. package/dist/components/data/portability/index.d.ts +2 -0
  140. package/dist/components/legendLayout.d.ts +56 -0
  141. package/dist/components/recipes/geographicDotGrid.d.ts +82 -0
  142. package/dist/components/recipes/geographicGrid.d.ts +100 -0
  143. package/dist/components/recipes/layout1d.d.ts +68 -0
  144. package/dist/components/recipes/physics.d.ts +2 -0
  145. package/dist/components/recipes/physicsStageGeography.d.ts +137 -0
  146. package/dist/components/semiotic-ai.d.ts +4 -3
  147. package/dist/components/semiotic-experimental-vacp.d.ts +11 -0
  148. package/dist/components/semiotic-experimental.d.ts +6 -3
  149. package/dist/components/semiotic-geo.d.ts +4 -0
  150. package/dist/components/semiotic-network.d.ts +2 -2
  151. package/dist/components/semiotic-physics.d.ts +9 -6
  152. package/dist/components/semiotic-recipes-core.d.ts +8 -1
  153. package/dist/components/semiotic.d.ts +2 -0
  154. package/dist/components/server/renderEvidence.d.ts +1 -1
  155. package/dist/components/server/renderToStaticSVG.d.ts +2 -1
  156. package/dist/components/server/serverChartConfigHeatmap.d.ts +6 -0
  157. package/dist/components/server/serverChartConfigNetworkStyles.d.ts +12 -0
  158. package/dist/components/server/serverChartConfigShared.d.ts +16 -0
  159. package/dist/components/server/serverChartConfigs.d.ts +2 -2
  160. package/dist/components/server/serverChartConfigsPhysics.d.ts +2 -2
  161. package/dist/components/server/serverChartConfigsXY.d.ts +0 -1
  162. package/dist/components/server/staticLegend.d.ts +6 -0
  163. package/dist/components/server/staticSVGChrome.d.ts +12 -3
  164. package/dist/components/server/staticValue.d.ts +8 -0
  165. package/dist/components/store/createStore.d.ts +2 -0
  166. package/dist/components/stream/OrdinalPipelineStore.d.ts +3 -0
  167. package/dist/components/stream/PipelineStore.d.ts +5 -0
  168. package/dist/components/stream/accessorUtils.d.ts +21 -0
  169. package/dist/components/stream/frameKeyboardNavigation.d.ts +3 -2
  170. package/dist/components/stream/geoPipelineConfig.d.ts +10 -0
  171. package/dist/components/stream/layouts/forceLayoutWorkerClient.d.ts +3 -8
  172. package/dist/components/stream/layouts/index.d.ts +1 -1
  173. package/dist/components/stream/legendRenderer.d.ts +8 -0
  174. package/dist/components/stream/moduleWorkerSession.d.ts +67 -0
  175. package/dist/components/stream/networkTypes.d.ts +2 -0
  176. package/dist/components/stream/ordinalSceneBuilders/sceneBuilderMap.d.ts +2 -1
  177. package/dist/components/stream/physics/PhysicsEvidence.d.ts +37 -0
  178. package/dist/components/stream/physics/PhysicsKernel.d.ts +9 -0
  179. package/dist/components/stream/physics/PhysicsPipelineStore.d.ts +9 -0
  180. package/dist/components/stream/physics/PhysicsSettledScene.d.ts +5 -0
  181. package/dist/components/stream/physics/physicsFramePipelineConfig.d.ts +19 -0
  182. package/dist/components/stream/physics/physicsPipelineSettle.d.ts +52 -0
  183. package/dist/components/stream/physics/physicsRegionRuntime.d.ts +23 -0
  184. package/dist/components/stream/pipelineIntroCancellation.d.ts +6 -0
  185. package/dist/components/stream/pipelineTransitions.d.ts +15 -1
  186. package/dist/components/stream/renderers/canvasRenderHelpers.d.ts +16 -4
  187. package/dist/components/stream/renderers/symbolCanvasRenderer.d.ts +4 -0
  188. package/dist/components/stream/symbolPath.d.ts +8 -0
  189. package/dist/components/stream/types.d.ts +4 -0
  190. package/dist/components/stream/useCanvasFrameHost.d.ts +6 -0
  191. package/dist/components/stream/useSemanticFrameInteractions.d.ts +12 -3
  192. package/dist/components/stream/xyFrameAxisTypes.d.ts +4 -0
  193. package/dist/components/types/legendTypes.d.ts +17 -1
  194. package/dist/controls.min.js +1 -1
  195. package/dist/controls.module.min.js +1 -1
  196. package/dist/forceLayoutWorker.js +1 -1
  197. package/dist/geo.min.js +1 -1
  198. package/dist/geo.module.min.js +1 -1
  199. package/dist/network.min.js +1 -1
  200. package/dist/network.module.min.js +1 -1
  201. package/dist/ordinal.min.js +1 -1
  202. package/dist/ordinal.module.min.js +1 -1
  203. package/dist/physics.min.js +1 -1
  204. package/dist/physics.module.min.js +1 -1
  205. package/dist/physicsWorker.js +1 -1
  206. package/dist/processSankeyLayoutWorker.js +1 -0
  207. package/dist/realtime.min.js +1 -1
  208. package/dist/realtime.module.min.js +1 -1
  209. package/dist/semiotic-ai-core.min.js +1 -1
  210. package/dist/semiotic-ai-core.module.min.js +1 -1
  211. package/dist/semiotic-ai.d.ts +4 -3
  212. package/dist/semiotic-ai.min.js +1 -1
  213. package/dist/semiotic-ai.module.min.js +1 -1
  214. package/dist/semiotic-data.module.min.js +1 -1
  215. package/dist/semiotic-experimental-vacp.d.ts +11 -0
  216. package/dist/semiotic-experimental-vacp.min.js +1 -0
  217. package/dist/semiotic-experimental-vacp.module.min.js +1 -0
  218. package/dist/semiotic-experimental.d.ts +6 -3
  219. package/dist/semiotic-experimental.min.js +2 -1
  220. package/dist/semiotic-experimental.module.min.js +2 -1
  221. package/dist/semiotic-geo.d.ts +4 -0
  222. package/dist/semiotic-network.d.ts +2 -2
  223. package/dist/semiotic-physics.d.ts +9 -6
  224. package/dist/semiotic-realtime-core.min.js +1 -1
  225. package/dist/semiotic-realtime-core.module.min.js +1 -1
  226. package/dist/semiotic-recipes-core.d.ts +8 -1
  227. package/dist/semiotic-recipes-core.min.js +1 -1
  228. package/dist/semiotic-recipes-core.module.min.js +1 -1
  229. package/dist/semiotic-recipes.min.js +1 -1
  230. package/dist/semiotic-recipes.module.min.js +1 -1
  231. package/dist/semiotic-server-edge.min.js +1 -1
  232. package/dist/semiotic-server-edge.module.min.js +1 -1
  233. package/dist/semiotic-server-node.min.js +1 -1
  234. package/dist/semiotic-server-node.module.min.js +1 -1
  235. package/dist/semiotic-themes-core.module.min.js +1 -1
  236. package/dist/semiotic-themes-react.module.min.js +1 -1
  237. package/dist/semiotic-themes.module.min.js +1 -1
  238. package/dist/semiotic-utils-core.min.js +1 -1
  239. package/dist/semiotic-utils-core.module.min.js +1 -1
  240. package/dist/semiotic-utils-react.module.min.js +1 -1
  241. package/dist/semiotic-utils.min.js +1 -1
  242. package/dist/semiotic-utils.module.min.js +1 -1
  243. package/dist/semiotic-value.min.js +1 -1
  244. package/dist/semiotic-value.module.min.js +1 -1
  245. package/dist/semiotic.d.ts +2 -0
  246. package/dist/semiotic.min.js +1 -1
  247. package/dist/semiotic.module.min.js +1 -1
  248. package/dist/server.min.js +1 -1
  249. package/dist/server.module.min.js +1 -1
  250. package/dist/xy.min.js +1 -1
  251. package/dist/xy.module.min.js +1 -1
  252. package/package.json +21 -4
  253. package/spec/README.md +94 -2
  254. package/spec/bindings/README.md +14 -3
  255. package/spec/v0.1/examples/annotation-provenance-reviewed-revision.json +27 -0
  256. package/spec/v0.1/examples/annotation-provenance-watcher-threshold.json +21 -0
  257. package/spec/v0.1/examples/audience-profile-executive-review.json +24 -0
  258. package/spec/v0.1/examples/audience-profile-incident-operators.json +42 -0
  259. package/spec/v0.1/examples/chart-capability-bar-comparison.json +48 -0
  260. package/spec/v0.1/examples/chart-capability-service-flow.json +54 -0
  261. package/dist/chunk-chunk-2CHN2TA3.module.min.js +0 -1
  262. package/dist/chunk-chunk-3NGIKFD6.module.min.js +0 -1
  263. package/dist/chunk-chunk-3SHB24AG.module.min.js +0 -1
  264. package/dist/chunk-chunk-4MMOOYTX.module.min.js +0 -2
  265. package/dist/chunk-chunk-5RKXZQ2P.module.min.js +0 -1
  266. package/dist/chunk-chunk-75OTQSXS.module.min.js +0 -1
  267. package/dist/chunk-chunk-7ALTGHK6.module.min.js +0 -1
  268. package/dist/chunk-chunk-A5GRQUOF.module.min.js +0 -1
  269. package/dist/chunk-chunk-AAF5LZAU.module.min.js +0 -2
  270. package/dist/chunk-chunk-ARZGA4LJ.module.min.js +0 -2
  271. package/dist/chunk-chunk-C4YA6TDR.module.min.js +0 -1
  272. package/dist/chunk-chunk-CAFLML4L.module.min.js +0 -2
  273. package/dist/chunk-chunk-CO5KQMGH.module.min.js +0 -1
  274. package/dist/chunk-chunk-DSNGDNJY.module.min.js +0 -1
  275. package/dist/chunk-chunk-FHBN7OEB.module.min.js +0 -2
  276. package/dist/chunk-chunk-GMQ5AYTD.module.min.js +0 -1
  277. package/dist/chunk-chunk-IP2UE74X.module.min.js +0 -1
  278. package/dist/chunk-chunk-ITDWLZXV.module.min.js +0 -2
  279. package/dist/chunk-chunk-JCG72SGW.module.min.js +0 -2
  280. package/dist/chunk-chunk-LPSPATPC.module.min.js +0 -1
  281. package/dist/chunk-chunk-OM6NWS4H.module.min.js +0 -2
  282. package/dist/chunk-chunk-PRDGLMJT.module.min.js +0 -2
  283. package/dist/chunk-chunk-PX5YQGDP.module.min.js +0 -2
  284. package/dist/chunk-chunk-Q2BS46W2.module.min.js +0 -2
  285. package/dist/chunk-chunk-QSQVBIJA.module.min.js +0 -1
  286. package/dist/chunk-chunk-RCF52Z42.module.min.js +0 -2
  287. package/dist/chunk-chunk-RNUHEXZA.module.min.js +0 -2
  288. package/dist/chunk-chunk-ROZWKEUG.module.min.js +0 -1
  289. package/dist/chunk-chunk-SMVD3EQJ.module.min.js +0 -2
  290. package/dist/chunk-chunk-T2FKJD4O.module.min.js +0 -2
  291. package/dist/chunk-chunk-UDREYOLV.module.min.js +0 -1
  292. package/dist/chunk-chunk-VOWE3SAP.module.min.js +0 -2
  293. package/dist/chunk-chunk-VQPNBUSW.module.min.js +0 -2
  294. package/dist/chunk-chunk-WAWCIHFJ.module.min.js +0 -1
  295. package/dist/chunk-chunk-WCX6U47H.module.min.js +0 -2
  296. package/dist/chunk-chunk-WYARAXHR.module.min.js +0 -2
  297. package/dist/chunk-chunk-XV3KGYTR.module.min.js +0 -2
  298. package/dist/chunk-chunk-YC2IVEPX.module.min.js +0 -1
  299. package/dist/chunk-chunk-ZOAQDIJO.module.min.js +0 -1
  300. package/dist/chunk-chunk-ZXIXAPRE.module.min.js +0 -2
  301. package/dist/chunk-statisticalOverlays-6MVAK5RW.module.min.js +0 -2
  302. package/dist/components/stream/renderers/networkSymbolRenderer.d.ts +0 -2
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{createProcessJourneyLedger as e,processJourneyRows as t,updateProcessJourney as n}from"./chunk-chunk-YWZB3KPI.module.min.js";import{BuiltInPhysicsEngineAdapter as s,CollisionSwarmChart as i,CrucibleChart as o,DEFAULT_CRUCIBLE_HEIGHT as r,DEFAULT_CRUCIBLE_OUTLETS as a,DEFAULT_CRUCIBLE_SIZE as c,DEFAULT_CRUCIBLE_WIDTH as l,EventDropChart as d,GaltonBoardChart as u,GauntletChart as h,GuantletChart as m,PhysicalFlowChart as p,PhysicsCustomChart as f,PhysicsPileChart as g,PhysicsPipelineStore as y,PhysicsSVGOverlay as k,PhysicsSedimentAccumulator as x,ProcessFlowChart as b,StreamPhysicsFrame as v,StreamPhysicsFrame_default as w,absorbRegion as I,aggregateRegionCounts as D,applyCrucibleEvent as M,bodiesToAnnotationAnchors as A,bodyGroupSpec as T,buildCollisionSwarmPhysics as S,buildCrucibleEvidence as C,buildCrucibleInitialSpawns as $,buildCrucibleLayout as E,buildCruciblePhysicsConfig as N,buildCrucibleProductEvents as j,buildCrucibleProjection as R,buildCrucibleStateSpawns as P,buildCrucibleTerminalSpawns as W,buildEventDropPhysics as B,buildGaltonBoardPhysics as F,buildPhysicalFlowPhysics as L,buildPhysicsAnnotationContext as q,buildPhysicsPile as O,buildProcessFlowPhysics as z,capacitatedRegion as H,chargeGateRegion as U,cloneCrucibleState as X,collidersFromPlotBounds as Y,collidersFromXScaleBins as G,compileCruciblePlan as J,composePhysicsControllers as Z,createCapacityQueueController as K,createDefaultPhysicsEngineAdapter as Q,createDependencyGateController as V,createInitialCrucibleState as _,createPortalController as ee,createServiceLevelController as te,createServiceResourcePoolController as ne,crucibleBondId as se,crucibleBoundaryColliders as ie,crucibleComponentBodyId as oe,crucibleProductBodyId as re,crucibleProjectionRows as ae,crucibleSemanticKey as ce,evaluateCrucibleConservation as le,evaluatePhysicsBodyBudget as de,forceFieldRegion as ue,groupCompletionRows as he,membraneRegion as me,normalizePhysicsAnnotations as pe,physicsProcessBoundaryColliders as fe,physicsProcessGroupSemanticItems as ge,physicsProcessRegionSemanticItem as ye,physicsProcessStageSemanticItems as ke,planGauntletPropertyWork as xe,portalRegion as be,pressureFieldRegion as ve,processChrome as we,processLaneWalls as Ie,processStageLayout as De,processStageRegions as Me,processVolumePolygons as Ae,regionCountsToProjectionRows as Te,replaceGauntletNegative as Se,replayCruciblePlan as Ce,resolveCrucibleSelector as $e,resolveCrucibleSnapshotAt as Ee,resolveCrucibleTime as Ne,routeSurfaceRegion as je,sedimentHeightfield as Re,stageTargetInVolume as Pe}from"./chunk-chunk-CAFLML4L.module.min.js";import{mulberry32 as We}from"./chunk-chunk-SIRIJ3DY.module.min.js";import{composeStyleRules as Be,makeRuleValueResolver as Fe,matchesThreshold as Le,resolveStyleRules as qe,ruleMatches as Oe}from"./chunk-chunk-EMO5NUGE.module.min.js";import"./chunk-chunk-SV4XAZ3Q.module.min.js";import"./chunk-chunk-RA7JCG7D.module.min.js";import{compileMotionEncoding as ze,deriveMotionVector as He,hatchFillId as Ue,hatchPatternDef as Xe,isHatchFill as Ye,opacityFromAge as Ge,resolveMotionAccessor as Je,resolveMotionAge as Ze,resolveMotionVector as Ke,resolveSvgFill as Qe}from"./chunk-chunk-PX5YQGDP.module.min.js";import"./chunk-chunk-JJ2OOIET.module.min.js";import"./chunk-chunk-WCX6U47H.module.min.js";import"./chunk-chunk-KTWEBFMX.module.min.js";import"./chunk-chunk-ACLDBMRH.module.min.js";import"./chunk-chunk-YHNZCPOZ.module.min.js";function Ve(e){const{data:t,encoding:n,defaults:s={},scales:i}=e,o=ze({data:t,encoding:n}),r=[],a=new Map,c=[],l=[],d=new Map;return o.rows.forEach((e,t)=>{const{id:o,datum:u}=e,h=Math.max(0,Je(n.appearance?.size,u,t)??s.size??6),m=Je(n.appearance?.shape,u,t)??s.shape??{type:"circle",radius:h},p=e.placement.x??s.x??0,f=e.placement.y??s.y??0,g=i?.x?i.x(p):p,y=i?.y?i.y(f):f,k=Je(n.appearance?.color,u,t)??s.color,x=Je(n.appearance?.opacity,u,t)??s.opacity,b=Je(n.appearance?.stroke,u,t)??s.stroke,v=Je(n.appearance?.strokeWidth,u,t)??s.strokeWidth,w=Je(n.time?.spawnAt,u,t)??e.time.arrival,I=e.kinematics.velocityX,D=e.kinematics.velocityY,M=Je(n.dynamics?.mass,u,t)??s.mass??1,A=Je(n.dynamics?.friction,u,t),T=Je(n.dynamics?.restitution,u,t),S=Je(n.dynamics?.bodyCollisions,u,t),C={id:o,x:g,y:y,mass:M,shape:{...m},datum:u,...null!=w&&{spawnAt:w},...null!=I&&{vx:I},...null!=D&&{vy:D},...null!=A&&{friction:A},...null!=T&&{restitution:T},...null!=S&&{bodyCollisions:S}},$={...null!=k&&{fill:k},...null!=x&&{opacity:x},...null!=b&&{stroke:b},...null!=v&&{strokeWidth:v}},E={id:o,datum:u,appearance:{color:k,opacity:x,shape:m,size:h,stroke:b,strokeWidth:v},placement:{x:g,y:y,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:w,spawnAt:w,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:I,velocityY:D,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:S,friction:A,mass:M,restitution:T},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:C};r.push(E),a.set(o,E),c.push(C),d.set(o,$),l.push({id:o,bodyId:o,label:e.accessible.label,description:e.accessible.description,datum:u,x:g,y:y,group:e.accessible.group})}),{rows:r,byId:a,spawns:c,semanticItems:l,bodyStyle:e=>d.get(e.id)??{}}}function _e(e){return t=>{const n=Ve({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),s=e.extend?.(t,n)??{};return{...s,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...s.semanticItems??[]]}}}var et=[.1,.5,.9],tt=1e6;function nt(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function st(e,t,n,s,i){return"function"==typeof s?s(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,s??i)}function it(e){const t=Number(e.toFixed(12));return Object.is(t,-0)?0:t}function ot(e,t,n,s){const i=e.flatMap((e,i)=>{const o=nt(st(e,i,t,n,"time")),r=nt(st(e,i,t,s,"value"));return null==o||null==r?[]:[{time:it(o),value:r,index:i}]});i.sort((e,t)=>e.time-t.time||e.index-t.index);const o=[];for(const e of i){const t=o[o.length-1];t?.time===e.time?t.value=e.value:o.push({time:e.time,value:e.value})}return o}function rt(e,t,n,s){if(!e.length)return null;const i=e[0],o=e[e.length-1];if(i.time>t)return"clamp"===s?i.value:null;if(t>o.time)return"clamp"===s?o.value:null;const r=function(e,t){let n=0,s=e.length;for(;s>n;){const i=n+s>>>1;t>e[i].time?n=i+1:s=i}return n}(e,t),a=e[r];if(a?.time===t)return a.value;const c=e[Math.max(0,r-1)];return"step"!==n&&a&&a.time!==c.time?c.value+(t-c.time)/(a.time-c.time)*(a.value-c.value):c.value}function at(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,s=Math.floor(n),i=Math.ceil(n);return s===i?e[s]:e[s]+(e[i]-e[s])*(n-s)}function ct(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",s=function(e){const t=(e??et).map(e=>{const t=nt(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return it(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),i=function(e){if(Array.isArray(e)){if(e.length>tt)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(e.map(nt).filter(e=>null!=e).map(it))).sort((e,t)=>e-t)}const t=e,n=nt(t.start),s=nt(t.end),i=nt(t.step);if(null==n||null==s||null==i||0>=i||n>s)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const o=Math.floor((s-n)/i)+1;if(o>tt)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");const r=[],a=1e-10*Math.max(1,Math.abs(s),Math.abs(n));for(let e=0;o>e;e+=1){const t=n+e*i;if(t>s+a)break;r.push(it(Math.min(t,s)))}if(r.length&&a>=Math.abs(r[r.length-1]-s)||r.push(it(s)),r.length>tt)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(r)).sort((e,t)=>e-t)}(e.sampleAt),o=e.runs.map(t=>ot(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:i.map(e=>{const i=o.map(s=>rt(s,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),r={};for(const e of s)r[e]=i.length?at(i,e):null;return{time:e,count:i.length,min:i.length?i[0]:null,max:i.length?i[i.length-1]:null,median:i.length?at(i,.5):null,quantiles:r}}),quantiles:s,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function lt(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function dt(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=nt(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const s=it(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,s))throw Error(`comparePhysicsTrace could not find quantile ${s} in the reference envelope`);return e.quantiles[s]??null}function ut(e,t,n){return t>e?"below":e>n?"above":"inside"}function ht(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const s=e.value-e.lower,i=t.value-t.lower,o=e.value-e.upper,r=t.value-t.upper,a=[0,1];for(const[e,t]of[[s,i],[o,r]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let c=0,l=0,d=0;for(let s=0;a.length-1>s;s+=1){const i=a[s],o=a[s+1];if(i>=o)continue;const r=(i+o)/2,u=(o-i)*n,h=ut(e.value+(t.value-e.value)*r,e.lower+(t.lower-e.lower)*r,e.upper+(t.upper-e.upper)*r);"below"===h?c+=u:"above"===h?d+=u:l+=u}return{below:c,inside:l,above:d,observed:n}}function mt(e,t,n={}){const s=n.interpolation??t.interpolation,i=n.outsideDomain??t.outsideDomain,o=ot(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),r=n.lower??lt(t,"lower"),a=n.upper??lt(t,"upper"),c=t.points.map(e=>{const t=rt(o,e.time,s,i),n=dt(e,r),c=dt(e,a);if(null!=n&&null!=c&&n>c)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:c,status:null==t||null==n||null==c?"unobserved":ut(t,n,c)}});let l=0,d=0,u=0,h=0,m=null,p=0,f=null;for(const e of c){if("below"===e.status?l+=1:"inside"===e.status?d+=1:"above"===e.status&&(u+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,m=e.time),n>p&&(p=n,f=e.time)}let g=0,y=0,k=0,x=0;for(let e=0;c.length-1>e;e+=1){const t=c[e],n=c[e+1],i=Math.max(0,n.time-t.time);if(i>0){if("linear"===s){const e=ht(t,n);g+=e.below,y+=e.inside,k+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=i,"below"===t.status?g+=i:"above"===t.status?k+=i:y+=i)}}const b=c[0]?.time,v=c[c.length-1]?.time,w=null==b||null==v?0:Math.max(0,v-b);return{points:c,sampleCount:c.length,observedSamples:l+d+u,belowSamples:l,insideSamples:d,aboveSamples:u,totalDuration:w,observedDuration:x,unobservedDuration:Math.max(0,w-x),belowDuration:g,insideDuration:y,aboveDuration:k,peakExcess:h,peakExcessAt:m,peakDeficit:p,peakDeficitAt:f}}function pt(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function ft(e,t,n,s){const i="function"==typeof e?e(t,n):e;return Number.isFinite(i)?Number(i):s}function gt(e,t,n){return pt(e[t])??n}function yt(e,t){return"number"==typeof e?e:e?.[t]??0}function kt(e){const{band:t,idPrefix:n,plot:s,projection:i}=e,{includeBoundaryWalls:o=!0,includeInteriorWalls:r=!0,wallThickness:a=4}=t,c=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const s of e.values){const i=e.scale(s);Number.isFinite(i)&&(n.add(Number(i)),n.add(Number(i)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>c.length)return[];const l=o?c.length-1:c.length-2,d=[];for(let e=o?0:1;l>=e;e+=1){if(!r&&e>0&&c.length-1>e)continue;const t=c[e];d.push({id:`${n}-wall-${e}`,shape:"x"===i?{type:"aabb",x:t,y:s.y+s.height/2,width:a,height:s.height}:{type:"aabb",x:s.x+s.width/2,y:t,width:s.width,height:a}})}return d}function xt(e){const{plot:t,idPrefix:n="physics-scale",bounds:s={},xBins:i,xBands:o,yBands:r}=e,a=[];if(!1!==s&&a.push(...Y(t,{idPrefix:n,...s})),i){const{idPrefix:e,yTop:s,yBottom:o,...r}=i;a.push(...G({...r,idPrefix:e??n+"-xbin",yTop:s??t.y,yBottom:o??t.y+t.height}))}return o&&a.push(...kt({band:o,idPrefix:o.idPrefix??n+"-xband",plot:t,projection:"x"})),r&&a.push(...kt({band:r,idPrefix:r.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function bt(e){const{plot:t,rows:n,columns:s=n+1,pegRadius:i=3,idPrefix:o="galton-peg",yStart:r=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:c=!0,restitution:l=.2,friction:d=.04}=e,u=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(s));if(0===u)return[];const m=u>1?(a-r)/(u-1):0,p=t.width/h,f=[];for(let e=0;u>e;e+=1){const n=c&&e%2==1?p/2:0;for(let s=0;h>s;s+=1){const a=t.x+p*(s+.5)+n;t.x+i>a||a>t.x+t.width-i||f.push({id:`${o}-${e}-${s}`,shape:{type:"aabb",x:a,y:r+e*m,width:2*i,height:2*i},restitution:l,friction:d})}}return f}function vt(e,t={}){const{idPrefix:n="physics-token",radius:s=5,shape:i,mass:o,vx:r,vy:a,spawnAt:c,seed:l=1,jitter:d,datum:u}=t,h=We(l),m=yt(d,"x"),p=yt(d,"y");return e.map((e,l)=>{const d=ft(t.x,e,l,gt(e,"x",0)),f=ft(t.y,e,l,gt(e,"y",0)),g=ft(s,e,l,5),y="function"==typeof i?i(e,l):i??{type:"circle",radius:g};return{id:`${n}-${e.index??l}`,x:d+(h()-.5)*m,y:f+(h()-.5)*p,vx:ft(r,e,l,0),vy:ft(a,e,l,0),mass:ft(o,e,l,1),spawnAt:ft(c,e,l,void 0),shape:y,datum:u?u(e,l):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function wt(e,t={}){const{idPrefix:n="sediment",collider:s=!0,colliderThickness:i=1,restitution:o=.05,friction:r=.2,...a}=t,c=Re(e,a),l=s?c.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+i/2,width:e.width,height:i},restitution:o,friction:r})):[];return{columns:c,colliders:l}}function It(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:s=1,startAt:i=0,rebase:o=!0,sort:r=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return pt("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),c=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:i+(o?t-c:t)})).sort((e,t)=>r?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:i,timeAccessor:"spawnAt",timeScale:s}}}import{forwardRef as Dt,useCallback as Mt,useEffect as At,useImperativeHandle as Tt,useMemo as St,useRef as Ct,useState as $t}from"react";function Et(e,t,n={}){const s=new Set,i=[...e.get(t)??[]];let o=0;for(;i.length>o;){const t=i[o];if(o+=1,!s.has(t)){s.add(t);for(const n of e.get(t)??[])i.push(n)}}return n.includeStart&&s.add(t),s}function Nt(e,t,n){return Je(n,e,t)}function jt(e,t){return t>e?-1:e>t?1:0}function Rt(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Pt(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function Wt(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function Bt(e){const t=[],n=new Map,s=[],i=new Set;e.data.forEach((o,r)=>{const a=(Nt(o,r,e.taskIDAccessor)??"")+"";if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${r} has an empty id.`,taskIDs:[]});if(n.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});const c=(Nt(o,r,e.laneAccessor)??"Unassigned")+"";i.has(c)||(i.add(c),s.push(c));const l=Nt(o,r,e.dependencyAccessor)??[],d=Array.from(new Set(Array.from(l,e=>e+""))).sort(jt),u=Nt(o,r,e.blockerAccessor),h=Nt(o,r,e.statusAccessor)??(u?"blocked":"waiting");n.set(a,{id:a,label:(Nt(o,r,e.labelAccessor)??a)+"",lane:c,laneIndex:0,level:0,index:r,datum:o,dependencyIDs:d,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:Nt(o,r,e.startAccessor),end:Nt(o,r,e.endAccessor),progress:Wt(Nt(o,r,e.progressAccessor)),status:h,completionTime:Nt(o,r,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!Nt(o,r,e.milestoneAccessor)})});const o=e.laneOrder?[...e.laneOrder,...s.filter(t=>!e.laneOrder?.includes(t))]:s,r=new Map(o.map((e,t)=>[e,t]));for(const e of n.values())e.laneIndex=r.get(e.lane)??0;const a=new Map,c=new Map;for(const e of n.keys())a.set(e,[]),c.set(e,[]);const l=[],d=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of d)e.dependencyIDs.forEach((s,i)=>{const o=n.get(s);if(!o)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${s}".`,taskIDs:[e.id,s]});const r={id:Rt(s,e.id),sourceID:s,targetID:e.id,sourceIndex:o.index,targetIndex:e.index,socketID:Pt(e.id,i),socketIndex:i};l.push(r),a.get(e.id)?.push(r),c.get(s)?.push(r),e.incomingEdgeIDs.push(r.id),e.socketIDs.push(r.socketID),o.outgoingEdgeIDs.push(r.id)});for(const e of a.values())e.sort((e,t)=>jt(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=Pt(e.targetID,t)});for(const e of c.values())e.sort((e,t)=>jt(e.targetID,t.targetID));for(const e of n.values()){const t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(c.get(e.id)??[]).map(e=>e.id)}const u=new Map,h=new Map;for(const e of n.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);const m=[...n.keys()].filter(e=>0===u.get(e)).sort(jt);let p=0;for(;m.length;){const e=m.shift();p+=1;for(const t of c.get(e)??[]){const n=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,n);const s=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,s),0===s){const e=m.findIndex(e=>e>t.targetID);0>e?m.push(t.targetID):m.splice(e,0,t.targetID)}}}if(p!==n.size){const e=[...n.keys()].filter(e=>(u.get(e)??0)>0).sort(jt);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let f=0;const g=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of g)e.level=h.get(e.id)??0,f=Math.max(f,e.level);return{nodes:g,edges:l,byID:n,incoming:a,outgoing:c,lanes:o,maxLevel:f,diagnostics:t,valid:0===t.length}}function Ft(e,t,n={}){const s=Math.max(240,t.width),i=Math.max(220,t.height),o=t.paddingX??48,r=t.paddingTop??48,a=t.paddingBottom??44,c=Math.max(70,(s-2*o)/Math.max(1,e.lanes.length)),l=Math.max(76,(i-r-a)/Math.max(1,e.maxLevel+1)),d=Math.min(n.taskWidth??112,Math.max(58,.78*c)),u=Math.min(n.taskHeight??58,.64*l),h=n.socketRadius??5,m=Math.max(1,Math.round(n.gutterCount??3)),p=new Map;for(const t of e.nodes){const e=`${t.laneIndex}:${t.level}`,n=p.get(e)??[];n.push(t),p.set(e,n)}for(const e of p.values())e.sort((e,t)=>jt(e.id,t.id));const f=e.nodes.map(e=>{const t=p.get(`${e.laneIndex}:${e.level}`)??[e],n=Math.max(0,t.findIndex(t=>t.id===e.id));return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:o+c*(e.laneIndex+.5),y:r+l*(e.level+.5)+(n-(t.length-1)/2)*Math.min(18,.3*u),width:d,height:u}}),g=new Map(f.map(e=>[e.taskID,e])),y=[],k=[];e.edges.forEach((t,n)=>{const s=g.get(t.sourceID),i=g.get(t.targetID);if(!s||!i)return;const o=e.incoming.get(t.targetID)??[],r=Math.min(.72*i.width,14*Math.max(1,o.length-1)),a=o.length>1?i.x-r/2+r*t.socketIndex/(o.length-1):i.x,c=i.y-i.height/2-h-2;y.push({id:t.socketID,edgeID:t.id,taskID:i.taskID,index:t.socketIndex,x:a,y:c,radius:h});const l={x:s.x,y:s.y+s.height/2+3},d=Math.min(c-10,l.y+.48*Math.max(18,c-l.y)+7*(n%m-(m-1)/2));var u;k.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:(u=[l,{x:l.x,y:d},{x:a,y:d},{x:a,y:c}],u.filter((e,t)=>{const n=u[t-1];return!n||n.x!==e.x||n.y!==e.y}))})});const x=new Map(y.map(e=>[e.id,e])),b=new Map(k.map(e=>[e.edgeID,e]));return{tasks:f,sockets:y,routes:k,taskByID:g,socketByID:x,routeByEdgeID:b}}function Lt(e,t,n="all"){const s=Array.from(new Set(t)).sort(jt),i=new Set,o=()=>s.every(e=>i.has(e));return{taskID:e,mode:n,incomingEdgeIDs:s,deliver:e=>s.includes(e)?(i.add(e),o()):o(),reset:(e=[])=>{i.clear();for(const t of e)s.includes(t)&&i.add(t)},isSatisfied:o,getSnapshot:()=>({taskID:e,mode:n,incomingEdgeIDs:[...s],deliveredEdgeIDs:[...i].sort(jt),satisfied:o()})}}function qt(e){return e instanceof Date?e.getTime():Number(e)}function Ot(e,t){const n=qt("object"!=typeof t||t instanceof Date?t:t.currentTime),s=e.map((e,t)=>({event:e,index:t,time:qt(e.at)})).filter(e=>Number.isFinite(e.time)&&n>=e.time).sort((e,t)=>e.time-t.time||e.index-t.index),i=new Set,o=new Map,r=new Set,a=new Set;for(const{event:e}of s)"task-completed"===e.type?(i.add(e.taskID),o.delete(e.taskID)):"task-blocked"===e.type?o.set(e.taskID,e.reason):"task-unblocked"===e.type?o.delete(e.taskID):"dependency-delivered"===e.type?r.add(e.edgeID):"task-armed"===e.type&&a.add(e.taskID);return{currentTime:n,appliedEvents:s.map(e=>e.event),completedTaskIDs:i,blockedByTaskID:o,deliveredEdgeIDs:r,armedTaskIDs:a}}function zt(e,t,n={}){const s=new Set(n.completedTaskIDs??[]),i=[...Et(function(e,t){const n=new Map;for(const t of e)n.set(t.id,new Set);for(const e of t)n.has(e.source)||n.set(e.source,new Set),n.has(e.target)||n.set(e.target,new Set),n.get(e.source).add(e.target);return n}(e.nodes,e.edges.map(e=>({source:e.sourceID,target:e.targetID}))),t)].map(t=>e.byID.get(t)).filter(e=>null!=e).filter(e=>!(n.isComplete?n.isComplete(e):s.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),o=Array.from(new Set(i.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:i.length,affectedLaneCount:o.length,downstreamTaskIDs:i.map(e=>e.id),affectedLanes:o}}var Ht=[];function Ut(e,t=0){if(e instanceof Date)return e.getTime();const n=Number(e);return Number.isFinite(n)?n:t}function Xt(e){if(null==e.completionTime)return null;const t=Ut(e.completionTime,NaN);return Number.isFinite(t)?t:null}function Yt(e,t,n,s){const i=new Set;for(const o of e.nodes){const r=e.incoming.get(o.id)??[];(s.has(o.id)||!n.has(o.id)&&r.every(e=>t.has(e.id)))&&i.add(o.id)}return i}function Gt(e,t,n,s){const i=e.nodes.map(Xt).filter(e=>null!=e),o=i.length?Math.min(...i)-1:0,r="replay"!==t||s?n:o,a=new Set,c=new Map;for(const n of e.nodes){const e=Xt(n);(null!=e&&r>=e||"done"===n.status&&"replay"!==t)&&a.add(n.id),n.blockerReason&&!a.has(n.id)&&c.set(n.id,n.blockerReason)}const l=new Set;if("replay"!==t||s)for(const t of e.edges)a.has(t.sourceID)&&l.add(t.id);return{currentTime:r,playing:!1,completed:a,delivered:l,inFlight:new Set,armed:Yt(e,l,c,a),blockers:c,previewTaskID:null}}function Jt(e){return{...e,completed:new Set(e.completed),delivered:new Set(e.delivered),inFlight:new Set(e.inFlight),armed:new Set(e.armed),blockers:new Map(e.blockers)}}function Zt(e){const t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function Kt(e){const t=Zt(e.body);if(!t||2>t.route.length)return null;const n=function(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}(t.route),s=function(e,t){let n=1/0,s=0,i=0;for(let o=1;t.length>o;o+=1){const r=t[o-1],a=t[o],c=a.x-r.x,l=a.y-r.y,d=c*c+l*l,u=Math.sqrt(d);if(0>=u)continue;const h=Math.max(0,Math.min(1,((e.x-r.x)*c+(e.y-r.y)*l)/d)),m=Math.hypot(e.x-(r.x+c*h),e.y-(r.y+l*h));n>m&&(n=m,s=i+h*u),i+=u}return s}(e.body,t.route),i=function(e,t){if(2>e.length)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let n=0;for(let s=1;e.length>s;s+=1){const i=e[s-1],o=e[s],r=o.x-i.x,a=o.y-i.y,c=Math.hypot(r,a);if(c>0){if(n+c>=t){const e=Math.max(0,Math.min(1,(t-n)/c));return{point:{x:i.x+r*e,y:i.y+a*e},tangent:{x:r/c,y:a/c}}}n+=c}}const s=e[e.length-2],i=e[e.length-1],o=i.x-s.x,r=i.y-s.y,a=Math.hypot(o,r)||1;return{point:i,tangent:{x:o/a,y:r/a}}}(t.route,Math.min(n,s+22));return{x:2.5*(78*i.tangent.x-e.body.vx)+8*(i.point.x-e.body.x),y:2.5*(78*i.tangent.y-e.body.vy)+8*(i.point.y-e.body.y)}}function Qt(e,t){const n=t.points[0]??{x:0,y:0},s=t.points[1]??n,i=s.x-n.x,o=s.y-n.y,r=Math.hypot(i,o)||1;return{id:"dependency-ball:"+e.id,x:n.x,y:n.y,vx:i/r*42,vy:o/r*42,mass:.7,restitution:.02,friction:.12,bodyCollisions:!1,shape:{type:"circle",radius:5},datum:{kind:"dependency-ball",edgeID:e.id,sourceID:e.sourceID,targetID:e.targetID,route:t.points}}}import{jsx as Vt,jsxs as _t}from"react/jsx-runtime";function en({machine:e,layout:t,runtime:n,downstreamSet:s,selectedSet:i,width:o,height:r,seed:a,reduced:c,onSelectTask:l}){return _t("svg",{"aria-hidden":"true",width:o,height:r,viewBox:`0 0 ${o} ${r}`,style:{position:"absolute",inset:0,overflow:"visible",pointerEvents:"none"},children:[Vt("defs",{children:Vt("filter",{id:"chain-shadow-"+a,x:"-20%",y:"-20%",width:"140%",height:"150%",children:Vt("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.2"})})}),e.lanes.map((e,n)=>{const s=t.tasks.filter(e=>e.laneIndex===n),i=s[0]?.x??0;return _t("g",{children:[Vt("line",{x1:i,x2:i,y1:32,y2:r-24,stroke:"var(--semiotic-grid, #d7dde0)",strokeWidth:1,strokeDasharray:"3 7"}),Vt("text",{x:i,y:23,textAnchor:"middle",fontSize:12,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e})]},e)}),t.routes.map(e=>{const t=n.delivered.has(e.edgeID),i=n.inFlight.has(e.edgeID),o=s.has(e.targetID)||s.has(e.sourceID),r=e.points.map(e=>`${e.x},${e.y}`).join(" ");return Vt("polyline",{points:r,fill:"none",stroke:o?"var(--semiotic-highlight, #e08a1e)":t?"var(--semiotic-success, #2b8a66)":"var(--semiotic-grid, #aeb8bd)",strokeWidth:o?4:i?3:2,strokeOpacity:t||i||o?.95:.48,strokeLinecap:"round",strokeLinejoin:"round"},e.edgeID)}),t.sockets.map(e=>{const t=n.delivered.has(e.edgeID);return _t("g",{children:[Vt("circle",{cx:e.x,cy:e.y,r:e.radius+2,fill:"var(--semiotic-background, #fff)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.5}),t&&Vt("circle",{cx:e.x,cy:e.y,r:e.radius-.5,fill:"var(--semiotic-success, #2b8a66)"})]},e.id)}),e.nodes.map(e=>{const o=t.taskByID.get(e.id);if(!o)return null;const r=n.completed.has(e.id),d=n.blockers.has(e.id),u=n.previewTaskID===e.id,h=i.has(e.id)||u,m=s.has(e.id),p=function(e,t){return t.completed.has(e.id)?"var(--semiotic-success, #2b8a66)":t.blockers.has(e.id)?"var(--semiotic-error, #c64035)":"in-progress"===e.status?"var(--semiotic-warning, #d18a22)":t.armed.has(e.id)?"var(--semiotic-primary, #2474a6)":"var(--semiotic-muted, #75818a)"}(e,n),f=o.x-o.width/2,g=o.y-o.height/2,y=Math.max(2,o.height*e.progress);return _t("g",{children:[_t("g",{style:{transform:`rotate(${r?76:0}deg)`,transformBox:"fill-box",transformOrigin:"50% 100%",transition:c?"none":"transform 520ms cubic-bezier(.2,.8,.25,1)",filter:"url(#chain-shadow-"+a+")"},children:[Vt("rect",{x:f,y:g,width:o.width,height:o.height,rx:e.milestone?12:4,fill:"var(--semiotic-background, #fff)",stroke:h||m?"var(--semiotic-highlight, #e08a1e)":p,strokeWidth:h?4:m?3:2}),Vt("rect",{x:f+3,y:g+o.height-y+1,width:o.width-6,height:Math.max(0,y-4),rx:2,fill:p,opacity:r?.86:.46})]}),d&&_t("g",{opacity:u?.28:1,children:[Vt("line",{x1:f-8,x2:f+14,y1:o.y+9,y2:o.y-9,stroke:"var(--semiotic-error, #c64035)",strokeWidth:7,strokeLinecap:"round"}),Vt("circle",{cx:f-8,cy:o.y+9,r:3,fill:"var(--semiotic-error, #c64035)"})]}),_t("g",{onPointerDown:()=>l(e.id),style:{cursor:"pointer",pointerEvents:"auto"},children:[Vt("rect",{x:f,y:g,width:o.width,height:o.height,fill:"transparent"}),Vt("text",{x:o.x,y:o.y-4,textAnchor:"middle",fontSize:10.5,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e.label.length>24?e.label.slice(0,22)+"…":e.label}),_t("text",{x:o.x,y:o.y+12,textAnchor:"middle",fontSize:9.5,fill:"var(--semiotic-text-muted, #5f6b72)",children:[Math.round(100*e.progress),"% · ",r?"done":d?"blocked":n.armed.has(e.id)?"ready":"waiting"]})]})]},e.id)})]})}import{jsx as tn,jsxs as nn}from"react/jsx-runtime";var sn={border:0,clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},on=Dt(function(e,t){const{data:n,taskIDAccessor:s,labelAccessor:i,laneAccessor:o,dependencyAccessor:r,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:m,mode:p="snapshot",insight:f="blocker-amplification",currentTime:g,controls:y=!1,selectedTaskIDs:k,onSelectionChange:x,onObservation:b,reducedMotion:v,seed:I=31,width:D=920,height:M=620,responsiveWidth:A,responsiveHeight:T,title:S="Dependency chain reaction",description:C,className:$,accessibleTable:E=!0,enableHover:N=!0}=e,j=Ct(null),[R,P]=$t([]),W=k?Array.from(k):R,B=St(()=>new Set(W),[W]),F=Ut(g,1/0),L="settle"===v,q=St(()=>Bt({data:n,taskIDAccessor:s,labelAccessor:i,laneAccessor:o,dependencyAccessor:r,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:m}),[n,s,i,o,r,a,c,l,d,u,h,m]),O=St(()=>Ft(q,{width:D,height:M}),[q,D,M]),[z,H]=$t(()=>Gt(q,p,F,L)),U=Ct(z),X=Mt(e=>{U.current=e,H(e)},[]),Y=Mt(e=>b?.(e),[b]);At(()=>{const e=Gt(q,p,F,L);j.current?.clear(),U.current=e,H(e)},[q,p,F,L]);const G=Mt(e=>{const t=B.has(e)?W.filter(t=>t!==e):[e];k||P(t),x?.(t)},[k,x,B,W]),J=Mt(e=>{if(L)return;const t=Jt(U.current),n=[];for(const s of q.outgoing.get(e)??[]){if(t.delivered.has(s.id)||t.inFlight.has(s.id))continue;const e=O.routeByEdgeID.get(s.id);e&&(t.inFlight.add(s.id),n.push(Qt(s,e)))}n.length&&(X(t),j.current?.pushMany(n,{pacing:{ratePerSec:8}}))},[X,O,q,L]),Z=Mt((e,t)=>{const n=q.byID.get(e),s=U.current;if(!n||s.completed.has(e))return;const i=Jt(s);i.completed.add(e),i.blockers.delete(e),i.armed.add(e),null!=t&&(i.currentTime=t),X(i),Y({type:"task-completed",taskID:e,datum:n.datum}),J(e)},[X,Y,q,J]),K=Mt(e=>{const t=Jt(U.current),n=[],s=[];for(const s of e){if(t.delivered.has(s))continue;const e=q.edges.find(e=>e.id===s);e&&(t.delivered.add(s),t.inFlight.delete(s),n.push(e))}for(const e of n){const n=q.byID.get(e.targetID);!n||t.blockers.has(n.id)||t.armed.has(n.id)||(q.incoming.get(n.id)??[]).every(e=>t.delivered.has(e.id))&&(t.armed.add(n.id),s.push(n.id))}if(n.length){X(t);for(const e of n)Y({type:"dependency-delivered",sourceID:e.sourceID,targetID:e.targetID});for(const e of s)Y({type:"task-armed",taskID:e})}},[X,Y,q]),Q=Mt((e,t)=>{const n=[],s=[];for(const e of t.readBodies()){const t=Zt(e);if(!t||U.current.delivered.has(t.edgeID))continue;const i=t.route[t.route.length-1];i&&9>=Math.hypot(e.x-i.x,e.y-i.y)&&(n.push(t.edgeID),s.push(e.id))}s.length&&t.remove(s),n.length&&K(n)},[K]),V=Mt(()=>{const e=Jt(U.current);for(const t of q.edges)e.completed.has(t.sourceID)&&e.delivered.add(t.id);e.inFlight.clear(),e.armed=Yt(q,e.delivered,e.blockers,e.completed),e.playing=!1,j.current?.settle(),X(e),Y({type:"machine-settled"})},[X,Y,q]),_=Mt(()=>{const e=Jt(U.current);e.playing=!1,X(e)},[X]),ee=Mt(()=>{const e=U.current,t=q.nodes.map(e=>({node:e,time:Xt(e)})).filter(t=>null!=t.time&&t.time>e.currentTime&&!e.completed.has(t.node.id)).sort((e,t)=>e.time-t.time||e.node.index-t.node.index)[0];if(t)return void Z(t.node.id,t.time);_();const n=[...e.blockers.keys()].map(t=>zt(q,t,{completedTaskIDs:e.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);n[0]&&Y({type:"machine-stalled",blockerID:n[0].blockerID,downstreamTaskCount:n[0].downstreamTaskCount,affectedLaneCount:n[0].affectedLaneCount})},[Y,q,_,Z]),te=Mt(()=>{if(L)return void V();const e=Jt(U.current);e.playing=!0,X(e)},[X,L,V]);At(()=>{if(!z.playing||"replay"!==p||L)return;const e=window.setInterval(ee,760);return()=>window.clearInterval(e)},[p,L,z.playing,ee]);const ne=Mt(()=>{j.current?.clear(),X(Gt(q,p,F,L))},[X,q,p,F,L]),se=Mt(e=>{if(!q.byID.has(e))return;const t=Jt(U.current);t.previewTaskID=e,X(t);const n=zt(q,e,{completedTaskIDs:t.completed});Y({type:"blocker-previewed",blockerID:e,downstreamTaskIDs:n.downstreamTaskIDs})},[X,Y,q]),ie=Mt(()=>{const e=Jt(U.current);e.previewTaskID=null,X(e)},[X]),oe=Mt((e,t)=>{if(!q.byID.has(e))return;const n=Jt(U.current);n.blockers.set(e,t),n.armed.delete(e),X(n)},[X,q]),re=Mt(e=>{if(!q.byID.has(e))return;const t=Jt(U.current);t.blockers.delete(e),(q.incoming.get(e)??[]).every(e=>t.delivered.has(e.id))&&t.armed.add(e),X(t)},[X,q]),ae=Mt(e=>zt(q,e,{completedTaskIDs:U.current.completed}),[q]),ce=Mt(()=>{const e=U.current;return{currentTime:e.currentTime,playing:e.playing,previewTaskID:e.previewTaskID,selectedTaskIDs:[...W],tasks:q.nodes.map(t=>({taskID:t.id,completed:e.completed.has(t.id),armed:e.armed.has(t.id),blocked:e.blockers.has(t.id),blockerReason:e.blockers.get(t.id)})),dependencies:q.edges.map(t=>({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,state:e.delivered.has(t.id)?"delivered":e.inFlight.has(t.id)?"in-flight":"waiting"}))}},[q,W]);Tt(t,()=>({play:te,pause:_,step:ee,reset:ne,settle:V,previewResolve:se,clearPreview:ie,completeTask:Z,blockTask:oe,unblockTask:re,getAmplification:ae,getMachineState:ce}),[oe,ie,ae,ce,_,Z,te,se,ne,V,ee,re]);const le=z.previewTaskID??W[0]??null,de=le?zt(q,le,{completedTaskIDs:z.completed}):null,ue=St(()=>new Set(de?.downstreamTaskIDs??[]),[de?.downstreamTaskIDs]),he=St(()=>function(e,t,n){return e.nodes.flatMap(s=>{const i=t.taskByID.get(s.id);if(!i)return[];const o=e.incoming.get(s.id)??[],r=o.filter(e=>n.delivered.has(e.id)).length,a=n.blockers.get(s.id),c=n.completed.has(s.id)?"completed":a?"blocked: "+a:n.armed.has(s.id)?"armed":"waiting";return[{id:s.id,label:`${s.label}, ${s.lane}, ${Math.round(100*s.progress)}%, ${c}`,description:`${r} of ${o.length} prerequisites delivered.`,datum:s.datum,x:i.x,y:i.y,width:i.width,height:i.height,shape:"rect",group:s.lane}]})}(q,O,z),[O,q,z]),me=St(()=>tn(en,{machine:q,layout:O,runtime:z,downstreamSet:ue,selectedSet:B,width:D,height:M,seed:I,reduced:L,onSelectTask:G}),[ue,M,O,q,L,z,I,G,B,D]),pe=St(()=>{const e=[...z.blockers.keys()].map(e=>zt(q,e,{completedTaskIDs:z.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);return e.length?e.map(e=>`${q.byID.get(e.blockerID)?.label??e.blockerID} affects ${e.downstreamTaskCount} unfinished tasks across ${e.affectedLaneCount} lanes.`).join(" "):"No explicit blockers are active."},[q,z.blockers,z.completed]),fe=St(()=>[{id:"chain-left",shape:{type:"segment",x1:2,y1:0,x2:2,y2:M,thickness:4}},{id:"chain-right",shape:{type:"segment",x1:D-2,y1:0,x2:D-2,y2:M,thickness:4}},{id:"chain-top",shape:{type:"segment",x1:0,y1:2,x2:D,y2:2,thickness:4}},{id:"chain-bottom",shape:{type:"segment",x1:0,y1:M-2,x2:D,y2:M-2,thickness:4}}],[M,D]),ge=!0===y?["play","pause","step","reset","settle"]:y||[];return nn("div",q.valid?{className:$,style:{width:D,maxWidth:"100%",position:"relative"},children:[ge.length>0&&tn("div",{"aria-label":"Chain reaction replay controls",style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:ge.map(e=>tn("button",{type:"button",onClick:"play"===e?te:"pause"===e?_:"step"===e?ee:"reset"===e?ne:V,"aria-pressed":"play"===e?z.playing:void 0,children:e[0].toUpperCase()+e.slice(1)},e))}),tn(w,{ref:j,size:[D,M],responsiveWidth:A,responsiveHeight:T,title:S,description:C??"Tasks are arranged by workstream and dependency depth. Balls represent satisfied prerequisites; task completion remains an explicit data event.",summary:`${pe}${de&&"blocker-amplification"===f?` Selected task reaches ${de.downstreamTaskCount} unfinished tasks across ${de.affectedLaneCount} lanes.`:""}`,accessibleTable:!1,enableHover:N,initialSpawns:Ht,bodyForces:Kt,bodyStyle:{fill:"var(--semiotic-accent, #f0a329)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.25},bodySemanticItems:!1,semanticItems:he,onSemanticItemActivate:e=>e.id&&G(e.id),foregroundGraphics:()=>me,paused:L,continuous:z.inFlight.size>0,onTick:Q,config:{bodyLimit:Math.max(16,q.edges.length+4),colliders:fe,settleStepLimit:2200,kernel:{seed:I,gravity:{x:0,y:7},fixedDt:1/60,cellSize:28,collisionIterations:2,velocityDamping:.992,restitution:.02,friction:.12,maxVelocity:150,sleepSpeed:1.1,sleepAfter:.8},observation:{chartType:"ChainReactionChart"}}}),E&&nn("table",{style:sn,children:[tn("caption",{children:pe}),tn("thead",{children:nn("tr",{children:[tn("th",{children:"Task"}),tn("th",{children:"Lane"}),tn("th",{children:"Progress"}),tn("th",{children:"State"}),tn("th",{children:"Waiting on"}),tn("th",{children:"Downstream reach"})]})}),tn("tbody",{children:q.nodes.map(e=>{const t=zt(q,e.id,{completedTaskIDs:z.completed});return nn("tr",{children:[tn("th",{scope:"row",children:e.label}),tn("td",{children:e.lane}),nn("td",{children:[Math.round(100*e.progress),"%"]}),tn("td",{children:z.completed.has(e.id)?"Completed":z.blockers.has(e.id)?"Blocked":z.armed.has(e.id)?"Armed":"Waiting"}),tn("td",{children:z.blockers.get(e.id)??(e.dependencyIDs.filter(e=>!z.completed.has(e)).join(", ")||"None")}),nn("td",{children:[t.downstreamTaskCount," tasks / ",t.affectedLaneCount," lanes"]})]},e.id)})})]})]}:{className:$,role:"alert",style:{width:D,maxWidth:"100%"},children:[tn("strong",{children:"ChainReactionChart could not compile this dependency graph."}),tn("ul",{children:q.diagnostics.map((e,t)=>tn("li",{children:e.message},`${e.code}-${t}`))})]})});on.displayName="ChainReactionChart";var rn=w;export{s as BuiltInPhysicsEngineAdapter,on as ChainReactionChart,i as CollisionSwarmChart,o as CrucibleChart,r as DEFAULT_CRUCIBLE_HEIGHT,a as DEFAULT_CRUCIBLE_OUTLETS,c as DEFAULT_CRUCIBLE_SIZE,l as DEFAULT_CRUCIBLE_WIDTH,d as EventDropChart,u as GaltonBoardChart,h as GauntletChart,m as GuantletChart,p as PhysicalFlowChart,f as PhysicsCustomChart,g as PhysicsPileChart,y as PhysicsPipelineStore,k as PhysicsSVGOverlay,x as PhysicsSedimentAccumulator,b as ProcessFlowChart,v as StreamPhysicsFrame,I as absorbRegion,D as aggregateRegionCounts,M as applyCrucibleEvent,It as arrivalReplay,A as bodiesToAnnotationAnchors,T as bodyGroupSpec,S as buildCollisionSwarmPhysics,C as buildCrucibleEvidence,$ as buildCrucibleInitialSpawns,E as buildCrucibleLayout,N as buildCruciblePhysicsConfig,j as buildCrucibleProductEvents,R as buildCrucibleProjection,P as buildCrucibleStateSpawns,W as buildCrucibleTerminalSpawns,B as buildEventDropPhysics,F as buildGaltonBoardPhysics,L as buildPhysicalFlowPhysics,q as buildPhysicsAnnotationContext,O as buildPhysicsPile,z as buildProcessFlowPhysics,zt as calculateBlockerAmplification,H as capacitatedRegion,U as chargeGateRegion,X as cloneCrucibleState,xt as collidersFromScales,mt as comparePhysicsTrace,J as compileCruciblePlan,Bt as compileDependencyMachine,ze as compileMotionEncoding,Ve as compilePhysicsEncoding,Z as composePhysicsControllers,Be as composeStyleRules,K as createCapacityQueueController,Q as createDefaultPhysicsEngineAdapter,V as createDependencyGateController,_ as createInitialCrucibleState,Lt as createLogicalJoin,_e as createPhysicsEncodingLayout,ee as createPortalController,e as createProcessJourneyLedger,te as createServiceLevelController,ne as createServiceResourcePoolController,se as crucibleBondId,ie as crucibleBoundaryColliders,oe as crucibleComponentBodyId,re as crucibleProductBodyId,ae as crucibleProjectionRows,ce as crucibleSemanticKey,rn as default,He as deriveMotionVector,le as evaluateCrucibleConservation,de as evaluatePhysicsBodyBudget,ue as forceFieldRegion,bt as galtonPegs,he as groupCompletionRows,Ue as hatchFillId,Xe as hatchPatternDef,Ye as isHatchFill,Fe as makeRuleValueResolver,Le as matchesThreshold,me as membraneRegion,pe as normalizePhysicsAnnotations,Ge as opacityFromAge,fe as physicsProcessBoundaryColliders,ge as physicsProcessGroupSemanticItems,ye as physicsProcessRegionSemanticItem,ke as physicsProcessStageSemanticItems,ct as physicsReferenceEnvelope,xe as planGauntletPropertyWork,be as portalRegion,ve as pressureFieldRegion,we as processChrome,t as processJourneyRows,Ie as processLaneWalls,De as processStageLayout,Me as processStageRegions,Ae as processVolumePolygons,Te as regionCountsToProjectionRows,Se as replaceGauntletNegative,Ce as replayCruciblePlan,Ot as replayStateTransitions,$e as resolveCrucibleSelector,Ee as resolveCrucibleSnapshotAt,Ne as resolveCrucibleTime,Je as resolveMotionAccessor,Ze as resolveMotionAge,Ke as resolveMotionVector,qe as resolveStyleRules,Qe as resolveSvgFill,Ft as routeDependencyTracks,je as routeSurfaceRegion,Oe as ruleMatches,wt as sedimentBake,Re as sedimentHeightfield,vt as spawnFromTokens,Pe as stageTargetInVolume,n as updateProcessJourney};
2
+ import{createProcessJourneyLedger as e,processJourneyRows as t,updateProcessJourney as n}from"./chunk-chunk-YWZB3KPI.module.min.js";import{ChainReactionChart as i,calculateBlockerAmplification as o,compileDependencyMachine as r,createLogicalJoin as s,replayStateTransitions as a,routeDependencyTracks as l}from"./chunk-chunk-BZNOAHJV.module.min.js";import{CollisionSwarmChart as u,CrucibleChart as c,DEFAULT_CRUCIBLE_HEIGHT as p,DEFAULT_CRUCIBLE_OUTLETS as h,DEFAULT_CRUCIBLE_SIZE as m,DEFAULT_CRUCIBLE_WIDTH as d,EventDropChart as f,GaltonBoardChart as y,GauntletChart as w,GuantletChart as g,PacketFlowChart as x,PhysicalFlowChart as b,PhysicsPileChart as v,ProcessFlowChart as k,UnitPileChart as M,applyCrucibleEvent as A,applyGauntletEffect as P,buildCrucibleEvidence as j,buildCrucibleInitialSpawns as E,buildCrucibleLayout as S,buildCruciblePhysicsConfig as $,buildCrucibleProductEvents as N,buildCrucibleProjection as R,buildCrucibleStateSpawns as D,buildCrucibleTerminalSpawns as I,cloneCrucibleState as q,compileCruciblePlan as B,createInitialCrucibleState as Y,crucibleBondId as W,crucibleBoundaryColliders as F,crucibleComponentBodyId as T,crucibleProductBodyId as X,crucibleProjectionRows as C,crucibleSemanticKey as L,defaultViability as O,evaluateCrucibleConservation as Z,eventLogItem as H,physicsProcessBoundaryColliders as J,physicsProcessGroupSemanticItems as z,physicsProcessRegionSemanticItem as U,physicsProcessStageSemanticItems as V,planGauntletPropertyWork as K,processChrome as Q,recordGauntletEvent as G,replaceGauntletNegative as _,replayCruciblePlan as ee,resolveCrucibleSelector as te,resolveCrucibleSnapshotAt as ne,resolveCrucibleTime as ie}from"./chunk-chunk-LJDH3WV3.module.min.js";import{BuiltInPhysicsEngineAdapter as oe,PhysicsCustomChart as re,PhysicsPipelineStore as se,PhysicsSVGOverlay as ae,PhysicsSedimentAccumulator as le,StreamPhysicsFrame as ue,StreamPhysicsFrame_default as ce,absorbRegion as pe,aggregateRegionCounts as he,bodiesToAnnotationAnchors as me,bodyGroupSpec as de,buildCollisionSwarmPhysics as fe,buildEventDropPhysics as ye,buildGaltonBoardPhysics as we,buildPhysicalFlowPhysics as ge,buildPhysicsAnnotationContext as xe,buildPhysicsPile as be,buildProcessFlowPhysics as ve,capacitatedRegion as ke,chargeGateRegion as Me,collidersFromPlotBounds as Ae,collidersFromXScaleBins as Pe,composePhysicsControllers as je,createCapacityQueueController as Ee,createDefaultPhysicsEngineAdapter as Se,createDependencyGateController as $e,createPortalController as Ne,createServiceLevelController as Re,createServiceResourcePoolController as De,evaluatePhysicsBodyBudget as Ie,forceFieldRegion as qe,groupCompletionRows as Be,membraneRegion as Ye,normalizePhysicsAnnotations as We,portalRegion as Fe,pressureFieldRegion as Te,processLaneWalls as Xe,processStageLayout as Ce,processStageRegions as Le,processVolumePolygons as Oe,regionCountsToProjectionRows as Ze,routeSurfaceRegion as He,sedimentHeightfield as Je,stageTargetInVolume as ze}from"./chunk-chunk-JJ4BSUYL.module.min.js";import{mulberry32 as Ue}from"./chunk-chunk-SIRIJ3DY.module.min.js";import{composeStyleRules as Ve,makeRuleValueResolver as Ke,matchesThreshold as Qe,resolveStyleRules as Ge,ruleMatches as _e}from"./chunk-chunk-EMO5NUGE.module.min.js";import"./chunk-chunk-SV4XAZ3Q.module.min.js";import"./chunk-chunk-SFLUSZ73.module.min.js";import{compileMotionEncoding as et,deriveMotionVector as tt,opacityFromAge as nt,resolveMotionAccessor as it,resolveMotionAge as ot,resolveMotionVector as rt}from"./chunk-chunk-4MLLQUGW.module.min.js";import{hatchFillId as st,hatchPatternDef as at,isHatchFill as lt,resolveSvgFill as ut}from"./chunk-chunk-HCNDE26Q.module.min.js";import"./chunk-chunk-2NVFEB7P.module.min.js";import"./chunk-chunk-PMR47KRY.module.min.js";import"./chunk-chunk-KTWEBFMX.module.min.js";import"./chunk-chunk-ACLDBMRH.module.min.js";import"./chunk-chunk-YHNZCPOZ.module.min.js";function ct(e){const{data:t,encoding:n,defaults:i={},scales:o}=e,r=et({data:t,encoding:n}),s=[],a=new Map,l=[],u=[],c=new Map;return r.rows.forEach((e,t)=>{const{id:r,datum:p}=e,h=Math.max(0,it(n.appearance?.size,p,t)??i.size??6),m=it(n.appearance?.shape,p,t)??i.shape??{type:"circle",radius:h},d=e.placement.x??i.x??0,f=e.placement.y??i.y??0,y=o?.x?o.x(d):d,w=o?.y?o.y(f):f,g=it(n.appearance?.color,p,t)??i.color,x=it(n.appearance?.opacity,p,t)??i.opacity,b=it(n.appearance?.stroke,p,t)??i.stroke,v=it(n.appearance?.strokeWidth,p,t)??i.strokeWidth,k=it(n.time?.spawnAt,p,t)??e.time.arrival,M=e.kinematics.velocityX,A=e.kinematics.velocityY,P=it(n.dynamics?.mass,p,t)??i.mass??1,j=it(n.dynamics?.friction,p,t),E=it(n.dynamics?.restitution,p,t),S=it(n.dynamics?.bodyCollisions,p,t),$={id:r,x:y,y:w,mass:P,shape:{...m},datum:p,...null!=k&&{spawnAt:k},...null!=M&&{vx:M},...null!=A&&{vy:A},...null!=j&&{friction:j},...null!=E&&{restitution:E},...null!=S&&{bodyCollisions:S}},N={...null!=g&&{fill:g},...null!=x&&{opacity:x},...null!=b&&{stroke:b},...null!=v&&{strokeWidth:v}},R={id:r,datum:p,appearance:{color:g,opacity:x,shape:m,size:h,stroke:b,strokeWidth:v},placement:{x:y,y:w,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:k,spawnAt:k,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:M,velocityY:A,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:S,friction:j,mass:P,restitution:E},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:$};s.push(R),a.set(r,R),l.push($),c.set(r,N),u.push({id:r,bodyId:r,label:e.accessible.label,description:e.accessible.description,datum:p,x:y,y:w,group:e.accessible.group})}),{rows:s,byId:a,spawns:l,semanticItems:u,bodyStyle:e=>c.get(e.id)??{}}}function pt(e){return t=>{const n=ct({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),i=e.extend?.(t,n)??{};return{...i,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...i.semanticItems??[]]}}}function ht(e,t){const{layout:n,positiveProperties:i,negativeProperties:o,viability:r,outcome:s}=t,a=function(e){return new Map(e.gates.map(e=>[e.id,e]))}(n),l=[...("function"==typeof t.events?t.events(e,n):t.events)??[]].sort((e,t)=>e.time-t.time);let u=e;for(const e of l){const t=e.gateId?a.get(e.gateId):void 0,l=e.effects??[],c={...H(e,l),appliedAt:e.time},p=G(u,c);if(p!==u){u=p;for(const n of l){const r={event:e,gate:t,negativeProperties:o,positiveProperties:i,project:u};n.when&&!n.when(r)||(u=P(u,n,r))}u={...u,viability:r?.(u,{negativeProperties:o,positiveProperties:i})??O(u,i,o)},e.final&&(u={...u,outcome:e.outcome??s?.(u,{layout:n,negativeProperties:o,positiveProperties:i})??(u.viability>20?"built":"approved_not_built")})}}return u}function mt(e){return e.projects.map(t=>ht(t,e))}var dt=[.1,.5,.9],ft=1e6;function yt(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function wt(e,t,n,i,o){return"function"==typeof i?i(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,i??o)}function gt(e){const t=Number(e.toFixed(12));return Object.is(t,-0)?0:t}function xt(e,t,n,i){const o=e.flatMap((e,o)=>{const r=yt(wt(e,o,t,n,"time")),s=yt(wt(e,o,t,i,"value"));return null==r||null==s?[]:[{time:gt(r),value:s,index:o}]});o.sort((e,t)=>e.time-t.time||e.index-t.index);const r=[];for(const e of o){const t=r[r.length-1];t?.time===e.time?t.value=e.value:r.push({time:e.time,value:e.value})}return r}function bt(e,t,n,i){if(!e.length)return null;const o=e[0],r=e[e.length-1];if(o.time>t)return"clamp"===i?o.value:null;if(t>r.time)return"clamp"===i?r.value:null;const s=function(e,t){let n=0,i=e.length;for(;i>n;){const o=n+i>>>1;t>e[o].time?n=o+1:i=o}return n}(e,t),a=e[s];if(a?.time===t)return a.value;const l=e[Math.max(0,s-1)];return"step"!==n&&a&&a.time!==l.time?l.value+(t-l.time)/(a.time-l.time)*(a.value-l.value):l.value}function vt(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,i=Math.floor(n),o=Math.ceil(n);return i===o?e[i]:e[i]+(e[o]-e[i])*(n-i)}function kt(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",i=function(e){const t=(e??dt).map(e=>{const t=yt(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return gt(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),o=function(e){if(Array.isArray(e)){if(e.length>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(e.map(yt).filter(e=>null!=e).map(gt))).sort((e,t)=>e-t)}const t=e,n=yt(t.start),i=yt(t.end),o=yt(t.step);if(null==n||null==i||null==o||0>=o||n>i)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const r=Math.floor((i-n)/o)+1;if(r>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");const s=[],a=1e-10*Math.max(1,Math.abs(i),Math.abs(n));for(let e=0;r>e;e+=1){const t=n+e*o;if(t>i+a)break;s.push(gt(Math.min(t,i)))}if(s.length&&a>=Math.abs(s[s.length-1]-i)||s.push(gt(i)),s.length>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(s)).sort((e,t)=>e-t)}(e.sampleAt),r=e.runs.map(t=>xt(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:o.map(e=>{const o=r.map(i=>bt(i,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),s={};for(const e of i)s[e]=o.length?vt(o,e):null;return{time:e,count:o.length,min:o.length?o[0]:null,max:o.length?o[o.length-1]:null,median:o.length?vt(o,.5):null,quantiles:s}}),quantiles:i,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function Mt(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function At(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=yt(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const i=gt(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,i))throw Error(`comparePhysicsTrace could not find quantile ${i} in the reference envelope`);return e.quantiles[i]??null}function Pt(e,t,n){return t>e?"below":e>n?"above":"inside"}function jt(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const i=e.value-e.lower,o=t.value-t.lower,r=e.value-e.upper,s=t.value-t.upper,a=[0,1];for(const[e,t]of[[i,o],[r,s]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let l=0,u=0,c=0;for(let i=0;a.length-1>i;i+=1){const o=a[i],r=a[i+1];if(o>=r)continue;const s=(o+r)/2,p=(r-o)*n,h=Pt(e.value+(t.value-e.value)*s,e.lower+(t.lower-e.lower)*s,e.upper+(t.upper-e.upper)*s);"below"===h?l+=p:"above"===h?c+=p:u+=p}return{below:l,inside:u,above:c,observed:n}}function Et(e,t,n={}){const i=n.interpolation??t.interpolation,o=n.outsideDomain??t.outsideDomain,r=xt(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),s=n.lower??Mt(t,"lower"),a=n.upper??Mt(t,"upper"),l=t.points.map(e=>{const t=bt(r,e.time,i,o),n=At(e,s),l=At(e,a);if(null!=n&&null!=l&&n>l)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:l,status:null==t||null==n||null==l?"unobserved":Pt(t,n,l)}});let u=0,c=0,p=0,h=0,m=null,d=0,f=null;for(const e of l){if("below"===e.status?u+=1:"inside"===e.status?c+=1:"above"===e.status&&(p+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,m=e.time),n>d&&(d=n,f=e.time)}let y=0,w=0,g=0,x=0;for(let e=0;l.length-1>e;e+=1){const t=l[e],n=l[e+1],o=Math.max(0,n.time-t.time);if(o>0){if("linear"===i){const e=jt(t,n);y+=e.below,w+=e.inside,g+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=o,"below"===t.status?y+=o:"above"===t.status?g+=o:w+=o)}}const b=l[0]?.time,v=l[l.length-1]?.time,k=null==b||null==v?0:Math.max(0,v-b);return{points:l,sampleCount:l.length,observedSamples:u+c+p,belowSamples:u,insideSamples:c,aboveSamples:p,totalDuration:k,observedDuration:x,unobservedDuration:Math.max(0,k-x),belowDuration:y,insideDuration:w,aboveDuration:g,peakExcess:h,peakExcessAt:m,peakDeficit:d,peakDeficitAt:f}}function St(e){const[t,n]=e.size,i=e.flow??"down",o=null==(v=e.padding)?{top:24,right:24,bottom:24,left:24}:"number"==typeof v?{top:v,right:v,bottom:v,left:v}:{top:v.top??0,right:v.right??0,bottom:v.bottom??0,left:v.left??0},r=Math.max(.05,Math.min(1,e.channelRatio??1)),s={x:o.left,y:o.top,width:Math.max(1,t-o.left-o.right),height:Math.max(1,n-o.top-o.bottom)},a="down"===i?s.height:s.width,l=a*Math.max(0,e.chargeExtent??.12),u=a*Math.max(0,e.projectionExtent??0),c=a*Math.max(0,e.destinationExtent??.55),p=Math.max(0,a-l-c-u),h=function(e){return"number"==typeof e?Array.from({length:Math.max(1,Math.round(e))},(e,t)=>({id:"bin-"+t,label:t+""})):0===e.length?[{id:"bin-0",label:"0"}]:e.map((e,t)=>({id:e.id,label:e.label??e.id??t+""}))}(e.destinations),m=("down"===i?s.width:s.height)/h.length,d="down"===i?(e,t)=>({x:s.x,y:s.y+e,width:s.width,height:t}):(e,t)=>({x:s.x+e,y:s.y,width:t,height:s.height}),f=d(0,l),y=d(l,p),w=l+p,g=d(w,c),x=d(w+c,u),b=h.map((e,t)=>{const n=t*m,o=m*r,a=(m-o)/2;return"down"===i?{id:e.id,label:e.label,order:t,x:s.x+n+a,y:g.y,width:o,height:g.height,centerX:s.x+(t+.5)*m,centerY:g.y+g.height/2}:{id:e.id,label:e.label,order:t,x:g.x,y:s.y+n+a,width:g.width,height:o,centerX:g.x+g.width/2,centerY:s.y+(t+.5)*m}});var v;return{width:t,height:n,flow:i,charge:f,apparatus:y,destinations:b,projection:x}}function $t(e,t){return e.destinations.find(e=>e.id===t)}function Nt(e,t,n){const{charge:i,flow:o}=e,r=Math.max(1,n),s=(t%r+.5)/r;return"down"===o?{x:i.x+i.width*s,y:i.y+i.height/2}:{x:i.x+i.width/2,y:i.y+i.height*s}}function Rt(e,t={}){const n=t.thickness??4,i=t.idPrefix??"stage",{destinations:o,flow:r,width:s,height:a}=e,l=[];if(o.length>0){const t=o[0];if("down"===r){const r=t.y+t.height;l.push({id:i+"-floor",shape:{type:"segment",x1:e.charge.x,y1:r,x2:e.charge.x+e.charge.width,y2:r,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerX-(o[e].centerX-o[e-1].centerX)/2;l.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:s,y1:t.y,x2:s,y2:r,thickness:n}})}}else{const r=t.x+t.width;l.push({id:i+"-floor",shape:{type:"segment",x1:r,y1:e.charge.y,x2:r,y2:e.charge.y+e.charge.height,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerY-(o[e].centerY-o[e-1].centerY)/2;l.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:t.x,y1:s,x2:r,y2:s,thickness:n}})}}}return!1!==t.walls&&l.push({id:i+"-wall-left",shape:{type:"segment",x1:1,y1:0,x2:1,y2:a,thickness:n}},{id:i+"-wall-right",shape:{type:"segment",x1:s-1,y1:0,x2:s-1,y2:a,thickness:n}}),l}function Dt(e,t={}){return`${t.charge??"bodies"} enter at the ${"down"===e.flow?"top":"left"}, travel ${"down"===e.flow?"downward":"left to right"} through ${t.apparatus??"the apparatus"}, and come to rest in ${e.destinations.length} ${t.destination??"destinations"}: ${e.destinations.map(e=>e.label).join(", ")}.`}function It(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function qt(e,t,n,i){const o="function"==typeof e?e(t,n):e;return Number.isFinite(o)?Number(o):i}function Bt(e,t,n){return It(e[t])??n}function Yt(e,t){return"number"==typeof e?e:e?.[t]??0}function Wt(e){const{band:t,idPrefix:n,plot:i,projection:o}=e,{includeBoundaryWalls:r=!0,includeInteriorWalls:s=!0,wallThickness:a=4}=t,l=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const i of e.values){const o=e.scale(i);Number.isFinite(o)&&(n.add(Number(o)),n.add(Number(o)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>l.length)return[];const u=r?l.length-1:l.length-2,c=[];for(let e=r?0:1;u>=e;e+=1){if(!s&&e>0&&l.length-1>e)continue;const t=l[e];c.push({id:`${n}-wall-${e}`,shape:"x"===o?{type:"aabb",x:t,y:i.y+i.height/2,width:a,height:i.height}:{type:"aabb",x:i.x+i.width/2,y:t,width:i.width,height:a}})}return c}function Ft(e){const{plot:t,idPrefix:n="physics-scale",bounds:i={},xBins:o,xBands:r,yBands:s}=e,a=[];if(!1!==i&&a.push(...Ae(t,{idPrefix:n,...i})),o){const{idPrefix:e,yTop:i,yBottom:r,...s}=o;a.push(...Pe({...s,idPrefix:e??n+"-xbin",yTop:i??t.y,yBottom:r??t.y+t.height}))}return r&&a.push(...Wt({band:r,idPrefix:r.idPrefix??n+"-xband",plot:t,projection:"x"})),s&&a.push(...Wt({band:s,idPrefix:s.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function Tt(e){const{plot:t,rows:n,columns:i=n+1,pegRadius:o=3,idPrefix:r="galton-peg",yStart:s=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:l=!0,restitution:u=.2,friction:c=.04}=e,p=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(i));if(0===p)return[];const m=p>1?(a-s)/(p-1):0,d=t.width/h,f=[];for(let e=0;p>e;e+=1){const n=l&&e%2==1?d/2:0;for(let i=0;h>i;i+=1){const a=t.x+d*(i+.5)+n;t.x+o>a||a>t.x+t.width-o||f.push({id:`${r}-${e}-${i}`,shape:{type:"aabb",x:a,y:s+e*m,width:2*o,height:2*o},restitution:u,friction:c})}}return f}function Xt(e,t={}){const{idPrefix:n="physics-token",radius:i=5,shape:o,mass:r,vx:s,vy:a,spawnAt:l,seed:u=1,jitter:c,datum:p}=t,h=Ue(u),m=Yt(c,"x"),d=Yt(c,"y");return e.map((e,u)=>{const c=qt(t.x,e,u,Bt(e,"x",0)),f=qt(t.y,e,u,Bt(e,"y",0)),y=qt(i,e,u,5),w="function"==typeof o?o(e,u):o??{type:"circle",radius:y};return{id:`${n}-${e.index??u}`,x:c+(h()-.5)*m,y:f+(h()-.5)*d,vx:qt(s,e,u,0),vy:qt(a,e,u,0),mass:qt(r,e,u,1),spawnAt:qt(l,e,u,void 0),shape:w,datum:p?p(e,u):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function Ct(e,t={}){const{idPrefix:n="sediment",collider:i=!0,colliderThickness:o=1,restitution:r=.05,friction:s=.2,...a}=t,l=Je(e,a),u=i?l.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+o/2,width:e.width,height:o},restitution:r,friction:s})):[];return{columns:l,colliders:u}}function Lt(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:i=1,startAt:o=0,rebase:r=!0,sort:s=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return It("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),l=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:o+(r?t-l:t)})).sort((e,t)=>s?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:o,timeAccessor:"spawnAt",timeScale:i}}}var Ot=ce;export{oe as BuiltInPhysicsEngineAdapter,i as ChainReactionChart,u as CollisionSwarmChart,c as CrucibleChart,p as DEFAULT_CRUCIBLE_HEIGHT,h as DEFAULT_CRUCIBLE_OUTLETS,m as DEFAULT_CRUCIBLE_SIZE,d as DEFAULT_CRUCIBLE_WIDTH,f as EventDropChart,y as GaltonBoardChart,w as GauntletChart,g as GuantletChart,x as PacketFlowChart,b as PhysicalFlowChart,re as PhysicsCustomChart,v as PhysicsPileChart,se as PhysicsPipelineStore,ae as PhysicsSVGOverlay,le as PhysicsSedimentAccumulator,k as ProcessFlowChart,ue as StreamPhysicsFrame,M as UnitPileChart,pe as absorbRegion,he as aggregateRegionCounts,A as applyCrucibleEvent,Lt as arrivalReplay,me as bodiesToAnnotationAnchors,de as bodyGroupSpec,fe as buildCollisionSwarmPhysics,j as buildCrucibleEvidence,E as buildCrucibleInitialSpawns,S as buildCrucibleLayout,$ as buildCruciblePhysicsConfig,N as buildCrucibleProductEvents,R as buildCrucibleProjection,D as buildCrucibleStateSpawns,I as buildCrucibleTerminalSpawns,ye as buildEventDropPhysics,we as buildGaltonBoardPhysics,ge as buildPhysicalFlowPhysics,xe as buildPhysicsAnnotationContext,be as buildPhysicsPile,ve as buildProcessFlowPhysics,o as calculateBlockerAmplification,ke as capacitatedRegion,Me as chargeGateRegion,q as cloneCrucibleState,Ft as collidersFromScales,Et as comparePhysicsTrace,B as compileCruciblePlan,r as compileDependencyMachine,et as compileMotionEncoding,ct as compilePhysicsEncoding,je as composePhysicsControllers,Ve as composeStyleRules,Ee as createCapacityQueueController,Se as createDefaultPhysicsEngineAdapter,$e as createDependencyGateController,Y as createInitialCrucibleState,s as createLogicalJoin,pt as createPhysicsEncodingLayout,Ne as createPortalController,e as createProcessJourneyLedger,Re as createServiceLevelController,De as createServiceResourcePoolController,W as crucibleBondId,F as crucibleBoundaryColliders,T as crucibleComponentBodyId,X as crucibleProductBodyId,C as crucibleProjectionRows,L as crucibleSemanticKey,Ot as default,tt as deriveMotionVector,Dt as describePhysicsStageGeography,Z as evaluateCrucibleConservation,Ie as evaluatePhysicsBodyBudget,qe as forceFieldRegion,Tt as galtonPegs,Be as groupCompletionRows,st as hatchFillId,at as hatchPatternDef,lt as isHatchFill,Ke as makeRuleValueResolver,Qe as matchesThreshold,Ye as membraneRegion,We as normalizePhysicsAnnotations,nt as opacityFromAge,Nt as physicsChargePoint,$t as physicsDestination,J as physicsProcessBoundaryColliders,z as physicsProcessGroupSemanticItems,U as physicsProcessRegionSemanticItem,V as physicsProcessStageSemanticItems,kt as physicsReferenceEnvelope,Rt as physicsStageColliders,St as physicsStageGeography,K as planGauntletPropertyWork,Fe as portalRegion,Te as pressureFieldRegion,Q as processChrome,t as processJourneyRows,Xe as processLaneWalls,Ce as processStageLayout,Le as processStageRegions,Oe as processVolumePolygons,Ze as regionCountsToProjectionRows,_ as replaceGauntletNegative,ee as replayCruciblePlan,a as replayStateTransitions,te as resolveCrucibleSelector,ne as resolveCrucibleSnapshotAt,ie as resolveCrucibleTime,ht as resolveGauntletTerminalState,mt as resolveGauntletTerminalStates,it as resolveMotionAccessor,ot as resolveMotionAge,rt as resolveMotionVector,Ge as resolveStyleRules,ut as resolveSvgFill,l as routeDependencyTracks,He as routeSurfaceRegion,_e as ruleMatches,Ct as sedimentBake,Je as sedimentHeightfield,Xt as spawnFromTokens,ze as stageTargetInVolume,n as updateProcessJourney};
@@ -1 +1 @@
1
- function t(t){let e=t>>>0;return function(){e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}var e={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},s=1e-9,i=.005;function n(t){return"circle"===t.type?{type:"circle",radius:t.radius}:{type:"aabb",width:t.width,height:t.height}}function o(t){return"aabb"===t.type?{type:"aabb",x:t.x,y:t.y,width:t.width,height:t.height}:{type:"segment",x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,thickness:t.thickness}}function r(t,e,s){return Math.max(e,Math.min(s,t))}function a(t){return t<0?-1:1}function d(t){if("circle"===t.shape.type){const e=t.shape.radius;return{minX:t.x-e,minY:t.y-e,maxX:t.x+e,maxY:t.y+e}}const e=t.shape.width/2,s=t.shape.height/2;return{minX:t.x-e,minY:t.y-s,maxX:t.x+e,maxY:t.y+s}}function h(t){const e=t.shape;if("aabb"===e.type){const t=e.width/2,s=e.height/2;return{minX:e.x-t,minY:e.y-s,maxX:e.x+t,maxY:e.y+s}}const s=(e.thickness??0)/2;return{minX:Math.min(e.x1,e.x2)-s,minY:Math.min(e.y1,e.y2)-s,maxX:Math.max(e.x1,e.x2)+s,maxY:Math.max(e.y1,e.y2)+s}}function c(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function l(t,e,s,i,n,o,r,d){const h=n-t,c=(s+r)/2-Math.abs(h);if(c<=0)return null;const l=o-e,u=(i+d)/2-Math.abs(l);return u<=0?null:c<u?{nx:a(h),ny:0,penetration:c}:{nx:0,ny:a(l),penetration:u}}function u(t,e,i,n,o,a,d){const h=a/2,c=d/2;let l=t-r(t,n-h,n+h),u=e-r(e,o-c,o+c);const p=l*l+u*u;if(p>i*i)return null;if(p<=s){const s=Math.abs(t-(n-h)),r=Math.abs(t-(n+h)),a=Math.abs(e-(o-c)),d=Math.abs(e-(o+c)),p=Math.min(s,r,a,d);return p===s?(l=-1,u=0,{nx:l,ny:u,penetration:i+s}):p===r?(l=1,u=0,{nx:l,ny:u,penetration:i+r}):p===a?(l=0,u=-1,{nx:l,ny:u,penetration:i+a}):(l=0,u=1,{nx:l,ny:u,penetration:i+d})}const y=Math.sqrt(p);return{nx:l/y,ny:u/y,penetration:i-y}}function p(t,e){if("circle"===t.shape.type&&"circle"===e.shape.type)return function(t,e,i,n,o,r){const a=n-t,d=o-e,h=i+r,c=a*a+d*d;if(c>=h*h)return null;if(c<=s)return{nx:1,ny:0,penetration:h};const l=Math.sqrt(c);return{nx:a/l,ny:d/l,penetration:h-l}}(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.radius);if("aabb"===t.shape.type&&"aabb"===e.shape.type)return l(t.x,t.y,t.shape.width,t.shape.height,e.x,e.y,e.shape.width,e.shape.height);if("circle"===t.shape.type&&"aabb"===e.shape.type){const s=u(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height);return s?{nx:-s.nx,ny:-s.ny,penetration:s.penetration}:null}return"aabb"===t.shape.type&&"circle"===e.shape.type?u(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height):null}function y(t,e){const i=e.shape;if("aabb"===i.type){if("circle"===t.shape.type)return u(t.x,t.y,t.shape.radius,i.x,i.y,i.width,i.height);return l(i.x,i.y,i.width,i.height,t.x,t.y,t.shape.width,t.shape.height)}const n="circle"===t.shape.type?t.shape.radius:Math.sqrt(t.shape.width*t.shape.width+t.shape.height*t.shape.height)/2;return function(t,e,i,n,o,a,d,h=0){const c=a-n,l=d-o,u=c*c+l*l,p=u<=s?0:r(((t-n)*c+(e-o)*l)/u,0,1),y=i+h/2,m=t-(n+c*p),v=e-(o+l*p),f=m*m+v*v;if(f>=y*y)return null;if(f<=s){const t=Math.sqrt(u);return t<=s?{nx:1,ny:0,penetration:y}:{nx:-l/t,ny:c/t,penetration:y}}const g=Math.sqrt(f);return{nx:m/g,ny:v/g,penetration:y-g}}(t.x,t.y,n,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function m(t,e){return`${t}\0${e}`}function v(t){const e=t.indexOf("\0");return{sensorId:t.slice(0,e),bodyId:t.slice(e+1)}}function f(t){return{id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,bodyCollisions:t.bodyCollisions,shape:n(t.shape),sleeping:t.sleeping,datum:t.datum,index:t.index,sleepTime:t.sleepTime,restitution:t.restitution,friction:t.friction}}function g(t){return t&&"function"!=typeof t?{property:t.property,equals:t.equals,notEquals:t.notEquals,oneOf:t.oneOf?.slice(),notOneOf:t.notOneOf?.slice()}:t}function x(t){return{id:t.id,shape:o(t.shape),sensor:t.sensor,restitution:t.restitution,friction:t.friction,bodyFilter:g(t.bodyFilter),index:t.index}}function b(t,e){return Boolean(e?.some(e=>Object.is(t,e)))}function S(t,e){const s=t.bodyFilter;if(!s)return!0;if("function"==typeof s)return s(e);const i=function(t,e){if(!e)return;let s=t;for(const t of e.split(".")){if(null==s||"object"!=typeof s)return;s=s[t]}return s}(e,s.property);return!("equals"in s&&!Object.is(i,s.equals))&&((!("notEquals"in s)||!Object.is(i,s.notEquals))&&(!(s.oneOf&&!b(i,s.oneOf))&&(!s.notOneOf||!b(i,s.notOneOf))))}var w=class{constructor(s={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...e,...s},this.random=t(this.options.seed)}init(s={}){this.options={...e,...s},this.random=t(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(t){const e={id:t.id,x:t.x,y:t.y,prevX:t.x,prevY:t.y,vx:t.vx??0,vy:t.vy??0,angle:t.angle??0,mass:Math.max(s,t.mass??1),bodyCollisions:t.bodyCollisions??!0,shape:n(t.shape),sleeping:!1,datum:t.datum,restitution:t.restitution,friction:t.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(t.id,e)}remove(t){for(const e of t){this.bodies.delete(e);for(const t of Array.from(this.activeSensors))v(t).bodyId===e&&this.activeSensors.delete(t)}}setColliders(t){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const e of t)this.colliders.set(e.id,{...e,shape:o(e.shape),bodyFilter:g(e.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(t){const e=t.id??`spring-${this.nextSpringIndex}`;return this.springs.set(e,{id:e,bodyId:t.bodyId,target:t.target,restLength:t.restLength??0,stiffness:t.stiffness??40,damping:t.damping??3}),this.nextSpringIndex+=1,e}removeConstraint(t){this.springs.delete(t)}applyImpulse(t,e,s){const i=this.bodies.get(t);i&&(i.vx+=e/i.mass,i.vy+=s/i.mass,this.wake(i))}step(t=this.options.fixedDt){const e=Math.max(0,t);if(this.lastEvents=[],0===e)return;const s=this.sortedBodies();for(const t of s)t.prevX=t.x,t.prevY=t.y;this.applySprings(e);const i=this.options.maxVelocity;for(const t of s)if(!t.sleeping){if(t.vx+=this.options.gravity.x*e,t.vy+=this.options.gravity.y*e,t.vx*=this.options.velocityDamping,t.vy*=this.options.velocityDamping,i>0){const e=Math.sqrt(t.vx*t.vx+t.vy*t.vy);if(e>i){const s=i/e;t.vx*=s,t.vy*=s}}t.x+=t.vx*e,t.y+=t.vy*e}this.supportedThisStep.clear();const n=this.bodyPairKeys(s),o=this.sortedColliders().filter(t=>!t.sensor);for(let t=0;t<this.options.collisionIterations;t+=1)this.resolveBodyPairs(s,n,0===t),this.resolveColliders(s,o,0===t);this.updateSensors(s),this.updateSleeping(s,e)}settle(t=1200,e=this.options.fixedDt){let s=0;for(;s<t&&!this.allSleeping();)this.step(e),s+=1;return s}readState(t=[]){t.length=0;for(const e of this.sortedBodies())t.push({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:n(e.shape),sleeping:e.sleeping,datum:e.datum});return t}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(v)}allSleeping(){for(const t of this.bodies.values())if(!t.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(f),colliders:this.sortedColliders().map(x),springs:Array.from(this.springs.values()).map(t=>({...t,target:{...t.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(e){this.options={...e.options,gravity:{...e.options.gravity}},this.random=t(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const t of e.bodies){const e=f(t);this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(const t of e.colliders){const e=x(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(const t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});const e=/^spring-(\d+)$/.exec(t.id);e&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(e[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((t,e)=>t.index-e.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((t,e)=>t.index-e.index)}applySprings(t){for(const e of Array.from(this.springs.values()).sort((t,e)=>t.id.localeCompare(e.id))){const i=this.bodies.get(e.bodyId);if(!i||i.sleeping)continue;const n="point"===e.target.type?e.target:this.bodies.get(e.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,a=o*o+r*r,d=Math.sqrt(a);if(d<=s)continue;const h=o/d,c=r/d,l="vx"in n?n.vx:0,u="vy"in n?n.vy:0,p=(l-i.vx)*h+(u-i.vy)*c,y=(d-e.restLength)*e.stiffness+p*e.damping;i.vx+=y*h*t/i.mass,i.vy+=y*c*t/i.mass}}resolveBodyPairs(t,e,s){for(const i of e){const[e,n]=i.split(":").map(Number),o=t[e],r=t[n];if(!o||!r)continue;const a=p(o,r);a&&(this.resolveDynamicCollision(o,r,a),s&&this.lastEvents.push({type:"contact",bodyId:o.id,otherId:r.id,sensor:!1}))}}bodyPairKeys(t){const e=Math.max(1,this.options.cellSize),s=new Map;for(let i=0;i<t.length;i+=1){if(!1===t[i].bodyCollisions)continue;const n=d(t[i]),o=Math.floor(n.minX/e),r=Math.floor(n.maxX/e),a=Math.floor(n.minY/e),h=Math.floor(n.maxY/e);for(let t=o;t<=r;t+=1)for(let e=a;e<=h;e+=1){const n=`${t}:${e}`,o=s.get(n);o?o.push(i):s.set(n,[i])}}const i=new Set;for(const e of Array.from(s.keys()).sort()){const n=s.get(e)??[];n.sort((t,e)=>t-e);for(let e=0;e<n.length;e+=1)for(let s=e+1;s<n.length;s+=1){const o=n[e],r=n[s];!1!==t[o].bodyCollisions&&!1!==t[r].bodyCollisions&&(c(d(t[o]),d(t[r]))&&i.add(`${o}:${r}`))}}return Array.from(i).sort((t,e)=>{const[s,i]=t.split(":").map(Number),[n,o]=e.split(":").map(Number);return s===n?i-o:s-n})}resolveDynamicCollision(t,e,n){t.sleeping&&this.contactOpposesGravity(n.nx,n.ny)&&this.supportedThisStep.add(e.id),e.sleeping&&this.contactOpposesGravity(-n.nx,-n.ny)&&this.supportedThisStep.add(t.id);const o=t.sleeping?0:1/t.mass,r=e.sleeping?0:1/e.mass,a=o+r;if(a<=s)return;const d=Math.max(0,n.penetration-i)/a;t.x-=n.nx*d*o,t.y-=n.ny*d*o,e.x+=n.nx*d*r,e.y+=n.ny*d*r;const h=e.vx-t.vx,c=e.vy-t.vy,l=h*n.nx+c*n.ny;if(l>0)return;const u=Math.abs(l),p=-(1+Math.min(t.restitution??this.options.restitution,e.restitution??this.options.restitution))*l/a,y=p*n.nx,m=p*n.ny;t.vx-=y*o,t.vy-=m*o,e.vx+=y*r,e.vy+=m*r,this.applyFriction(t,e,n,p,o,r),u>this.options.contactWakeSpeed&&(this.wake(t),this.wake(e))}applyFriction(t,e,i,n,o,a){const d=-i.ny,h=i.nx,c=(e.vx-t.vx)*d+(e.vy-t.vy)*h,l=o+a;if(Math.abs(c)<=s||l<=s)return;const u=Math.max(0,Math.min(1,Math.max(t.friction??this.options.friction,e.friction??this.options.friction))),p=r(-c/l,-n*u,n*u),y=p*d,m=p*h;t.vx-=y*o,t.vy-=m*o,e.vx+=y*a,e.vy+=m*a}resolveColliders(t,e,s){for(const i of t)for(const t of e){if(!S(t,i))continue;if(!c(d(i),h(t)))continue;const e=y(i,t);e&&(this.resolveStaticCollision(i,t,e),this.contactOpposesGravity(e.nx,e.ny)&&this.supportedThisStep.add(i.id),s&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:t.id,sensor:!1}))}}resolveStaticCollision(t,e,s){t.x+=s.nx*Math.max(0,s.penetration-i),t.y+=s.ny*Math.max(0,s.penetration-i);const n=t.vx*s.nx+t.vy*s.ny;if(n<0){const i=Math.min(t.restitution??this.options.restitution,e.restitution??this.options.restitution);t.vx-=(1+i)*n*s.nx,t.vy-=(1+i)*n*s.ny;const o=-s.ny,r=s.nx,a=t.vx*o+t.vy*r,d=Math.max(0,Math.min(1,Math.max(t.friction??this.options.friction,e.friction??this.options.friction)));t.vx-=a*o*d,t.vy-=a*r*d}}updateSensors(t){const e=new Set,s=this.sortedColliders().filter(t=>t.sensor);for(const i of t){const t=d(i);for(const n of s){if(!S(n,i))continue;if(!c(t,h(n)))continue;if(!y(i,n))continue;const s=m(n.id,i.id);e.add(s),this.activeSensors.has(s)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:n.id})}}for(const t of Array.from(this.activeSensors).sort()){if(e.has(t))continue;const{sensorId:s,bodyId:i}=v(t);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:s})}this.activeSensors=e}updateSleeping(t,e){const s=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of t){const t=Math.sqrt(i.vx*i.vx+i.vy*i.vy),n=Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY));!(t<this.options.sleepSpeed&&n<this.options.sleepSpeed*e)||s&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=e,!i.sleeping&&i.sleepTime>=this.options.sleepAfter&&(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}}contactOpposesGravity(t,e){const{x:s,y:i}=this.options.gravity,n=Math.hypot(s,i);return n<=1e-9||(t*s+e*i)/n<-.2}wake(t){t.sleeping&&this.lastEvents.push({type:"wake",bodyId:t.id}),t.sleeping=!1,t.sleepTime=0}nextRandom(){return this.random()}},I=class{constructor(t={}){this.id="builtin",this.capabilities={...(new w).capabilities,engine:"builtin"},this.world=new w(t)}init(t={}){this.world.init(t)}spawn(t){this.world.spawn(t)}remove(t){this.world.remove(t)}setColliders(t){this.world.setColliders(t)}setConstraint(t){return this.world.setConstraint(t)}removeConstraint(t){this.world.removeConstraint(t)}applyImpulse(t,e,s){this.world.applyImpulse(t,e,s)}step(t){this.world.step(t)}settle(t,e){return this.world.settle(t,e)}readState(t){return this.world.readState(t)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(t){this.world.restore(t)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function B(t,e={}){return t?"function"==typeof t?t(e):(t.init(e),t):function(t={}){return new I(t)}(e)}var M=["binId","targetBin","category","windowIndex","lane","group"];function O(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function q(t,e){if(!Number.isFinite(e))return;t.count+=1,t.total+=e,t.min=Math.min(t.min,e),t.max=Math.max(t.max,e);const s=e-t.mean;t.mean+=s/t.count;const i=e-t.mean;t.m2+=s*i}function k(t){return{count:t.count,total:t.total,mean:t.count>0?t.mean:0,min:t.count>0?t.min:0,max:t.count>0?t.max:0,variance:t.count>1?t.m2/(t.count-1):0}}function C(t){return{count:t.count,total:t.total,mean:t.mean,m2:t.variance*Math.max(0,t.count-1),min:t.count>0?t.min:Number.POSITIVE_INFINITY,max:t.count>0?t.max:Number.NEGATIVE_INFINITY}}function T(t,e){const s=t;if(null!=s[e])return s[e];const i=t.datum;return i&&"object"==typeof i?i[e]:void 0}function A(t,e,s){return"function"==typeof t?t(e,s):"string"==typeof t?T(e,t):void 0}function D(t){if(null==t)return;const e=String(t);return e.trim()?e:void 0}function R(t){const e=k(t.value);return{id:t.id,label:t.label,count:e.count,total:e.total,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:k(t.x),y:k(t.y),value:e}}var N=class{constructor(t=!1){this.bins=new Map,this.nextIndex=0,this.config=t}updateConfig(t){void 0!==t&&(this.config=t,!1===t&&this.clear())}isEnabled(){return!1!==this.config}add(t){if(!1===this.config)return null;const e=this.nextIndex;this.nextIndex+=1;const s=D(A(this.config.binAccessor,t,e))??function(t){for(const e of M){const s=D(T(t,e));if(s)return s}return"sediment"}(t),i=D(A(this.config.labelAccessor,t,e))??s,n=function(t,e,s){if("number"==typeof t)return t;const i="function"==typeof t?t(e,s):"string"==typeof t?T(e,t):1,n="number"==typeof i?i:Number(i);return Number.isFinite(n)?n:1}(this.config.valueAccessor,t,e),o=Math.max(0,Math.floor(this.config.retainBodyIds??12));let r=this.bins.get(s);return r||(r={id:s,label:i,bodyIds:[],x:O(),y:O(),value:O()},this.bins.set(s,r)),r.label=i,r.lastBodyId=t.id,r.lastDatum=t.datum,q(r.x,t.x),q(r.y,t.y),q(r.value,n),o>0&&(r.bodyIds.push(t.id),r.bodyIds.length>o&&(r.bodyIds=r.bodyIds.slice(r.bodyIds.length-o))),R(r)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(R)}restore(t=[]){this.bins.clear();for(const e of t)this.bins.set(e.id,{id:e.id,label:e.label,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:C(e.x),y:C(e.y),value:C(e.value)});this.nextIndex=t.reduce((t,e)=>t+e.count,0)}totals(){const t=this.snapshot();return{bins:t.length,count:t.reduce((t,e)=>t+e.count,0),total:t.reduce((t,e)=>t+e.total,0)}}};function P(t){const e=Number(t);if(Number.isFinite(e)&&!(e<=0))return Math.floor(e)}function E(t){const e=Math.max(0,Math.floor(t.liveBodies)),s=Math.max(0,Math.floor(t.queuedBodies??0)),i=e+s,n=P(t.bodyLimit),o=P(t.engineMaxBodiesHint),r=function(t,e,s){if(!1===s)return;const i=P(s?.warnAt);return null!=i?i:null!=t?Math.max(1,Math.floor(.8*t)):null!=e?Math.max(1,Math.floor(.8*e)):void 0}(n,o,t.options),a=null==n?0:Math.max(0,e-n),d=a>0?"overflow":null!=r&&i>=r?"warning":"ok";return{action:"overflow"!==d?"continue":t.sedimentEnabled?"sediment":t.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:o,liveBodies:e,overflow:a,projectedBodies:i,queuedBodies:s,state:d,warnAt:r}}var F={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Y={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function X(t={},e=Y){return{chartId:t.chartId??e.chartId,chartType:t.chartType??e.chartType,sensors:t.sensors??e.sensors,onObservation:t.onObservation??e.onObservation,onSimulationStateChange:t.onSimulationStateChange??e.onSimulationStateChange}}function L(t){return{...t,shape:{...t.shape},datum:t.datum,springs:t.springs?.map(t=>({...t,target:{...t.target}}))}}function K(t){if(t instanceof Date){const e=t.getTime();return Number.isFinite(e)?e:void 0}const e="number"==typeof t?t:"string"==typeof t&&t.trim()?Number(t):NaN;return Number.isFinite(e)?e:void 0}function j(t,e){const s=t;if(null!=s[e])return s[e];const i=t.datum;return i&&"object"==typeof i?i[e]:void 0}function V(t,e={}){const s=K(e.startAt)??0,i=e.pacing??"immediate";if("arrival"===i){const i=t.map((t,s)=>function(t,e,s){return"function"==typeof s?K(s(t,e)):"string"==typeof s?K(j(t,s)):K(t.spawnAt)??K(j(t,"arrivalTime"))??K(j(t,"timestamp"))??K(j(t,"time"))??K(j(t,"eventTime"))}(t,s,e.timeAccessor)),n=i.filter(t=>null!=t),o=n.length>0?Math.min(...n):0,r=K(e.timeScale)??1,a=r>0?r:1;return t.map((t,e)=>{const n=i[e],r=null==n?0:Math.max(0,n-o);return{...L(t),spawnAt:s+r/a}})}if("object"==typeof i){const e=K(i.ratePerSec);if(e&&e>0)return t.map((t,i)=>({...L(t),spawnAt:s+i/e}))}return t.map(t=>({...L(t),spawnAt:s}))}function $(t){return{...L(t),sequence:t.sequence,spawnAt:t.spawnAt}}function H(t){return t.map(t=>({...t,shape:{...t.shape},bodyFilter:t.bodyFilter&&"function"!=typeof t.bodyFilter?{...t.bodyFilter,oneOf:t.bodyFilter.oneOf?.slice(),notOneOf:t.bodyFilter.notOneOf?.slice()}:t.bodyFilter}))}function W(t){return!1!==t&&{...t}}function z(t,e){return t.spawnAt===e.spawnAt?t.sequence-e.sequence:t.spawnAt-e.spawnAt}function G(t){return{...t,gravity:{...t.gravity}}}function _(t,e,s,i){if("circle"===t.shape.type){const n=t.x-e,o=t.y-s,r=t.shape.radius+i,a=n*n+o*o;return a<=r*r?a:null}const n=Math.max(Math.abs(e-t.x)-t.shape.width/2,0),o=Math.max(Math.abs(s-t.y)-t.shape.height/2,0),r=n*n+o*o;return r<=i*i?r:null}function U(t){const e=t.indexOf("\0");return{sensorId:t.slice(0,e),bodyId:t.slice(e+1)}}var J={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function Q(t,e){const s={...t};for(const t of e){s[J[t]]++}return s}function Z(t,e,s){const i=new Set(e);return{changeSet:{...t,...t.keys?{keys:[...t.keys]}:{}},changed:i,revisions:Q(s,i)}}var tt=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=Z({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}record(t,e){const s=Z(t,e,this.revisions);this.revisions=s.revisions,this.latest=s;for(const t of[...this.listeners])t();return s}};import{quadtree as et}from"d3-quadtree";var st=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(t,e,s,i,n,o=0){const r=this.ensure(t,e);if(!r)return null;let a=null,d=Number.POSITIVE_INFINITY;const h=Math.max(0,o)+this.maxSearchRadius,c=i-h,l=i+h,u=n-h,p=n+h;return r.visit((t,e,r,h,y)=>{if(h<c||e>l||y<u||r>p)return!0;if(t.length)return!1;let m=t;for(;m;){const t=m.data;if(t){const e=_(t,i,n,Math.max(0,o));null!=e&&(e<d||e===d&&s.indexOf(t.id)>s.indexOf(a?.id??""))&&(a=t,d=e)}m=m.next}return!1}),a}ensure(t,e){if(this.tree&&this.revision===e)return this.tree;const s=t.readState();return 0===s.length?(this.tree=null,this.maxSearchRadius=0,this.revision=e,null):(this.maxSearchRadius=s.reduce((t,e)=>Math.max(t,function(t){return"circle"===t.shape.type?t.shape.radius:Math.hypot(t.shape.width,t.shape.height)/2}(e)),0),this.tree=et().x(t=>t.x).y(t=>t.y).addAll(s),this.revision=e,this.tree)}};var it=["data","scene-geometry","data-paint","accessibility","evidence"],nt=["scene-geometry","data-paint","accessibility","evidence"],ot=["overlay","accessibility","evidence"],rt=(t,e)=>({retainedData:t,invalidations:e}),at=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],dt=["scene-geometry","data-paint","accessibility","evidence"],ht=[],ct={engine:rt("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:rt("preserve",dt),colliders:rt("preserve",dt),sediment:rt("preserve",dt),bodyBudget:rt("preserve",at),bodyLimit:rt("preserve",at),eviction:rt("preserve",at),fixedDt:rt("preserve",ht),maxDeltaSeconds:rt("preserve",ht),maxSubsteps:rt("preserve",ht),settleStepLimit:rt("preserve",ht),timeScale:rt("preserve",ht),observation:rt("preserve",ht)},lt=rt("preserve",at);function ut(t){let e="preserve";const s=new Set;for(const i of t){const t=ct[i]??lt;"rebuild"===t.retainedData&&(e="rebuild");for(const e of t.invalidations)s.add(e)}return{retainedData:e,invalidations:s}}var pt=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function yt(t,e){return t===e||!(!t||!e)&&(t.gravity?.x===e.gravity?.x&&t.gravity?.y===e.gravity?.y&&pt.every(s=>t[s]===e[s]))}function mt(t,e,s,i){return t||!e?"paused":s||!i?"running":"settled"}function vt(t,e,s,i,n,o){const r={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===s)return r;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return r;const d=n.length-a;if(d<=0)return r;const h=function(t,e,s){if("sleeping-first"!==e)return s.slice();const i=new Map(t.readState().map(t=>[t.id,t.sleeping])),n=[],o=[];for(const t of s)i.get(t)?n.push(t):o.push(t);return[...n,...o]}(t,s,n),c=h.slice(0,d);if(0===c.length)return r;const l=function(t,e,s,i){const n=new Map(t.readState().map(t=>[t.id,t])),o=[];for(const t of s){const s=n.get(t);if(!s)continue;const r=e.add(s);r&&(o.push(t),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:t,datum:s.datum,x:s.x,y:s.y,binId:r.id,count:r.count,total:r.total}))}return o}(t,e,c,o);t.remove(c);const u=new Set(c);return{evicted:c,sedimented:l,liveBodyOrder:n.filter(t=>!u.has(t))}}var ft=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(t){this.speed=function(t){const e=t?.sleepSpeed;return"number"==typeof e&&Number.isFinite(e)&&e>0?e:8}(t)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(t,e,s){if(s>0)return void(this.seconds=0);const i=t.readState(this.scratch),n=this.speed*this.speed;let o=!0;for(const t of i)if(!t.sleeping&&t.vx*t.vx+t.vy*t.vy>=n){o=!1;break}this.seconds=o?this.seconds+Math.max(0,e):0}},gt=class{constructor(t={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new st,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new tt,this.simulationState="settled",this.visible=!0,this.quiescence=new ft;const{bodyBudget:e,colliders:s,engine:i,kernel:n,observation:o,sediment:r,...a}=t;this.config={...F,...a},this.configInput={...t},this.bodyBudget=e??{},this.engineInput=i,this.observation=X(o),this.sediment=new N(r??!1),this.world=B(i,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),s&&this.world.setColliders(H(s))}updateConfig(t){const e=function(t,e){return Object.keys(t).filter(s=>"kernel"===s?!yt(t.kernel,e.kernel):t[s]!==e[s])}(t,this.configInput),{colliders:s,bodyBudget:i,engine:n,kernel:o,observation:r,sediment:a,...d}=t;if(this.config={...this.config,...d},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){const t=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=B(n,t.options),this.world.restore(t),this.revision+=1}if(o&&!yt(o,this.configInput.kernel)){const t=this.world.snapshot(),e={...t.options,...o,gravity:{...t.options.gravity,...o.gravity}};this.world.restore({...t,options:e}),this.quiescence.setKernelOptions(e),this.revision+=1}r&&(this.observation=X(r,this.observation)),this.sediment.updateConfig(a),s&&(this.world.setColliders(H(s)),this.revision+=1),this.configInput={...this.configInput,...t};const h=ut(e);this.updateResults.record({kind:"config",keys:e},h.invalidations)}updateConfigWithResult(t){return this.updateConfig(t),this.updateResults.last}setColliders(t){this.world.setColliders(H(t)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ut(["colliders"]).invalidations)}enqueue(t,e){const s=Array.isArray(t)?t:[t],i=e?V(s,{...e,startAt:e.startAt??this.elapsedSeconds}):s;for(const t of i)this.queue.push({...L(t),sequence:this.nextSequence,spawnAt:t.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(z),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?it:[])}enqueueWithResult(t,e){return this.enqueue(t,e),this.updateResults.last}spawnNow(t){this.spawnOne(L(t)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},it)}materializeDueSpawns(){const t=this.revision,e=[],s=[];return this.spawnDue(e,s),0===e.length||(this.observeBodyBudget(s),this.evictOverflow(s),this.syncSimulationState(s),this.revision+=1,this.updateResults.record({kind:"enqueue",count:e.length},this.revision!==t?it:[])),e}clear(){const t=this.world.snapshot().options;this.world.init({...t,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},it)}tick(t){const e=this.revision,s=[],i=[],n=[],o=[],r=[];if(this.paused||!this.visible){const t=this.result(0,s,i,n,o,r,!1);return this.updateResults.record({kind:"tick",count:0},[]),t}const a=Math.max(0,Math.min(t,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(s,r);const d=this.observeBodyBudget(r),h=this.evictOverflow(r);i.push(...h.evicted),n.push(...h.sedimented),this.syncSimulationState(r),this.accumulator+=a;let c=0;for(;this.accumulator>=this.config.fixedDt&&c<this.config.maxSubsteps;){this.world.step(this.config.fixedDt);const t=this.world.events();o.push(...t),this.observeKernelEvents(t,r),this.observeSensorTransitions(r),this.accumulator-=this.config.fixedDt,c+=1}c===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,s.length),(c>0||s.length>0||i.length>0||n.length>0||o.length>0)&&(this.revision+=1);const l=this.result(c,s,i,n,o,r,void 0,d);return this.updateResults.record({kind:"tick",count:c},this.revision!==e?s.length||i.length||n.length?it:nt:[]),l}settle(t=this.config.settleStepLimit){const e=this.revision;this.spawnDue([],[]);const s=this.world.settle(t,this.config.fixedDt);return s>0&&(this.revision+=1),this.syncSimulationState(),this.updateResults.record({kind:"settle",count:s},this.revision!==e?nt:[]),s}settleWithObservations(t=this.config.settleStepLimit){const e=this.revision,s=[],i=[],n=[],o=[],r=[];if(this.paused||!this.visible){const t=this.result(0,s,i,n,o,r,!1);return this.updateResults.record({kind:"settle",count:0},[]),t}this.spawnDue(s,r);const a=this.observeBodyBudget(r),d=this.evictOverflow(r);i.push(...d.evicted),n.push(...d.sedimented),this.syncSimulationState(r);let h=0;for(s.length>0&&this.quiescence.reset();h<t&&!this.atRest();){this.world.step(this.config.fixedDt);const t=this.world.events();o.push(...t),this.observeKernelEvents(t,r),this.observeSensorTransitions(r),h+=1,this.quiescence.refresh(this.world,this.config.fixedDt,0)}(h>0||s.length>0||i.length>0||n.length>0||o.length>0)&&(this.revision+=1);const c=this.result(h,s,i,n,o,r,void 0,a);return this.updateResults.record({kind:"settle",count:h},this.revision!==e?s.length||i.length||n.length?it:nt:[]),c}readBodies(t=[]){return this.world.readState(t)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(t={}){return function(t,e={}){const{baselineY:s=0,binWidth:i=24,gap:n=2,maxHeight:o=80,value:r="count",x:a}=e,d=Math.max(1,...t.map(t=>t[r]));return t.map((t,e)=>{const h=Math.max(0,t[r]/d*o),c=a?.(t,e)??e*(i+n);return{binId:t.id,label:t.label,index:e,count:t.count,total:t.total,x:c,y:s-h,width:i,height:h,meanX:t.x.mean,meanY:t.y.mean}})}(this.readSediment(),t)}hitTest(t,e,s=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,t,e,s)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(t){const{timestamp:e,chartType:s,chartId:i,...n}=t,o={...n,timestamp:e??this.elapsedSeconds,chartType:s??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(o),this.updateResults.record({kind:"update",count:1},["evidence"]),o}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(t){return this.updateResults.subscribe(t)}version(){return this.revision}setPaused(t){const e=this.paused!==t;this.paused=t,this.syncSimulationState(),this.updateResults.record({kind:"pause"},e?ot:[])}setVisible(t){const e=this.visible!==t;this.visible=t,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},e?ot:[])}remove(t){const e=new Set(t),s=new Set(this.liveBodyOrder),i=new Set(this.queue.map(t=>t.id));this.queue=this.queue.filter(t=>!e.has(t.id)),this.liveBodyOrder=this.liveBodyOrder.filter(t=>!e.has(t)),this.world.remove(t),this.removeActiveSensorPairsForBodies(e);const n=t.filter(t=>s.has(t)||i.has(t));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?it:[]),n}setConstraint(t){const e=this.world.setConstraint(t);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},nt),e}removeConstraint(t){this.world.removeConstraint(t),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},nt)}applyImpulse(t,e,s){this.world.applyImpulse(t,e,s),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[t]},nt)}nextRandom(){return this.world.nextRandom()}controls(){return t=this,{applyImpulse:(e,s,i)=>t.applyImpulse(e,s,i),clear:()=>t.clear(),hitTest:(e,s,i)=>t.hitTest(e,s,i),pause:()=>t.setPaused(!0),push:(e,s)=>t.enqueue(e,s),pushMany:(e,s)=>t.enqueue(e,s),bodyBudgetStatus:()=>t.bodyBudgetStatus(),readBodies:e=>t.readBodies(e),readSediment:()=>t.readSediment(),recordObservation:e=>t.recordObservation(e),remove:e=>t.remove(e),restore:e=>t.restore(e),resume:()=>t.setPaused(!1),settle:e=>t.settle(e),settleWithObservations:e=>t.settleWithObservations(e),snapshot:()=>t.snapshot(),sedimentHeightfield:e=>t.sedimentHeightfield(e),sedimentTotals:()=>t.sedimentTotals(),step:e=>t.tick(e)};var t}snapshot(){const t=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:W(this.bodyBudget),config:{...this.config,kernel:G(t.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map($),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:t}}restore(t){this.config={bodyLimit:t.config.bodyLimit,eviction:t.config.eviction,fixedDt:t.config.fixedDt,maxDeltaSeconds:t.config.maxDeltaSeconds,maxSubsteps:t.config.maxSubsteps,settleStepLimit:t.config.settleStepLimit,timeScale:t.config.timeScale},this.configInput={...t.config,bodyBudget:W(t.bodyBudget??{}),kernel:G(t.world.options)},this.bodyBudget=W(t.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(t.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(t.activeSensorPairs),this.accumulator=t.accumulator,this.elapsedSeconds=t.elapsedSeconds,this.paused=t.paused,this.queue=t.queue.map($).sort(z),this.revision=t.revision,this.sediment.restore(t.sediment??[]),this.simulationState=t.simulationState??mt(t.paused,t.visible,t.queue.length>0,t.world.bodies.every(t=>t.sleeping)),this.liveBodyOrder=t.liveBodyOrder.slice(),this.visible=t.visible,this.nextSequence=this.queue.reduce((t,e)=>Math.max(t,e.sequence),-1)+1,this.world.restore(t.world),this.updateResults.record({kind:"restore"},it)}spawnDue(t,e){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds;){const s=this.queue.shift();if(!s)return;this.spawnOne(s,e),t.push(s.id)}}spawnOne(t,e){this.liveBodyOrder=this.liveBodyOrder.filter(e=>e!==t.id),this.removeActiveSensorPairsForBodies(new Set([t.id])),this.world.spawn(t),this.liveBodyOrder.push(t.id);for(const e of t.springs??[])this.world.setConstraint({...e,bodyId:t.id});const s=this.world.readState().find(e=>e.id===t.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:t.id,datum:s?.datum??t.datum,x:s?.x??t.x,y:s?.y??t.y},e)}result(t,e,s,i,n,o,r,a=this.evaluateBodyBudget()){this.syncSimulationState(o);const d=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:s,events:n,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:r??(this.queue.length>0||!this.atRest()),sleeping:d,sedimented:i,spawned:e,steps:t}}observeKernelEvents(t,e){!function(t,e,s){if(0===e.length)return;const i=new Map(t.readState().map(t=>[t.id,t]));for(const t of e){if("sleep"!==t.type)continue;const e=i.get(t.bodyId);s.emit({type:"physics-settle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:t.bodyId,datum:e?.datum,x:e?.x,y:e?.y})}}(this.world,t,this.observationContext(e))}observeSensorTransitions(t){this.activeSensorPairs=function(t,e,s){const i=new Set(t.activeSensorPairs().map(t=>`${t.sensorId}\0${t.bodyId}`));if(0===i.size&&0===e.size)return i;const n=new Map(t.readState().map(t=>[t.id,t])),o=(t,e)=>{const{sensorId:i,bodyId:o}=U(e),r=s.observation.sensors[i],a=n.get(o);s.emit({type:"enter"===t?r?.enterType??"physics-bin-enter":r?.exitType??"physics-bin-exit",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:o,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:r?.binId??i})};for(const t of Array.from(i).sort())e.has(t)||o("enter",t);for(const t of Array.from(e).sort())i.has(t)||o("exit",t);return i}(this.world,this.activeSensorPairs,this.observationContext(t))}removeActiveSensorPairsForBodies(t){!function(t,e){for(const s of t)e.has(U(s).bodyId)&&t.delete(s)}(this.activeSensorPairs,t)}observationContext(t){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:e=>this.emitObservation(e,t)}}emitObservation(t,e){e?.push(t),this.observation.onObservation?.(t)}evaluateBodyBudget(){return E({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(t){const e=this.evaluateBodyBudget();if("ok"===e.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",e;const s=`${e.state}:${e.action}`;return s===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=s,this.emitObservation({type:"overflow"===e.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:e.action,bodyLimit:e.bodyLimit,engineMaxBodiesHint:e.engineMaxBodiesHint,liveBodies:e.liveBodies,overflow:e.overflow,projectedBodies:e.projectedBodies,queuedBodies:e.queuedBodies,warnAt:e.warnAt},t)),e}syncSimulationState(t){const e=mt(this.paused,this.visible,this.queue.length>0,this.atRest());if(e===this.simulationState)return;const s=this.simulationState;this.simulationState=e,function(t,e,s){s.observation.onSimulationStateChange?.(e,t),"running"!==e&&"settled"!==e||s.emit({type:"running"===e?"sim-active":"sim-idle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,simulationState:e,previousSimulationState:t})}(s,e,this.observationContext(t))}evictOverflow(t){const{evicted:e,sedimented:s,liveBodyOrder:i}=vt(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(t));return e.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(e))),{evicted:e,sedimented:s}}};function xt(t,e){return function(t,e,s=[],i){const n=new Array(e.length),o=new Float32Array(2*e.length),r=new Float32Array(2*e.length),a=new Uint8Array(e.length);return e.forEach((t,e)=>{const s=2*e;n[e]=t.id,o[s]=t.x,o[s+1]=t.y,r[s]=t.vx,r[s+1]=t.vy,a[e]=t.sleeping?1:0}),{bodies:e,ids:n,positions:o,result:t,sediment:s,sleeping:a,snapshot:i,velocities:r}}(e,t.readBodies(),t.readSediment(),t.snapshot())}function bt(t){return xt(t,t.tick(0))}var St=function(){let t=new gt;return{handle(e){switch(e.type){case"init":return t=new gt(e.config),e.snapshot?t.restore(e.snapshot):e.initialSpawns?.length&&t.enqueue(e.initialSpawns,e.initialSpawnPacing),{type:"frame",frame:bt(t)};case"configure":return t.updateConfig(e.config),{type:"frame",frame:bt(t)};case"enqueue":return t.enqueue(e.spawns,e.pacing),{type:"frame",frame:bt(t)};case"tick":return{type:"frame",frame:xt(t,t.tick(e.deltaSeconds))};case"settle":return{type:"frame",frame:xt(t,t.settleWithObservations(e.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:t.snapshot()};case"restore":return t.restore(e.snapshot),{type:"frame",frame:bt(t)};case"clear":return t.clear(),{type:"frame",frame:bt(t)};case"remove":return{type:"removed",removed:t.remove(e.ids),frame:bt(t)};case"applyImpulse":return t.applyImpulse(e.id,e.ix,e.iy),{type:"frame",frame:bt(t)};case"setPaused":return t.setPaused(e.paused),{type:"frame",frame:bt(t)};case"setVisible":return t.setVisible(e.visible),{type:"frame",frame:bt(t)}}}}}();function wt(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t)}}self.onmessage=t=>{const e=t.data;try{const t=St.handle(e.command);self.postMessage({ok:!0,payload:t,requestId:e.requestId},function(t){return"frame"===t.type||"removed"===t.type?[(e=t.frame).positions.buffer,e.velocities.buffer,e.sleeping.buffer]:[];var e}(t))}catch(t){self.postMessage({error:wt(t),ok:!1,requestId:e.requestId})}};
1
+ function e(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}var t={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},s=1e-9,i=.005;function n(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function o(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function r(e,t,s){return Math.max(t,Math.min(s,e))}function a(e,t,s){return Math.min(e??s,t??s)}function d(e,t,s){return r(Math.max(e??s,t??s),0,1)}function h(e){return e<0?-1:1}function c(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,s=e.shape.height/2;return{minX:e.x-t,minY:e.y-s,maxX:e.x+t,maxY:e.y+s}}function l(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,s=t.height/2;return{minX:t.x-e,minY:t.y-s,maxX:t.x+e,maxY:t.y+s}}const s=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-s,minY:Math.min(t.y1,t.y2)-s,maxX:Math.max(t.x1,t.x2)+s,maxY:Math.max(t.y1,t.y2)+s}}function u(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function p(e,t,s,i,n,o,r,a){const d=n-e,c=(s+r)/2-Math.abs(d);if(c<=0)return null;const l=o-t,u=(i+a)/2-Math.abs(l);return u<=0?null:c<u?{nx:h(d),ny:0,penetration:c}:{nx:0,ny:h(l),penetration:u}}function y(e,t,i,n,o,a,d){const h=a/2,c=d/2,l=e-r(e,n-h,n+h),u=t-r(t,o-c,o+c),p=l*l+u*u;if(p>i*i)return null;if(p<=s){const s=Math.abs(e-(n-h)),r=Math.abs(e-(n+h)),a=Math.abs(t-(o-c)),d=Math.abs(t-(o+c)),l=Math.min(s,r,a,d);return l===s?{nx:-1,ny:0,penetration:i+s}:l===r?{nx:1,ny:0,penetration:i+r}:l===a?{nx:0,ny:-1,penetration:i+a}:{nx:0,ny:1,penetration:i+d}}const y=Math.sqrt(p);return{nx:l/y,ny:u/y,penetration:i-y}}function v(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,n,o,r){const a=n-e,d=o-t,h=i+r,c=a*a+d*d;if(c>=h*h)return null;if(c<=s)return{nx:1,ny:0,penetration:h};const l=Math.sqrt(c);return{nx:a/l,ny:d/l,penetration:h-l}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return p(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const s=y(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return s?{nx:-s.nx,ny:-s.ny,penetration:s.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?y(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function m(e,t){const i=t.shape;if("aabb"===i.type)return"circle"===e.shape.type?y(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height):p(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height);const n="circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2;return function(e,t,i,n,o,a,d,h=0){const c=a-n,l=d-o,u=c*c+l*l,p=u<=s?0:r(((e-n)*c+(t-o)*l)/u,0,1),y=i+h/2,v=e-(n+c*p),m=t-(o+l*p),f=v*v+m*m;if(f>=y*y)return null;if(f<=s){const e=Math.sqrt(u);return e<=s?{nx:1,ny:0,penetration:y}:{nx:-l/e,ny:c/e,penetration:y}}const g=Math.sqrt(f);return{nx:v/g,ny:m/g,penetration:y-g}}(e.x,e.y,n,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function f(e,t){return`${e}\0${t}`}function g(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function x(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,shape:n(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function b(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function S(e){return{id:e.id,shape:o(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:b(e.bodyFilter),index:e.index}}function w(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function I(e,t){return function(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const s=function(e,t){if(!t)return;let s=e;for(const e of t.split(".")){if(null==s||"object"!=typeof s)return;s=s[e]}return s}(e,t.property);return!("equals"in t&&!Object.is(s,t.equals)||"notEquals"in t&&Object.is(s,t.notEquals)||t.oneOf&&!w(s,t.oneOf)||t.notOneOf&&w(s,t.notOneOf))}(t,e.bodyFilter)}var B=class{constructor(s={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...t,...s},this.random=e(this.options.seed)}init(s={}){this.options={...t,...s},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(s,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:n(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))g(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:o(t.shape),bodyFilter:b(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??`spring-${this.nextSpringIndex}`;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,s){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=s/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const s=this.sortedBodies();for(const e of s)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of s)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const s=i/t;e.vx*=s,e.vy*=s}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const n=this.bodyPairKeys(s),o=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;e<this.options.collisionIterations;e+=1)this.resolveBodyPairs(s,n,0===e),this.resolveColliders(s,o,0===e);this.updateSensors(s),this.updateSleeping(s,t)}settle(e=1200,t=this.options.fixedDt){let s=0;for(;s<e&&!this.allSleeping();)this.step(t),s+=1;return s}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:n(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(g)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(x),colliders:this.sortedColliders().map(S),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(t){this.options={...t.options,gravity:{...t.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(t.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of t.bodies){const t=x(e);this.bodies.set(t.id,t),this.nextBodyIndex=Math.max(this.nextBodyIndex,t.index+1)}this.nextColliderIndex=0;for(const e of t.colliders){const t=S(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of t.springs){this.springs.set(e.id,{...e,target:{...e.target}});const t=/^spring-(\d+)$/.exec(e.id);t&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(t[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;const n="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,a=o*o+r*r,d=Math.sqrt(a);if(d<=s)continue;const h=o/d,c=r/d,l="vx"in n?n.vx:0,u="vy"in n?n.vy:0,p=(l-i.vx)*h+(u-i.vy)*c,y=(d-t.restLength)*t.stiffness+p*t.damping;i.vx+=y*h*e/i.mass,i.vy+=y*c*e/i.mass}}resolveBodyPairs(e,t,s){for(const i of t){const[t,n]=i.split(":").map(Number),o=e[t],r=e[n];if(!o||!r)continue;const a=v(o,r);a&&(this.resolveDynamicCollision(o,r,a),s&&this.lastEvents.push({type:"contact",bodyId:o.id,otherId:r.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),s=new Map;for(let i=0;i<e.length;i+=1){if(!1===e[i].bodyCollisions)continue;const n=c(e[i]),o=Math.floor(n.minX/t),r=Math.floor(n.maxX/t),a=Math.floor(n.minY/t),d=Math.floor(n.maxY/t);for(let e=o;e<=r;e+=1)for(let t=a;t<=d;t+=1){const n=`${e}:${t}`,o=s.get(n);o?o.push(i):s.set(n,[i])}}const i=new Set;for(const t of Array.from(s.keys()).sort()){const n=s.get(t)??[];n.sort((e,t)=>e-t);for(let t=0;t<n.length;t+=1)for(let s=t+1;s<n.length;s+=1){const o=n[t],r=n[s];!1!==e[o].bodyCollisions&&!1!==e[r].bodyCollisions&&(u(c(e[o]),c(e[r]))&&i.add(`${o}:${r}`))}}return Array.from(i).sort((e,t)=>{const[s,i]=e.split(":").map(Number),[n,o]=t.split(":").map(Number);return s===n?i-o:s-n})}resolveDynamicCollision(e,t,n){e.sleeping&&this.contactOpposesGravity(n.nx,n.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-n.nx,-n.ny)&&this.supportedThisStep.add(e.id);const o=e.sleeping?0:1/e.mass,r=t.sleeping?0:1/t.mass,d=o+r;if(d<=s)return;const h=Math.max(0,n.penetration-i)/d;e.x-=n.nx*h*o,e.y-=n.ny*h*o,t.x+=n.nx*h*r,t.y+=n.ny*h*r;const c=t.vx-e.vx,l=t.vy-e.vy,u=c*n.nx+l*n.ny;if(u>0)return;const p=Math.abs(u),y=-(1+a(e.restitution,t.restitution,this.options.restitution))*u/d,v=y*n.nx,m=y*n.ny;e.vx-=v*o,e.vy-=m*o,t.vx+=v*r,t.vy+=m*r,this.applyFriction(e,t,n,y,o,r),p>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,n,o,a){const h=-i.ny,c=i.nx,l=(t.vx-e.vx)*h+(t.vy-e.vy)*c,u=o+a;if(Math.abs(l)<=s||u<=s)return;const p=d(e.friction,t.friction,this.options.friction),y=r(-l/u,-n*p,n*p),v=y*h,m=y*c;e.vx-=v*o,e.vy-=m*o,t.vx+=v*a,t.vy+=m*a}resolveColliders(e,t,s){for(const i of e)for(const e of t){if(!I(e,i))continue;if(!u(c(i),l(e)))continue;const t=m(i,e);t&&(this.resolveStaticCollision(i,e,t),this.contactOpposesGravity(t.nx,t.ny)&&this.supportedThisStep.add(i.id),s&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,s){e.x+=s.nx*Math.max(0,s.penetration-i),e.y+=s.ny*Math.max(0,s.penetration-i);const n=e.vx*s.nx+e.vy*s.ny;if(n<0){const i=a(e.restitution,t.restitution,this.options.restitution);e.vx-=(1+i)*n*s.nx,e.vy-=(1+i)*n*s.ny;const o=-s.ny,r=s.nx,h=e.vx*o+e.vy*r,c=d(e.friction,t.friction,this.options.friction);e.vx-=h*o*c,e.vy-=h*r*c}}updateSensors(e){const t=new Set,s=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=c(i);for(const n of s){if(!I(n,i))continue;if(!u(e,l(n)))continue;if(!m(i,n))continue;const s=f(n.id,i.id);t.add(s),this.activeSensors.has(s)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:n.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:s,bodyId:i}=g(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:s})}this.activeSensors=t}updateSleeping(e,t){const s=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e){const e=Math.sqrt(i.vx*i.vx+i.vy*i.vy),n=Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY));!(e<this.options.sleepSpeed&&n<this.options.sleepSpeed*t)||s&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,!i.sleeping&&i.sleepTime>=this.options.sleepAfter&&(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}}contactOpposesGravity(e,t){const{x:s,y:i}=this.options.gravity,n=Math.hypot(s,i);return n<=1e-9||(e*s+t*i)/n<-.2}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},M=class{constructor(e={}){this.id="builtin",this.capabilities={...(new B).capabilities,engine:"builtin"},this.world=new B(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function O(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new M(e)}(t)}var q=["binId","targetBin","category","windowIndex","lane","group"];function k(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function T(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const s=t-e.mean;e.mean+=s/e.count;const i=t-e.mean;e.m2+=s*i}function C(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function A(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:Number.POSITIVE_INFINITY,max:e.count>0?e.max:Number.NEGATIVE_INFINITY}}function D(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function R(e,t,s){return"function"==typeof e?e(t,s):"string"==typeof e?D(t,e):void 0}function E(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function N(e){const t=C(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:C(e.x),y:C(e.y),value:t}}var P=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const s=E(R(this.config.binAccessor,e,t))??function(e){for(const t of q){const s=E(D(e,t));if(s)return s}return"sediment"}(e),i=E(R(this.config.labelAccessor,e,t))??s,n=function(e,t,s){if("number"==typeof e)return e;const i="function"==typeof e?e(t,s):"string"==typeof e?D(t,e):1,n="number"==typeof i?i:Number(i);return Number.isFinite(n)?n:1}(this.config.valueAccessor,e,t),o=Math.max(0,Math.floor(this.config.retainBodyIds??12));let r=this.bins.get(s);return r||(r={id:s,label:i,bodyIds:[],x:k(),y:k(),value:k()},this.bins.set(s,r)),r.label=i,r.lastBodyId=e.id,r.lastDatum=e.datum,T(r.x,e.x),T(r.y,e.y),T(r.value,n),o>0&&(r.bodyIds.push(e.id),r.bodyIds.length>o&&(r.bodyIds=r.bodyIds.slice(r.bodyIds.length-o))),N(r)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(N)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:A(t.x),y:A(t.y),value:A(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function F(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function Y(e){const t=Math.max(0,Math.floor(e.liveBodies)),s=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+s,n=F(e.bodyLimit),o=F(e.engineMaxBodiesHint),r=function(e,t,s){if(!1===s)return;const i=F(s?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(n,o,e.options),a=null==n?0:Math.max(0,t-n),d=a>0?"overflow":null!=r&&i>=r?"warning":"ok";return{action:"overflow"!==d?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:o,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:s,state:d,warnAt:r}}var X={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},L={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function K(e={},t=L){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function H(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function j(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function V(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function $(e,t={}){const s=j(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,s)=>function(e,t,s){return"function"==typeof s?j(s(e,t)):"string"==typeof s?j(V(e,s)):j(e.spawnAt)??j(V(e,"arrivalTime"))??j(V(e,"timestamp"))??j(V(e,"time"))??j(V(e,"eventTime"))}(e,s,t.timeAccessor)),n=i.filter(e=>null!=e),o=n.length>0?Math.min(...n):0,r=j(t.timeScale)??1,a=r>0?r:1;return e.map((e,t)=>{const n=i[t],r=null==n?0:Math.max(0,n-o);return{...H(e),spawnAt:s+r/a}})}if("object"==typeof i){const t=j(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...H(e),spawnAt:s+i/t}))}return e.map(e=>({...H(e),spawnAt:s}))}function z(e){return{...H(e),sequence:e.sequence,spawnAt:e.spawnAt}}function W(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function G(e){return!1!==e&&{...e}}function _(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function U(e){return{...e,gravity:{...e.gravity}}}function Q(e,t,s,i){if("circle"===e.shape.type){const n=e.x-t,o=e.y-s,r=e.shape.radius+i,a=n*n+o*o;return a<=r*r?a:null}const n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),o=Math.max(Math.abs(s-e.y)-e.shape.height/2,0),r=n*n+o*o;return r<=i*i?r:null}function J(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}var Z={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function ee(e,t){const s={...e};for(const e of t){s[Z[e]]++}return s}function te(e,t,s){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:ee(s,i)}}var se=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=te({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const s=te(e,t,this.revisions);this.revisions=s.revisions,this.latest=s;for(const e of[...this.listeners])e();return s}};import{quadtree as ie}from"d3-quadtree";var ne=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,s,i,n,o=0){const r=this.ensure(e,t);if(!r)return null;let a=null,d=Number.POSITIVE_INFINITY;const h=Math.max(0,o)+this.maxSearchRadius,c=i-h,l=i+h,u=n-h,p=n+h;return r.visit((e,t,r,h,y)=>{if(h<c||t>l||y<u||r>p)return!0;if(e.length)return!1;let v=e;for(;v;){const e=v.data;if(e){const t=Q(e,i,n,Math.max(0,o));null!=t&&(t<d||t===d&&s.indexOf(e.id)>s.indexOf(a?.id??""))&&(a=e,d=t)}v=v.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const s=e.readState();return 0===s.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=s.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=ie().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};var oe=["data","scene-geometry","data-paint","accessibility","evidence"],re=["scene-geometry","data-paint","accessibility","evidence"],ae=["overlay","accessibility","evidence"],de=(e,t)=>({retainedData:e,invalidations:t}),he=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],ce=["scene-geometry","data-paint","accessibility","evidence"],le=[],ue={engine:de("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:de("preserve",ce),colliders:de("preserve",ce),sediment:de("preserve",ce),bodyBudget:de("preserve",he),bodyLimit:de("preserve",he),eviction:de("preserve",he),fixedDt:de("preserve",le),maxDeltaSeconds:de("preserve",le),maxSubsteps:de("preserve",le),settleStepLimit:de("preserve",le),timeScale:de("preserve",le),observation:de("preserve",le)},pe=de("preserve",he);function ye(e){let t="preserve";const s=new Set;for(const i of e){const e=ue[i]??pe;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)s.add(t)}return{retainedData:t,invalidations:s}}var ve=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function me(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&ve.every(s=>e[s]===t[s]))}function fe(e,t,s,i){return e||!t?"paused":s||!i?"running":"settled"}function ge(e,t,s,i,n,o){const r={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===s)return r;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return r;const d=n.length-a;if(d<=0)return r;const h=function(e,t,s){if("sleeping-first"!==t)return s.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],o=[];for(const e of s)i.get(e)?n.push(e):o.push(e);return[...n,...o]}(e,s,n),c=h.slice(0,d);if(0===c.length)return r;const l=function(e,t,s,i){const n=new Map(e.readState().map(e=>[e.id,e])),o=[];for(const e of s){const s=n.get(e);if(!s)continue;const r=t.add(s);r&&(o.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:s.datum,x:s.x,y:s.y,binId:r.id,count:r.count,total:r.total}))}return o}(e,t,c,o);e.remove(c);const u=new Set(c);return{evicted:c,sedimented:l,liveBodyOrder:n.filter(e=>!u.has(e))}}var xe=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,s){if(s>0)return void(this.seconds=0);const i=e.readState(this.scratch),n=this.speed*this.speed;let o=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=n){o=!1;break}this.seconds=o?this.seconds+Math.max(0,t):0}};var be=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new ne,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new se,this.simulationState="settled",this.visible=!0,this.quiescence=new xe;const{bodyBudget:t,colliders:s,engine:i,kernel:n,observation:o,sediment:r,...a}=e;this.config={...X,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=K(o),this.sediment=new P(r??!1),this.world=O(i,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),s&&this.world.setColliders(W(s))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(s=>"kernel"===s?!me(e.kernel,t.kernel):e[s]!==t[s])}(e,this.configInput),{colliders:s,bodyBudget:i,engine:n,kernel:o,observation:r,sediment:a,...d}=e;if(this.config={...this.config,...d},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=O(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!me(o,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...o,gravity:{...e.options.gravity,...o.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}r&&(this.observation=K(r,this.observation)),this.sediment.updateConfig(a),s&&(this.world.setColliders(W(s)),this.revision+=1),this.configInput={...this.configInput,...e};const h=ye(t);this.updateResults.record({kind:"config",keys:t},h.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(W(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ye(["colliders"]).invalidations)}enqueue(e,t){const s=Array.isArray(e)?e:[e],i=t?$(s,{...t,startAt:t.startAt??this.elapsedSeconds}):s;for(const e of i)this.queue.push({...H(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(_),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?oe:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(H(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},oe)}materializeDueSpawns(){const e=this.revision,t=[],s=[];return this.spawnDue(t,s),0===t.length||(this.observeBodyBudget(s),this.evictOverflow(s),this.syncSimulationState(s),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?oe:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},oe)}tick(e){const t=this.revision,s=[],i=[],n=[],o=[],r=[];if(this.paused||!this.visible){const e=this.result(0,s,i,n,o,r,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(s,r);const d=this.observeBodyBudget(r),h=this.evictOverflow(r);i.push(...h.evicted),n.push(...h.sedimented),this.syncSimulationState(r),this.accumulator+=a;let c=0;for(;this.accumulator>=this.config.fixedDt&&c<this.config.maxSubsteps;){this.world.step(this.config.fixedDt);const e=this.world.events();o.push(...e),this.observeKernelEvents(e,r),this.observeSensorTransitions(r),this.accumulator-=this.config.fixedDt,c+=1}c===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,s.length),(c>0||s.length>0||i.length>0||n.length>0||o.length>0)&&(this.revision+=1);const l=this.result(c,s,i,n,o,r,void 0,d);return this.updateResults.record({kind:"tick",count:c},this.revision!==t?s.length||i.length||n.length?oe:re:[]),l}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit){return this.runSettle(e,!0)}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t){const s=this.revision,i=[],n=[],o=[],r=[],a=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,i,n,o,r,a??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(i,a);const d=this.observeBodyBudget(a),h=this.evictOverflow(a);n.push(...h.evicted),o.push(...h.sedimented),this.syncSimulationState(a),i.length>0&&this.quiescence.reset();const c=t?{spawned:i,evicted:n,sedimented:o,events:r,observations:a}:{spawned:i},{steps:l,budget:u}=function(e,t,s){let i,n=0;for(;n<t&&(e.queueSize()>0||!e.atRest());){e.advanceTime(e.fixedDt);const t=[];if(e.spawnDue(t,s.observations),t.length>0){s.spawned.push(...t),i=e.observeBodyBudget(s.observations);const n=e.evictOverflow(s.observations);s.evicted?.push(...n.evicted),s.sedimented?.push(...n.sedimented)}e.step(e.fixedDt);const o=e.drainEvents();s.events&&(s.events.push(...o),e.observeKernelEvents(o,s.observations),e.observeSensorTransitions(s.observations)),n+=1,e.refreshQuiescence(e.fixedDt,t.length)}return{steps:n,budget:i}}(this.settleHost(),e,c),p=i.length+n.length+o.length>0;(l>0||p||r.length>0)&&(this.revision+=1);const y=this.result(l,i,n,o,r,a??[],void 0,u??d);return this.updateResults.record({kind:"settle",count:l},this.revision===s?[]:p?oe:re),y}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return function(e,t={}){const{baselineY:s=0,binWidth:i=24,gap:n=2,maxHeight:o=80,value:r="count",x:a}=t,d=Math.max(1,...e.map(e=>e[r]));return e.map((e,t)=>{const h=Math.max(0,e[r]/d*o),c=a?.(e,t)??t*(i+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:c,y:s-h,width:i,height:h,meanX:e.x.mean,meanY:e.y.mean}})}(this.readSediment(),e)}hitTest(e,t,s=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,s)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:s,chartId:i,...n}=e,o={...n,timestamp:t??this.elapsedSeconds,chartType:s??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(o),this.updateResults.record({kind:"update",count:1},["evidence"]),o}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?ae:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?ae:[])}remove(e){const t=new Set(e),s=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const n=e.filter(e=>s.has(e)||i.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?oe:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},re),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},re)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},re)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,s,i)=>e.applyImpulse(t,s,i),clear:()=>e.clear(),hitTest:(t,s,i)=>e.hitTest(t,s,i),pause:()=>e.setPaused(!0),push:(t,s)=>e.enqueue(t,s),pushMany:(t,s)=>e.enqueue(t,s),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:G(this.bodyBudget),config:{...this.config,kernel:U(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(z),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:G(e.bodyBudget??{}),kernel:U(e.world.options)},this.bodyBudget=G(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(z).sort(_),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??fe(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},oe)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds;){const s=this.queue.shift();if(!s)return;this.spawnOne(s,t),e.push(s.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const s=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:s?.datum??e.datum,x:s?.x??e.x,y:s?.y??e.y},t)}result(e,t,s,i,n,o,r,a=this.evaluateBodyBudget()){this.syncSimulationState(o);const d=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:s,events:n,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:r??(this.queue.length>0||!this.atRest()),sleeping:d,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,s){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);s.emit({type:"physics-settle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,s){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const n=new Map(e.readState().map(e=>[e.id,e])),o=(e,t)=>{const{sensorId:i,bodyId:o}=J(t),r=s.observation.sensors[i],a=n.get(o);s.emit({type:"enter"===e?r?.enterType??"physics-bin-enter":r?.exitType??"physics-bin-exit",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:o,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:r?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||o("enter",e);for(const e of Array.from(t).sort())i.has(e)||o("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const s of e)t.has(J(s).bodyId)&&e.delete(s)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return Y({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const s=`${t.state}:${t.action}`;return s===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=s,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=fe(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const s=this.simulationState;this.simulationState=t,function(e,t,s){s.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||s.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,simulationState:t,previousSimulationState:e})}(s,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:s,liveBodyOrder:i}=ge(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:s}}};function Se(e,t){return function(e,t,s=[],i){const n=new Array(t.length),o=new Float32Array(2*t.length),r=new Float32Array(2*t.length),a=new Uint8Array(t.length);return t.forEach((e,t)=>{const s=2*t;n[t]=e.id,o[s]=e.x,o[s+1]=e.y,r[s]=e.vx,r[s+1]=e.vy,a[t]=e.sleeping?1:0}),{bodies:t,ids:n,positions:o,result:e,sediment:s,sleeping:a,snapshot:i,velocities:r}}(t,e.readBodies(),e.readSediment(),e.snapshot())}function we(e){return Se(e,e.tick(0))}var Ie=function(){let e=new be;return{handle(t){switch(t.type){case"init":return e=new be(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:we(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:we(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:we(e)};case"tick":return{type:"frame",frame:Se(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:Se(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:we(e)};case"clear":return e.clear(),{type:"frame",frame:we(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:we(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:we(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:we(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:we(e)}}}}}();function Be(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:{message:String(e)}}self.onmessage=e=>{const t=e.data;try{const e=Ie.handle(t.command);self.postMessage({ok:!0,payload:e,requestId:t.requestId},function(e){return"frame"===e.type||"removed"===e.type?[(t=e.frame).positions.buffer,t.velocities.buffer,t.sleeping.buffer]:[];var t}(e))}catch(e){self.postMessage({error:Be(e),ok:!1,requestId:t.requestId})}};
@@ -0,0 +1 @@
1
+ import{scaleTime as t}from"d3-scale";var e={static:{duplicateIds:"fatal",invalidSystemTime:"warn"},mcp:{duplicateIds:"fatal",invalidSystemTime:"warn"},push:{duplicateIds:"warn",invalidSystemTime:"strip"}};function n(t="static"){return e[t]??e.static}var o=new Set(["invalid-domain","missing-node","backward-edge","invalid-edge-time","invalid-value","invalid-node-time"]);function s(t){return"fatal"===t.severity||"warn"===t.severity?t.severity:o.has(t.kind)?"fatal":"warn"}function i(t){const{desired:e,minGaps:n,weights:o}=t,s=e.length;if(0===s)return[];if(n.length!==Math.max(0,s-1))throw new Error("placeWithMinGap: minGaps must have desired.length - 1 entries");const i=new Array(s).fill(0);for(let t=1;t<s;t++)i[t]=i[t-1]+Math.max(0,Number.isFinite(n[t-1])?n[t-1]:0);const a=[];for(let t=0;t<s;t++){const n=Math.max(Number.EPSILON,Number.isFinite(o?.[t])?o[t]:1),s=(Number.isFinite(e[t])?e[t]:0)-i[t];for(a.push({start:t,end:t,weight:n,mean:s});a.length>1;){const t=a[a.length-1],e=a[a.length-2];if(e.mean<=t.mean)break;const n=e.weight+t.weight;a.splice(a.length-2,2,{start:e.start,end:t.end,weight:n,mean:(e.mean*e.weight+t.mean*t.weight)/n})}}const r=Number.isFinite(t.min)?t.min:-1/0,l=Number.isFinite(t.max)?t.max-i[s-1]:1/0,c=l<r?r:l,u=new Array(s);for(const t of a){const e=Math.max(r,Math.min(c,t.mean));for(let n=t.start;n<=t.end;n++)u[n]=e+i[n]}return u}function a(t,e){let n=0,o=t.length-1,s=-1;for(;n<=o;){const i=n+o>>>1;t[i].at<=e?(s=i,n=i+1):o=i-1}return s<0?{at:e,before:0,after:0}:t[s]}function r(t,e=0){if(0===t.length)return{adjacentClearance:[],positions:[]};const n=[],o=[0];for(let s=0;s<t.length-1;s++){const i=t[s],r=t[s+1],l=[...new Set([...i.map(t=>t.at),...r.map(t=>t.at)])].sort((t,e)=>t-e);let c=0;for(const t of l){const e=a(i,t),n=a(r,t);c=Math.max(c,e.after+n.before)}n.push(c),o.push(o[o.length-1]+c+e)}return{adjacentClearance:n,positions:o}}function l(t,e,n,o={}){let s=[...t];if(s.length<=1)return s;let i=[...s],a=n(s),r=1;const l=Math.max(0,o.passes??6),c=Math.max(1,o.maxEvaluations??1/0);for(let t=0;t<l&&r<c;t++){const t=new Map(s.map((t,e)=>[t,e])),l=new Map,c=new Map;for(const n of e){const e=t.get(n.source),o=t.get(n.target);if(null==e||null==o)continue;const s=Number.isFinite(n.weight)&&n.weight>0?n.weight:1;l.set(n.source,(l.get(n.source)??0)+o*s),c.set(n.source,(c.get(n.source)??0)+s),l.set(n.target,(l.get(n.target)??0)+e*s),c.set(n.target,(c.get(n.target)??0)+s)}s=s.map((t,e)=>({item:t,index:e,barycenter:(l.get(t)??e)/(c.get(t)??1)})).sort((t,e)=>t.barycenter-e.barycenter||(o.compare?.(t.item,e.item)??t.index-e.index)).map(t=>t.item);const u=n(s);if(r++,u<a)a=u,i=[...s];else if(u===a)break}return i}function c(t,e,n={}){const o=[...t],s=o.length;if(s<=1||s>(n.maxItems??8))return o;const i=Math.max(1,n.maxEvaluations??1/0);let a=0,r=[...o],l=1/0;const c=()=>{if(a>=i)return;const t=e(o);a++,t<l&&(l=t,r=[...o])};c();const u=new Array(s).fill(0);let f=0;for(;f<s&&a<i;)if(u[f]<f){const t=f%2==0?0:u[f];[o[t],o[f]]=[o[f],o[t]],c(),u[f]++,f=0}else u[f]=0,f++;return r}function u(t,e){return t<e?-1:t>e?1:0}function f(t){return t.occupants.map(t=>t.id).sort(u).join("\0")}function d(t,e,n=0){return t.slice(0,-1).map((o,s)=>{const i=t[s+1];return null!=o.group&&o.group===i.group?n:e})}function g(t,e){return t.map(t=>{const n=new Map;for(const o of t.occupants){const t=e[o.id];if(t)for(const e of t.samples){const t=n.get(e.t)??{before:0,after:0},o=e.boundaryOffset??0;n.set(e.t,{before:Math.max(t.before,e.topMass-o),after:Math.max(t.after,e.botMass+o)})}}return[...n].sort((t,e)=>t[0]-e[0]).map(([t,e])=>({at:t,...e}))})}function m(t,e,n){if(0===t.length)return[];const{padding:o,plotH:s,valueScale:i}=n,a=n.stackValueScale??i,r=d(t,o,n.groupPadding??0),l=[o+t[0].peak.topPeak*a];for(let n=1;n<t.length;n++)l.push(l[n-1]+e[n-1]*a+r[n-1]);const c=l[l.length-1]+t[t.length-1].peak.botPeak*a+o;if(c>s&&c>0){const t=s/c;for(let e=0;e<l.length;e++)l[e]*=t}return l}function p(t,e){const n=(t.boundaryOffset??0)*e,o=t.value*e;if("out"===t.kind){const s=t.sideMassBefore*e;return n+("top"===t.side?o/2-s:s-o/2)}const s=t.sideMassAfter*e;return n+("top"===t.side?o/2-s:s-o/2)}function h(t,e,n,o,s,a){const l=a.adjacentClearance?[...a.adjacentClearance]:r(g(o,n)).adjacentClearance,c=m(o,l,a);let u="hug"===a.lanePlacement?function(t,e,n,o,s,a,r){const l=t.length;if(0===l)return[];const{padding:c,plotH:u,valueScale:f}=r,g=d(t,c,r.groupPadding??0),h=s.map((t,e)=>t*f+g[e]),b=c+t[0].peak.topPeak*f,M=u-c-t[l-1].peak.botPeak*f;if(M-b<=h.reduce((t,e)=>t+e,0)+1e-6)return m(t,s,r);let y=1===l?[(b+M)/2]:[...a];for(let t=0;t<12;t++){const t=new Array(l).fill(0),s=new Array(l).fill(0);for(const i of n){const n=e[i.source],a=e[i.target];if(null==n||null==a||n===a)continue;const r=o[i.source]?.localAttachments.get(i.id),l=o[i.target]?.localAttachments.get(i.id);if(!r||!l)continue;const c=i.value>0&&Number.isFinite(i.value)?i.value:1,u=p(r,f),d=p(l,f);t[n]+=(y[a]+d-u)*c,s[n]+=c,t[a]+=(y[n]+u-d)*c,s[a]+=c}const a=i({desired:y.map((e,n)=>0===s[n]?e:.45*e+t[n]/s[n]*.55),minGaps:h,weights:s.map(t=>Math.max(1,t)),min:b,max:M});let r=0;for(let t=0;t<l;t++)r=Math.max(r,Math.abs(a[t]-y[t]));if(y=a,r<.01)break}return y}(o,s,e,n,l,c,a):[...c];if("hug"===a.lanePlacement){const n=e=>{const n={};for(const o of t)n[o.id]=e[s[o.id]];return n};b(n(u),e)>b(n(c),e)+1e-6&&(u=[...c])}const f={};for(const e of t)f[e.id]=u[s[e.id]];let h=1/0,M=-1/0;for(const e of t){const t=f[e.id],o=n[e.id];Number.isFinite(t)&&o&&(h=Math.min(h,t-o.topPeak*a.valueScale),M=Math.max(M,t+o.botPeak*a.valueScale))}return{adjacentClearance:l,centerlines:f,slotCenter:u,stackCenter:c,verticalUtilization:Number.isFinite(h)&&Number.isFinite(M)&&a.plotH>0?Math.max(0,Math.min(1,(M-h)/a.plotH)):0}}function b(t,e){let n=0;for(const o of e){const e=t[o.source],s=t[o.target];Number.isFinite(e)&&Number.isFinite(s)&&(n+=Math.abs(e-s)*(o.value>0?o.value:1))}return n}function M(t,e){const n=t?.samples;if(!n||0===n.length||e<n[0].t)return{top:0,bot:0};let o=0,s=n.length-1,i=0;for(;o<=s;){const t=o+s>>>1;n[t].t<=e?(i=t,o=t+1):s=t-1}const a=n[i].boundaryOffset??0;return{top:n[i].topMass-a,bot:n[i].botMass+a}}function y(t,e,n,o,s){const i=1-s;return i*i*i*t+3*i*i*s*e+3*i*s*s*n+s*s*s*o}function x(t,e){let n=0,o=1;for(let s=0;s<28;s++){const s=(n+o)/2;y(0,e,e,1,s)<t?n=s:o=s}return(n+o)/2}function w(t,e,n){const o=e+p(t,n),s=t.value*n/2;return[o-s,o+s]}function v(t,e,n,o){return Math.max(0,Math.min(e,o)-Math.max(t,n))/Math.max(1e-9,e-t)}function k(t,e,n,o,s,i,a){const{valueScale:r,domain:l,mode:c="quality"}=a,u="source"===a.ribbonLane?.85:"target"===a.ribbonLane?.15:.5;let f=0;for(const a of t){const t=o[a.source],d=o[a.target];if(null==t||null==d||Math.abs(t-d)<2)continue;const g=e[a.source]?.localAttachments.get(a.id),m=e[a.target]?.localAttachments.get(a.id);if(!g||!m)continue;const p=Math.max(a.startTime,l?.[0]??-1/0),h=Math.min(a.endTime,l?.[1]??1/0);if(!(h>p))continue;const[b,k]=w(g,s[a.source],r),[T,S]=w(m,s[a.target],r),N=Math.min(t,d)+1,O=Math.max(t,d)-1;for(let t=N;t<=O;t++){const o=n[t];if(!o)continue;const l=[p,h];if("quality"===c)for(const t of o.occupants)for(const n of e[t.id]?.samples??[])n.t>p&&n.t<h&&l.push(n.t);const d=t=>{const n=x((t-p)/(h-p),u),l=y(b,b,T,T,n),c=y(k,k,S,S,n);let f=0;for(const n of o.occupants){if(n.id===a.source||n.id===a.target)continue;const o=i[n.id];if(null!=o?.start&&t<o.start)continue;if(null!=o?.end&&t>o.end)continue;const u=M(e[n.id],t),d=s[n.id];f=Math.max(f,v(l,c,d-u.top*r,d+u.bot*r))}return f},g=[...new Set(l)].sort((t,e)=>t-e);let m=0;for(let t=0;t<g.length-1;t++){const e=g[t],n=g[t+1]-e;m+=(d(e+.25*n)+d(e+.5*n)+d(e+.75*n))/3*n}f+=m/(h-p)*(a.value>0?a.value:1)}}return f}function T(t,e,n,o,s,i,a,r,l,c,u="both",f){return{crossings:t,weightedLength:e,pixelLength:b(a,n),transitOcclusion:k(n,o,s,i,a,r,{valueScale:l,ribbonLane:u,domain:f,mode:"quality"}),verticalUtilization:c}}function S(t,e){return e?Math.max(e[0],Math.min(e[1],t)):t}function N(t,e){return t.map(t=>({t:S(t.t,e),topMass:t.topMass,botMass:t.botMass,...null!=t.boundaryOffset&&{boundaryOffset:t.boundaryOffset}}))}function O(t,e,n){const o=e+(t.boundaryOffset??0)*n,s=t.value*n;if("out"===t.kind){const e=t.sideMassBefore*n;if("top"===t.side){const t=o-e;return[t,t+s]}const i=o+e;return[i-s,i]}const i=t.sideMassAfter*n;if("top"===t.side){const t=o-i;return[t,t+s]}const a=o+i;return[a-s,a]}function P(t,e,n,o,s="temporal"){const i=e.incoming[t.id],a=e.outgoing[t.id],r=[];for(const t of i)r.push({time:t.endTime,delta:+t.value,edge:t,kind:"in",side:n.get(t.id).targetSide});for(const t of a)r.push({time:t.startTime,delta:-t.value,edge:t,kind:"out",side:n.get(t.id).sourceSide});const l={create:0,in:1,"transfer-out":2,"transfer-in":3,out:4},c=()=>{r.sort((t,e)=>t.time-e.time||(t.phase??0)-(e.phase??0)||(t.sequence??0)-(e.sequence??0)||(l[t.kind]??99)-(l[e.kind]??99)||((t,e)=>{if(!o||!t.edge||!e.edge||t.kind!==e.kind||t.side!==e.side)return 0;if("out"===t.kind){if(t.edge.target===e.edge.target&&t.edge.endTime===e.edge.endTime)return 0;const n=o.get(t.edge.id)?.target,s=o.get(e.edge.id)?.target;return"number"==typeof n&&Number.isFinite(n)&&"number"==typeof s&&Number.isFinite(s)&&n!==s?"top"===t.side?n-s:s-n:0}if("in"===t.kind){if(t.edge.source===e.edge.source&&t.edge.startTime===e.edge.startTime)return 0;const n=o.get(t.edge.id)?.source,s=o.get(e.edge.id)?.source;return"number"==typeof n&&Number.isFinite(n)&&"number"==typeof s&&Number.isFinite(s)&&n!==s?"top"===t.side?s-n:n-s:0}return 0})(t,e)||u(t.edge?.id??"",e.edge?.id??"")||u(t.side,e.side)||t.delta-e.delta)},f=r.length?function(t,e=1/0){let n=e;for(const e of t)e<n&&(n=e);return n}(r.map(t=>t.time)):null,d=Array.isArray(t.xExtent)&&Number.isFinite(t.xExtent[0])?t.xExtent[0]:null,g=null!=d?d-1:null!=f&&Number.isFinite(f)?f-1:null;c();let m=null,p=0;for(const t of r)t.time!==m&&(m=t.time,p=0),t.sequence=p++;const h=t=>({time:t.time,phase:0,sequence:t.sequence??0}),b=[];let M=0,y=0;for(const t of r)if("out"===t.kind){const e=Math.abs(t.delta);let n=e-("top"===t.side?M:y);if(n>0){const e="top"===t.side?"bot":"top",o="top"===e?M:y,s=Math.min(n,o);if(s>0){const o=h(t);b.push({...o,delta:-s,kind:"transfer-out",side:e}),b.push({...o,delta:+s,kind:"transfer-in",side:t.side}),"top"===e?M-=s:y-=s,"top"===t.side?M+=s:y+=s,n-=s}n>0&&null!==g&&(b.push({time:g,delta:+n,kind:"create",side:t.side}),"top"===t.side?M+=n:y+=n)}"top"===t.side?M-=e:y-=e}else if("in"===t.kind){const e=Math.abs(t.delta);"top"===t.side?M+=e:y+=e}r.push(...b),c();let x=0,w=0,v=0,k=0,T=0,S=0;const N=[],O=new Map,P=t=>{N.push({t:t,topMass:x,botMass:w,...Math.abs(v)>1e-12&&{boundaryOffset:v}})},F=()=>{k=Math.max(k,x+w),T=Math.max(T,x-v),S=Math.max(S,w+v)};for(const t of r){if("transfer-out"!==t.kind&&"transfer-in"!==t.kind&&P(t.time),("in"===t.kind||"out"===t.kind)&&t.edge){const e="top"===t.side?x:w,n=e+t.delta;O.set(t.edge.id,{side:t.side,time:t.time,sideMassBefore:e,sideMassAfter:n,kind:t.kind,value:Math.abs(t.delta),...Math.abs(v)>1e-12&&{boundaryOffset:v}})}"top"===t.side?x+=t.delta:w+=t.delta,"transfer-in"===t.kind?(v+="top"===t.side?t.delta:-t.delta,F(),P(t.time)):"transfer-out"!==t.kind&&(F(),"out"===t.kind&&x+w<=1e-12&&(v=0),P(t.time))}const A=[];let I=0;for(;I<N.length;){let t=I;for(;t+1<N.length&&N[t+1].t===N[I].t;)t++;A.push(N[I]);for(let e=I+1;e<=t;e++){const t=A[A.length-1];N[e].topMass===t.topMass&&N[e].botMass===t.botMass&&(N[e].boundaryOffset??0)===(t.boundaryOffset??0)||A.push(N[e])}I=t+1}const E=Array.isArray(t.xExtent)&&Number.isFinite(t.xExtent[1])?t.xExtent[1]:null;let $=null;for(const t of a)null!=t.systemInTime&&Number.isFinite(t.systemInTime)&&t.systemInTime<t.startTime&&(null===$||t.systemInTime<$)&&($=t.systemInTime);let L=null;for(const t of i)null!=t.systemOutTime&&Number.isFinite(t.systemOutTime)&&t.systemOutTime>t.endTime&&(null===L||t.systemOutTime>L)&&(L=t.systemOutTime);if(A.length>0){const t=A[A.length-1],e=Math.max(null!=E?E:-1/0,null!=L?L:-1/0);Number.isFinite(e)&&e>t.t&&t.topMass+t.botMass>0&&A.push({t:e,topMass:t.topMass,botMass:t.botMass,...null!=t.boundaryOffset&&{boundaryOffset:t.boundaryOffset}});const n=A[0],o=A.find(t=>t.topMass+t.botMass>0);let s,i=1/0;null!=d&&Number.isFinite(d)&&d<n.t&&n.topMass+n.botMass>0&&(i=d,s=n),o&&null!=$&&Number.isFinite($)&&$<o.t&&$<i&&(i=$,s=o),s&&Number.isFinite(i)&&A.unshift({t:i,topMass:s.topMass,botMass:s.botMass,...null!=s.boundaryOffset&&{boundaryOffset:s.boundaryOffset}})}let B=A;if("max"===s&&null!=d&&null!=E&&E>d){let t,e=0;for(const n of A){const o=n.topMass+n.botMass;o>e&&(e=o,t=n)}if(t){const e={topMass:t.topMass,botMass:t.botMass,...null!=t.boundaryOffset&&{boundaryOffset:t.boundaryOffset}};B=[...A.filter(t=>t.t<d),{t:d,...e},{t:E,...e},...A.filter(t=>t.t>E)]}}return{samples:B,peak:k,topPeak:T,botPeak:S,localAttachments:O}}function F(t){const e={};return t.forEach((t,n)=>{for(const o of t.occupants)e[o.id]=n}),e}function A(t,e,n){t.splice(0,t.length,...n);const o=F(n);for(const t of Object.keys(e))delete e[t];Object.assign(e,o)}function I(t){const e=new Map,n=[];t.forEach((t,o)=>{if(!t.group)return void n.push({anchor:o,stableId:f(t),slots:[t]});const s=e.get(t.group)??{indexes:[],slots:[]};s.indexes.push(o),s.slots.push(t),e.set(t.group,s)});for(const[t,o]of e)n.push({anchor:o.indexes.reduce((t,e)=>t+e,0)/o.indexes.length,stableId:`${t}\0${o.slots.map(f).join("\0")}`,slots:o.slots});return n.sort((t,e)=>t.anchor-e.anchor||u(t.stableId,e.stableId))}function E(t){return t.some(t=>t.group)?I(t).flatMap(t=>t.slots):[...t]}function $(t){return t.flatMap(t=>t.slots)}function L(t,e,n){const o=new Map;return t.forEach((t,e)=>{for(const n of t.slots)o.set(n,e)}),t.map((t,s)=>{if(t.slots.length<=1)return t;const i=new Map;for(const e of t.slots)i.set(e,0);for(const t of e){const e=o.get(t.source),n=o.get(t.target);if(null==e||null==n)continue;const a=Number.isFinite(t.weight)&&t.weight>0?t.weight:1;if(e===s&&n!==s){const e=n>s?1:-1;i.set(t.source,(i.get(t.source)??0)+a*e)}else if(n===s&&e!==s){const n=e>s?1:-1;i.set(t.target,(i.get(t.target)??0)+a*n)}}const a=[...t.slots].sort((t,e)=>(i.get(t)??0)-(i.get(e)??0)||n(t,e));return{...t,slots:a}})}function B(t,e){t.some(t=>t.group)&&A(t,e,E(t))}function z(t,e){return t.source!==e.source&&t.target!==e.target&&t.source!==e.target&&t.target!==e.source&&Math.max(t.startTime,e.startTime)<Math.min(t.endTime,e.endTime)}function C(t,e){return function(t,e,n=()=>!0){let o=0;for(let s=0;s<t.length;s++){const[i,a]=e(t[s]);for(let r=s+1;r<t.length;r++){if(!n(t[s],t[r]))continue;const[l,c]=e(t[r]);(i-l)*(a-c)<0&&o++}}return o}(e,e=>[t[e.source],t[e.target]],z)}function X(t,e){let n=0;for(const o of e){const e=t[o.source],s=t[o.target];null!=e&&null!=s&&(n+=Math.abs(e-s)*(o.value>0?o.value:1))}return n}function H(t,e,n){const[o,s]=n.get(t.first),[i,a]=n.get(t.second);return(e.get(o)-e.get(i))*(e.get(s)-e.get(a))<0?1:0}var D=t=>{let e=1;for(let n=2;n<=t;n++)e*=n;return e},j=828*D(8),Y=3e3;function q(t,e,n,o,s,i,a){const d=[...s],m=new Map(s.map(t=>[t,f(t)])),p=new Map;for(const t of s)for(const e of t.occupants)p.set(e.id,t);const M=new Map,y=[];for(const t of e){const e=p.get(t.source),n=p.get(t.target);e&&n&&(M.set(t,[e,n]),e!==n&&y.push({source:e,target:n,weight:t.value}))}const x=[];for(let t=0;t<e.length;t++)if(M.has(e[t]))for(let n=t+1;n<e.length;n++){if(!M.has(e[n])||!z(e[t],e[n]))continue;const o=new Set([...M.get(e[t]),...M.get(e[n])]);x.push({index:x.length,first:e[t],second:e[n],involvedSlots:o})}const w=new Map;for(const t of s)w.set(t,[]);for(const t of x)for(const e of t.involvedSlots)w.get(e)?.push(t);const v=new Uint32Array(x.length);let T=0;const S=e.reduce((t,e)=>t+(e.value>0?e.value:1),0),N=a.plotH/Math.max(1,s.length),O=s.reduce((t,e)=>t+e.peak.topPeak+e.peak.botPeak,0),P=Math.max(1,S)*(Math.max(1,a.plotH)+N*Math.max(O,s.length)+1e-6*Math.max(1,s.length-1))+1,B=4*N,C={fullCrossing:0,localCrossing:0},q=new Map,V=(t,e)=>{let o=q.get(t);o||(o=new Map,q.set(t,o));const s=o.get(e);if(null!=s)return s;const i=function(t,e,n){return r(g([t,e],n)).adjacentClearance[0]??0}(t,e,n);return o.set(e,i),i},U=new Map(s.map((t,e)=>[t,e])),W=e.flatMap(t=>{const e=M.get(t);return e?[{source:U.get(e[0]),target:U.get(e[1]),weight:t.value>0?t.value:1}]:[]}),R=new Map;for(const t of e){const e=M.get(t);e&&R.set(t,{source:U.get(e[0]),target:U.get(e[1])})}const _=new Map,G=new Map;for(const t of e)_.has(t.source)||_.set(t.source,new Set),G.has(t.target)||G.set(t.target,new Set),_.get(t.source).add(t.target),G.get(t.target).add(t.source);const Z=e.flatMap(t=>{if(!(t=>{const e=new Set([..._.get(t.source)??[],...G.get(t.source)??[]]),n=new Set([..._.get(t.target)??[],...G.get(t.target)??[]]);return 1===_.get(t.source)?.size&&_.get(t.source).has(t.target)||1===e.size&&e.has(t.target)||1===n.size&&n.has(t.source)})(t))return[];const e=R.get(t);return e&&e.source!==e.target?[{source:e.source,target:e.target,weight:t.value>0?t.value:1}]:[]}),Q=t=>{let e=0;for(const n of Z)e+=Math.max(0,Math.abs(t[n.source]-t[n.target])-1)*n.weight;return e*B},J=t=>{const e=new Int16Array(s.length);for(let n=0;n<t.length;n++)e[U.get(t[n])]=n;return Q(e)},K=x.map(t=>{const e=R.get(t.first),n=R.get(t.second);return[e.source,e.target,n.source,n.target]}),tt=new Int16Array(s.length),et=new Float64Array(s.length),nt=new Float64Array(s.length+1),ot=t=>{for(let e=0;e<t.length;e++)tt[U.get(t[e])]=e;let e=0;for(const[t,n,o,s]of K)(tt[t]-tt[o])*(tt[n]-tt[s])<0&&e++;if(t.length>0){const e=U.get(t[0]);et[e]=a.padding+t[0].peak.topPeak*a.valueScale;for(let e=1;e<t.length;e++){const n=U.get(t[e-1]),o=U.get(t[e]);et[o]=et[n]+V(t[e-1],t[e])*a.valueScale+a.padding}const n=U.get(t[t.length-1]),o=et[n]+t[t.length-1].peak.botPeak*a.valueScale+a.padding;if(o>a.plotH&&o>0){const t=a.plotH/o;for(let e=0;e<et.length;e++)et[e]*=t}}nt[0]=0;for(let e=0;e<t.length;e++)nt[e+1]=nt[e]+t[e].peak.topPeak+t[e].peak.botPeak;let n=0,o=0,s=0;for(const t of W){const e=tt[t.source],i=tt[t.target];if(n+=Math.abs(e-i)*t.weight,o+=Math.abs(et[t.source]-et[t.target])*t.weight,Math.abs(e-i)>=2){const n=Math.min(e,i)+1,o=Math.max(e,i);s+=(nt[o]-nt[n])*t.weight}}return e*P+o+s*N+Q(tt)+1e-6*n},st=(t,n)=>{const o=new Array(t.length+1).fill(0);for(let e=0;e<t.length;e++)o[e+1]=o[e]+t[e].peak.topPeak+t[e].peak.botPeak;let s=0;for(const t of e){const e=n[t.source],i=n[t.target];if(null==e||null==i||Math.abs(e-i)<2)continue;const a=Math.min(e,i)+1;s+=(o[Math.max(e,i)]-o[a])*(t.value>0?t.value:1)}return s},it=o=>{const s=F(o),i=o.slice(0,-1).map((t,e)=>V(t,o[e+1])),r=h(t,e,n,o,s,{plotH:a.plotH,padding:a.padding,valueScale:a.valueScale,lanePlacement:a.lanePlacement??"stack",groupPadding:a.groupPadding,adjacentClearance:i});return{map:s,geometry:r,weightedLength:X(s,e),pixelLength:b(r.centerlines,e),transitOcclusion:st(o,s)}},at=(t,e,n)=>({crossings:t,weightedLength:e.weightedLength,pixelLength:e.pixelLength,transitOcclusion:e.transitOcclusion,cost:t*P+e.pixelLength+e.transitOcclusion*N+J(n)+1e-6*e.weightedLength}),rt=(t,e)=>{let n=e;if(null==n){const e=new Map(t.map((t,e)=>[t,e]));n=x.reduce((t,n)=>t+H(n,e,M),0),C.fullCrossing++}return at(n,it(t),t)},lt=(t,s,i="quality")=>{let r=s;if(null==r){const e=new Map(t.map((t,e)=>[t,e]));r=x.reduce((t,n)=>t+H(n,e,M),0),C.fullCrossing++}const l=it(t);return at(r,{...l,transitOcclusion:k(e,n,t,l.map,l.geometry.centerlines,o,{valueScale:a.valueScale,ribbonLane:a.ribbonLane,domain:a.domain,mode:i})},t)};let ct=[...d];const ut=(t,e)=>u(m.get(t),m.get(e)),ft=function(t){const e=new Set;for(const n of t)if(n.group){if(e.has(n.group))return!0;e.add(n.group)}return!1}(ct),dt=t=>{const e=(t=>{const e=l(t,y,t=>rt(t).cost,{passes:6,compare:ut,maxEvaluations:Y});let n=rt(e),o=Y;for(let t=0;t<6&&o>0;t++){let s=!1;const i=Array.from({length:e.length-1},(t,e)=>e);t%2==1&&i.reverse();for(const t of i){if(o--<=0)break;const i=e[t],a=e[t+1],r=new Map(e.map((t,e)=>[t,e]));let l=0;const c=[];T++;for(const t of[...w.get(i)??[],...w.get(a)??[]])v[t.index]!==T&&(v[t.index]=T,c.push(t),l+=H(t,r,M));[e[t],e[t+1]]=[a,i];const u=new Map(r);u.set(i,t+1),u.set(a,t);let f=0;for(const t of c)f+=H(t,u,M);C.localCrossing+=c.length;const d=rt(e,n.crossings-l+f);d.cost<n.cost?(n=d,s=!0):[e[t],e[t+1]]=[i,a]}if(!s)break}return e})(t);if((t.length<=8?D(t.length)*(t.length+W.length+K.length):1/0)>j)return e;const n=c(t,ot,{maxItems:8,maxEvaluations:5e4}),o=lt(n),s=lt(e);return o.crossings!==s.crossings&&o.crossings<s.crossings?n:e},gt=t=>{let e=I(t);if(e.length<=1)return $(e);const n=t=>rt($(t)).cost;e=I(dt(t)),e=L(e,y,ut);const o=function(t,e){const n=new Map;for(const e of t)for(const t of e.slots)n.set(t,e);const o=new Map;for(const t of e){const e=n.get(t.source),s=n.get(t.target);if(!e||!s||e===s)continue;const i=Number.isFinite(t.weight)&&t.weight>0?t.weight:1,a=e.stableId<s.stableId?`${e.stableId}\0${s.stableId}`:`${s.stableId}\0${e.stableId}`,r=o.get(a);r?r.weight=(r.weight??0)+i:o.set(a,{source:e,target:s,weight:i})}return[...o.values()]}(e,y);e=l(e,o,n,{passes:6,compare:(t,e)=>u(t.stableId,e.stableId),maxEvaluations:Y}),e=function(t,e,n={}){const o=[...t];if(o.length<=1)return o;let s=e(o),i=1;const a=Math.max(0,n.passes??6),r=Math.max(1,n.maxEvaluations??1/0);for(let t=0;t<a&&i<r;t++){let t=!1;for(let n=0;n<o.length-1&&i<r;n++){[o[n],o[n+1]]=[o[n+1],o[n]];const a=e(o);i++,a<s?(s=a,t=!0):[o[n],o[n+1]]=[o[n+1],o[n]]}if(!t)break}return o}(e,n,{passes:8,maxEvaluations:Y});if((e.length<=8?D(e.length)*(e.length+W.length+K.length):1/0)<=j){const t=c(e,t=>ot($(t)),{maxItems:8,maxEvaluations:5e4}),n=$(t),o=$(e),s=lt(n),i=lt(o);s.crossings!==i.crossings?e=s.crossings<i.crossings?t:e:s.cost<i.cost&&(e=t)}return e=L(e,y,ut),$(e)},mt="geometry-refine"===a.mode;if(mt||"crossing-min"!==a.laneOrder&&"crossing-min+inside-out"!==a.laneOrder){if(!mt&&"inside-out"===a.laneOrder)if(ft){const t=I(ct),e=t=>t.slots.reduce((t,e)=>t+e.peak.topPeak+e.peak.botPeak,0),n=[...t].sort((t,n)=>e(n)-e(t)||u(t.stableId,n.stableId)),o=new Array(n.length);let s=Math.floor((n.length-1)/2)-1,i=Math.floor((n.length-1)/2)+1;n.length>0&&(o[Math.floor((n.length-1)/2)]=n[0]);for(let t=1;t<n.length;t++)t%2==1&&i<n.length?o[i++]=n[t]:s>=0?o[s--]=n[t]:o[i++]=n[t];ct=$(o)}else{const t=[...ct].sort((t,e)=>{const n=t.peak.topPeak+t.peak.botPeak;return e.peak.topPeak+e.peak.botPeak-n||ut(t,e)}),e=new Array(t.length);let n=Math.floor((t.length-1)/2)-1,o=Math.floor((t.length-1)/2)+1;t.length>0&&(e[Math.floor((t.length-1)/2)]=t[0]);for(let s=1;s<t.length;s++)s%2==1&&o<t.length?e[o++]=t[s]:n>=0?e[n--]=t[s]:e[o++]=t[s];ct=e}}else ct=ft?gt(ct):dt(ct);if(!mt&&"crossing-min+inside-out"===a.laneOrder&&ct.length>1)if(ft){const t=I(ct);let e=rt($(t)),n=$(t),o=e;const s=Math.floor((t.length-1)/2),i=t=>t.slots.reduce((t,e)=>t+e.peak.topPeak+e.peak.botPeak,0),a=[...t].sort((t,e)=>i(e)-i(t)||u(t.stableId,e.stableId));for(const i of a){const a=t.indexOf(i);if(a===s)continue;t.splice(a,1),t.splice(s,0,i);const r=$(t),l=rt(r);l.cost<=e.cost?(e=l,l.cost<o.cost&&(n=r,o=l)):(t.splice(s,1),t.splice(a,0,i))}ct=n}else{let t=rt(ct),e=[...ct],n=t;const o=Math.floor((ct.length-1)/2),s=[...ct].sort((t,e)=>e.peak.topPeak+e.peak.botPeak-(t.peak.topPeak+t.peak.botPeak)||ut(t,e));for(const i of s){const s=ct.indexOf(i);if(s===o)continue;ct.splice(s,1),ct.splice(o,0,i);const a=rt(ct);a.cost<=t.cost?(t=a,a.cost<n.cost&&(e=[...ct],n=a)):(ct.splice(o,1),ct.splice(s,0,i))}ct=e}if((mt||"crossing-min"===a.laneOrder||"crossing-min+inside-out"===a.laneOrder)&&ct.length>1)if(ft){let t=I(ct),e=lt($(t),void 0,"score");for(let n=0;n<6&&t.length>1;n++){let n=!1;for(let o=0;o<t.length-1;o++){[t[o],t[o+1]]=[t[o+1],t[o]];const s=$(t),i=lt(s,void 0,"score");i.cost<e.cost?(ct=s,e=i,n=!0):[t[o],t[o+1]]=[t[o+1],t[o]]}if(!n)break}t=L(I(ct),y,ut),ct=$(t)}else{let t=lt(ct,void 0,"score");for(let e=0;e<ct.length-1;e++){const n=ct[e],o=ct[e+1],s=new Map(ct.map((t,e)=>[t,e]));let i=0;const a=[];T++;for(const t of[...w.get(n)??[],...w.get(o)??[]])v[t.index]!==T&&(v[t.index]=T,a.push(t),i+=H(t,s,M));[ct[e],ct[e+1]]=[o,n];const r=new Map(s);r.set(n,e+1),r.set(o,e);let l=0;for(const t of a)l+=H(t,r,M);C.localCrossing+=a.length;const c=lt(ct,t.crossings-i+l,"score");c.cost<t.cost?t=c:[ct[e],ct[e+1]]=[n,o]}}const pt=E(d);ct=E(ct);let ht=lt(ct);const bt=lt(pt);if(mt){const t=J(pt),e=J(ct);(ht.crossings>bt.crossings||ht.crossings===bt.crossings&&e>t+1e-9||ht.cost>bt.cost)&&(ct=pt,ht=bt)}else ht.cost>bt.cost&&(ct=pt,ht=bt);return A(s,i,ct),{before:bt,after:ht,initialOrder:d.map(t=>m.get(t)),evaluations:C}}function V(t,e,n){const o=t.map(t=>{const o=t.occupants.map(t=>({id:t.id,end:n[t.id]?.end??t.end}));let s=0,i=0;for(const t of o){const n=e[t.id];s=Math.max(s,n?.topPeak||0),i=Math.max(i,n?.botPeak||0)}return{occupants:o,peak:{topPeak:s,botPeak:i},...null!=t.group?{group:t.group}:{}}}),s={};return o.forEach((t,e)=>{for(const n of t.occupants)s[n.id]=e}),{slots:o,slotByNode:s}}var U=new Map;var W=1e-9,R=1e5;function _(t,e){let n=1/0,o=-1/0;for(const e of t?.samples??[])e.topMass+e.botMass<=W||(n=Math.min(n,e.t),o=Math.max(o,e.t));return Number.isFinite(n)&&Number.isFinite(o)?(null!=e.start&&(n=Math.max(n,e.start)),null!=e.end&&(o=Math.min(o,e.end)),o>=n?{start:n,end:o}:{start:null,end:null}):{start:null,end:null}}function G(t,e){return null!=t.start&&null!=t.end&&null!=e.start&&null!=e.end&&!(t.end<=e.start||e.end<=t.start)}function Z(t,e){return u(t,e)<=0?`${t}\0${e}`:`${e}\0${t}`}function Q(t){const e=new Map,n=new Map;for(const o of t)n.has(o.source)||n.set(o.source,new Set),e.has(o.target)||e.set(o.target,new Set),n.get(o.source).add(o.target),e.get(o.target).add(o.source);return{incoming:new Map([...e].map(([t,e])=>[t,e.size])),outgoing:new Map([...n].map(([t,e])=>[t,e.size]))}}function J(t){const e=new Map,n=new Map,o=(t,e,n,o)=>{let s=t.get(e);s||(s=new Map,t.set(e,s)),s.set(n,(s.get(n)??0)+o)};for(const s of t){const t=s.value>0&&Number.isFinite(s.value)?s.value:1;o(e,s.source,s.target,t),o(n,s.target,s.source,t)}const s=new Map,i=t=>{if(s.has(t))return;const o=e.get(t),i=n.get(t);if(o&&1===o.size&&(!i||0===i.size)){const[e,n]=[...o][0];return void s.set(t,{partner:e,weight:n})}const a=new Map;for(const[t,e]of o??[])a.set(t,(a.get(t)??0)+e);for(const[t,e]of i??[])a.set(t,(a.get(t)??0)+e);if(1===a.size){const[e,n]=[...a][0];s.set(t,{partner:e,weight:n})}};for(const e of t)i(e.source),i(e.target);return s}function K(t,e,n){const o=n.get(t),s=n.get(e);return!o||!s||(o.partner===s.partner||(o.partner===e||s.partner===t))}function tt(t,e,n){return!!n.has(t)&&e.some(e=>!K(t,e,n))}function et(t,e){return(t.value>0&&Number.isFinite(t.value)?t.value:1)*(1+(1===e.outgoing.get(t.source)?1:0)+(1===e.incoming.get(t.target)?1:0))}function nt(t,e,n,o){if(t.length<=12||o.slotCount<=1)return o.assignment;const s=new Map(t.map((t,e)=>[t,e])),i=Array.from({length:t.length},()=>new Map),a=Q(n);for(const t of n){const e=s.get(t.source),n=s.get(t.target);if(null==e||null==n||e===n)continue;const o=et(t,a);i[e].set(n,(i[e].get(n)??0)+o),i[n].set(e,(i[n].get(e)??0)+o)}const r=J(n),l=t.map(t=>r.get(t)?.weight??0),c=Array.from({length:t.length},()=>new Map);let u=0;for(let n=0;n<t.length-1&&u<5e4;n++)if(r.has(t[n]))for(let o=n+1;o<t.length;o++){if(!r.has(t[o]))continue;if(e.conflicts(t[n],t[o]))continue;u++;const s=Math.min(l[n],l[o])||Math.max(l[n],l[o]),i=K(t[n],t[o],r)?s:-s;if(!(Math.abs(i)<=W)&&(c[n].set(o,i),c[o].set(n,i),u>=5e4))break}const f=[...o.assignment],d=Array.from({length:o.slotCount},()=>[]);f.forEach((t,e)=>d[t].push(e));const g=(t,e,n)=>{const o=f[e],s=f[n];let i=0;const a=new Set;for(const r of[e,n])for(const[l,c]of t[r]){const t=r<l?`${r}:${l}`:`${l}:${r}`;if(a.has(t))continue;a.add(t);const u=f[r]===f[l],d=(r===e?s:o)===(l===e?s:l===n?o:f[l]);u!==d&&(i+=d?c:-c)}return i},m=(t,e,n)=>{let o=0;for(const[s,i]of t[e]){const t=f[e]===f[s],a=n===f[s];t!==a&&(o+=a?i:-i)}return o},p=(t,e)=>t>W||Math.abs(t)<=W&&e>W,h=(t,e,n,o)=>t>n+W||Math.abs(t-n)<=W&&e>o+W;let b=0;for(let n=0;n<32&&b<R;n++){let n=null,o=-1,s=-1,a=-1,r=-1/0,l=-1/0;for(let u=0;u<t.length;u++){for(let g=0;g<d.length&&!(b++>=R);g++){if(g===f[u])continue;if(!d[g].every(n=>!e.conflicts(t[u],t[n])))continue;const b=m(i,u,g),M=m(c,u,g);p(b,M)&&h(b,M,r,l)&&(n="move",o=u,s=-1,a=g,r=b,l=M)}if(b>=R)break}for(let u=0;u<t.length-1;u++){for(let m=u+1;m<t.length&&!(b++>=R);m++){const b=f[u],M=f[m];if(b===M)continue;if(!d[M].every(n=>n===m||!e.conflicts(t[u],t[n])))continue;if(!d[b].every(n=>n===u||!e.conflicts(t[m],t[n])))continue;const y=g(i,u,m),x=g(c,u,m);p(y,x)&&h(y,x,r,l)&&(n="swap",o=u,s=m,a=-1,r=y,l=x)}if(b>=R)break}if(null==n||-1===o)break;if("move"===n){const t=f[o];d[t].splice(d[t].indexOf(o),1),d[a].push(o),f[o]=a;continue}const u=f[o],M=f[s];d[u].splice(d[u].indexOf(o),1,s),d[M].splice(d[M].indexOf(s),1,o),f[o]=M,f[s]=u}return f}function ot(t,e,n,o){if(0===t.length||t.length>12||o.slotCount<=1)return o.assignment;const s=new Map(t.map((t,e)=>[t,e])),i=Array.from({length:t.length},()=>new Float64Array(t.length)),a=Array.from({length:t.length},()=>new Map),r=Array.from({length:t.length},()=>new Map),l=Q(n);for(const t of n){const e=s.get(t.source),n=s.get(t.target);if(null==e||null==n||e===n)continue;const o=et(t,l);i[e][n]+=o,i[n][e]+=o,r[e].set(n,(r[e].get(n)??0)+o),a[n].set(e,(a[n].get(e)??0)+o)}const c=J(n),u=t.map(t=>c.get(t)?.weight??0),f=Array.from({length:t.length},()=>new Float64Array(t.length));for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){for(const[t,o]of a[e])f[e][n]+=Math.min(o,a[n].get(t)??0);for(const[t,o]of r[e])f[e][n]+=Math.min(o,r[n].get(t)??0);if(c.has(t[e])&&c.has(t[n])){const o=Math.min(u[e],u[n])||Math.max(u[e],u[n]);f[e][n]+=K(t[e],t[n],c)?o:-o}f[n][e]=f[e][n]}let d=[...o.assignment],g=(e=>{let n=0,o=0;for(let s=0;s<t.length;s++)for(let a=s+1;a<t.length;a++)e[s]===e[a]&&(n+=i[s][a],o+=f[s][a]);return{flow:n,affinity:o}})(d),m=0;const p=new Array(t.length).fill(-1),h=Array.from({length:o.slotCount},()=>[]),b=(n,s,a,r)=>{if(m>=75e3)return;if(n===t.length)return m++,void((a>g.flow||a===g.flow&&r>g.affinity||a===g.flow&&r===g.affinity&&function(t,e){for(let n=0;n<Math.min(t.length,e.length);n++)if(t[n]!==e[n])return t[n]<e[n];return t.length<e.length}(p,d))&&(d=[...p],g={flow:a,affinity:r}));const l=Math.min(s+1,o.slotCount-1);for(let o=0;o<=l;o++){if(h[o].some(o=>e.conflicts(t[n],t[o])))continue;let l=0,c=0;for(const t of h[o])l+=i[n][t],c+=f[n][t];if(p[n]=o,h[o].push(n),b(n+1,Math.max(s,o),a+l,r+c),h[o].pop(),p[n]=-1,m>=75e3)return}};return p[0]=0,h[0].push(0),b(1,0,0,0),d}function st(t,e,n,o){const s=function(t,e,n,o){return`${t.map(t=>{const e=n[t.id],s=o[t.id];return[t.id,t.group??"",t.xExtent?.[0]??"",t.xExtent?.[1]??"",e?.topPeak??0,e?.botPeak??0,s?.start??"",s?.end??""].join(":")}).join("|")}#${e.map(t=>[t.id,t.source,t.target,t.value,t.startTime,t.endTime].join(":")).join("|")}`}(t,e,n,o),i=(a=s,U.get(a));var a;if(i)return V(i.slots,n,o);const r={};for(const e of t)r[e.id]=_(n[e.id],o[e.id]);const l=function(t,e){return t.filter(t=>null!=e[t.id].start).sort((t,n)=>e[t.id].start-e[n.id].start||e[t.id].end-e[n.id].end||u(t.id,n.id)).map(t=>t.id)}(t,r),c=new Map(t.map(t=>[t.id,t])),f=new Map(t.map(t=>[t.id,t.group||void 0])),d=function(t,e,n,o,s){const i=new Set,a=new Map(t.map(t=>[t,new Set])),r=new Map(t.map(t=>[t,new Set]));for(const t of o)i.add(Z(t.source,t.target)),a.get(t.target)?.add(t.source),r.get(t.source)?.add(t.target);const l=new Map,c=new Set,u=(t,e)=>{for(let n=0;n<t.length;n++)for(let o=n+1;o<t.length;o++){const s=Z(t[n],t[o]);e instanceof Map?e.set(s,[t[n],t[o]]):e.add(s)}};for(const t of r.values())u([...t],l);for(const t of a.values())u([...t],c);const f=new Set;for(const[t,[o,s]]of l)c.has(t)&&(G(e[o],e[s])||G(n[o],n[s])&&(f.add(o),f.add(s)));return{conflicts:(t,n)=>{const o=s.get(t),a=s.get(n);return null!=o&&null!=a&&o!==a||null!=o!=(null!=a)&&!i.has(Z(t,n))||!!G(e[t],e[n])||!(!f.has(t)&&!f.has(n))&&!i.has(Z(t,n))}}}(l,r,o,e,f),g=function(t,e,n=new Map){const o=[],s=[];for(const i of t){let t=o.findIndex(t=>t.every(t=>!e.conflicts(i,t))&&!tt(i,t,n));-1!==t||n.has(i)||(t=o.findIndex(t=>t.every(t=>!e.conflicts(i,t)))),-1===t&&(t=o.length,o.push([])),o[t].push(i),s.push(t)}return{assignment:s,slotCount:o.length}}(l,d,J(e)),m=ot(l,d,e,{...g,assignment:nt(l,d,e,g)}),p=new Map,h=m.map(t=>(p.has(t)||p.set(t,p.size),p.get(t))),b=Array.from({length:p.size||(t.length>0?1:0)},()=>({occupants:[],peak:{topPeak:0,botPeak:0}})),M={};l.forEach((t,e)=>{const n=h[e],o=b[n];o.occupants.push({id:t,end:r[t].end??-1/0});const s=c.get(t)?.group;s&&(o.group=s),M[t]=n});for(const e of[...t].sort((t,e)=>u(t.id,e.id)))null==M[e.id]&&(b[0].occupants.push({id:e.id,end:-1/0}),M[e.id]=0);for(const t of b){t.occupants.sort((t,e)=>(r[t.id].start??1/0)-(r[e.id].start??1/0)||u(t.id,e.id));for(const e of t.occupants){const o=n[e.id];t.peak.topPeak=Math.max(t.peak.topPeak,o?.topPeak||0),t.peak.botPeak=Math.max(t.peak.botPeak,o?.botPeak||0)}}const y={slots:b,slotByNode:M};return function(t,e){for(U.has(t)&&U.delete(t),U.set(t,{slots:e.slots.map(t=>({occupants:t.occupants.map(t=>({...t})),peak:{...t.peak},...null!=t.group?{group:t.group}:{}})),slotByNode:{...e.slotByNode}});U.size>12;){const t=U.keys().next().value;if(null==t)break;U.delete(t)}}(s,y),y}function it(t){return t.topMass+t.botMass}function at(t,e){const n=t.samples.filter(t=>t.t===e);if(n.length>0)return n.reduce((t,e)=>it(e)>=it(t)?e:t,n[0]);let o=null;for(const n of t.samples){if(n.t>e)break;o=n}return o}function rt(t,e,n,o,s,i,a=0){const r=new Map;for(const n of t){if(!n.group||!e[n.id])continue;const t=r.get(n.group)??[];t.push(n),r.set(n.group,t)}if(0===r.size||!(i>0))return e;const l=(c=e,Object.fromEntries(Object.entries(c).map(([t,e])=>[t,{...e,samples:e.samples.map(t=>({...t})),localAttachments:new Map([...e.localAttachments].map(([t,e])=>[t,{...e}]))}])));var c;for(const[t,c]of r){const r=n.map((t,e)=>({slot:t,index:e})).filter(({slot:e})=>e.group===t);if(0===r.length)continue;const u=r[0].slot,f=r.at(-1).slot,d=s[u.occupants[0]?.id],g=s[f.occupants[0]?.id];if(!Number.isFinite(d)||!Number.isFinite(g))continue;const m=(d-u.peak.topPeak*i+(g+f.peak.botPeak*i))/2,p=[...new Set(c.flatMap(t=>e[t.id].samples.map(t=>t.t)))].sort((t,e)=>t-e),h=new Map;for(const t of c)h.set(t.id,new Map);for(const t of p){const n=new Map;for(const s of c){const i=at(e[s.id],t);if(!i||it(i)<=1e-9)continue;const a=o[s.id];if(null==a)continue;const r=n.get(a)??[];r.push({node:s,sample:i}),n.set(a,r)}const r=[...n].sort((t,e)=>t[0]-e[0]).map(([t,e])=>({slot:t,active:e,mass:Math.max(...e.map(({sample:t})=>it(t)))}));if(0===r.length)continue;let l=m-(r.reduce((t,e)=>t+e.mass,0)*i+Math.max(0,a)*Math.max(0,r.length-1))/2;for(const e of r){for(const{node:n,sample:o}of e.active){const e=(l-s[n.id])/i+o.topMass-(o.boundaryOffset??0);h.get(n.id).set(t,e)}l+=e.mass*i+Math.max(0,a)}}for(const t of c){const n=e[t.id],o=l[t.id],s=h.get(t.id),i=[];for(const t of p){const e=s.get(t),o=n.samples.filter(e=>e.t===t);if(o.length>0){i.push(...o.map(t=>({...t,...null!=e?{boundaryOffset:(t.boundaryOffset??0)+e}:{}})));continue}const a=at(n,t);null==e||!a||it(a)<=1e-9||i.push({...a,t:t,boundaryOffset:(a.boundaryOffset??0)+e})}o.samples=i,o.localAttachments=new Map([...n.localAttachments].map(([t,e])=>{const n=s.get(e.time);return[t,{...e,...null!=n?{boundaryOffset:(e.boundaryOffset??0)+n}:{}}]}))}}return l}function lt(t,e,n,o,s){const{plotH:i,padding:a,valueScale:r,packing:l,laneOrder:c,lifetimeMode:d="half",lanePlacement:g="stack",groupPadding:m=0,ribbonLane:p="both",domain:b}=s,M={},y={};for(const e of t)M[e.id]=n[e.id].topPeak||0,y[e.id]=n[e.id].botPeak||0;const x="half"===d,w={};for(const e of t){const t=Array.isArray(e.xExtent)?e.xExtent[0]:null,n=Array.isArray(e.xExtent)?e.xExtent[1]:null;let s=null!=t&&Number.isFinite(t)?t:1/0,i=null!=n&&Number.isFinite(n)?n:-1/0;for(const t of o.outgoing[e.id]){t.startTime<s&&(s=t.startTime),null!=t.systemInTime&&Number.isFinite(t.systemInTime)&&t.systemInTime<s&&(s=t.systemInTime);const e=x?(t.startTime+t.endTime)/2:t.endTime;e>i&&(i=e)}for(const t of o.incoming[e.id]){const e=x?(t.startTime+t.endTime)/2:t.startTime;e<s&&(s=e),t.endTime>i&&(i=t.endTime),null!=t.systemOutTime&&Number.isFinite(t.systemOutTime)&&t.systemOutTime>i&&(i=t.systemOutTime)}w[e.id]={start:Number.isFinite(s)?s:null,end:Number.isFinite(i)?i:null}}let v={},k=[],T=[];if(s.frozenSlots){const t=V(s.frozenSlots,n,w);k=t.slots,v=t.slotByNode,T=k.map(f)}else if("reuse"===l){const o=st(t,e,n,w);k=o.slots,v=o.slotByNode}else t.forEach((t,e)=>{k.push({occupants:[{id:t.id,end:w[t.id]?.end??-1/0}],peak:{topPeak:M[t.id],botPeak:y[t.id]},...t.group?{group:t.group}:{}}),v[t.id]=e});B(k,v),0===T.length&&(T=k.map(f));let S=null;s.frozenSlots||(s.fixedSlotOrder?function(t,e,n){const o=new Map(n.map((t,e)=>[t,e]));A(t,e,[...t].sort((t,e)=>(o.get(f(t))??1/0)-(o.get(f(e))??1/0)||u(f(t),f(e))))}(k,v,s.fixedSlotOrder):s.runOrdering&&c&&"insertion"!==c&&(S=q(t,e,n,w,k,v,{plotH:i,padding:a,valueScale:r,groupPadding:m,laneOrder:c,ribbonLane:p,domain:b}))),B(k,v);const N=h(t,e,n,k,v,{plotH:i,padding:a,valueScale:r,stackValueScale:s.stackValueScale,lanePlacement:g,groupPadding:m}),O=0===k.length?0:k[0].peak.topPeak+N.adjacentClearance.reduce((t,e)=>t+e,0)+k[k.length-1].peak.botPeak,P=S?.before.crossings??null,F=S?.after.crossings??null,I=S?.before.weightedLength??null,E=S?.after.weightedLength??null;return{effectiveSlotsHeight:O,centerlines:N.centerlines,laneLifetime:w,slots:k,slotByNode:v,slotCenter:N.slotCenter,stackCenter:N.stackCenter,verticalUtilization:N.verticalUtilization,selectedSlotOrder:k.map(f),initialSlotOrder:T,ordering:S,crossingsBefore:P,crossingsAfter:F,lengthBefore:I,lengthAfter:E}}function ct(t,e,n){const{plotH:o,pairing:s="temporal",packing:i="reuse",laneOrder:a="crossing-min",lifetimeMode:r="half",maxValueScale:l,lanePlacement:c="stack",nodeSizing:g="temporal",groupPadding:m=0,ribbonLane:p="both",domain:b}=n,M=Number.isFinite(m)?Math.max(0,m):0,y=function(t,e){const n={},o={};for(const e of t)n[e.id]=[],o[e.id]=[];for(const t of e)o[t.source]&&o[t.source].push(t),n[t.target]&&n[t.target].push(t);return{incoming:n,outgoing:o}}(t,e),x=function(t,e,n,o="temporal"){const s="temporal"===o?(t,e)=>t.endTime-e.endTime||u(t.id,e.id):(t,e)=>e.value-t.value||u(t.id,e.id),i="temporal"===o?(t,e)=>t.startTime-e.startTime||u(t.id,e.id):(t,e)=>e.value-t.value||u(t.id,e.id),a=new Map;for(const t of e)a.set(t.id,{});const r=(t,e)=>{const n=new Map;for(const o of t){const t=o[e];n.has(t)||n.set(t,{partner:t,edges:[],total:0,earliestStart:1/0,latestEnd:-1/0});const s=n.get(t);s.edges.push(o),s.total+=o.value,s.earliestStart=Math.min(s.earliestStart,o.startTime),s.latestEnd=Math.max(s.latestEnd,o.endTime)}const a=[...n.values()];"temporal"===o?a.sort((t,n)=>"target"===e?t.earliestStart-n.earliestStart||u(t.partner,n.partner):t.latestEnd-n.latestEnd||u(t.partner,n.partner)):a.sort((t,e)=>e.total-t.total||u(t.partner,e.partner));for(const t of a)t.edges.sort("target"===e?i:s);return a};for(const e of t){const t=n.outgoing[e.id],o=n.incoming[e.id];if(0===o.length)r(t,"target").forEach((t,e)=>{const n=e%2==0?"top":"bot";for(const e of t.edges)a.get(e.id).sourceSide=n});else if(0===t.length)r(o,"source").forEach((t,e)=>{const n=e%2==0?"top":"bot";for(const e of t.edges)a.get(e.id).targetSide=n});else{const e=r(o,"source"),n=r(t,"target"),s=Math.max(e.length,n.length);for(let t=0;t<s;t++){const o=t%2==0?"top":"bot";if(e[t])for(const n of e[t].edges)a.get(n.id).targetSide=o;if(n[t])for(const e of n[t].edges)a.get(e.id).sourceSide=o}}}return a}(t,e,y,s);let w={};for(const e of t)w[e.id]=P(e,y,x,void 0,g);const v=lt(t,e,w,y,{plotH:o,padding:12,valueScale:1,packing:i,laneOrder:a,lifetimeMode:r,runOrdering:!0,lanePlacement:"stack",groupPadding:M,ribbonLane:p,domain:b}),k=v.slots.map(t=>({occupants:t.occupants.map(t=>({...t})),peak:{...t.peak},...null!=t.group?{group:t.group}:{}})),S=new Set;for(const t of e){const e=v.slotByNode[t.source],n=v.slotByNode[t.target];if(void 0===e||void 0===n)continue;const o=x.get(t.id);e!==n?n<e?(o.sourceSide="top",o.targetSide="bot"):(o.sourceSide="bot",o.targetSide="top"):(S.add(t.id),o.sourceSide="bot",o.targetSide="bot")}for(const e of t){const t=y.outgoing[e.id],n=y.incoming[e.id],o=new Set(t.map(t=>x.get(t.id).sourceSide)),s=new Set(n.map(t=>x.get(t.id).targetSide));if(1===o.size&&n.length>0){const t=[...o][0];for(const e of n)v.slotByNode[e.source]===v.slotByNode[e.target]&&(x.get(e.id).targetSide=t)}if(1===s.size&&t.length>0){const e=[...s][0];for(const n of t)v.slotByNode[n.source]===v.slotByNode[n.target]&&(x.get(n.id).sourceSide=e)}}!function(t,e,n){const o=new Map,s=[];for(const e of t)s.push({time:e.startTime,kind:"out",edge:e}),s.push({time:e.endTime,kind:"in",edge:e});s.sort((t,e)=>t.time-e.time||(t.kind===e.kind?0:"in"===t.kind?-1:1)||("out"===t.kind?e.edge.value-t.edge.value:0)||u(t.edge.id,e.edge.id));const i=t=>{let e=o.get(t);return e||(e={top:0,bot:0},o.set(t,e)),e},a=(t,e,n)=>{const o="top"===e?"bot":"top",s=Math.min(n,t[e]);t[e]-=s;const i=n-s;i>0&&(t[o]=Math.max(0,t[o]-i))};for(const t of s){const{edge:o}=t;if("in"===t.kind){const t=e.get(o.id)?.targetSide??"bot";i(o.target)[t]+=o.value;continue}const s=i(o.source),r=e.get(o.id);let l=r.sourceSide??"bot";if(n[o.source]===n[o.target]){const t=s.top>=o.value,e=s.bot>=o.value;t!==e?l=t?"top":"bot":t||e||s.top===s.bot||(l=s.top>s.bot?"top":"bot"),r.sourceSide=l,r.targetSide=l}a(s,l,o.value)}}(e,x,v.slotByNode),function(t,e,n,o){for(const s of t){const t=e.incoming[s.id],i=e.outgoing[s.id];if(0===t.length||0===i.length)continue;const a=()=>{const e={inTop:0,inBot:0,outTop:0,outBot:0};for(const o of t)"top"===n.get(o.id).targetSide?e.inTop+=o.value:e.inBot+=o.value;for(const t of i)"top"===n.get(t.id).sourceSide?e.outTop+=t.value:e.outBot+=t.value;return e},r=(t,e)=>{const s=a(),r="top"===t?s.outTop-s.inTop:s.outBot-s.inBot,l="top"===e?s.inTop-s.outTop:s.inBot-s.outBot;if(r<=0||l<=0)return!1;const c=Math.min(r,l),f=i.filter(e=>!o.has(e.id)&&n.get(e.id).sourceSide===t&&e.value<=c).sort((t,e)=>e.value-t.value||u(t.id,e.id));return 0!==f.length&&(n.get(f[0].id).sourceSide=e,!0)};let l=i.length+1;for(;l-- >0&&(r("top","bot")||r("bot","top")););}}(t,y,x,S),w={};for(const e of t)w[e.id]=P(e,y,x,void 0,g);const N=lt(t,e,w,y,{plotH:o,padding:12,valueScale:1,packing:i,laneOrder:a,lifetimeMode:r,frozenSlots:k,lanePlacement:"stack",groupPadding:M,ribbonLane:p,domain:b}),F=N.effectiveSlotsHeight??N.slots.reduce((t,e)=>t+e.peak.topPeak+e.peak.botPeak,0),A=N.slots.slice(0,-1).reduce((t,e,n)=>t+(null!=e.group&&e.group===N.slots[n+1].group?1:0),0),I=Math.max(1,N.slots.length+1-A),E=Math.min(12,Math.max(0,.35*o-A*M)/I),$=2*E+d(N.slots,E,M).reduce((t,e)=>t+e,0),L=F>0?Math.max(0,(o-$)/F):1,B=Number.isFinite(l)&&l>0?Math.min(L,l):L;let z=lt(t,e,w,y,{plotH:o,padding:E,valueScale:B,packing:i,laneOrder:a,lifetimeMode:r,frozenSlots:k,lanePlacement:c,groupPadding:M,ribbonLane:p,domain:b,stackValueScale:L});const H=Number.isFinite(l)&&l>0&&l+1e-12<L;if("insertion"!==a&&("hug"===c||H)&&z.slots.length>1&&(q(t,e,w,z.laneLifetime,z.slots,z.slotByNode,{plotH:o,padding:E,valueScale:B,groupPadding:M,laneOrder:a,ribbonLane:p,domain:b,lanePlacement:c,mode:"geometry-refine"}),z=lt(t,e,w,y,{plotH:o,padding:E,valueScale:B,packing:i,laneOrder:a,lifetimeMode:r,frozenSlots:z.slots,fixedSlotOrder:z.slots.map(f),lanePlacement:c,groupPadding:M,ribbonLane:p,domain:b,stackValueScale:L})),function(t,e){const n=(t,n)=>{for(const o of t){const t=new Map;for(const s of o){const o=`${("out"===n?e.get(s.id)?.sourceSide:e.get(s.id)?.targetSide)??""}\0${"out"===n?s.startTime:s.endTime}`,i="out"===n?`${s.target}\0${s.endTime}`:`${s.source}\0${s.startTime}`,a=t.get(o);if(null!=a&&a!==i)return!0;t.set(o,i)}}return!1};return n(Object.values(t.outgoing),"out")||n(Object.values(t.incoming),"in")}(y,x)){const n=function(t,e,n,o){const s=new Map;for(const i of t){const t=e[i.source]?.localAttachments.get(i.id),a=e[i.target]?.localAttachments.get(i.id),r=n[i.source],l=n[i.target];if(!(t&&a&&Number.isFinite(r)&&Number.isFinite(l)))continue;const c=O(t,r,o),u=O(a,l,o);s.set(i.id,{source:(c[0]+c[1])/2,target:(u[0]+u[1])/2})}return s}(e,w,z.centerlines,B);w={};for(const e of t)w[e.id]=P(e,y,x,n,g);z=lt(t,e,w,y,{plotH:o,padding:E,valueScale:B,packing:i,laneOrder:a,lifetimeMode:r,frozenSlots:z.slots,fixedSlotOrder:z.slots.map(f),lanePlacement:c,groupPadding:M,ribbonLane:p,domain:b,stackValueScale:L})}const D=new Map(v.initialSlotOrder.map((t,e)=>[t,e])),j=[...z.slots].sort((t,e)=>(D.get(f(t))??1/0)-(D.get(f(e))??1/0)||u(f(t),f(e))),Y={};j.forEach((t,e)=>{for(const n of t.occupants)Y[n.id]=e});const V=h(t,e,w,j,Y,{plotH:o,padding:E,valueScale:B,stackValueScale:L,lanePlacement:"stack",groupPadding:M}),U=rt(t,w,j,Y,V.centerlines,B,M),W=T(C(Y,e),X(Y,e),e,U,j,Y,V.centerlines,z.laneLifetime,B,V.verticalUtilization,p,b);w=rt(t,w,z.slots,z.slotByNode,z.centerlines,B,M);const R=T(C(z.slotByNode,e),X(z.slotByNode,e),e,w,z.slots,z.slotByNode,z.centerlines,z.laneLifetime,B,z.verticalUtilization,p,b);return{nodeData:w,sides:x,valueScale:B,padding:E,compressedPadding:E<12,centerlines:z.centerlines,laneLifetime:z.laneLifetime,slots:z.slots,slotByNode:z.slotByNode,crossingsBefore:"insertion"===a?null:W.crossings,crossingsAfter:"insertion"===a?null:R.crossings,lengthBefore:"insertion"===a?null:W.weightedLength,lengthAfter:"insertion"===a?null:R.weightedLength,layoutQualityBefore:W,layoutQuality:R}}function ut(t,e,n,o,s,i,a,r,l={}){const c=s,u=t=>r?Math.max(r[0],Math.min(r[1],t)):t;let f=i(u(t.time));const d=i(u(n.time)),g=t.value*c,m=n.value*c,p=e+(t.boundaryOffset??0)*c,h=o+(n.boundaryOffset??0)*c,b=t.sideMassBefore*c,M=n.sideMassAfter*c;let y,x,w,v;"top"===t.side?(y=p-b,x=y+g):(x=p+b,y=x-g),"top"===n.side?(w=h-M,v=w+m):(v=h+M,w=v-m);const k=l.sourceRunwayStart,T=l.minRun,S=(y+x)/2,N=(w+v)/2,O=Math.abs(N-S),P=d-f,F="number"==typeof k&&Number.isFinite(k),A="number"==typeof T&&Number.isFinite(T)&&T>0;if(F&&O>1e-9&&P>0&&("auto"===T||A)){const e="source"===a?.85:"target"===a?.15:.5,n=1.5*Math.min(e*e,(1-e)*(1-e)),o="auto"===T?Math.min(144,Math.sqrt(8*O/n)):T;if(o>P){const e=i(u(Math.min(k,t.time)));if(Number.isFinite(e)){const t=Math.min(f,e);f=Math.min(f,Math.max(t,d-o))}}}const I="source"===a?f+.85*(d-f):"target"===a?f+.15*(d-f):(f+d)/2;return{sx:f,sTop:y,sBot:x,tx:d,tTop:w,tBot:v,cp1X:I,cp2X:I}}function ft(t){return Math.max(18,11*t.length*.58)}function dt(t){const e=1.22*ft(t.labelText)+4;return"start"===t.labelAnchor?[t.labelX,t.labelX+e]:"middle"===t.labelAnchor?[t.labelX-e/2,t.labelX+e/2]:[t.labelX-e,t.labelX]}function gt(t,e){const n=t.labelX-ft(t.labelText),o=e.labelX-ft(e.labelText);return n<=e.labelX+3&&o<=t.labelX+3}function mt(t,e,n){const o=t.map(t=>({...t})),s=new Map;for(const t of o){const n=e[t.id];if(null==n)continue;const o=s.get(n)??[];o.push(t),s.set(n,o)}const i=t=>{if(t.length<2)return;const e=t.reduce((t,e)=>t+e.labelY,0)/t.length,o=(t.length-1)/2;t.forEach((t,s)=>{t.labelY=Math.max(8,Math.min(n-8,e+16*(s-o)))})};for(const t of s.values()){t.sort((t,e)=>t.labelX-e.labelX||t.id.localeCompare(e.id));let e=[],n=-1/0;for(const o of t){const t=o.labelX-ft(o.labelText);e.length>0&&t>n+3&&(i(e),e=[],n=-1/0),e.push(o),n=Math.max(n,o.labelX)}i(e)}return function(t,e){const n=[...t].sort((t,e)=>t.labelY-e.labelY||t.labelX-e.labelX||t.id.localeCompare(e.id));for(let t=0;t<3;t+=1){for(let t=0;t<n.length;t+=1){let e=8;for(let o=0;o<t;o+=1)gt(n[t],n[o])&&(e=Math.max(e,n[o].labelY+16));n[t].labelY=Math.max(n[t].labelY,e)}for(let t=n.length-1;t>=0;t-=1){let o=e-8;for(let e=t+1;e<n.length;e+=1)gt(n[t],n[e])&&(o=Math.min(o,n[e].labelY-16));n[t].labelY=Math.min(n[t].labelY,o)}}}(o,n),o}var pt=/(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?),(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)/gi;function ht(t){return t.replace(pt,(t,e,n)=>`${n},${e}`)}function bt(t){if(!t)return;const e=t=>({x:t.y,y:t.x});return{...t,...t.points&&{points:t.points.map(e)},...t.segments&&{segments:t.segments.map(t=>t.map(e))}}}function Mt(t){return{...t,pathD:ht(t.pathD),y0:t.x0,y1:t.x1,x0:0,x1:0}}function yt(t,e){const n=function(t){if(null==t)return()=>{};const e="function"==typeof t?t:e=>e[t];return t=>xt(e(t))}(e??"value"),o=null==t?void 0:"function"==typeof t?t:e=>e[t];return t=>{const e=o?o(t):void 0;return{value:n(t),category:null==e?void 0:String(e)}}}function xt(t){if("number"==typeof t)return Number.isFinite(t)?t:void 0;if("string"==typeof t&&""!==t.trim()){const e=Number(t);return Number.isFinite(e)?e:void 0}}function wt(t,e,n){const o=t.when;return void 0===o||!0===o||!1!==o&&("function"==typeof o?o(e,n):function(t,e,n){const o=null!=t.axis?n[t.axis]:null!=t.field?e[t.field]:n.value;if(void 0!==t.eq&&o!==t.eq)return!1;if(void 0!==t.ne&&o===t.ne)return!1;if(void 0!==t.in&&!t.in.includes(o))return!1;if(void 0===t.gt&&void 0===t.gte&&void 0===t.lt&&void 0===t.lte&&void 0===t.within&&void 0===t.outside)return!0;const s=xt(o);if(void 0===s)return!1;if(void 0!==t.gt&&!(s>t.gt))return!1;if(void 0!==t.gte&&!(s>=t.gte))return!1;if(void 0!==t.lt&&!(s<t.lt))return!1;if(void 0!==t.lte&&!(s<=t.lte))return!1;if(void 0!==t.within){const[e,n]=t.within;if(!(s>=e&&s<=n))return!1}if(void 0!==t.outside){const[e,n]=t.outside;if(!(s<e||s>n))return!1}return!0}(o,e,n))}import{jsx as vt,jsxs as kt}from"react/jsx-runtime";function Tt(e){const{nodes:o,edges:i,domain:a,plotW:r,plotH:l,ribbonLane:c,ribbonMinRun:u=0,edgeOpacity:f,colorOf:d,layoutOpts:g,orientation:m="horizontal",showLabels:p=!0,labelPriorityAccessor:h,maxLabels:b,selectionDatum:M="raw",styleRules:y,colorBy:x,valueAccessor:w,usageMode:v="static"}=e,k="vertical"===m?l:r,T="vertical"===m?r:l,P=function(t,e,o,s={}){const i=n(s.usageMode??"static"),a=[],r=new Set;for(const e of t)r.has(e.id)&&a.push({kind:"duplicate-node",id:e.id,severity:i.duplicateIds}),r.add(e.id);const l=new Set,c=Array.isArray(o)&&2===o.length,u=c&&Number.isFinite(o[0])&&Number.isFinite(o[1]),f=u&&o[0]<=o[1];c&&u&&f||a.push({kind:"invalid-domain"});for(const e of t)null!=e.xExtent&&(Array.isArray(e.xExtent)&&2===e.xExtent.length&&Number.isFinite(e.xExtent[0])&&Number.isFinite(e.xExtent[1])&&e.xExtent[0]<=e.xExtent[1]||a.push({kind:"invalid-node-time",id:e.id}));for(const t of e)l.has(t.id)&&a.push({kind:"duplicate-edge",id:t.id,severity:i.duplicateIds}),l.add(t.id),r.has(t.source)||a.push({kind:"missing-node",id:t.id,endpoint:"source",nodeId:t.source}),r.has(t.target)||a.push({kind:"missing-node",id:t.id,endpoint:"target",nodeId:t.target}),Number.isFinite(t.startTime)&&Number.isFinite(t.endTime)?((null!=t.systemInTime&&!Number.isFinite(t.systemInTime)||null!=t.systemOutTime&&!Number.isFinite(t.systemOutTime))&&a.push({kind:"invalid-system-time",id:t.id,severity:"warn"}),(!Number.isFinite(t.value)||t.value<=0)&&a.push({kind:"invalid-value",id:t.id}),t.endTime<t.startTime&&a.push({kind:"backward-edge",severity:"fatal",id:t.id,source:t.source,target:t.target})):a.push({kind:"invalid-edge-time",id:t.id});return a}(o,i,a,{usageMode:v}),{fatal:F,warnings:A}=function(t){const e=[],n=[];for(const o of t)"fatal"===s(o)?e.push(o):n.push(o);return{fatal:e,warnings:n}}(P),I=function(t,e,o="static"){if("strip"!==n(o).invalidSystemTime)return t;const s=new Set(e.filter(t=>"invalid-system-time"===t.kind).map(t=>t.id));return 0===s.size?t:t.map(t=>{if(!s.has(t.id))return t;const e={...t};return null==e.systemInTime||Number.isFinite(e.systemInTime)||delete e.systemInTime,null==e.systemOutTime||Number.isFinite(e.systemOutTime)||delete e.systemOutTime,e})}(i,P,v),E=t().domain(a).range([0,k]);if(F.length>0)return{layout:null,layoutConfig:{bands:[],ribbons:[],showLabels:!1!==p},issues:F,warnings:A,xScale:E};const $=ct(o,I,{plotH:T,...g,ribbonLane:c,domain:a}),{centerlines:L,nodeData:B,valueScale:z}=$,C=yt(x,w),X=[],H=[],D=0===u?new Map:function(t,e,n){const o=new Set(e.map(t=>t.target)),s=new Map(t.map(t=>[t.id,t])),i=new Map;for(const t of e){if(o.has(t.source))continue;const e=i.get(t.source)??[];e.push(t),i.set(t.source,e)}const a=new Map;for(const e of t){if(!e.group)continue;const t=a.get(e.group)??[];t.push(e),a.set(e.group,t)}const r=new Set;for(const[t,e]of a){const n=e.flatMap(t=>i.get(t.id)??[]),s=new Set(n.map(t=>t.startTime));n.length>0&&1===s.size&&e.every(t=>{const e=t.xExtent?.[0],s=n[0].startTime;return!o.has(t.id)&&(i.get(t.id)?.length??0)>0&&Number.isFinite(e)&&e<s})&&r.add(t)}const l=new Map;for(const[t,e]of i){const o=s.get(t);if(o?.group&&!r.has(o.group))continue;const i=o?.xExtent?.[0],a=[...e].sort((t,e)=>t.startTime-e.startTime||t.id.localeCompare(e.id)),c=a[0]?.startTime-1;let u=null;for(let t=0;t<a.length;){const e=a[t].startTime;let o=t+1;for(;o<a.length&&a[o].startTime===e;)o++;for(let e=t;e<o;e++){const t=a[e],o=Number.isFinite(i)&&i<t.startTime,s=Number.isFinite(t.systemInTime)&&t.systemInTime<t.startTime;if(!o&&!s)continue;let r=n[0];o&&(r=Math.max(r,i)),s&&(r=Math.max(r,t.systemInTime)),!o&&s&&Number.isFinite(c)&&(r=Math.max(r,c)),null!=u&&(r=Math.max(r,u)),r<t.startTime&&l.set(t.id,r)}u=e,t=o}}for(const[t,e]of a){if(!r.has(t))continue;const n=e.flatMap(t=>i.get(t.id)??[]);if(!n.every(t=>l.has(t.id))){for(const t of n)l.delete(t.id);continue}const o=Math.max(...n.map(t=>l.get(t.id)));for(const t of n)l.set(t.id,o)}return l}(o,I,a),j=new Map(o.filter(t=>t.group).map(t=>[t.id,t.group])),Y=new Map;for(const t of I){const e=B[t.source]?.localAttachments.get(t.id),n=B[t.target]?.localAttachments.get(t.id);e&&n&&Y.set(t.id,ut(e,L[t.source],n,L[t.target],z,E,c,a,{minRun:u,sourceRunwayStart:D.get(t.id)}))}const q=function(t,e,n,o,s,i){const a=new Map(e),r=new Map;for(const e of t){const t=i?.get(e.source),n=null==t?`node:${e.source}`:`group:${t}`,o=r.get(n)??new Map,s=o.get(e.startTime)??[];s.push(e),o.set(e.startTime,s),r.set(n,o)}for(const t of r.values())for(const[i,r]of t){if(!r.some(t=>n.has(t.id)))continue;const t=r.map(t=>e.get(t.id));if(t.some(t=>null==t))continue;const l=o(i),c=Math.min(...t.map(t=>t.sx));if(!(c<l-1e-9))continue;const u=Math.max(...r.map(t=>{const e=n.get(t.id);return null==e?l:Math.min(l,o(e))})),f=Math.min(l,Math.max(c,u));for(const t of r){const n=e.get(t.id),o="source"===s?.85:"target"===s?.15:.5,i=f+(n.tx-f)*o;a.set(t.id,{...n,sx:f,cp1X:i,cp2X:i})}}return a}(I,Y,D,E,c,j),V=function(t,e,n,o,s){const i=new Map;for(const a of t){if(!n.has(a.id))continue;const t=e.get(a.id);if(!(t&&t.sx<o(a.startTime)-1e-9))continue;const r=s(t.sx);Number.isFinite(r)&&r<a.startTime&&i.set(a.id,r)}return i}(I,q,D,E,t=>a[0]+t/k*(a[1]-a[0])),U=function(t,e,n){const o=new Map,s=new Map;for(const[t,e]of n??[]){const n=s.get(e)??[];n.push(t),s.set(e,n)}for(const i of t){const t=e.get(i.id);if(!(null!=t&&Number.isFinite(t)&&t<i.startTime))continue;const a=n?.get(i.source),r=null==a?[i.source]:s.get(a)??[i.source];for(const e of r){const n=o.get(e)??new Map,s=n.get(i.startTime);n.set(i.startTime,null==s?t:Math.min(s,t)),o.set(e,n)}}return o}(I,V,j);o.forEach((t,e)=>{const n=B[t.id];if(!n||0===n.samples.length)return;const o=(s=n.samples,(i=U.get(t.id))&&0!==i.size?s.map(t=>{const e=i.get(t.t);return null==e?t:{...t,t:e}}):s);var s,i;const r=function(t,e,n,o,s){if(0===t.length)return null;const i=N(t,s),a=t=>e+(i[t].boundaryOffset??0)*n,r=t=>a(t)-i[t].topMass*n,l=t=>a(t)+i[t].botMass*n;let c=`M${o(i[0].t)},${r(0)}`;for(let t=1;t<i.length;t++)c+=` L${o(i[t].t)},${r(t)}`;c+=` L${o(i[i.length-1].t)},${l(i.length-1)}`;for(let t=i.length-2;t>=0;t--)c+=` L${o(i[t].t)},${l(t)}`;return c+" Z"}(o,L[t.id],z,E,a);if(!r)return;const l=N(o,a),c=l.find(t=>t.topMass+t.botMass>0)||l[0],u=(c.botMass-c.topMass+2*(c.boundaryOffset??0))*z/2,f=L[t.id]+u;let g,p,h=d(t.id,e),b=h,M=.5;const x=t.__raw??t;if(y&&y.length>0){const t=function(t,e,n){if(!e||0===e.length)return{};let o={};for(const s of e){if(!wt(s,t,n))continue;const e="function"==typeof s.style?s.style(t,n):s.style;e&&(o={...o,...e})}return o}(x,y,C(x));"string"==typeof t.fill?h=t.fill:null!=t.fill&&("object"==typeof(w=t.fill)&&null!==w&&"hatch"===w.type)&&(p=t.fill,h=t.fill.background&&"transparent"!==t.fill.background?t.fill.background:h),"string"==typeof t.stroke&&(b=t.stroke),"number"==typeof t.strokeWidth&&(M=t.strokeWidth),"number"==typeof t.fillOpacity&&(g=t.fillOpacity),"number"==typeof t.opacity&&null==g&&(g=t.opacity)}var w;const v=function(t,e,n,o,s,i){const a=n.nodeData[t];if(!a||0===a.samples.length)return[];const r=n.valueScale,l=n.centerlines[t],c=N(a.samples,s),u=c.find(t=>t.topMass+t.botMass>0)||c[0],f=[...c].reverse().find(t=>t.topMass+t.botMass>0)||c[c.length-1],d=o(u.t),g=o(f.t),m=t=>o(S(t,s)),p=[],h=(t,e,n,o)=>`M${t},${e} L${n},${e} L${n},${o} L${t},${o} Z`;for(const n of e){if(n.source===t&&null!=n.systemInTime&&Number.isFinite(n.systemInTime)){const t=a.localAttachments.get(n.id),e=i?.get(n.id)??n.startTime;if(t&&"out"===t.kind&&n.systemInTime<e){const o=m(n.systemInTime),i=m(e),a=null!=s&&n.systemInTime<s[0],c=a?o:o-20,u=a?Math.min(i,o+20):o,f=Math.max(d,c);if(i>f){const[e,n]=O(t,l,r);p.push({pathD:h(f,e,i,n),x0:c,x1:u,from:0,to:1})}}}if(n.target===t&&null!=n.systemOutTime&&Number.isFinite(n.systemOutTime)){const t=a.localAttachments.get(n.id);if(t&&"in"===t.kind&&n.systemOutTime>n.endTime){const e=m(n.systemOutTime),o=m(n.endTime),s=e+20,i=Math.min(g,s);if(i>o){const[n,a]=O(t,l,r);p.push({pathD:h(o,n,i,a),x0:e,x1:s,from:1,to:0})}}}}return p}(t.id,I,$,E,a,V);X.push({id:t.id,pathD:r,fill:h,stroke:b,strokeWidth:M,...null!=g&&{fillOpacity:g},...p&&{hatchFill:p},...v.length>0&&{gradientStubs:v},rawDatum:x,labelX:E("vertical"===m&&t.xExtent?t.xExtent[0]:c.t)-4,labelY:f,labelText:t.label??t.id})});const W=new Map;o.forEach((t,e)=>W.set(t.id,e)),I.forEach(t=>{const e=q.get(t.id);if(!e)return;const n=W.get(t.source)??0,o=d(t.source,n),{pathD:s,bezier:i}=function(t){const{sx:e,sTop:n,sBot:o,tx:s,tTop:i,tBot:a,cp1X:r,cp2X:l}=t,c=(n+o)/2,u=(i+a)/2;return{pathD:[`M${e},${n}`,`C${r},${n} ${l},${i} ${s},${i}`,`L${s},${a}`,`C${l},${a} ${r},${o} ${e},${o}`,"Z"].join(" "),bezier:{circular:!1,points:[{x:e,y:c},{x:r,y:c},{x:l,y:u},{x:s,y:u}],halfWidth:(o-n)/2}}}(e),a=t.__raw??t,r="function"==typeof f?Number(f(a)):f,l=Number.isFinite(r)?Math.max(0,Math.min(1,r)):.35;H.push({id:t.id,pathD:s,fill:o,opacity:l,rawDatum:a,bezier:i})});const R=mt(X,$.slotByNode,T).map(t=>function(t,e){return"horizontal"===e?t:{...t,pathD:ht(t.pathD),gradientStubs:t.gradientStubs?.map(Mt),labelX:t.labelY,labelY:t.labelX,labelAnchor:"middle",labelBaseline:"auto"}}(t,m)),_="vertical"===m?function(t,e,n){const o=t.map(t=>({...t}));for(const t of o){const n=1.22*ft(t.labelText)+4;t.labelX=n>=e-4?e/2:Math.max(n/2+2,Math.min(e-n/2-2,t.labelX))}const s=[],i=[...o].sort((t,e)=>t.labelY-e.labelY||t.labelX-e.labelX);for(const t of i){const e=s[s.length-1];!e||Math.abs(e[0].labelY-t.labelY)>14?s.push([t]):e.push(t)}for(const t of s){t.sort((t,e)=>t.labelX-e.labelX||t.id.localeCompare(e.id));const e=[],o=new Map;for(const n of t){const[t,s]=dt(n);let i=e.findIndex(e=>t>e+8);-1===i&&(i=e.length),e[i]=s,o.set(n,i)}const s=t.reduce((t,e)=>t+e.labelY,0)/t.length,i=s<14*e.length+8;for(const e of t){const t=o.get(e)??0;e.labelY=i?Math.min(n-8,12+14*t):Math.max(8,s-14*t)}}return o}(R,r,l):R,G=new Map;if(null!=h)for(const t of o){const e=t.__raw??t,n="function"==typeof h?h(e):Number(e[h]);Number.isFinite(n)&&G.set(t.id,n)}const Z=function(t,e,n,o,s={}){if(!1===o)return t.map(t=>({...t,labelText:"",labelDeferred:!1,labelFullText:void 0}));if(!0===o)return t.map(t=>({...t,labelDeferred:!1,labelFullText:void 0}));const i=Math.max(1,e*n);let a=Math.max(4,Math.min(t.length,Math.floor(i/14e3)));Number.isFinite(s.maxLabels)&&s.maxLabels>=0&&(a=Math.min(a,Math.floor(s.maxLabels)));const r=t.map((t,e)=>{const n=s.priorityById?.get(t.id),o=Math.abs(t.labelY);return{band:t,index:e,score:null!=n&&Number.isFinite(n)?1e6*n+ft(t.labelText):ft(t.labelText)+.01*o}}).filter(t=>t.band.labelText.trim().length>0).sort((t,e)=>e.score-t.score||t.index-e.index||t.band.id.localeCompare(e.band.id)),l=new Set(r.slice(0,a).map(t=>t.band.id));return t.map(t=>l.has(t.id)||0===t.labelText.trim().length?{...t,labelDeferred:!1,labelFullText:void 0}:{...t,labelFullText:t.labelText,labelText:"",labelDeferred:!0})}(_,r,l,p,{...G.size>0&&{priorityById:G},...null!=b&&{maxLabels:b}});return{layout:$,layoutConfig:{bands:Z,ribbons:H.map(t=>function(t,e){return"horizontal"===e?t:{...t,pathD:ht(t.pathD),bezier:bt(t.bezier)}}(t,m)),showLabels:!1!==p,selectionDatum:M},issues:[],warnings:A,xScale:E}}self.onmessage=t=>{const e=t.data,n=e?.requestId,o=e?.request??e;try{const t=o.colorById??{},e=o.fallbackPalette??["#475569"],a=(n,o)=>t[n]??e[o%e.length]??"#475569",r=Tt({...o.input,colorOf:a});self.postMessage({requestId:n,layout:(i=r.layout,i?{...i,sides:i.sides instanceof Map?[...i.sides.entries()]:i.sides}:null),layoutConfig:(s=r.layoutConfig,{bands:(s.bands??[]).map(({rawDatum:t,...e})=>e),ribbons:(s.ribbons??[]).map(({rawDatum:t,...e})=>e),showLabels:s.showLabels}),issues:r.issues,warnings:r.warnings,domain:o.input.domain,timelineExtent:"vertical"===o.input.orientation?o.input.plotH:o.input.plotW})}catch(t){self.postMessage({requestId:n,error:{message:t instanceof Error?t.message:String(t),name:t instanceof Error?t.name:"Error",stack:t instanceof Error?t.stack:void 0}})}var s,i};