nodejs-map 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +95 -2
  3. package/dist/app/assets/LearnView-Cqz9Ux8w.js +3 -0
  4. package/dist/app/assets/LearnView-Cqz9Ux8w.js.map +1 -0
  5. package/dist/app/assets/LearnView-Nrw6YQU8.css +1 -0
  6. package/dist/app/assets/app.worker-DZKurLgd.js +8 -0
  7. package/dist/app/assets/app.worker-DZKurLgd.js.map +1 -0
  8. package/dist/app/assets/atlas.worker-DGHewGIv.js +2 -0
  9. package/dist/app/assets/atlas.worker-DGHewGIv.js.map +1 -0
  10. package/dist/app/assets/cm-BTWjV_Gb.js +13 -0
  11. package/dist/app/assets/cm-BTWjV_Gb.js.map +1 -0
  12. package/dist/app/assets/dist-B37Ex44M.js +2 -0
  13. package/dist/app/assets/dist-B37Ex44M.js.map +1 -0
  14. package/dist/app/assets/dist-Dv4HNg5q.js +2 -0
  15. package/dist/app/assets/dist-Dv4HNg5q.js.map +1 -0
  16. package/dist/app/assets/index-BRoted4h.css +1 -0
  17. package/dist/app/assets/index-eLItdROg.js +18 -0
  18. package/dist/app/assets/index-eLItdROg.js.map +1 -0
  19. package/dist/app/assets/map-CISW7_cc.css +1 -0
  20. package/dist/app/assets/map-mCCk9DTc.js +132 -0
  21. package/dist/app/assets/map-mCCk9DTc.js.map +1 -0
  22. package/dist/app/assets/sdf-label-font-1nAa0TP8.png +0 -0
  23. package/dist/app/config.json +5 -0
  24. package/dist/app/favicon.svg +1 -0
  25. package/dist/app/index.html +21 -0
  26. package/dist/atlas/v26.13.1/build-report.json +178 -0
  27. package/dist/atlas/v26.13.1/chunks/lib.bootstrap.0.json +1 -0
  28. package/dist/atlas/v26.13.1/chunks/lib.core.0.json +1 -0
  29. package/dist/atlas/v26.13.1/chunks/lib.crypto.0.json +1 -0
  30. package/dist/atlas/v26.13.1/chunks/lib.devtools.0.json +1 -0
  31. package/dist/atlas/v26.13.1/chunks/lib.events.0.json +1 -0
  32. package/dist/atlas/v26.13.1/chunks/lib.fs.0.json +1 -0
  33. package/dist/atlas/v26.13.1/chunks/lib.modules.0.json +1 -0
  34. package/dist/atlas/v26.13.1/chunks/lib.net.0.json +1 -0
  35. package/dist/atlas/v26.13.1/chunks/lib.net.1.json +1 -0
  36. package/dist/atlas/v26.13.1/chunks/lib.platform.0.json +1 -0
  37. package/dist/atlas/v26.13.1/chunks/lib.process.0.json +1 -0
  38. package/dist/atlas/v26.13.1/chunks/lib.rest.0.json +1 -0
  39. package/dist/atlas/v26.13.1/chunks/lib.streams.0.json +1 -0
  40. package/dist/atlas/v26.13.1/chunks/lib.timers.0.json +1 -0
  41. package/dist/atlas/v26.13.1/chunks/lib.workers.0.json +1 -0
  42. package/dist/atlas/v26.13.1/chunks/lib.zlib.0.json +1 -0
  43. package/dist/atlas/v26.13.1/chunks/src.callbacks.0.json +1 -0
  44. package/dist/atlas/v26.13.1/chunks/src.crypto.0.json +1 -0
  45. package/dist/atlas/v26.13.1/chunks/src.diag.0.json +1 -0
  46. package/dist/atlas/v26.13.1/chunks/src.fs.0.json +1 -0
  47. package/dist/atlas/v26.13.1/chunks/src.inspector.0.json +1 -0
  48. package/dist/atlas/v26.13.1/chunks/src.loop.0.json +1 -0
  49. package/dist/atlas/v26.13.1/chunks/src.modules.0.json +1 -0
  50. package/dist/atlas/v26.13.1/chunks/src.napi.0.json +1 -0
  51. package/dist/atlas/v26.13.1/chunks/src.net.0.json +1 -0
  52. package/dist/atlas/v26.13.1/chunks/src.net.1.json +1 -0
  53. package/dist/atlas/v26.13.1/chunks/src.process.0.json +1 -0
  54. package/dist/atlas/v26.13.1/chunks/src.rest.0.json +1 -0
  55. package/dist/atlas/v26.13.1/chunks/src.support.0.json +1 -0
  56. package/dist/atlas/v26.13.1/chunks/src.zlib.0.json +1 -0
  57. package/dist/atlas/v26.13.1/chunks/uv.api.0.json +1 -0
  58. package/dist/atlas/v26.13.1/chunks/uv.backends.0.json +1 -0
  59. package/dist/atlas/v26.13.1/chunks/uv.fs.0.json +1 -0
  60. package/dist/atlas/v26.13.1/chunks/uv.loop.0.json +1 -0
  61. package/dist/atlas/v26.13.1/chunks/uv.net.0.json +1 -0
  62. package/dist/atlas/v26.13.1/chunks/uv.rest.0.json +1 -0
  63. package/dist/atlas/v26.13.1/chunks/uv.threadpool.0.json +1 -0
  64. package/dist/atlas/v26.13.1/chunks/v8.api.0.json +1 -0
  65. package/dist/atlas/v26.13.1/chunks/v8.asmjs.0.json +1 -0
  66. package/dist/atlas/v26.13.1/chunks/v8.ast.0.json +1 -0
  67. package/dist/atlas/v26.13.1/chunks/v8.base.0.json +1 -0
  68. package/dist/atlas/v26.13.1/chunks/v8.baseline.0.json +1 -0
  69. package/dist/atlas/v26.13.1/chunks/v8.bigint.0.json +1 -0
  70. package/dist/atlas/v26.13.1/chunks/v8.builtins.0.json +1 -0
  71. package/dist/atlas/v26.13.1/chunks/v8.codegen.0.json +1 -0
  72. package/dist/atlas/v26.13.1/chunks/v8.codegen.riscv.0.json +1 -0
  73. package/dist/atlas/v26.13.1/chunks/v8.common.0.json +1 -0
  74. package/dist/atlas/v26.13.1/chunks/v8.compiler-dispatcher.0.json +1 -0
  75. package/dist/atlas/v26.13.1/chunks/v8.compiler.0.json +1 -0
  76. package/dist/atlas/v26.13.1/chunks/v8.compiler.backend.0.json +1 -0
  77. package/dist/atlas/v26.13.1/chunks/v8.compiler.turboshaft.0.json +1 -0
  78. package/dist/atlas/v26.13.1/chunks/v8.d8.0.json +1 -0
  79. package/dist/atlas/v26.13.1/chunks/v8.date.0.json +1 -0
  80. package/dist/atlas/v26.13.1/chunks/v8.debug.0.json +1 -0
  81. package/dist/atlas/v26.13.1/chunks/v8.deoptimizer.0.json +1 -0
  82. package/dist/atlas/v26.13.1/chunks/v8.diagnostics.0.json +1 -0
  83. package/dist/atlas/v26.13.1/chunks/v8.dumpling.0.json +1 -0
  84. package/dist/atlas/v26.13.1/chunks/v8.execution.0.json +1 -0
  85. package/dist/atlas/v26.13.1/chunks/v8.extensions.0.json +1 -0
  86. package/dist/atlas/v26.13.1/chunks/v8.flags.0.json +1 -0
  87. package/dist/atlas/v26.13.1/chunks/v8.fuzzilli.0.json +1 -0
  88. package/dist/atlas/v26.13.1/chunks/v8.handles.0.json +1 -0
  89. package/dist/atlas/v26.13.1/chunks/v8.heap.0.json +1 -0
  90. package/dist/atlas/v26.13.1/chunks/v8.heap.cppgc.0.json +1 -0
  91. package/dist/atlas/v26.13.1/chunks/v8.ic.0.json +1 -0
  92. package/dist/atlas/v26.13.1/chunks/v8.init.0.json +1 -0
  93. package/dist/atlas/v26.13.1/chunks/v8.inspector.0.json +1 -0
  94. package/dist/atlas/v26.13.1/chunks/v8.interpreter.0.json +1 -0
  95. package/dist/atlas/v26.13.1/chunks/v8.json.0.json +1 -0
  96. package/dist/atlas/v26.13.1/chunks/v8.libplatform.0.json +1 -0
  97. package/dist/atlas/v26.13.1/chunks/v8.libsampler.0.json +1 -0
  98. package/dist/atlas/v26.13.1/chunks/v8.logging.0.json +1 -0
  99. package/dist/atlas/v26.13.1/chunks/v8.maglev.0.json +1 -0
  100. package/dist/atlas/v26.13.1/chunks/v8.numbers.0.json +1 -0
  101. package/dist/atlas/v26.13.1/chunks/v8.objects.0.json +1 -0
  102. package/dist/atlas/v26.13.1/chunks/v8.parsing.0.json +1 -0
  103. package/dist/atlas/v26.13.1/chunks/v8.profiler.0.json +1 -0
  104. package/dist/atlas/v26.13.1/chunks/v8.regexp.0.json +1 -0
  105. package/dist/atlas/v26.13.1/chunks/v8.root.0.json +1 -0
  106. package/dist/atlas/v26.13.1/chunks/v8.roots.0.json +1 -0
  107. package/dist/atlas/v26.13.1/chunks/v8.runtime.0.json +1 -0
  108. package/dist/atlas/v26.13.1/chunks/v8.sandbox.0.json +1 -0
  109. package/dist/atlas/v26.13.1/chunks/v8.snapshot.0.json +1 -0
  110. package/dist/atlas/v26.13.1/chunks/v8.strings.0.json +1 -0
  111. package/dist/atlas/v26.13.1/chunks/v8.tasks.0.json +1 -0
  112. package/dist/atlas/v26.13.1/chunks/v8.torque.0.json +1 -0
  113. package/dist/atlas/v26.13.1/chunks/v8.tracing.0.json +1 -0
  114. package/dist/atlas/v26.13.1/chunks/v8.trap-handler.0.json +1 -0
  115. package/dist/atlas/v26.13.1/chunks/v8.utils.0.json +1 -0
  116. package/dist/atlas/v26.13.1/chunks/v8.wasm.0.json +1 -0
  117. package/dist/atlas/v26.13.1/chunks/v8.zone.0.json +1 -0
  118. package/dist/atlas/v26.13.1/edges.json +1 -0
  119. package/dist/atlas/v26.13.1/files.json +1 -0
  120. package/dist/atlas/v26.13.1/index.json +1 -0
  121. package/dist/atlas/v26.13.1/search.json +1 -0
  122. package/dist/cli.js +6268 -0
  123. package/dist/examples.json +1 -0
  124. package/dist/learn/async-await.json +1 -0
  125. package/dist/learn/backpressure.json +1 -0
  126. package/dist/learn/big-picture.json +1 -0
  127. package/dist/learn/blocking-the-loop.json +1 -0
  128. package/dist/learn/breakpoints.json +1 -0
  129. package/dist/learn/call-stack.json +1 -0
  130. package/dist/learn/first-run.json +1 -0
  131. package/dist/learn/follow-readfile.json +1 -0
  132. package/dist/learn/four-threads-six-jobs.json +1 -0
  133. package/dist/learn/glossary.json +1 -0
  134. package/dist/learn/hiding-areas.json +1 -0
  135. package/dist/learn/http-one-request.json +1 -0
  136. package/dist/learn/http-two-requests.json +1 -0
  137. package/dist/learn/img/big-picture.webp +0 -0
  138. package/dist/learn/img/first-run-queues.webp +0 -0
  139. package/dist/learn/img/hide-restore-strip.webp +0 -0
  140. package/dist/learn/img/hide-view-menu.webp +0 -0
  141. package/dist/learn/img/map-call-path.webp +0 -0
  142. package/dist/learn/img/marks-in-a-run.webp +0 -0
  143. package/dist/learn/img/paused-at-breakpoint.webp +0 -0
  144. package/dist/learn/img/paused-in-node-fs.webp +0 -0
  145. package/dist/learn/img/playback-bar.webp +0 -0
  146. package/dist/learn/img/save-and-share.webp +0 -0
  147. package/dist/learn/img/tour-areas.webp +0 -0
  148. package/dist/learn/index.json +390 -0
  149. package/dist/learn/keep-alive.json +1 -0
  150. package/dist/learn/loop-phases.json +1 -0
  151. package/dist/learn/many-clients.json +1 -0
  152. package/dist/learn/microtasks-belong-to-v8.json +1 -0
  153. package/dist/learn/next-tick.json +1 -0
  154. package/dist/learn/observed-and-inferred.json +1 -0
  155. package/dist/learn/one-libuv-timer.json +1 -0
  156. package/dist/learn/order-and-esm.json +1 -0
  157. package/dist/learn/pipeline-errors.json +1 -0
  158. package/dist/learn/playback.json +1 -0
  159. package/dist/learn/pool-size.json +1 -0
  160. package/dist/learn/prerequisites.json +1 -0
  161. package/dist/learn/probe-build.json +1 -0
  162. package/dist/learn/promises-and-microtasks.json +1 -0
  163. package/dist/learn/reading-a-file.json +1 -0
  164. package/dist/learn/rec/async-await-chain.nmrec.gz +0 -0
  165. package/dist/learn/rec/backpressure.nmrec.gz +0 -0
  166. package/dist/learn/rec/beforeexit-and-exit.nmrec.gz +0 -0
  167. package/dist/learn/rec/block-loop.nmrec.gz +0 -0
  168. package/dist/learn/rec/dns-lookup-thread-pool.nmrec.gz +0 -0
  169. package/dist/learn/rec/esm-twist.nmrec.gz +0 -0
  170. package/dist/learn/rec/eventemitter-is-synchronous.nmrec.gz +0 -0
  171. package/dist/learn/rec/first-run.nmrec.gz +0 -0
  172. package/dist/learn/rec/fs-promises-await.nmrec.gz +0 -0
  173. package/dist/learn/rec/fs-sync-vs-async.nmrec.gz +0 -0
  174. package/dist/learn/rec/http-blocking-fixed.nmrec.gz +0 -0
  175. package/dist/learn/rec/http-blocking.nmrec.gz +0 -0
  176. package/dist/learn/rec/http-keep-alive.nmrec.gz +0 -0
  177. package/dist/learn/rec/http-roundtrip.nmrec.gz +0 -0
  178. package/dist/learn/rec/http-two-requests.nmrec.gz +0 -0
  179. package/dist/learn/rec/interval-and-clear.nmrec.gz +0 -0
  180. package/dist/learn/rec/nested-ticks-and-microtasks.nmrec.gz +0 -0
  181. package/dist/learn/rec/next-tick.nmrec.gz +0 -0
  182. package/dist/learn/rec/pbkdf2-six-jobs-four-threads.nmrec.gz +0 -0
  183. package/dist/learn/rec/phase-check.nmrec.gz +0 -0
  184. package/dist/learn/rec/phase-close.nmrec.gz +0 -0
  185. package/dist/learn/rec/phase-io.nmrec.gz +0 -0
  186. package/dist/learn/rec/pipeline-error.nmrec.gz +0 -0
  187. package/dist/learn/rec/pool-users.nmrec.gz +0 -0
  188. package/dist/learn/rec/pool-with-two-threads.nmrec.gz +0 -0
  189. package/dist/learn/rec/promise-microtasks.nmrec.gz +0 -0
  190. package/dist/learn/rec/readfile-thread-pool.nmrec.gz +0 -0
  191. package/dist/learn/rec/run-to-completion.nmrec.gz +0 -0
  192. package/dist/learn/rec/split-work.nmrec.gz +0 -0
  193. package/dist/learn/rec/stream-pipeline-file.nmrec.gz +0 -0
  194. package/dist/learn/rec/streams-memory.nmrec.gz +0 -0
  195. package/dist/learn/rec/tcp-many-clients.nmrec.gz +0 -0
  196. package/dist/learn/rec/tcp-round-trip.nmrec.gz +0 -0
  197. package/dist/learn/rec/tick-before-promise.nmrec.gz +0 -0
  198. package/dist/learn/rec/timeout-vs-immediate-io.nmrec.gz +0 -0
  199. package/dist/learn/rec/timeout-vs-immediate-main.nmrec.gz +0 -0
  200. package/dist/learn/rec/timer-lateness.nmrec.gz +0 -0
  201. package/dist/learn/rec/timer-vs-file-read.nmrec.gz +0 -0
  202. package/dist/learn/rec/timers-phase.nmrec.gz +0 -0
  203. package/dist/learn/rec/unref-timer.nmrec.gz +0 -0
  204. package/dist/learn/save-and-share.json +1 -0
  205. package/dist/learn/slow-handler.json +1 -0
  206. package/dist/learn/splitting-work.json +1 -0
  207. package/dist/learn/staying-alive.json +1 -0
  208. package/dist/learn/stepping-into-node.json +1 -0
  209. package/dist/learn/streams-basics.json +1 -0
  210. package/dist/learn/tcp-step-by-step.json +1 -0
  211. package/dist/learn/the-map.json +1 -0
  212. package/dist/learn/three-marks.json +1 -0
  213. package/dist/learn/timeout-vs-immediate.json +1 -0
  214. package/dist/learn/timers-are-not-now.json +1 -0
  215. package/dist/learn/tour.json +1 -0
  216. package/dist/learn/what-it-is.json +1 -0
  217. package/dist/learn/what-uses-the-pool.json +1 -0
  218. package/dist/lessons/async-await-chain.nmrec.gz +0 -0
  219. package/dist/lessons/beforeexit-and-exit.nmrec.gz +0 -0
  220. package/dist/lessons/dns-lookup-thread-pool.nmrec.gz +0 -0
  221. package/dist/lessons/esm-twist.nmrec.gz +0 -0
  222. package/dist/lessons/eventemitter-is-synchronous.nmrec.gz +0 -0
  223. package/dist/lessons/fs-promises-await.nmrec.gz +0 -0
  224. package/dist/lessons/fs-sync-vs-async.nmrec.gz +0 -0
  225. package/dist/lessons/index.json +621 -0
  226. package/dist/lessons/interval-and-clear.nmrec.gz +0 -0
  227. package/dist/lessons/nested-ticks-and-microtasks.nmrec.gz +0 -0
  228. package/dist/lessons/pbkdf2-six-jobs-four-threads.nmrec.gz +0 -0
  229. package/dist/lessons/pool-with-two-threads.nmrec.gz +0 -0
  230. package/dist/lessons/readfile-thread-pool.nmrec.gz +0 -0
  231. package/dist/lessons/tcp-round-trip.nmrec.gz +0 -0
  232. package/dist/lessons/tick-before-promise.nmrec.gz +0 -0
  233. package/dist/lessons/timeout-vs-immediate-io.nmrec.gz +0 -0
  234. package/dist/lessons/timeout-vs-immediate-main.nmrec.gz +0 -0
  235. package/dist/lessons/timer-vs-file-read.nmrec.gz +0 -0
  236. package/dist/lessons/timers-phase.nmrec.gz +0 -0
  237. package/dist/preload.cjs +507 -0
  238. package/package.json +25 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-eLItdROg.js","names":["n","t","r","u","i","f","o","e","l","c","a","h","p","y","v","w","d","_","g","n","k","r","u","f","e","m","$","x","S","C","z","E","j","L","H","I","l","c","a","s","h","v","w","d","_","g","k","q","G","A","y","P","J","T","N","V","p","b","m","M","C","j","q","A","O","P","T","B","K","D","F","x","Q","done","milestone","name","t","r","u","i","o","f","c","e","a","n","v","l","m","h","s","p","y","d","_","G","i","A","E","F","T","w","b","g","D","B","k","z","f","o","a","r","cmModule","loadCodeMirror","__vitePreload","CodeView","props","host","useRef","handle","ready","setReady","useState","failed","setFailed","latest","withBreakpoints","emitted","unechoed","useEffect","live","cm","text","line","marks","markLine","markKind","markTag","scrolledAt","frame","timer","apply","el","mark","now","scroll","_jsxs","_jsx","on","off","reason","DEFAULT_REASONS","gateReason","gate","notes","note","controlStates","input","connected","provider","status","caps","cannotStart","noDebugger","whenLive","extra","jsControl","needPaused","gateControl","kind","gateGroupReason","states","ids","id","reasons","only","ATLAS_SCHEMA","CHUNK_SCHEMA","FILES_SCHEMA","SEARCH_SCHEMA","EDGES_SCHEMA","CHUNK_COLS","AtlasValidationError","what","problems","MAX_PROBLEMS","OS_TAGS","INDEX_KINDS","ROW_KINDS","SAFE_PATH","SAFE_URL","Checker","msg","at","opt","min","max","nullable","ok","\"path\"","\"start\"","\"end\"","\"sym\"","\"os\"","\"url\"","report","validateIndex","\"schema\"","node","\"node\"","\"version\"","\"commit\"","\"repo\"","world","\"world\"","\"w\"","\"h\"","boxes","\"boxes\"","\"id\"","\"p\"","\"k\"","\"t\"","\"n\"","\"d\"","\"r\"","loc","\"loc\"","\"tree\"","paths","\"paths\"","\"title\"","\"certainty\"","steps","sat","st","\"desc\"","\"thread\"","\"locs\"","\"steps\"","\"branches\"","chunks","\"chunks\"","ch","\"group\"","\"rows\"","\"bytes\"","aliases","\"aliases\"","t","validateChunk","knownParents","\"cols\"","rows","seen","variant","validateFiles","chunkCount","\"files\"","validateSearch","\"entries\"","validateEdges","\"edges\"","\"kind\"","\"from\"","REPO","enc","path","lines","start","end","githubBlobUrl","commit","githubTreeUrl","githubDevUrl","GITHUB_DEV_NOTE","rawSourceUrl","osMatches","os","platform","pickRange","ranges","best","bestScore","score","boxLinks","box","scriptUrlToPath","url","ROW_KIND","WORLD","indexBoxToBox","rowToBox","row","chunk","AtlasStore","#fetchJson","#indexUrl","#index","#boxes","#children","#abs","#chunks","#files","#search","#edges","opts","index","#add","list","cur","real","have","ref","#chunkForPath","group","cached","abs","chunkId","raw","view","out","#loadFiles","fileId","visit","child","query","limit","entries","hits","label","tail","tier","WELL_KNOWN","PHASE_IDS","ASYNC_TYPE_INFO","ASYNC_TYPE_AT","type","QUEUE_LABEL","QUEUE_HELP","PHASE_LABEL","SOURCE_LABEL","SOURCE_HELP","nf1","nf3","nf0","formatMicros","us","formatMillis","ms","formatCount","plural","one","many","baseName","urlOrPath","parts","part","isSameProgram","scriptUrl","programName","oneLine","code","OWN_WORDS","itemKindWords","title","own","crypto","itemTitle","item","words","LOG_GROUPS","LOG_GROUP_LABEL","h","w","o","d","x","y","b","_","O","p","g","S","m","a","t","useSignal","o","v","f","c","i","n","k","s","r","l","F","useSignalEffect","e","u","TIMELINE_CLASSES","PHASE_CODES","CERTAINTY_CODES","table","RecordingError","message","LIMITS","fail","str","num","nonNeg","int","poolSize","count","bool","oneOf","allowed","req","check","isPlainObject","proto","object","spec","extraAllowed","key","value","obj","LOC","FRAME","NODE_INFO","CERT","CAPS","PHASE","QUEUE","frames","args","keys","BASE","PAYLOADS","\"output\"","\"scope\"","\"signal\"","\"note\"","SPEC_BY_KIND","S","ENTRIES","BACKGROUND_IDS","RULES","BACKGROUND","BY_ID","ruleById","PERSISTENT_HANDLE_TYPES","BY_ID","replayRuleById","SHARE_LINK_SAFE_CHARS","FRAGMENT_PREFIX","B64","B64_VALUE","QUEUES","listApply","before","patch","entry","chunkKey","logKey","applyViewPatch","previous","queues","changed","CERTAINTIES","CERTAINTY_LABEL","CERTAINTY_MEANING","RANK","weakest","APP_RULES","PHASE_RING_RULE","findRule","RULE_PLATFORM_LABEL","MAX_LABEL","lineStarts","starts","lineAt","offset","lo","hi","mid","FUNCTION_VALUES","STOPS_NAME_SEARCH","namedDeclaration","def","pending","assign","target","targetText","userFileId","fileName","extractUserBoxes","parser","lineCount","found","top","userBoxAtLine","buildHighlights","ctx","byKey","add","role","certainty","badge","place","waiting","busy","thread","job","from","actionPlace","callbackPlace","LINE_TAGS","highlightFor","where","sameHighlight","pauseWords","LESSON_ID","parseRoute","hash","routeHash","route","sameRoute","MAX_TEXT","MAX_BLOCKS","MAX_ITEMS","str","parseLearnIndex","chapters","lessons","\"lessons\"","le","\"file\"","level","\"level\"","minutes","\"minutes\"","\"summary\"","lessonsOf","parseInline","\"text\"","\"href\"","parseBlock","\"ordered\"","\"items\"","\"lang\"","\"example\"","width","\"width\"","height","\"height\"","\"src\"","caption","\"caption\"","\"alt\"","\"question\"","\"answer\"","parseExample","example","\"name\"","\"module\"","\"racy\"","\"recording\"","step","\"index\"","parseLearnLesson","examples","\"examples\"","neighbour","prev","\"prev\"","next","\"next\"","\"chapter\"","\"blocks\"","safeExternalUrl","href","inlinePieces","inline","lesson","courseFileUrl","indexUrl","lessonUrl","file","base","snippetNameFor","LEARN_STORAGE_KEY","parseProgress","empty","\"done\"","\"last\"","\"introDismissed\"","REPLY_OP","EVENTS_FRAME","HelperError","ProtocolClient","#socket","#opts","#waiting","#nextId","#open","#closed","#opened","resolve","reject","#handleClose","ev","#handleMessage","welcome","data","webSocketUrl","relative","pageUrl","EMPTY","normalizePlatform","fileTarget","targetForAtlasId","atlas","range","other","targetForNodeFrame","boxId","languageOfPath","isSafeTag","tag","withSlash","folder","urlInside","createAtlasStore","deps","state","signal","current","store","fetchJson","response","MAX_NOTICE_CHARS","publicUrl","parseAppConfig","optionalPath","atlasBase","\"atlasBase\"","learn","\"mode\"","\"ws\"","playerUrl","createConnectionStore","config","signal","notices","error","client","nextNotice","notify","notice","computed","opened","mine","QUEUE_NAMES","VIEW_OPTIONS","KICK_MS","TICK_TIMEOUT_MS","createParts","signal","createPlayerStore","worker","clock","publish","batch","player","timeline","markers","problem","nextId","kickUntil","touched","ticking","tickSentAt","cancelFrame","disposed","timelineWanted","post","transfer","needsTicks","kick","ask","send","settle","re","event","cmd","filter","position","axis","run","fragment","header","gzip","isNodeFile","clean","withFile","map","marksOf","set","off","entriesOf","toggled","removed","withEnabled","enabled","withMarks","enabledAt","sameMarks","breakpointsToSend","active","appliesTo","scriptUrlOfPath","SPEEDS","DEFAULT_SNIPPET","AREA_IDS","DEFAULT_AREAS","areasOf","TAB_IDS","oneOf","fraction","bool","SPLIT_MIN","SPLIT_MAX","SHEET_MIN","SHEET_MAX","POOL_SIZE_MAX","linesByFile","validators","DEFAULTS","STORAGE_KEY","parseSettings","createSettings","storage","schedule","write","stored","initial","settings","signal","first","snapshot","dispose","effect","browserStorage","MAX_EXAMPLES","parseExamples","exampleFileName","createProgramStore","source","signal","fileTicket","computed","breakpointSet","snippetName","module","dir","AREA_LABEL","AREA_KEY","LAST_AREA_MESSAGE","createLayoutStore","areas","narrow","shown","computed","sheet","area","on","wanted","split","createLearnStore","saved","signal","introDismissed","returnTo","last","ticket","persist","showRouteLesson","all","computed","isDone","back","decideAutoReplay","speedWords","speed","stepsPerSecond","rate","count","word","planRun","wantsDebugger","thenReplays","stops","says","why","MAX_LESSONS","MAX_STEPS","parseLessons","lessonRecordingUrl","recording","recordingFileName","errorText","createSessionStore","connection","program","signal","opening","starting","runActive","gates","announcement","replaying","replayStarts","touchesAtStart","debuggerInUse","stopRequested","replaySeenPlaying","touchesAtReplay","effect","liveSource","openTicket","announce","computed","liveStatus","controls","plan","refuse","liveRun","activeRun","armedGates","chosen","can","stopLiveRun","adoptRecording","open","origin","headerForSave","includeSource","info","sources","rest","mode","breakpoints","pauseOnStart","reply","action","onOff","final","ended","finished","decision","guide","absolute","request","MAX_CACHED","createSourceStore","signal","cache","remember","load","result","fromProgram","fetchRawText","createUiStore","signal","startWorker","import.meta.ROLLDOWN_FILE_URL_7ZSdDL2aCnJUqjfBOtOsLw","like","fn","ui","session","fitMap","layout","helperMode","computed","hasRun","pick","src","userBoxes","signal","lastHighlights","highlights","focus","loop","main","pool","debug","old","lastCodeHighlight","codeHighlight","editorMark","sourceMark","lastCodeLine","codeLine","spot","showTab","tab","reveal","showOnMap","openSource","revealInEditor","openFrame","openLoc","revealTicket","playExample","lessonId","runExample","openPathFromLesson","pathId","picker","jumpToEvent","direction","openMark","changeSpeed","toggleTheme","dark","downloadBytes","bytes","openRecordingFile","shareBaseUrl","bootError","fragmentHasRecording","openFragmentIfAny","boot","effect","theme","\"theme\"","served","onShow","untracked","seenRun","seenPause","tabBeforeSource","pause","FOLLOW_SETTLE_MS","FOLLOW_GAP_MS","MAP_FIT_ID","dragFrom","DRAG_PX","userMovedMap","noteMapInteraction","actionBox","playing","coarse","showActionOnMap","flownTo","flownAt","lastVersionZero","wait","Ctl","children","onAct","pressed","useId","hint","showHint","clearHint","_jsxs","PATHS","Icon","_jsx","PHASES","ModuleSelect","_jsxs","_jsx","Options","snippet","debuggerNote","Gates","phase","setPhase","useState","groupReason","capable","armed","RunMore","RunButtons","paused","more","stop","mac","keysOf","toggleArea","ViewMenu","setOpen","useState","button","useRef","menu","menuId","useId","items","close","focusButton","focusAt","setFocusAt","useEffect","onDown","onMenuKey","any","act","_jsxs","_jsx","AreaClose","RestoreStrip","vertical","What","_jsxs","_jsx","REAL_TIME_WHY","FROZEN_WHY","PausedStrip","atTail","canAct","elsewhere","Strip","helper","noLinesNote","lineNote","ProgramCode","EditorPane","debugNote","mods","SHORTCUTS","isPrintable","comboMatches","combo","ctrl","matchShortcut","typing","plain","KEY_WORDS","comboKeys","bucketForIndex","summary","fractionOfPosition","span","bucket","within","seekForFraction","barHeight","bucketsForWidth","cssWidth","useElementSize","useRef","size","setSize","useState","useLayoutEffect","update","observer","mediaMatches","useMedia","matches","setMatches","useEffect","useRowHeight","listKeyDown","container","selector","LIST_KEYS","HEIGHT","BAR_CLASSES","color","PHASE_COLOR","colorCache","themeColors","canvas","css","colors","get","draw","dpr","bw","classes","barBottom","barSpan","total","pauseColor","skip","full","xOfIndex","stdout","stderr","lastX","x0","Timeline","wrap","useRef","cursor","future","length","useEffect","useLayoutEffect","redraw","seekAt","clientX","rect","_jsxs","jump","handled","_jsx","STEP_UNITS","stepUnit","signal","StepUnitSelect","_jsx","_jsxs","SPEED_HINT","useReplayFlash","flash","setFlash","useState","useRef","useEffect","SpeedSelect","Transport","nothing","atStart","atEnd","unit","dead","play","forward","moveMap","follow","_Fragment","Banner","onDismiss","_jsxs","_jsx","PausedBanner","GateBanner","GATE_WORDS","VersionNotice","LearnLinks","Banners","connError","sessionError","atlasState","DASH","MarkGlyph","_jsxs","_jsx","Mark","rule","subject","tabbable","FactMark","fact","ProviderSelect","providers","_jsxs","_jsx","What","compact","_Fragment","REPLAYING","Legend","RecordingActions","fileInput","Views","learning","TopBar","Dialog","onClose","wide","useRef","titleId","useId","alive","requestClose","useEffect","dialog","opener","_jsxs","_jsx","LegendDialog","_jsxs","_jsx","Citation","setTarget","useState","useEffect","RuleBody","MarkDialog","GROUPS","HIDDEN_IN_HELP","Keys","ShortcutRow","shortcut","tabs","HelpDialog","FileBrowser","setDir","setState","parent","runnable","ProgramDialog","SourceChoice","onChange","SaveDialog","include","setInclude","setGzip","setBusy","ShareDialog","setResult","copied","setCopied","link","MoreDialog","PlaybackDialog","useDropToOpen","hasFiles","over","leave","drop","Dialogs","MapStandIn","flyTo","_jsx","loadMap","MapRegion","Panel","setPanel","useState","useEffect","body","_jsx","_jsxs","cursorRowIn","window","memo","render","same","Memo","MAX_SCROLL_PX","virtualWindow","scrollTop","viewportHeight","rowHeight","overscan","natural","totalHeight","visible","maxScroll","firstVisible","maxFirst","scrollTopForRow","lead","OWN_SCROLL_MS","VirtualList","renderRow","onWindow","keepVisible","onKeyDown","activeDescendant","useRef","rerender","useState","spacer","kept","ownScrollUntil","keepKey","win","useLayoutEffect","useEffect","_jsx","MapButton","_jsx","LocButton","ItemChip","queue","_jsxs","itemMapId","Row","meta","mapId","selected","onActivate","activate","Empty","Section","aside","NoRun","MARGIN","LOW_WATER","groupsOn","signal","certaintyOn","followCursor","toggle","EventRow","_jsxs","_jsx","EventsPanel","groups","setData","useState","shownRows","useRef","again","version","dataKey","useCallback","asked","local","cursorRow","dataRef","covered","stale","needCursor","useEffect","rowAt","move","OpenLesson","go","_jsx","_jsxs","_Fragment","each","Gallery","openId","Programs","LessonsPanel","lists","parts","RING","DASH","arc","radius","gap","a0","a1","ARCS","PhaseRing","osName","_jsxs","lit","_jsx","viaWords","useIsCloseCallback","setSeen","useState","useEffect","answer","MainThread","closing","TriggerChain","chain","setChain","PositionLine","RunFacts","Notes","LastPause","Problems","NowPanel","MAX_CHUNK_CHARS","cleanOutput","Chunk","cut","_jsxs","_jsx","OutputPanel","output","scroller","useRef","pinned","useEffect","parts","MAX_ROWS","jobWords","JobBody","_jsxs","_Fragment","_jsx","Lane","JobList","jobs","which","Notice","how","PoolPanel","requests","held","tid","parts","MAX_ROWS","QUEUES","QueueHead","_jsxs","_jsx","More","LeftAtEnd","Queue","_Fragment","Due","dueIn","timerMeta","Timers","timers","recent","waitingTotal","Elsewhere","QueuesPanel","SourcePanel","_jsx","script","_jsxs","_Fragment","MAX_VARIABLES","MAX_DEPTH","useRequest","useState","useEffect","Variables","objectId","depth","pauseKey","loaded","_jsx","_jsxs","Variable","variable","expandable","_Fragment","Scope","scope","startOpen","Scopes","liveNow","ScopeList","frameWhere","PausedStack","CallbackStack","stack","lineText","nodeLines","Breakpoints","nodeFile","warnings","warning","StackPanel","TABS","visibleTabs","Panels","strip","useRef","widths","markEdges","useLayoutEffect","useEffect","_jsxs","_jsx","Splitter","clamp","fromPointer","_jsx","isTyping","useShortcuts","useEffect","onKey","Hint","_jsx","learnModule","LearnSlot","View","setView","useState","App","layout","useRef","side","splitMap","splitEditor","splitSheet","useLayoutEffect","layoutStore","noSide","layoutClass","sideClass","_jsxs","_Fragment","root","render","_jsx"],"sources":["../../../../node_modules/.pnpm/preact@11.2.0/node_modules/preact/dist/preact.mjs","../../src/lib/marks.ts","../../../../node_modules/.pnpm/preact@11.2.0/node_modules/preact/hooks/dist/hooks.mjs","../../../../node_modules/.pnpm/preact@11.2.0/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs","../../src/editor/CodeView.tsx","../../src/lib/controls.ts","../../../atlas-format/src/schema.ts","../../../atlas-format/src/validate.ts","../../../atlas-format/src/links.ts","../../../atlas-format/src/store.ts","../../../atlas-format/src/well-known.ts","../../src/lib/format.ts","../../../../node_modules/.pnpm/@preact+signals-core@1.14.5/node_modules/@preact/signals-core/dist/signals-core.module.js","../../../../node_modules/.pnpm/@preact+signals@2.11.4_preact@11.2.0/node_modules/@preact/signals/dist/signals.module.js","../../../replay/src/types.ts","../../../replay/src/run-index.ts","../../../event-format/src/validate.ts","../../../event-format/src/rules.ts","../../../replay/src/reducer.ts","../../../replay/src/rules.ts","../../../replay/src/timeline.ts","../../../replay/src/replay.ts","../../../replay/src/recording.ts","../../../replay/src/patch.ts","../../src/lib/certainty.ts","../../src/lib/userBoxes.ts","../../src/lib/highlights.ts","../../src/lib/sourceLine.ts","../../src/lib/route.ts","../../src/lib/learn.ts","../../src/lib/protocolClient.ts","../../src/lib/sourceTarget.ts","../../src/stores/atlas.ts","../../src/stores/connection.ts","../../src/stores/player.ts","../../src/lib/breakpoints.ts","../../src/stores/settings.ts","../../src/stores/program.ts","../../src/stores/layout.ts","../../src/stores/learn.ts","../../src/lib/autoReplay.ts","../../src/lib/runMode.ts","../../src/stores/session.ts","../../src/stores/source.ts","../../src/stores/ui.ts","../../src/stores/index.ts","../../src/shell/Ctl.tsx","../../src/shell/icons.tsx","../../src/editor/RunControls.tsx","../../src/shell/ViewMenu.tsx","../../src/editor/EditorPane.tsx","../../src/lib/shortcuts.ts","../../src/lib/timelineMath.ts","../../src/shell/hooks.ts","../../src/transport/Timeline.tsx","../../src/transport/Transport.tsx","../../src/shell/Banners.tsx","../../src/shell/Mark.tsx","../../src/shell/TopBar.tsx","../../src/shell/Dialog.tsx","../../src/shell/Dialogs.tsx","../../src/shell/MapStandIn.tsx","../../src/shell/MapRegion.tsx","../../src/lib/logIndex.ts","../../src/shell/memo.ts","../../src/lib/virtual.ts","../../src/shell/VirtualList.tsx","../../src/panels/parts.tsx","../../src/panels/EventsPanel.tsx","../../src/panels/LessonsPanel.tsx","../../src/panels/NowPanel.tsx","../../src/panels/OutputPanel.tsx","../../src/panels/PoolPanel.tsx","../../src/panels/QueuesPanel.tsx","../../src/panels/SourcePanel.tsx","../../src/panels/StackPanel.tsx","../../src/shell/Panels.tsx","../../src/shell/Splitter.tsx","../../src/shell/App.tsx","../../src/main.tsx"],"sourcesContent":["var n,t,r,u,i,f,o,e,l,c,a,s,h=Symbol.for(\"pv\"),p={},y=[],v=/^m(i|n|o|s|text|space)$/,w=Array.isArray,d=y.slice,_=Object.assign;function g(n){n&&n.parentNode&&n.remove()}function k(n,t,r){var u,i,f,o={},e=arguments.length;for(f in t)\"key\"==f?u=t[f]:\"ref\"==f&&\"function\"!=typeof n?i=t[f]:o[f]=t[f];return e>2&&(o.children=e>3?d.call(arguments,2):r),m(n,o,u,i,null)}function b(n,t,r){var u,i,f,o=_({},n.props),e=arguments.length;for(f in t)\"key\"==f?u=t[f]:\"ref\"==f&&\"function\"!=typeof n.type?i=t[f]:o[f]=t[f];return e>2&&(o.children=e>3?d.call(arguments,2):r),m(n.type,o,void 0!==u?u:n.key,void 0!==i?i:n.ref,null)}function m(r,u,i,f,o){var e={type:r,props:u,key:i,ref:f,__k:null,__:null,__b:0,__e:null,__c:null,constructor:h,__v:o||++t,__i:-1,__u:0};return!o&&n.vnode&&n.vnode(e),e}function M(){return{current:null}}function $(n){return n.children}function x(n,t){this.props=n,this.context=t,this.__g=0}function S(n,t){if(null==t)return n.__&&S(n.__,n.__i+1);for(var r;t<n.__k.length;t++)if((r=n.__k[t])&&r.__e)return r.__e;return\"function\"!=typeof n.type||n.props.__P?null:S(n)}function C(t){var r,u=t.__v,i=u.__e,f=[],o=[],e=t.__P;e&&((r=_({constructor:h},u)).__v=u.__v+1,n.vnode&&n.vnode(r),z(e,r,u,t.__n,e.namespaceURI,32&u.__u?[i]:null,f,i||S(u),32&u.__u,o),r.__v=u.__v,r.__.__k[r.__i]=r,E(f,r,o),u.__=u.__e=null,r.__e!=i&&j(r))}function j(n){if((n=n.__)&&n.__c&&!n.props.__P)return n.__e=null,n.__k.some(function(t){return t&&(n.__e=t.__e)}),j(n)}function L(t){(8&t.__g||(t.__g|=8,u.push(t),f++))&&i==n.debounceRendering||((i=n.debounceRendering)||queueMicrotask)(H)}function H(){try{for(var n,t=1;u.length;)u.length>t&&u.sort(o),n=u.shift(),t=u.length,8&n.__g&&C(n)}finally{(f=u.length)&&(i||queueMicrotask)(H)}}function I(n,t,r,u,i,f,o,e,l,c,a){var s,h,v,w,d,_,g=u.__k||y,k=t.length;for(l=q(r,t,g,l,k),s=0;s<k;s++)null!=(v=r.__k[s])&&(h=~v.__i&&g[v.__i]||p,v.__i=s,_=z(n,v,h,i,f,o,e,l,c,a),w=v.__e,(h.ref!=v.ref||8&h.__u)&&(h.ref&&G(h.ref,null,v,h),v.ref&&a.push(v.ref,v.__c||w,v)),d=d||w,4&v.__u?(l=A(v,l,n,!h.__v),h.__e&&(h.__e=null)):\"function\"==typeof v.type&&void 0!==_?l=_:w&&(l=w.nextSibling),v.__u&=-21);return r.__e=d,l}function q(n,t,r,u,i){var f,o,e,l,c,a,s,p,y,v=r.length,d=v,_=0,g=0,k=n.__k=Array(i);for(f=0;f<i;f++)null!=(o=t[f])&&\"boolean\"!=typeof o&&\"function\"!=typeof o?(\"object\"!=typeof o||o.constructor===String?o=k[f]=m(null,o):w(o)?o=k[f]=m($,{children:o}):o.constructor===h&&o.__b?o=k[f]=m(o.type,o.props,o.key,o.ref,o.__v):k[f]=o,l=f+_,o.__=n,o.__b=n.__b+1,e=null,~(c=o.__i=P(o,r,l,d))&&(d--,(e=r[c])&&(e.__u|=2)),e&&e.__v?(o.__u|=16,c==l-1?_--:c==l+1?_++:c!=l&&(c>l?_--:_++,g=1)):(~c||(i>v?_--:i<v&&_++),\"function\"!=typeof o.type&&(o.__u|=4))):k[f]=null;if(g){for(a=[],s=[],f=0;f<i;f++)if((o=k[f])&&16&o.__u){for(_=0,p=a.length;_<p;)a[y=_+p>>1]<o.__i?_=y+1:p=y;a[_]=o.__i,s[f]=_+1}for(_=a.length;f--;)s[f]&&(s[f]==_?_--:k[f].__u|=4)}if(d)for(f=0;f<v;f++)!(e=r[f])||2&e.__u||(e.__e==u&&(u=S(e)),J(e,e));return u}function A(n,t,r,u){var i,f,o,e;if(\"function\"==typeof n.type){if(n.props.__P)return t;if(i=n.__k)for(f=0;f<i.length;f++)i[f]&&(i[f].__=n,t=A(i[f],t,r,!1));return t}for(t&&!t.parentNode&&(t=S(n))&&!t.parentNode&&(t=null),o=n.__e,e=t;e&&8==e.nodeType;)e=e.nextSibling;for(o!=e&&(!u&&r.moveBefore&&o.parentNode?r.moveBefore(o,t):r.insertBefore(o,t||null)),t=o;(t=t&&t.nextSibling)&&8==t.nodeType&&!t.data.startsWith(\"$s\"););return t}function O(n,t){return t=t||[],null!=n&&\"boolean\"!=typeof n&&(w(n)?n.some(function(n){O(n,t)}):t.push(n)),t}function P(n,t,r,u){var i,f=n.key,o=n.type,e=t[r],l=e&&!(2&e.__u);if(null===e&&null==f||l&&f==e.key&&o==e.type)return r;if(u>(l?1:0)){for(i=r-1;i>=0;i--)if((e=t[i])&&!(2&e.__u)&&f==e.key&&o==e.type)return i;for(i=r+1;i<t.length;i++)if((e=t[i])&&!(2&e.__u)&&f==e.key&&o==e.type)return i}return-1}function T(n,t,r){null==r&&(r=\"\"),\"-\"==t[0]?n.setProperty(t,r):n[t]=r}function N(n,t,r,u,i){var f,o;if(\"style\"==t)if(\"string\"==typeof r)n.style.cssText=r;else{if(\"string\"==typeof u&&(n.style.cssText=u=\"\"),u)for(t in u)r&&t in r||T(n.style,t);if(r)for(t in r)u&&r[t]==u[t]||T(n.style,t,r[t])}else if(\"o\"==t[0]&&\"n\"==t[1])\"function\"!=typeof r&&(r=null),\"function\"!=typeof u&&(u=null),(n.__e||(n.__e={}))[t]=r,r&&u||(o=a[t]||(a[t]=V(t)),(n.__a||(n.__a={}))[t]=c,f=t!=(t=t.replace(l,\"$1\")),(t=t.slice(2))[0]<\"a\"&&(t=t.toLowerCase()),r?n.addEventListener(t,o,f):n.removeEventListener(t,o,f));else{if(\"http://www.w3.org/2000/svg\"==i)t=t.replace(/xlink(H|:h)/,\"h\").replace(/sName$/,\"s\");else if(\"width\"!=t&&\"height\"!=t&&\"href\"!=t&&\"list\"!=t&&\"form\"!=t&&\"tabIndex\"!=t&&\"download\"!=t&&\"rowSpan\"!=t&&\"colSpan\"!=t&&\"role\"!=t&&\"popover\"!=t&&t in n)try{return void(n[t]=null==r?\"\":r)}catch(n){}if(\"function\"==typeof r)return;null==r||!1===r&&\"-\"!=t[4]?n.removeAttribute(t):n.setAttribute(t,\"popover\"==t&&1==r?\"\":r)}}function V(t){return function(r){var u=this.__e;if(u){if(u=u[t],null==r[e])r[e]=c++;else if(r[e]<this.__a[t])return;return u(n.event?n.event(r):r)}}}function z(t,r,u,i,f,o,e,l,c,a){var s,p,v,d,k,b,m,M,C,j,L,H,q,A,O,P,T,N,V=r.type;if(r.constructor!==h)return null;128&u.__u&&(c=32&u.__u,s=u.__c.__z)&&(r.__u|=c,p=o=[],8==s.nodeType?l=B(s,o):o.push(s),l=o[0]||l),(s=n.__b)&&s(r);n:if(\"function\"==typeof V){v=e.length;try{if(M=r.props,C=(s=V.prototype)&&s.render,j=(s=V.contextType)&&i[s.__c],L=s?j?j.props.value:s.__:i,(d=u.__c)?(r.__c=d,2&d.__g&&(d.__g|=1)):(C?r.__c=d=new V(M,L):(r.__c=d=new x(M,L),d.constructor=V,d.render=K),j&&j.sub(d),d.state||(d.state={}),d.__n=i,d.__g|=8,d.__h=[],d.__k=[]),C&&(d.__s||(d.__s=d.state),V.getDerivedStateFromProps&&(d.__s==d.state&&(d.__s=_({},d.__s)),_(d.__s,V.getDerivedStateFromProps(M,d.__s)))),k=d.props,b=d.state,d.__v=r,u.__c){if(M!==k&&C&&!V.getDerivedStateFromProps&&d.componentWillReceiveProps&&d.componentWillReceiveProps(M,L),r.__v==u.__v&&!(8&d.__g)||!(4&d.__g)&&d.shouldComponentUpdate&&!1===d.shouldComponentUpdate(M,d.__s,L)){r.__v!=u.__v&&(d.props=M,d.state=d.__s,d.__g&=-9),r.__e=u.__e,r.__k=u.__k,r.__k.some(function(n){n&&(n.__=r)}),y.push.apply(d.__h,d.__k),d.__k=[],d.__h.length&&e.push(d),l=S(u);break n}d.componentWillUpdate&&d.componentWillUpdate(M,d.__s,L),C&&d.componentDidUpdate&&d.__h.push(function(){d.componentDidUpdate(k,b,m)})}else C&&!V.getDerivedStateFromProps&&d.componentWillMount&&d.componentWillMount(),C&&d.componentDidMount&&d.__h.push(d.componentDidMount);d.context=L,d.props=M,d.__P=t,d.__g&=-5,H=n.__r,q=C?25:0;do{d.__g&=-9,H&&H(r),s=d.render(d.props,d.state=d.__s,d.context)}while(8&d.__g&&++q<25);C&&(y.push.apply(d.__h,d.__k),d.__k=[]),d.state=d.__s,d.getChildContext&&(i=_({},i,d.getChildContext())),C&&u.__c&&d.getSnapshotBeforeUpdate&&(m=d.getSnapshotBeforeUpdate(k,b)),A=s&&s.type===$&&null==s.key?s.props.children:s,M.__P&&(s=l,f=(t=M.__P).namespaceURI,c=o=null,u.props&&u.props.__P!=t&&(u.__k.some(function(n){n&&J(n,n)}),u.__k=null),l=u.__k?S(u,0):null),l=I(t,w(A)?A:[A],r,u,i,f,o,e,l,c,a),M.__P&&(r.__e=null,l=s),r.__u&=-161,p&&p.some(g),d.__h.length&&e.push(d),1&d.__g&&(d.__g&=-4)}catch(t){if(e.length=v,r.__v=null,c||o)if(t&&t.then){if(r.__u|=128|c,o){for(~(T=o.indexOf(l||void 0))||(T=o.length);(N=o[T-1])&&8==N.nodeType;)T--;for(;T<o.length;T++)if(N=o[T])if(o[T]=null,O){if(N==P)break}else{if(8!=N.nodeType)break;N.data.startsWith(\"$s\")&&(P=B(O=N))}}if(!O){for(;l&&8==l.nodeType&&l.nextSibling;)l=l.nextSibling;O=l}(s=B(O=r.__c.__z||(r.__c.__z=O)))?(r.__e=O,l=s):r.__e=l,l=l&&l.nextSibling}else o&&o.some(g);else r.__e=u.__e;r.__k||(r.__k=u.__k||[]),t&&t.then||D(r),n.__e(t,r,u)}}else l=r.__e=F(u.__e,r,u,i,f,o,e,c,a,t);return(s=n.diffed)&&s(r),l}function B(n,t){if(n&&8==n.nodeType&&n.data.startsWith(\"$s\"))for(var r=1;n=n.nextSibling;){if(8==n.nodeType)if(n.data.startsWith(\"$s\"))r++;else if(n.data.startsWith(\"/$s\")&&!--r)return n;t&&t.push(n)}}function D(n){n&&(n.__c&&(n.__c.__g|=4),n.__k&&n.__k.some(D))}function E(t,r,u){for(var i=0;i<u.length;)G(u[i++],u[i++],u[i++]);n.__c&&n.__c(r,t),t.some(function(r){try{t=r.__h,r.__h=[],t.some(function(n){n.call(r)})}catch(t){n.__e(t,r.__v)}})}function F(t,r,u,i,f,o,e,l,c,a){var s,h,y,_,k,b,m,M,$=u.props||p,x=r.props,C=r.type;if(\"svg\"==C?f=\"http://www.w3.org/2000/svg\":\"math\"==C?f=\"http://www.w3.org/1998/Math/MathML\":f||(f=\"http://www.w3.org/1999/xhtml\"),o)for(s=0;s<o.length;s++)if((k=o[s])&&(C?k.localName==C:3==k.nodeType)){t=k,o[s]=null;break}if(!t){if(M=a.ownerDocument||document,!C)return M.createTextNode(x);t=M.createElementNS(f,C,x.is?x:a),l&&(n.__m&&n.__m(r,o),l=!1),o=null}if(C){if(a=\"template\"==C&&t.content||t,o=\"textarea\"==C&&null!=x.defaultValue?null:o&&d.call(a.childNodes),!l&&o)for($={},s=0;s<t.attributes.length;s++)$[(k=t.attributes[s]).name]=k.value;for(s in $)k=$[s],\"dangerouslySetInnerHTML\"==s?y=k:\"children\"==s||s in x||\"value\"==s&&\"defaultValue\"in x||\"checked\"==s&&\"defaultChecked\"in x||N(t,s,null,k,f);for(s in x)k=x[s],\"children\"==s?_=k:\"dangerouslySetInnerHTML\"==s?h=k:\"value\"==s?b=k:\"checked\"==s?m=k:l&&\"function\"!=typeof k||$[s]===k||N(t,s,k,$[s],f);h?(l||y&&(h.__html==y.__html||h.__html==t.innerHTML)||(t.innerHTML=h.__html),r.__k=[]):(y&&(t.textContent=\"\"),(\"foreignObject\"==C||\"http://www.w3.org/1998/Math/MathML\"==f&&v.test(C))&&(f=\"http://www.w3.org/1999/xhtml\"),I(a,w(_)?_:[_],r,u,i,f,o,e,o?o[0]:u.__k&&S(u,0),l,c),o&&o.some(g)),l&&\"textarea\"!=C||(s=\"value\",\"progress\"==C&&null==b?t.removeAttribute(s):null==b||b===t[s]&&(\"progress\"!=C||b)||N(t,s,b,$[s],f),s=\"checked\",null!=m&&m!=t[s]&&N(t,s,m,$[s],f))}else $===x||l&&t.data==x||(t.data=x);return t}function G(t,r,u,i){try{\"function\"==typeof t?r?r.__x=t(r)||1:i&&(i=i.__c||i.__e)&&(r=i.__x)&&(i.__x=null,\"function\"==typeof r?r():t(null)):t.current=r}catch(t){n.__e(t,u)}}function J(t,r,u){var i,f,o,e;if(n.unmount&&n.unmount(t),!(i=t.ref)||i.current&&i.current!=t.__e||G(i,null,r,t),i=t.__c){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(t){n.__e(t,r)}i.__P=i.__n=null}if(i=t.__k)for(e=0;e<i.length;e++)i[e]&&J(i[e],r,\"function\"!=typeof t.type||u&&!t.props.__P);!u&&(i=t.__c)&&(i=i.__z)&&(f=B(i,o=[]))&&(i==t.__e&&o.some(g),g(f),g(i)),u||g(t.__e),t.__e=t.__c=t.__=null}function K(n,t,r){return this.constructor(n,r)}function Q(t,r){var u,i,f,o;n.__&&n.__(t,r),9==r.nodeType&&(r=r.documentElement),i=(u=t&&32&t.__u)?null:r.__k,r.__k=m($,{children:[t]}),f=[],o=[],z(r,r.__k,i||p,p,r.namespaceURI,i?null:r.firstChild?d.call(r.childNodes):null,f,i?i.__e:r.firstChild,u,o),E(f,r.__k,o),r.__k.props.children=null}function R(n,t){n&&\"object\"==typeof n&&(n.__u|=32),Q(n,t)}function U(n){function t(n){var r,u;return this.getChildContext||(r=new Set,(u={})[t.__c]=this,this.getChildContext=function(){return u},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&r.forEach(function(n){n.__g|=4,L(n)})},this.sub=function(n){r.add(n);var t=n.componentWillUnmount;n.componentWillUnmount=function(){r.delete(n),t&&t.call(n)}}),n.children}return t.__c=\"__cC\"+s++,t.__=n,t.Provider=(t.Consumer=function(n,t){return n.children(t)}).contextType=t,t}function W(n){return n.children}function X(n,t){return m(W,{__P:t,children:n})}n={__e:function(n,t,r,u){for(var i,o,e;t=t.__;)if((i=t.__c)&&!(1&i.__g)){i.__g|=4;try{if((e=(o=i.constructor)&&o.getDerivedStateFromError)&&i.setState(o.getDerivedStateFromError(n)),i.componentDidCatch&&(i.componentDidCatch(n,u||{}),e=1),e&&8&i.__g)return void(i.__g|=2)}catch(t){n=t}}throw f=0,n}},t=0,r=function(n){return null!=n&&n.constructor===h},x.prototype.setState=function(n,t){var r=this.__s;r&&r!=this.state||(r=this.__s=_({},this.state)),\"function\"==typeof n&&(n=n(_({},r),this.props)),n&&(_(r,n),this.__v&&(t&&this.__k.push(t),L(this)))},x.prototype.forceUpdate=function(n){this.__v&&(this.__g|=4,n&&this.__h.push(n),L(this))},x.prototype.render=$,u=[],f=0,o=function(n,t){return n.__v.__b-t.__v.__b},e=Symbol(),l=/(PointerCapture)$|Capture$/i,c=0,a={},s=0;export{x as Component,$ as Fragment,b as cloneElement,U as createContext,k as createElement,X as createPortal,M as createRef,k as h,R as hydrate,r as isValidElement,n as options,Q as render,O as toChildArray};\n//# sourceMappingURL=preact.mjs.map\n","/**\n * Start-up milestones as User Timing marks (\"nm:...\"), so that \"how long until the app is\n * usable\" can be read in the browser's performance panel and by test/measure.ts.\n */\nexport type Milestone =\n /** The first bundle has been evaluated. */\n | 'script'\n /** The shell is on screen. */\n | 'rendered'\n /** config.json is read: the mode is known. */\n | 'config'\n /** Helper mode: the helper's welcome is in; Run can be pressed. */\n | 'connected'\n /** The list of lessons is in. */\n | 'lessons'\n /** The atlas index is loaded and checked. */\n | 'atlas'\n /** The code editor's chunk is loaded and an editor exists. */\n | 'editor';\n\nconst done = new Set<Milestone>();\n\nexport function milestone(name: Milestone): void {\n if (done.has(name)) return;\n done.add(name);\n try {\n performance.mark(`nm:${name}`);\n } catch {\n // User Timing is a diagnostic; never let it break start-up.\n }\n}\n","import{options as n}from\"preact\";var t,r,u,i,o=Object.is,f=0,c=[],e=[],a=n,v=a.__b,l=a.__r,m=a.diffed,h=a.__c,s=a.unmount,p=a.__;function y(n,t){a.__h&&a.__h(r,n,f||t),f=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return f=1,_(G,n)}function _(n,u,i){var f=y(t++,2);if(f.t=n,!f.__c&&(f.__=[i?i(u):G(void 0,u),function(n){var t=(f.__N||f.__)[0],r=f.t(t,n);o(t,r)||(f.__N=[r,f.__[1]],f.__c.setState({}))}],f.__c=r,!r.__f)){r.__f=!0;var c=r.shouldComponentUpdate;r.shouldComponentUpdate=function(n,t,r){var u=this.__H;if(!u)return!0;var i=!1,f=this.props!=n;if(u.__.some(function(n){n.__N&&(i=!0,o(n.__[0],n.__N[0])||(f=!0))}),c){var e=c.call(this,n,t,r);return i?e||f:e}return!i||f}}return f.__}function A(n,u){var i=y(t++,3);!a.__s&&E(i.__H,u)&&(i.__P=!0,i.__=n,i.u=u,r.__H.__h.push(i))}function F(n,u){var i=y(t++,4);!a.__s&&E(i.__H,u)&&(i.__P=!1,i.__=n,i.u=u,r.__h.push(i))}function T(n){return f=5,w(function(){return{current:n}},[])}function q(n,t,r){f=6,F(function(){if(\"function\"==typeof n){var r=n(t());return function(){n(null),\"function\"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function w(n,r){var u=y(t++,7);return E(u.__H,r)&&(u.__=n(),u.__H=r),u.__}function b(n,t){return f=8,w(function(){return n},t)}function j(n){var u=r.context[n.__c],i=y(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function x(n,t){a.useDebugValue&&a.useDebugValue(t?t(n):n)}function O(n){var u=y(t++,10),i=d();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){return i[1]()}]}function P(){var n=y(t++,11);if(!n.__){for(var u=r.__v;!u.__m&&u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__=\"P\"+i[0]+\"-\"+i[1]++}return n.__}function g(){var n;do{for(;n=e.shift();)try{C(n)}catch(t){a.__e(t,{__:(n=n.__P)&&n.__v})}for(;n=c.shift();){var t=n.__H;if(n.__P&&t)try{t.__h.some(C),t.__h.some(D),t.__h=[]}catch(r){t.__h=[],a.__e(r,n.__v)}}}while(e.length)}a.__b=function(n){r=null,v&&v(n)},a.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),p&&p(n,t)},a.__r=function(n){l&&l(n),t=0;var i=(r=n.__c).__H;i&&(u==r?r.__h=[]:(i.__h.some(C),i.__h.some(D),t=0),i.__h=[],i.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})),u=r},a.diffed=function(n){m&&m(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&B(c.push(t)),t.__H.__.some(function(n){n.u&&(n.__H=n.u)})),u=r=null},a.__c=function(n,t){t.some(function(n){try{n.__h.some(C),n.__h=n.__h.filter(function(n){return!n.__||D(n)})}catch(t){n.__h=[function(){throw t}]}}),h&&h(n,t)},a.unmount=function(n){s&&s(n);var t,r,u=n.__c;u&&u.__H&&(u.__H.__.some(function(u){try{if(u.__P&&u.__c){if(void 0===r){for(r=n.__;r&&(!r.__c||!r.__c.__P);)r=r.__;r=r&&r.__c}u.__P=r,B(e.push(u))}else C(u)}catch(n){t=n}}),u.__H=void 0,t&&a.__e(t,u.__v))};var k=\"function\"==typeof requestAnimationFrame;function z(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function B(n){1!=n&&i==a.requestAnimationFrame||((i=a.requestAnimationFrame)||z)(g)}function C(n){var t=r,u=n.__c;\"function\"==typeof u&&(n.__c=void 0,u()),r=t}function D(n){var t=r;n.__c=n.__(),r=t}function E(n,t){return!n||n.length!=t.length||t.some(function(t,r){return!o(t,n[r])})}function G(n,t){return\"function\"==typeof t?t(n):t}export{b as useCallback,j as useContext,x as useDebugValue,A as useEffect,O as useErrorBoundary,P as useId,q as useImperativeHandle,F as useLayoutEffect,w as useMemo,_ as useReducer,T as useRef,d as useState};\n//# sourceMappingURL=hooks.mjs.map\n","import{options as r,Fragment as t}from\"preact\";export{Fragment}from\"preact\";var e=/[\"&<]/;function n(r){if(!r.length||!e.test(r))return r;for(var t=0,n=0,f=\"\",o=\"\";n<r.length;n++){switch(r.charCodeAt(n)){case 34:o=\"&quot;\";break;case 38:o=\"&amp;\";break;case 60:o=\"&lt;\";break;default:continue}n!=t&&(f+=r.slice(t,n)),f+=o,t=n+1}return n!=t&&(f+=r.slice(t,n)),f}var f=Symbol.for(\"pv\"),o=0,u=Array.isArray;function a(t,e,n,u,a,i){e||(e={});var c,l,p=e;if(\"ref\"in p&&\"function\"!=typeof t)for(l in p={},e)\"ref\"==l?c=e[l]:p[l]=e[l];var s={type:t,props:p,key:n,ref:c,__k:null,__:null,__b:0,__e:null,__c:null,constructor:f,__v:--o,__i:-1,__u:0};return(a||i)&&(s.__source=a,s.__self=i),r.vnode&&r.vnode(s),s}function i(r){var e=a(t,{tpl:r,exprs:[].slice.call(arguments,1)});return e.key=e.__v,e}var c={},l=/[A-Z]/g;function p(t,e){if(r.attr){var f=r.attr(t,e);if(\"string\"==typeof f)return f}if(e=function(r){return null!=r&&\"object\"==typeof r&&\"function\"==typeof r.valueOf?r.valueOf():r}(e),\"ref\"==t||\"key\"==t)return\"\";if(\"style\"==t&&\"object\"==typeof e){var o=\"\";for(var u in e){var a=e[u];null!=a&&\"\"!==a&&(o=o+(\"-\"==u[0]?u:c[u]||(c[u]=u.replace(l,\"-$&\").toLowerCase()))+\":\"+a+\";\")}return t+'=\"'+n(o)+'\"'}return null==e||!1===e||\"function\"==typeof e||\"object\"==typeof e?\"\":!0===e?t:t+'=\"'+n(\"\"+e)+'\"'}function s(r){if(null==r||\"boolean\"==typeof r||\"function\"==typeof r)return null;if(\"object\"==typeof r){if(r.constructor===f)return r;if(u(r)){for(var t=0;t<r.length;t++)r[t]=s(r[t]);return r}}return n(\"\"+r)}export{a as jsx,p as jsxAttr,a as jsxDEV,s as jsxEscape,i as jsxTemplate,a as jsxs};\n//# sourceMappingURL=jsxRuntime.mjs.map\n","/**\n * A code view for Preact: shows the text at once as plain text, then swaps in CodeMirror\n * when its chunk has loaded. Used by the program editor and by the source panel.\n */\nimport { useEffect, useRef, useState } from 'preact/hooks';\nimport type { BreakpointMark } from '../lib/breakpoints.ts';\nimport { milestone } from '../lib/marks.ts';\nimport type { CodeLanguage, CodeView as CodeViewHandle, LineMark } from './cm.ts';\n\nexport interface CodeViewProps {\n text: string;\n language: CodeLanguage;\n readOnly: boolean;\n label: string;\n onChange?: ((text: string) => void) | undefined;\n breakpoints?: readonly BreakpointMark[] | undefined;\n /** False: all breakpoints are deactivated (drawn hollow). */\n breakpointsActive?: boolean | undefined;\n onToggleBreakpoint?: ((line: number) => void) | undefined;\n onBreakpointsMoved?: ((marks: BreakpointMark[]) => void) | undefined;\n lineMark?: LineMark | null | undefined;\n range?: { start: number; end: number } | null | undefined;\n /** Changes when the range should be scrolled into view again. */\n revealKey?: string | number | undefined;\n}\n\n/** Loaded once, shared by every code view. */\nlet cmModule: Promise<typeof import('./cm.ts')> | null = null;\nexport function loadCodeMirror(): Promise<typeof import('./cm.ts')> {\n cmModule ??= import('./cm.ts');\n return cmModule;\n}\n\nexport function CodeView(props: CodeViewProps) {\n const host = useRef<HTMLDivElement>(null);\n const handle = useRef<CodeViewHandle | null>(null);\n const [ready, setReady] = useState(false);\n const [failed, setFailed] = useState(false);\n // The callbacks may change on every render; CodeMirror keeps calling through this ref.\n const latest = useRef(props);\n latest.current = props;\n const withBreakpoints = props.onToggleBreakpoint !== undefined;\n /** The latest text the editor itself reported, and how many reports have not come back as the text prop yet. */\n const emitted = useRef<string | null>(null);\n const unechoed = useRef(0);\n\n useEffect(() => {\n let live = true;\n loadCodeMirror().then(\n (cm) => {\n if (!live || !host.current) return;\n const p = latest.current;\n handle.current = cm.createCodeView({\n parent: host.current,\n doc: p.text,\n language: p.language,\n readOnly: p.readOnly,\n label: p.label,\n onChange: (text) => {\n emitted.current = text;\n unechoed.current++;\n latest.current.onChange?.(text);\n },\n ...(withBreakpoints\n ? {\n onToggleBreakpoint: (line: number) => latest.current.onToggleBreakpoint?.(line),\n onBreakpointsMoved: (marks: BreakpointMark[]) => latest.current.onBreakpointsMoved?.(marks),\n }\n : {}),\n });\n setReady(true);\n milestone('editor');\n },\n () => {\n if (live) setFailed(true);\n },\n );\n return () => {\n live = false;\n handle.current?.destroy();\n handle.current = null;\n };\n }, [withBreakpoints]);\n\n // The text prop is pushed into the editor only when it is news to the editor. While the\n // user types, every edit goes out through onChange and comes back as this prop a moment\n // later - by then the editor may already hold a newer text. Writing such an echo back\n // would replace what was typed since and move the caret (seen as scrambled text when\n // typing fast). So: the latest text the editor sent is never written back, and neither\n // are the older ones still on their way.\n useEffect(() => {\n if (props.text === emitted.current) {\n unechoed.current = 0;\n return;\n }\n if (unechoed.current > 0) {\n unechoed.current--;\n return;\n }\n handle.current?.setDoc(props.text);\n }, [ready, props.text]);\n useEffect(() => {\n handle.current?.setLanguage(props.language);\n }, [ready, props.language]);\n useEffect(() => {\n handle.current?.setReadOnly(props.readOnly);\n }, [ready, props.readOnly]);\n useEffect(() => {\n handle.current?.setLabel(props.label);\n }, [ready, props.label]);\n useEffect(() => {\n handle.current?.setBreakpoints(props.breakpoints ?? [], props.breakpointsActive !== false);\n }, [ready, props.breakpoints, props.breakpointsActive, props.text]);\n // The current line changes with every callback during playback. Its update is the one\n // piece of CodeMirror work that happens while playing, so it is done at most once per\n // animation frame, and not at all while the editor is not on screen (it is then\n // applied when the editor shows again).\n const markLine = props.lineMark?.line;\n const markKind = props.lineMark?.kind;\n const markTag = props.lineMark?.tag;\n /** When the line was last scrolled into view. */\n const scrolledAt = useRef(0);\n useEffect(() => {\n let frame = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const apply = (): void => {\n const el = host.current;\n if (!handle.current || !el) return;\n if (el.offsetParent === null || document.hidden) {\n // Not visible: look again later instead of working for nobody.\n timer = setTimeout(() => {\n frame = requestAnimationFrame(apply);\n }, 250);\n return;\n }\n // The paused line is always brought into view. The quiet lines of a replay change\n // with almost every step: those are scrolled to at most twice a second (scrolling\n // makes CodeMirror measure the page, which is the costly part).\n const mark = latest.current.lineMark ?? null;\n const now = performance.now();\n const scroll = mark !== null && (mark.kind === 'paused' || mark.kind === 'frame' || now - scrolledAt.current > 500);\n if (scroll) scrolledAt.current = now;\n handle.current.setLineMark(mark, scroll);\n };\n frame = requestAnimationFrame(apply);\n return () => {\n cancelAnimationFrame(frame);\n clearTimeout(timer);\n };\n }, [ready, markLine, markKind, markTag, props.text]);\n useEffect(() => {\n handle.current?.setRange(props.range ?? null, true);\n }, [ready, props.range?.start, props.range?.end, props.revealKey, props.text]);\n\n return (\n <div class=\"code\">\n <div ref={host} class=\"code__cm\" />\n {ready ? null : (\n <pre class=\"code__plain mono\" tabIndex={0} aria-label={props.label}>\n {props.text}\n </pre>\n )}\n {failed ? <p class=\"code__note warn-text\">The code editor could not be loaded; the text is shown without highlighting and cannot be edited here.</p> : null}\n </div>\n );\n}\n","/**\n * Which run controls are on, and for the ones that are off, why - in words the user can\n * read. Pure: the toolbar renders what this returns.\n *\n * A control is off for one of two kinds of reasons:\n * - the selected Node cannot do it (a capability is missing). The words come from the\n * helper's CapabilityNotes when it sent some, else from the defaults below;\n * - the moment is wrong (nothing is running, the program is not paused, ...).\n * The capability reason wins: \"start a run first\" would be a false promise for a control\n * that this Node can never offer.\n */\nimport type { Capabilities } from '@nodejs-map/event-format';\nimport type { CapabilityNotes, ProviderInfo } from '@nodejs-map/protocol';\n\nexport type ControlId =\n | 'run'\n | 'debug'\n | 'stop'\n | 'pause'\n | 'resume'\n | 'stepOver'\n | 'stepInto'\n | 'stepOut'\n | 'pauseAtNextPhase'\n | 'stepPhase'\n | 'runToPhase'\n | 'gateTimer'\n | 'gatePoolStart'\n | 'gatePoolPost'\n | 'gateResume';\n\nexport const CONTROL_IDS: readonly ControlId[] = [\n 'run', 'debug', 'stop', 'pause', 'resume', 'stepOver', 'stepInto', 'stepOut',\n 'pauseAtNextPhase', 'stepPhase', 'runToPhase', 'gateTimer', 'gatePoolStart', 'gatePoolPost', 'gateResume',\n];\n\n/** Where the live run is. */\nexport type LiveStatus =\n /** No run yet, or the last one is over. */\n | 'idle'\n /** `run` was sent, the helper has not answered. */\n | 'starting'\n | 'running'\n /** JavaScript is stopped at a statement. */\n | 'paused'\n /** The target is stopped at a gate (probe build). */\n | 'gated';\n\nexport interface ControlInput {\n /** Helper mode with an open connection. */\n connected: boolean;\n provider: ProviderInfo | null;\n notes: CapabilityNotes;\n status: LiveStatus;\n}\n\nexport interface ControlState {\n enabled: boolean;\n /** Why the control is off. Null when it is on. */\n reason: string | null;\n}\n\nconst on: ControlState = { enabled: true, reason: null };\nconst off = (reason: string): ControlState => ({ enabled: false, reason });\n\nexport const DEFAULT_REASONS = {\n notConnected: 'The helper is not connected. Start nodejs-map again in a terminal.',\n noProvider: 'No Node.js is selected.',\n providerUnavailable: 'This Node.js is not available.',\n jsDebugger: 'This Node.js cannot be debugged: the helper could not use its inspector.',\n gatePhase:\n 'Needs the probe build. An official Node.js can only be paused at a JavaScript statement, not between event loop phases.',\n gateTimer: 'Needs the probe build. An official Node.js cannot stop just before a timer fires.',\n gatePoolStart: 'Needs the probe build. An official Node.js cannot stop a thread pool thread before it starts a job.',\n gatePoolPost: 'Needs the probe build. An official Node.js cannot stop a thread pool thread before it hands back a result.',\n nothingRunning: 'Nothing is running.',\n starting: 'The program is starting.',\n notPaused: 'The program is not paused.',\n alreadyPaused: 'The program is already paused.',\n notAtGate: 'The program is not stopped at a gate.',\n atGate: 'The program is stopped at a gate. Resume it first.',\n} as const;\n\ntype GateName = keyof Capabilities['gates'];\n\nfunction gateReason(gate: GateName, notes: CapabilityNotes): string {\n const note = notes[`gates.${gate}`] ?? notes.gates;\n if (note) return note;\n switch (gate) {\n case 'phase':\n return DEFAULT_REASONS.gatePhase;\n case 'timer':\n return DEFAULT_REASONS.gateTimer;\n case 'poolStart':\n return DEFAULT_REASONS.gatePoolStart;\n case 'poolPost':\n return DEFAULT_REASONS.gatePoolPost;\n }\n}\n\nexport function controlStates(input: ControlInput): Record<ControlId, ControlState> {\n const { connected, provider, notes, status } = input;\n const caps = provider?.caps ?? null;\n const live = status === 'running' || status === 'paused' || status === 'gated';\n\n /** Reason no run can start, or null. */\n const cannotStart: string | null = !connected\n ? DEFAULT_REASONS.notConnected\n : !provider\n ? DEFAULT_REASONS.noProvider\n : !provider.available\n ? (provider.why ?? DEFAULT_REASONS.providerUnavailable)\n : status === 'starting'\n ? DEFAULT_REASONS.starting\n : null;\n\n const noDebugger: string | null =\n cannotStart ?? (caps && !caps.jsDebugger ? (notes.jsDebugger ?? DEFAULT_REASONS.jsDebugger) : null);\n\n const whenLive = (extra?: () => ControlState): ControlState => {\n if (!connected) return off(DEFAULT_REASONS.notConnected);\n if (status === 'starting') return off(DEFAULT_REASONS.starting);\n if (!live) return off(DEFAULT_REASONS.nothingRunning);\n return extra ? extra() : on;\n };\n\n const jsControl = (needPaused: boolean): ControlState => {\n if (caps && !caps.jsDebugger) return off(notes.jsDebugger ?? DEFAULT_REASONS.jsDebugger);\n // A run started without the debugger can still be paused: the helper attaches it then\n // (and says so if it cannot). So the mode of the run does not switch these off.\n return whenLive(() => {\n if (status === 'gated') return off(DEFAULT_REASONS.atGate);\n if (needPaused) return status === 'paused' ? on : off(DEFAULT_REASONS.notPaused);\n return status === 'paused' ? off(DEFAULT_REASONS.alreadyPaused) : on;\n });\n };\n\n /**\n * arm: a gate that can be chosen before the run as well (real programs are over in\n * milliseconds; nobody can click that fast). With no run it is a toggle for the\n * next run; during a run it acts at once.\n * act: needs a running program (step one phase, run to a phase).\n * resume: needs a program stopped at a gate.\n */\n const gateControl = (gate: GateName, kind: 'arm' | 'act' | 'resume'): ControlState => {\n if (!connected) return off(DEFAULT_REASONS.notConnected);\n if (!caps || !caps.gates[gate]) return off(gateReason(gate, notes));\n if (kind === 'arm' && !live) {\n if (status === 'starting') return off(DEFAULT_REASONS.starting);\n return provider && !provider.available ? off(provider.why ?? DEFAULT_REASONS.providerUnavailable) : on;\n }\n return whenLive(() => {\n if (kind === 'resume') return status === 'gated' ? on : off(DEFAULT_REASONS.notAtGate);\n return on;\n });\n };\n\n return {\n run: cannotStart ? off(cannotStart) : on,\n debug: noDebugger ? off(noDebugger) : on,\n stop: !connected\n ? off(DEFAULT_REASONS.notConnected)\n : live || status === 'starting'\n ? on\n : off(DEFAULT_REASONS.nothingRunning),\n pause: jsControl(false),\n resume: jsControl(true),\n stepOver: jsControl(true),\n stepInto: jsControl(true),\n stepOut: jsControl(true),\n pauseAtNextPhase: gateControl('phase', 'arm'),\n stepPhase: gateControl('phase', 'act'),\n runToPhase: gateControl('phase', 'act'),\n gateTimer: gateControl('timer', 'arm'),\n gatePoolStart: gateControl('poolStart', 'arm'),\n gatePoolPost: gateControl('poolPost', 'arm'),\n gateResume: gateControl('phase', 'resume'),\n };\n}\n\n/**\n * One sentence for the whole \"loop gates\" group when its phase controls are all off for\n * the same reason (the usual case on an official build), else null.\n */\nexport function gateGroupReason(states: Record<ControlId, ControlState>): string | null {\n const ids: ControlId[] = ['pauseAtNextPhase', 'stepPhase', 'runToPhase'];\n // All three off for one reason: that is a missing capability (or no connection); a\n // Node that can do gates has the first of them on even before a run.\n if (ids.some((id) => states[id].enabled)) return null;\n const reasons = new Set(ids.map((id) => states[id].reason));\n if (reasons.size !== 1) return null;\n const [only] = reasons;\n return only ?? null;\n}\n","/**\n * The nodejs-map atlas, version 1.\n *\n * An atlas describes one Node.js release (tag + commit) as nested boxes with code\n * locations. It is a set of static JSON files:\n *\n * index.json tiers 1-2 (regions, groups, feature boxes, single boxes), curated\n * paths, the chunk manifest, aliases. Small: load it first.\n * chunks/<id>.json tier 3 (directories, files, functions) of one group, or of part\n * of a big group. Load on demand (by box id or by what is in view).\n * files.json path -> chunk + line count, for locate(path, line). Lazy.\n * search.json [label, id] pairs for search. Lazy.\n * edges.json extracted relations (lib -> binding -> C++ -> libuv). Lazy.\n *\n * Rects nest: every box's `r` is [x, y, w, h] relative to its PARENT box's rect, in\n * units of 1/10000 of the parent's width/height (regions: relative to the world).\n * The absolute rect is obtained by walking up the parents (AtlasStore.absRect does this).\n *\n * Ids (stable across releases while the thing exists, see ID_GRAMMAR):\n * o:<overlay-id> region, group or feature, written by hand in the overlay\n * p:<path>/<step> curated path step (also hand-written)\n * f:<path> file, e.g. f:lib/fs.js\n * d:<group>:<path> directory inside a group\n * s:<path>#<qualified-name> function, e.g. s:src/api/callback.cc#node::InternalCallbackScope::Close\n * (duplicates in one file add ~<hash of params|return type|#if condition>)\n * x:<path> single box (a whole bundled dependency), e.g. x:deps/openssl\n * b:<binding>[.<member>] binding nodes; only appear in edges\n */\n\nexport const ATLAS_SCHEMA = 'nodejs-map/atlas@1';\nexport const CHUNK_SCHEMA = 'nodejs-map/atlas-chunk@1';\nexport const FILES_SCHEMA = 'nodejs-map/atlas-files@1';\nexport const SEARCH_SCHEMA = 'nodejs-map/atlas-search@1';\nexport const EDGES_SCHEMA = 'nodejs-map/atlas-edges@1';\n\nexport const ID_GRAMMAR = {\n overlay: /^o:[a-z0-9][a-zA-Z0-9._-]*$/,\n pathStep: /^p:[a-zA-Z0-9._-]+(\\/[a-zA-Z0-9._-]+)*$/,\n file: /^f:.+$/,\n dir: /^d:[a-zA-Z0-9._-]+:.+$/,\n fn: /^s:[^#]+#.+$/,\n single: /^x:.+$/,\n} as const;\n\n/** OS tag on a code location. `unix` covers linux and darwin. */\nexport type OsTag = 'unix' | 'linux' | 'darwin' | 'win';\n/** process.platform values the app cares about. */\nexport type Platform = 'win32' | 'darwin' | 'linux';\n\n/** [x, y, w, h], integers, relative to the parent's rect in units of 1/10000. */\nexport type Rect = [number, number, number, number];\n/** Absolute rect in world units. */\nexport interface AbsRect { x: number; y: number; w: number; h: number }\n\n/** A line range in one file at the atlas commit. Lines are 1-based and inclusive. */\nexport interface CodeRange {\n path: string;\n start: number;\n end: number;\n /** Fully qualified symbol, e.g. \"node::InternalCallbackScope::Close\" or \"ReadFileContext.prototype.read\". */\n sym: string;\n /** Present when this range applies to one platform only. */\n os?: OsTag;\n /** Preprocessor / if() condition when the symbol has per-platform variants in one file. */\n cond?: string;\n}\n\n/** A directory link (no line range). */\nexport interface TreeLocation { tree: string }\n\nexport type IndexBoxKind = 'region' | 'group' | 'feature' | 'single';\nexport type ChunkRowKind = 'd' | 'f' | 's';\nexport type BoxKind = IndexBoxKind | 'dir' | 'file' | 'fn';\nexport type Tier = 1 | 2 | 3;\n\n/**\n * A box in index.json.\n * loc: features have CodeRange[] (one per platform where they differ); regions, groups and\n * single boxes have a TreeLocation or null (\"Your code\" has null: it is filled at run time).\n */\nexport interface IndexBox {\n id: string;\n /** Parent id; \"o:world\" for regions. */\n p: string;\n k: IndexBoxKind;\n t: Tier;\n /** Title. */\n n: string;\n /** One-line description (plain English). */\n d?: string;\n r: Rect;\n loc: CodeRange[] | TreeLocation | null;\n /** single boxes: number of files and bytes in the dependency. */\n files?: number;\n bytes?: number;\n}\n\nexport interface PathStep {\n id: string;\n title: string;\n /** One sentence. */\n desc: string;\n thread: 'main' | 'pool';\n /** Present when the whole step only happens on that platform. */\n os?: OsTag;\n /** Where it happens; one entry per platform where the code differs. */\n locs: Array<CodeRange & { url: string }>;\n /** Optional link to the feature box this step corresponds to. */\n box?: string;\n}\n\nexport interface PathBranch { id: string; title: string; desc?: string; steps: PathStep[] }\n\nexport interface CuratedPath {\n id: string;\n title: string;\n desc: string;\n /** Curated paths are hand-traced illustrations: always \"model\". */\n certainty: 'model';\n steps: PathStep[];\n branches: PathBranch[];\n}\n\nexport interface ChunkRef {\n /** Chunk id, e.g. \"lib.fs.0\". */\n id: string;\n /** Owning group box id. */\n group: string;\n url: string;\n /** Bounding rect of the chunk's content, relative to the group's rect. */\n r: Rect;\n rows: number;\n bytes: number;\n}\n\nexport interface AtlasIndex {\n schema: typeof ATLAS_SCHEMA;\n node: { version: string; commit: string; repo: 'nodejs/node' };\n builder: { version: string; overlayHash: string };\n world: { w: number; h: number };\n boxes: IndexBox[];\n paths: CuratedPath[];\n chunks: ChunkRef[];\n /** Relative URLs of the lazy files. */\n files: string;\n search: string;\n edges: string;\n /** Renamed or moved ids: old -> new. */\n aliases: Record<string, string>;\n}\n\n/**\n * One tier-3 row: [id, parent, kind, label, x, y, w, h, start, end, variant?]\n * kind 'd' directory (start/end null), 'f' file (start null, end = line count),\n * 's' function (start/end = line range). variant: #if / if() condition, when relevant.\n */\nexport type ChunkRow =\n | [string, string, ChunkRowKind, string, number, number, number, number, number | null, number | null]\n | [string, string, ChunkRowKind, string, number, number, number, number, number | null, number | null, string];\n\nexport const CHUNK_COLS = ['id', 'p', 'k', 'n', 'x', 'y', 'w', 'h', 'a', 'b', 'v'] as const;\n\nexport interface AtlasChunk {\n schema: typeof CHUNK_SCHEMA;\n id: string;\n group: string;\n cols: typeof CHUNK_COLS;\n /** Parents come before children. Rows of directories that were split across chunks are repeated. */\n rows: ChunkRow[];\n}\n\n/** files.json: [path, index into AtlasIndex.chunks, line count] sorted by path. */\nexport interface AtlasFiles { schema: typeof FILES_SCHEMA; files: Array<[string, number, number]> }\n\nexport interface AtlasSearch { schema: typeof SEARCH_SCHEMA; entries: Array<[string, string]> }\n\nexport type Edge =\n | { kind: 'uses-binding'; from: string; to: string; line: number; registered: boolean }\n | { kind: 'registers-binding'; from: string; to: string; line: number; macro: string; init: string | null }\n | { kind: 'binding-method'; from: string; name: string; to: string | null; cxx: string; api: string; at: { path: string; line: number }; heuristic?: true }\n | { kind: 'calls-binding'; from: string; to: string; line: number; cxx: string | null }\n | { kind: 'calls-uv'; from: string; to: string[]; name: string; how: 'call' | 'ref'; lines: number[] };\n\n/** Extracted edges are inferred from source text, never observed. */\nexport interface AtlasEdges { schema: typeof EDGES_SCHEMA; certainty: 'inferred'; edges: Edge[] }\n\n/** A box with everything resolved, as AtlasStore returns it. */\nexport interface Box {\n id: string;\n parent: string;\n kind: BoxKind;\n tier: Tier;\n title: string;\n desc?: string;\n /** Relative rect (as stored). */\n rect: Rect;\n /** Code ranges (features, functions). Empty for others. */\n ranges: CodeRange[];\n /** Files: path and line count. */\n file?: { path: string; lines: number | null };\n /** Directories, groups, regions, single boxes: a folder link. */\n tree?: string;\n /** Functions: #if / if() variant condition. */\n variant?: string;\n /** Chunk the box came from (tier 3). */\n chunk?: string;\n}\n","// Runtime validation of atlas files. The app never trusts a fetched file: every index and\n// chunk goes through these checks before use. Hand-written (zero dependencies); errors are\n// collected (up to a limit) so a broken file reports all of its problems at once.\nimport {\n ATLAS_SCHEMA, CHUNK_SCHEMA, FILES_SCHEMA, SEARCH_SCHEMA, EDGES_SCHEMA, CHUNK_COLS,\n} from './schema.ts';\nimport type { AtlasIndex, AtlasChunk, AtlasFiles, AtlasSearch, AtlasEdges } from './schema.ts';\n\nexport class AtlasValidationError extends Error {\n readonly problems: string[];\n constructor(what: string, problems: string[]) {\n super(`invalid ${what}: ${problems.slice(0, 5).join('; ')}${problems.length > 5 ? ` (+${problems.length - 5} more)` : ''}`);\n this.name = 'AtlasValidationError';\n this.problems = problems;\n }\n}\n\nconst MAX_PROBLEMS = 50;\nconst OS_TAGS = new Set(['unix', 'linux', 'darwin', 'win']);\nconst INDEX_KINDS = new Set(['region', 'group', 'feature', 'single']);\nconst ROW_KINDS = new Set(['d', 'f', 's']);\nconst SAFE_PATH = /^(?!\\/)(?!.*(^|\\/)\\.\\.(\\/|$))[A-Za-z0-9_@+.,~=\\-/]+$/;\nconst SAFE_URL = /^(?!\\/)(?!.*(^|\\/)\\.\\.(\\/|$))[A-Za-z0-9_.\\-/]+\\.json$/;\n\nclass Checker {\n readonly problems: string[] = [];\n fail(msg: string): void { if (this.problems.length < MAX_PROBLEMS) this.problems.push(msg); }\n isObj(v: unknown, at: string): v is Record<string, unknown> {\n if (typeof v === 'object' && v !== null && !Array.isArray(v)) return true;\n this.fail(`${at}: expected an object`); return false;\n }\n str(v: unknown, at: string, opt = false): boolean {\n if (v === undefined && opt) return true;\n if (typeof v === 'string' && v.length > 0 && v.length < 4096) return true;\n this.fail(`${at}: expected a non-empty string`); return false;\n }\n int(v: unknown, at: string, min = 0, max = Number.MAX_SAFE_INTEGER, nullable = false): boolean {\n if (v === null && nullable) return true;\n if (typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max) return true;\n this.fail(`${at}: expected an integer in ${min}..${max}${nullable ? ' or null' : ''}`); return false;\n }\n path(v: unknown, at: string): boolean {\n if (typeof v === 'string' && SAFE_PATH.test(v)) return true;\n this.fail(`${at}: not a safe relative repository path`); return false;\n }\n rect(v: unknown, at: string): boolean {\n if (!Array.isArray(v) || v.length !== 4) { this.fail(`${at}: rect must be [x, y, w, h]`); return false; }\n let ok = true;\n v.forEach((n, i) => { ok = this.int(n, `${at}[${i}]`, i < 2 ? -10 : 0, 10010) && ok; });\n return ok;\n }\n range(v: unknown, at: string): boolean {\n if (!this.isObj(v, at)) return false;\n let ok = this.path(v['path'], `${at}.path`) && this.int(v['start'], `${at}.start`, 1) && this.int(v['end'], `${at}.end`, 1) && this.str(v['sym'], `${at}.sym`);\n if (ok && (v['end'] as number) < (v['start'] as number)) { this.fail(`${at}: end before start`); ok = false; }\n if (v['os'] !== undefined && !OS_TAGS.has(v['os'] as string)) { this.fail(`${at}.os: unknown OS tag`); ok = false; }\n if (v['url'] !== undefined && !(typeof v['url'] === 'string' && v['url'].startsWith('https://github.com/nodejs/node/blob/'))) { this.fail(`${at}.url: not a nodejs/node GitHub permalink`); ok = false; }\n return ok;\n }\n}\n\nfunction report<T>(c: Checker, what: string, v: unknown): T {\n if (c.problems.length) throw new AtlasValidationError(what, c.problems);\n return v as T;\n}\n\n/** Validates index.json. Returns it typed, or throws AtlasValidationError listing the problems. */\nexport function validateIndex(v: unknown): AtlasIndex {\n const c = new Checker();\n if (!c.isObj(v, 'index')) return report(c, 'index', v);\n if (v['schema'] !== ATLAS_SCHEMA) c.fail(`schema: expected \"${ATLAS_SCHEMA}\", got ${JSON.stringify(v['schema'])}`);\n const node = v['node'];\n if (c.isObj(node, 'node')) {\n c.str(node['version'], 'node.version');\n if (!(typeof node['commit'] === 'string' && /^[0-9a-f]{40}$/.test(node['commit']))) c.fail('node.commit: expected a 40-hex commit');\n if (node['repo'] !== 'nodejs/node') c.fail('node.repo: expected \"nodejs/node\"');\n }\n const world = v['world'];\n if (c.isObj(world, 'world')) { c.int(world['w'], 'world.w', 1); c.int(world['h'], 'world.h', 1); }\n for (const k of ['files', 'search', 'edges']) if (!(typeof v[k] === 'string' && SAFE_URL.test(v[k]))) c.fail(`${k}: expected a relative .json URL`);\n const ids = new Set<string>(['o:world']);\n const boxes = v['boxes'];\n if (!Array.isArray(boxes)) c.fail('boxes: expected an array');\n else {\n boxes.forEach((b: unknown, i) => {\n const at = `boxes[${i}]`;\n if (!c.isObj(b, at)) return;\n if (c.str(b['id'], `${at}.id`)) {\n if (ids.has(b['id'] as string)) c.fail(`${at}.id: duplicate ${b['id']}`);\n ids.add(b['id'] as string);\n }\n if (!ids.has(b['p'] as string)) c.fail(`${at}.p: parent ${JSON.stringify(b['p'])} must appear earlier`);\n if (!INDEX_KINDS.has(b['k'] as string)) c.fail(`${at}.k: unknown kind`);\n c.int(b['t'], `${at}.t`, 1, 3);\n c.str(b['n'], `${at}.n`);\n c.str(b['d'], `${at}.d`, true);\n c.rect(b['r'], `${at}.r`);\n const loc = b['loc'];\n if (Array.isArray(loc)) loc.forEach((l: unknown, j) => c.range(l, `${at}.loc[${j}]`));\n else if (loc !== null) { if (c.isObj(loc, `${at}.loc`)) c.path(loc['tree'], `${at}.loc.tree`); }\n if (b['k'] === 'feature' && !(Array.isArray(loc) && loc.length > 0)) c.fail(`${at}: a feature needs at least one code range`);\n });\n }\n const paths = v['paths'];\n if (!Array.isArray(paths)) c.fail('paths: expected an array');\n else paths.forEach((p: unknown, i) => {\n const at = `paths[${i}]`;\n if (!c.isObj(p, at)) return;\n c.str(p['id'], `${at}.id`); c.str(p['title'], `${at}.title`);\n if (p['certainty'] !== 'model') c.fail(`${at}.certainty: curated paths are \"model\"`);\n const steps = (s: unknown, sat: string): void => {\n if (!Array.isArray(s)) { c.fail(`${sat}: expected an array`); return; }\n s.forEach((st: unknown, j) => {\n const a = `${sat}[${j}]`;\n if (!c.isObj(st, a)) return;\n c.str(st['id'], `${a}.id`); c.str(st['title'], `${a}.title`); c.str(st['desc'], `${a}.desc`);\n if (st['thread'] !== 'main' && st['thread'] !== 'pool') c.fail(`${a}.thread: main or pool`);\n if (!Array.isArray(st['locs']) || st['locs'].length === 0) c.fail(`${a}.locs: at least one location`);\n else st['locs'].forEach((l: unknown, k) => c.range(l, `${a}.locs[${k}]`));\n });\n };\n steps(p['steps'], `${at}.steps`);\n if (Array.isArray(p['branches'])) p['branches'].forEach((b: unknown, j) => { if (c.isObj(b, `${at}.branches[${j}]`)) steps(b['steps'], `${at}.branches[${j}].steps`); });\n else c.fail(`${at}.branches: expected an array`);\n });\n const chunks = v['chunks'];\n if (!Array.isArray(chunks)) c.fail('chunks: expected an array');\n else chunks.forEach((ch: unknown, i) => {\n const at = `chunks[${i}]`;\n if (!c.isObj(ch, at)) return;\n c.str(ch['id'], `${at}.id`);\n if (!ids.has(ch['group'] as string)) c.fail(`${at}.group: unknown box ${JSON.stringify(ch['group'])}`);\n if (!(typeof ch['url'] === 'string' && SAFE_URL.test(ch['url']))) c.fail(`${at}.url: expected a relative .json URL`);\n c.rect(ch['r'], `${at}.r`); c.int(ch['rows'], `${at}.rows`, 1); c.int(ch['bytes'], `${at}.bytes`, 1);\n });\n const aliases = v['aliases'];\n if (c.isObj(aliases, 'aliases')) for (const [k, t] of Object.entries(aliases)) if (typeof t !== 'string') c.fail(`aliases.${k}: expected a string`);\n return report<AtlasIndex>(c, 'index', v);\n}\n\n/** Validates a chunk file. `knownParents` are ids that may be referenced as parents (index boxes). */\nexport function validateChunk(v: unknown, knownParents?: ReadonlySet<string>): AtlasChunk {\n const c = new Checker();\n if (!c.isObj(v, 'chunk')) return report(c, 'chunk', v);\n if (v['schema'] !== CHUNK_SCHEMA) c.fail(`schema: expected \"${CHUNK_SCHEMA}\"`);\n c.str(v['id'], 'id'); c.str(v['group'], 'group');\n if (JSON.stringify(v['cols']) !== JSON.stringify(CHUNK_COLS)) c.fail('cols: unexpected column list');\n const rows = v['rows'];\n if (!Array.isArray(rows)) c.fail('rows: expected an array');\n else {\n const seen = new Set<string>();\n rows.forEach((r: unknown, i) => {\n const at = `rows[${i}]`;\n if (!Array.isArray(r) || (r.length !== 10 && r.length !== 11)) { c.fail(`${at}: expected 10 or 11 columns`); return; }\n const [id, p, k, n, x, y, w, h, a, b, variant] = r as unknown[];\n if (!c.str(id, `${at}.id`)) return;\n const ids = id as string;\n if (!(typeof p === 'string' && (seen.has(p) || p === v['group'] || knownParents?.has(p)))) c.fail(`${at}.p: parent ${JSON.stringify(p)} unknown or after its child`);\n if (!ROW_KINDS.has(k as string)) c.fail(`${at}.k: d, f or s`);\n c.str(n, `${at}.n`);\n c.rect([x, y, w, h], `${at}.rect`);\n if (k === 'd') { if (!ids.startsWith('d:')) c.fail(`${at}: directory id must start with d:`); }\n else if (k === 'f') { if (!ids.startsWith('f:')) c.fail(`${at}: file id must start with f:`); else c.path(ids.slice(2), `${at}.path`); c.int(b, `${at}.b`, 0, Number.MAX_SAFE_INTEGER, true); }\n else if (k === 's') {\n if (!/^s:[^#]+#.+$/.test(ids)) c.fail(`${at}: function id must be s:<path>#<name>`); else c.path(ids.slice(2, ids.indexOf('#')), `${at}.path`);\n if (c.int(a, `${at}.a`, 1) && c.int(b, `${at}.b`, 1) && (b as number) < (a as number)) c.fail(`${at}: end before start`);\n }\n if (variant !== undefined && typeof variant !== 'string') c.fail(`${at}.v: expected a string`);\n seen.add(ids);\n });\n }\n return report<AtlasChunk>(c, 'chunk', v);\n}\n\nexport function validateFiles(v: unknown, chunkCount: number): AtlasFiles {\n const c = new Checker();\n if (c.isObj(v, 'files')) {\n if (v['schema'] !== FILES_SCHEMA) c.fail(`schema: expected \"${FILES_SCHEMA}\"`);\n if (!Array.isArray(v['files'])) c.fail('files: expected an array');\n else v['files'].forEach((f: unknown, i) => {\n if (!Array.isArray(f) || f.length !== 3) { c.fail(`files[${i}]: expected [path, chunk, lines]`); return; }\n c.path(f[0], `files[${i}][0]`); c.int(f[1], `files[${i}][1]`, 0, chunkCount - 1); c.int(f[2], `files[${i}][2]`, 0);\n });\n }\n return report<AtlasFiles>(c, 'files', v);\n}\n\nexport function validateSearch(v: unknown): AtlasSearch {\n const c = new Checker();\n if (c.isObj(v, 'search')) {\n if (v['schema'] !== SEARCH_SCHEMA) c.fail(`schema: expected \"${SEARCH_SCHEMA}\"`);\n if (!Array.isArray(v['entries'])) c.fail('entries: expected an array');\n else v['entries'].forEach((e: unknown, i) => { if (!Array.isArray(e) || e.length !== 2 || typeof e[0] !== 'string' || typeof e[1] !== 'string') c.fail(`entries[${i}]: expected [label, id]`); });\n }\n return report<AtlasSearch>(c, 'search', v);\n}\n\nexport function validateEdges(v: unknown): AtlasEdges {\n const c = new Checker();\n if (c.isObj(v, 'edges')) {\n if (v['schema'] !== EDGES_SCHEMA) c.fail(`schema: expected \"${EDGES_SCHEMA}\"`);\n if (v['certainty'] !== 'inferred') c.fail('certainty: extracted edges are \"inferred\"');\n if (!Array.isArray(v['edges'])) c.fail('edges: expected an array');\n else v['edges'].forEach((e: unknown, i) => { if (c.isObj(e, `edges[${i}]`)) { c.str(e['kind'], `edges[${i}].kind`); c.str(e['from'], `edges[${i}].from`); } });\n }\n return report<AtlasEdges>(c, 'edges', v);\n}\n","// Links to Node's source at the atlas commit. The atlas never contains Node's source text:\n// the app fetches it on demand from rawSourceUrl().\nimport type { CodeRange, OsTag, Platform, Box } from './schema.ts';\n\nconst REPO = 'nodejs/node';\nconst enc = (path: string): string => path.split('/').map(encodeURIComponent).join('/');\nconst lines = (start?: number, end?: number): string =>\n start ? (end && end !== start ? `#L${start}-L${end}` : `#L${start}`) : '';\n\n/** https://github.com/nodejs/node/blob/<commit>/<path>#L<a>-L<b> - GitHub highlights the lines. */\nexport function githubBlobUrl(commit: string, path: string, start?: number, end?: number): string {\n return `https://github.com/${REPO}/blob/${commit}/${enc(path)}${lines(start, end)}`;\n}\n\n/** https://github.com/nodejs/node/tree/<commit>/<path> - a folder. */\nexport function githubTreeUrl(commit: string, path: string): string {\n return `https://github.com/${REPO}/tree/${commit}/${enc(path)}`;\n}\n\n/** https://github.dev/nodejs/node/blob/<commit>/<path>#L<a>-L<b> - opens the web editor. See GITHUB_DEV_NOTE. */\nexport function githubDevUrl(commit: string, path: string, start?: number, end?: number): string {\n return `https://github.dev/${REPO}/blob/${commit}/${enc(path)}${lines(start, end)}`;\n}\n\n/** Text for the UI next to \"Open in web editor\". */\nexport const GITHUB_DEV_NOTE =\n 'Opens in the GitHub web editor (github.dev, which redirects to vscode.dev). The line selection works only when you are signed in to GitHub; otherwise you land on a sign-in page.';\n\n/** https://raw.githubusercontent.com/nodejs/node/<commit>/<path> - plain source text for the source panel. */\nexport function rawSourceUrl(commit: string, path: string): string {\n return `https://raw.githubusercontent.com/${REPO}/${commit}/${enc(path)}`;\n}\n\n/** Does a location tagged `os` apply on `platform`? Untagged locations apply everywhere. */\nexport function osMatches(os: OsTag | undefined, platform: Platform): boolean {\n if (os === undefined) return true;\n if (os === 'win') return platform === 'win32';\n if (os === 'unix') return platform === 'linux' || platform === 'darwin';\n return os === platform;\n}\n\n/**\n * Picks the code range for a platform: an exact OS tag wins over \"unix\", which wins over an\n * untagged range. Returns undefined when no range applies (e.g. a Windows-only step on Linux).\n */\nexport function pickRange<T extends CodeRange>(ranges: readonly T[], platform: Platform): T | undefined {\n let best: T | undefined;\n let bestScore = -1;\n for (const r of ranges) {\n if (!osMatches(r.os, platform)) continue;\n const score = r.os === undefined ? 1 : r.os === 'unix' ? 2 : 3;\n if (score > bestScore) { best = r; bestScore = score; }\n }\n return best;\n}\n\nexport interface BoxLinks {\n /** GitHub permalink (blob with line range, blob for a file, tree for a folder). */\n github: string;\n /** Web editor link (files and ranges only). */\n githubDev?: string;\n /** Raw source text (files and ranges only). */\n raw?: string;\n /** The range the links point at, when there is one. */\n range?: CodeRange;\n}\n\n/** Links for a box on a platform, or undefined if it has no code location there (\"Your code\"). */\nexport function boxLinks(commit: string, box: Box, platform: Platform): BoxLinks | undefined {\n const r = pickRange(box.ranges, platform);\n if (r) return { github: githubBlobUrl(commit, r.path, r.start, r.end), githubDev: githubDevUrl(commit, r.path, r.start, r.end), raw: rawSourceUrl(commit, r.path), range: r };\n if (box.file) return { github: githubBlobUrl(commit, box.file.path), githubDev: githubDevUrl(commit, box.file.path), raw: rawSourceUrl(commit, box.file.path) };\n if (box.tree) return { github: githubTreeUrl(commit, box.tree) };\n return undefined;\n}\n\n/**\n * Maps a script URL as V8/CDP reports it for Node's own JavaScript to the repository path:\n * \"node:internal/timers\" -> \"lib/internal/timers.js\", \"node:fs\" -> \"lib/fs.js\".\n * Returns null for anything else (user code, file:// URLs, evaluated code).\n */\nexport function scriptUrlToPath(url: string): string | null {\n const m = /^node:([a-z0-9_][a-z0-9_./-]*)$/i.exec(url);\n if (!m || m[1] === undefined || m[1].includes('..')) return null;\n const id = m[1];\n return `lib/${id}${/\\.(m?js|cjs)$/.test(id) ? '' : '.js'}`;\n}\n","// AtlasStore: loads an atlas on demand over a caller-supplied fetchJson(relativeUrl).\n// Works in the browser (fetch) and in Node (read files). Every file is validated before use.\nimport type {\n AtlasIndex, AtlasChunk, AtlasEdges, Box, ChunkRef, ChunkRow, CodeRange, IndexBox, Platform, AbsRect, Tier, BoxKind,\n} from './schema.ts';\nimport { validateIndex, validateChunk, validateFiles, validateSearch, validateEdges } from './validate.ts';\nimport { pickRange, boxLinks, scriptUrlToPath } from './links.ts';\nimport type { BoxLinks } from './links.ts';\n\nexport type FetchJson = (relativeUrl: string) => Promise<unknown>;\n\nexport interface AtlasStoreOptions {\n fetchJson: FetchJson;\n /** URL of the index, relative to the atlas folder. Default \"index.json\". */\n indexUrl?: string;\n}\n\nexport interface SearchHit { id: string; label: string; score: number }\n\nconst ROW_KIND: Record<string, BoxKind> = { d: 'dir', f: 'file', s: 'fn' };\nconst WORLD = 'o:world';\n\nfunction indexBoxToBox(b: IndexBox): Box {\n const box: Box = { id: b.id, parent: b.p, kind: b.k, tier: b.t, title: b.n, rect: b.r, ranges: [] };\n if (b.d !== undefined) box.desc = b.d;\n if (Array.isArray(b.loc)) box.ranges = b.loc;\n else if (b.loc) box.tree = b.loc.tree;\n return box;\n}\n\nfunction rowToBox(row: ChunkRow, chunk: string): Box {\n const [id, p, k, n, x, y, w, h, a, b, v] = row;\n const box: Box = { id, parent: p, kind: ROW_KIND[k] ?? 'file', tier: 3, title: n, rect: [x, y, w, h], ranges: [], chunk };\n if (k === 's' && a !== null && b !== null) box.ranges = [{ path: id.slice(2, id.indexOf('#')), start: a, end: b, sym: n }];\n else if (k === 'f') box.file = { path: id.slice(2), lines: b };\n else if (k === 'd') box.tree = id.slice(id.indexOf(':', 2) + 1);\n if (v !== undefined) { box.variant = v; for (const r of box.ranges) r.cond = v; }\n return box;\n}\n\nexport class AtlasStore {\n readonly #fetchJson: FetchJson;\n readonly #indexUrl: string;\n #index: AtlasIndex | undefined;\n readonly #boxes = new Map<string, Box>();\n readonly #children = new Map<string, string[]>();\n readonly #abs = new Map<string, AbsRect>();\n readonly #chunks = new Map<string, Promise<AtlasChunk>>();\n #files: Promise<Map<string, [number, number]>> | undefined;\n #search: Promise<Array<[string, string]>> | undefined;\n #edges: Promise<AtlasEdges> | undefined;\n\n constructor(opts: AtlasStoreOptions) {\n this.#fetchJson = opts.fetchJson;\n this.#indexUrl = opts.indexUrl ?? 'index.json';\n }\n\n /** Loads and validates index.json (tiers 1-2). Call once before anything else. */\n async load(): Promise<AtlasIndex> {\n if (this.#index) return this.#index;\n const index = validateIndex(await this.#fetchJson(this.#indexUrl));\n this.#index = index;\n for (const b of index.boxes) this.#add(indexBoxToBox(b));\n return index;\n }\n\n get index(): AtlasIndex {\n if (!this.#index) throw new Error('AtlasStore: call load() first');\n return this.#index;\n }\n\n get commit(): string { return this.index.node.commit; }\n\n #add(box: Box): void {\n if (this.#boxes.has(box.id)) return; // split-directory rows repeat across chunks\n this.#boxes.set(box.id, box);\n const list = this.#children.get(box.parent);\n if (list) list.push(box.id); else this.#children.set(box.parent, [box.id]);\n }\n\n /** Follows aliases (old id -> new id), at most 16 hops. */\n resolveAlias(id: string): string {\n const aliases = this.index.aliases;\n let cur = id;\n for (let i = 0; i < 16 && Object.hasOwn(aliases, cur); i++) cur = aliases[cur] as string;\n return cur;\n }\n\n /** A box that is already loaded (tiers 1-2 always are), or undefined. */\n getBox(id: string): Box | undefined { return this.#boxes.get(this.resolveAlias(id)); }\n\n /** A box by id, loading the chunk that holds it when needed. */\n async box(id: string): Promise<Box | undefined> {\n const real = this.resolveAlias(id);\n const have = this.#boxes.get(real);\n if (have) return have;\n if (real.startsWith('f:') || real.startsWith('s:')) {\n const path = real.startsWith('f:') ? real.slice(2) : real.slice(2, real.indexOf('#'));\n const ref = await this.#chunkForPath(path);\n if (ref) await this.loadChunk(ref.id);\n } else if (real.startsWith('d:')) {\n const group = `o:${real.slice(2, real.indexOf(':', 2))}`;\n for (const ch of this.index.chunks) if (ch.group === group) await this.loadChunk(ch.id);\n }\n return this.#boxes.get(real);\n }\n\n /** Children that are loaded (tier-3 children appear once their chunk is loaded). */\n children(id: string): Box[] {\n return (this.#children.get(id) ?? []).map((c) => this.#boxes.get(c)).filter((b): b is Box => b !== undefined);\n }\n\n /** Absolute rect in world units. The box (and so its ancestors) must be loaded. */\n absRect(id: string): AbsRect | undefined {\n const real = this.resolveAlias(id);\n const cached = this.#abs.get(real);\n if (cached) return cached;\n if (real === WORLD) return { x: 0, y: 0, w: this.index.world.w, h: this.index.world.h };\n const box = this.#boxes.get(real);\n if (!box) return undefined;\n const p = this.absRect(box.parent);\n if (!p) return undefined;\n const [x, y, w, h] = box.rect;\n const abs = { x: p.x + (x / 1e4) * p.w, y: p.y + (y / 1e4) * p.h, w: (w / 1e4) * p.w, h: (h / 1e4) * p.h };\n this.#abs.set(real, abs);\n return abs;\n }\n\n /** Loads (once) and validates a chunk; its boxes become available. */\n loadChunk(chunkId: string): Promise<AtlasChunk> {\n let p = this.#chunks.get(chunkId);\n if (!p) {\n const ref = this.index.chunks.find((c) => c.id === chunkId);\n if (!ref) return Promise.reject(new Error(`unknown chunk ${chunkId}`));\n p = this.#fetchJson(ref.url).then((raw) => {\n const chunk = validateChunk(raw, new Set(this.#boxes.keys()));\n if (chunk.id !== ref.id || chunk.group !== ref.group) throw new Error(`chunk ${ref.url} does not match the manifest`);\n for (const row of chunk.rows) this.#add(rowToBox(row, chunk.id));\n return chunk;\n });\n p.catch(() => this.#chunks.delete(chunkId));\n this.#chunks.set(chunkId, p);\n }\n return p;\n }\n\n /** Chunks whose content intersects a world-space view rect (for a renderer at tier-3 zoom). */\n chunksInView(view: AbsRect): ChunkRef[] {\n const out: ChunkRef[] = [];\n for (const ch of this.index.chunks) {\n const g = this.absRect(ch.group);\n if (!g) continue;\n const [x, y, w, h] = ch.r;\n const r = { x: g.x + (x / 1e4) * g.w, y: g.y + (y / 1e4) * g.h, w: (w / 1e4) * g.w, h: (h / 1e4) * g.h };\n if (r.x < view.x + view.w && r.x + r.w > view.x && r.y < view.y + view.h && r.y + r.h > view.y) out.push(ch);\n }\n return out;\n }\n\n /** Loads every chunk that intersects the view. */\n async loadInView(view: AbsRect): Promise<void> {\n await Promise.all(this.chunksInView(view).map((c) => this.loadChunk(c.id)));\n }\n\n #loadFiles(): Promise<Map<string, [number, number]>> {\n this.#files ??= this.#fetchJson(this.index.files).then((raw) => {\n const f = validateFiles(raw, this.index.chunks.length);\n return new Map(f.files.map(([p, c, l]) => [p, [c, l]]));\n });\n return this.#files;\n }\n\n async #chunkForPath(path: string): Promise<ChunkRef | undefined> {\n const e = (await this.#loadFiles()).get(path);\n return e ? this.index.chunks[e[0]] : undefined;\n }\n\n /** Line count of a file in the atlas (undefined when the file is not in the atlas). */\n async lineCount(path: string): Promise<number | undefined> {\n return (await this.#loadFiles()).get(path)?.[1];\n }\n\n /**\n * The deepest box containing `line` of `path`: a function box if one contains it, else the\n * file box. Undefined when the file is not in the atlas (e.g. V8 headers are, test/ is not).\n */\n async locate(path: string, line: number): Promise<string | undefined> {\n const ref = await this.#chunkForPath(path);\n if (!ref) return undefined;\n await this.loadChunk(ref.id);\n const fileId = `f:${path}`;\n // Functions nest (a JS function inside another is its child box): descend to the smallest range.\n let best: Box | undefined;\n const visit = (id: string): void => {\n for (const child of this.children(id)) {\n const r = child.ranges[0];\n if (!r || line < r.start || line > r.end) continue;\n if (!best || r.end - r.start <= (best.ranges[0] as CodeRange).end - (best.ranges[0] as CodeRange).start) best = child;\n visit(child.id);\n }\n };\n visit(fileId);\n return best ? (best as Box).id : this.#boxes.has(fileId) ? fileId : undefined;\n }\n\n /** locate() for a V8/CDP script URL of Node's own JavaScript (\"node:internal/timers\"). */\n async locateScript(url: string, line: number): Promise<string | undefined> {\n const path = scriptUrlToPath(url);\n return path ? this.locate(path, line) : undefined;\n }\n\n /** The code range of a box for a platform (exact OS > unix > untagged). */\n pickRange(box: Box, platform: Platform): CodeRange | undefined { return pickRange(box.ranges, platform); }\n\n /** GitHub / web editor / raw links for a box on a platform. */\n links(box: Box, platform: Platform): BoxLinks | undefined { return boxLinks(this.commit, box, platform); }\n\n /** Case-insensitive search over box labels (loads search.json on first use). */\n async search(query: string, limit = 20): Promise<SearchHit[]> {\n this.#search ??= this.#fetchJson(this.index.search).then((raw) => validateSearch(raw).entries);\n const entries = await this.#search;\n const q = query.trim().toLowerCase();\n if (!q) return [];\n const hits: SearchHit[] = [];\n for (const [label, id] of entries) {\n const l = label.toLowerCase();\n const at = l.indexOf(q);\n if (at < 0) continue;\n const tail = l.split(/::|\\.|\\//).pop() ?? l;\n const score = l === q || tail === q ? 0 : tail.startsWith(q) ? 1 : at === 0 ? 2 : 3;\n hits.push({ id, label, score: score * 1e4 + l.length });\n }\n hits.sort((a, b) => a.score - b.score || (a.label < b.label ? -1 : a.label > b.label ? 1 : 0));\n return hits.slice(0, limit);\n }\n\n /** Extracted edges (inferred, not observed). */\n edges(): Promise<AtlasEdges> {\n this.#edges ??= this.#fetchJson(this.index.edges).then(validateEdges);\n return this.#edges;\n }\n\n /** Index boxes of a tier (1 or 2), for the first view. */\n boxesOfTier(tier: Tier): Box[] {\n return this.index.boxes.filter((b) => b.t === tier).map((b) => this.#boxes.get(b.id) as Box);\n }\n}\n","// Atlas ids the live view points at. Each is a feature box in the overlay (o:...), so it\n// survives releases: the overlay is updated when Node's code moves, the id stays.\n// The atlas builder fails if any of these ids is missing from a built atlas.\n// Meanings are true for Node v26.13.1 (libuv 1.52.1); each box links to the exact code.\n\nexport interface WellKnownEntry {\n readonly id: string;\n /** One line, plain English. */\n readonly meaning: string;\n}\n\nexport const WELL_KNOWN = {\n // ---- the event loop (libuv)\n uvRun: { id: 'o:loop.run', meaning: 'uv_run: the event loop. Runs due timers once, then turns: pending, idle, prepare, poll, pending again, check, close, timers.' },\n phaseTimers: { id: 'o:phase.timers', meaning: 'Timers phase: uv__run_timers runs every libuv timer whose time has come (Node uses one for all JS timers).' },\n phasePending: { id: 'o:phase.pending', meaning: 'Pending phase: callbacks deferred from the previous turn; on Windows, completed I/O requests run here.' },\n phaseIdle: { id: 'o:phase.idle', meaning: 'Idle phase: idle handles; Node keeps one active while immediates are queued so poll does not block.' },\n phasePrepare: { id: 'o:phase.prepare', meaning: 'Prepare phase: prepare handles, just before the loop waits for I/O.' },\n phasePoll: { id: 'o:phase.poll', meaning: 'Poll phase: waits for I/O (epoll, kqueue or IOCP) up to the next timer and runs what is ready.' },\n phaseCheck: { id: 'o:phase.check', meaning: 'Check phase: check handles; Node runs setImmediate callbacks here.' },\n phaseClosing: { id: 'o:phase.close', meaning: 'Close phase: close callbacks of handles closed during this turn.' },\n loopTime: { id: 'o:loop.updateTime', meaning: 'The loop clock: libuv reads the time once per turn; timers compare against this cached time.' },\n spinEventLoop: { id: 'o:loop.spin', meaning: \"Node's loop driver: calls uv_run until there is no more work, then emits beforeExit.\" },\n\n // ---- nextTick and microtasks\n tickEnqueue: { id: 'o:tick.nextTick', meaning: 'process.nextTick: pushes a callback onto the nextTick queue.' },\n tickDrain: { id: 'o:tick.drain', meaning: 'processTicksAndRejections: runs the nextTick queue, then microtasks, until both are empty.' },\n runNextTicks: { id: 'o:tick.runNextTicks', meaning: 'runNextTicks: drains nextTicks and microtasks between two timer or immediate callbacks.' },\n microtaskEnqueue: { id: 'o:microtask.queueMicrotask', meaning: 'queueMicrotask: puts a callback on V8\\'s microtask queue.' },\n microtaskCallback: { id: 'o:microtask.runCallback', meaning: 'runMicrotask: the wrapper that runs a queueMicrotask callback with async_hooks before/after.' },\n microtaskCheckpoint: { id: 'o:microtask.checkpoint', meaning: 'MicrotaskQueue::PerformCheckpoint: V8 runs all queued microtasks if it is not already doing so.' },\n microtaskDrain: { id: 'o:microtask.run', meaning: 'MicrotaskQueue::RunMicrotasks: V8 runs every queued microtask (promise reactions, queueMicrotask callbacks).' },\n runMicrotasksBinding: { id: 'o:microtask.binding', meaning: 'runMicrotasks(): the C++ binding processTicksAndRejections calls to make V8 drain the microtask queue.' },\n\n // ---- promises in V8\n promiseThen: { id: 'o:v8.promiseThen', meaning: 'Promise.prototype.then (V8 Torque builtin).' },\n performPromiseThen: { id: 'o:v8.performPromiseThen', meaning: 'PerformPromiseThen: stores the reaction, or queues a reaction job at once if the promise is already settled.' },\n triggerPromiseReactions: { id: 'o:v8.triggerReactions', meaning: 'TriggerPromiseReactions: when a promise settles, turns each stored reaction into a queued job.' },\n promiseReactionEnqueue: { id: 'o:v8.enqueueMicrotask', meaning: 'EnqueueMicrotask builtin: where a promise reaction job (or any microtask) is appended to the microtask queue.' },\n runMicrotasksBuiltin: { id: 'o:v8.runMicrotasksBuiltin', meaning: 'RunMicrotasks builtin: the loop inside V8 that takes jobs off the microtask queue.' },\n runSingleMicrotask: { id: 'o:v8.runSingleMicrotask', meaning: 'RunSingleMicrotask: runs one job, dispatching on its kind (callable, promise reaction, ...).' },\n promiseReactionRun: { id: 'o:v8.promiseReactionJob', meaning: 'PromiseReactionJob: runs a .then/.catch handler with the settled value and settles the derived promise.' },\n\n // ---- timers\n timerSet: { id: 'o:timers.setTimeout', meaning: 'setTimeout: creates a Timeout and inserts it into the timer lists.' },\n setInterval: { id: 'o:timers.setInterval', meaning: 'setInterval: a Timeout that is re-inserted after each run.' },\n timerInsert: { id: 'o:timers.insert', meaning: 'insert: appends the timer to the list for its duration; a new earliest list reschedules the libuv timer.' },\n scheduleTimer: { id: 'o:timers.scheduleTimer', meaning: 'Environment::ScheduleTimer: starts the single libuv timer for the earliest JS timer.' },\n timersNative: { id: 'o:timers.runTimers', meaning: 'Environment::RunTimers: the libuv timer callback; calls processTimers in JS and reschedules.' },\n timersProcess: { id: 'o:timers.processTimers', meaning: 'processTimers: walks the due timer lists in expiry order.' },\n listOnTimeout: { id: 'o:timers.listOnTimeout', meaning: 'listOnTimeout: runs each due timer of one list; nextTicks and microtasks run between timers.' },\n uvRunTimers: { id: 'o:phase.timers', meaning: 'uv__run_timers: libuv runs timers whose timeout is not later than the loop time.' },\n\n // ---- immediates\n immediateSet: { id: 'o:immediate.setImmediate', meaning: 'setImmediate: creates an Immediate and appends it to the immediate queue.' },\n immediateNative: { id: 'o:immediate.check', meaning: 'Environment::CheckImmediate: the check-phase callback that calls processImmediate.' },\n immediateProcess: { id: 'o:immediate.process', meaning: 'processImmediate: runs the queued immediates; nextTicks and microtasks run between them.' },\n toggleImmediateRef: { id: 'o:immediate.toggleRef', meaning: 'Environment::ToggleImmediateRef: starts/stops an idle handle so poll does not block while immediates wait.' },\n\n // ---- thread pool (libuv)\n poolQueueWork: { id: 'o:pool.queue_work', meaning: 'uv_queue_work: the public \"run this function on the thread pool\" call.' },\n poolSubmit: { id: 'o:pool.submit', meaning: 'uv__work_submit: queues work for the pool (starts the threads on first use).' },\n poolPost: { id: 'o:pool.post', meaning: 'post: appends to the shared work queue and wakes an idle pool thread.' },\n poolWorker: { id: 'o:pool.worker', meaning: 'worker: a pool thread; waits, runs one work item, posts the result back.' },\n poolDone: { id: 'o:pool.done', meaning: 'uv__work_done: on the main thread, runs the after-work callbacks of finished items.' },\n poolWake: { id: 'o:pool.asyncSend', meaning: 'uv_async_send: wakes the loop from another thread (eventfd/pipe on Unix, a completion packet on Windows).' },\n scheduleWork: { id: 'o:cb.ScheduleWork', meaning: \"ThreadPoolWork::ScheduleWork: Node's wrapper around uv_queue_work for fs, crypto and zlib jobs.\" },\n\n // ---- calling back into JavaScript\n asyncWrapMakeCallback: { id: 'o:cb.MakeCallback', meaning: 'AsyncWrap::MakeCallback: calls a JS callback for an async resource (async_hooks before/after).' },\n makeCallback: { id: 'o:cb.InternalMakeCallback', meaning: 'InternalMakeCallback: opens a callback scope, calls the function, closes the scope.' },\n callbackScopeClose: { id: 'o:cb.ScopeClose', meaning: 'InternalCallbackScope::Close: after a callback, runs microtasks or the nextTick drain.' },\n\n // ---- debugger\n inspectorPause: { id: 'o:inspector.pause', meaning: 'runMessageLoopOnPause: the main thread waits here while a breakpoint holds JavaScript.' },\n\n // ---- fs\n fsReadFile: { id: 'o:fs.readFile', meaning: 'fs.readFile: small files in one thread-pool job (ReadFileJob), large ones in chunks.' },\n fsReadFileJobRun: { id: 'o:fs.ReadFileJob.Run', meaning: 'ReadFileJob::Run: schedules the whole read on the thread pool.' },\n fsReadFileJobWork: { id: 'o:fs.ReadFileJob.DoThreadPoolWork', meaning: 'ReadFileJob::DoThreadPoolWork: open, fstat, read, close on a pool thread.' },\n fsReadFileJobAfter: { id: 'o:fs.ReadFileJob.AfterThreadPoolWork', meaning: 'ReadFileJob::AfterThreadPoolWork: builds the Buffer and calls back into JS.' },\n fsReqCallback: { id: 'o:fs.reqCallback', meaning: 'FSReqCallback::Resolve: delivers the result of an async fs request to its JS callback.' },\n fsReqPromise: { id: 'o:fs.reqPromise', meaning: 'FSReqPromise::Resolve: settles the promise of an fs/promises request.' },\n\n // ---- crypto\n cryptoPbkdf2: { id: 'o:crypto.pbkdf2', meaning: 'crypto.pbkdf2: creates a PBKDF2Job and runs it on the thread pool.' },\n cryptoRandomBytes: { id: 'o:crypto.randomBytes', meaning: 'crypto.randomBytes: creates a RandomBytesJob and runs it on the thread pool.' },\n cryptoJobRun: { id: 'o:crypto.jobRun', meaning: 'CryptoJob::Run: runs a crypto job now (sync) or schedules it on the thread pool (async).' },\n cryptoDeriveBitsWork: { id: 'o:crypto.deriveBitsWork', meaning: 'DeriveBitsJob::DoThreadPoolWork: the pool-thread side of pbkdf2, randomBytes, scrypt, hkdf...' },\n cryptoPbkdf2DeriveBits: { id: 'o:crypto.pbkdf2DeriveBits', meaning: 'PBKDF2Traits::DeriveBits: the PBKDF2 computation (OpenSSL) on a pool thread.' },\n cryptoRandomBytesDeriveBits: { id: 'o:crypto.randomBytesDeriveBits', meaning: 'RandomBytesTraits::DeriveBits: fills the buffer with random bytes on a pool thread.' },\n cryptoJobAfter: { id: 'o:crypto.jobAfter', meaning: 'CryptoJob::AfterThreadPoolWork: back on the main thread, calls job.ondone in JS.' },\n\n // ---- zlib\n zlibProcessChunk: { id: 'o:zlib.processChunk', meaning: 'processChunk: hands one chunk to the native zlib handle (async write).' },\n zlibWrite: { id: 'o:zlib.write', meaning: 'CompressionStream::Write: queues compression work on the thread pool.' },\n zlibWork: { id: 'o:zlib.work', meaning: 'ZlibContext::DoThreadPoolWork: runs deflate/inflate on a pool thread.' },\n zlibAfter: { id: 'o:zlib.after', meaning: 'CompressionStream::AfterThreadPoolWork: back on the main thread, calls the JS write callback.' },\n\n // ---- dns.lookup\n dnsLookup: { id: 'o:dns.lookup', meaning: 'dns.lookup: asks the OS resolver (getaddrinfo) on the thread pool, not c-ares.' },\n dnsGetAddrInfo: { id: 'o:dns.getAddrInfo', meaning: 'GetAddrInfo (C++): starts uv_getaddrinfo with AfterGetAddrInfo as callback.' },\n uvGetaddrinfo: { id: 'o:dns.uvGetaddrinfo', meaning: 'uv_getaddrinfo: queues the lookup as slow I/O work on the thread pool.' },\n getaddrinfoWork: { id: 'o:dns.getaddrinfoWork', meaning: 'uv__getaddrinfo_work: calls the OS getaddrinfo on a pool thread.' },\n dnsAfterGetAddrInfo: { id: 'o:dns.afterGetAddrInfo', meaning: 'AfterGetAddrInfo: back on the main thread, converts the addresses and calls oncomplete in JS.' },\n\n // ---- sockets, processes, http (async_hooks resources)\n streamRead: { id: 'o:net.streamRead', meaning: 'LibuvStreamWrap::OnUvRead: data arrived on a TCP socket, pipe or TTY; calls onread in JS.' },\n streamAfterWrite: { id: 'o:net.afterWrite', meaning: 'LibuvStreamWrap::AfterUvWrite: a write finished; calls the write callback.' },\n streamAfterShutdown: { id: 'o:net.afterShutdown', meaning: 'LibuvStreamWrap::AfterUvShutdown: the write side was shut down.' },\n onConnection: { id: 'o:net.onConnection', meaning: 'ConnectionWrap::OnConnection: a server accepted a connection.' },\n afterConnect: { id: 'o:net.afterConnect', meaning: 'ConnectionWrap::AfterConnect: an outgoing connect finished.' },\n udpRecv: { id: 'o:net.udpRecv', meaning: 'UDPWrap::OnRecv: a datagram arrived.' },\n processExit: { id: 'o:proc.onExit', meaning: 'ProcessWrap::OnExit: a child process exited.' },\n fsEvent: { id: 'o:fs.watchEvent', meaning: 'FSEventWrap::OnEvent: fs.watch saw a change.' },\n statWatcher: { id: 'o:fs.statWatcher', meaning: 'StatWatcher::Callback: fs.watchFile polled a changed stat.' },\n httpIncoming: { id: 'o:http.incoming', meaning: 'IncomingMessage: a received HTTP request (server) or response (client).' },\n httpClientRequest: { id: 'o:http.clientRequest', meaning: 'ClientRequest: an outgoing HTTP request.' },\n udpSendDone: { id: 'o:net.udpSendDone', meaning: 'UDPWrap::OnSendDone: a datagram send finished; calls oncomplete in JS.' },\n\n // ---- c-ares DNS (dns.resolve*, dns.Resolver)\n dnsChannel: { id: 'o:dns.channel', meaning: 'ChannelWrap::New: creates the c-ares resolver channel used by dns.resolve* and dns.Resolver.' },\n dnsQueryResponse: { id: 'o:dns.queryResponse', meaning: 'QueryWrap::QueueResponseCallback: defers a c-ares answer with SetImmediate, so its callback runs in the check phase.' },\n nativeImmediatesRun: { id: 'o:immediate.native', meaning: 'Environment::RunAndClearNativeImmediates: runs C++ SetImmediate callbacks (such as c-ares answers) from CheckImmediate.' },\n\n // ---- stream shutdown and handle close\n streamShutdownQueue: { id: 'o:uv.shutdown', meaning: 'uv_shutdown: on Unix, with no writes pending, puts the stream on the pending queue (uv__io_feed); on Windows (TCP), queues a pending request.' },\n streamShutdownRun: { id: 'o:uv.shutdownDone', meaning: 'Where the shutdown callback runs: uv__drain on Unix (from the pending phase), uv__process_tcp_shutdown_req on Windows (TCP).' },\n uvClose: { id: 'o:loop.uvClose', meaning: 'uv_close: starts closing a handle; its close callback always runs later, in the close phase.' },\n closeCallbacks: { id: 'o:loop.finishClose', meaning: 'Where a close callback runs: uv__finish_close (called by uv__run_closing_handles) on Unix, uv__process_endgames on Windows.' },\n handleOnClose: { id: 'o:cb.handleOnClose', meaning: \"HandleWrap::OnClose: Node's close callback for every handle; calls the JS handle's onclose.\" },\n\n // ---- streams and workers\n streamFinished: { id: 'o:streams.eos', meaning: 'eos (stream.finished): calls back once a stream has ended, finished or errored; used by pipeline.' },\n messagePortOnMessage: { id: 'o:worker.onMessage', meaning: 'MessagePort::OnMessage: delivers queued messages from another thread to the JS listener of the port.' },\n workerExit: { id: 'o:worker.onExit', meaning: 'Worker::JoinThread: after the worker thread stopped, calls onexit in the parent thread.' },\n} as const satisfies Record<string, WellKnownEntry>;\n\nexport type WellKnownName = keyof typeof WELL_KNOWN;\n\n/** The 7 phases in the order uv_run runs them in one turn (timers also run once before the first turn). */\nexport const PHASE_ORDER = ['pending', 'idle', 'prepare', 'poll', 'check', 'closing', 'timers'] as const;\nexport type PhaseName = (typeof PHASE_ORDER)[number];\nexport const PHASE_IDS: Readonly<Record<PhaseName, string>> = {\n timers: WELL_KNOWN.phaseTimers.id,\n pending: WELL_KNOWN.phasePending.id,\n idle: WELL_KNOWN.phaseIdle.id,\n prepare: WELL_KNOWN.phasePrepare.id,\n poll: WELL_KNOWN.phasePoll.id,\n check: WELL_KNOWN.phaseCheck.id,\n closing: WELL_KNOWN.phaseClosing.id,\n};\n\n/** Atlas id of an event-loop phase. */\nexport function phaseAtlasId(phase: PhaseName): string {\n return PHASE_IDS[phase];\n}\n\n/**\n * async_hooks resource types (as reported by Node v26.13.1, checked with a probe script) to\n * the atlas box where the resource's callback is made. Types not listed here map to nothing.\n */\nexport interface AsyncTypeInfo extends WellKnownEntry {\n /** Short label a student can read, shown as the item's title in the app (\"setTimeout\", \"pbkdf2 request\"). */\n readonly title: string;\n}\n\nexport const ASYNC_TYPE_INFO: Readonly<Record<string, AsyncTypeInfo>> = {\n Timeout: { id: WELL_KNOWN.listOnTimeout.id, title: 'setTimeout / setInterval timer', meaning: 'setTimeout / setInterval timer; its callback runs from listOnTimeout.' },\n Immediate: { id: WELL_KNOWN.immediateProcess.id, title: 'setImmediate', meaning: 'setImmediate; its callback runs from processImmediate in the check phase.' },\n TickObject: { id: WELL_KNOWN.tickDrain.id, title: 'process.nextTick', meaning: 'process.nextTick; its callback runs from processTicksAndRejections.' },\n PROMISE: { id: WELL_KNOWN.promiseReactionRun.id, title: 'promise', meaning: 'A promise (reported while an async hook is enabled); its reactions run as microtasks.' },\n Microtask: { id: WELL_KNOWN.microtaskCallback.id, title: 'queueMicrotask', meaning: 'queueMicrotask callback; runs from the microtask queue via runMicrotask.' },\n FSREQCALLBACK: { id: WELL_KNOWN.fsReqCallback.id, title: 'fs request (callback)', meaning: 'Callback-style fs request. fs.readFile\\'s ReadFileJob reports this type too (its callback comes from ReadFileJob::AfterThreadPoolWork).' },\n FSREQPROMISE: { id: WELL_KNOWN.fsReqPromise.id, title: 'fs/promises request', meaning: 'fs/promises request.' },\n PBKDF2REQUEST: { id: WELL_KNOWN.cryptoJobAfter.id, title: 'pbkdf2 request', meaning: 'crypto.pbkdf2 job; work in PBKDF2Traits::DeriveBits on the pool.' },\n RANDOMBYTESREQUEST: { id: WELL_KNOWN.cryptoJobAfter.id, title: 'randomBytes request', meaning: 'crypto.randomBytes / randomFill job; work in RandomBytesTraits::DeriveBits on the pool.' },\n SCRYPTREQUEST: { id: WELL_KNOWN.cryptoJobAfter.id, title: 'scrypt request', meaning: 'crypto.scrypt job on the pool.' },\n GETADDRINFOREQWRAP: { id: WELL_KNOWN.dnsAfterGetAddrInfo.id, title: 'dns.lookup request', meaning: 'dns.lookup request; getaddrinfo runs on the pool.' },\n ZLIB: { id: WELL_KNOWN.zlibAfter.id, title: 'zlib stream', meaning: 'zlib stream; each chunk is compressed on the pool.' },\n TCPWRAP: { id: WELL_KNOWN.streamRead.id, title: 'TCP connection', meaning: 'TCP socket handle; reads arrive in the poll phase.' },\n TCPSERVERWRAP: { id: WELL_KNOWN.onConnection.id, title: 'TCP server', meaning: 'TCP server handle; new connections arrive in the poll phase.' },\n TCPCONNECTWRAP: { id: WELL_KNOWN.afterConnect.id, title: 'TCP connect request', meaning: 'Outgoing TCP connect request.' },\n PIPEWRAP: { id: WELL_KNOWN.streamRead.id, title: 'pipe', meaning: 'Pipe handle (also stdio pipes).' },\n PIPECONNECTWRAP: { id: WELL_KNOWN.afterConnect.id, title: 'pipe connect request', meaning: 'Outgoing pipe connect request.' },\n TTYWRAP: { id: WELL_KNOWN.streamRead.id, title: 'terminal (TTY)', meaning: 'TTY handle (terminal stdio).' },\n WRITEWRAP: { id: WELL_KNOWN.streamAfterWrite.id, title: 'stream write', meaning: 'A stream write request.' },\n SHUTDOWNWRAP: { id: WELL_KNOWN.streamAfterShutdown.id, title: 'stream shutdown', meaning: 'A stream shutdown request; on Unix uv__drain runs its callback - in the pending phase when no write was waiting, else in poll after the last write.' },\n UDPWRAP: { id: WELL_KNOWN.udpRecv.id, title: 'UDP socket', meaning: 'UDP socket handle.' },\n PROCESSWRAP: { id: WELL_KNOWN.processExit.id, title: 'child process', meaning: 'Child process handle.' },\n FSEVENTWRAP: { id: WELL_KNOWN.fsEvent.id, title: 'fs.watch watcher', meaning: 'fs.watch handle.' },\n STATWATCHER: { id: WELL_KNOWN.statWatcher.id, title: 'fs.watchFile watcher', meaning: 'fs.watchFile handle.' },\n HTTPINCOMINGMESSAGE: { id: WELL_KNOWN.httpIncoming.id, title: 'HTTP incoming message', meaning: 'HTTP incoming message (server request or client response).' },\n QUERYWRAP: { id: WELL_KNOWN.dnsQueryResponse.id, title: 'DNS query (dns.resolve*)', meaning: 'A c-ares query; the answer is deferred with SetImmediate, so the callback runs in the check phase.' },\n DNSCHANNEL: { id: WELL_KNOWN.dnsChannel.id, title: 'DNS resolver (c-ares)', meaning: 'The c-ares channel behind dns.resolve* and dns.Resolver; created when the dns module loads.' },\n PIPESERVERWRAP: { id: WELL_KNOWN.onConnection.id, title: 'pipe server', meaning: 'Pipe (named pipe / Unix socket) server handle; new connections arrive in the poll phase.' },\n UDPSENDWRAP: { id: WELL_KNOWN.udpSendDone.id, title: 'UDP send', meaning: 'A UDP send request.' },\n STREAM_END_OF_STREAM: { id: WELL_KNOWN.streamFinished.id, title: 'stream finished callback', meaning: 'stream.finished / pipeline callback, bound to the context where it was registered.' },\n MESSAGEPORT: { id: WELL_KNOWN.messagePortOnMessage.id, title: 'MessagePort (worker messages)', meaning: 'A message channel between threads; messages are delivered by MessagePort::OnMessage.' },\n WORKER: { id: WELL_KNOWN.workerExit.id, title: 'worker thread', meaning: 'A worker_threads Worker as seen from the parent thread.' },\n HTTPCLIENTREQUEST: { id: WELL_KNOWN.httpClientRequest.id, title: 'HTTP client request', meaning: 'HTTP client request.' },\n};\n\n/** async_hooks type string -> atlas id of the best place to point at for an item of that type. */\nexport const ASYNC_TYPE_AT: Readonly<Record<string, string>> = Object.fromEntries(\n Object.entries(ASYNC_TYPE_INFO).map(([type, e]) => [type, e.id]),\n);\n\n/** Every distinct well-known id (WELL_KNOWN plus the async type map). */\nexport function allWellKnownIds(): string[] {\n const ids = new Set<string>();\n for (const e of Object.values(WELL_KNOWN)) ids.add(e.id);\n for (const id of Object.values(ASYNC_TYPE_AT)) ids.add(id);\n return [...ids].sort();\n}\n","/**\n * Words and numbers for the screen. Pure functions; everything returned is plain text\n * that components render as text nodes (never as HTML).\n */\nimport type { EventKind, NmEvent, Phase, QueueName, SourceId } from '@nodejs-map/event-format';\nimport { ASYNC_TYPE_INFO } from '@nodejs-map/atlas-format';\n\nexport const QUEUE_ORDER: readonly QueueName[] = ['nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close'];\n\nexport const QUEUE_LABEL: Readonly<Record<QueueName, string>> = {\n nextTick: 'nextTick queue',\n microtask: 'Microtask queue',\n timers: 'Timers',\n immediate: 'Immediates',\n pool: 'Thread pool requests',\n io: 'Pending I/O',\n close: 'Close callbacks',\n};\n\nexport const QUEUE_HELP: Readonly<Record<QueueName, string>> = {\n nextTick: 'process.nextTick callbacks. Drained after the current callback, before promises.',\n microtask: 'Promise reactions and queueMicrotask callbacks (V8). Drained after the nextTick queue.',\n timers: 'setTimeout and setInterval. Run in the timers phase when their time has come.',\n immediate: 'setImmediate callbacks. Run in the check phase.',\n pool: 'Requests whose work runs on the libuv thread pool.',\n io: 'Requests and handles waiting on the operating system.',\n close: 'Handles waiting for their close callback.',\n};\n\nexport const PHASE_LABEL: Readonly<Record<Phase, string>> = {\n timers: 'timers',\n pending: 'pending',\n idle: 'idle',\n prepare: 'prepare',\n poll: 'poll',\n check: 'check',\n closing: 'close',\n};\n\nexport const SOURCE_LABEL: Readonly<Record<SourceId, string>> = {\n hooks: 'async_hooks',\n trace: 'trace events',\n cdp: 'debugger',\n probe: 'probe build',\n helper: 'helper',\n rule: 'rule',\n};\n\nexport const SOURCE_HELP: Readonly<Record<SourceId, string>> = {\n hooks: 'Reported by async_hooks inside the program.',\n trace: \"Reported by Node's own trace events.\",\n cdp: 'Reported by the JavaScript debugger (DevTools protocol).',\n probe: 'Reported by the probe build from inside libuv and Node.',\n helper: 'Reported by the nodejs-map helper process.',\n rule: 'Worked out by a rule from other events.',\n};\n\nconst nf1 = new Intl.NumberFormat('en', { maximumFractionDigits: 1, minimumFractionDigits: 1 });\nconst nf3 = new Intl.NumberFormat('en', { maximumFractionDigits: 3, minimumFractionDigits: 3 });\nconst nf0 = new Intl.NumberFormat('en', { maximumFractionDigits: 0 });\n\n/** A point in time or a span given in microseconds: \"850 µs\", \"12.345 ms\", \"3.210 s\". */\nexport function formatMicros(us: number): string {\n if (!Number.isFinite(us)) return '-';\n const abs = Math.abs(us);\n if (abs < 1000) return `${nf0.format(us)} µs`;\n if (abs < 1_000_000) return `${nf3.format(us / 1000)} ms`;\n return `${nf3.format(us / 1_000_000)} s`;\n}\n\n/** A span given in milliseconds: \"0.4 ms\", \"12.0 ms\", \"3.2 s\". */\nexport function formatMillis(ms: number): string {\n if (!Number.isFinite(ms)) return '-';\n if (Math.abs(ms) < 1000) return `${nf1.format(ms)} ms`;\n return `${nf1.format(ms / 1000)} s`;\n}\n\nexport function formatCount(n: number): string {\n return nf0.format(n);\n}\n\nexport function plural(n: number, one: string, many = `${one}s`): string {\n return `${formatCount(n)} ${n === 1 ? one : many}`;\n}\n\n/** Last path segment of a URL or path: \"file:///a/b/c.js\" -> \"c.js\". Never throws. */\nexport function baseName(urlOrPath: string): string {\n const cut = urlOrPath.replace(/[?#].*$/, '');\n const parts = cut.split(/[\\\\/]/);\n for (let i = parts.length - 1; i >= 0; i--) {\n const part = parts[i];\n if (part) {\n try {\n return decodeURIComponent(part);\n } catch {\n return part;\n }\n }\n }\n return urlOrPath;\n}\n\n/** Does a script URL from the target name this program? Compared by base name. */\nexport function isSameProgram(scriptUrl: string, programName: string): boolean {\n if (scriptUrl === programName) return true;\n if (scriptUrl.startsWith('node:')) return false; // Node's own JavaScript is never the program\n return baseName(scriptUrl) === baseName(programName);\n}\n\n/** Text is shown on one line in lists: cut it and make control characters visible. */\nexport function oneLine(text: string, max = 160): string {\n let out = '';\n for (const ch of text) {\n if (out.length >= max) return `${out}…`;\n const code = ch.codePointAt(0) as number;\n if (ch === '\\n') out += '⏎';\n else if (ch === '\\t') out += ' ';\n else if (code < 0x20 || code === 0x7f) out += '�';\n else out += ch;\n }\n return out;\n}\n\n/**\n * Plain words for an async_hooks type, shown before the raw type (which stays visible next\n * to them). In order: the label the helper gave the item (\"setTimeout 5 ms\"), else the\n * title the atlas has for the type (ASYNC_TYPE_INFO), else the few words below for types\n * the atlas does not list. null: we have no words, the raw type is all there is.\n */\nconst OWN_WORDS: Readonly<Record<string, string>> = {\n GETNAMEINFOREQWRAP: 'dns.lookupService request',\n};\n\nexport function itemKindWords(type: string): string | null {\n const title = ASYNC_TYPE_INFO[type]?.title;\n if (title) return title;\n const own = OWN_WORDS[type];\n if (own) return own;\n // Crypto jobs are all named <WHAT>REQUEST (HKDFREQUEST, SIGNREQUEST, ...).\n const crypto = /^([A-Z0-9]{2,24})REQUEST$/.exec(type);\n if (crypto && crypto[1]) return `${crypto[1].toLowerCase()} request`;\n return null;\n}\n\n/** For labels and dialog titles: \"setTimeout 5 ms #12 (Timeout)\", \"TCP server #7 (TCPSERVERWRAP)\". */\nexport function itemTitle(item: { id: number; type: string; label: string | null }): string {\n const words = item.label ? oneLine(item.label, 60) : itemKindWords(item.type);\n return words ? `${words} #${item.id} (${item.type})` : `${item.type} #${item.id}`;\n}\n\n/** Groups for the event log filters. Every kind belongs to exactly one. */\nexport type LogGroup = 'run' | 'output' | 'callbacks' | 'queues' | 'loop' | 'timers' | 'pool' | 'items' | 'debug' | 'signals';\n\nexport const LOG_GROUPS: readonly LogGroup[] = ['run', 'output', 'callbacks', 'queues', 'loop', 'timers', 'pool', 'items', 'debug', 'signals'];\n\nexport const LOG_GROUP_LABEL: Readonly<Record<LogGroup, string>> = {\n run: 'Run',\n output: 'Output',\n callbacks: 'Callbacks',\n queues: 'Queues',\n loop: 'Loop',\n timers: 'Timers',\n pool: 'Pool',\n items: 'Items',\n debug: 'Debugger',\n signals: 'Raw signals',\n};\n\nexport const KIND_GROUP: Readonly<Record<EventKind, LogGroup>> = {\n 'run.start': 'run',\n 'run.end': 'run',\n note: 'run',\n output: 'output',\n 'item.new': 'items',\n 'item.gone': 'items',\n 'promise.settled': 'items',\n 'callback.start': 'callbacks',\n 'callback.end': 'callbacks',\n 'timer.set': 'timers',\n 'timer.fired': 'timers',\n 'loop.sample': 'signals',\n scope: 'signals',\n 'pool.thread': 'signals',\n signal: 'signals',\n 'queue.add': 'queues',\n 'queue.remove': 'queues',\n 'loop.turn': 'loop',\n 'phase.enter': 'loop',\n 'phase.leave': 'loop',\n 'pool.queued': 'pool',\n 'pool.started': 'pool',\n 'pool.finished': 'pool',\n 'pool.posted': 'pool',\n 'pool.delivered': 'pool',\n 'pool.cancelled': 'pool',\n 'pool.size': 'pool',\n 'pool.link': 'pool',\n 'debug.paused': 'debug',\n 'debug.resumed': 'debug',\n 'gate.stopped': 'debug',\n 'gate.released': 'debug',\n 'clock.frozen': 'debug',\n 'clock.unfrozen': 'debug',\n};\n\n/** One line that says what an event is. Used by the event log (built in the worker). */\nexport function summarizeEvent(e: NmEvent): string {\n switch (e.k) {\n case 'run.start':\n return `Run started: ${oneLine(e.program, 60)} on Node ${e.node.version} (${e.mode === 'debug' ? 'debug' : 'free run'}, pool size ${e.poolSize})`;\n case 'run.end':\n return e.signal ? `Run ended by signal ${e.signal}` : `Run ended with exit code ${String(e.code)}`;\n case 'output':\n return `${e.stream}: ${oneLine(e.text, 120)}`;\n case 'item.new':\n return `New ${e.label ? `${oneLine(e.label, 40)} (${e.type})` : e.type} #${e.id}, created during #${e.trigger}${e.loc ? ` at ${baseName(e.loc.url)}:${e.loc.line}` : ''}`;\n case 'callback.start':\n // `close` marks the close callback of a handle (a socket, a server, a child process).\n return `${e.close === true ? 'Close callback' : 'Callback'} of ${e.type} #${e.id} started`;\n case 'callback.end':\n return `Callback of #${e.id} returned`;\n case 'item.gone':\n return `#${e.id} destroyed`;\n case 'promise.settled':\n return `Promise #${e.id} settled`;\n case 'timer.set':\n return `${e.repeat ? 'setInterval' : 'setTimeout'} #${e.id}: ${formatMillis(e.delayMs)}`;\n case 'loop.sample':\n return `Loop counters: turn ${e.loopCount}, ${e.events} events, ${e.eventsWaiting} waiting`;\n case 'scope':\n return `Node scope ${oneLine(e.name, 40)} lasted ${formatMicros(e.durUs)}`;\n case 'pool.thread':\n return `A pool thread ${e.edge === 'start' ? 'started' : 'finished'} ${oneLine(e.name, 40)}`;\n case 'signal':\n return `${oneLine(e.cat, 40)} / ${oneLine(e.name, 40)} (${oneLine(e.ph, 4)})`;\n case 'queue.add':\n return `#${e.id} waits in ${QUEUE_LABEL[e.queue] ?? e.queue}`;\n case 'queue.remove':\n return `#${e.id} left ${QUEUE_LABEL[e.queue] ?? e.queue} (${e.why === 'cancel' ? 'cancelled' : 'gone'})`;\n case 'loop.turn':\n return `Loop turn ${e.n}`;\n case 'phase.enter':\n return `Entered the ${PHASE_LABEL[e.phase] ?? e.phase} phase`;\n case 'phase.leave':\n return `Left the ${PHASE_LABEL[e.phase] ?? e.phase} phase`;\n case 'timer.fired':\n return `Node's timer is due${e.lateMs === undefined ? '' : `, ${formatMillis(e.lateMs)} late`}`;\n case 'pool.queued':\n return `Pool job ${oneLine(e.job, 24)} queued (${e.kind}${e.op ? ` ${oneLine(e.op, 30)}` : ''})`;\n case 'pool.started':\n return `Pool thread ${e.thread} started job ${oneLine(e.job, 24)}`;\n case 'pool.finished':\n return `Pool thread ${e.thread} finished job ${oneLine(e.job, 24)}`;\n case 'pool.posted':\n return `Pool thread ${e.thread} posted the result of job ${oneLine(e.job, 24)} to the loop`;\n case 'pool.delivered':\n return `The loop took the result of pool job ${oneLine(e.job, 24)}`;\n case 'pool.cancelled':\n return `Pool job ${oneLine(e.job, 24)} was cancelled before a thread took it`;\n case 'pool.size':\n return `The thread pool has ${e.size} threads (the program changed the size before first use)`;\n case 'pool.link':\n return `Pool job ${oneLine(e.job, 24)} belongs to #${e.id}`;\n case 'debug.paused': {\n const top = e.frames[0];\n return `Paused (${e.reason})${top ? ` at ${baseName(top.loc.url)}:${top.loc.line}` : ''}`;\n }\n case 'debug.resumed':\n return `Resumed after ${formatMillis(e.pausedMs)}`;\n case 'gate.stopped':\n return `Stopped at the ${e.gate} gate${e.phase ? ` (${PHASE_LABEL[e.phase] ?? e.phase})` : ''}`;\n case 'gate.released':\n return `Gate released after ${formatMillis(e.stoppedMs)}`;\n case 'clock.frozen':\n return 'Loop clock frozen';\n case 'clock.unfrozen':\n return `Loop clock running again; ${formatMillis(e.hiddenMs)} hidden from the program`;\n case 'note':\n return `${e.level === 'warn' ? 'Warning from the tool' : 'Note from the tool'}: ${oneLine(e.text, 220)}`;\n default:\n // A kind from a newer format version: show its name rather than nothing.\n return String((e as { k: unknown }).k);\n }\n}\n","var i=Symbol.for(\"preact-signals\");function t(){if(!(v>1)){var i,t=!1;!function(){var i=c;c=void 0;while(void 0!==i){var t=i.S;if(t.v===i.v)for(var r=t.t;void 0!==r;r=r.x)if(r.i===i.i)r.i=t.i;i=i.o}}();while(void 0!==h){var r=h;h=void 0;s++;while(void 0!==r){var n=r.u;r.u=void 0;r.f&=-3;if(!(8&r.f)&&w(r))try{r.c()}catch(r){if(!t){i=r;t=!0}}r=n}}s=0;v--;if(t)throw i}else v--}function r(i){if(v>0)return i();u=++e;v++;try{return i()}finally{t()}}var n,o=void 0;function f(i){var t=o,r=n;o=void 0;n=void 0;try{return i()}finally{o=t;n=r}}var h=void 0,v=0,s=0,e=0,u=0,c=void 0,a=0;function d(i){if(void 0!==o){var t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t}return t}}}function l(i,t){this.v=i;this.i=0;this.n=void 0;this.t=void 0;this.l=0;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name}l.prototype.brand=i;l.prototype.h=function(){return!0};l.prototype.S=function(i){var t=this,r=this.t;if(r!==i&&void 0===i.e){i.x=r;this.t=i;if(void 0!==r)r.e=i;else f(function(){var i;null==(i=t.W)||i.call(t)})}};l.prototype.U=function(i){var t=this;if(void 0!==this.t){var r=i.e,n=i.x;if(void 0!==r){r.x=n;i.e=void 0}if(void 0!==n){n.e=r;i.x=void 0}if(i===this.t){this.t=n;if(void 0===n)f(function(){var i;null==(i=t.Z)||i.call(t)})}}};l.prototype.subscribe=function(i){var t=this;return x(function(){var r=t.value;f(function(){return i(r)})},{name:\"sub\"})};l.prototype.valueOf=function(){return this.value};l.prototype.toString=function(){return this.value+\"\"};l.prototype.toJSON=function(){return this.value};l.prototype.peek=function(){var i=this;return f(function(){return i.value})};Object.defineProperty(l.prototype,\"value\",{get:function(){var i=d(this);if(void 0!==i)i.i=this.i;return this.v},set:function(i){if(i!==this.v){if(s>100)throw new Error(\"Cycle detected\");!function(i){if(0!==v&&0===s)if(i.l!==u){i.l=u;c={S:i,v:i.v,i:i.i,o:c}}}(this);this.v=i;this.i++;a++;v++;try{for(var r=this.t;void 0!==r;r=r.x)r.t.N()}finally{t()}}}});function y(i,t){return new l(i,t)}function w(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function b(i){for(var t=i.s;void 0!==t;t=t.n){var r=t.S.n;if(void 0!==r)t.r=r;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break}}}function _(i){var t=i.s,r=void 0;while(void 0!==t){var n=t.p;if(-1===t.i){t.S.U(t);if(void 0!==n)n.n=t.n;if(void 0!==t.n)t.n.p=n}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=n}i.s=r}function j(i,t){l.call(this,void 0,t);this.x=i;this.s=void 0;this.g=a-1;this.f=4}j.prototype=new l;j.prototype.h=function(){this.f&=-3;if(1&this.f)return!1;if(32==(36&this.f))return!0;this.f&=-5;if(this.g===a)return!0;this.g=a;this.f|=1;if(this.i>0&&!w(this)){this.f&=-2;return!0}var i=o;try{b(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++}}catch(i){this.v=i;this.f|=16;this.i++}o=i;_(this);this.f&=-2;return!0};j.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t)}l.prototype.S.call(this,i)};j.prototype.U=function(i){if(void 0!==this.t){l.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t)}}};j.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N()}};Object.defineProperty(j.prototype,\"value\",{get:function(){if(1&this.f)throw new Error(\"Cycle detected\");var i=d(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v}});function O(i,t){return new j(i,t)}function p(i){var r=i.j;i.j=void 0;if(\"function\"==typeof r){v++;var n=o;o=void 0;try{r()}catch(t){i.f&=-2;i.f|=8;g(i);throw t}finally{o=n;t()}}}function g(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;p(i)}function S(i){if(o!==this)throw new Error(\"Out-of-order effect\");_(this);o=i;this.f&=-2;try{if(8&this.f)g(this)}finally{t()}}function m(i,t){this.x=i;this.j=void 0;this.s=void 0;this.u=void 0;this.f=32;this.name=null==t?void 0:t.name;if(n)n.push(this)}m.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if(\"function\"==typeof t)this.j=t}finally{i()}};m.prototype.S=function(){if(1&this.f)throw new Error(\"Cycle detected\");this.f|=1;this.f&=-9;p(this);b(this);v++;var i=o;o=this;return S.bind(this,i)};m.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.u=h;h=this}};m.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this)};m.prototype.dispose=function(){this.d()};function x(i,t){var r=new m(i,t);try{r.c()}catch(i){r.d();throw i}var n=r.d.bind(r);n[Symbol.dispose]=n;return n}function E(i){return function(){var t=arguments,n=this;return r(function(){return f(function(){return i.apply(n,[].slice.call(t))})})}}function C(){var i=n;n=[];return function(){var t=n;if(n&&i)i=i.concat(n);n=i;return t}}var k=function(i,t){t.push(i);for(var r=\"[object Object]\"===Object.prototype.toString.call(i),n=Object.create(null),o=i;o&&o!==Object.prototype;o=r&&Object.getPrototypeOf(o)){var f=Object.getOwnPropertyDescriptors(o);for(var h in f)if(!n[h]){n[h]=!0;var v=f[h].value;if(\"function\"==typeof v){if(\"constructor\"!==h)i[h]=E(v)}else if(o===i&&\"object\"==typeof v&&null!==v&&!(\"brand\"in v)&&t.indexOf(v)<0)k(v,t)}}};function T(i){return function(){var t,o,f=C();try{o=i.apply(void 0,[].slice.call(arguments))}catch(i){var h=n;n=void 0;if(h)try{r(function(){for(var i=0;i<h.length;i++)try{h[i].dispose()}catch(i){}})}catch(i){}throw i}finally{t=f()}k(o,[]);o[Symbol.dispose]=E(function(){if(t)for(var i=0;i<t.length;i++)t[i].dispose();t=void 0});return o}}export{j as Computed,m as Effect,l as Signal,E as action,r as batch,O as computed,T as createModel,x as effect,y as signal,f as untracked};//# sourceMappingURL=signals-core.module.js.map\n","import{createElement as i,Fragment as n,Component as r,options as t,isValidElement as f}from\"preact\";import{useMemo as o,useRef as e,useEffect as u}from\"preact/hooks\";import{effect as a,Signal as c,computed as v,signal as s,batch as l}from\"@preact/signals-core\";export{Signal,action,batch,computed,createModel,effect,signal,untracked}from\"@preact/signals-core\";var h,d,p,m=\"undefined\"!=typeof window&&!!window.__PREACT_SIGNALS_DEVTOOLS__,_=[],g=[];a(function(){h=this.N})();function b(i,n){t[i]=n.bind(null,t[i]||function(){})}function y(i){if(p){var n=p;p=void 0;n()}p=i&&i.S()}function w(i){var n=this,r=i.data,t=useSignal(r);t.name=\"ReactiveDom\";t.value=r;var e=o(function(){var i=n,r=n.__v;while(r=r.__)if(r.__c){r.__c.__$f|=4;break}var o=v(function(){var i=t.value.value;return 0===i?0:!0===i?\"\":i||\"\"}),e=v(function(){return!Array.isArray(o.value)&&!f(o.value)}),u=a(function(){this.N=M;if(e.value){var n=o.value;if(i.__v&&i.__v.__e&&3===i.__v.__e.nodeType)i.__v.__e.data=n}}),c=n.__$u.d;n.__$u.d=function(){u();c.call(this)};return[e,o]},[]),u=e[0],c=e[1];return u.value?c.peek():c.value}w.displayName=\"ReactiveTextNode\";Object.defineProperties(c.prototype,{constructor:{configurable:!0,value:i(n,null).constructor},type:{configurable:!0,value:w},props:{configurable:!0,get:function(){var i=this;return{data:{get value(){return i.value}}}}},__b:{configurable:!0,value:1}});b(\"__b\",function(i,n){y();d=void 0;if(\"string\"==typeof n.type){var r,t=n.props;for(var f in t)if(\"children\"!==f){var o=t[f];if(o instanceof c){if(!r)n.__np=r={};r[f]=o;t[f]=o.peek()}}}i(n)});b(\"__r\",function(i,r){i(r);if(r.type!==n){y();var t,f=r.__c;if(f){f.__$f&=-2;if(void 0===(t=f.__$u))f.__$u=t=function(i,n){var r;a(function(){r=this},{name:n});r.c=i;return r}(function(i){return function(){var n;if(m)null==(n=this.y)||n.call(this);i.__$f|=1;i.setState({})}}(f),\"function\"==typeof r.type?r.type.displayName||r.type.name:\"\")}d=f;y(t)}});b(\"__e\",function(i,n,r,t){y();d=void 0;i(n,r,t)});b(\"diffed\",function(i,n){y();d=void 0;var r;if(\"string\"==typeof n.type&&(r=n.__e)){var t=n.__np,f=n.props,o=r.U;if(o)for(var e in o){var u=o[e];if(!(void 0===u||t&&e in t)){u.d();o[e]=void 0}}if(t){if(!o){o={};r.U=o}for(var a in t){var c=o[a],v=t[a];if(void 0===c){c=k(r,a,v,f);o[a]=c}else c.o(v,f)}}}i(n)});function k(i,n,r,t){var f=n in i&&void 0===i.ownerSVGElement,o=s(r);return{o:function(i,n){o.value=i;t=n},d:a(function(){this.N=M;var r=o.value.value;if(t[n]!==r){t[n]=r;if(f)i[n]=r;else if(null!=r&&(!1!==r||\"-\"===n[4]))i.setAttribute(n,r);else i.removeAttribute(n)}})}}b(\"unmount\",function(i,n){if(\"string\"==typeof n.type){var r=n.__e;if(r){var t=r.U;if(t){r.U=void 0;for(var f in t){var o=t[f];if(o)o.d()}}}var e=n.__np;if(e){var u=n.props;for(var a in e)u[a]=e[a]}n.__np=void 0}else{var c=n.__c;if(c){c.__$f|=8;var v=c.__$u;if(v){c.__$u=void 0;v.d()}}}i(n)});b(\"__h\",function(i,n,r,t){if(t<3)n.__$f|=2;i(n,r,t)});r.prototype.shouldComponentUpdate=function(i,n){if(this.__R)return!0;var r=this.__$u,t=r&&void 0!==r.s;for(var f in n)return!0;if(this.__f||\"boolean\"==typeof this.u&&!0===this.u){var o=2&this.__$f;if(!(t||o||4&this.__$f))return!0;if(1&this.__$f)return!0}else{if(!(t||4&this.__$f))return!0;if(3&this.__$f)return!0}for(var e in i)if(\"__source\"!==e&&i[e]!==this.props[e])return!0;for(var u in this.props)if(!(u in i))return!0;return!1};function useSignal(i,n){return o(function(){return s(i,n)},[])}function useComputed(i,n){var r=e(i);r.current=i;d.__$f|=4;return o(function(){return v(function(){return r.current()},n)},[])}var q=\"undefined\"==typeof requestAnimationFrame?setTimeout:function(i){var n=function(){clearTimeout(r);cancelAnimationFrame(t);i()},r=setTimeout(n,35),t=requestAnimationFrame(n)},A=function(i){queueMicrotask(function(){queueMicrotask(i)})};function T(){l(function(){var i;while(i=_.shift())h.call(i)})}function x(){if(1===_.push(this))(t.requestAnimationFrame||q)(T)}function F(){l(function(){var i;while(i=g.shift())h.call(i)})}function M(){if(1===g.push(this))(t.requestAnimationFrame||A)(F)}function useSignalEffect(i,n){var r=e(i);r.current=i;var t=d;u(function(){return a(function(){this.N=x;if(!(t&&8&t.__$f))return r.current()},n)},[])}function R(i){var n=o(function(){return i()},[]);u(function(){return n[Symbol.dispose]},[n]);return n}export{useComputed,R as useModel,useSignal,useSignalEffect};//# sourceMappingURL=signals.module.js.map\n","/**\n * Public data types of @nodejs-map/replay.\n *\n * Everything in this file is plain data: objects, arrays, strings, numbers,\n * booleans, null and typed arrays. Nothing here holds a class instance, a Map\n * or a function, so every value can be sent with postMessage (structured\n * clone) and compared in tests with deepStrictEqual.\n *\n * Absent values are `null`, never `undefined`, for the same reason.\n *\n * Words used throughout:\n * - position: a number P from 0 to the length of the event list. \"The state\n * at position P\" is the state after the first P events were applied.\n * Position 0 is before the first event. The event applied last is the one\n * at index P - 1.\n * - index: the place of one event in the list (0-based).\n * - t: microseconds on the target's clock, as in the event format.\n */\n\nimport type {\n Capabilities,\n Certainty,\n EventKind,\n EventPayloads,\n Frame,\n Loc,\n NmEvent,\n NodeInfo,\n Phase,\n PoolWorkKind,\n QueueName,\n RecordingHeader,\n} from '@nodejs-map/event-format';\n\n// ---------------------------------------------------------------------------\n// Honesty marks\n// ---------------------------------------------------------------------------\n\n/**\n * Where a fact on screen comes from: the event that said so. The UI marks\n * every drawn thing from this (observed / inferred / model) and can open the\n * rule text for `rule`.\n *\n * `rule` is a rule id of @nodejs-map/event-format (RULES) when the event\n * named one, or an id of REPLAY_RULES (they start with \"replay:\") when this\n * package worked the fact out itself. null: the event named no rule.\n */\nexport interface Fact {\n c: Certainty;\n rule: string | null;\n /** Index of the event this fact comes from. */\n index: number;\n /** Time of that event, microseconds. */\n t: number;\n}\n\n// ---------------------------------------------------------------------------\n// The view state\n// ---------------------------------------------------------------------------\n\n/**\n * - idle: no `run.start` seen yet\n * - running: the program runs\n * - paused: JavaScript is stopped at a statement (`debug.paused`)\n * - gate: the target is stopped at a gate (`gate.stopped`, probe build)\n * - ended: `run.end` seen\n */\nexport type RunStatus = 'idle' | 'running' | 'paused' | 'gate' | 'ended';\n\nexport interface RunView {\n status: RunStatus;\n node: NodeInfo | null;\n caps: Capabilities | null;\n program: string | null;\n mode: 'free' | 'debug' | null;\n poolSize: number | null;\n /** From `run.end`. */\n exitCode: number | null;\n signal: string | null;\n started: Fact | null;\n ended: Fact | null;\n}\n\n/** An async item, as far as it is needed to draw a chip for it. */\nexport interface ItemRef {\n id: number;\n /** The async_hooks type. \"?\" when no `item.new` and no `callback.start` named one. */\n type: string;\n label: string | null;\n /** The item during whose callback this one was created; 0 or 1 for the main script. */\n trigger: number;\n /** Where in the user's program it was created. */\n loc: Loc | null;\n /** The `item.new` event. null: the item was first seen in some other event (it was created before the hooks were on). */\n created: Fact | null;\n}\n\n/**\n * - created: seen, not waiting in any queue we know of, no callback yet\n * - waiting: in at least one queue\n * - running: its callback is on the main thread right now\n * - ran: at least one callback has returned and it is not waiting again\n * - gone: destroyed (`item.gone`)\n */\nexport type ItemState = 'created' | 'waiting' | 'running' | 'ran' | 'gone';\n\n/** One async item with its life up to the current position. */\nexport interface ItemView extends ItemRef {\n state: ItemState;\n /** The queues it waits in at this position (normally none or one). */\n queues: QueueName[];\n /** How many callbacks of this item have started so far. */\n runs: number;\n /** Latest `callback.start` and `callback.end` so far. */\n lastStart: Fact | null;\n lastEnd: Fact | null;\n /** `item.gone`. */\n gone: Fact | null;\n /** `promise.settled`. */\n settled: Fact | null;\n /** Timer details when a `timer.set` was seen for this item. */\n timer: TimerView | null;\n /** Name of the pool job tied to this item, when one is. */\n job: string | null;\n /** How many items seen so far name this one as their trigger. */\n children: number;\n}\n\n/**\n * How a callback got onto the main thread.\n * - phase: run by the event loop from one of its phases\n * - nextTick: run by the nextTick drain (processTicksAndRejections)\n * - microtask: run by the microtask drain\n * - unknown: the events do not say\n */\nexport type CallbackVia = 'phase' | 'nextTick' | 'microtask' | 'unknown';\n\nexport interface CallbackFrame {\n item: ItemRef;\n /** The `callback.start` event. */\n from: Fact;\n via: CallbackVia;\n /**\n * How we know `via`. When the item was waiting in a queue, this is the\n * certainty and rule of its `queue.add`. Otherwise it is worked out from\n * the item's type and marked inferred with the matching rule (K1, M1).\n * null when `via` is \"unknown\".\n */\n viaFrom: Fact | null;\n /** The queue the item left when this callback started. null: it was in none. */\n queue: QueueName | null;\n /** The loop phase at that moment, when one was known. */\n phase: Phase | null;\n phaseFrom: Fact | null;\n /** True when that phase was the second run of pending callbacks, right after poll. */\n phaseAfterPoll: boolean;\n /** 0 for a callback started from the loop or a drain; 1 and up when it started inside another callback. */\n depth: number;\n}\n\n/**\n * What the main thread is doing.\n * - main: running the main script (from `run.start` until the first\n * callback, loop event or the end; rule \"replay:main\")\n * - callback: `stack` is not empty; the last frame is the one running\n * - nothing: between callbacks, or the run has not started or has ended\n */\nexport interface MainThreadView {\n doing: 'main' | 'callback' | 'nothing';\n /** For \"main\": the `run.start` fact re-marked as inferred. For \"nothing\": the event that emptied the thread. For \"callback\": the top frame's start. */\n from: Fact | null;\n /** Outermost first. Empty unless `doing` is \"callback\". */\n stack: CallbackFrame[];\n}\n\nexport interface LoopView {\n /** From `loop.turn` (and `phase.enter` when it carries a turn). null before the first one. */\n turn: number | null;\n turnFrom: Fact | null;\n /** The phase the loop is in. null: between phases, or not known. */\n phase: Phase | null;\n phaseFrom: Fact | null;\n /**\n * True when the current phase is libuv's second run of pending callbacks,\n * right after poll (\"pending (after poll)\"; on Windows this is where\n * completed requests run).\n */\n afterPoll: boolean;\n /**\n * The latest poll timeout reported (probe build): how long the loop was\n * prepared to wait in poll. 0: no wait. -1: until something happens.\n * `current` is true while the loop is in that very poll phase.\n */\n poll: { timeoutMs: number; current: boolean; from: Fact } | null;\n /** The phase left most recently. */\n lastPhase: { phase: Phase; afterPoll: boolean; entered: Fact | null; left: Fact } | null;\n /** The latest `scope` signal (RunTimers / CheckImmediate), kept as evidence. */\n lastScope: { name: string; durUs: number; from: Fact } | null;\n /** The latest `loop.sample` signal. */\n lastSample: { loopCount: number; events: number; eventsWaiting: number; from: Fact } | null;\n}\n\nexport interface QueueEntryView {\n item: ItemRef;\n /** The `queue.add` event: since when it waits, how sure, which rule. */\n from: Fact;\n /** Atlas id of that `queue.add`, when it had one. */\n at: string | null;\n /**\n * Callbacks of this item that started while it stayed in the queue. Only\n * persistent handles in \"io\" stay (see PERSISTENT_HANDLE_TYPES); for every\n * other entry this is 0.\n */\n runs: number;\n}\n\nexport interface QueueView {\n name: QueueName;\n /** Number of entries in the queue. */\n total: number;\n /** In arrival order. At most ViewOptions.maxEntries; the oldest are kept. */\n entries: QueueEntryView[];\n truncated: boolean;\n /**\n * True once `run.end` is applied and the queue is not empty: these items\n * were left waiting when the run ended and never ran (a timer created in\n * an \"exit\" listener, for example). Their entries are unchanged.\n */\n leftAtEnd: boolean;\n}\n\n/**\n * - waiting: armed, its callback has not started\n * - running: its callback is on the main thread\n * - done: its callback returned and it was not armed again\n * - cleared: cancelled or destroyed before running (again)\n */\nexport type TimerState = 'waiting' | 'running' | 'done' | 'cleared';\n\nexport interface TimerView {\n item: ItemRef;\n delayMs: number;\n repeat: boolean;\n /** The `timer.set` event. */\n set: Fact;\n /** The event that armed it most recently: `timer.set`, or the `queue.add` that put a repeating timer back. */\n armed: Fact;\n /**\n * When it is due: time of `armed` plus the delay, in microseconds. This is\n * our arithmetic, not a report from Node (rule \"replay:due\").\n */\n dueT: number;\n dueFrom: Fact;\n state: TimerState;\n /** Callbacks started so far. */\n runs: number;\n /** Latest callback start. */\n lastRun: Fact | null;\n /** How late the latest callback started against `dueT` at that time, in milliseconds (rule \"replay:due\"). */\n lateMs: number | null;\n /** The event that cleared it. */\n cleared: Fact | null;\n}\n\nexport interface TimersView {\n /** Waiting and running timers, soonest due first. At most ViewOptions.maxEntries. */\n active: TimerView[];\n /** Done and cleared timers, oldest first, the most recent ones only. */\n recent: TimerView[];\n counts: { set: number; waiting: number; running: number; done: number; cleared: number };\n /** Loop-level `timer.fired` events: how many, and the latest. */\n fired: { count: number; last: { lateMs: number | null; from: Fact } | null };\n truncated: boolean;\n /** True once `run.end` is applied and timers are still waiting: they were left waiting when the run ended. */\n leftAtEnd: boolean;\n}\n\n/**\n * The life of a pool job: queued -> started -> finished -> posted -> delivered.\n * - waiting: queued, no thread has picked it up\n * - running: a thread runs its work function\n * - finished: the work function returned. On the probe build the thread\n * still holds the job until it has posted the result; on an\n * official build nothing more is reported and the job is shown\n * on its way to the loop.\n * - posted: the result is on the loop's done list (probe build only)\n * A delivered or cancelled job is no longer shown.\n */\nexport type PoolJobState = 'waiting' | 'running' | 'finished' | 'posted';\n\n/** The gates a target can be stopped at (see `gate.stopped` in the event format). */\nexport type GateName = EventPayloads['gate.stopped']['gate'];\n\nexport interface PoolJobView {\n job: string;\n kind: PoolWorkKind;\n op: string | null;\n state: PoolJobState;\n /** The async item it belongs to, when `pool.queued` or `pool.link` said so. */\n item: ItemRef | null;\n /** The event that tied the job to the item. */\n itemFrom: Fact | null;\n /** Display index of the thread that runs or ran it. */\n thread: number | null;\n queued: Fact | null;\n started: Fact | null;\n finished: Fact | null;\n /** `pool.posted` (probe build). */\n posted: Fact | null;\n /** Atlas id of the latest pool event of this job. */\n at: string | null;\n /** The gate that holds this job right now (poolStart, poolPost or poolDone), or null. See PoolView.held. */\n held: GateName | null;\n}\n\nexport interface PoolThreadView {\n /** Display index, 1-based. */\n thread: number;\n /**\n * The job this thread holds: one it runs (state \"running\") or, on the\n * probe build, one whose work has returned and whose result it has not\n * posted yet (state \"finished\").\n */\n job: PoolJobView | null;\n /** The real thread id, when the `pool.started` event carried one. */\n tid: number | null;\n /** Jobs this thread has started so far. */\n jobs: number;\n /** True when the index is above the pool size of `run.start`: the events showed a thread we did not expect. */\n extra: boolean;\n}\n\n/** What one real thread id did, from `pool.thread` signals. Evidence, not a job assignment. */\nexport interface PoolTidView {\n tid: number;\n busy: boolean;\n /** Name of the job kind it started most recently. */\n name: string;\n /** The latest signal of this thread. */\n from: Fact;\n starts: number;\n ends: number;\n}\n\nexport interface PoolView {\n /**\n * The number of pool threads in effect at this position: the size from\n * the latest `pool.size` event, or UV_THREADPOOL_SIZE as `run.start`\n * reported it (which stays in RunView.poolSize). A program can set the\n * variable itself before it first uses the pool; libuv reads it only then.\n * The thread lanes follow this number: lanes above it that are idle and\n * never ran a job are removed, missing ones are added.\n */\n size: number | null;\n /** The event the size comes from: `pool.size`, or `run.start`. */\n sizeFrom: Fact | null;\n threads: PoolThreadView[];\n /** Jobs queued and not yet picked up, oldest first. */\n waiting: PoolJobView[];\n /**\n * Jobs whose work is over and whose done-callback has not run, oldest\n * first.\n *\n * Probe build: the jobs on the loop's done list, from `pool.posted` (state\n * \"posted\") until `pool.delivered`.\n *\n * Official build: neither event exists. A job is listed from\n * `pool.finished` (state \"finished\") until the callback of its item starts\n * or the item goes away (rule \"replay:delivered\"). A job that was never\n * tied to an item cannot leave that way: such jobs are kept, oldest\n * dropped first, up to UNLINKED_DONE_LIMIT.\n */\n done: PoolJobView[];\n /**\n * The job a gate holds right now, when the target is stopped at a pool\n * gate that names one.\n * - poolStart: a pool thread holds a job it has not started (where \"thread\")\n * - poolPost: a pool thread holds a finished job it has not posted (where \"thread\")\n * - poolDone: the loop holds a result before its done-callback (where \"loop\")\n * `thread` is the display index of the holding thread when the events tell\n * it: the thread the job is shown on, or the thread whose real id is the\n * gate event's `tid`. `view` is null when the job is not on screen.\n */\n held: { gate: GateName; job: string; where: 'thread' | 'loop'; thread: number | null; view: PoolJobView | null; from: Fact } | null;\n tids: PoolTidView[];\n counts: { queued: number; started: number; finished: number; posted: number; delivered: number; cancelled: number; droppedUnlinked: number };\n truncated: boolean;\n /** True once `run.end` is applied and jobs are still waiting, on a thread or in the done list: the run ended with them unfinished or undelivered. */\n leftAtEnd: boolean;\n}\n\nexport interface OutputChunk {\n /** Ordinal of this chunk in the run, from 0. Stable: use it as a list key. */\n seq: number;\n index: number;\n t: number;\n stream: 'stdout' | 'stderr';\n text: string;\n /** The line of the user's program that made the write, when the event told it. Absent otherwise. */\n loc?: Loc;\n}\n\nexport interface OutputView {\n /** Chunks written up to this position. */\n total: number;\n /** Characters written up to this position. */\n chars: number;\n /**\n * The latest chunks, at most ViewOptions.maxOutput. Older ones are read\n * with Replay.output(fromSeq, toSeq). The chunk objects are the same\n * objects from one view to the next; nothing is copied per step.\n */\n chunks: OutputChunk[];\n}\n\nexport interface DebugView {\n paused: boolean;\n reason: 'breakpoint' | 'step' | 'pause' | 'exception' | 'entry' | 'other' | null;\n /** Top frame first. Empty when not paused. */\n frames: Frame[];\n /** True on an official build: real time kept running while paused, and the UI must say so. */\n timeKeptRunning: boolean;\n /** The `debug.paused` event. */\n from: Fact | null;\n /** The latest pause that is over. */\n lastPause: { pausedMs: number; timeKeptRunning: boolean; paused: Fact | null; resumed: Fact } | null;\n /** Pauses so far, including a current one. */\n pauses: number;\n gate: {\n stopped: boolean;\n gate: GateName | null;\n phase: Phase | null;\n job: string | null;\n from: Fact | null;\n /** From the latest `gate.released`. */\n lastStoppedMs: number | null;\n stops: number;\n };\n clock: {\n frozen: boolean;\n /** What froze it, when the event said: a gate or a JavaScript breakpoint. */\n why: 'gate' | 'breakpoint' | null;\n from: Fact | null;\n /** From the latest `clock.unfrozen`. */\n lastHiddenMs: number | null;\n /** Sum of `hiddenMs` so far. */\n hiddenMs: number;\n };\n}\n\nexport interface NoteView {\n seq: number;\n level: 'info' | 'warn';\n text: string;\n from: Fact;\n}\n\nexport interface NotesView {\n total: number;\n /** The latest notes, oldest first, at most ViewOptions.maxNotes. */\n items: NoteView[];\n}\n\n/** A place on the map where work is waiting. */\n/** The line of code the replay is at. */\nexport interface SourceSpot {\n /** Where: the script URL as the events report it (a user file or snippet name, or \"node:...\") and the 1-based line. */\n loc: Loc;\n /**\n * Why this line:\n * - 'paused': the debugger is stopped on this line (the top frame of debug.paused) - exact;\n * - 'output': this line wrote the latest output;\n * - 'created': this line created the latest async item (the setTimeout(...), .then(...), fs.readFile(...) call);\n * - 'callback': a callback is running and nothing in it has been located yet; the line is where that callback's item was created, NOT the line executing now.\n */\n why: 'paused' | 'output' | 'created' | 'callback';\n /** The item concerned, for 'created' and 'callback'; null otherwise. */\n item: number | null;\n /**\n * The event that says so: the one that carries `loc`. For 'paused' the\n * `debug.paused`, for 'output' the `output`, for 'created' and 'callback'\n * the `item.new` of the item.\n */\n from: Fact;\n}\n\n/**\n * A place on the map with work at it, and exactly how much of which kind.\n *\n * Every thing is counted once, at one place, in one of the four numbers:\n *\n * - A queue entry counts as `waiting` at the atlas id of its `queue.add`.\n * - A pool job counts at the atlas id of its latest pool event, by its\n * state: `poolWaiting` (queued, no thread yet), `poolRunning` (a thread\n * runs it), `poolDone` (finished or posted, not yet delivered).\n * - A request in the \"pool\" queue whose job is known (tied to it by\n * `pool.queued` or `pool.link`) is the same piece of work as that job. It\n * is represented by the job only and its queue entry is not counted. An\n * entry of the \"pool\" queue is counted on its own (as `waiting`) only when\n * no job is known for it.\n *\n * So with six pbkdf2 requests, four of them on threads: the submit place\n * has poolWaiting 2 and nothing else, the worker place has poolRunning 4.\n */\nexport interface WaitingPlace {\n /** Atlas id. */\n at: string;\n /** The total: waiting + poolWaiting + poolRunning + poolDone. */\n count: number;\n /** The weakest certainty among the events these things come from (model < inferred < observed). */\n c: Certainty;\n /** Queue entries waiting here. */\n waiting: number;\n /** Pool jobs here that wait for a thread. */\n poolWaiting: number;\n /** Pool jobs here that a thread is running. */\n poolRunning: number;\n /** Pool jobs here whose work has finished (or whose result is posted) and has not been delivered. */\n poolDone: number;\n /** The queues the `waiting` entries are in. */\n queues: QueueName[];\n /** True when any of the three pool numbers is not zero. */\n pool: boolean;\n}\n\nexport interface FocusView {\n /** Atlas id where the action is: the `at` of the latest event that has one. */\n at: string | null;\n from: Fact | null;\n kind: EventKind | null;\n /** Atlas ids with work at them: queue entries waiting, pool jobs waiting, running or done. Sorted by id. See WaitingPlace for how things are counted. */\n waiting: WaitingPlace[];\n}\n\nexport interface LogEntry {\n index: number;\n event: NmEvent;\n /** True when the reducer skipped this event (unknown kind or malformed). */\n skipped: boolean;\n}\n\nexport interface ProblemCounts {\n /** Events with a kind this version does not know. */\n unknown: number;\n /** Events that are not an object, have no usable time, or lack a field their kind needs. */\n malformed: number;\n /**\n * Events that disagree with earlier ones (a callback end with no start, a\n * thread starting a job while it runs another, ...). They are applied in\n * the way that keeps the view consistent with the latest event.\n */\n inconsistent: number;\n}\n\n/** The complete state the screen draws at one position. */\nexport interface ViewState {\n /** Events applied: the state is \"after the first `position` events\". */\n position: number;\n /** Events in the store. */\n length: number;\n /** Events the reducer has prepared. Smaller than `length` only while a large batch is being indexed (see Replay.pump). */\n ready: number;\n /** True while the run has not ended. */\n live: boolean;\n /** Bumped every time the event list changes. */\n version: number;\n /** Time of the latest applied event, microseconds; never goes down as the position goes up. */\n t: number;\n /** Time of the last event in the store. */\n endT: number;\n\n run: RunView;\n main: MainThreadView;\n loop: LoopView;\n queues: Record<QueueName, QueueView>;\n /** Counts of async items up to this position. The items themselves: `referenced` below, or Replay.item / Replay.items / Replay.why. */\n items: {\n total: number;\n /** Present only with ViewOptions.items = \"all\": every item so far, in creation order. */\n all: ItemView[] | null;\n };\n timers: TimersView;\n pool: PoolView;\n output: OutputView;\n debug: DebugView;\n notes: NotesView;\n focus: FocusView;\n /**\n * The line of code to highlight, or null.\n *\n * While the debugger is paused: the top frame's location, whatever its\n * origin. Otherwise, while JavaScript is running (the main script or a\n * callback): the latest located event of the stretch of JavaScript that is\n * running now - an output with a location, the creation of an item with a\n * location - and, in a callback where nothing has been located yet, the\n * line that created the callback's item. When an inner callback ends, the\n * spot of the outer one comes back. null when no JavaScript is running\n * (between callbacks, before the start, after the end): the highlight\n * goes away rather than sticking to a stale line.\n */\n source: SourceSpot | null;\n /** The latest events, oldest first, at most ViewOptions.maxLog. */\n log: LogEntry[];\n problems: ProblemCounts;\n}\n\nexport interface ViewOptions {\n /** Cap for each queue, the active timers and each pool list. Default 200. */\n maxEntries?: number;\n /** Cap for output chunks in the view. Default 200. */\n maxOutput?: number;\n /** Cap for notes in the view. Default 50. */\n maxNotes?: number;\n /** Cap for the log. Default 50. */\n maxLog?: number;\n /** \"all\" adds every item seen so far to `items.all`. Meant for small runs and tests. Default \"none\". */\n items?: 'none' | 'all';\n}\n\n// ---------------------------------------------------------------------------\n// View patches\n// ---------------------------------------------------------------------------\n\n/**\n * How an ordered list changed. The new list is: `prepend`, then the entries\n * of the old list whose number (chunk seq, event index) is in [from, to),\n * then `append`.\n */\nexport interface ListPatch<T> {\n from: number;\n to: number;\n prepend: T[];\n append: T[];\n}\n\n/**\n * The difference between two views (see diffView and applyViewPatch). A\n * patch applies to the view made by the patch before it; a `full` patch\n * applies to nothing and carries everything.\n */\nexport interface ViewPatch {\n full: boolean;\n /** Parts of the view that changed, each one whole. */\n set: Partial<Pick<ViewState, 'position' | 'length' | 'ready' | 'live' | 'version' | 't' | 'endT' | 'run' | 'main' | 'loop' | 'items' | 'timers' | 'pool' | 'debug' | 'notes' | 'focus' | 'source' | 'problems'>>;\n /** The queues that changed, each one whole. */\n queues: Partial<Record<QueueName, QueueView>>;\n /** null: the output part is unchanged. */\n output: ({ total: number; chars: number } & ListPatch<OutputChunk>) | null;\n /** null: the log is unchanged. */\n log: ListPatch<LogEntry> | null;\n}\n\n// ---------------------------------------------------------------------------\n// Event store\n// ---------------------------------------------------------------------------\n\n/** The `events` message of the helper protocol, without the envelope. */\nexport interface EventBatch {\n /** The first `base` events stay as they are. */\n base: number;\n /** They are followed by these. */\n events: readonly NmEvent[];\n}\n\nexport type StoreStatus = 'empty' | 'live' | 'ended';\n\nexport interface StoreChange {\n /**\n * The lowest index whose event changed, was added or was removed. State at\n * positions up to and including `from` is unaffected; everything after it\n * must be recomputed.\n */\n from: number;\n /** Length before and after. */\n previousLength: number;\n length: number;\n /** True when events that were in the list were replaced or removed (a late tail). */\n truncated: boolean;\n /** True when the whole run was replaced: reset() or load(). Views go back to position 0. */\n replaced: boolean;\n status: StoreStatus;\n version: number;\n /**\n * Set when the batch was not applied: its `base` was beyond the end of the\n * list (events are missing in between) or not a whole number from 0 up.\n */\n rejected: 'gap' | 'bad-base' | null;\n}\n\n// ---------------------------------------------------------------------------\n// Stepping\n// ---------------------------------------------------------------------------\n\n/**\n * What a step stops at. A step moves to the position just after the next\n * (or previous) event of the kind.\n * - event: any event\n * - step: a \"meaningful\" event: anything except the pure signals listed in SIGNAL_KINDS\n * - callback: `callback.start`\n * - phase: `phase.enter`\n * - turn: `loop.turn`\n * - output: `output`\n * - pause: `debug.paused` or `gate.stopped`\n */\nexport type StepKind = 'event' | 'step' | 'callback' | 'phase' | 'turn' | 'output' | 'pause';\n\n// ---------------------------------------------------------------------------\n// Player\n// ---------------------------------------------------------------------------\n\n/**\n * How playback time is spent.\n * - steps: every meaningful step takes the same time (stepsPerSecond at 1x);\n * pure signals ride along with the next step. The default.\n * - time: program time, slowed down (timeScale at 1x).\n * - tick: exactly one event per tick() call, whatever the clock says.\n */\nexport type Pace = 'steps' | 'time' | 'tick';\n\nexport interface PlayerOptions {\n /** 0.05 to 20. Default 1. */\n speed?: number;\n pace?: Pace;\n /** \"steps\" pace: meaningful steps per second at 1x. Default DEFAULT_STEPS_PER_SECOND. */\n stepsPerSecond?: number;\n /** \"time\" pace: seconds of program time per second of playback at 1x. Default DEFAULT_TIME_SCALE. */\n timeScale?: number;\n /** A gap between two events longer than this (microseconds of program time) is dead time. Default DEFAULT_DEAD_TIME_US. 0 turns compression off. */\n deadTimeUs?: number;\n /** How long a dead gap plays at 1x, in milliseconds. Default DEFAULT_DEAD_TIME_PAUSE_MS. */\n deadTimePauseMs?: number;\n /** Stick to the tail while the run is live. Default true. */\n follow?: boolean;\n /** The most clock time one tick may account for, in milliseconds (a tab that was in the background does not leap). Default 250. */\n maxTickMs?: number;\n}\n\n/** Reported while the player sits in a compressed gap. */\nexport interface DeadTime {\n /** Length of the gap in milliseconds of program time: \"nothing happened for N ms\". */\n ms: number;\n /** The gap lies between the events at these two indexes. */\n afterIndex: number;\n beforeIndex: number;\n /**\n * What the main thread was doing during the gap, so the UI can word it\n * honestly: \"nothing\" (the loop was waiting), \"callback\" or \"main\"\n * (JavaScript was running and no event was sent).\n */\n during: 'nothing' | 'callback' | 'main';\n /** 0 to 1: how much of the short pause has played. */\n progress: number;\n}\n\nexport interface PlayerState {\n playing: boolean;\n speed: number;\n pace: Pace;\n /** The follow switch. */\n follow: boolean;\n /** True when the position is being held at the tail of a live run. */\n following: boolean;\n position: number;\n /** Events the player can reach (Replay.ready). */\n length: number;\n live: boolean;\n /** At the last event of a run that has ended. */\n atEnd: boolean;\n /** Playing, at the tail of a live run, waiting for more events. */\n waiting: boolean;\n deadTime: DeadTime | null;\n /** Time at the position, microseconds. */\n t: number;\n}\n\nexport type PlayerCommand =\n | { do: 'play' }\n | { do: 'pause' }\n | { do: 'toggle' }\n | { do: 'speed'; speed: number }\n | { do: 'pace'; pace: Pace }\n | { do: 'follow'; on: boolean }\n | { do: 'seek'; position: number }\n | { do: 'seekTime'; t: number }\n | { do: 'step'; kind: StepKind; direction: 1 | -1 }\n | { do: 'options'; options: PlayerOptions };\n\nexport interface PlayerTick {\n /** True when the position changed during this tick. */\n moved: boolean;\n /** True when anything in PlayerState changed during this tick. */\n changed: boolean;\n state: PlayerState;\n}\n\n// ---------------------------------------------------------------------------\n// Timeline\n// ---------------------------------------------------------------------------\n\n/**\n * What a timeline bucket counts. One count per class per bucket.\n * \"cb.*\" are callback starts by the queue the item came from; \"cb.other\" is\n * a callback of an item that was in no queue.\n */\nexport const TIMELINE_CLASSES = [\n 'cb.nextTick',\n 'cb.microtask',\n 'cb.timers',\n 'cb.immediate',\n 'cb.pool',\n 'cb.io',\n 'cb.close',\n 'cb.other',\n 'stdout',\n 'stderr',\n 'pause',\n 'pool',\n 'note',\n] as const;\nexport type TimelineClass = (typeof TIMELINE_CLASSES)[number];\n\n/** Codes used in TimelineSummary.phase: index into this list. 0 means no phase known. */\nexport const PHASE_CODES: readonly (Phase | null)[] = [null, 'timers', 'pending', 'idle', 'prepare', 'poll', 'check', 'closing'];\n\n/** Codes used in TimelineSummary.phaseCertainty: index into this list. */\nexport const CERTAINTY_CODES: readonly (Certainty | null)[] = [null, 'observed', 'inferred', 'model'];\n\nexport type TimelineAxis = 'index' | 'time';\n\n/**\n * The run cut into `width` buckets, for the scrubber. Columns are typed\n * arrays so the summary is cheap to build, to post and to draw.\n */\nexport interface TimelineSummary {\n axis: TimelineAxis;\n width: number;\n /** Store version this was built from. */\n version: number;\n /** Events covered. */\n length: number;\n /** Domain of the axis: event indexes for \"index\", microseconds for \"time\". Bucket b covers from + b*(to-from)/width. */\n from: number;\n to: number;\n /** Per bucket: index of the first event in it. For an empty bucket (time axis): index of the next event after it. Length `width`. */\n start: Uint32Array;\n /** Per bucket: number of events. Length `width`. */\n events: Uint32Array;\n /** Per bucket: the phase most of the bucket was in, as a PHASE_CODES index. */\n phase: Uint8Array;\n /** Per bucket: weakest certainty of the phase information in it, as a CERTAINTY_CODES index. */\n phaseCertainty: Uint8Array;\n /** Per bucket: 1 when the program was paused or stopped at a gate in it. */\n paused: Uint8Array;\n /** Per bucket: 1 when a callback was running in it. */\n busy: Uint8Array;\n /** Per bucket and class: counts, laid out as counts[bucket * TIMELINE_CLASSES.length + classIndex]. */\n counts: Uint32Array;\n}\n\nexport interface PauseMarker {\n kind: 'debug' | 'gate';\n /** Index and time of `debug.paused` / `gate.stopped`. */\n index: number;\n t: number;\n /** Index of the matching `debug.resumed` / `gate.released`. null while still paused. */\n endIndex: number | null;\n /** From the resume event. */\n ms: number | null;\n reason: string;\n timeKeptRunning: boolean;\n}\n\nexport interface NoteMarker {\n index: number;\n t: number;\n level: 'info' | 'warn';\n text: string;\n}\n\nexport interface TimelineMarkers {\n version: number;\n pauses: PauseMarker[];\n notes: NoteMarker[];\n /** Event indexes of `loop.turn`, ascending, and the turn number of each. */\n turnIndex: Uint32Array;\n turnNumber: Uint32Array;\n /** Event indexes of `output`, ascending, and the stream of each (0 stdout, 1 stderr). */\n outputIndex: Uint32Array;\n outputStream: Uint8Array;\n}\n\n// ---------------------------------------------------------------------------\n// Recordings and share links\n// ---------------------------------------------------------------------------\n\nexport interface OpenOptions {\n /** Refuse input that unpacks to more than this many bytes. Default MAX_RECORDING_BYTES. */\n maxBytes?: number;\n}\n\nexport interface SaveOptions {\n /** true: gzip-compressed bytes. false: the UTF-8 text. Default false. */\n gzip?: boolean;\n}\n\nexport type ShareResult =\n | {\n ok: true;\n /** Goes after the \"#\" of the player URL. Starts with FRAGMENT_PREFIX. */\n fragment: string;\n /** Length of `fragment` in characters. */\n length: number;\n /** True when it is at most SHARE_LINK_SAFE_CHARS: it also fits places with tight message limits. */\n fitsEverywhere: boolean;\n }\n | {\n ok: false;\n reason: 'too-big';\n /** The length the fragment would have had, and the limit it exceeds. */\n length: number;\n limit: number;\n /** \"Too big to share as a link, share the file instead\", with the numbers. */\n message: string;\n };\n\nexport interface ShareOptions {\n /** Default SHARE_LINK_MAX_CHARS. */\n maxChars?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Worker protocol\n// ---------------------------------------------------------------------------\n\n/** Questions the UI can ask about the run. Answers are about the current position unless a position is given. */\nexport type ReplayQuery =\n /** One item with its life. */\n | { what: 'item'; id: number }\n /** \"Why did this run?\": the item, then the item that scheduled it, and so on up to the main script. */\n | { what: 'why'; id: number }\n /** Items in creation order. */\n | { what: 'items'; from: number; limit: number }\n /** Output chunks by seq, `from` included, `to` excluded. */\n | { what: 'output'; from: number; to: number }\n /** Events by index, `from` included, `to` excluded (at most 1,000 per call). */\n | { what: 'events'; from: number; to: number }\n /** The view at another position, without moving the player. */\n | { what: 'viewAt'; position: number };\n\nexport type ReplayAnswer =\n | { what: 'item'; item: ItemView | null }\n | { what: 'why'; chain: ItemView[] }\n | { what: 'items'; items: ItemView[]; total: number }\n | { what: 'output'; chunks: OutputChunk[] }\n | { what: 'events'; entries: LogEntry[] }\n | { what: 'viewAt'; view: ViewState };\n\n/** UI -> worker (or -> ReplayHost on the main thread). */\nexport type HostRequest =\n /** Forget the run and start empty. */\n | { op: 'reset' }\n /** A batch from the helper's `events` message. */\n | { op: 'events'; base: number; events: NmEvent[] }\n /** The helper's `run.ended`: the list is final. */\n | { op: 'ended' }\n /** Open a recording (text, or bytes that are text or gzip). Replaces the run. Nothing is executed. */\n | { op: 'open'; id: number; data: string | ArrayBuffer | Uint8Array }\n /** Open a share link fragment. Replaces the run. Nothing is executed. */\n | { op: 'openFragment'; id: number; fragment: string }\n /** Encode the run held by the host as a recording file. */\n | { op: 'save'; id: number; header: RecordingHeader; gzip: boolean }\n /** Encode the run held by the host as a share link fragment. */\n | { op: 'share'; id: number; header: RecordingHeader }\n | { op: 'player'; cmd: PlayerCommand }\n /**\n * The UI's clock, normally sent once per animation frame. The host answers\n * each tick with at most one `view` (only when something changed). Without\n * ticks the host runs on its own timer (see `configure.clock`).\n */\n | { op: 'tick'; now: number }\n | {\n op: 'configure';\n /** Merged into the options of posted views. The host starts with maxEntries 60, maxOutput 50, maxLog 30 (smaller than Replay.view: a posted view is copied). */\n view?: ViewOptions;\n /**\n * \"full\" (default): every post is a whole view (`view` messages).\n * \"patch\": posts are `patch` messages carrying only what changed since\n * the post before; rebuild the view with applyViewPatch. Sending this\n * again makes the next patch a full one (use it to resynchronise).\n */\n views?: 'full' | 'patch';\n /** \"external\": the UI sends `tick`. \"internal\": the host ticks itself about 60 times a second. Default \"internal\". */\n clock?: 'external' | 'internal';\n /** Ask for timeline summaries at this width; null stops them. They are re-sent when the run changes. */\n timeline?: { width: number; axis: TimelineAxis } | null;\n /** Ask for marker lists; re-sent when the run changes. */\n markers?: boolean;\n }\n | { op: 'query'; id: number; q: ReplayQuery };\n\n/** worker (or ReplayHost) -> UI. */\nexport type HostMessage =\n | { op: 'ready' }\n | { op: 'view'; view: ViewState; player: PlayerState }\n /** Instead of `view` when `configure.views` is \"patch\". */\n | { op: 'patch'; patch: ViewPatch; player: PlayerState }\n | { op: 'timeline'; summary: TimelineSummary }\n | { op: 'markers'; markers: TimelineMarkers }\n | { op: 'answer'; re: number; answer: ReplayAnswer }\n | { op: 'opened'; re: number; header: RecordingHeader; events: number }\n | { op: 'saved'; re: number; bytes: Uint8Array }\n | { op: 'shared'; re: number; result: ShareResult }\n | { op: 'error'; re: number | null; message: string };\n","/**\n * The run index: everything about a run that does not depend on the position\n * being shown.\n *\n * The view state has two kinds of content. Some of it is small and changes\n * with every step (what runs now, who waits where); that is the \"live\" state\n * of reducer.ts, and keyframes hold copies of it. The rest only ever grows\n * with the run (every item ever seen, all output, all notes, the per-event\n * columns the scrubber draws). Copying that into keyframes would cost memory\n * proportional to events x items, so it is kept here once, with the index of\n * the event that produced each piece. \"The items at position P\" is then\n * \"the items whose event index is below P\": a filter, not a copy.\n *\n * The index is built in event order (add) and can be cut back (truncate)\n * when a late tail replaces the end of the list.\n *\n * Internal: not part of the public API.\n */\n\nimport type { Certainty, EventKind, NmEvent, Phase, QueueName } from '@nodejs-map/event-format';\nimport type { Fact, ItemRef, OutputChunk, PauseMarker } from './types.ts';\n\n// ---- per-event flags --------------------------------------------------------\n\nexport const F_STEP = 1; // a \"meaningful\" step stops here\nexport const F_CALLBACK = 2; // callback.start\nexport const F_PHASE = 4; // phase.enter\nexport const F_TURN = 8; // loop.turn\nexport const F_OUTPUT = 16; // output\nexport const F_PAUSE = 32; // debug.paused or gate.stopped\nexport const F_SKIP = 64; // the reducer skips this event\nexport const F_UNKNOWN = 128; // with F_SKIP: unknown kind (otherwise malformed)\n\nexport const QUEUE_NAMES: readonly QueueName[] = ['nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close'];\n// Lookup tables have no prototype: a name such as \"constructor\" in a bad event must not find anything.\nconst table = (entries: Record<string, number>): Record<string, number> => Object.assign(Object.create(null) as Record<string, number>, entries);\nconst QUEUE_CODE = table({ nextTick: 0, microtask: 1, timers: 2, immediate: 3, pool: 4, io: 5, close: 6 });\nexport const PHASES: readonly (Phase | null)[] = [null, 'timers', 'pending', 'idle', 'prepare', 'poll', 'check', 'closing'];\nconst PHASE_CODE = table({ timers: 1, pending: 2, idle: 3, prepare: 4, poll: 5, check: 6, closing: 7 });\n\nexport function queueCode(name: unknown): number {\n const code = typeof name === 'string' ? QUEUE_CODE[name] : undefined;\n return code === undefined ? -1 : code;\n}\n\nexport function phaseCode(name: unknown): number {\n const code = typeof name === 'string' ? PHASE_CODE[name] : undefined;\n return code === undefined ? 0 : code;\n}\n\n/**\n * Event kinds that are pure signals. A \"meaningful\" step never stops on\n * them: they are evidence, or bookkeeping that another event of the same\n * moment already shows (`item.new` and `timer.set` are followed by the\n * `queue.add` that puts the item on screen; `item.gone` of a waiting item\n * comes with its `queue.remove`).\n */\nexport const SIGNAL_KINDS: ReadonlySet<EventKind> = new Set<EventKind>([\n 'loop.sample',\n 'signal',\n 'scope',\n 'pool.thread',\n 'promise.settled',\n 'item.new',\n 'item.gone',\n 'timer.set',\n 'pool.link',\n 'clock.frozen',\n 'clock.unfrozen',\n]);\n\n/** libuv's MAX_THREADPOOL_SIZE; a thread index above it is not believable. */\nconst MAX_THREAD_INDEX = 1024;\n\nconst isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\nconst isId = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0;\nconst isStr = (v: unknown): v is string => typeof v === 'string';\nconst isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null;\n/** A source location as the views use it: a url and a line (a column, when there is one, must be a number). */\nexport const isLoc = (v: unknown): boolean => isObj(v) && isStr(v['url']) && isNum(v['line']) && (v['col'] === undefined || isNum(v['col']));\nconst isLocOrAbsent = (v: unknown): boolean => v === undefined || isLoc(v);\n\n/**\n * Is this event usable? 0: yes. 1: unknown kind. 2: malformed.\n *\n * Only what the reducer reads is checked. Recording files are validated in\n * full by the event-format codec; live events come from our own helper. This\n * check exists so that a bad event can never crash the view or be drawn with\n * a certainty it does not have.\n */\nexport function checkEvent(value: unknown): 0 | 1 | 2 {\n if (!isObj(value)) return 2;\n const e = value;\n if (!isStr(e['k']) || !isNum(e['t'])) return 2;\n const c = e['c'];\n if (c !== 'observed' && c !== 'inferred' && c !== 'model') return 2;\n if (e['rule'] !== undefined && !isStr(e['rule'])) return 2;\n if (e['at'] !== undefined && !isStr(e['at'])) return 2;\n if (e['tid'] !== undefined && !isNum(e['tid'])) return 2;\n switch (e['k']) {\n case 'run.start':\n return isObj(e['node']) && isObj(e['caps']) && isStr(e['mode']) && isStr(e['program']) && isNum(e['poolSize']) ? 0 : 2;\n case 'run.end':\n return (e['code'] === null || e['code'] === undefined || isNum(e['code'])) && (e['signal'] === null || e['signal'] === undefined || isStr(e['signal'])) ? 0 : 2;\n case 'output':\n return (e['stream'] === 'stdout' || e['stream'] === 'stderr') && isStr(e['text']) && isLocOrAbsent(e['loc']) ? 0 : 2;\n case 'item.new':\n return isId(e['id']) && isStr(e['type']) && isId(e['trigger']) && (e['label'] === undefined || isStr(e['label'])) && isLocOrAbsent(e['loc']) ? 0 : 2;\n case 'callback.start':\n return isId(e['id']) && isStr(e['type']) ? 0 : 2;\n case 'callback.end':\n case 'item.gone':\n case 'promise.settled':\n return isId(e['id']) ? 0 : 2;\n case 'timer.set':\n return isId(e['id']) && isNum(e['delayMs']) && typeof e['repeat'] === 'boolean' ? 0 : 2;\n case 'loop.sample':\n return isNum(e['loopCount']) && isNum(e['events']) && isNum(e['eventsWaiting']) ? 0 : 2;\n case 'scope':\n return isStr(e['name']) && isNum(e['durUs']) ? 0 : 2;\n case 'pool.thread':\n return (e['edge'] === 'start' || e['edge'] === 'end') && isStr(e['name']) ? 0 : 2;\n case 'signal':\n return isStr(e['cat']) && isStr(e['name']) && isStr(e['ph']) ? 0 : 2;\n case 'queue.add':\n case 'queue.remove':\n return queueCode(e['queue']) >= 0 && isId(e['id']) ? 0 : 2;\n case 'loop.turn':\n return isNum(e['n']) ? 0 : 2;\n case 'phase.enter':\n case 'phase.leave':\n return phaseCode(e['phase']) > 0 &&\n (e['turn'] === undefined || isNum(e['turn'])) &&\n (e['afterPoll'] === undefined || typeof e['afterPoll'] === 'boolean') &&\n (e['pollTimeoutMs'] === undefined || isNum(e['pollTimeoutMs']))\n ? 0\n : 2;\n case 'timer.fired':\n return e['lateMs'] === undefined || isNum(e['lateMs']) ? 0 : 2;\n case 'pool.queued':\n return isStr(e['job']) && isStr(e['kind']) && (e['op'] === undefined || isStr(e['op'])) && (e['id'] === undefined || isId(e['id'])) ? 0 : 2;\n case 'pool.delivered':\n case 'pool.cancelled':\n return isStr(e['job']) ? 0 : 2;\n case 'pool.started':\n case 'pool.finished':\n case 'pool.posted':\n return isStr(e['job']) && isId(e['thread']) && (e['thread'] as number) >= 1 && (e['thread'] as number) <= MAX_THREAD_INDEX ? 0 : 2;\n case 'pool.link':\n return isStr(e['job']) && isId(e['id']) ? 0 : 2;\n case 'pool.size':\n return isId(e['size']) && (e['size'] as number) >= 1 && (e['size'] as number) <= MAX_THREAD_INDEX ? 0 : 2;\n case 'debug.paused':\n return isStr(e['reason']) && Array.isArray(e['frames']) && typeof e['timeKeptRunning'] === 'boolean' ? 0 : 2;\n case 'debug.resumed':\n return isNum(e['pausedMs']) ? 0 : 2;\n case 'gate.stopped':\n return isStr(e['gate']) && (e['job'] === undefined || isStr(e['job'])) && (e['phase'] === undefined || phaseCode(e['phase']) > 0) ? 0 : 2;\n case 'gate.released':\n return isNum(e['stoppedMs']) ? 0 : 2;\n case 'clock.frozen':\n return e['why'] === undefined || isStr(e['why']) ? 0 : 2;\n case 'clock.unfrozen':\n return isNum(e['hiddenMs']) ? 0 : 2;\n case 'note':\n return (e['level'] === 'info' || e['level'] === 'warn') && isStr(e['text']) ? 0 : 2;\n default:\n return 1;\n }\n}\n\n// ---- records ------------------------------------------------------------------\n\nexport interface TimerRec {\n /** Index of `timer.set`. */\n setIndex: number;\n delayMs: number;\n repeat: boolean;\n /** Indexes of the events that armed it: `timer.set`, then each `queue.add` that put it back after a run. Ascending. */\n arms: number[];\n /** Index of the event that cleared it, or -1. */\n clearedIndex: number;\n}\n\nexport interface ItemRec {\n id: number;\n /** The item as `item.new` described it; before that event, as far as other events showed it. */\n ref: ItemRef;\n /** When the item was seen before its `item.new`: what was known until then. */\n early: ItemRef | null;\n /** Index of `item.new`, or -1. */\n newIndex: number;\n /** Index of the first event that mentioned the item. */\n firstIndex: number;\n /** Indexes of `callback.start` / `callback.end`, ascending. */\n starts: number[];\n ends: number[];\n goneIndex: number;\n settledIndex: number;\n /** Indexes of the `item.new` events that name this item as trigger, ascending. */\n children: number[];\n /** Pool jobs tied to this item, with the index of the event that tied them. */\n jobNames: string[];\n jobIndexes: number[];\n timer: TimerRec | null;\n}\n\n/** Timer states as numbers; 0 means \"no timer at this position\". */\nexport const T_NONE = 0;\nexport const T_WAITING = 1;\nexport const T_RUNNING = 2;\nexport const T_DONE = 3;\nexport const T_CLEARED = 4;\n\n/** How many entries of an ascending list are below `limit`. */\nexport function countBelow(list: readonly number[], limit: number): number {\n let n = list.length;\n if (n <= 16) {\n while (n > 0 && (list[n - 1] as number) >= limit) n--;\n return n;\n }\n let lo = 0;\n while (lo < n) {\n const mid = (lo + n) >>> 1;\n if ((list[mid] as number) < limit) lo = mid + 1;\n else n = mid;\n }\n return lo;\n}\n\n/** The last entry of an ascending list that is below `limit`, or -1. */\nexport function lastBelow(list: readonly number[], limit: number): number {\n const n = countBelow(list, limit);\n return n === 0 ? -1 : (list[n - 1] as number);\n}\n\nexport function factOf(e: NmEvent, index: number): Fact {\n return { c: e.c, rule: e.rule === undefined ? null : e.rule, index, t: e.t };\n}\n\nconst WEAKNESS: Record<Certainty, number> = { observed: 0, inferred: 1, model: 2 };\n/** The weaker of two certainties (model < inferred < observed). */\nexport function weaker(a: Certainty, b: Certainty): Certainty {\n return WEAKNESS[a] >= WEAKNESS[b] ? a : b;\n}\n\n// ---- the index ------------------------------------------------------------------\n\nexport class RunIndex {\n /** Events indexed so far. */\n n = 0;\n /** Per event: F_* bits. */\n flags = new Uint8Array(1024);\n /**\n * Per block of 256 events: the F_* bits of all its events or-ed together.\n * A search for the next or previous stop of a kind skips whole blocks that\n * have none, so it stays fast when the kind is rare or absent in a long run.\n */\n blockFlags = new Uint8Array(4);\n /** Per event: its time, made non-decreasing (the largest `t` up to it), microseconds. */\n tMono = new Float64Array(1024);\n /**\n * Per event, written by the reducer after it applied the event: the loop\n * phase (bits 0-2), the certainty of that phase (bits 3-4, CERTAINTY_CODES),\n * paused or stopped (bit 5), a callback is running (bit 6).\n */\n tlState = new Uint8Array(1024);\n /** Per event: 1 + index into TIMELINE_CLASSES, or 0. Written by the reducer. */\n tlClass = new Uint8Array(1024);\n\n readonly items = new Map<number, ItemRec>();\n /** Items in order of first mention. */\n readonly order: ItemRec[] = [];\n readonly output: OutputChunk[] = [];\n /** Characters written up to and including each chunk. */\n readonly outputChars: number[] = [];\n /** Event indexes of notes. */\n readonly notes: number[] = [];\n /** Event indexes of `loop.turn` and the turn numbers. */\n readonly turns: number[] = [];\n readonly turnNumbers: number[] = [];\n readonly pauses: PauseMarker[] = [];\n\n #openDebug: PauseMarker | null = null;\n #openGate: PauseMarker | null = null;\n /** Log of record changes: which item was touched by which event. Lets truncate() undo them. */\n #touchIndex: number[] = [];\n #touchId: number[] = [];\n\n #grow(): void {\n const size = this.flags.length * 2;\n const grow8 = (a: Uint8Array) => {\n const b = new Uint8Array(size);\n b.set(a);\n return b;\n };\n this.flags = grow8(this.flags);\n const blocks = new Uint8Array(size >> 8);\n blocks.set(this.blockFlags);\n this.blockFlags = blocks;\n this.tlState = grow8(this.tlState);\n this.tlClass = grow8(this.tlClass);\n const t = new Float64Array(size);\n t.set(this.tMono);\n this.tMono = t;\n }\n\n #touch(rec: ItemRec, i: number): void {\n this.#touchIndex.push(i);\n this.#touchId.push(rec.id);\n }\n\n /** The record of item `id`, made on first mention. */\n #ensure(id: number, i: number, type: string): ItemRec {\n let rec = this.items.get(id);\n if (rec === undefined) {\n rec = {\n id,\n ref: { id, type, label: null, trigger: 0, loc: null, created: null },\n early: null,\n newIndex: -1,\n firstIndex: i,\n starts: [],\n ends: [],\n goneIndex: -1,\n settledIndex: -1,\n children: [],\n jobNames: [],\n jobIndexes: [],\n timer: null,\n };\n this.items.set(id, rec);\n this.order.push(rec);\n this.#touch(rec, i);\n } else if (type !== '?' && rec.newIndex < 0 && rec.ref.type === '?') {\n // The type of an item first seen without one. A type is a fixed\n // property of the item, not a state, so it is not rolled back by\n // position; truncate() drops it with the record if needed.\n rec.ref = { ...rec.ref, type };\n }\n return rec;\n }\n\n /**\n * Index the event at position `i` (which must be the next one). Returns\n * its flags. Never throws on bad input: such events get F_SKIP.\n */\n add(e: NmEvent, i: number): number {\n if (i >= this.flags.length) this.#grow();\n const prevT = i === 0 ? 0 : (this.tMono[i - 1] as number);\n this.tlState[i] = 0;\n this.tlClass[i] = 0;\n const bad = checkEvent(e);\n if (bad !== 0) {\n const f = bad === 1 ? F_SKIP | F_UNKNOWN : F_SKIP;\n this.flags[i] = f;\n if ((i & 255) === 0) this.blockFlags[i >> 8] = f;\n else this.blockFlags[i >> 8] = (this.blockFlags[i >> 8] as number) | f;\n // An unknown kind from a newer helper still has a usable time.\n const t = bad === 1 ? (e as { t: number }).t : prevT;\n this.tMono[i] = i === 0 || t > prevT ? t : prevT;\n this.n = i + 1;\n return f;\n }\n this.tMono[i] = i === 0 || e.t > prevT ? e.t : prevT;\n let f = SIGNAL_KINDS.has(e.k) ? 0 : F_STEP;\n\n switch (e.k) {\n case 'item.new': {\n const ref: ItemRef = {\n id: e.id,\n type: e.type,\n label: e.label === undefined ? null : e.label,\n trigger: e.trigger,\n loc: e.loc === undefined ? null : e.loc,\n created: factOf(e, i),\n };\n const existing = this.items.get(e.id);\n if (existing === undefined) {\n const rec = this.#ensure(e.id, i, e.type);\n rec.ref = ref;\n rec.newIndex = i;\n const parent = this.items.get(e.trigger);\n if (parent !== undefined && parent !== rec) {\n parent.children.push(i);\n this.#touch(parent, i);\n }\n } else if (existing.newIndex < 0) {\n // Seen earlier in another event; now we learn what it is.\n existing.early = existing.ref;\n existing.ref = ref;\n existing.newIndex = i;\n this.#touch(existing, i);\n const parent = this.items.get(e.trigger);\n if (parent !== undefined && parent !== existing) {\n parent.children.push(i);\n this.#touch(parent, i);\n }\n }\n // A second item.new for the same id is ignored here; the reducer counts it as inconsistent.\n break;\n }\n case 'callback.start': {\n const rec = this.#ensure(e.id, i, e.type);\n rec.starts.push(i);\n this.#touch(rec, i);\n f |= F_CALLBACK;\n break;\n }\n case 'callback.end': {\n const rec = this.#ensure(e.id, i, '?');\n rec.ends.push(i);\n this.#touch(rec, i);\n break;\n }\n case 'item.gone': {\n const rec = this.#ensure(e.id, i, '?');\n if (rec.goneIndex < 0) rec.goneIndex = i;\n const tm = rec.timer;\n // A timer destroyed while it was armed was cleared (clearTimeout, clearInterval).\n if (tm !== null && tm.clearedIndex < 0 && (tm.arms[tm.arms.length - 1] as number) > lastOf(rec.starts)) tm.clearedIndex = i;\n this.#touch(rec, i);\n break;\n }\n case 'promise.settled': {\n const rec = this.#ensure(e.id, i, '?');\n if (rec.settledIndex < 0) rec.settledIndex = i;\n this.#touch(rec, i);\n break;\n }\n case 'timer.set': {\n const rec = this.#ensure(e.id, i, '?');\n if (rec.timer === null) rec.timer = { setIndex: i, delayMs: e.delayMs, repeat: e.repeat, arms: [i], clearedIndex: -1 };\n else rec.timer.arms.push(i); // set again: armed again, first delay kept (the reducer counts it as inconsistent)\n this.#touch(rec, i);\n break;\n }\n case 'queue.add': {\n const rec = this.#ensure(e.id, i, '?');\n const tm = rec.timer;\n // A timer put back into the timers queue after a run is armed again\n // (setInterval, rule QT2 of the event format).\n if (e.queue === 'timers' && tm !== null && tm.clearedIndex < 0 && lastOf(rec.starts) > (tm.arms[tm.arms.length - 1] as number)) {\n tm.arms.push(i);\n this.#touch(rec, i);\n }\n break;\n }\n case 'queue.remove': {\n const rec = this.items.get(e.id);\n const tm = rec === undefined ? null : rec.timer;\n if (rec !== undefined && tm !== null && e.queue === 'timers' && tm.clearedIndex < 0) {\n // Cleared: while armed, or (a repeating timer) from inside its own callback.\n if (tm.repeat || (tm.arms[tm.arms.length - 1] as number) > lastOf(rec.starts)) {\n tm.clearedIndex = i;\n this.#touch(rec, i);\n }\n }\n break;\n }\n case 'pool.queued':\n if (e.id !== undefined) this.#tie(e.id, e.job, i);\n break;\n case 'pool.link':\n this.#tie(e.id, e.job, i);\n break;\n case 'output': {\n const before = this.outputChars.length === 0 ? 0 : (this.outputChars[this.outputChars.length - 1] as number);\n const chunk: OutputChunk = { seq: this.output.length, index: i, t: e.t, stream: e.stream, text: e.text };\n if (e.loc !== undefined) chunk.loc = e.loc;\n this.output.push(chunk);\n this.outputChars.push(before + e.text.length);\n f |= F_OUTPUT;\n break;\n }\n case 'note':\n this.notes.push(i);\n break;\n case 'loop.turn':\n this.turns.push(i);\n this.turnNumbers.push(e.n);\n f |= F_TURN;\n break;\n case 'phase.enter':\n f |= F_PHASE;\n break;\n case 'debug.paused': {\n const m: PauseMarker = { kind: 'debug', index: i, t: e.t, endIndex: null, ms: null, reason: e.reason, timeKeptRunning: e.timeKeptRunning };\n this.pauses.push(m);\n this.#openDebug = m;\n f |= F_PAUSE;\n break;\n }\n case 'debug.resumed':\n if (this.#openDebug !== null) {\n this.#openDebug.endIndex = i;\n this.#openDebug.ms = e.pausedMs;\n this.#openDebug = null;\n }\n break;\n case 'gate.stopped': {\n const m: PauseMarker = { kind: 'gate', index: i, t: e.t, endIndex: null, ms: null, reason: e.gate, timeKeptRunning: false };\n this.pauses.push(m);\n this.#openGate = m;\n f |= F_PAUSE;\n break;\n }\n case 'gate.released':\n if (this.#openGate !== null) {\n this.#openGate.endIndex = i;\n this.#openGate.ms = e.stoppedMs;\n this.#openGate = null;\n }\n break;\n default:\n break;\n }\n this.flags[i] = f;\n if ((i & 255) === 0) this.blockFlags[i >> 8] = f;\n else this.blockFlags[i >> 8] = (this.blockFlags[i >> 8] as number) | f;\n this.n = i + 1;\n return f;\n }\n\n /** The first index in [from, n) whose flags have a bit of `mask`, or -1. */\n nextWith(mask: number, from: number): number {\n const flags = this.flags;\n const blocks = this.blockFlags;\n const n = this.n;\n let i = Math.max(0, from);\n while (i < n) {\n if (((blocks[i >> 8] as number) & mask) === 0) {\n i = ((i >> 8) + 1) << 8; // nothing in this block\n continue;\n }\n const end = Math.min(n, ((i >> 8) + 1) << 8);\n for (; i < end; i++) if (((flags[i] as number) & mask) !== 0) return i;\n }\n return -1;\n }\n\n /** The last index in [0, from] whose flags have a bit of `mask`, or -1. */\n previousWith(mask: number, from: number): number {\n const flags = this.flags;\n const blocks = this.blockFlags;\n let i = Math.min(this.n - 1, from);\n while (i >= 0) {\n if (((blocks[i >> 8] as number) & mask) === 0) {\n i = ((i >> 8) << 8) - 1;\n continue;\n }\n const start = (i >> 8) << 8;\n for (; i >= start; i--) if (((flags[i] as number) & mask) !== 0) return i;\n }\n return -1;\n }\n\n #tie(id: number, job: string, i: number): void {\n const rec = this.#ensure(id, i, '?');\n rec.jobNames.push(job);\n rec.jobIndexes.push(i);\n this.#touch(rec, i);\n }\n\n /** Forget everything that came from events at index `from` and above. */\n truncate(from: number): void {\n if (from >= this.n) return;\n const ti = this.#touchIndex;\n const tid = this.#touchId;\n while (ti.length > 0 && (ti[ti.length - 1] as number) >= from) {\n ti.pop();\n const rec = this.items.get(tid.pop() as number);\n if (rec === undefined) continue;\n if (rec.firstIndex >= from) {\n this.items.delete(rec.id);\n continue;\n }\n if (rec.newIndex >= from) {\n rec.ref = rec.early as ItemRef;\n rec.early = null;\n rec.newIndex = -1;\n }\n cut(rec.starts, from);\n cut(rec.ends, from);\n cut(rec.children, from);\n const keep = countBelow(rec.jobIndexes, from);\n rec.jobIndexes.length = keep;\n rec.jobNames.length = keep;\n if (rec.goneIndex >= from) rec.goneIndex = -1;\n if (rec.settledIndex >= from) rec.settledIndex = -1;\n const tm = rec.timer;\n if (tm !== null) {\n if (tm.setIndex >= from) rec.timer = null;\n else {\n cut(tm.arms, from);\n if (tm.clearedIndex >= from) tm.clearedIndex = -1;\n }\n }\n }\n const order = this.order;\n while (order.length > 0 && (order[order.length - 1] as ItemRec).firstIndex >= from) order.pop();\n while (this.output.length > 0 && (this.output[this.output.length - 1] as OutputChunk).index >= from) {\n this.output.pop();\n this.outputChars.pop();\n }\n cut(this.notes, from);\n const turns = countBelow(this.turns, from);\n this.turns.length = turns;\n this.turnNumbers.length = turns;\n const pauses = this.pauses;\n while (pauses.length > 0 && (pauses[pauses.length - 1] as PauseMarker).index >= from) pauses.pop();\n // A pause that ended at or after `from` is open again. Only the latest\n // remaining pause of each kind can be affected: a later one of the same\n // kind would have started after that end, and was dropped above.\n this.#openDebug = this.#reopen('debug', from);\n this.#openGate = this.#reopen('gate', from);\n // The block that `from` cuts through keeps only the bits of the events that are left.\n // (Later blocks are started afresh by add() when their first event arrives.)\n if ((from & 255) !== 0) {\n let bits = 0;\n for (let i = from & ~255; i < from; i++) bits |= this.flags[i] as number;\n this.blockFlags[from >> 8] = bits;\n }\n this.n = from;\n }\n\n #reopen(kind: 'debug' | 'gate', from: number): PauseMarker | null {\n for (let k = this.pauses.length - 1; k >= 0; k--) {\n const m = this.pauses[k] as PauseMarker;\n if (m.kind !== kind) continue;\n if (m.endIndex !== null && m.endIndex >= from) {\n m.endIndex = null;\n m.ms = null;\n }\n return m.endIndex === null ? m : null;\n }\n return null;\n }\n\n /** How many items had been mentioned before position `p`. */\n itemsBefore(p: number): number {\n const order = this.order;\n let lo = 0;\n let hi = order.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((order[mid] as ItemRec).firstIndex < p) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n\n /** The item as it was known at position `p`. */\n refAt(rec: ItemRec, p: number): ItemRef {\n return rec.newIndex >= 0 && rec.newIndex >= p && rec.early !== null ? rec.early : rec.ref;\n }\n\n /** State of the item's timer at position `p`. `running`: its callback is on the stack at `p`. */\n timerStateAt(rec: ItemRec, p: number, running: boolean): number {\n const tm = rec.timer;\n if (tm === null || tm.setIndex >= p) return T_NONE;\n if (tm.clearedIndex >= 0 && tm.clearedIndex < p) return T_CLEARED;\n if (running) return T_RUNNING;\n return lastBelow(tm.arms, p) > lastBelow(rec.starts, p) ? T_WAITING : T_DONE;\n }\n}\n\nfunction lastOf(list: readonly number[]): number {\n return list.length === 0 ? -1 : (list[list.length - 1] as number);\n}\n\n/** Drop the entries of an ascending list that are `from` or above. */\nfunction cut(list: number[], from: number): void {\n let n = list.length;\n while (n > 0 && (list[n - 1] as number) >= from) n--;\n list.length = n;\n}\n","/**\n * Validation of events and recording headers.\n *\n * A recording file is untrusted input: it may come from a shared link. These\n * functions check every field, reject unknown kinds and unknown fields, cap\n * the length of every string, and return a fresh plain object that contains\n * nothing but the checked fields. They never evaluate anything.\n */\n\nimport type { Capabilities, EventKind, Frame, Loc, NmEvent, NodeInfo, RecordingHeader } from './types.ts';\nimport { FORMAT_VERSION } from './types.ts';\n\n/** Thrown for anything wrong with a recording, an event or a header. */\nexport class RecordingError extends Error {\n /** 1-based line of the recording text, when the error belongs to one. */\n readonly line: number | undefined;\n constructor(message: string, line?: number) {\n super(line === undefined ? message : `line ${line}: ${message}`);\n this.name = 'RecordingError';\n this.line = line;\n }\n}\n\n/** Limits. Generous for real recordings, small enough to bound memory per field. */\nexport const LIMITS = {\n /** Output text of one write, source text of one file. */\n text: 1_000_000,\n /** Names, labels, types, urls, atlas ids. */\n name: 512,\n /** Frames of one paused stack. */\n frames: 200,\n /** Keys of a `signal` event's args. */\n args: 32,\n /** Source files carried in a header. */\n sources: 64,\n} as const;\n\ntype Check = (v: unknown, path: string) => unknown;\n\nfunction fail(path: string, what: string): never {\n throw new RecordingError(`${path}: ${what}`);\n}\n\nconst str = (max: number): Check => (v, p) => {\n if (typeof v !== 'string') fail(p, 'must be a string');\n if ((v as string).length > max) fail(p, `string longer than ${max}`);\n return v;\n};\nconst name = str(LIMITS.name);\nconst text = str(LIMITS.text);\nconst num: Check = (v, p) => {\n if (typeof v !== 'number' || !Number.isFinite(v)) fail(p, 'must be a finite number');\n return v;\n};\nconst nonNeg: Check = (v, p) => {\n num(v, p);\n if ((v as number) < 0) fail(p, 'must not be negative');\n return v;\n};\nconst int: Check = (v, p) => {\n if (typeof v !== 'number' || !Number.isSafeInteger(v)) fail(p, 'must be an integer');\n return v;\n};\n/** A libuv pool size: 1 to 1024 threads (MAX_THREADPOOL_SIZE). */\nconst poolSize: Check = (v, p) => {\n if (typeof v !== 'number' || !Number.isInteger(v) || v < 1 || v > 1024) fail(p, 'must be a whole number from 1 to 1024');\n return v;\n};\nconst count: Check = (v, p) => {\n int(v, p);\n if ((v as number) < 0) fail(p, 'must not be negative');\n return v;\n};\nconst bool: Check = (v, p) => {\n if (typeof v !== 'boolean') fail(p, 'must be true or false');\n return v;\n};\nconst oneOf = (...allowed: readonly string[]): Check => (v, p) => {\n if (typeof v !== 'string' || !allowed.includes(v)) fail(p, `must be one of ${allowed.join(', ')}`);\n return v;\n};\nconst nullable = (c: Check): Check => (v, p) => (v === null ? null : c(v, p));\n\ninterface Field {\n check: Check;\n optional?: true;\n}\ntype Spec = Record<string, Field>;\nconst req = (check: Check): Field => ({ check });\nconst opt = (check: Check): Field => ({ check, optional: true });\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\n/** Checks `v` against `spec`; unknown keys are an error. Returns a fresh object. */\nfunction object(spec: Spec, v: unknown, path: string, extraAllowed?: ReadonlySet<string>): Record<string, unknown> {\n if (!isPlainObject(v)) fail(path, 'must be an object');\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(v)) {\n if (!Object.hasOwn(spec, key) && !(extraAllowed && extraAllowed.has(key))) fail(path, `unknown field \"${key}\"`);\n }\n for (const key of Object.keys(spec)) {\n const f = spec[key] as Field;\n const value = Object.hasOwn(v, key) ? v[key] : undefined;\n if (value === undefined) {\n if (!f.optional) fail(path, `missing field \"${key}\"`);\n continue;\n }\n out[key] = f.check(value, path === '' ? key : `${path}.${key}`);\n }\n return out;\n}\nconst obj = (spec: Spec): Check => (v, p) => object(spec, v, p);\n\nconst LOC: Spec = { url: req(name), line: req(count), col: opt(count) };\nconst FRAME: Spec = { fn: req(name), loc: req(obj(LOC)), origin: req(oneOf('user', 'node', 'other')), at: opt(name) };\nconst NODE_INFO: Spec = { version: req(name), v8: req(name), uv: req(name), platform: req(name), arch: req(name) };\nconst CERT = oneOf('observed', 'inferred', 'model');\nconst CAPS: Spec = {\n provider: req(oneOf('user', 'pinned', 'probe')),\n jsDebugger: req(bool),\n asyncItems: req(bool),\n poolThreads: req(oneOf('delayed', 'live', 'none')),\n phasesTimersCheck: req(oneOf('observed', 'inferred', 'model', 'none')),\n phasesOther: req(oneOf('observed', 'inferred', 'model', 'none')),\n gates: req(obj({ phase: req(bool), timer: req(bool), poolStart: req(bool), poolPost: req(bool) })),\n frozenClock: req(bool),\n};\nconst PHASE = oneOf('timers', 'pending', 'idle', 'prepare', 'poll', 'check', 'closing');\nconst QUEUE = oneOf('nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close');\n\nconst frames: Check = (v, p) => {\n if (!Array.isArray(v)) fail(p, 'must be a list');\n if (v.length > LIMITS.frames) fail(p, `more than ${LIMITS.frames} frames`);\n return v.map((f, i) => object(FRAME, f, `${p}[${i}]`));\n};\n\nconst args: Check = (v, p) => {\n if (!isPlainObject(v)) fail(p, 'must be an object');\n const keys = Object.keys(v);\n if (keys.length > LIMITS.args) fail(p, `more than ${LIMITS.args} keys`);\n const out: Record<string, string | number | boolean | null> = Object.create(null) as Record<string, string | number | boolean | null>;\n for (const key of keys) {\n if (key.length > LIMITS.name) fail(p, 'key too long');\n const x = v[key];\n if (x === null || typeof x === 'boolean') out[key] = x;\n else if (typeof x === 'number' && Number.isFinite(x)) out[key] = x;\n else if (typeof x === 'string' && x.length <= LIMITS.text) out[key] = x;\n else fail(`${p}.${key}`, 'must be a string, a finite number, true, false or null');\n }\n // a plain object again (the null prototype above only protects the copy loop)\n return Object.assign({}, out);\n};\n\n/** Fields every event may carry besides its payload. */\nconst BASE: Spec = {\n k: req(name),\n t: req(num),\n tq: opt(oneOf('approx', 'tie')),\n src: req(oneOf('hooks', 'trace', 'cdp', 'probe', 'helper', 'rule')),\n c: req(CERT),\n rule: opt(str(32)),\n at: opt(name),\n tid: opt(count),\n};\n\n/** The payload fields of every kind. Keep in step with EventPayloads in types.ts. */\nconst PAYLOADS: { [K in EventKind]: Spec } = {\n 'run.start': {\n node: req(obj(NODE_INFO)),\n caps: req(obj(CAPS)),\n mode: req(oneOf('free', 'debug')),\n program: req(name),\n poolSize: req(count),\n },\n 'run.end': { code: req(nullable(int)), signal: req(nullable(name)) },\n 'output': { stream: req(oneOf('stdout', 'stderr')), text: req(text), loc: opt(obj(LOC)) },\n 'item.new': { id: req(count), type: req(name), trigger: req(count), label: opt(name), loc: opt(obj(LOC)) },\n 'callback.start': { id: req(count), type: req(name), close: opt(bool) },\n 'callback.end': { id: req(count) },\n 'item.gone': { id: req(count) },\n 'promise.settled': { id: req(count) },\n 'timer.set': { id: req(count), delayMs: req(nonNeg), repeat: req(bool) },\n 'loop.sample': { loopCount: req(count), events: req(count), eventsWaiting: req(count) },\n 'scope': { name: req(name), durUs: req(nonNeg) },\n 'pool.thread': { edge: req(oneOf('start', 'end')), name: req(name) },\n 'signal': { cat: req(name), name: req(name), ph: req(str(8)), ref: opt(name), args: opt(args) },\n 'queue.add': { queue: req(QUEUE), id: req(count) },\n 'queue.remove': { queue: req(QUEUE), id: req(count), why: req(oneOf('cancel', 'gone')) },\n 'loop.turn': { n: req(count) },\n 'phase.enter': { phase: req(PHASE), turn: opt(count), afterPoll: opt(bool), pollTimeoutMs: opt(num) },\n 'phase.leave': { phase: req(PHASE), turn: opt(count), afterPoll: opt(bool) },\n 'timer.fired': { lateMs: opt(num) },\n 'pool.queued': {\n job: req(name),\n kind: req(oneOf('fs', 'dns', 'crypto', 'zlib', 'user', 'unknown')),\n op: opt(name),\n id: opt(count),\n },\n 'pool.started': { job: req(name), thread: req(count) },\n 'pool.finished': { job: req(name), thread: req(count) },\n 'pool.posted': { job: req(name), thread: req(count) },\n 'pool.delivered': { job: req(name) },\n 'pool.cancelled': { job: req(name) },\n 'pool.link': { job: req(name), id: req(count) },\n 'pool.size': { size: req(poolSize) },\n 'debug.paused': {\n reason: req(oneOf('breakpoint', 'step', 'pause', 'exception', 'entry', 'other')),\n frames: req(frames),\n timeKeptRunning: req(bool),\n },\n 'debug.resumed': { pausedMs: req(nonNeg) },\n 'gate.stopped': { gate: req(oneOf('phase', 'turn', 'timer', 'poolStart', 'poolPost', 'poolDone', 'manual')), phase: opt(PHASE), job: opt(name) },\n 'gate.released': { stoppedMs: req(nonNeg) },\n 'clock.frozen': { why: opt(oneOf('gate', 'breakpoint')) },\n 'clock.unfrozen': { hiddenMs: req(nonNeg) },\n 'note': { level: req(oneOf('info', 'warn')), text: req(str(2000)) },\n};\n\nconst KINDS: ReadonlySet<string> = new Set(Object.keys(PAYLOADS));\nconst SPEC_BY_KIND = new Map<string, Spec>();\nfor (const k of Object.keys(PAYLOADS) as EventKind[]) SPEC_BY_KIND.set(k, { ...BASE, ...PAYLOADS[k] });\n\n/** Every event kind of this format version. */\nexport function eventKinds(): EventKind[] {\n return Object.keys(PAYLOADS) as EventKind[];\n}\n\n/** True when `k` is a kind of this format version. */\nexport function isEventKind(k: unknown): k is EventKind {\n return typeof k === 'string' && KINDS.has(k);\n}\n\n/** The names of the fields an event of kind `k` may carry besides `k`, `t`, `src`, `c`. */\nexport function fieldNames(k: EventKind): string[] {\n return Object.keys(SPEC_BY_KIND.get(k) as Spec).filter((f) => f !== 'k' && f !== 't' && f !== 'src' && f !== 'c');\n}\n\n/**\n * Checks one event. Returns a fresh object with only the known fields.\n * Throws RecordingError when anything is off.\n */\nexport function validateEvent(value: unknown): NmEvent {\n if (!isPlainObject(value)) throw new RecordingError('an event must be an object');\n const k = value['k'];\n if (!isEventKind(k)) throw new RecordingError(`unknown event kind ${typeof k === 'string' ? JSON.stringify(k.slice(0, 60)) : typeof k}`);\n const out = object(SPEC_BY_KIND.get(k) as Spec, value, k);\n if (out['c'] !== 'observed' && typeof out['rule'] !== 'string') {\n throw new RecordingError(`${k}: an ${String(out['c'])} event must name its rule`);\n }\n return out as unknown as NmEvent;\n}\n\nconst HEADER: Spec = {\n format: req(oneOf('nodejs-map-recording')),\n version: req(count),\n created: req(str(64)),\n tool: req(str(64)),\n node: req(obj(NODE_INFO)),\n atlas: req(obj({ tag: req(str(64)), commit: req(str(64)) })),\n title: opt(name),\n description: opt(str(4000)),\n sources: opt((v, p) => {\n if (!Array.isArray(v)) fail(p, 'must be a list');\n if (v.length > LIMITS.sources) fail(p, `more than ${LIMITS.sources} sources`);\n return v.map((s, i) => object({ name: req(name), text: req(text) }, s, `${p}[${i}]`));\n }),\n};\n\n/**\n * Checks a recording header. Refuses a newer format version: an older reader\n * cannot know what a newer writer meant.\n */\nexport function validateHeader(value: unknown): RecordingHeader {\n const out = object(HEADER, value, 'header') as unknown as RecordingHeader;\n if (out.version > FORMAT_VERSION) {\n throw new RecordingError(`this recording is format version ${out.version}; this reader understands up to ${FORMAT_VERSION}`);\n }\n if (out.version < 1) throw new RecordingError('header.version: must be 1 or more');\n if (Number.isNaN(Date.parse(out.created))) throw new RecordingError('header.created: not a date');\n return out;\n}\n\n/** Type helpers re-exported for callers that build events by hand. */\nexport type { Capabilities, Frame, Loc, NodeInfo };\n","/**\n * The rule registry.\n *\n * Every event that is not a raw signal names the rule that produced it\n * (`rule` on the event). A rule says, in plain English, what was seen and\n * what may be concluded from it, how sure the conclusion is, and which parts\n * of Node's source it relies on.\n *\n * `cites` are atlas ids, never line numbers:\n * s:<path>#<qualified name> a function in Node's source at the tag\n * o:<name> a well-known box of the atlas overlay\n * The atlas resolves them to files and lines for the Node version in use, and\n * a proof test checks that every id cited here exists in the built atlas.\n *\n * Rules are data. The code that applies them lives in the helper\n * (rule stage); the ids here are the contract between the two.\n */\n\nimport type { Certainty } from './types.ts';\n\nexport interface Rule {\n /** Short id written into events, for example \"T1\". */\n id: string;\n title: string;\n /** \"When we see X, we claim Y\", in plain English. */\n statement: string;\n /** The certainty of the events this rule produces. */\n yields: Certainty;\n /** Where the rule holds. `unix` covers Linux and macOS. */\n platform: 'all' | 'unix' | 'win32';\n /** Atlas ids of the source the rule relies on. */\n cites: readonly string[];\n}\n\n// Source symbols used below, kept in one place so a rename is one edit.\nconst S = {\n // the scope constructor has overloads; the overlay box for InternalMakeCallback covers them\n callbackScopeCtor: 'o:cb.InternalMakeCallback',\n callbackScopeClose: 's:src/api/callback.cc#node::InternalCallbackScope::Close',\n runTimers: 's:src/env.cc#node::Environment::RunTimers',\n scheduleTimer: 's:src/env.cc#node::Environment::ScheduleTimer',\n checkImmediate: 's:src/env.cc#node::Environment::CheckImmediate',\n toggleImmediateRef: 's:src/env.cc#node::Environment::ToggleImmediateRef',\n uvRunTimers: 's:deps/uv/src/timer.c#uv__run_timers',\n processTimers: 's:lib/internal/timers.js#getTimerCallbacks/processTimers',\n listOnTimeout: 'o:timers.listOnTimeout',\n processImmediate: 's:lib/internal/timers.js#getTimerCallbacks/processImmediate',\n timeoutCtor: 's:lib/internal/timers.js#Timeout.prototype.constructor',\n immediateCtor: 's:lib/internal/timers.js#Immediate.prototype.constructor',\n timerInsert: 's:lib/internal/timers.js#insert',\n nextTick: 's:lib/internal/process/task_queues.js#nextTick',\n processTicks: 's:lib/internal/process/task_queues.js#processTicksAndRejections',\n queueMicrotask: 's:lib/internal/process/task_queues.js#queueMicrotask',\n runMicrotask: 's:lib/internal/process/task_queues.js#runMicrotask',\n promiseInitHook: 's:lib/internal/async_hooks.js#promiseInitHook',\n promiseBeforeHook: 's:lib/internal/async_hooks.js#promiseBeforeHook',\n uvRunUnix: 's:deps/uv/src/unix/core.c#uv_run',\n uvRunWin: 's:deps/uv/src/win/core.c#uv_run',\n uvPollWin: 's:deps/uv/src/win/core.c#uv__poll',\n uvProcessReqs: 's:deps/uv/src/win/core.c#uv__process_reqs',\n uvIoPollLinux: 's:deps/uv/src/unix/linux.c#uv__io_poll',\n uvAsyncIo: 's:deps/uv/src/unix/async.c#uv__async_io',\n uvAsyncWakeupWin: 's:deps/uv/src/win/async.c#uv__process_async_wakeup_req',\n worker: 's:deps/uv/src/threadpool.c#worker',\n post: 's:deps/uv/src/threadpool.c#post',\n workSubmit: 's:deps/uv/src/threadpool.c#uv__work_submit',\n workDone: 's:deps/uv/src/threadpool.c#uv__work_done',\n initThreads: 's:deps/uv/src/threadpool.c#init_threads',\n scheduleWork: 's:src/threadpoolwork-inl.h#node::ThreadPoolWork::ScheduleWork',\n fsWorkUnix: 's:deps/uv/src/unix/fs.c#uv__fs_work',\n fsWorkWin: 's:deps/uv/src/win/fs.c#uv__fs_work',\n getaddrinfoUnix: 's:deps/uv/src/unix/getaddrinfo.c#uv_getaddrinfo',\n getaddrinfoWin: 's:deps/uv/src/win/getaddrinfo.c#uv_getaddrinfo',\n uvMetricsInfo: 's:src/node_perf.cc#node::performance::UvMetricsInfo',\n queryResponse: 's:src/cares_wrap.h#node::cares_wrap::QueryWrap::QueueResponseCallback',\n handleOnClose: 's:src/handle_wrap.cc#node::HandleWrap::OnClose',\n closingUnix: 's:deps/uv/src/unix/core.c#uv__run_closing_handles',\n closingWin: 's:deps/uv/src/win/core.c#uv__process_endgames',\n ioFeed: 's:deps/uv/src/unix/core.c#uv__io_feed',\n runPending: 's:deps/uv/src/unix/core.c#uv__run_pending',\n streamIo: 's:deps/uv/src/unix/stream.c#uv__stream_io',\n writeReqFinish: 's:deps/uv/src/unix/stream.c#uv__write_req_finish',\n shutdownUnix: 's:deps/uv/src/unix/stream.c#uv_shutdown',\n} as const;\n\nconst O = {\n phaseTimers: 'o:phase.timers',\n phasePending: 'o:phase.pending',\n phasePoll: 'o:phase.poll',\n phaseCheck: 'o:phase.check',\n tickDrain: 'o:tick.drain',\n microtaskDrain: 'o:microtask.run',\n promiseReactionEnqueue: 'o:v8.enqueueMicrotask',\n promiseReactionRun: 'o:v8.promiseReactionJob',\n performPromiseThen: 'o:v8.performPromiseThen',\n triggerReactions: 'o:v8.triggerReactions',\n poolSubmit: 'o:pool.submit',\n poolWorker: 'o:pool.worker',\n poolDone: 'o:pool.done',\n makeCallback: 'o:cb.InternalMakeCallback',\n uvRun: 'o:loop.run',\n dnsQueryResponse: 'o:dns.queryResponse',\n nativeImmediatesRun: 'o:immediate.native',\n shutdownQueue: 'o:uv.shutdown',\n shutdownRun: 'o:uv.shutdownDone',\n closeCallbacks: 'o:loop.finishClose',\n handleOnClose: 'o:cb.handleOnClose',\n} as const;\n\nconst ENTRIES: readonly Rule[] = [\n // ---- callbacks ------------------------------------------------------------\n {\n id: 'C0',\n title: 'A callback started or ended',\n statement:\n 'Node calls the async_hooks \"before\" hook just before it runs the JavaScript callback of an async item and \"after\" when the callback has returned. We report these two moments as they are.',\n yields: 'observed',\n platform: 'all',\n cites: [S.callbackScopeCtor, S.callbackScopeClose, S.listOnTimeout, S.processImmediate, S.processTicks],\n },\n\n // ---- timers phase -----------------------------------------------------------\n {\n id: 'T0',\n title: 'The timers phase ran timer callbacks',\n statement:\n \"Node reports a timed scope named RunTimers each time libuv's timers step calls Node's one timer. From its start to its end the loop is in the timers phase and is running due setTimeout and setInterval callbacks.\",\n yields: 'observed',\n platform: 'all',\n cites: [S.runTimers, S.uvRunTimers, S.scheduleTimer, O.phaseTimers],\n },\n {\n id: 'T1',\n title: 'A timer callback implies the timers phase',\n statement:\n 'A callback of an item of type Timeout started and no RunTimers scope has been reported for that moment (trace events arrive later than hooks). Timeout callbacks are only ever run by processTimers, which libuv calls in its timers step, so the loop is in the timers phase.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.processTimers, S.listOnTimeout, S.runTimers, O.phaseTimers],\n },\n {\n id: 'T2',\n title: 'A timer callback inside a reported timers scope',\n statement:\n 'A Timeout callback started between the start and the end of a RunTimers scope that Node reported. Both facts are observed, so this callback ran in the timers phase.',\n yields: 'observed',\n platform: 'all',\n cites: [S.runTimers, S.listOnTimeout],\n },\n\n // ---- check phase ------------------------------------------------------------\n {\n id: 'I0',\n title: 'The check phase ran',\n statement:\n 'Node reports a timed scope named CheckImmediate from the callback of a libuv check handle that is always active. It runs once in every loop turn, in the check phase, whether or not the program used setImmediate.',\n yields: 'observed',\n platform: 'all',\n cites: [S.checkImmediate, O.phaseCheck],\n },\n {\n id: 'I1',\n title: 'An immediate callback implies the check phase',\n statement:\n 'A callback of an item of type Immediate started and no CheckImmediate scope has been reported for that moment. Immediate callbacks are only run by processImmediate, which Node calls from the check phase.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.processImmediate, S.checkImmediate, O.phaseCheck],\n },\n {\n id: 'I2',\n title: 'An immediate callback inside a reported check scope',\n statement: 'An Immediate callback started between the start and the end of a CheckImmediate scope that Node reported.',\n yields: 'observed',\n platform: 'all',\n cites: [S.checkImmediate, S.processImmediate],\n },\n\n // ---- I/O callbacks ----------------------------------------------------------\n {\n id: 'P1u',\n title: 'A thread pool result is delivered inside the poll step (Linux, macOS)',\n statement:\n 'A callback of a thread-pool-backed item (file system, dns.lookup, crypto, zlib) started outside the timers and check phases. On Unix a finished job wakes the loop through an async handle, and libuv runs the callback from uv__io_poll, so the loop is in the poll phase.',\n yields: 'inferred',\n platform: 'unix',\n cites: [S.uvRunUnix, S.uvIoPollLinux, S.uvAsyncIo, S.workDone, O.phasePoll],\n },\n {\n id: 'P1w',\n title: 'A thread pool result is delivered after the poll step (Windows)',\n statement:\n 'A callback of a thread-pool-backed item started outside the timers and check phases. On Windows uv__poll only collects finished requests; their callbacks run in uv__process_reqs, which uv_run calls right after the poll and again at the top of the next turn. We show this as the pending step.',\n yields: 'inferred',\n platform: 'win32',\n cites: [S.uvRunWin, S.uvPollWin, S.uvProcessReqs, S.uvAsyncWakeupWin, S.workDone, O.phasePending],\n },\n {\n id: 'P2',\n title: 'A handle callback that is not its close callback is delivered by the poll step',\n statement:\n 'A callback of a handle (TCP socket or server, pipe, terminal, UDP socket, child process, signal, file watcher) started outside the timers and check phases, and the helper saw that it is not the handle\\'s close callback (rule CL1). Data, connections and other events of a handle are read in the poll step: on Unix libuv calls back from there; on Windows uv__poll only collects them and the callbacks run in uv__process_reqs right after, which we show as the pending step after the poll. On Windows the same holds for write, shutdown, connect and send requests. No phase is inferred, rather than a wrong one, in these cases: write, shutdown, connect and send requests on Unix (libuv finishes them from uv__stream_io in the poll step when data was still waiting to be written, and otherwise queues the stream with uv__io_feed so that the callback runs in a pending pass: a shutdown with no write waiting runs in the pending step, one behind queued writes in the poll step, and the type does not say which); message ports and every other kind of item, whose callbacks can be made from several steps; a handle whose close state the helper could not read.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.uvRunUnix, S.uvRunWin, S.uvProcessReqs, S.streamIo, S.ioFeed, S.runPending, S.writeReqFinish, S.shutdownUnix, O.shutdownQueue, O.shutdownRun, O.phasePoll, O.phasePending],\n },\n {\n id: 'CL1',\n title: 'A handle\\'s close callback runs in the closing step',\n statement:\n 'A callback of a handle started, and the handle object carries the property Node sets when close(callback) is called (handle_onclose). After close() the handle gets no other callback, so this one is the close callback: libuv makes it in the closing step at the end of the turn (uv__run_closing_handles on Unix, uv__process_endgames on Windows), and Node passes it on from HandleWrap::OnClose.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.handleOnClose, S.closingUnix, S.closingWin, S.uvRunUnix, S.uvRunWin, O.handleOnClose, O.closeCallbacks],\n },\n {\n id: 'I3',\n title: 'A dns.resolve answer is delivered in the check phase',\n statement:\n 'A callback of a QUERYWRAP item (dns.resolve and its relatives, answered by c-ares) started outside a reported scope. Node does not call back when the answer arrives on the socket: QueryWrap::QueueResponseCallback defers it with SetImmediate, so it runs with the native immediates in the check phase, on every system.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.queryResponse, S.checkImmediate, O.dnsQueryResponse, O.nativeImmediatesRun, O.phaseCheck],\n },\n\n // ---- nextTick and microtasks ------------------------------------------------\n {\n id: 'K1',\n title: 'A nextTick callback ran from the tick queue',\n statement:\n 'A callback of an item of type TickObject started. process.nextTick creates exactly one TickObject per call and processTicksAndRejections runs them in order when the current callback scope closes, before the loop continues.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.nextTick, S.processTicks, S.callbackScopeClose, O.tickDrain],\n },\n {\n id: 'M1',\n title: 'A microtask ran',\n statement:\n 'A callback of an item of type PROMISE or Microtask started. Promise reactions and queueMicrotask callbacks are jobs on V8\\'s microtask queue, drained after the nextTick queue and whenever a callback scope closes.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.promiseBeforeHook, S.runMicrotask, S.processTicks, S.callbackScopeClose, O.microtaskDrain, O.promiseReactionRun],\n },\n\n // ---- loop turns ---------------------------------------------------------------\n {\n id: 'L1',\n title: 'Loop counters',\n statement:\n \"performance.nodeTiming.uvMetricsInfo returns libuv's own counters. loopCount is increased once per turn, just before the poll step. We read it when a top-level callback starts, so the value is exact but the moment a turn began is not known from it.\",\n yields: 'observed',\n platform: 'all',\n cites: [S.uvMetricsInfo, S.uvRunUnix, S.uvRunWin],\n },\n {\n id: 'L2',\n title: 'Loop turns from the check phase',\n statement:\n 'CheckImmediate is reported once per loop turn (rule I0). The timers step that follows it belongs to the same turn. The first callback or scope after that starts the next turn; we place the turn boundary there.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.checkImmediate, S.uvRunUnix, S.uvRunWin, O.uvRun],\n },\n {\n id: 'L3',\n title: 'Loop turns from the loop counter',\n statement:\n 'The loop counter read when a callback starts (rule L1) is higher than at the previous callback, so at least one new turn began in between. Until trace events arrive we place the turn boundary at this callback. Turns in which no callback of ours ran are skipped.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.uvMetricsInfo, S.uvRunUnix, S.uvRunWin, O.uvRun],\n },\n\n // ---- thread pool ----------------------------------------------------------------\n {\n id: 'W0',\n title: 'A job was submitted to, or came back from, the thread pool',\n statement:\n \"Node's ThreadPoolWork reports a trace event with the job's address when it submits work to libuv and another when the result is delivered on the main thread.\",\n yields: 'observed',\n platform: 'all',\n cites: [S.scheduleWork, S.workSubmit, S.workDone, O.poolSubmit, O.poolDone],\n },\n {\n id: 'W1',\n title: 'Which async item a pool job belongs to',\n statement:\n 'The trace event for a submitted job follows the creation of an async item of a thread-pool-backed type on the main thread, in the same synchronous call. We take that item as the owner of the job. The trace event itself carries no async id.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.scheduleWork, S.workSubmit],\n },\n {\n id: 'W2',\n title: 'A pool thread started a job',\n statement:\n \"Node's ThreadPoolWork reports a trace event from the pool thread when the work function begins. The event carries the real thread id and the kind of job, but not which job.\",\n yields: 'observed',\n platform: 'all',\n cites: [S.scheduleWork, S.worker, O.poolWorker],\n },\n {\n id: 'W2b',\n title: 'Which job a pool thread started',\n statement:\n 'libuv keeps one first-in first-out work queue for all pool threads. The n-th \"started\" report for a kind of job is therefore the n-th submitted job of that kind. Two threads that take jobs within the same microsecond can report in swapped order.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.worker, S.post, S.workSubmit],\n },\n {\n id: 'W3',\n title: 'A pool thread finished a job',\n statement:\n 'The pool thread reports a trace event when the work function returns. The thread and the time are observed; the job is the one that thread started (rule W2b).',\n yields: 'inferred',\n platform: 'all',\n cites: [S.scheduleWork, S.worker],\n },\n {\n id: 'W4',\n title: 'The result of a pool job was delivered',\n statement:\n 'The pool thread appends the finished job to the loop\\'s done queue and wakes the loop; uv__work_done runs the after-work callbacks on the main thread in that order. The \"result delivered\" trace event with the job\\'s address marks this, and the callback of the owning item follows.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.worker, S.workDone, O.poolDone],\n },\n {\n id: 'W5',\n title: 'A job is waiting for a free pool thread',\n statement:\n 'A job was submitted while as many jobs as the pool has threads were running. It waits in the queue. This count is incomplete: file system requests and dns.lookup hold pool threads without reporting from them, and dns.lookup may use at most half of the threads.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.worker, S.post, S.initThreads],\n },\n {\n id: 'W6',\n title: 'File system requests and dns.lookup use the pool without thread reports',\n statement:\n 'Classic file system requests and dns.lookup are handed to the pool by libuv itself, not through ThreadPoolWork. Node reports their start and end on the main thread only. We show them as queued pool work; which thread ran them, and when, is not available on an official build.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.fsWorkUnix, S.fsWorkWin, S.getaddrinfoUnix, S.getaddrinfoWin, S.workSubmit],\n },\n {\n id: 'X1',\n title: 'The first use of the thread pool blocks the main thread',\n statement:\n 'The pool threads are created on the first submission, and the submitting thread waits until all of them have started. A gap on the main thread right after the first submission is this wait.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.workSubmit, S.initThreads],\n },\n {\n id: 'W7',\n title: 'The pool size is read when the pool is first used',\n statement:\n 'libuv creates the pool threads at the first submission and reads UV_THREADPOOL_SIZE only then (no value: 4 threads; 0 or text that is not a number: 1; at most 1024). A program can therefore still set the variable before its first pool request. The helper reads the variable when the first thread-pool-backed async item is created and reports the size when it differs from the one the run started with. A use of the pool that creates no such item (a native add-on, a worker thread) is not seen.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.initThreads, S.workSubmit],\n },\n {\n id: 'G1',\n title: 'Thread reports are missing for a pool job',\n statement:\n 'Every ThreadPoolWork job reports one start and one end from its pool thread. When a job was submitted and delivered but one of the two reports is absent, it was dropped while trace events were being read from the target. The job ran; its thread or times are not known.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.scheduleWork],\n },\n\n // ---- where items wait ---------------------------------------------------------------\n {\n id: 'QT',\n title: 'A new Timeout waits in the timer lists',\n statement:\n 'An async item of type Timeout was created. setTimeout and setInterval construct a Timeout and insert it into the timer lists in the same call, so the item is waiting in the timers queue.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.timeoutCtor, S.timerInsert],\n },\n {\n id: 'QT2',\n title: 'A repeating timer waits again after it ran',\n statement:\n 'The callback of a Timeout created by setInterval returned and the timer was not cleared. listOnTimeout inserts a repeating timer again after each run.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.listOnTimeout, S.timerInsert],\n },\n {\n id: 'QI',\n title: 'A new Immediate waits in the immediate queue',\n statement: 'An async item of type Immediate was created. The Immediate constructor appends itself to the immediate queue.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.immediateCtor, S.processImmediate, S.toggleImmediateRef],\n },\n {\n id: 'QK',\n title: 'A new TickObject waits in the nextTick queue',\n statement: 'An async item of type TickObject was created. process.nextTick pushes exactly one TickObject onto the tick queue per call.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.nextTick],\n },\n {\n id: 'QM',\n title: 'A queueMicrotask callback waits in the microtask queue',\n statement: 'An async item of type Microtask was created. queueMicrotask creates it and enqueues the callback on V8\\'s microtask queue in the same call.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.queueMicrotask, O.promiseReactionEnqueue],\n },\n {\n id: 'QP',\n title: 'A promise reaction is queued when its promise settles',\n statement:\n 'then, catch, finally and await register a reaction on a promise and create a second promise for it (async_hooks reports that one with the first as its trigger). V8 puts the reaction job on the microtask queue when the first promise settles, or at once when it has already settled. The helper sees settling through the promiseResolve hook, which fires on fulfil and reject and not when a promise is merely resolved with another promise. So the reaction is shown in the microtask queue from the later of the two moments, creation and settling, until its callback starts. A promise that is only created while another promise\\'s callback runs is not a reaction (its trigger is the running callback); neither is a promise that settles or runs before its trigger has settled (the wrapper an await makes around a plain value). Reactions of a promise whose settling was not seen are not shown as queued; they simply run.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.promiseInitHook, O.performPromiseThen, O.triggerReactions, O.promiseReactionEnqueue],\n },\n {\n id: 'QP2',\n title: 'A reaction that was shown as queued did not run in its turn',\n statement:\n 'The microtask queue is first-in first-out and is emptied completely before the next timer, immediate or I/O callback. When a reaction that rule QP put in the queue is overtaken by a later microtask, or is still listed when such a callback starts, it was not in the queue: rule QP was wrong for this promise. The entry is removed here rather than left standing.',\n yields: 'inferred',\n platform: 'all',\n cites: [O.promiseReactionEnqueue, O.triggerReactions],\n },\n {\n id: 'QW',\n title: 'A new thread-pool-backed request waits for the pool',\n statement:\n 'An async item of a thread-pool-backed type was created (FSREQCALLBACK, FSREQPROMISE, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, a crypto *REQUEST, zlib). Node creates the item and submits the work in the same call, so the request is with the thread pool until its callback starts.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.workSubmit, S.scheduleWork, O.poolSubmit],\n },\n {\n id: 'QR',\n title: 'A new one-shot I/O request waits on the operating system',\n statement:\n 'An async item of a one-shot request type was created (a connect, write or shutdown request). It waits for the operating system until its callback starts.',\n yields: 'inferred',\n platform: 'all',\n cites: [O.phasePoll, O.makeCallback],\n },\n {\n id: 'QX',\n title: 'A waiting item went away without running',\n statement:\n 'An item that was waiting was reported as destroyed before any callback of it started (for example clearTimeout, clearImmediate or clearInterval). It left its queue.',\n yields: 'inferred',\n platform: 'all',\n cites: [S.timeoutCtor, S.immediateCtor],\n },\n];\n\n/**\n * Entries that explain what the helper relies on but that no event carries:\n * background, not rules. (They used to sit in RULES; an id here never appears\n * in an event's `rule`.)\n */\nconst BACKGROUND_IDS: ReadonlySet<string> = new Set(['C0', 'T2', 'I2', 'L1', 'W2', 'W4', 'W5', 'W6', 'X1']);\n\n/** The rules: exactly the ids that code writes into events (the helper's rule stage and sources, and the replay package for K1 and M1). */\nexport const RULES: readonly Rule[] = ENTRIES.filter((r) => !BACKGROUND_IDS.has(r.id));\n\n/** Background explanations: same shape as a rule, never the `rule` of an event. */\nexport const BACKGROUND: readonly Rule[] = ENTRIES.filter((r) => BACKGROUND_IDS.has(r.id));\n\nconst BY_ID = new Map<string, Rule>(RULES.map((r) => [r.id, r]));\n\n/** The rule with this id, or undefined. */\nexport function ruleById(id: string): Rule | undefined {\n return BY_ID.get(id);\n}\n\n/** True when `id` names a rule of this registry. */\nexport function isRuleId(id: string): boolean {\n return BY_ID.has(id);\n}\n\n/** Every atlas id cited by any rule, sorted, without duplicates. */\nexport function allCitedIds(): string[] {\n const ids = new Set<string>();\n for (const r of ENTRIES) for (const c of r.cites) ids.add(c);\n return [...ids].sort();\n}\n\n/**\n * async_hooks types whose work runs on the libuv thread pool. Crypto request\n * types all end in \"REQUEST\".\n */\nexport function isPoolBackedType(type: string): boolean {\n return POOL_BACKED.has(type);\n}\n\n/**\n * The async_hooks types whose work runs on the libuv thread pool, by name\n * (src/async_wrap.h at the tag lists every provider). Not a rule on the\n * name: HTTPCLIENTREQUEST also ends in \"REQUEST\" and has nothing to do with\n * the pool.\n */\nexport const POOL_BACKED_TYPES: readonly string[] = [\n // file system requests (uv_fs_* with a callback) and dns.lookup (uv_getaddrinfo, uv_getnameinfo)\n 'FSREQCALLBACK', 'FSREQPROMISE', 'FILEHANDLECLOSEREQ', 'GETADDRINFOREQWRAP', 'GETNAMEINFOREQWRAP',\n // compression streams: zlib, brotli and zstd streams all use the provider ZLIB\n 'ZLIB',\n // crypto jobs (CryptoJob is a ThreadPoolWork)\n 'ARGON2REQUEST', 'CHECKPRIMEREQUEST', 'CIPHERREQUEST', 'DERIVEBITSREQUEST', 'HASHREQUEST', 'KEYEXPORTREQUEST', 'KEYGENREQUEST', 'KEYPAIRGENREQUEST',\n 'PBKDF2REQUEST', 'RANDOMBYTESREQUEST', 'RANDOMPRIMEREQUEST', 'SCRYPTREQUEST', 'SIGNREQUEST', 'VERIFYREQUEST',\n];\nconst POOL_BACKED: ReadonlySet<string> = new Set(POOL_BACKED_TYPES);\n\n/** Provider types whose name ends in \"REQUEST\" and that are not thread pool work. */\nexport const NOT_POOL_REQUEST_TYPES: readonly string[] = ['HTTPCLIENTREQUEST'];\n\n/** One-shot request types that wait on the operating system (rule QR). */\nexport function isIoRequestType(type: string): boolean {\n return type === 'TCPCONNECTWRAP' || type === 'PIPECONNECTWRAP' || type === 'WRITEWRAP' || type === 'SHUTDOWNWRAP' || type === 'UDPSENDWRAP';\n}\n\n/** Which queue a new item of this type waits in, with the rule that says so. Undefined: none we can name. */\nexport function queueOfNewItem(type: string, _triggerType?: string): { queue: 'nextTick' | 'microtask' | 'timers' | 'immediate' | 'pool' | 'io'; rule: string } | undefined {\n if (type === 'Timeout') return { queue: 'timers', rule: 'QT' };\n if (type === 'Immediate') return { queue: 'immediate', rule: 'QI' };\n if (type === 'TickObject') return { queue: 'nextTick', rule: 'QK' };\n if (type === 'Microtask') return { queue: 'microtask', rule: 'QM' };\n // Promise reactions (rule QP) depend on when the trigger settles and on what\n // was running: the helper's rule stage decides them, not the type alone.\n if (type === 'PROMISE') return undefined;\n if (isPoolBackedType(type)) return { queue: 'pool', rule: 'QW' };\n if (isIoRequestType(type)) return { queue: 'io', rule: 'QR' };\n return undefined;\n}\n","/**\n * The reducer: the small, fast-changing part of the view state (\"live\"\n * state) and the one function that advances it by one event.\n *\n * Rules the reducer follows:\n *\n * - It reflects events; it does not know how Node works. Where it has to\n * conclude something itself (see rules.ts) the result is marked inferred\n * with a \"replay:\" rule id.\n * - It never shows a state the events contradict. When a later event\n * disagrees with what is on screen (a new phase starts while another is\n * still shown, a thread starts a job while it shows another), the later\n * event wins and the disagreement is counted in `inconsistent`.\n * - It never throws on input. Unknown kinds and malformed events were\n * flagged by the index and are only counted here.\n *\n * The live state holds ids and event indexes, not copies of event data:\n * details are read from the event list when a view is built (view.ts). That\n * keeps a keyframe (a copy of this state) small.\n *\n * Internal, except for the three constants re-exported by index.ts.\n */\n\nimport type { NmEvent, PoolWorkKind } from '@nodejs-map/event-format';\nimport { isIoRequestType, isPoolBackedType } from '@nodejs-map/event-format';\nimport type { RunStatus } from './types.ts';\nimport {\n F_SKIP,\n F_UNKNOWN,\n T_CLEARED,\n T_DONE,\n T_NONE,\n T_RUNNING,\n T_WAITING,\n lastBelow,\n phaseCode,\n queueCode,\n} from './run-index.ts';\nimport type { ItemRec, RunIndex } from './run-index.ts';\n\nexport { SIGNAL_KINDS } from './run-index.ts';\n\n/**\n * async_hooks types of libuv handles: things that call back many times\n * (a server accepts many connections, a socket reads many chunks). When one\n * of them waits in the \"io\" queue it stays there across its callbacks, until\n * `item.gone` or a `queue.remove` (rule \"replay:handle\"). Every other item\n * leaves its queue when its callback starts, as the event format says.\n *\n * The list is the provider types of the classes that derive from HandleWrap\n * in Node's src/ at v26.13.1 (tcp_wrap.h, pipe_wrap.h, tty_wrap.cc,\n * udp_wrap.h, process_wrap.cc, signal_wrap.cc, fs_event_wrap.cc,\n * node_stat_watcher.h, node_messaging.h), checked against that tag.\n */\nexport const PERSISTENT_HANDLE_TYPES: ReadonlySet<string> = new Set([\n 'TCPWRAP',\n 'TCPSERVERWRAP',\n 'PIPEWRAP',\n 'PIPESERVERWRAP',\n 'TTYWRAP',\n 'UDPWRAP',\n 'PROCESSWRAP',\n 'SIGNALWRAP',\n 'FSEVENTWRAP',\n 'STATWATCHER',\n 'MESSAGEPORT',\n]);\n\n/**\n * A finished pool job normally leaves the \"done\" list when the callback of\n * its item starts. A job that was never tied to an item has no such moment\n * (the format has no \"delivered\" event), so it would stay forever. We keep\n * the most recent ones, flagged as untied (PoolJobView.item is null), and\n * drop the oldest beyond this number. The count of dropped ones is shown.\n */\nexport const UNLINKED_DONE_LIMIT = 32;\n\n/** How many finished or cleared timers the live state remembers for display. */\nexport const RECENT_TIMERS = 32;\n\n// ---- pieces of the live state -------------------------------------------------\n// All of them are immutable once made: a change replaces the object. That is\n// what lets a keyframe copy arrays and maps without copying their entries.\n\nexport interface QEntry {\n readonly id: number;\n /** Index of the `queue.add`. */\n readonly index: number;\n /** Callbacks started while it stayed (persistent handles). */\n readonly runs: number;\n}\n\n/** A queue in arrival order. Removal at the front only moves `head`. */\nexport interface QueueL {\n items: QEntry[];\n head: number;\n}\n\nexport const VIA_UNKNOWN = 0;\nexport const VIA_PHASE = 1;\nexport const VIA_TICK = 2;\nexport const VIA_MICRO = 3;\n\nexport interface FrameL {\n readonly id: number;\n /** Index of the `callback.start`. */\n readonly index: number;\n readonly via: number;\n /** Index of the `queue.add` that tells us `via`; -1 when `via` comes from the item's type (rule `viaRule`). */\n readonly viaIndex: number;\n readonly viaRule: string | null;\n /** Queue code the item left, or -1. */\n readonly queue: number;\n readonly phase: number;\n readonly phaseIndex: number;\n readonly depth: number;\n /**\n * Index of the latest event inside this callback that has a source\n * location (an `output` or an `item.new` with `loc`), or -1. Kept per\n * frame so that the spot of an outer callback comes back when an inner one\n * ends.\n */\n readonly srcIndex: number;\n}\n\nexport const JOB_WAITING = 0;\nexport const JOB_RUNNING = 1;\nexport const JOB_FINISHED = 2;\nexport const JOB_POSTED = 3;\n\nexport interface JobL {\n readonly job: string;\n readonly kind: PoolWorkKind;\n readonly op: string | null;\n /** Item id, or -1. */\n readonly id: number;\n readonly linkIndex: number;\n readonly state: number;\n /** Display thread index, or 0. */\n readonly thread: number;\n readonly queuedIndex: number;\n readonly startedIndex: number;\n readonly finishedIndex: number;\n readonly postedIndex: number;\n /** True while the job is in the done list. */\n readonly done: boolean;\n /** Index of the latest pool event of this job that carried an atlas id, or -1. */\n readonly atIndex: number;\n}\n\nexport interface ThreadL {\n readonly job: string | null;\n readonly tid: number;\n readonly jobs: number;\n}\n\nexport interface TidL {\n readonly tid: number;\n readonly busy: boolean;\n readonly name: string;\n readonly index: number;\n readonly starts: number;\n readonly ends: number;\n}\n\nexport interface Live {\n // run\n status: RunStatus;\n /** Index of `run.start` / `run.end`, or -1. */\n startIndex: number;\n endIndex: number;\n // main thread\n mainScript: boolean;\n /** The same as FrameL.srcIndex, for the main script. */\n mainSrcIndex: number;\n /** Index of the event after which the thread had nothing to run, or -1. */\n idleIndex: number;\n stack: FrameL[];\n // loop\n turn: number;\n turnIndex: number;\n phase: number;\n phaseIndex: number;\n lastPhase: number;\n lastPhaseEntered: number;\n lastPhaseLeft: number;\n /** Index of the latest `phase.enter` that told the poll timeout, or -1. */\n pollIndex: number;\n scopeIndex: number;\n sampleIndex: number;\n // queues\n queues: QueueL[];\n /** Item id -> bit mask of the queues it is in. */\n where: Map<number, number>;\n // timers\n timersActive: Set<number>;\n timersRecent: number[];\n tSet: number;\n tWaiting: number;\n tRunning: number;\n tDone: number;\n tCleared: number;\n firedCount: number;\n firedIndex: number;\n // pool\n /** Index of the latest `pool.size`, or -1: the size is the one of `run.start`. */\n poolSizeIndex: number;\n threads: ThreadL[];\n jobs: Map<string, JobL>;\n poolWaiting: string[];\n poolDone: string[];\n /** How many jobs in the done list belong to no known item. */\n doneUntied: number;\n tids: Map<number, TidL>;\n pQueued: number;\n pStarted: number;\n pFinished: number;\n pPosted: number;\n pDelivered: number;\n pCancelled: number;\n pDropped: number;\n /**\n * True when this binary reports `pool.posted` (the probe build: capability\n * poolThreads \"live\", or such an event was seen). Then a finished job stays\n * on its thread until it is posted. Otherwise the thread is free at\n * `pool.finished`.\n */\n poolPosts: boolean;\n // output, notes\n outputCount: number;\n noteCount: number;\n // debugger\n paused: boolean;\n pausedIndex: number;\n lastPausedIndex: number;\n lastResumedIndex: number;\n pauses: number;\n gateStopped: boolean;\n gateIndex: number;\n gateReleasedIndex: number;\n gateStops: number;\n clockFrozen: boolean;\n clockIndex: number;\n clockUnfrozenIndex: number;\n hiddenMs: number;\n // focus\n focusIndex: number;\n // problems\n unknown: number;\n malformed: number;\n inconsistent: number;\n}\n\nexport function createLive(): Live {\n const queues: QueueL[] = [];\n for (let q = 0; q < 7; q++) queues.push({ items: [], head: 0 });\n return {\n status: 'idle',\n startIndex: -1,\n endIndex: -1,\n mainScript: false,\n mainSrcIndex: -1,\n idleIndex: -1,\n stack: [],\n turn: -1,\n turnIndex: -1,\n phase: 0,\n phaseIndex: -1,\n lastPhase: 0,\n lastPhaseEntered: -1,\n lastPhaseLeft: -1,\n pollIndex: -1,\n scopeIndex: -1,\n sampleIndex: -1,\n queues,\n where: new Map(),\n timersActive: new Set(),\n timersRecent: [],\n tSet: 0,\n tWaiting: 0,\n tRunning: 0,\n tDone: 0,\n tCleared: 0,\n firedCount: 0,\n firedIndex: -1,\n poolSizeIndex: -1,\n threads: [],\n jobs: new Map(),\n poolWaiting: [],\n poolDone: [],\n doneUntied: 0,\n tids: new Map(),\n pQueued: 0,\n pStarted: 0,\n pFinished: 0,\n pPosted: 0,\n pDelivered: 0,\n pCancelled: 0,\n pDropped: 0,\n poolPosts: false,\n outputCount: 0,\n noteCount: 0,\n paused: false,\n pausedIndex: -1,\n lastPausedIndex: -1,\n lastResumedIndex: -1,\n pauses: 0,\n gateStopped: false,\n gateIndex: -1,\n gateReleasedIndex: -1,\n gateStops: 0,\n clockFrozen: false,\n clockIndex: -1,\n clockUnfrozenIndex: -1,\n hiddenMs: 0,\n focusIndex: -1,\n unknown: 0,\n malformed: 0,\n inconsistent: 0,\n };\n}\n\n/** An independent copy. Entries are shared (they are immutable); containers are copied. */\nexport function cloneLive(s: Live): Live {\n const queues: QueueL[] = [];\n for (const q of s.queues) queues.push({ items: q.head === 0 ? q.items.slice() : q.items.slice(q.head), head: 0 });\n return {\n ...s,\n stack: s.stack.slice(),\n queues,\n where: new Map(s.where),\n timersActive: new Set(s.timersActive),\n timersRecent: s.timersRecent.slice(),\n threads: s.threads.slice(),\n jobs: new Map(s.jobs),\n poolWaiting: s.poolWaiting.slice(),\n poolDone: s.poolDone.slice(),\n tids: new Map(s.tids),\n };\n}\n\n/** Roughly how many container slots a copy of this state has: the cost of a keyframe. */\nexport function liveSize(s: Live): number {\n let n = 64 + s.stack.length + s.where.size * 2 + s.timersActive.size + s.timersRecent.length + s.threads.length + s.jobs.size * 2 + s.poolWaiting.length + s.poolDone.length + s.tids.size * 2;\n for (const q of s.queues) n += q.items.length - q.head;\n return n;\n}\n\n// ---- queue helpers ------------------------------------------------------------\n\nfunction queuePush(live: Live, q: number, entry: QEntry): void {\n (live.queues[q] as QueueL).items.push(entry);\n live.where.set(entry.id, (live.where.get(entry.id) ?? 0) | (1 << q));\n}\n\nfunction queueFind(queue: QueueL, id: number): number {\n const items = queue.items;\n for (let k = queue.head; k < items.length; k++) if ((items[k] as QEntry).id === id) return k;\n return -1;\n}\n\n/** Remove item `id` from queue `q`. Returns its entry, or null when it was not there. */\nfunction queueTake(live: Live, q: number, id: number): QEntry | null {\n const mask = live.where.get(id);\n if (mask === undefined || (mask & (1 << q)) === 0) return null;\n const queue = live.queues[q] as QueueL;\n const k = queueFind(queue, id);\n const rest = mask & ~(1 << q);\n if (rest === 0) live.where.delete(id);\n else live.where.set(id, rest);\n if (k < 0) return null;\n const entry = queue.items[k] as QEntry;\n if (k === queue.head) {\n // The usual case: queues drain from the front. Moving `head` instead of\n // shifting the array keeps a long drain linear.\n queue.head++;\n if (queue.head === queue.items.length) {\n queue.items = [];\n queue.head = 0;\n } else if (queue.head >= 1024 && queue.head * 2 >= queue.items.length) {\n queue.items = queue.items.slice(queue.head);\n queue.head = 0;\n }\n } else {\n queue.items.splice(k, 1);\n }\n return entry;\n}\n\nfunction inStack(live: Live, id: number): boolean {\n const stack = live.stack;\n for (let k = stack.length - 1; k >= 0; k--) if ((stack[k] as FrameL).id === id) return true;\n return false;\n}\n\n// ---- timers ---------------------------------------------------------------------\n\nfunction timerCount(live: Live, state: number, d: number): void {\n if (state === T_WAITING) live.tWaiting += d;\n else if (state === T_RUNNING) live.tRunning += d;\n else if (state === T_DONE) live.tDone += d;\n else if (state === T_CLEARED) live.tCleared += d;\n}\n\n/**\n * Bring the timer bookkeeping of one item up to date after event `i`.\n * `before` is the timer's state before the event. Both states come from the\n * same function of the index, so counts, lists and TimerView.state agree.\n */\nfunction timerMoved(live: Live, index: RunIndex, rec: ItemRec, before: number, i: number): void {\n const after = index.timerStateAt(rec, i + 1, inStack(live, rec.id));\n if (after === before) return;\n if (before === T_NONE) live.tSet++;\n timerCount(live, before, -1);\n timerCount(live, after, 1);\n const activeAfter = after === T_WAITING || after === T_RUNNING;\n const activeBefore = before === T_WAITING || before === T_RUNNING;\n if (activeAfter && !activeBefore) {\n live.timersActive.add(rec.id);\n const k = live.timersRecent.indexOf(rec.id);\n if (k >= 0) live.timersRecent.splice(k, 1);\n } else if (!activeAfter) {\n live.timersActive.delete(rec.id);\n const k = live.timersRecent.indexOf(rec.id);\n if (k >= 0) live.timersRecent.splice(k, 1);\n live.timersRecent.push(rec.id);\n if (live.timersRecent.length > RECENT_TIMERS) live.timersRecent.shift();\n }\n}\n\n/**\n * The timers among `frames` (callbacks about to leave the stack), each once,\n * with its state at position `i`, to hand to timerMoved after the stack changed.\n */\nfunction stackTimers(live: Live, index: RunIndex, frames: readonly FrameL[], i: number): [ItemRec, number][] {\n const out: [ItemRec, number][] = [];\n for (const f of frames) {\n const rec = index.items.get(f.id);\n if (rec === undefined || rec.timer === null) continue;\n let seen = false;\n for (const o of out) if (o[0] === rec) seen = true;\n if (!seen) out.push([rec, index.timerStateAt(rec, i, true)]);\n }\n return out;\n}\n\n// ---- pool -----------------------------------------------------------------------\n\nfunction dropFrom(list: string[], job: string): boolean {\n const k = list.indexOf(job);\n if (k < 0) return false;\n list.splice(k, 1);\n return true;\n}\n\nfunction ensureThread(live: Live, thread: number): void {\n while (live.threads.length < thread) live.threads.push({ job: null, tid: -1, jobs: 0 });\n}\n\n/** Take a job out of wherever it is shown: the waiting list, its thread, the done list. Its record stays. */\nfunction detach(live: Live, job: JobL): void {\n if (job.state === JOB_WAITING) {\n dropFrom(live.poolWaiting, job.job);\n return;\n }\n const th = job.thread > 0 ? live.threads[job.thread - 1] : undefined;\n if (th !== undefined && th.job === job.job) live.threads[job.thread - 1] = { job: null, tid: th.tid, jobs: th.jobs };\n if (job.done) doneRemove(live, job);\n}\n\n/** Put a job at the end of the done list. */\nfunction doneAdd(live: Live, job: JobL): void {\n live.jobs.set(job.job, job.done ? job : { ...job, done: true });\n live.poolDone.push(job.job);\n if (job.id < 0) live.doneUntied++;\n}\n\n/** Take a job out of the done list (its record is left to the caller). */\nfunction doneRemove(live: Live, job: JobL): void {\n if (!dropFrom(live.poolDone, job.job)) return;\n if (job.id < 0) live.doneUntied--;\n}\n\n/** Thread `thread` now holds job `name`. `started`: count it as a job the thread started. */\nfunction occupy(live: Live, thread: number, name: string, tid: number | undefined, started: boolean): void {\n ensureThread(live, thread);\n const th = live.threads[thread - 1] as ThreadL;\n if (th.job !== null && th.job !== name) {\n // The thread was shown with another job that never reported its end.\n // One thread holds one job: the old one is no longer there.\n live.inconsistent++;\n live.jobs.delete(th.job);\n }\n live.threads[thread - 1] = { job: name, tid: tid === undefined ? th.tid : tid, jobs: th.jobs + (started ? 1 : 0) };\n}\n\n/**\n * The callback of an item started, or the item went away: the results of\n * its pool jobs have reached the loop (rule \"replay:delivered\").\n *\n * - A job in the done list leaves it.\n * - A job that still shows as waiting leaves too. File system requests and\n * dns.lookup run on the pool without any report from the thread (rule W6\n * of the event format): their job is only ever \"queued\", and the callback\n * is the one sign that the work was done.\n * - A job shown on a thread stays until that thread reports its end: the\n * report is on its way (thread-side times are approximate), and when it\n * arrives finishJob sees that the callback has already run.\n *\n * The item's jobs are found through the index (the names tied to it before\n * this event), so nothing is searched when the item has none.\n */\nfunction deliver(live: Live, rec: ItemRec, i: number): void {\n const names = rec.jobNames;\n for (let k = 0; k < names.length && (rec.jobIndexes[k] as number) < i; k++) {\n const job = live.jobs.get(names[k] as string);\n if (job === undefined || job.id !== rec.id) continue;\n if (job.state === JOB_WAITING) dropFrom(live.poolWaiting, job.job);\n else if (job.done) doneRemove(live, job);\n else continue;\n live.jobs.delete(job.job);\n live.pDelivered++;\n }\n}\n\n/** A finished job joins the done list, unless its result evidently arrived already. */\nfunction finishJob(live: Live, index: RunIndex, job: JobL, i: number): void {\n if (job.id >= 0) {\n const rec = index.items.get(job.id);\n // Thread-side times are approximate against the main thread (`tq`), so\n // \"finished\" can land after the callback that consumed the result. The\n // callback is the stronger fact: the result was delivered.\n const since = job.queuedIndex >= 0 ? job.queuedIndex : job.startedIndex;\n if (rec !== undefined && ((rec.goneIndex >= 0 && rec.goneIndex <= i) || lastBelow(rec.starts, i + 1) > since)) {\n live.jobs.delete(job.job);\n live.pDelivered++;\n return;\n }\n }\n doneAdd(live, job);\n // Jobs of no known item can never be seen leaving; keep only the latest few (see UNLINKED_DONE_LIMIT).\n for (let k = 0; live.doneUntied > UNLINKED_DONE_LIMIT && k < live.poolDone.length; ) {\n const name = live.poolDone[k] as string;\n if ((live.jobs.get(name) as JobL).id < 0) {\n live.poolDone.splice(k, 1);\n live.jobs.delete(name);\n live.pDropped++;\n live.doneUntied--;\n } else k++;\n }\n}\n\n// ---- callbacks ----------------------------------------------------------------------\n\n/** Which rule lets us say how a callback of this type got onto the main thread, when the item was in no queue. */\nfunction viaFromType(type: string, platform: string): { via: number; rule: string } | null {\n if (type === 'TickObject') return { via: VIA_TICK, rule: 'K1' };\n if (type === 'PROMISE' || type === 'Microtask') return { via: VIA_MICRO, rule: 'M1' };\n if (type === 'Timeout') return { via: VIA_PHASE, rule: 'T1' };\n if (type === 'Immediate') return { via: VIA_PHASE, rule: 'I1' };\n if (isPoolBackedType(type)) return { via: VIA_PHASE, rule: platform === 'win32' ? 'P1w' : 'P1u' };\n if (isIoRequestType(type) || PERSISTENT_HANDLE_TYPES.has(type)) return { via: VIA_PHASE, rule: 'P2' };\n // Anything else (a user AsyncResource, for example) can be run from anywhere.\n return null;\n}\n\nfunction setStatus(live: Live): void {\n if (live.endIndex >= 0) live.status = 'ended';\n else if (live.startIndex < 0) live.status = 'idle';\n else if (live.paused) live.status = 'paused';\n else if (live.gateStopped) live.status = 'gate';\n else live.status = 'running';\n}\n\nfunction leavePhase(live: Live, i: number): void {\n if (live.phase === 0) return;\n live.lastPhase = live.phase;\n live.lastPhaseEntered = live.phaseIndex;\n live.lastPhaseLeft = i;\n live.phase = 0;\n live.phaseIndex = -1;\n}\n\n/**\n * The event at `i` has a source location: it is the latest located thing in\n * the JavaScript that is running now (the innermost callback, or the main\n * script). When no JavaScript is running the event locates nothing.\n */\nfunction located(live: Live, i: number): void {\n const top = live.stack.length - 1;\n if (top >= 0) live.stack[top] = { ...(live.stack[top] as FrameL), srcIndex: i };\n else if (live.mainScript) live.mainSrcIndex = i;\n}\n\n/** The loop did something: the main script is over. */\nfunction loopActivity(live: Live, i: number): void {\n if (live.mainScript) {\n live.mainScript = false;\n if (live.stack.length === 0) live.idleIndex = i;\n }\n}\n\n/**\n * Apply the event at index `i` to `live`. `flags` are the event's flags from\n * the index, which must already contain this event. `events` is the whole\n * list (earlier events are read for details such as the platform).\n *\n * Returns 1 + the TIMELINE_CLASSES index this event counts as, or 0.\n */\nexport function applyEvent(live: Live, e: NmEvent, i: number, flags: number, index: RunIndex, events: readonly NmEvent[]): number {\n if ((flags & F_SKIP) !== 0) {\n if ((flags & F_UNKNOWN) !== 0) live.unknown++;\n else live.malformed++;\n return 0;\n }\n if (e.at !== undefined && e.at !== '') live.focusIndex = i;\n let cls = 0;\n\n switch (e.k) {\n case 'run.start': {\n if (live.startIndex >= 0) live.inconsistent++;\n live.startIndex = i;\n live.endIndex = -1;\n live.mainScript = true;\n live.mainSrcIndex = -1;\n live.poolPosts = e.caps.poolThreads === 'live';\n live.poolSizeIndex = -1;\n const size = Math.max(0, Math.min(1024, Math.floor(e.poolSize)));\n ensureThread(live, size);\n setStatus(live);\n break;\n }\n case 'run.end': {\n live.endIndex = i;\n // Nothing runs in a process that has exited. Queues and pool lists are\n // left as they were: that is what never got to run.\n const cut = stackTimers(live, index, live.stack, i);\n if (live.stack.length > 0) live.stack = [];\n for (const [rec, before] of cut) timerMoved(live, index, rec, before, i);\n live.mainScript = false;\n live.idleIndex = i;\n leavePhase(live, i);\n if (live.paused) {\n live.paused = false;\n live.lastPausedIndex = live.pausedIndex;\n live.lastResumedIndex = -1;\n }\n live.gateStopped = false;\n live.clockFrozen = false;\n setStatus(live);\n break;\n }\n case 'output':\n if (e.loc !== undefined) located(live, i);\n live.outputCount++;\n cls = e.stream === 'stdout' ? 9 : 10;\n break;\n case 'item.new': {\n if (e.loc !== undefined) located(live, i);\n const rec = index.items.get(e.id);\n if (rec !== undefined && rec.newIndex !== i) live.inconsistent++; // a second item.new for the same id\n break;\n }\n case 'callback.start': {\n const rec = index.items.get(e.id) as ItemRec;\n const timerBefore = index.timerStateAt(rec, i, inStack(live, e.id));\n live.mainScript = false;\n const depth = live.stack.length;\n // The type as this very event states it, so that applying the event\n // again later (after a jump) cannot come out differently.\n const type = e.type;\n let via = VIA_UNKNOWN;\n let viaIndex = -1;\n let viaRule: string | null = null;\n let queue = -1;\n const mask = live.where.get(e.id);\n if (mask !== undefined) {\n for (let q = 0; q < 7; q++) {\n if ((mask & (1 << q)) === 0) continue;\n if (q === 5 && PERSISTENT_HANDLE_TYPES.has(type)) {\n // A handle stays in \"io\" across its callbacks.\n const io = live.queues[5] as QueueL;\n const k = queueFind(io, e.id);\n if (k >= 0) {\n const entry = io.items[k] as QEntry;\n io.items[k] = { id: entry.id, index: entry.index, runs: entry.runs + 1 };\n if (queue < 0) {\n queue = q;\n viaIndex = entry.index;\n }\n }\n continue;\n }\n const entry = queueTake(live, q, e.id);\n if (entry !== null && queue < 0) {\n queue = q;\n viaIndex = entry.index;\n }\n }\n }\n if (queue >= 0) {\n via = queue === 0 ? VIA_TICK : queue === 1 ? VIA_MICRO : VIA_PHASE;\n } else {\n const start = live.startIndex >= 0 ? events[live.startIndex] : undefined;\n const platform = start !== undefined && start.k === 'run.start' ? start.node.platform : '';\n const guess = viaFromType(type, platform);\n if (guess !== null) {\n via = guess.via;\n viaRule = guess.rule;\n }\n }\n live.stack.push({ id: e.id, index: i, via, viaIndex, viaRule, queue, phase: depth === 0 ? live.phase : 0, phaseIndex: depth === 0 ? live.phaseIndex : -1, depth, srcIndex: -1 });\n deliver(live, rec, i);\n if (timerBefore !== T_NONE) timerMoved(live, index, rec, timerBefore, i);\n cls = queue >= 0 ? queue + 1 : 8;\n break;\n }\n case 'callback.end': {\n const stack = live.stack;\n let k = stack.length - 1;\n while (k >= 0 && (stack[k] as FrameL).id !== e.id) k--;\n if (k < 0) {\n live.inconsistent++; // an end without a start\n break;\n }\n if (k !== stack.length - 1) live.inconsistent++; // callbacks above it never ended; they cannot still be running\n const closing = stack.slice(k);\n const moved = stackTimers(live, index, closing, i);\n stack.length = k;\n if (k === 0) live.idleIndex = i;\n for (const [rec, before] of moved) timerMoved(live, index, rec, before, i);\n break;\n }\n case 'item.gone': {\n const rec = index.items.get(e.id) as ItemRec;\n const timerBefore = index.timerStateAt(rec, i, inStack(live, e.id));\n const mask = live.where.get(e.id);\n if (mask !== undefined) for (let q = 0; q < 7; q++) if ((mask & (1 << q)) !== 0) queueTake(live, q, e.id);\n deliver(live, rec, i);\n if (timerBefore !== T_NONE) timerMoved(live, index, rec, timerBefore, i);\n break;\n }\n case 'promise.settled':\n break;\n case 'timer.set': {\n const rec = index.items.get(e.id) as ItemRec;\n if (rec.timer !== null && rec.timer.setIndex !== i) live.inconsistent++; // set twice: the index treats it as armed again\n timerMoved(live, index, rec, index.timerStateAt(rec, i, inStack(live, e.id)), i);\n break;\n }\n case 'loop.sample':\n live.sampleIndex = i;\n break;\n case 'scope':\n // Node reports these two from inside the loop: the main script is over.\n if (e.name === 'RunTimers' || e.name === 'CheckImmediate') loopActivity(live, i);\n live.scopeIndex = i;\n break;\n case 'pool.thread': {\n if (e.tid === undefined) break;\n const old = live.tids.get(e.tid);\n const starts = (old === undefined ? 0 : old.starts) + (e.edge === 'start' ? 1 : 0);\n const ends = (old === undefined ? 0 : old.ends) + (e.edge === 'end' ? 1 : 0);\n live.tids.set(e.tid, { tid: e.tid, busy: e.edge === 'start', name: e.name, index: i, starts, ends });\n break;\n }\n case 'signal':\n break;\n case 'queue.add': {\n const q = queueCode(e.queue);\n const rec = index.items.get(e.id) as ItemRec;\n const timerBefore = q === 2 ? index.timerStateAt(rec, i, inStack(live, e.id)) : T_NONE;\n const mask = live.where.get(e.id) ?? 0;\n // Already there (a handle the helper reports again): one entry, waiting since the first report.\n if ((mask & (1 << q)) === 0) queuePush(live, q, { id: e.id, index: i, runs: 0 });\n if (timerBefore !== T_NONE) timerMoved(live, index, rec, timerBefore, i);\n break;\n }\n case 'queue.remove': {\n const q = queueCode(e.queue);\n const rec = index.items.get(e.id);\n const timerBefore = q === 2 && rec !== undefined ? index.timerStateAt(rec, i, inStack(live, e.id)) : T_NONE;\n queueTake(live, q, e.id);\n if (rec !== undefined && timerBefore !== T_NONE) timerMoved(live, index, rec, timerBefore, i);\n break;\n }\n case 'loop.turn':\n loopActivity(live, i);\n // A new turn: the phase shown from the turn before is over.\n leavePhase(live, i);\n live.turn = e.n;\n live.turnIndex = i;\n break;\n case 'phase.enter': {\n loopActivity(live, i);\n leavePhase(live, i);\n live.phase = phaseCode(e.phase);\n live.phaseIndex = i;\n if (e.pollTimeoutMs !== undefined) live.pollIndex = i;\n if (e.turn !== undefined && e.turn !== live.turn) {\n live.turn = e.turn;\n live.turnIndex = i;\n }\n break;\n }\n case 'phase.leave': {\n const p = phaseCode(e.phase);\n if (live.phase === p) leavePhase(live, i);\n else if (live.phase === 0) {\n // We did not see it start.\n live.lastPhase = p;\n live.lastPhaseEntered = -1;\n live.lastPhaseLeft = i;\n } else live.inconsistent++; // leaving a phase that is not the one shown; the shown one started later, keep it\n break;\n }\n case 'timer.fired':\n loopActivity(live, i);\n live.firedCount++;\n live.firedIndex = i;\n break;\n case 'pool.queued': {\n const old = live.jobs.get(e.job);\n if (old !== undefined) {\n // The same job name twice: the new report replaces the old job.\n live.inconsistent++;\n detach(live, old);\n }\n live.jobs.set(e.job, {\n job: e.job,\n kind: e.kind,\n op: e.op === undefined ? null : e.op,\n id: e.id === undefined ? -1 : e.id,\n linkIndex: e.id === undefined ? -1 : i,\n state: JOB_WAITING,\n thread: 0,\n queuedIndex: i,\n startedIndex: -1,\n finishedIndex: -1,\n postedIndex: -1,\n done: false,\n atIndex: e.at === undefined ? -1 : i,\n });\n live.poolWaiting.push(e.job);\n live.pQueued++;\n cls = 12;\n break;\n }\n case 'pool.started': {\n let job = live.jobs.get(e.job);\n if (job === undefined) {\n // Started without a \"queued\" report (reports can be lost, rule G1): show what we know.\n job = { job: e.job, kind: 'unknown', op: null, id: -1, linkIndex: -1, state: JOB_WAITING, thread: 0, queuedIndex: -1, startedIndex: -1, finishedIndex: -1, postedIndex: -1, done: false, atIndex: -1 };\n } else {\n if (job.state !== JOB_WAITING) live.inconsistent++; // started twice, or after it finished\n detach(live, job);\n }\n occupy(live, e.thread, e.job, e.tid, true);\n live.jobs.set(e.job, { ...job, state: JOB_RUNNING, thread: e.thread, startedIndex: i, done: false, atIndex: e.at === undefined ? job.atIndex : i });\n live.pStarted++;\n cls = 12;\n break;\n }\n case 'pool.finished': {\n let job = live.jobs.get(e.job);\n if (job === undefined) {\n job = { job: e.job, kind: 'unknown', op: null, id: -1, linkIndex: -1, state: JOB_WAITING, thread: 0, queuedIndex: -1, startedIndex: -1, finishedIndex: -1, postedIndex: -1, done: false, atIndex: -1 };\n } else {\n // Finished on another thread than it started on, or finished twice. (Waiting: the \"started\" report was lost; that is rule G1, not a contradiction.)\n if ((job.state === JOB_RUNNING && job.thread !== e.thread) || job.state >= JOB_FINISHED) live.inconsistent++;\n detach(live, job);\n }\n live.pFinished++;\n const finished: JobL = { ...job, state: JOB_FINISHED, thread: e.thread, finishedIndex: i, done: false, atIndex: e.at === undefined ? job.atIndex : i };\n if (live.poolPosts) {\n // This binary reports the posting of results (probe build). Until\n // `pool.posted` the thread still holds the job: it has to hand the\n // result to the loop, and a \"poolPost\" gate can hold it right here.\n occupy(live, e.thread, e.job, e.tid, false);\n live.jobs.set(e.job, finished);\n } else {\n // An official build says nothing more about this job. Its thread is\n // free for the next one and the result is on its way to the loop.\n finishJob(live, index, finished, i);\n }\n cls = 12;\n break;\n }\n case 'pool.posted': {\n live.poolPosts = true;\n let job = live.jobs.get(e.job);\n if (job === undefined) {\n job = { job: e.job, kind: 'unknown', op: null, id: -1, linkIndex: -1, state: JOB_WAITING, thread: 0, queuedIndex: -1, startedIndex: -1, finishedIndex: -1, postedIndex: -1, done: false, atIndex: -1 };\n } else {\n if (job.state === JOB_POSTED) live.inconsistent++; // posted twice\n detach(live, job);\n }\n live.pPosted++;\n finishJob(live, index, { ...job, state: JOB_POSTED, thread: e.thread, postedIndex: i, done: false, atIndex: e.at === undefined ? job.atIndex : i }, i);\n cls = 12;\n break;\n }\n case 'pool.delivered': {\n const job = live.jobs.get(e.job);\n cls = 12;\n if (job === undefined) break; // already off the screen (cancelled, or its item's callback was seen first)\n if (job.state === JOB_WAITING || job.state === JOB_RUNNING) live.inconsistent++; // a result with no report of the work ending\n detach(live, job);\n live.jobs.delete(e.job);\n live.pDelivered++;\n break;\n }\n case 'pool.cancelled': {\n const job = live.jobs.get(e.job);\n cls = 12;\n if (job === undefined) break;\n if (job.state !== JOB_WAITING) {\n live.inconsistent++; // a thread had picked it up; it cannot have been cancelled, so it stays where it is\n break;\n }\n detach(live, job);\n live.jobs.delete(e.job);\n live.pCancelled++;\n break;\n }\n case 'pool.size': {\n // The pool has this many threads from here on. Lanes above the new\n // size go, unless the events have shown them at work: a lane that\n // holds a job or ran one stays, and shows as \"extra\".\n live.poolSizeIndex = i;\n ensureThread(live, e.size);\n while (live.threads.length > e.size) {\n const last = live.threads[live.threads.length - 1] as ThreadL;\n if (last.job !== null || last.jobs > 0) break;\n live.threads.pop();\n }\n cls = 12;\n break;\n }\n case 'pool.link': {\n const job = live.jobs.get(e.job);\n if (job === undefined) break; // a link for a job that is not on screen\n if (job.done) {\n // Now that we know whose job it is: was its result consumed already?\n doneRemove(live, job);\n live.jobs.delete(e.job);\n finishJob(live, index, { ...job, id: e.id, linkIndex: i, done: false }, i);\n } else live.jobs.set(e.job, { ...job, id: e.id, linkIndex: i });\n break;\n }\n case 'debug.paused':\n live.paused = true;\n live.pausedIndex = i;\n live.pauses++;\n setStatus(live);\n cls = 11;\n break;\n case 'debug.resumed':\n live.lastPausedIndex = live.paused ? live.pausedIndex : -1;\n live.lastResumedIndex = i;\n live.paused = false;\n live.pausedIndex = -1;\n setStatus(live);\n break;\n case 'gate.stopped':\n live.gateStopped = true;\n live.gateIndex = i;\n live.gateStops++;\n setStatus(live);\n cls = 11;\n break;\n case 'gate.released':\n live.gateStopped = false;\n live.gateReleasedIndex = i;\n setStatus(live);\n break;\n case 'clock.frozen':\n live.clockFrozen = true;\n live.clockIndex = i;\n break;\n case 'clock.unfrozen':\n live.clockFrozen = false;\n live.clockUnfrozenIndex = i;\n live.hiddenMs += e.hiddenMs;\n break;\n case 'note':\n live.noteCount++;\n cls = 13;\n break;\n default:\n break;\n }\n return cls;\n}\n","/**\n * Rules this package applies itself.\n *\n * Almost everything on screen is a direct reflection of an event and carries\n * that event's certainty and rule. In a few places the reducer has to\n * conclude something that no event states. Each such conclusion is listed\n * here, is always marked \"inferred\", and names its rule in the Fact it puts\n * into the view, so the UI can show the reasoning exactly as it does for the\n * helper's rules (RULES in @nodejs-map/event-format). Ids start with\n * \"replay:\" so they can never collide with those.\n *\n * `cites` use the same atlas id scheme as the event format's rules. The ids\n * below follow the naming of ids that rules.ts of the event format already\n * cites; they have not been checked against a built atlas from here (the\n * proof suite that does this reads RULES, not this list).\n */\n\nimport type { Rule } from '@nodejs-map/event-format';\n\nexport const RULE_MAIN = 'replay:main';\nexport const RULE_DUE = 'replay:due';\nexport const RULE_HANDLE = 'replay:handle';\nexport const RULE_DELIVERED = 'replay:delivered';\n\nexport const REPLAY_RULES: readonly Rule[] = [\n {\n id: RULE_MAIN,\n title: 'The main script is running',\n statement:\n 'The run has started and no callback has started and the event loop has reported nothing yet. Node runs its start-up code and then the main script before it enters the loop, so the main thread is running one of the two. For an ES module the body itself runs inside promise callbacks, which then show as callbacks.',\n yields: 'inferred',\n platform: 'all',\n cites: ['s:lib/internal/modules/run_main.js#executeUserEntryPoint', 'o:loop.run'],\n },\n {\n id: RULE_DUE,\n title: 'When a timer is due',\n statement:\n \"A timer was armed (set, or put back after a run) with a delay. We show it as due at the time of that event plus the delay, and measure lateness against that. Node starts the delay from the loop's cached clock, which was read at the start of the current loop turn, so the real due time can be earlier than shown by the time the current callback had already been running.\",\n yields: 'inferred',\n platform: 'all',\n cites: ['s:lib/internal/timers.js#Timeout.prototype.constructor', 's:lib/internal/timers.js#insert', 'o:timers.listOnTimeout'],\n },\n {\n id: RULE_HANDLE,\n title: 'A handle keeps waiting after its callback',\n statement:\n 'An item whose type is a libuv handle (a socket, a server, a pipe, a child process, a watcher) was waiting on the operating system and one of its callbacks ran. A handle stays registered with the loop until it is closed, so it is still shown as waiting. It leaves when it is reported destroyed.',\n yields: 'inferred',\n platform: 'all',\n cites: ['s:src/handle_wrap.cc#node::HandleWrap::OnClose', 'o:phase.poll'],\n },\n {\n id: RULE_DELIVERED,\n title: 'The result of a pool job reached the loop',\n statement:\n 'The callback of an item started, or the item was destroyed, while a pool job of that item was shown as finished or as still queued. The after-work callback on the main thread is what leads to that callback, so the work is done and its result is no longer waiting to be delivered. (File system requests and dns.lookup report nothing from the pool thread; for them the callback is the only sign that the work ran.)',\n yields: 'inferred',\n platform: 'all',\n cites: ['s:deps/uv/src/threadpool.c#uv__work_done', 'o:pool.done'],\n },\n];\n\nconst BY_ID = new Map<string, Rule>(REPLAY_RULES.map((r) => [r.id, r]));\n\n/** The replay rule with this id, or undefined. */\nexport function replayRuleById(id: string): Rule | undefined {\n return BY_ID.get(id);\n}\n","/**\n * The timeline summary for the scrubber.\n *\n * \"Computed incrementally\" here means: what each event contributes (its\n * class, the loop phase after it, paused or not, a callback running or not)\n * is worked out once, when the event is indexed, and stored in two bytes per\n * event (RunIndex.tlState and tlClass). Cutting the run into buckets for a\n * given width is then one pass over those bytes with no allocation per\n * event: about a millisecond for 100,000 events (see the measurements in the\n * test folder), cheap enough to redo on every resize and for every batch of\n * a live run. A prefix-sum structure would make it independent of the run\n * length, at 4 bytes per class per event; the single pass was chosen because\n * it is fast enough and costs no memory.\n */\n\nimport { TIMELINE_CLASSES } from './types.ts';\nimport type { NoteMarker, PauseMarker, TimelineAxis, TimelineClass, TimelineMarkers, TimelineSummary } from './types.ts';\nimport type { NmEvent } from '@nodejs-map/event-format';\nimport type { RunIndex } from './run-index.ts';\n\nconst CLASSES = TIMELINE_CLASSES.length;\nexport const MAX_TIMELINE_WIDTH = 8192;\n\n/**\n * Cut the first `n` events into `width` buckets.\n *\n * A bucket without events (more pixels than events, or a quiet stretch on\n * the time axis) shows the state left by the last event before it: the loop\n * was still in that phase, the program was still paused.\n */\nexport function buildTimeline(index: RunIndex, n: number, width: number, axis: TimelineAxis, version: number): TimelineSummary {\n const W = Math.max(1, Math.min(MAX_TIMELINE_WIDTH, Math.floor(Number.isFinite(width) ? width : 1)));\n const start = new Uint32Array(W);\n const events = new Uint32Array(W);\n const phase = new Uint8Array(W);\n const phaseCertainty = new Uint8Array(W);\n const paused = new Uint8Array(W);\n const busy = new Uint8Array(W);\n const counts = new Uint32Array(W * CLASSES);\n const tlState = index.tlState;\n const tlClass = index.tlClass;\n const tMono = index.tMono;\n const t0 = n === 0 ? 0 : (tMono[0] as number);\n const t1 = n === 0 ? 0 : (tMono[n - 1] as number);\n const byTime = axis === 'time';\n const span = t1 - t0;\n const hist = new Uint32Array(8);\n\n let i = 0;\n let carry = 0;\n for (let b = 0; b < W; b++) {\n start[b] = i;\n // The first event index that belongs to a later bucket.\n let end: number;\n if (b === W - 1) end = n;\n else if (!byTime) end = Math.min(n, Math.ceil(((b + 1) * n) / W));\n else if (span <= 0) end = n;\n else {\n const limit = t0 + ((b + 1) * span) / W;\n end = i;\n while (end < n && (tMono[end] as number) < limit) end++;\n }\n if (end <= i) {\n phase[b] = carry & 7;\n phaseCertainty[b] = (carry >> 3) & 3;\n paused[b] = (carry & 32) !== 0 ? 1 : 0;\n busy[b] = (carry & 64) !== 0 ? 1 : 0;\n continue;\n }\n hist.fill(0);\n let cert = 0;\n let bits = 0;\n const row = b * CLASSES;\n for (; i < end; i++) {\n const s = tlState[i] as number;\n const ph = s & 7;\n if (ph !== 0) {\n hist[ph] = (hist[ph] as number) + 1;\n const c = (s >> 3) & 3;\n if (c > cert) cert = c;\n }\n bits |= s;\n const cls = tlClass[i] as number;\n if (cls !== 0) counts[row + cls - 1] = (counts[row + cls - 1] as number) + 1;\n carry = s;\n }\n events[b] = end - (start[b] as number);\n let best = 0;\n let bestCount = 0;\n for (let ph = 1; ph < 8; ph++) {\n if ((hist[ph] as number) > bestCount) {\n best = ph;\n bestCount = hist[ph] as number;\n }\n }\n phase[b] = best;\n phaseCertainty[b] = best === 0 ? 0 : cert;\n paused[b] = (bits & 32) !== 0 ? 1 : 0;\n busy[b] = (bits & 64) !== 0 ? 1 : 0;\n }\n return {\n axis: byTime ? 'time' : 'index',\n width: W,\n version,\n length: n,\n from: byTime ? t0 : 0,\n to: byTime ? t1 : n,\n start,\n events,\n phase,\n phaseCertainty,\n paused,\n busy,\n counts,\n };\n}\n\nexport function buildMarkers(index: RunIndex, events: readonly NmEvent[], version: number): TimelineMarkers {\n const notes: NoteMarker[] = [];\n for (const i of index.notes) {\n const e = events[i] as NmEvent;\n if (e.k === 'note') notes.push({ index: i, t: e.t, level: e.level, text: e.text });\n }\n const outputIndex = new Uint32Array(index.output.length);\n const outputStream = new Uint8Array(index.output.length);\n for (let k = 0; k < index.output.length; k++) {\n const chunk = index.output[k] as (typeof index.output)[number];\n outputIndex[k] = chunk.index;\n outputStream[k] = chunk.stream === 'stderr' ? 1 : 0;\n }\n return {\n version,\n // Copies: the index updates its own markers when a pause ends.\n pauses: index.pauses.map((m): PauseMarker => ({ ...m })),\n notes,\n turnIndex: Uint32Array.from(index.turns),\n turnNumber: Uint32Array.from(index.turnNumbers),\n outputIndex,\n outputStream,\n };\n}\n\n/** The bucket that holds the event at `index`, clamped to the summary. Works for both axes. */\nexport function bucketOfIndex(summary: TimelineSummary, index: number): number {\n // The last bucket whose first event is at or before `index`.\n const start = summary.start;\n let lo = 0;\n let hi = summary.width;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((start[mid] as number) <= index) lo = mid + 1;\n else hi = mid;\n }\n return Math.max(0, lo - 1);\n}\n\n/** The bucket that holds time `t` in microseconds on a time-axis summary, clamped to the summary. */\nexport function bucketOfTime(summary: TimelineSummary, t: number): number {\n const span = summary.to - summary.from;\n if (!(span > 0)) return 0;\n const b = Math.floor(((t - summary.from) / span) * summary.width);\n return Math.max(0, Math.min(summary.width - 1, b));\n}\n\n/** The counts of one bucket as an object keyed by class. */\nexport function bucketCounts(summary: TimelineSummary, bucket: number): Record<TimelineClass, number> {\n const out = {} as Record<TimelineClass, number>;\n const row = Math.max(0, Math.min(summary.width - 1, Math.floor(bucket))) * CLASSES;\n for (let c = 0; c < CLASSES; c++) out[TIMELINE_CLASSES[c] as TimelineClass] = summary.counts[row + c] as number;\n return out;\n}\n","/**\n * Replay: the view state at any position of one run.\n *\n * How it is built\n * ---------------\n * Three things are kept:\n *\n * 1. The run index (run-index.ts): everything that only grows with the run,\n * stored once, tagged with event indexes.\n * 2. The frontier: the live state (reducer.ts) after all indexed events. New\n * events are applied to it as they arrive, so the tail of a live run - the\n * position the screen shows most of the time - never needs a jump.\n * 3. Keyframes: copies of the frontier taken on the way. To show another\n * position, the nearest keyframe at or before it is copied and the events\n * from there are applied again (the \"cursor\"). Stepping forward advances\n * the cursor by one event; stepping back restores and replays.\n *\n * Keyframe interval\n * -----------------\n * A jump costs one keyframe copy plus at most `interval` events. Applying an\n * event that is already indexed measured about 0.3 microseconds on a loaded\n * laptop (test/bench.ts: a random jump over a 100,000-event run took 0.09 ms\n * at the median and 0.19 ms at the 95th percentile, view not included). So\n * 512 events are at most about 0.15 ms, 0.6 ms under the 4x CPU throttle of\n * the brief: far inside one frame, which is what makes dragging the scrubber\n * and stepping backwards feel immediate. A keyframe of a normal program is\n * about a hundred slots, so 100,000 events need 195 keyframes and about\n * 0.6 MB (measured). Halving the interval would double that memory to save\n * time nobody can see; doubling it would save 0.3 MB and bring a backward\n * step on a slow phone close to a millisecond for no real gain. 512 is the\n * point where neither cost matters.\n *\n * A program with very long queues (ten thousand pending timers) makes every\n * keyframe large. The interval therefore grows with the size of the state:\n * the next keyframe is taken after max(interval, slots / 4) events. That\n * bounds keyframe memory to about 4 slots per event whatever the program\n * does, and keeps the copy and the replay of a jump in proportion.\n *\n * A late tail\n * -----------\n * When the store reports that events from index `from` changed, the index is\n * cut back to `from`, keyframes after `from` are dropped, the frontier is\n * rebuilt from the last keyframe that is left, and the new tail is applied.\n * The result is the same as if the events had arrived in that order to begin\n * with (the tests check this).\n */\n\nimport type { NmEvent } from '@nodejs-map/event-format';\nimport type { EventStore } from './store.ts';\nimport type {\n ItemView,\n LogEntry,\n OutputChunk,\n ReplayAnswer,\n ReplayQuery,\n StepKind,\n StoreChange,\n TimelineAxis,\n TimelineMarkers,\n TimelineSummary,\n ViewOptions,\n ViewState,\n} from './types.ts';\nimport { F_CALLBACK, F_OUTPUT, F_PAUSE, F_PHASE, F_STEP, F_TURN, RunIndex } from './run-index.ts';\nimport type { ItemRec } from './run-index.ts';\nimport { applyEvent, cloneLive, createLive, liveSize } from './reducer.ts';\nimport type { Live } from './reducer.ts';\nimport { DEFAULT_VIEW, buildView, itemView, itemsRange, logEntries, outputRange, resolveOptions } from './view.ts';\nimport type { ViewContext } from './view.ts';\nimport { buildMarkers, buildTimeline } from './timeline.ts';\n\n/** Events between keyframes; see the comment at the top of this file for the reasoning. */\nexport const DEFAULT_KEYFRAME_INTERVAL = 512;\n\n/** The most events one 'events' query returns. */\nconst MAX_EVENTS_PER_QUERY = 1000;\n/** The longest trigger chain why() follows. */\nconst MAX_CHAIN = 1000;\n\nexport interface ReplayOptions {\n /** Events between keyframes. Default DEFAULT_KEYFRAME_INTERVAL. */\n keyframeInterval?: number;\n /**\n * true (default): new events are indexed inside EventStore.apply.\n * false: they are indexed by pump(), in slices, so no single call is long\n * (opening a 100,000-event recording on the main thread).\n */\n eager?: boolean;\n /** Defaults for view(). */\n view?: ViewOptions;\n}\n\nexport interface ReplayStats {\n /** Events indexed. */\n ready: number;\n keyframes: number;\n /** Container slots held by all keyframes together (a slot is one reference, about 8 bytes, or one map entry, about 40). */\n keyframeSlots: number;\n keyframeInterval: number;\n}\n\nconst CERT_CODE: Record<string, number> = { observed: 1, inferred: 2, model: 3 };\n\nconst now: () => number = typeof performance !== 'undefined' && typeof performance.now === 'function' ? () => performance.now() : () => Date.now();\n\nfunction maskOf(kind: StepKind): number {\n switch (kind) {\n case 'step':\n return F_STEP;\n case 'callback':\n return F_CALLBACK;\n case 'phase':\n return F_PHASE;\n case 'turn':\n return F_TURN;\n case 'output':\n return F_OUTPUT;\n case 'pause':\n return F_PAUSE;\n default:\n return 0xff; // 'event': anything (see find)\n }\n}\n\n/** The view state at any position of one run. */\nexport class Replay {\n readonly store: EventStore;\n #index = new RunIndex();\n #ready = 0;\n #frontier: Live = createLive();\n #keyframes: Live[] = [];\n #keyframePos: number[] = [];\n #keyframeSlots = 0;\n #nextKeyframe: number;\n #interval: number;\n #eager: boolean;\n /** The position asked for. The position shown is min(target, ready). */\n #target = 0;\n #cursor: Live | null = null;\n #cursorPos = 0;\n #viewDefaults: Required<ViewOptions>;\n #listeners = new Set<(change: StoreChange) => void>();\n #unsubscribe: () => void;\n #timelines = new Map<string, TimelineSummary>();\n #markers: TimelineMarkers | null = null;\n #markersReady = -1;\n\n constructor(store: EventStore, options?: ReplayOptions) {\n this.store = store;\n const k = options?.keyframeInterval;\n this.#interval = typeof k === 'number' && k >= 1 ? Math.floor(k) : DEFAULT_KEYFRAME_INTERVAL;\n this.#nextKeyframe = this.#interval;\n this.#eager = options?.eager !== false;\n this.#viewDefaults = resolveOptions(DEFAULT_VIEW, options?.view);\n this.#unsubscribe = store.subscribe((change) => this.#onChange(change));\n if (this.#eager) this.#ingest(Infinity);\n }\n\n // ---- taking in events ---------------------------------------------------------\n\n #onChange(change: StoreChange): void {\n if (change.rejected === null) {\n if (change.replaced) this.#target = 0;\n if (change.from < this.#ready) this.#rollback(change.from);\n if (this.#target > change.length) this.#target = change.length;\n if (this.#eager) this.#ingest(Infinity);\n }\n for (const listener of [...this.#listeners]) listener(change);\n }\n\n /** Forget everything computed from events at `from` and above. */\n #rollback(from: number): void {\n this.#index.truncate(from);\n while (this.#keyframePos.length > 0 && (this.#keyframePos[this.#keyframePos.length - 1] as number) > from) {\n this.#keyframePos.pop();\n this.#keyframeSlots -= liveSize(this.#keyframes.pop() as Live);\n }\n const k = this.#keyframePos.length - 1;\n const base = k >= 0 ? (this.#keyframePos[k] as number) : 0;\n const live = k >= 0 ? cloneLive(this.#keyframes[k] as Live) : createLive();\n this.#replay(live, base, from);\n this.#frontier = live;\n this.#ready = from;\n this.#nextKeyframe = base + (k >= 0 ? this.#gap(this.#keyframes[k] as Live) : this.#interval);\n if (this.#cursor !== null && this.#cursorPos > from) this.#cursor = null;\n }\n\n #gap(keyframe: Live): number {\n return Math.max(this.#interval, liveSize(keyframe) >> 2);\n }\n\n /** Apply the already indexed events [from, to) to `live`. */\n #replay(live: Live, from: number, to: number): void {\n const events = this.store.events;\n const index = this.#index;\n const flags = index.flags;\n for (let i = from; i < to; i++) applyEvent(live, events[i] as NmEvent, i, flags[i] as number, index, events);\n }\n\n /** Index events until the store is exhausted or the budget is spent. */\n #ingest(budgetMs: number): void {\n const events = this.store.events;\n const n = events.length;\n let i = this.#ready;\n if (i >= n) return;\n const index = this.#index;\n const live = this.#frontier;\n const deadline = budgetMs === Infinity ? Infinity : now() + budgetMs;\n while (i < n) {\n const e = events[i] as NmEvent;\n const flags = index.add(e, i);\n index.tlClass[i] = applyEvent(live, e, i, flags, index, events);\n let state = live.phase;\n if (state !== 0) state |= (CERT_CODE[(events[live.phaseIndex] as NmEvent).c] ?? 0) << 3;\n if (live.paused || live.gateStopped) state |= 32;\n if (live.stack.length > 0) state |= 64;\n index.tlState[i] = state;\n i++;\n if (i === this.#nextKeyframe) {\n const copy = cloneLive(live);\n this.#keyframes.push(copy);\n this.#keyframePos.push(i);\n this.#keyframeSlots += liveSize(copy);\n this.#nextKeyframe = i + this.#gap(copy);\n }\n if ((i & 255) === 0 && deadline !== Infinity && now() >= deadline) break;\n }\n this.#ready = i;\n }\n\n /** Events indexed so far; positions up to here can be shown. */\n get ready(): number {\n return this.#ready;\n }\n\n /**\n * Index more events, for at most `budgetMs` milliseconds (default 4).\n * Returns true when more remain. Only needed with `eager: false`.\n */\n pump(budgetMs = 4): boolean {\n this.#ingest(Math.max(0, budgetMs));\n return this.#ready < this.store.length;\n }\n\n // ---- position -------------------------------------------------------------------\n\n /** Events applied to the current view: 0 to `ready`. */\n get position(): number {\n return Math.min(this.#target, this.#ready);\n }\n\n /** Index of the last keyframe at or before `p`, or -1. */\n #keyframeBefore(p: number): number {\n const pos = this.#keyframePos;\n let lo = 0;\n let hi = pos.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((pos[mid] as number) <= p) lo = mid + 1;\n else hi = mid;\n }\n return lo - 1;\n }\n\n /** A fresh live state at position `p`. */\n #stateAt(p: number): Live {\n const k = this.#keyframeBefore(p);\n const base = k >= 0 ? (this.#keyframePos[k] as number) : 0;\n const live = k >= 0 ? cloneLive(this.#keyframes[k] as Live) : createLive();\n this.#replay(live, base, p);\n return live;\n }\n\n /** The live state at the current position. Not to be changed by the caller. */\n #live(): Live {\n const p = this.position;\n if (p === this.#ready) return this.#frontier;\n const k = this.#keyframeBefore(p);\n const base = k >= 0 ? (this.#keyframePos[k] as number) : 0;\n if (this.#cursor !== null && this.#cursorPos <= p && this.#cursorPos >= base) {\n // The cursor is at least as close as the keyframe: walk on from it.\n this.#replay(this.#cursor, this.#cursorPos, p);\n } else {\n this.#cursor = this.#stateAt(p);\n }\n this.#cursorPos = p;\n return this.#cursor;\n }\n\n /** Jump to a position (clamped to 0..length). Returns the position reached, which is lower while events are still being indexed. */\n seek(position: number): number {\n const p = Number.isFinite(position) ? Math.floor(position) : position > 0 ? this.store.length : 0;\n this.#target = Math.max(0, Math.min(this.store.length, p));\n return this.position;\n }\n\n /** Jump to time `t` (microseconds): the state after every event up to and including that time. */\n seekTime(t: number): number {\n return this.seek(this.positionAtTime(t));\n }\n\n /** The position that shows time `t`: the number of events whose time is `t` or earlier. */\n positionAtTime(t: number): number {\n const tMono = this.#index.tMono;\n let lo = 0;\n let hi = this.#ready;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((tMono[mid] as number) <= t) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n\n /**\n * Time at a position, microseconds: the time of the event applied last,\n * made non-decreasing (an event stamped earlier than its predecessor\n * counts as simultaneous with it). Position 0 has the time of the first\n * event.\n */\n timeAt(position: number): number {\n if (this.#ready === 0) return 0;\n const p = Math.max(1, Math.min(this.#ready, Math.floor(position)));\n return this.#index.tMono[p - 1] as number;\n }\n\n /**\n * The position step() would move to from `from` (default: the current\n * position), without moving. A stop is the position just after an event\n * of the kind. null: there is no such stop in that direction. Going back\n * with \"event\" or \"step\" from the first stop reaches position 0.\n */\n find(kind: StepKind, direction: 1 | -1, from?: number): number | null {\n const ready = this.#ready;\n const p = from === undefined ? this.position : Math.max(0, Math.min(ready, Math.floor(from)));\n if (kind === 'event') {\n const q = direction > 0 ? p + 1 : p - 1;\n return q < 0 || q > ready ? null : q;\n }\n const mask = maskOf(kind);\n if (direction > 0) {\n const i = this.#index.nextWith(mask, p);\n return i < 0 || i >= ready ? null : i + 1;\n }\n const i = this.#index.previousWith(mask, p - 2);\n if (i >= 0) return i + 1;\n return kind === 'step' && p > 0 ? 0 : null;\n }\n\n /** Move to the next or previous stop of a kind. Returns the new position, or null when there is none (the position is then unchanged). */\n step(kind: StepKind, direction: 1 | -1): number | null {\n const q = this.find(kind, direction);\n if (q === null) return null;\n this.#target = q;\n return q;\n }\n\n // ---- views ------------------------------------------------------------------------\n\n #context(): ViewContext {\n return { index: this.#index, events: this.store.events, length: this.store.length, ready: this.#ready, live: this.store.live, version: this.store.version };\n }\n\n /** The view at the current position. A new object on every call. */\n view(options?: ViewOptions): ViewState {\n return buildView(this.#context(), this.#live(), this.position, resolveOptions(this.#viewDefaults, options));\n }\n\n /** The view at another position, without moving. */\n viewAt(position: number, options?: ViewOptions): ViewState {\n const p = Math.max(0, Math.min(this.#ready, Math.floor(position)));\n const live = p === this.position ? this.#live() : this.#stateAt(p);\n return buildView(this.#context(), live, p, resolveOptions(this.#viewDefaults, options));\n }\n\n /** What the main thread is doing at the current position (cheap; the player uses it to word dead time). */\n doing(): 'main' | 'callback' | 'nothing' {\n const live = this.#live();\n if (live.stack.length > 0) return 'callback';\n return live.mainScript && live.startIndex >= 0 ? 'main' : 'nothing';\n }\n\n /** One item with its life up to the current position. null: not seen yet. */\n item(id: number): ItemView | null {\n const p = this.position;\n const rec = this.#index.items.get(id);\n if (rec === undefined || rec.firstIndex >= p) return null;\n return itemView(this.#context(), this.#live(), rec, p);\n }\n\n /**\n * \"Why did this run?\": the item, then the item during whose callback it\n * was created, and so on. The chain ends at an item whose trigger is the\n * main script (0 or 1) or is not known to this run.\n */\n why(id: number): ItemView[] {\n const p = this.position;\n const ctx = this.#context();\n const live = this.#live();\n const chain: ItemView[] = [];\n const seen = new Set<number>();\n let next = id;\n while (chain.length < MAX_CHAIN && !seen.has(next)) {\n seen.add(next);\n const rec: ItemRec | undefined = this.#index.items.get(next);\n if (rec === undefined || rec.firstIndex >= p) break;\n const v = itemView(ctx, live, rec, p);\n chain.push(v);\n if (v.created === null) break; // nothing is known about who made it\n next = v.trigger;\n }\n return chain;\n }\n\n /** Items seen up to the current position, in creation order. */\n items(from = 0, limit = Infinity): ItemView[] {\n const p = this.position;\n const total = this.#index.itemsBefore(p);\n return itemsRange(this.#context(), this.#live(), p, from, Math.min(limit, total));\n }\n\n /** How many items exist at the current position. */\n itemCount(): number {\n return this.#index.itemsBefore(this.position);\n }\n\n /** Output chunks by seq (`toSeq` excluded), up to the current position. */\n output(fromSeq: number, toSeq: number): OutputChunk[] {\n return outputRange(this.#context(), this.#live(), fromSeq, toSeq);\n }\n\n /** Events by index (`to` excluded), whatever the position. */\n events(from: number, to: number): LogEntry[] {\n return logEntries(this.#context(), from, to);\n }\n\n /** The run cut into `width` buckets. Cached until the run or the arguments change. */\n timeline(width: number, axis: TimelineAxis = 'index'): TimelineSummary {\n const key = axis + ':' + width;\n const cached = this.#timelines.get(key);\n const version = this.store.version;\n if (cached !== undefined && cached.version === version && cached.length === this.#ready) return cached;\n const summary = buildTimeline(this.#index, this.#ready, width, axis, version);\n // Keep the map small: widths change on resize and old ones are not coming back.\n if (this.#timelines.size >= 4) this.#timelines.clear();\n this.#timelines.set(key, summary);\n return summary;\n }\n\n /** Pauses, notes, loop turns and output positions. Cached until the run changes. */\n markers(): TimelineMarkers {\n const version = this.store.version;\n const m = this.#markers;\n if (m !== null && m.version === version && this.#markersReady === this.#ready) return m;\n this.#markers = buildMarkers(this.#index, this.store.events, version);\n this.#markersReady = this.#ready;\n return this.#markers;\n }\n\n /** Answer a ReplayQuery (the worker protocol uses this). */\n query(q: ReplayQuery): ReplayAnswer {\n switch (q.what) {\n case 'item':\n return { what: 'item', item: this.item(q.id) };\n case 'why':\n return { what: 'why', chain: this.why(q.id) };\n case 'items':\n return { what: 'items', items: this.items(q.from, q.limit), total: this.itemCount() };\n case 'output':\n return { what: 'output', chunks: this.output(q.from, q.to) };\n case 'events': {\n const from = Math.max(0, Math.floor(q.from));\n return { what: 'events', entries: this.events(from, Math.min(q.to, from + MAX_EVENTS_PER_QUERY)) };\n }\n case 'viewAt':\n return { what: 'viewAt', view: this.viewAt(q.position) };\n default:\n throw new TypeError('unknown query');\n }\n }\n\n /** Numbers about the replay itself, for a developer overlay and the benchmarks. */\n stats(): ReplayStats {\n return { ready: this.#ready, keyframes: this.#keyframes.length, keyframeSlots: this.#keyframeSlots, keyframeInterval: this.#interval };\n }\n\n /** Calls `listener` after the replay has taken in a store change. Returns a function that stops it. */\n subscribe(listener: (change: StoreChange) => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n /** Stop listening to the store. */\n dispose(): void {\n this.#unsubscribe();\n this.#listeners.clear();\n }\n}\n","/**\n * Recording files and share links.\n *\n * Safety: a recording or a link is untrusted input (anyone can send one).\n * Everything here treats it as data only. Bytes are unpacked with the\n * platform's own gzip (DecompressionStream) under a size cap, decoded as\n * UTF-8, and handed to the event-format decoder, which uses JSON.parse and\n * validates every header field and every event. Nothing is evaluated,\n * imported, fetched or run; source text carried in a recording stays text.\n *\n * Uses only globals that browsers, Web Workers and Node 26 all have:\n * CompressionStream, DecompressionStream, TextEncoder, TextDecoder.\n */\n\nimport { RecordingError, decodeRecording, encodeRecording } from '@nodejs-map/event-format';\nimport type { Recording } from '@nodejs-map/event-format';\nimport type { OpenOptions, SaveOptions, ShareOptions, ShareResult } from './types.ts';\n\n/**\n * The longest fragment recordingToFragment will produce, in characters.\n *\n * A link is only useful if it survives being pasted. The fragment never\n * reaches a server, so server limits do not matter; what matters is where\n * people paste links and what browsers accept. Figures as documented by the\n * vendors, from memory, not re-checked while writing this:\n *\n * browsers Chrome and Edge accept URLs up to 2 MB; Firefox about 1 MB;\n * Safari has handled tens of thousands of characters for years\n * chat apps Slack 40,000 characters per message; WhatsApp 65,536;\n * Microsoft Teams about 28 KB; Telegram 4,096; Discord 2,000\n *\n * 24,000 stays under Slack, WhatsApp and Teams with room for the page URL\n * and a sentence around it, and far under every browser. It holds roughly\n * 18 KB of gzip, which is a run of one to three thousand events: every\n * lesson-sized program. Anything longer is better as a file anyway: nobody\n * can read, check or trust a link of a hundred thousand characters.\n *\n * Telegram and Discord cut a message well below any limit that would be\n * useful here, so they get a flag instead of a limit: ShareResult.fitsEverywhere\n * is true only up to SHARE_LINK_SAFE_CHARS, and the UI can offer the file\n * for those places.\n */\nexport const SHARE_LINK_MAX_CHARS = 24_000;\n\n/** At or below this many characters a link also fits the tightest message limits (Discord: 2,000). */\nexport const SHARE_LINK_SAFE_CHARS = 2_000;\n\n/**\n * Refuse a recording that unpacks to more than this many bytes. A gzip file\n * of a few kilobytes can unpack to gigabytes; the cap is checked while\n * unpacking, so such a file costs at most this much memory. 256 MB is about\n * ten times the largest recording we expect (a million events).\n */\nexport const MAX_RECORDING_BYTES = 256 * 1024 * 1024;\n\n/** The same cap for links, which are small by construction. */\nconst MAX_FRAGMENT_BYTES = 32 * 1024 * 1024;\n/** Refuse to even look at a fragment longer than this (Chrome's URL limit). */\nconst MAX_FRAGMENT_CHARS = 2 * 1024 * 1024;\n\n/**\n * A fragment is `rec=1.<data>`: the key \"rec\", the link format version \"1\"\n * (gzip of the recording text, then base64url without padding), a dot, the\n * data. A key=value form lets the app keep other state in the fragment\n * next to it, separated by \"&\".\n */\nexport const FRAGMENT_PREFIX = 'rec=1.';\n\n// ---- bytes ----------------------------------------------------------------------\n\nfunction toBytes(input: ArrayBuffer | Uint8Array): Uint8Array {\n return input instanceof Uint8Array ? input : new Uint8Array(input);\n}\n\n/** Push `bytes` through a compression or decompression stream and collect the result, at most `maxBytes`. */\nasync function pipe(stream: { readable: ReadableStream<Uint8Array>; writable: WritableStream<Uint8Array> }, bytes: Uint8Array, maxBytes: number, tooBig: string): Promise<Uint8Array> {\n const writer = stream.writable.getWriter();\n // Writing and reading must go on at the same time (the stream applies\n // back-pressure). Failures of the write side surface on the read side\n // too; these handlers only keep them from being reported twice.\n writer.write(bytes).catch(() => {});\n writer.close().catch(() => {});\n const reader = stream.readable.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n reader.cancel().catch(() => {});\n throw new RecordingError(tooBig);\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nfunction gzip(bytes: Uint8Array): Promise<Uint8Array> {\n return pipe(new CompressionStream('gzip') as unknown as { readable: ReadableStream<Uint8Array>; writable: WritableStream<Uint8Array> }, bytes, Infinity, '');\n}\n\nasync function gunzip(bytes: Uint8Array, maxBytes: number): Promise<Uint8Array> {\n const tooBig = `the recording is larger than ${Math.round(maxBytes / (1024 * 1024))} MB when unpacked`;\n try {\n return await pipe(new DecompressionStream('gzip') as unknown as { readable: ReadableStream<Uint8Array>; writable: WritableStream<Uint8Array> }, bytes, maxBytes, tooBig);\n } catch (error) {\n if (error instanceof RecordingError) throw error;\n throw new RecordingError('not a valid gzip file');\n }\n}\n\nfunction isGzip(bytes: Uint8Array): boolean {\n return bytes.length >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b;\n}\n\nfunction utf8(bytes: Uint8Array): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n throw new RecordingError('not a text file (invalid UTF-8)');\n }\n}\n\nfunction parse(text: string): Recording {\n let recording: Recording;\n try {\n recording = decodeRecording(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\n } catch (error) {\n if (error instanceof RecordingError) throw error;\n // The decoder is meant to throw RecordingError only; anything else is still just a bad file.\n throw new RecordingError('not a nodejs-map recording');\n }\n if (recording === null || typeof recording !== 'object' || recording.header === undefined || recording.header === null || !Array.isArray(recording.events)) {\n throw new RecordingError('not a nodejs-map recording');\n }\n return recording;\n}\n\n// ---- base64url ------------------------------------------------------------------\n\nconst B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\nconst B64_VALUE = new Int8Array(128).fill(-1);\nfor (let i = 0; i < 64; i++) B64_VALUE[B64.charCodeAt(i)] = i;\n\nfunction toBase64Url(bytes: Uint8Array): string {\n const parts: string[] = [];\n let piece = '';\n const n = bytes.length;\n for (let i = 0; i < n; i += 3) {\n const a = bytes[i] as number;\n const b = i + 1 < n ? (bytes[i + 1] as number) : 0;\n const c = i + 2 < n ? (bytes[i + 2] as number) : 0;\n piece += B64[a >> 2] as string;\n piece += B64[((a & 3) << 4) | (b >> 4)] as string;\n if (i + 1 < n) piece += B64[((b & 15) << 2) | (c >> 6)] as string;\n if (i + 2 < n) piece += B64[c & 63] as string;\n if (piece.length >= 8192) {\n parts.push(piece);\n piece = '';\n }\n }\n parts.push(piece);\n return parts.join('');\n}\n\nfunction fromBase64Url(text: string): Uint8Array {\n const n = text.length;\n if (n % 4 === 1) throw new RecordingError('the link is damaged (wrong length)');\n const out = new Uint8Array(Math.floor((n * 3) / 4));\n let o = 0;\n for (let i = 0; i < n; i += 4) {\n const v = [0, 0, 0, 0];\n for (let k = 0; k < 4; k++) {\n if (i + k >= n) break;\n const code = text.charCodeAt(i + k);\n const value = code < 128 ? (B64_VALUE[code] as number) : -1;\n if (value < 0) throw new RecordingError('the link is damaged (unexpected character)');\n v[k] = value;\n }\n const [a, b, c, d] = v as [number, number, number, number];\n out[o++] = (a << 2) | (b >> 4);\n if (i + 2 < n) out[o++] = ((b & 15) << 4) | (c >> 2);\n if (i + 3 < n) out[o++] = ((c & 3) << 6) | d;\n }\n return out;\n}\n\n// ---- public -----------------------------------------------------------------------\n\n/**\n * Parse a recording from text, or from bytes that are UTF-8 text or gzip\n * (told apart by the gzip signature). Rejects with RecordingError for\n * anything that is not a valid recording. Nothing is executed.\n */\nexport async function openRecording(input: string | ArrayBuffer | Uint8Array, options?: OpenOptions): Promise<Recording> {\n const maxBytes = options?.maxBytes !== undefined && options.maxBytes > 0 ? options.maxBytes : MAX_RECORDING_BYTES;\n if (typeof input === 'string') {\n if (input.length > maxBytes) throw new RecordingError(`the recording is larger than ${Math.round(maxBytes / (1024 * 1024))} MB`);\n return parse(input);\n }\n if (!(input instanceof Uint8Array) && !(input instanceof ArrayBuffer)) throw new RecordingError('not a recording: expected text or bytes');\n let bytes = toBytes(input);\n if (isGzip(bytes)) bytes = await gunzip(bytes, maxBytes);\n else if (bytes.byteLength > maxBytes) throw new RecordingError(`the recording is larger than ${Math.round(maxBytes / (1024 * 1024))} MB`);\n return parse(utf8(bytes));\n}\n\n/** Encode a recording as file bytes: the UTF-8 text of the event-format codec, or gzip of it. */\nexport async function saveRecording(recording: Recording, options?: SaveOptions): Promise<Uint8Array> {\n const bytes = new TextEncoder().encode(encodeRecording(recording));\n return options?.gzip === true ? gzip(bytes) : bytes;\n}\n\n/**\n * Encode a recording for the URL fragment (gzip, then base64url). When the\n * result would be longer than the limit, nothing is produced and the result\n * says so: share the file instead.\n */\nexport async function recordingToFragment(recording: Recording, options?: ShareOptions): Promise<ShareResult> {\n const limit = options?.maxChars !== undefined && options.maxChars > 0 ? Math.floor(options.maxChars) : SHARE_LINK_MAX_CHARS;\n const packed = await gzip(new TextEncoder().encode(encodeRecording(recording)));\n const length = FRAGMENT_PREFIX.length + Math.ceil((packed.byteLength * 4) / 3);\n if (length > limit) {\n return {\n ok: false,\n reason: 'too-big',\n length,\n limit,\n message: `This recording is too big to share as a link (${length.toLocaleString('en-US')} characters; links work up to ${limit.toLocaleString('en-US')}). Save it and share the file instead.`,\n };\n }\n const fragment = FRAGMENT_PREFIX + toBase64Url(packed);\n return { ok: true, fragment, length: fragment.length, fitsEverywhere: fragment.length <= SHARE_LINK_SAFE_CHARS };\n}\n\n/**\n * Parse a fragment made by recordingToFragment. Accepts it with or without\n * the leading \"#\", alone or among other \"&\"-separated parts. Rejects with\n * RecordingError. Nothing is executed.\n */\nexport async function recordingFromFragment(fragment: string, options?: OpenOptions): Promise<Recording> {\n if (typeof fragment !== 'string') throw new RecordingError('not a recording link');\n if (fragment.length > MAX_FRAGMENT_CHARS) throw new RecordingError('the link is too long to be a recording link');\n const body = fragment.startsWith('#') ? fragment.slice(1) : fragment;\n let value: string | undefined;\n for (const part of body.split('&')) {\n if (part.startsWith('rec=')) {\n value = part.slice(4);\n break;\n }\n }\n if (value === undefined) throw new RecordingError('this link does not contain a recording');\n const dot = value.indexOf('.');\n if (dot < 0 || value.slice(0, dot) !== '1') throw new RecordingError('this link was made by a newer version of nodejs-map');\n const packed = fromBase64Url(value.slice(dot + 1));\n if (!isGzip(packed)) throw new RecordingError('the link is damaged');\n const maxBytes = options?.maxBytes !== undefined && options.maxBytes > 0 ? Math.min(options.maxBytes, MAX_FRAGMENT_BYTES) : MAX_FRAGMENT_BYTES;\n return parse(utf8(await gunzip(packed, maxBytes)));\n}\n","/**\n * View patches: post only what changed.\n *\n * A full view is a few to a few dozen kilobytes, and most of it is the same\n * from one step to the next (the node info, the thread lanes, the queues\n * nothing touched, the older output chunks and log entries). A patch carries\n * the top-level parts of the view that differ from the view before it, and\n * for the two append-mostly lists (output chunks, log entries) only the new\n * entries.\n *\n * applyViewPatch rebuilds the full view on the receiving side. The parts\n * that did not change are the very same objects as in the view before, so a\n * UI that compares by identity can skip every panel whose part is untouched;\n * that saves more main-thread time than the smaller message does.\n *\n * Both functions work on plain data and are pure.\n */\n\nimport type { QueueName } from '@nodejs-map/event-format';\nimport type { ListPatch, LogEntry, OutputChunk, QueueView, ViewPatch, ViewState } from './types.ts';\n\nconst QUEUES: readonly QueueName[] = ['nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close'];\n\n/** The parts of a view that are replaced whole when they differ. */\nconst PARTS = ['run', 'main', 'loop', 'items', 'timers', 'pool', 'debug', 'notes', 'focus', 'source', 'problems'] as const;\n/** The plain values at the top of a view. */\nconst SCALARS = ['position', 'length', 'ready', 'live', 'version', 't', 'endT'] as const;\n\n/** Deep equality of plain data (objects, arrays, primitives, null). */\nfunction same(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!same(a[i], b[i])) return false;\n return true;\n }\n if (Array.isArray(b)) return false;\n const ka = Object.keys(a);\n if (ka.length !== Object.keys(b).length) return false;\n for (const k of ka) if (!same((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;\n return true;\n}\n\n/**\n * What of an ordered list (entries numbered by `key`, never changing while\n * the run is unchanged) can stay, and what has to be sent.\n */\nfunction listPatch<T>(before: readonly T[], after: readonly T[], key: (entry: T) => number, comparable: boolean): ListPatch<T> | null {\n if (!comparable || before.length === 0 || after.length === 0) {\n return before.length === 0 && after.length === 0 ? null : { from: 0, to: 0, prepend: [], append: after.slice() };\n }\n // Both lists are consecutive runs of numbers. Keep the overlap; send what\n // comes before it (a step back) and what comes after it (a step forward).\n const a0 = key(before[0] as T);\n const a1 = key(before[before.length - 1] as T);\n const b0 = key(after[0] as T);\n const b1 = key(after[after.length - 1] as T);\n if (a0 === b0 && a1 === b1) return null;\n const from = Math.max(a0, b0);\n const to = Math.min(a1, b1) + 1;\n if (from >= to) return { from: 0, to: 0, prepend: [], append: after.slice() }; // nothing in common\n const prepend: T[] = [];\n const append: T[] = [];\n for (const entry of after) {\n const k = key(entry);\n if (k < from) prepend.push(entry);\n else if (k >= to) append.push(entry);\n }\n return { from, to, prepend, append };\n}\n\nfunction listApply<T>(before: readonly T[], patch: ListPatch<T> | null, key: (entry: T) => number): T[] {\n if (patch === null) return before as T[];\n const out: T[] = patch.prepend.slice();\n for (const entry of before) {\n const k = key(entry);\n if (k >= patch.from && k < patch.to) out.push(entry);\n }\n for (const entry of patch.append) out.push(entry);\n return out;\n}\n\nconst chunkKey = (c: OutputChunk): number => c.seq;\nconst logKey = (l: LogEntry): number => l.index;\n\n/**\n * The patch that turns `previous` into `next`. With `previous` null the\n * patch is a full one: it carries everything and applies to nothing.\n */\nexport function diffView(previous: ViewState | null, next: ViewState): ViewPatch {\n const set: Record<string, unknown> = {};\n const queues: Partial<Record<QueueName, QueueView>> = {};\n if (previous === null) {\n for (const k of SCALARS) set[k] = next[k];\n for (const k of PARTS) set[k] = next[k];\n for (const q of QUEUES) queues[q] = next.queues[q];\n return {\n full: true,\n set: set as ViewPatch['set'],\n queues,\n output: { total: next.output.total, chars: next.output.chars, from: 0, to: 0, prepend: [], append: next.output.chunks.slice() },\n log: { from: 0, to: 0, prepend: [], append: next.log.slice() },\n };\n }\n for (const k of SCALARS) if (previous[k] !== next[k]) set[k] = next[k];\n for (const k of PARTS) if (!same(previous[k], next[k])) set[k] = next[k];\n for (const q of QUEUES) if (!same(previous.queues[q], next.queues[q])) queues[q] = next.queues[q];\n // Chunk and log numbers mean the same thing only while the event list is unchanged.\n const comparable = previous.version === next.version;\n const chunks = listPatch(previous.output.chunks, next.output.chunks, chunkKey, comparable);\n const output = chunks === null && previous.output.total === next.output.total && previous.output.chars === next.output.chars ? null : { total: next.output.total, chars: next.output.chars, ...(chunks ?? { from: 0, to: Number.MAX_SAFE_INTEGER, prepend: [], append: [] }) };\n return { full: false, set: set as ViewPatch['set'], queues, output, log: listPatch(previous.log, next.log, logKey, comparable) };\n}\n\n/**\n * The view that `patch` describes, given the view before it (null for a\n * full patch). Parts the patch does not mention are the same objects as in\n * `previous`. Throws when a patch that is not full is applied to nothing:\n * ask the host for a full one (`configure` with `views: 'patch'` again).\n */\nexport function applyViewPatch(previous: ViewState | null, patch: ViewPatch): ViewState {\n if (previous === null) {\n if (!patch.full) throw new Error('a view patch needs the view before it');\n const s = patch.set as ViewState;\n return {\n ...s,\n queues: patch.queues as Record<QueueName, QueueView>,\n output: { total: patch.output?.total ?? 0, chars: patch.output?.chars ?? 0, chunks: patch.output?.append ?? [] },\n log: patch.log?.append ?? [],\n };\n }\n let queues = previous.queues;\n for (const q of QUEUES) {\n const changed = patch.queues[q];\n if (changed !== undefined) {\n if (queues === previous.queues) queues = { ...previous.queues };\n queues[q] = changed;\n }\n }\n const o = patch.output;\n return {\n ...previous,\n ...patch.set,\n queues,\n output: o === null ? previous.output : { total: o.total, chars: o.chars, chunks: patch.full ? o.append : listApply(previous.output.chunks, o, chunkKey) },\n log: patch.full ? (patch.log?.append ?? []) : listApply(previous.log, patch.log, logKey),\n };\n}\n","/**\n * The honesty marks: one visual language for \"how do we know this?\", used by every panel\n * and passed to the map.\n *\n * observed solid ring, filled centre Node reported it\n * inferred dashed ring, open centre worked out from other signals by a named rule\n * model dotted ring, open centre an illustration\n *\n * The line style carries the meaning; the colour only repeats it. So the marks read the\n * same in greyscale and for colour-blind users. The same three line styles are used for\n * the left edge of rows (see styles/panels.css) and for the segments of the phase ring.\n */\nimport type { Certainty, Rule } from '@nodejs-map/event-format';\nimport { BACKGROUND, ruleById } from '@nodejs-map/event-format';\nimport { replayRuleById } from '@nodejs-map/replay';\n\nexport const CERTAINTIES: readonly Certainty[] = ['observed', 'inferred', 'model'];\n\nexport const CERTAINTY_LABEL: Readonly<Record<Certainty, string>> = {\n observed: 'Observed',\n inferred: 'Inferred',\n model: 'Model',\n};\n\nexport const CERTAINTY_MEANING: Readonly<Record<Certainty, string>> = {\n observed: 'Node.js reported this itself.',\n inferred: 'Worked out from other signals by a rule. Open the mark to read the rule and the source it relies on.',\n model: 'An illustration of how this part works, not a measurement of this run.',\n};\n\nconst RANK: Readonly<Record<Certainty, number>> = { observed: 2, inferred: 1, model: 0 };\n\n/** The weaker of two certainties (model < inferred < observed). */\nexport function weakest(a: Certainty, b: Certainty): Certainty {\n return RANK[a] <= RANK[b] ? a : b;\n}\n\n/**\n * Rules for the things the app itself draws as illustrations. Same shape as the rules of\n * the event format; ids start with \"app:\". The cited ids are ones the event format's\n * rules cite too, so the atlas build already proves they exist.\n */\nexport const APP_RULES: readonly Rule[] = [\n {\n id: 'app:phase-ring',\n title: 'The ring of loop phases',\n statement:\n 'uv_run runs its steps in a fixed order: timers once before the first turn, then in every turn pending, idle, prepare, poll, pending again, check, close and timers. The ring draws that order as a picture. Which phase is lit comes from the events of this run and carries its own mark; the ring itself measures nothing.',\n yields: 'model',\n platform: 'all',\n cites: ['s:deps/uv/src/unix/core.c#uv_run', 's:deps/uv/src/win/core.c#uv_run', 'o:loop.run'],\n },\n];\n\nexport const PHASE_RING_RULE = 'app:phase-ring';\n\n/**\n * A rule by id: of the event format (the rules events name, and its \"background\" entries,\n * which explain a source and are not named by events of this version - an older recording\n * may still name one), of the replay package, or of the app.\n */\nexport function findRule(id: string | null | undefined): Rule | undefined {\n if (!id) return undefined;\n return ruleById(id) ?? BACKGROUND.find((r) => r.id === id) ?? replayRuleById(id) ?? APP_RULES.find((r) => r.id === id);\n}\n\nexport const RULE_PLATFORM_LABEL: Readonly<Record<Rule['platform'], string>> = {\n all: 'Windows, macOS and Linux',\n unix: 'macOS and Linux',\n win32: 'Windows',\n};\n\n/**\n * What the mark of a fact opens. An inferred or model fact must be explainable; when its\n * rule is unknown to this version of the app we say so instead of showing nothing.\n */\nexport interface MarkTarget {\n certainty: Certainty;\n /** Rule id as written in the event; null when the event named none. */\n ruleId: string | null;\n /** Index of the event the fact comes from, when known: the dialog offers \"go to this event\". */\n index: number | null;\n /** Short words for what is being explained, for the dialog title. */\n subject: string;\n}\n","/**\n * \"Your code\" on the map: one box per program file and one per top-level function or\n * class, with its line range.\n *\n * A light parse is enough: we walk the top level of the syntax tree that the editor's\n * JavaScript parser (Lezer) produces. Lezer never fails on broken code (it produces error\n * nodes and carries on), so half-typed programs still give boxes. The parser is passed in\n * so this module stays out of the first bundle: the caller imports it lazily together\n * with the editor.\n */\nimport type { UserBox } from '../map/contract.ts';\n\n/** The parts of Lezer's tree API used here. */\ninterface SyntaxNodeLike {\n readonly name: string;\n readonly from: number;\n readonly to: number;\n readonly firstChild: SyntaxNodeLike | null;\n readonly nextSibling: SyntaxNodeLike | null;\n getChild(type: string): SyntaxNodeLike | null;\n}\nexport interface JsParserLike {\n parse(text: string): { readonly topNode: SyntaxNodeLike };\n}\n\nexport const MAX_USER_BOXES = 400;\nconst MAX_LABEL = 80;\n\n/** Offsets of line starts, for offset -> 1-based line. */\nfunction lineStarts(text: string): number[] {\n const starts = [0];\n for (let i = text.indexOf('\\n'); i >= 0; i = text.indexOf('\\n', i + 1)) starts.push(i + 1);\n return starts;\n}\n\nfunction lineAt(starts: readonly number[], offset: number): number {\n let lo = 0;\n let hi = starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if ((starts[mid] as number) <= offset) lo = mid;\n else hi = mid - 1;\n }\n return lo + 1;\n}\n\nconst FUNCTION_VALUES = new Set(['ArrowFunction', 'FunctionExpression', 'ClassExpression']);\nconst STOPS_NAME_SEARCH = new Set(['extends', 'ParamList', 'ClassBody', 'Block', '⚠']);\n\ninterface Found {\n name: string;\n kind: 'function' | 'class';\n from: number;\n to: number;\n}\n\nfunction namedDeclaration(node: SyntaxNodeLike, text: string, out: Found[]): void {\n switch (node.name) {\n case 'FunctionDeclaration':\n case 'ClassDeclaration': {\n // The name comes before the parameters, the body and any \"extends\"; an anonymous\n // default export has none (\"export default class extends Base {}\").\n let def: SyntaxNodeLike | null = null;\n for (let child = node.firstChild; child; child = child.nextSibling) {\n if (child.name === 'VariableDefinition') def = child;\n if (def || STOPS_NAME_SEARCH.has(child.name)) break;\n }\n const name = def ? text.slice(def.from, def.to) : 'default';\n out.push({ name, kind: node.name === 'ClassDeclaration' ? 'class' : 'function', from: node.from, to: node.to });\n return;\n }\n case 'VariableDeclaration': {\n // const a = () => {}, b = function () {}, C = class {};\n let pending: SyntaxNodeLike | null = null;\n for (let child = node.firstChild; child; child = child.nextSibling) {\n if (child.name === 'VariableDefinition') pending = child;\n else if (pending && FUNCTION_VALUES.has(child.name)) {\n out.push({\n name: text.slice(pending.from, pending.to),\n kind: child.name === 'ClassExpression' ? 'class' : 'function',\n from: node.from,\n to: child.to,\n });\n pending = null;\n }\n }\n return;\n }\n case 'ExportDeclaration': {\n for (let child = node.firstChild; child; child = child.nextSibling) namedDeclaration(child, text, out);\n return;\n }\n case 'ExpressionStatement': {\n // module.exports.name = function () {} / exports.name = () => {}\n const assign = node.getChild('AssignmentExpression');\n if (!assign) return;\n let target: SyntaxNodeLike | null = null;\n for (let child = assign.firstChild; child; child = child.nextSibling) {\n if (child.name === 'MemberExpression' && !target) target = child;\n else if (target && FUNCTION_VALUES.has(child.name)) {\n const targetText = text.slice(target.from, target.to);\n const m = /^(?:module\\.)?exports\\.([A-Za-z_$][\\w$]*)$/.exec(targetText);\n if (m && m[1]) {\n out.push({ name: m[1], kind: child.name === 'ClassExpression' ? 'class' : 'function', from: node.from, to: child.to });\n }\n }\n }\n return;\n }\n default:\n }\n}\n\n/** A file name is shown as text and used inside ids; keep it short and on one line. */\nexport function userFileId(fileName: string): string {\n return `u:${fileName.replace(/[\\r\\n#]/g, '_').slice(0, 200)}`;\n}\n\nexport function extractUserBoxes(fileName: string, text: string, parser: JsParserLike): UserBox[] {\n const fileId = userFileId(fileName);\n const starts = lineStarts(text);\n const lineCount = text.length === 0 ? 1 : lineAt(starts, text.length - (text.endsWith('\\n') ? 1 : 0));\n const boxes: UserBox[] = [\n { id: fileId, parent: null, label: fileName.slice(0, MAX_LABEL), lines: { start: 1, end: Math.max(1, lineCount) } },\n ];\n\n const found: Found[] = [];\n const top = parser.parse(text).topNode;\n for (let node = top.firstChild; node; node = node.nextSibling) namedDeclaration(node, text, found);\n\n const seen = new Map<string, number>();\n for (const f of found) {\n if (boxes.length >= MAX_USER_BOXES) break;\n const n = (seen.get(f.name) ?? 0) + 1;\n seen.set(f.name, n);\n // Two top-level declarations may share a name (broken code, or a redeclared var): keep ids unique.\n const id = `${fileId}#${f.name}${n > 1 ? `~${n}` : ''}`;\n boxes.push({\n id,\n parent: fileId,\n label: (f.kind === 'class' ? `class ${f.name}` : `${f.name}()`).slice(0, MAX_LABEL),\n lines: { start: lineAt(starts, f.from), end: lineAt(starts, Math.max(f.from, f.to - 1)) },\n });\n }\n return boxes;\n}\n\n/** The box whose range holds `line`: the smallest function or class, else the file. */\nexport function userBoxAtLine(boxes: readonly UserBox[], fileName: string, line: number): UserBox | undefined {\n const fileId = userFileId(fileName);\n let best: UserBox | undefined;\n for (const b of boxes) {\n if (b.id !== fileId && b.parent !== fileId) continue;\n if (!b.lines || line < b.lines.start || line > b.lines.end) continue;\n if (!best || !best.lines || b.lines.end - b.lines.start <= best.lines.end - best.lines.start) best = b;\n }\n return best;\n}\n","/**\n * What the map lights up for a view state. Pure.\n *\n * Every highlight carries the certainty of the fact it shows, taken from the event that\n * said so. Nothing is promoted: when two facts light the same box in the same role, the\n * weaker certainty is kept.\n */\nimport type { Certainty } from '@nodejs-map/event-format';\nimport { ASYNC_TYPE_AT, PHASE_IDS, WELL_KNOWN } from '@nodejs-map/atlas-format';\nimport type { ViewState } from '@nodejs-map/replay';\nimport type { HighlightRole, MapHighlight, UserBox } from '../map/contract.ts';\nimport { weakest } from './certainty.ts';\nimport { isSameProgram } from './format.ts';\nimport { userBoxAtLine } from './userBoxes.ts';\n\nexport interface HighlightContext {\n userBoxes: readonly UserBox[];\n /** Name of the program on screen, to match paused user frames against. */\n programName: string | null;\n}\n\n/** The parts of the view the highlights are made from. */\nexport type HighlightView = Pick<ViewState, 'focus' | 'loop' | 'main' | 'pool' | 'debug'>;\n\nexport function buildHighlights(view: HighlightView | null, ctx: HighlightContext): MapHighlight[] {\n if (!view) return [];\n const byKey = new Map<string, MapHighlight>();\n const add = (id: string | null | undefined, role: HighlightRole, certainty: Certainty, badge?: string): void => {\n if (!id) return;\n const key = `${role}\\n${id}`;\n const have = byKey.get(key);\n if (have) {\n have.certainty = weakest(have.certainty, certainty);\n if (badge && !have.badge) have.badge = badge;\n return;\n }\n const h: MapHighlight = { id, role, certainty };\n if (badge) h.badge = badge;\n byKey.set(key, h);\n };\n\n // Where work waits. Replay counts each piece of work once and says what state it is in:\n // queue entries and pool jobs without a thread are \"waiting\"; pool jobs whose result has\n // not reached the loop yet are \"finished\". Jobs running on a thread are not waiting:\n // the busy-thread highlight below shows them as active.\n for (const place of view.focus.waiting) {\n const waiting = place.waiting + place.poolWaiting;\n const parts: string[] = [];\n if (waiting > 0) parts.push(`${waiting} waiting`);\n if (place.poolDone > 0) parts.push(`${place.poolDone} finished`);\n if (parts.length > 0) add(place.at, 'waiting', place.c, parts.join(', '));\n }\n\n // The loop phase.\n if (view.loop.phase && view.loop.phaseFrom) {\n add(PHASE_IDS[view.loop.phase], 'active', view.loop.phaseFrom.c, `${view.loop.phase} phase`);\n }\n\n // The callback on the main thread: the place in Node that makes callbacks of this type.\n const top = view.main.stack[view.main.stack.length - 1];\n if (top) {\n add(ASYNC_TYPE_AT[top.item.type], 'active', top.from.c);\n }\n\n // Busy pool threads: one highlight per place, saying how many threads are at work there.\n const busy = new Map<string, { n: number; c: Certainty }>();\n for (const thread of view.pool.threads) {\n const job = thread.job;\n if (!job) continue;\n const from = job.started ?? job.queued;\n const id = job.at ?? WELL_KNOWN.poolWorker.id;\n const c: Certainty = from ? from.c : 'inferred';\n const have = busy.get(id);\n if (have) {\n have.n++;\n have.c = weakest(have.c, c);\n } else busy.set(id, { n: 1, c });\n }\n for (const [id, b] of busy) add(id, 'active', b.c, b.n === 1 ? '1 pool thread running' : `${b.n} pool threads running`);\n\n // The latest event that names a place.\n if (view.focus.at && view.focus.from) add(view.focus.at, 'active', view.focus.from.c);\n\n // Paused: the main thread waits in the inspector, and the top frames say where.\n if (view.debug.paused && view.debug.from) {\n const c = view.debug.from.c;\n add(WELL_KNOWN.inspectorPause.id, 'active', c, 'paused');\n const frame = view.debug.frames[0];\n if (frame) {\n if (frame.at) add(frame.at, 'active', c, 'paused here');\n else if (frame.origin === 'user' && ctx.programName && isSameProgram(frame.loc.url, ctx.programName)) {\n add(userBoxAtLine(ctx.userBoxes, ctx.programName, frame.loc.line)?.id, 'active', c, `line ${frame.loc.line}`);\n }\n }\n }\n\n return [...byKey.values()];\n}\n\n/**\n * The one box \"follow the action\" asks the map to show. It changes when the program moves\n * to another callback, another loop phase or a debugger pause - not with every event:\n *\n * 1. paused in Node's own JavaScript: the box of that frame;\n * 2. a callback is running: the place in Node that runs callbacks of that kind\n * (listOnTimeout for a timer, processImmediate for an immediate, ...);\n * 3. else the loop phase.\n *\n * The place of the latest event is deliberately not used: it moves many times inside one\n * callback (every setTimeout call, every queue entry), and a map that flies that often\n * cannot be read.\n */\nexport function actionPlace(view: Pick<ViewState, 'debug' | 'main' | 'loop'> | null): { id: string; certainty: Certainty } | null {\n if (!view) return null;\n if (view.debug.paused && view.debug.from) {\n const frame = view.debug.frames.find((f) => f.origin === 'node' && f.at);\n if (frame?.at) return { id: frame.at, certainty: view.debug.from.c };\n }\n const top = view.main.stack[view.main.stack.length - 1];\n const callbackPlace = top ? ASYNC_TYPE_AT[top.item.type] : undefined;\n if (top && callbackPlace) return { id: callbackPlace, certainty: top.from.c };\n if (view.loop.phase && view.loop.phaseFrom) return { id: PHASE_IDS[view.loop.phase], certainty: view.loop.phaseFrom.c };\n return null;\n}\n","/**\n * Which line of code to highlight, in which code view, and how.\n *\n * Two code views exist: the editor (the user's program) and the Source panel (one file of\n * Node's own source). The line comes from the replay's `ViewState.source` or, while the\n * debugger is paused, from the frame of the call stack the user selected.\n *\n * Only a paused line is the line that is executing. The other three kinds are places the\n * events can vouch for - the line that wrote the latest output, the line that scheduled\n * the latest async work, the line where the running callback was scheduled - and must\n * not look like the first: they get a quieter style and a tag in words.\n */\nimport type { Frame, Loc } from '@nodejs-map/event-format';\nimport { isSameProgram } from './format.ts';\n\nexport type LineKind =\n /** The debugger is stopped on this line: exact. */\n | 'paused'\n /** A frame further down the paused call stack, selected by the user: \"called from here\". */\n | 'frame'\n /** This line wrote the latest output. */\n | 'output'\n /** This line scheduled the latest async work. */\n | 'created'\n /** A callback is running; this is the line where it was scheduled, not the line executing now. */\n | 'callback';\n\nexport interface CodeHighlight {\n /** The code view that holds the script. */\n where: 'editor' | 'source';\n /** The script, as the events name it. */\n url: string;\n /** 1-based. */\n line: number;\n kind: LineKind;\n /** Words shown at the end of the line, for the kinds that are not \"executing here\". */\n tag: string | null;\n}\n\nexport const LINE_TAGS: Readonly<Record<LineKind, string | null>> = {\n paused: null,\n frame: 'called from here',\n output: 'wrote this output',\n created: 'scheduled here',\n callback: 'callback scheduled here is running',\n};\n\nexport interface HighlightInput {\n /** `ViewState.source` at the player's position. */\n source: { loc: Loc; why: 'paused' | 'output' | 'created' | 'callback' } | null;\n /** The call stack, when the debugger is paused at this position; else null. */\n frames: readonly Pick<Frame, 'loc'>[] | null;\n /** The frame selected in the call stack (0 = top). */\n frame: number;\n /** Name of the program whose text the editor shows; null when the editor has no text. */\n programName: string | null;\n}\n\n/**\n * The line to highlight, or null: no JavaScript is running at this position, or the\n * script is one that neither code view can hold (another file of the user's project).\n */\nexport function highlightFor(input: HighlightInput): CodeHighlight | null {\n let loc: Loc;\n let kind: LineKind;\n const frames = input.frames;\n if (frames && frames.length > 0) {\n const at = Math.min(Math.max(0, input.frame), frames.length - 1);\n loc = (frames[at] as Pick<Frame, 'loc'>).loc;\n kind = at === 0 ? 'paused' : 'frame';\n } else if (input.source) {\n loc = input.source.loc;\n kind = input.source.why;\n } else {\n return null;\n }\n if (!Number.isInteger(loc.line) || loc.line < 1) return null;\n const where = input.programName !== null && isSameProgram(loc.url, input.programName) ? 'editor' : loc.url.startsWith('node:') ? 'source' : null;\n if (where === null) return null;\n return { where, url: loc.url, line: loc.line, kind, tag: LINE_TAGS[kind] };\n}\n\nexport function sameHighlight(a: CodeHighlight | null, b: CodeHighlight | null): boolean {\n if (a === null || b === null) return a === b;\n return a.where === b.where && a.url === b.url && a.line === b.line && a.kind === b.kind;\n}\n\n/** \"Paused on breakpoint\", \"Paused on step\", ...: the words DevTools uses, for the strip over the code. */\nexport function pauseWords(reason: string | null): string {\n switch (reason) {\n case 'breakpoint':\n return 'Paused on breakpoint';\n case 'step':\n return 'Paused on step';\n case 'entry':\n return 'Paused on the first line';\n case 'exception':\n return 'Paused on exception';\n case 'pause':\n return 'Paused';\n default:\n return 'Paused in the debugger';\n }\n}\n","/**\n * The two views of the app and their addresses. The address is the fragment, so it works\n * on a static site and from 127.0.0.1 alike, survives a reload, and back/forward work:\n *\n * (nothing), #/ the main view (map, code, panels)\n * #/learn the Learn page, at the lesson last read or the first one\n * #/learn/<lesson id> one lesson\n *\n * Any other fragment (a share link \"#r=...\") belongs to the main view and is left alone.\n */\n\nexport type Route = { view: 'main' } | { view: 'learn'; lesson: string | null };\n\n/** Lesson ids are file-name-like words; anything else in the address is not a lesson. */\nexport const LESSON_ID = /^[a-z0-9][a-z0-9._-]{0,80}$/i;\n\nexport function parseRoute(hash: string): Route {\n const path = hash.replace(/^#/, '');\n if (path !== '/learn' && !path.startsWith('/learn/')) return { view: 'main' };\n let id = path.slice('/learn/'.length).replace(/\\/+$/, '');\n try {\n id = decodeURIComponent(id);\n } catch {\n id = '';\n }\n return { view: 'learn', lesson: LESSON_ID.test(id) ? id : null };\n}\n\nexport function routeHash(route: Route): string {\n if (route.view === 'main') return '#/';\n return route.lesson !== null && LESSON_ID.test(route.lesson) ? `#/learn/${encodeURIComponent(route.lesson)}` : '#/learn';\n}\n\nexport function sameRoute(a: Route, b: Route): boolean {\n return a.view === b.view && (a.view !== 'learn' || b.view !== 'learn' || a.lesson === b.lesson);\n}\n","/**\n * The Learn course as data: reading its files defensively, and turning its blocks into\n * what the page may show.\n *\n * The course is ours, but it arrives as JSON over the network, so it is treated like any\n * other input: every text stays text (the page renders it with text nodes, never as\n * HTML), links go only to https addresses or to lessons that exist, and images and\n * recordings only to files inside the course's own folder. A link that fails these checks\n * is not dropped silently: its words stay, as plain text.\n */\nimport type { LearnBlock, LearnExample, LearnIndex, LearnInline, LearnLesson } from '@nodejs-map/protocol';\nimport { LESSON_ID, routeHash } from './route.ts';\n\nconst MAX_TEXT = 20_000;\nconst MAX_BLOCKS = 400;\nconst MAX_ITEMS = 200;\n\nconst str = (v: unknown, max = MAX_TEXT): string => (typeof v === 'string' ? v.slice(0, max) : '');\n\nexport function parseLearnIndex(raw: unknown): LearnIndex {\n if (typeof raw !== 'object' || raw === null || !Array.isArray((raw as { chapters?: unknown }).chapters)) throw new Error('no \"chapters\" list');\n const chapters: LearnIndex['chapters'] = [];\n for (const c of (raw as { chapters: unknown[] }).chapters.slice(0, 50)) {\n if (typeof c !== 'object' || c === null) continue;\n const ch = c as Record<string, unknown>;\n const lessons: LearnIndex['chapters'][number]['lessons'] = [];\n for (const l of Array.isArray(ch['lessons']) ? ch['lessons'].slice(0, MAX_ITEMS) : []) {\n if (typeof l !== 'object' || l === null) continue;\n const le = l as Record<string, unknown>;\n if (typeof le['id'] !== 'string' || !LESSON_ID.test(le['id']) || typeof le['file'] !== 'string') continue;\n const level = le['level'] === 'core' || le['level'] === 'deep' ? le['level'] : 'start';\n const minutes = typeof le['minutes'] === 'number' && Number.isFinite(le['minutes']) ? Math.max(1, Math.min(600, Math.round(le['minutes']))) : 1;\n lessons.push({ id: le['id'], title: str(le['title'], 160), summary: str(le['summary'], 600), minutes, level, file: le['file'].slice(0, 300) });\n }\n chapters.push({ id: str(ch['id'], 80), title: str(ch['title'], 160), summary: str(ch['summary'], 600), lessons });\n }\n return { version: 1, chapters };\n}\n\n/** Every lesson of the course in reading order. */\nexport function lessonsOf(index: LearnIndex): LearnIndex['chapters'][number]['lessons'] {\n return index.chapters.flatMap((c) => c.lessons);\n}\n\nfunction parseInline(raw: unknown): LearnInline[] {\n if (!Array.isArray(raw)) return typeof raw === 'string' ? [raw.slice(0, MAX_TEXT)] : [];\n const out: LearnInline[] = [];\n for (const part of raw.slice(0, MAX_ITEMS) as unknown[]) {\n if (typeof part === 'string') out.push(part.slice(0, MAX_TEXT));\n else if (typeof part === 'object' && part !== null) {\n const p = part as Record<string, unknown>;\n const text = str(p['text']);\n switch (p['t']) {\n case 'code':\n case 'strong':\n case 'em':\n case 'kbd':\n case 'ui':\n out.push({ t: p['t'], text });\n break;\n case 'path':\n out.push({ t: 'path', id: str(p['id'], 200), text });\n break;\n case 'link':\n out.push({ t: 'link', text, href: str(p['href'], 2000) });\n break;\n default:\n if (text) out.push(text); // an inline kind this version does not know: its words stay\n }\n }\n }\n return out;\n}\n\nfunction parseBlock(raw: unknown): LearnBlock | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const b = raw as Record<string, unknown>;\n switch (b['t']) {\n case 'p':\n return { t: 'p', text: parseInline(b['text']) };\n case 'h':\n return { t: 'h', level: b['level'] === 3 ? 3 : 2, id: str(b['id'], 120).replace(/[^\\w.-]+/g, '-'), text: str(b['text'], 300) };\n case 'list':\n return { t: 'list', ordered: b['ordered'] === true, items: (Array.isArray(b['items']) ? b['items'].slice(0, MAX_ITEMS) : []).map(parseInline) };\n case 'note':\n return { t: 'note', kind: b['kind'] === 'honest' || b['kind'] === 'warn' ? b['kind'] : 'tip', text: parseInline(b['text']) };\n case 'code':\n return { t: 'code', lang: b['lang'] === 'js' || b['lang'] === 'sh' ? b['lang'] : 'text', text: str(b['text'], 200_000) };\n case 'example':\n return { t: 'example', example: str(b['example'], 120) };\n case 'image': {\n const width = typeof b['width'] === 'number' && b['width'] > 0 && b['width'] < 20_000 ? Math.round(b['width']) : 0;\n const height = typeof b['height'] === 'number' && b['height'] > 0 && b['height'] < 20_000 ? Math.round(b['height']) : 0;\n if (typeof b['src'] !== 'string' || width === 0 || height === 0) return null;\n const caption = str(b['caption'], 600);\n return { t: 'image', src: b['src'].slice(0, 300), alt: str(b['alt'], 600), width, height, ...(caption ? { caption } : {}) };\n }\n case 'check':\n return { t: 'check', question: parseInline(b['question']), answer: parseInline(b['answer']) };\n default:\n return null; // a block kind this version does not know is left out\n }\n}\n\nfunction parseExample(id: string, raw: unknown): LearnExample | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const e = raw as Record<string, unknown>;\n if (typeof e['text'] !== 'string' || e['text'].length > 200_000) return null;\n const example: LearnExample = {\n id,\n title: str(e['title'], 200),\n name: str(e['name'], 80),\n module: e['module'] === 'esm' ? 'esm' : 'commonjs',\n text: e['text'],\n racy: e['racy'] === true,\n output: (Array.isArray(e['output']) ? e['output'].slice(0, 2000) : []).map((l) => str(l, 2000)),\n };\n if (typeof e['recording'] === 'string') example.recording = e['recording'].slice(0, 300);\n if (Array.isArray(e['steps'])) {\n example.steps = [];\n for (const s of e['steps'].slice(0, MAX_ITEMS) as unknown[]) {\n if (typeof s !== 'object' || s === null) continue;\n const step = s as Record<string, unknown>;\n if (typeof step['index'] !== 'number' || !Number.isInteger(step['index']) || step['index'] < 0) continue;\n example.steps.push({ index: step['index'], title: str(step['title'], 160), text: str(step['text'], 2000) });\n }\n example.steps.sort((a, b) => a.index - b.index);\n }\n return example;\n}\n\nexport function parseLearnLesson(raw: unknown): LearnLesson {\n if (typeof raw !== 'object' || raw === null || !Array.isArray((raw as { blocks?: unknown }).blocks)) throw new Error('no \"blocks\" list');\n const l = raw as Record<string, unknown>;\n const examples: Record<string, LearnExample> = {};\n if (typeof l['examples'] === 'object' && l['examples'] !== null) {\n for (const [id, value] of Object.entries(l['examples']).slice(0, MAX_ITEMS)) {\n const example = parseExample(id.slice(0, 120), value);\n if (example) examples[example.id] = example;\n }\n }\n const neighbour = (v: unknown): { id: string; title: string } | undefined => {\n if (typeof v !== 'object' || v === null) return undefined;\n const n = v as Record<string, unknown>;\n return typeof n['id'] === 'string' && LESSON_ID.test(n['id']) ? { id: n['id'], title: str(n['title'], 160) } : undefined;\n };\n const prev = neighbour(l['prev']);\n const next = neighbour(l['next']);\n return {\n id: str(l['id'], 80),\n chapter: str(l['chapter'], 80),\n title: str(l['title'], 200),\n summary: str(l['summary'], 800),\n blocks: (l['blocks'] as unknown[]).slice(0, MAX_BLOCKS).map(parseBlock).filter((b): b is LearnBlock => b !== null),\n examples,\n ...(prev ? { prev } : {}),\n ...(next ? { next } : {}),\n };\n}\n\n// ---- what the page may show ---------------------------------------------------------------\n\n/** One piece of inline text, ready to render. `text` is always shown as a text node. */\nexport type InlinePiece =\n | { kind: 'text' | 'code' | 'strong' | 'em' | 'kbd' | 'ui'; text: string }\n /** A link inside the app: another lesson. */\n | { kind: 'lesson'; text: string; href: string; lesson: string }\n /** A link to another site: https only, opened in a new tab without a referrer. */\n | { kind: 'external'; text: string; href: string }\n /** A curated call path of the map. */\n | { kind: 'path'; text: string; id: string };\n\nexport interface RenderContext {\n /** Does a lesson with this id exist in the course? */\n hasLesson(id: string): boolean;\n}\n\n/** An https address, as the URL parser sees it; null for anything else (javascript:, data:, http:, relative...). */\nexport function safeExternalUrl(href: string): string | null {\n let url: URL;\n try {\n url = new URL(href);\n } catch {\n return null;\n }\n return url.protocol === 'https:' && url.username === '' && url.password === '' ? url.href : null;\n}\n\nexport function inlinePieces(inline: readonly LearnInline[], ctx: RenderContext): InlinePiece[] {\n return inline.map((part): InlinePiece => {\n if (typeof part === 'string') return { kind: 'text', text: part };\n switch (part.t) {\n case 'link': {\n if (part.href.startsWith('learn:')) {\n const lesson = part.href.slice('learn:'.length);\n // A lesson that does not exist: the words stay, the link does not.\n return LESSON_ID.test(lesson) && ctx.hasLesson(lesson) ? { kind: 'lesson', text: part.text, lesson, href: routeHash({ view: 'learn', lesson }) } : { kind: 'text', text: part.text };\n }\n const href = safeExternalUrl(part.href);\n return href ? { kind: 'external', text: part.text, href } : { kind: 'text', text: part.text };\n }\n case 'path':\n return /^p:[\\w.-]{1,120}$/.test(part.id) ? { kind: 'path', text: part.text, id: part.id } : { kind: 'text', text: part.text };\n default:\n return { kind: part.t, text: part.text };\n }\n });\n}\n\n/**\n * The address of a file a lesson names (an image, a recording): relative to the lesson\n * file, and never outside the folder of the course.\n */\nexport function courseFileUrl(indexUrl: string, lessonUrl: string, file: string): string | null {\n let url: URL;\n let base: URL;\n try {\n base = new URL('.', indexUrl);\n url = new URL(file, lessonUrl);\n } catch {\n return null;\n }\n if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) return null;\n return url.href;\n}\n\n/** A file name the editor accepts for a snippet; else a plain default with the right extension. */\nexport function snippetNameFor(example: Pick<LearnExample, 'name' | 'module'>): string {\n return /^\\w[\\w.-]{0,80}$/.test(example.name) ? example.name : example.module === 'esm' ? 'example.mjs' : 'example.js';\n}\n\n// ---- progress ----------------------------------------------------------------------------\n\nexport interface LearnProgress {\n /** Ids of the lessons marked as done. */\n done: string[];\n /** The lesson last opened, for \"#/learn\" without an id. */\n last: string | null;\n /** The \"New here?\" offer of the main view was dismissed. */\n introDismissed: boolean;\n}\n\nexport const LEARN_STORAGE_KEY = 'nodejs-map.learn.v1';\n\nexport function parseProgress(text: string | null): LearnProgress {\n const empty: LearnProgress = { done: [], last: null, introDismissed: false };\n if (text === null) return empty;\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch {\n return empty;\n }\n if (typeof raw !== 'object' || raw === null) return empty;\n const r = raw as Record<string, unknown>;\n const done = Array.isArray(r['done']) ? [...new Set(r['done'].filter((x): x is string => typeof x === 'string' && LESSON_ID.test(x)))].slice(0, 1000) : [];\n return { done, last: typeof r['last'] === 'string' && LESSON_ID.test(r['last']) ? r['last'] : null, introDismissed: r['introDismissed'] === true };\n}\n","/**\n * The app's side of the helper protocol: one WebSocket, requests matched to replies by id.\n *\n * Two things are deliberate here:\n *\n * - `events` messages can carry thousands of events. The page must not parse them (the\n * replay model lives in a worker), so a frame that starts like an `events` message is\n * handed on as text, unparsed. The check looks only at the start of the frame; if the\n * helper ever orders the keys differently the frame is parsed here instead, which is\n * slower but still correct.\n * - Everything received is data. Nothing in a message can make the app send a `run`.\n */\nimport type { ClientMessage, ServerMessage } from '@nodejs-map/protocol';\nimport { PROTOCOL_VERSION } from '@nodejs-map/protocol';\n\n/** Distributes Omit over the members of the ClientMessage union. */\ntype WithoutId<T> = T extends unknown ? Omit<T, 'id'> : never;\nexport type ClientRequest = WithoutId<ClientMessage>;\n\ntype ReplyOpFor = {\n hello: 'welcome';\n run: 'run.started';\n stop: 'ok';\n 'debug.breakpoints': 'ok';\n 'debug.do': 'ok';\n 'debug.scopes': 'debug.scopes';\n 'debug.props': 'debug.props';\n source: 'source';\n 'gate.do': 'ok';\n 'files.list': 'files.list';\n 'files.read': 'files.read';\n};\nconst REPLY_OP: ReplyOpFor = {\n hello: 'welcome',\n run: 'run.started',\n stop: 'ok',\n 'debug.breakpoints': 'ok',\n 'debug.do': 'ok',\n 'debug.scopes': 'debug.scopes',\n 'debug.props': 'debug.props',\n source: 'source',\n 'gate.do': 'ok',\n 'files.list': 'files.list',\n 'files.read': 'files.read',\n};\n\nexport type ReplyTo<Op extends ClientMessage['op']> = Extract<ServerMessage, { op: ReplyOpFor[Op]; re: number }>;\nexport type Welcome = Extract<ServerMessage, { op: 'welcome' }>;\nexport type Pushed = Extract<ServerMessage, { op: 'run.ended' | 'notice' | 'events' }>;\n\n/** The part of WebSocket the client uses; tests pass a fake. */\nexport interface SocketLike {\n send(text: string): void;\n close(): void;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onclose: ((ev: unknown) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n}\n\nexport interface ProtocolClientOptions {\n socket: SocketLike;\n /** An `events` frame, as text, not parsed. */\n onEventsText(text: string): void;\n /** Any other message the helper sent on its own. */\n onPush(message: Exclude<Pushed, { op: 'events' }>): void;\n onClose(): void;\n /** Milliseconds after which an unanswered request fails. */\n timeoutMs?: number;\n}\n\nconst EVENTS_FRAME = /^\\s*\\{\\s*\"op\"\\s*:\\s*\"events\"\\s*[,}]/;\n\nexport class HelperError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'HelperError';\n }\n}\n\nexport class ProtocolClient {\n readonly #socket: SocketLike;\n readonly #opts: ProtocolClientOptions;\n readonly #waiting = new Map<number, { op: string; resolve: (m: ServerMessage) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>();\n #nextId = 1;\n #open = false;\n #closed = false;\n readonly #opened: Promise<void>;\n\n constructor(opts: ProtocolClientOptions) {\n this.#opts = opts;\n this.#socket = opts.socket;\n this.#opened = new Promise<void>((resolve, reject) => {\n this.#socket.onopen = () => {\n this.#open = true;\n resolve();\n };\n this.#socket.onerror = () => reject(new HelperError('Could not connect to the helper.'));\n this.#socket.onclose = () => {\n reject(new HelperError('The connection to the helper closed.'));\n this.#handleClose();\n };\n });\n // A rejected open with no request waiting must not surface as an unhandled rejection.\n this.#opened.catch(() => undefined);\n this.#socket.onmessage = (ev) => this.#handleMessage(ev.data);\n }\n\n /** Sends `hello` and returns the helper's welcome. Rejects when the versions differ. */\n async hello(): Promise<Welcome> {\n const welcome = await this.request({ op: 'hello', protocol: PROTOCOL_VERSION });\n if (welcome.protocol !== PROTOCOL_VERSION) {\n throw new HelperError(\n `This page speaks helper protocol ${PROTOCOL_VERSION}, the helper speaks ${String(welcome.protocol)}. Restart nodejs-map so both come from the same version.`,\n );\n }\n return welcome;\n }\n\n async request<M extends ClientRequest>(message: M): Promise<ReplyTo<M['op']>> {\n await this.#opened;\n if (this.#closed) throw new HelperError('The connection to the helper closed.');\n const id = this.#nextId++;\n return new Promise<ReplyTo<M['op']>>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.#waiting.delete(id);\n reject(new HelperError(`The helper did not answer \"${message.op}\".`));\n }, this.#opts.timeoutMs ?? 15_000);\n this.#waiting.set(id, { op: message.op, resolve: resolve as (m: ServerMessage) => void, reject, timer });\n this.#socket.send(JSON.stringify({ ...message, id }));\n });\n }\n\n close(): void {\n this.#socket.close();\n this.#handleClose();\n }\n\n get isOpen(): boolean {\n return this.#open && !this.#closed;\n }\n\n #handleClose(): void {\n if (this.#closed) return;\n this.#closed = true;\n for (const w of this.#waiting.values()) {\n clearTimeout(w.timer);\n w.reject(new HelperError('The connection to the helper closed.'));\n }\n this.#waiting.clear();\n this.#opts.onClose();\n }\n\n #handleMessage(data: unknown): void {\n if (typeof data !== 'string') return; // the protocol is text frames only\n if (EVENTS_FRAME.test(data.length > 64 ? data.slice(0, 64) : data)) {\n this.#opts.onEventsText(data);\n return;\n }\n let message: ServerMessage;\n try {\n message = JSON.parse(data) as ServerMessage;\n } catch {\n return;\n }\n if (typeof message !== 'object' || message === null || typeof message.op !== 'string') return;\n if (message.op === 'events') {\n // Key order differed from what the fast path expects: pass the text on all the same.\n this.#opts.onEventsText(data);\n return;\n }\n if ('re' in message && typeof message.re === 'number') {\n const w = this.#waiting.get(message.re);\n if (!w) return;\n this.#waiting.delete(message.re);\n clearTimeout(w.timer);\n if (message.op === 'error') w.reject(new HelperError(String(message.message)));\n else if (message.op !== REPLY_OP[w.op as keyof ReplyOpFor]) w.reject(new HelperError(`Unexpected reply \"${message.op}\" to \"${w.op}\".`));\n else w.resolve(message);\n return;\n }\n if (message.op === 'run.ended' || message.op === 'notice') this.#opts.onPush(message);\n }\n}\n\n/** Turns the relative WebSocket path of config.json into an absolute ws: or wss: URL. */\nexport function webSocketUrl(relative: string, pageUrl: string): string {\n const url = new URL(relative, pageUrl);\n url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';\n url.hash = '';\n return url.href;\n}\n","/**\n * What the source panel shows: a file of Node's source at the atlas commit, a line range\n * in it, and the links out. This module turns the things a user can click (a map box, a\n * stack frame, a rule citation, an event) into such a target. It never holds source text.\n */\nimport type { Frame } from '@nodejs-map/event-format';\nimport { githubBlobUrl, githubDevUrl, githubTreeUrl, rawSourceUrl, scriptUrlToPath } from '@nodejs-map/atlas-format';\nimport type { AtlasStore, Platform } from '@nodejs-map/atlas-format';\n\nexport interface SourceTarget {\n /** What was opened, in words: a box title or a function name. */\n title: string;\n /** One-line description from the atlas, when there is one. */\n description: string | null;\n /** Atlas id, when the target is (or lies in) a box of the map. */\n atlasId: string | null;\n /** Repository path at the atlas commit. null: the target has no file (a folder, or nothing known). */\n path: string | null;\n /** 1-based inclusive line range to highlight. null: the whole file. */\n start: number | null;\n end: number | null;\n /** A single line to mark inside the range (the paused line of a frame). */\n line: number | null;\n /** \"node:...\" script URL when the text can also come from the running target. */\n scriptUrl: string | null;\n /** Condition for per-platform variants (\"#if defined(_WIN32)\"). */\n variant: string | null;\n github: string | null;\n githubDev: string | null;\n raw: string | null;\n /** Why there is nothing to show, when there is not. */\n note: string | null;\n}\n\nconst EMPTY: Omit<SourceTarget, 'title'> = {\n description: null,\n atlasId: null,\n path: null,\n start: null,\n end: null,\n line: null,\n scriptUrl: null,\n variant: null,\n github: null,\n githubDev: null,\n raw: null,\n note: null,\n};\n\nexport function normalizePlatform(platform: string | null | undefined): Platform {\n return platform === 'win32' || platform === 'darwin' ? platform : 'linux';\n}\n\nfunction fileTarget(commit: string, title: string, path: string, start: number | null, end: number | null): SourceTarget {\n return {\n ...EMPTY,\n title,\n path,\n start,\n end,\n github: githubBlobUrl(commit, path, start ?? undefined, end ?? undefined),\n githubDev: githubDevUrl(commit, path, start ?? undefined, end ?? undefined),\n raw: rawSourceUrl(commit, path),\n };\n}\n\n/** A box of the map (or any atlas id cited by a rule or carried by an event). */\nexport async function targetForAtlasId(atlas: AtlasStore, platform: Platform, id: string): Promise<SourceTarget> {\n let box;\n try {\n box = await atlas.box(id);\n } catch {\n return { ...EMPTY, title: id, atlasId: id, note: 'The map data for this place could not be loaded.' };\n }\n if (!box) {\n return { ...EMPTY, title: id, atlasId: id, note: `This place (${id}) is not in the map for Node ${atlas.index.node.version}.` };\n }\n const commit = atlas.commit;\n const range = atlas.pickRange(box, platform);\n if (range) {\n return {\n ...fileTarget(commit, box.title, range.path, range.start, range.end),\n description: box.desc ?? null,\n atlasId: box.id,\n variant: range.cond ?? box.variant ?? null,\n scriptUrl: null,\n };\n }\n if (box.ranges.length > 0) {\n // The box has code, but not on this platform (for example a Windows-only step on Linux).\n const other = box.ranges[0];\n return {\n ...EMPTY,\n title: box.title,\n description: box.desc ?? null,\n atlasId: box.id,\n note: `This code does not exist on ${platform === 'win32' ? 'Windows' : platform === 'darwin' ? 'macOS' : 'Linux'}${other ? `; it lives in ${other.path}` : ''}.`,\n };\n }\n if (box.file) {\n return { ...fileTarget(commit, box.title, box.file.path, null, null), description: box.desc ?? null, atlasId: box.id };\n }\n if (box.tree) {\n return {\n ...EMPTY,\n title: box.title,\n description: box.desc ?? null,\n atlasId: box.id,\n github: githubTreeUrl(commit, box.tree),\n note: 'This box is a folder. Zoom in on the map to reach its files, or open the folder on GitHub.',\n };\n }\n return {\n ...EMPTY,\n title: box.title,\n description: box.desc ?? null,\n atlasId: box.id,\n note: 'This box has no source in Node.js itself.',\n };\n}\n\n/** A stack frame in Node's own JavaScript (\"node:internal/timers\"). */\nexport async function targetForNodeFrame(atlas: AtlasStore | null, frame: Frame): Promise<SourceTarget> {\n const title = frame.fn || '(anonymous)';\n const path = scriptUrlToPath(frame.loc.url);\n if (!path) {\n return { ...EMPTY, title, note: `${frame.loc.url} is not part of Node's own JavaScript, so there is no source to link to.` };\n }\n if (!atlas) {\n return { ...EMPTY, title, path, line: frame.loc.line, scriptUrl: frame.loc.url, note: null };\n }\n const commit = atlas.commit;\n let boxId: string | undefined = frame.at;\n if (!boxId) {\n try {\n boxId = await atlas.locate(path, frame.loc.line);\n } catch {\n boxId = undefined;\n }\n }\n let start: number | null = frame.loc.line;\n let end: number | null = frame.loc.line;\n if (boxId) {\n const box = await atlas.box(boxId).catch(() => undefined);\n const range = box?.ranges.find((r) => r.path === path && frame.loc.line >= r.start && frame.loc.line <= r.end);\n if (range) {\n start = range.start;\n end = range.end;\n }\n }\n return {\n ...fileTarget(commit, title, path, start, end),\n atlasId: boxId ?? null,\n line: frame.loc.line,\n scriptUrl: frame.loc.url,\n };\n}\n\nexport type SourceLanguage = 'javascript' | 'cpp' | 'plain';\n\nexport function languageOfPath(path: string): SourceLanguage {\n if (/\\.(?:m?js|cjs)$/i.test(path)) return 'javascript';\n if (/\\.(?:c|cc|cpp|cxx|h|hh|hpp|inl|inc)$/i.test(path)) return 'cpp';\n return 'plain';\n}\n","/**\n * The atlas store: which atlas (map data for one Node release) is loaded.\n *\n * Helper mode loads the atlas the helper serves. Player mode loads the one named in the\n * recording's header; when the site does not have it we say so plainly and show no map\n * (never another version's map as if it were the right one).\n */\nimport { signal } from '@preact/signals';\nimport type { ReadonlySignal } from '@preact/signals';\nimport { AtlasStore } from '@nodejs-map/atlas-format';\nimport { milestone } from '../lib/marks.ts';\n\nexport type AtlasState =\n | { status: 'none' }\n | { status: 'loading'; tag: string }\n | { status: 'ready'; tag: string; commit: string; store: AtlasStore; /** Absolute URL of the atlas folder. */ base: string }\n | { status: 'missing'; tag: string; reason: string };\n\nexport interface AtlasStoreHandle {\n readonly state: ReadonlySignal<AtlasState>;\n /**\n * Loads the atlas in `folder` (a URL relative to the page, holding index.json).\n * A second call for the same folder does nothing; a call for another folder replaces it.\n */\n load(folder: string, tag: string): Promise<void>;\n /** Says that no atlas is available for `tag`, with the reason. */\n unavailable(tag: string, reason: string): void;\n}\n\nexport interface AtlasDeps {\n /** Absolute URL of the page, to resolve relative folders against. */\n pageUrl(): string;\n fetchJson(url: string): Promise<unknown>;\n}\n\n/** A release tag as it may appear in a URL path: \"v26.13.1\". Recording headers are untrusted. */\nexport function isSafeTag(tag: string): boolean {\n return /^v\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(tag);\n}\n\nexport function withSlash(folder: string): string {\n return folder.endsWith('/') ? folder : `${folder}/`;\n}\n\n/**\n * Resolves `relative` inside `folder`; null when it would leave the folder. Atlas files\n * name their own chunk URLs, so a bad file must not be able to point the app elsewhere.\n */\nexport function urlInside(folder: URL, relative: string): string | null {\n let url: URL;\n try {\n url = new URL(relative, folder);\n } catch {\n return null;\n }\n if (url.origin !== folder.origin || !url.pathname.startsWith(folder.pathname)) return null;\n return url.href;\n}\n\nexport function createAtlasStore(deps: AtlasDeps): AtlasStoreHandle {\n const state = signal<AtlasState>({ status: 'none' });\n let current = '';\n\n return {\n state,\n async load(folder, tag) {\n const base = new URL(withSlash(folder), deps.pageUrl());\n if (base.href === current) return;\n current = base.href;\n state.value = { status: 'loading', tag };\n const store = new AtlasStore({\n fetchJson: (relative) => {\n const url = urlInside(base, relative);\n return url === null ? Promise.reject(new Error(`The atlas names a file outside its folder: ${relative}`)) : deps.fetchJson(url);\n },\n });\n try {\n const index = await store.load();\n if (current !== base.href) return; // replaced while loading\n state.value = { status: 'ready', tag: `v${index.node.version.replace(/^v/, '')}`, commit: index.node.commit, store, base: base.href };\n milestone('atlas');\n } catch (e) {\n if (current !== base.href) return;\n current = '';\n state.value = { status: 'missing', tag, reason: e instanceof Error ? e.message : String(e) };\n }\n },\n unavailable(tag, reason) {\n current = '';\n state.value = { status: 'missing', tag, reason };\n },\n };\n}\n\n/** fetch + JSON with a clear error for the two usual failures. */\nexport async function fetchJson(url: string): Promise<unknown> {\n let response: Response;\n try {\n response = await fetch(url, { credentials: 'same-origin' });\n } catch {\n throw new Error('could not be loaded (no connection?)');\n }\n if (!response.ok) throw new Error(response.status === 404 ? 'is not on this site' : `could not be loaded (HTTP ${response.status})`);\n return (await response.json()) as unknown;\n}\n","/**\n * The connection store: which mode the app is in and, in helper mode, the WebSocket to\n * the helper and what its welcome said (providers, capability notes, atlas, folder).\n */\nimport { computed, signal } from '@preact/signals';\nimport type { ReadonlySignal } from '@preact/signals';\nimport type { AppConfig, CapabilityNotes, ProviderInfo } from '@nodejs-map/protocol';\nimport { HelperError, ProtocolClient } from '../lib/protocolClient.ts';\nimport type { ClientRequest, Pushed, ReplyTo, SocketLike, Welcome } from '../lib/protocolClient.ts';\n\nexport type ConnectionStatus =\n /** Player mode, or config.json not read yet: there is no helper. */\n | 'none'\n | 'connecting'\n | 'open'\n /** Was open; the helper went away. */\n | 'closed'\n /** Never opened. */\n | 'failed';\n\nexport interface Notice {\n id: number;\n level: 'info' | 'warn' | 'error';\n text: string;\n}\n\nexport interface ConnectionStore {\n readonly config: ReadonlySignal<AppConfig | null>;\n /** null until config.json is read. */\n readonly mode: ReadonlySignal<'helper' | 'player' | null>;\n readonly status: ReadonlySignal<ConnectionStatus>;\n readonly welcome: ReadonlySignal<Welcome | null>;\n readonly providers: ReadonlySignal<readonly ProviderInfo[]>;\n readonly notes: ReadonlySignal<CapabilityNotes>;\n readonly notices: ReadonlySignal<readonly Notice[]>;\n /** Why the connection is not open, in words. */\n readonly error: ReadonlySignal<string | null>;\n\n setConfig(config: AppConfig): void;\n /** Opens the WebSocket and says hello. Resolves when the welcome is in (or the attempt failed). */\n connect(url: string): Promise<void>;\n request<M extends ClientRequest>(message: M): Promise<ReplyTo<M['op']>>;\n notify(level: Notice['level'], text: string): void;\n dismiss(id: number): void;\n}\n\nexport interface ConnectionDeps {\n makeSocket(url: string): SocketLike;\n onEventsText(text: string): void;\n onRunEnded(message: Extract<Pushed, { op: 'run.ended' }>): void;\n}\n\nconst MAX_NOTICES = 5;\nconst MAX_NOTICE_CHARS = 600;\n\n/**\n * The address of the public player site, for share links: an http(s) URL without query or\n * fragment. Anything else is dropped (the app then offers the file instead of a link).\n */\nfunction publicUrl(text: string | undefined): string | undefined {\n if (text === undefined) return undefined;\n try {\n const url = new URL(text);\n if (url.protocol !== 'https:' && url.protocol !== 'http:') return undefined;\n url.hash = '';\n url.search = '';\n return url.href;\n } catch {\n return undefined;\n }\n}\n\n/** Checks the shape of config.json. It is fetched from our own origin, but a wrong file must fail clearly. */\nexport function parseAppConfig(raw: unknown): AppConfig {\n if (typeof raw !== 'object' || raw === null) throw new Error('config.json is not an object.');\n const c = raw as Record<string, unknown>;\n const optionalPath = (key: string): string | undefined => {\n const v = c[key];\n if (v === undefined) return undefined;\n if (typeof v !== 'string') throw new Error(`config.json: \"${key}\" must be text.`);\n return v;\n };\n const atlasBase = c['atlasBase'];\n if (typeof atlasBase !== 'string') throw new Error('config.json: \"atlasBase\" is missing.');\n const examples = optionalPath('examples');\n const lessons = optionalPath('lessons');\n const learn = optionalPath('learn');\n if (c['mode'] === 'helper') {\n if (typeof c['ws'] !== 'string') throw new Error('config.json: \"ws\" is missing.');\n const playerUrl = publicUrl(optionalPath('playerUrl'));\n return {\n mode: 'helper',\n ws: c['ws'],\n atlasBase,\n ...(examples !== undefined ? { examples } : {}),\n ...(lessons !== undefined ? { lessons } : {}),\n ...(learn !== undefined ? { learn } : {}),\n ...(playerUrl !== undefined ? { playerUrl } : {}),\n };\n }\n if (c['mode'] === 'player') {\n return { mode: 'player', atlasBase, ...(lessons !== undefined ? { lessons } : {}), ...(learn !== undefined ? { learn } : {}) };\n }\n throw new Error('config.json: \"mode\" must be \"helper\" or \"player\".');\n}\n\nexport function createConnectionStore(deps: ConnectionDeps): ConnectionStore {\n const config = signal<AppConfig | null>(null);\n const status = signal<ConnectionStatus>('none');\n const welcome = signal<Welcome | null>(null);\n const notices = signal<readonly Notice[]>([]);\n const error = signal<string | null>(null);\n let client: ProtocolClient | null = null;\n let nextNotice = 1;\n\n const notify = (level: Notice['level'], text: string): void => {\n const notice: Notice = { id: nextNotice++, level, text: text.slice(0, MAX_NOTICE_CHARS) };\n notices.value = [...notices.value, notice].slice(-MAX_NOTICES);\n };\n\n return {\n config,\n mode: computed(() => config.value?.mode ?? null),\n status,\n welcome,\n providers: computed(() => welcome.value?.providers ?? []),\n notes: computed(() => welcome.value?.notes ?? {}),\n notices,\n error,\n setConfig(next) {\n config.value = next;\n },\n async connect(url) {\n status.value = 'connecting';\n error.value = null;\n let opened = false;\n const mine = new ProtocolClient({\n socket: deps.makeSocket(url),\n onEventsText: deps.onEventsText,\n onPush(message) {\n if (message.op === 'notice') notify(message.level, String(message.text));\n else deps.onRunEnded(message);\n },\n onClose() {\n if (client !== mine || status.value === 'failed') return; // keep the more specific reason\n status.value = opened ? 'closed' : 'failed';\n error.value = opened\n ? 'The helper stopped or the connection was lost. Start nodejs-map again in a terminal, then reload this page.'\n : 'Could not connect to the helper. Start nodejs-map again in a terminal; this page works only with the helper that opened it.';\n },\n });\n client = mine;\n try {\n welcome.value = await mine.hello();\n opened = true;\n status.value = 'open';\n } catch (e) {\n if (client === mine && status.value === 'connecting') {\n status.value = 'failed';\n error.value = e instanceof HelperError ? e.message : 'Could not connect to the helper.';\n }\n mine.close();\n }\n },\n request(message) {\n if (!client || status.value !== 'open') return Promise.reject(new HelperError('The helper is not connected.'));\n return client.request(message);\n },\n notify,\n dismiss(id) {\n notices.value = notices.value.filter((n) => n.id !== id);\n },\n };\n}\n","/**\n * The player store: the page's side of the worker.\n *\n * It holds what the worker last said (view state, player state, timeline, markers, the\n * state of the run's tail) as signals, and turns user actions into worker messages.\n *\n * The view state arrives as patches (replay's `views: 'patch'`): only the parts that\n * changed since the last post. applyViewPatch keeps every untouched part the very same\n * object, and the store has ONE SIGNAL PER PART (`parts`). A panel reads the parts it\n * draws and nothing else, so a step that only moves the nextTick queue re-renders the\n * nextTick queue - not the pool lanes, the phase ring or the output. This, more than the\n * size of the messages, is what keeps a step of playback short on a slow device.\n *\n * The clock is the page's: one `tick` per animation frame while something can change\n * (playing, a live run, indexing, or just after a command), and never a second tick\n * before the worker has answered the first. The worker answers a tick with at most one\n * view, so a slow page or a slow worker means fewer views, not a growing backlog.\n */\nimport { batch, signal } from '@preact/signals';\nimport type { ReadonlySignal, Signal } from '@preact/signals';\nimport type { QueueName, RecordingHeader } from '@nodejs-map/event-format';\nimport { applyViewPatch } from '@nodejs-map/replay';\nimport type {\n DebugView,\n FocusView,\n SourceSpot,\n LoopView,\n MainThreadView,\n NotesView,\n OutputView,\n PlayerCommand,\n PlayerState,\n PoolView,\n ProblemCounts,\n QueueView,\n ReplayAnswer,\n ReplayQuery,\n RunView,\n ShareResult,\n TimelineAxis,\n TimelineMarkers,\n TimelineSummary,\n TimersView,\n ViewOptions,\n ViewState,\n} from '@nodejs-map/replay';\nimport type { LogFilter, LogWindow, TailState } from '../lib/logIndex.ts';\nimport type { WorkerMessage, WorkerRequest } from '../worker/protocol.ts';\n\n/** The part of Worker the store uses; tests pass a fake that runs AppHost in-process. */\nexport interface WorkerLike {\n postMessage(message: WorkerRequest, transfer?: Transferable[]): void;\n onmessage: ((event: { data: WorkerMessage }) => void) | null;\n onerror: ((event: unknown) => void) | null;\n}\n\nexport interface FrameClock {\n /** Calls `fn` before the next paint with a steady millisecond time; returns a cancel function. */\n request(fn: (now: number) => void): () => void;\n now(): number;\n}\n\ntype AnswerOf<Q extends ReplayQuery> = Extract<ReplayAnswer, { what: Q['what'] }>;\n\nexport interface OpenedRecording {\n header: RecordingHeader;\n events: number;\n}\n\nexport interface FinishedRun {\n /** False when the run named is not the one on show any more. */\n current: boolean;\n length: number;\n /** Meaningful steps (events that are not raw signals). */\n steps: number;\n /** Times the program was stopped during the run (debugger pauses and gate stops). */\n pauses: number;\n}\n\nexport interface TailInfo extends TailState {\n run: string | null;\n}\n\n/**\n * The view state, one signal per part. A part's signal changes only when that part\n * changed; null (or 0 / false for the plain values) means there is no view yet.\n */\nexport interface ViewParts {\n /** Events applied: the state is \"after the first `position` events\". */\n readonly position: ReadonlySignal<number>;\n readonly length: ReadonlySignal<number>;\n readonly ready: ReadonlySignal<number>;\n readonly live: ReadonlySignal<boolean>;\n /** Bumped every time the event list changes. */\n readonly version: ReadonlySignal<number>;\n /** Time at the position, microseconds. */\n readonly t: ReadonlySignal<number>;\n readonly run: ReadonlySignal<RunView | null>;\n readonly main: ReadonlySignal<MainThreadView | null>;\n readonly loop: ReadonlySignal<LoopView | null>;\n readonly timers: ReadonlySignal<TimersView | null>;\n readonly pool: ReadonlySignal<PoolView | null>;\n readonly output: ReadonlySignal<OutputView | null>;\n readonly debug: ReadonlySignal<DebugView | null>;\n readonly notes: ReadonlySignal<NotesView | null>;\n readonly focus: ReadonlySignal<FocusView | null>;\n /** The line of code the run or replay is at (replay's ViewState.source); null when no JavaScript is running. */\n readonly source: ReadonlySignal<SourceSpot | null>;\n readonly problems: ReadonlySignal<ProblemCounts | null>;\n readonly itemCount: ReadonlySignal<number>;\n readonly queues: Readonly<Record<QueueName, ReadonlySignal<QueueView | null>>>;\n}\n\nexport const QUEUE_NAMES: readonly QueueName[] = ['nextTick', 'microtask', 'timers', 'immediate', 'pool', 'io', 'close'];\n\nexport interface PlayerStore {\n /**\n * The whole view. It is a new object on every step: components must read `parts`\n * instead. This signal is for tests and for code that reads once without subscribing\n * (`view.peek()`).\n */\n readonly view: ReadonlySignal<ViewState | null>;\n readonly parts: ViewParts;\n readonly player: ReadonlySignal<PlayerState | null>;\n readonly timeline: ReadonlySignal<TimelineSummary | null>;\n readonly markers: ReadonlySignal<TimelineMarkers | null>;\n readonly tail: ReadonlySignal<TailInfo>;\n /** The latest problem the worker reported that belongs to no request. */\n readonly problem: ReadonlySignal<string | null>;\n /** False until the worker has loaded. */\n readonly ready: ReadonlySignal<boolean>;\n\n command(cmd: PlayerCommand): void;\n query<Q extends ReplayQuery>(q: Q): Promise<AnswerOf<Q>>;\n log(filter: LogFilter, offset: number, limit: number, position: number): Promise<LogWindow>;\n setTimeline(width: number, axis: TimelineAxis): void;\n /** Changes the caps of the posted view (for example: output chunks only while the Output panel is on show). */\n setViewCaps(caps: ViewOptions): void;\n\n newRun(): void;\n setRun(run: string): void;\n eventsText(text: string): void;\n /** Tells the worker that the run is over; resolves to the final size of the run. */\n runEnded(run: string): Promise<FinishedRun>;\n /**\n * How many times the position was taken in hand so far: play, pause, a step, a seek, or\n * turning off \"follow the live run\". Compared before and after a run, it says whether\n * the user took control of the player during it.\n */\n touches(): number;\n open(data: string | ArrayBuffer | Uint8Array): Promise<OpenedRecording>;\n openFragment(fragment: string): Promise<OpenedRecording>;\n close(): void;\n save(header: RecordingHeader, gzip: boolean): Promise<Uint8Array>;\n share(header: RecordingHeader): Promise<ShareResult>;\n dispose(): void;\n}\n\n/**\n * What the worker puts into a posted view. The panels draw at most 60 rows per list;\n * the event log is not taken from the view at all (the Events panel asks for the rows it\n * shows); output chunks are asked for only while the Output panel is on show.\n */\nexport const VIEW_OPTIONS: ViewOptions = { maxEntries: 60, maxOutput: 0, maxNotes: 5, maxLog: 0, items: 'none' };\n/** Output chunks in the view while the Output panel is on show. */\nexport const OUTPUT_CHUNKS_ON_SHOW = 150;\n\n/** After a command, keep ticking this long so its effect is picked up even when nothing plays. */\nconst KICK_MS = 600;\n/** A tick unanswered for this long is taken as lost. */\nconst TICK_TIMEOUT_MS = 1000;\n\ninterface Waiting {\n resolve: (value: never) => void;\n reject: (error: Error) => void;\n}\n\ninterface PartSignals {\n position: Signal<number>;\n length: Signal<number>;\n ready: Signal<number>;\n live: Signal<boolean>;\n version: Signal<number>;\n t: Signal<number>;\n run: Signal<RunView | null>;\n main: Signal<MainThreadView | null>;\n loop: Signal<LoopView | null>;\n timers: Signal<TimersView | null>;\n pool: Signal<PoolView | null>;\n output: Signal<OutputView | null>;\n debug: Signal<DebugView | null>;\n notes: Signal<NotesView | null>;\n focus: Signal<FocusView | null>;\n source: Signal<SourceSpot | null>;\n problems: Signal<ProblemCounts | null>;\n itemCount: Signal<number>;\n queues: Record<QueueName, Signal<QueueView | null>>;\n}\n\nfunction createParts(): PartSignals {\n return {\n position: signal(0),\n length: signal(0),\n ready: signal(0),\n live: signal(false),\n version: signal(0),\n t: signal(0),\n run: signal(null),\n main: signal(null),\n loop: signal(null),\n timers: signal(null),\n pool: signal(null),\n output: signal(null),\n debug: signal(null),\n notes: signal(null),\n focus: signal(null),\n source: signal(null),\n problems: signal(null),\n itemCount: signal(0),\n queues: Object.fromEntries(QUEUE_NAMES.map((q) => [q, signal<QueueView | null>(null)])) as Record<QueueName, Signal<QueueView | null>>,\n };\n}\n\nexport function createPlayerStore(worker: WorkerLike, clock: FrameClock): PlayerStore {\n const view = signal<ViewState | null>(null);\n const parts = createParts();\n\n /** Takes a new whole view apart into the part signals. A signal notifies only when its value is another object. */\n const publish = (next: ViewState, state: PlayerState): void => {\n batch(() => {\n view.value = next;\n player.value = state;\n parts.position.value = next.position;\n parts.length.value = next.length;\n parts.ready.value = next.ready;\n parts.live.value = next.live;\n parts.version.value = next.version;\n parts.t.value = next.t;\n parts.run.value = next.run;\n parts.main.value = next.main;\n parts.loop.value = next.loop;\n parts.timers.value = next.timers;\n parts.pool.value = next.pool;\n parts.output.value = next.output;\n parts.debug.value = next.debug;\n parts.notes.value = next.notes;\n parts.focus.value = next.focus;\n parts.source.value = next.source ?? null;\n parts.problems.value = next.problems;\n parts.itemCount.value = next.items.total;\n for (const q of QUEUE_NAMES) parts.queues[q].value = next.queues[q];\n });\n };\n const player = signal<PlayerState | null>(null);\n const timeline = signal<TimelineSummary | null>(null);\n const markers = signal<TimelineMarkers | null>(null);\n const tail = signal<TailInfo>({ status: 'idle', mode: null, length: 0, pauses: 0, located: false, run: null });\n const problem = signal<string | null>(null);\n const ready = signal(false);\n\n const waiting = new Map<number, Waiting>();\n let nextId = 1;\n let kickUntil = 0;\n let touched = 0;\n /** A tick is with the worker and has not been answered. */\n let ticking = false;\n /** When that tick was sent; a lost answer must not stop the clock for good. */\n let tickSentAt = 0;\n let cancelFrame: (() => void) | null = null;\n let disposed = false;\n let timelineWanted: { width: number; axis: TimelineAxis } | null = null;\n\n const post = (message: WorkerRequest, transfer?: Transferable[]): void => {\n if (disposed) return;\n worker.postMessage(message, transfer);\n };\n\n const needsTicks = (): boolean => {\n if (clock.now() < kickUntil) return true;\n const p = player.peek();\n const v = view.peek();\n if (p && (p.playing || p.live)) return true;\n if (v && (v.live || v.ready < v.length)) return true;\n return false;\n };\n\n const frame = (now: number): void => {\n cancelFrame = null;\n if (disposed) return;\n if (!ticking || now - tickSentAt > TICK_TIMEOUT_MS) {\n ticking = true;\n tickSentAt = now;\n post({ op: 'tick', now });\n }\n if (needsTicks()) cancelFrame = clock.request(frame);\n };\n\n const kick = (): void => {\n kickUntil = clock.now() + KICK_MS;\n if (!cancelFrame && !disposed) cancelFrame = clock.request(frame);\n };\n\n const ask = <T>(send: (id: number) => void): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n const id = nextId++;\n waiting.set(id, { resolve: resolve as (value: never) => void, reject });\n send(id);\n kick();\n });\n\n const settle = (re: number | null, value: unknown, error?: string): boolean => {\n if (re === null) return false;\n const w = waiting.get(re);\n if (!w) return false;\n waiting.delete(re);\n if (error !== undefined) w.reject(new Error(error));\n else w.resolve(value as never);\n return true;\n };\n\n worker.onmessage = (event) => {\n const m = event.data;\n switch (m.op) {\n case 'ready':\n return;\n case 'view':\n publish(m.view, m.player);\n return;\n case 'patch': {\n let next: ViewState;\n try {\n next = applyViewPatch(view.peek(), m.patch);\n } catch {\n // A patch without the view before it (should not happen): ask for a full one.\n post({ op: 'configure', views: 'patch' });\n kick();\n return;\n }\n publish(next, m.player);\n return;\n }\n case 'timeline':\n timeline.value = m.summary;\n return;\n case 'markers':\n markers.value = m.markers;\n return;\n case 'answer':\n settle(m.re, m.answer);\n return;\n case 'saved':\n settle(m.re, m.bytes);\n return;\n case 'shared':\n settle(m.re, m.result);\n return;\n case 'opened':\n // Recordings are opened through app.open; a host-level `opened` is not expected.\n settle(m.re, { header: m.header, events: m.events });\n return;\n case 'error':\n case 'app.error':\n if (!settle(m.re, undefined, m.message)) problem.value = m.message;\n return;\n case 'app.opened':\n settle(m.re, { header: m.header, events: m.events } satisfies OpenedRecording);\n kick();\n return;\n case 'app.log':\n settle(m.re, m.window);\n return;\n case 'app.runFinal':\n settle(m.re, { current: m.current, length: m.length, steps: m.steps, pauses: m.pauses } satisfies FinishedRun);\n return;\n case 'app.ticked':\n ticking = false;\n return;\n case 'app.tail':\n tail.value = { ...m.tail, run: m.run };\n kick();\n return;\n }\n };\n worker.onerror = () => {\n problem.value = 'The part of the app that reads events stopped working. Reload the page.';\n };\n\n post({ op: 'configure', view: VIEW_OPTIONS, views: 'patch', clock: 'external', markers: true });\n ready.value = true;\n kick();\n\n return {\n view,\n parts,\n player,\n timeline,\n markers,\n tail,\n problem,\n ready,\n command(cmd) {\n if (cmd.do === 'play' || cmd.do === 'pause' || cmd.do === 'toggle' || cmd.do === 'seek' || cmd.do === 'seekTime' || cmd.do === 'step' || (cmd.do === 'follow' && !cmd.on)) touched++;\n post({ op: 'player', cmd });\n kick();\n },\n touches: () => touched,\n query<Q extends ReplayQuery>(q: Q): Promise<AnswerOf<Q>> {\n return ask<AnswerOf<Q>>((id) => post({ op: 'query', id, q }));\n },\n log(filter, offset, limit, position) {\n return ask<LogWindow>((id) => post({ op: 'app.log', id, filter, offset, limit, position }));\n },\n setTimeline(width, axis) {\n if (timelineWanted && timelineWanted.width === width && timelineWanted.axis === axis) return;\n timelineWanted = { width, axis };\n post({ op: 'configure', timeline: { width, axis } });\n kick();\n },\n setViewCaps(caps) {\n post({ op: 'configure', view: caps });\n kick();\n },\n newRun() {\n problem.value = null;\n post({ op: 'app.newRun' });\n kick();\n },\n setRun(run) {\n post({ op: 'app.run', run });\n kick();\n },\n eventsText(text) {\n post({ op: 'app.eventsText', text });\n if (!cancelFrame) kick();\n },\n runEnded(run) {\n // Never rejects: a caller that does not wait for the answer must not leave a rejection behind.\n return ask<FinishedRun>((id) => post({ op: 'app.runEnded', id, run })).catch(() => ({ current: false, length: 0, steps: 0, pauses: 0 }));\n },\n open(data) {\n problem.value = null;\n return ask<OpenedRecording>((id) => post({ op: 'app.open', id, data }));\n },\n openFragment(fragment) {\n problem.value = null;\n return ask<OpenedRecording>((id) => post({ op: 'app.openFragment', id, fragment }));\n },\n close() {\n post({ op: 'app.close' });\n kick();\n },\n save(header, gzip) {\n return ask<Uint8Array>((id) => post({ op: 'save', id, header, gzip }));\n },\n share(header) {\n return ask<ShareResult>((id) => post({ op: 'share', id, header }));\n },\n dispose() {\n disposed = true;\n cancelFrame?.();\n for (const w of waiting.values()) w.reject(new Error('The player was closed.'));\n waiting.clear();\n },\n };\n}\n","/**\n * Breakpoints as data. Pure: the program store keeps them in the settings, the editor\n * draws them, the session sends them.\n *\n * A breakpoint belongs to a file key: the name of the editor snippet, the path of a file\n * of the helper's folder, or \"node:...\" for one of Node's own JavaScript files (the same\n * strings the helper protocol uses in `Breakpoint.file`). Each one can be switched off\n * without being removed, and all of them can be deactivated at once (DevTools'\n * \"Deactivate breakpoints\"): a deactivated or switched-off breakpoint stays on screen,\n * drawn hollow, and is not sent to the program.\n */\nimport type { Breakpoint } from '@nodejs-map/protocol';\nimport { isSameProgram } from './format.ts';\n\n/** Lines (1-based, ascending, no doubles) by file key. */\nexport type LinesByFile = Readonly<Record<string, readonly number[]>>;\n\nexport interface BreakpointSet {\n /** Every breakpoint. */\n lines: LinesByFile;\n /** The ones switched off: a subset of `lines`. */\n off: LinesByFile;\n}\n\nexport interface BreakpointMark {\n line: number;\n enabled: boolean;\n}\n\nexport interface BreakpointEntry extends BreakpointMark {\n file: string;\n}\n\nexport const isNodeFile = (file: string): boolean => file.startsWith('node:');\n\nconst clean = (lines: readonly number[]): number[] => [...new Set(lines.filter((l) => Number.isInteger(l) && l >= 1))].sort((a, b) => a - b);\n\nfunction withFile(map: LinesByFile, file: string, lines: readonly number[]): Record<string, readonly number[]> {\n const next: Record<string, readonly number[]> = { ...map };\n const list = clean(lines);\n if (list.length > 0) next[file] = list;\n else delete next[file];\n return next;\n}\n\n/** The breakpoints of one file, in line order. */\nexport function marksOf(set: BreakpointSet, file: string): BreakpointMark[] {\n const off = new Set(set.off[file] ?? []);\n return (set.lines[file] ?? []).map((line) => ({ line, enabled: !off.has(line) }));\n}\n\n/** Every breakpoint: the files in name order (Node's own files last), the lines ascending. */\nexport function entriesOf(set: BreakpointSet): BreakpointEntry[] {\n const files = Object.keys(set.lines).sort((a, b) => Number(isNodeFile(a)) - Number(isNodeFile(b)) || a.localeCompare(b));\n return files.flatMap((file) => marksOf(set, file).map((m) => ({ file, ...m })));\n}\n\n/** A click on a line number: adds a breakpoint, or removes the one that is there (switched off or not). */\nexport function toggled(set: BreakpointSet, file: string, line: number): BreakpointSet {\n if (!Number.isInteger(line) || line < 1) return set;\n const have = set.lines[file] ?? [];\n if (have.includes(line)) return removed(set, file, line);\n return { lines: withFile(set.lines, file, [...have, line]), off: set.off };\n}\n\nexport function removed(set: BreakpointSet, file: string, line: number): BreakpointSet {\n return {\n lines: withFile(set.lines, file, (set.lines[file] ?? []).filter((l) => l !== line)),\n off: withFile(set.off, file, (set.off[file] ?? []).filter((l) => l !== line)),\n };\n}\n\nexport function withEnabled(set: BreakpointSet, file: string, line: number, enabled: boolean): BreakpointSet {\n if (!(set.lines[file] ?? []).includes(line)) return set;\n const off = (set.off[file] ?? []).filter((l) => l !== line);\n return { lines: set.lines, off: withFile(set.off, file, enabled ? off : [...off, line]) };\n}\n\n/**\n * Replaces the breakpoints of one file: the editor reports where they are after an edit\n * moved them (two that end up on one line become one; it stays on unless both were off).\n */\nexport function withMarks(set: BreakpointSet, file: string, marks: readonly BreakpointMark[]): BreakpointSet {\n const enabledAt = new Map<number, boolean>();\n for (const m of marks) enabledAt.set(m.line, (enabledAt.get(m.line) ?? false) || m.enabled);\n const lines = [...enabledAt.keys()];\n return { lines: withFile(set.lines, file, lines), off: withFile(set.off, file, lines.filter((l) => enabledAt.get(l) === false)) };\n}\n\nexport function sameMarks(a: readonly BreakpointMark[], b: readonly BreakpointMark[]): boolean {\n return a.length === b.length && a.every((m, i) => m.line === b[i]?.line && m.enabled === b[i]?.enabled);\n}\n\n/**\n * What the program is told: the breakpoints that are on, of the scripts this run can\n * reach - the program itself and Node's own JavaScript. Breakpoints kept for another\n * program stay where they are and are not sent. Nothing is sent while breakpoints are\n * deactivated.\n */\nexport function breakpointsToSend(set: BreakpointSet, active: boolean, programName: string): Breakpoint[] {\n if (!active) return [];\n return entriesOf(set)\n .filter((b) => b.enabled && (isNodeFile(b.file) || b.file === programName))\n .map(({ file, line }) => ({ file, line }));\n}\n\n/** Does this breakpoint apply to a run of `programName`? (For the list: the others are shown as kept for another program.) */\nexport function appliesTo(entry: Pick<BreakpointEntry, 'file'>, programName: string): boolean {\n return isNodeFile(entry.file) || entry.file === programName;\n}\n\n/** The file key a script URL of the run belongs to, among the keys that have breakpoints or the program itself. */\nexport function fileKeyOf(scriptUrl: string, programName: string): string {\n return isSameProgram(scriptUrl, programName) ? programName : scriptUrl;\n}\n\n/** \"node:internal/timers\" for \"lib/internal/timers.js\": the name V8 gives the script of one of Node's own JavaScript files. */\nexport function scriptUrlOfPath(path: string): string | null {\n const m = /^lib\\/([a-z0-9_][a-z0-9_./-]*)\\.js$/i.exec(path);\n return m && m[1] !== undefined && !m[1].includes('..') ? `node:${m[1]}` : null;\n}\n","/**\n * Settings: what the user chose and expects to find again after a reload (theme, split\n * positions, run options, the snippet being edited, breakpoints).\n *\n * One signal per setting, so a component re-renders only for the settings it reads.\n * Values read from storage are untrusted (another version of the app, or anyone with\n * access to the browser profile, may have written them): each one is validated and falls\n * back to its default.\n */\nimport { effect, signal } from '@preact/signals';\nimport type { Signal } from '@preact/signals';\n\nexport type ThemeChoice = 'system' | 'light' | 'dark';\nexport type ModuleKind = 'commonjs' | 'esm';\nexport type ProviderId = 'user' | 'pinned' | 'probe';\n\nexport const SPEEDS = [0.1, 0.25, 0.5, 1, 2, 4, 8, 16] as const;\n\n/**\n * \"Record source lines\" for a new profile. With it the helper captures a stack for every\n * output and every async item, which is what lets the page highlight the line of code the\n * replay is at; it slows programs that create very many items. The one place to change\n * the default.\n */\nexport const RECORD_SOURCE_LINES_DEFAULT = true;\n\nexport const DEFAULT_SNIPPET = `// Edit this program, then press Run.\nconst fs = require('node:fs');\n\nsetTimeout(() => console.log('timeout'), 0);\nsetImmediate(() => console.log('immediate'));\nfs.readFile(__filename, () => console.log('file read'));\nprocess.nextTick(() => console.log('nextTick'));\nPromise.resolve().then(() => console.log('promise'));\nconsole.log('main script done');\n`;\n\nexport interface SettingsValues {\n theme: ThemeChoice;\n /** Share of the window width given to the map (desktop layout). */\n splitMap: number;\n /** Share of the right column's height given to the editor (desktop layout). */\n splitEditor: number;\n /** Share of the height between top bar and transport given to the map (narrow layout); the bottom sheet gets the rest. */\n splitSheet: number;\n module: ModuleKind;\n /** UV_THREADPOOL_SIZE for the next run; null leaves the environment alone. */\n poolSize: number | null;\n pauseOnStart: boolean;\n /**\n * \"Record source lines\": ask the helper to record which line of the program wrote each\n * output and created each async item (the run option `itemLocations`).\n * (Before the line highlight existed this was \"itemLocations\", off by default; the new\n * name makes every profile start from the new default once.)\n */\n sourceLines: boolean;\n /** When a run started with Run finishes, go back to its start and play it at the chosen speed. */\n autoReplay: boolean;\n provider: ProviderId;\n /** Playback speed: 1 means one second of the run per second. */\n speed: number;\n /**\n * \"Move map with the run\": the map flies to the code that is running. Off unless the\n * user turns it on; nothing else turns it on. (It used to be \"followAction\", on by\n * default: the owner asked for a map that stays still, so the old stored value is not\n * read any more - everyone starts from off once.)\n */\n moveMap: boolean;\n /** Text of the editor snippet. */\n snippet: string;\n /** Name the snippet runs under (\"snippet.js\"); an example gives its own. */\n snippetName: string;\n /** Breakpoint lines (1-based) by file: a program name, or \"node:...\" for one of Node's own files. */\n breakpoints: Record<string, number[]>;\n /** The breakpoints that are switched off (kept, drawn hollow, not sent): a subset of `breakpoints`. */\n breakpointsOff: Record<string, number[]>;\n /** False: all breakpoints are deactivated at once (DevTools' \"Deactivate breakpoints\"). */\n breakpointsActive: boolean;\n /** The panel on show. */\n tab: TabId;\n /** What the timeline's horizontal axis counts. */\n timelineAxis: 'index' | 'time';\n /** Which areas of the main view are on show (the View menu; stores/layout.ts). */\n areas: AreaVisibility;\n}\n\nexport const AREA_IDS = ['map', 'code', 'panels', 'playback'] as const;\nexport type AreaId = (typeof AREA_IDS)[number];\nexport type AreaVisibility = Readonly<Record<AreaId, boolean>>;\nexport const DEFAULT_AREAS: AreaVisibility = { map: true, code: true, panels: true, playback: true };\n\n/** Four booleans, at least one of map, code and panels on: anything else is not a layout this app shows. */\nconst areasOf = (v: unknown): AreaVisibility | undefined => {\n if (typeof v !== 'object' || v === null || Array.isArray(v)) return undefined;\n const raw = v as Record<string, unknown>;\n if (!AREA_IDS.every((id) => typeof raw[id] === 'boolean')) return undefined;\n const out = Object.fromEntries(AREA_IDS.map((id) => [id, raw[id] as boolean])) as Record<AreaId, boolean>;\n return out.map || out.code || out.panels ? out : undefined;\n};\n\nexport const TAB_IDS = ['code', 'now', 'stack', 'queues', 'pool', 'output', 'events', 'source', 'lessons'] as const;\nexport type TabId = (typeof TAB_IDS)[number];\n\ntype Validators = { [K in keyof SettingsValues]: (v: unknown) => SettingsValues[K] | undefined };\n\nconst oneOf = <T extends string>(...allowed: T[]) => (v: unknown): T | undefined =>\n typeof v === 'string' && (allowed as string[]).includes(v) ? (v as T) : undefined;\nconst fraction = (min: number, max: number) => (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : undefined;\nconst bool = (v: unknown): boolean | undefined => (typeof v === 'boolean' ? v : undefined);\n\nexport const SPLIT_MIN = 0.2;\nexport const SPLIT_MAX = 0.8;\n/** The bottom sheet can be dragged almost closed (map 88%) or almost full (map 12%). */\nexport const SHEET_MIN = 0.12;\nexport const SHEET_MAX = 0.88;\nexport const POOL_SIZE_MAX = 1024; // libuv's MAX_THREADPOOL_SIZE\nexport const SNIPPET_MAX = 200_000;\n\nconst linesByFile = (v: unknown): Record<string, number[]> | undefined => {\n if (typeof v !== 'object' || v === null || Array.isArray(v)) return undefined;\n const out: Record<string, number[]> = {};\n for (const [file, lines] of Object.entries(v).slice(0, 500)) {\n if (!Array.isArray(lines) || file.length > 300) continue;\n const clean = lines.filter((n): n is number => Number.isInteger(n) && n >= 1 && n < 1e7);\n if (clean.length > 0) out[file] = [...new Set(clean)].sort((a, b) => a - b);\n }\n return out;\n};\n\nconst validators: Validators = {\n theme: oneOf('system', 'light', 'dark'),\n splitMap: fraction(SPLIT_MIN, SPLIT_MAX),\n splitEditor: fraction(SPLIT_MIN, SPLIT_MAX),\n splitSheet: fraction(SHEET_MIN, SHEET_MAX),\n module: oneOf('commonjs', 'esm'),\n poolSize: (v) =>\n v === null ? null : typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= POOL_SIZE_MAX ? v : undefined,\n pauseOnStart: bool,\n sourceLines: bool,\n autoReplay: bool,\n provider: oneOf('user', 'pinned', 'probe'),\n speed: (v) => (typeof v === 'number' && (SPEEDS as readonly number[]).includes(v) ? v : undefined),\n moveMap: bool,\n snippet: (v) => (typeof v === 'string' && v.length <= SNIPPET_MAX ? v : undefined),\n snippetName: (v) => (typeof v === 'string' && /^\\w[\\w.-]{0,80}$/.test(v) ? v : undefined),\n tab: oneOf(...TAB_IDS),\n timelineAxis: oneOf('index', 'time'),\n breakpoints: linesByFile,\n breakpointsOff: linesByFile,\n breakpointsActive: bool,\n areas: areasOf,\n};\n\nexport const DEFAULTS: SettingsValues = {\n theme: 'system',\n splitMap: 0.56,\n splitEditor: 0.48,\n splitSheet: 0.6,\n module: 'commonjs',\n poolSize: null,\n pauseOnStart: false,\n sourceLines: RECORD_SOURCE_LINES_DEFAULT,\n autoReplay: true,\n provider: 'user',\n speed: 1,\n moveMap: false,\n snippet: DEFAULT_SNIPPET,\n snippetName: 'snippet.js',\n breakpoints: {},\n breakpointsOff: {},\n breakpointsActive: true,\n tab: 'now',\n timelineAxis: 'index',\n areas: DEFAULT_AREAS,\n};\n\nexport type Settings = { readonly [K in keyof SettingsValues]: Signal<SettingsValues[K]> };\n\n/** The two methods of Storage we use; lets tests pass a plain object. */\nexport interface KeyValueStore {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n}\n\nexport const STORAGE_KEY = 'nodejs-map.settings.v1';\n\n/** Parses stored text; anything invalid falls back to the default for that key. */\nexport function parseSettings(text: string | null): SettingsValues {\n const out: Record<string, unknown> = { ...DEFAULTS };\n if (text === null) return out as unknown as SettingsValues;\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch {\n return out as unknown as SettingsValues;\n }\n if (typeof raw !== 'object' || raw === null) return out as unknown as SettingsValues;\n for (const key of Object.keys(validators) as (keyof SettingsValues)[]) {\n if (!Object.hasOwn(raw, key)) continue;\n const value = validators[key]((raw as Record<string, unknown>)[key]);\n if (value !== undefined) out[key] = value;\n }\n return out as unknown as SettingsValues;\n}\n\nexport interface SettingsStore {\n settings: Settings;\n /** Stops writing to storage (tests). */\n dispose(): void;\n /** Writes now what is waiting to be written (the page is going away). */\n flush(): void;\n}\n\n/**\n * Creates the settings signals from storage and writes them back when one changes.\n * Writes are grouped by `schedule` (a splitter drag changes a value on every frame).\n */\nexport function createSettings(\n storage: KeyValueStore | null,\n schedule: (write: () => void) => void = (write) => void setTimeout(write, 250),\n): SettingsStore {\n let stored: string | null = null;\n try {\n stored = storage?.getItem(STORAGE_KEY) ?? null;\n } catch {\n // Storage can be blocked (private mode, site settings): run with defaults.\n }\n const initial = parseSettings(stored);\n const settings = Object.fromEntries(\n (Object.keys(initial) as (keyof SettingsValues)[]).map((k) => [k, signal(initial[k])]),\n ) as unknown as Settings;\n\n let pending = false;\n let first = true;\n const snapshot = (): string =>\n JSON.stringify(Object.fromEntries(Object.entries(settings).map(([k, s]) => [k, (s as Signal<unknown>).value])));\n const dispose = effect(() => {\n snapshot(); // subscribe to every setting\n if (first) {\n first = false;\n return;\n }\n if (pending || !storage) return;\n pending = true;\n schedule(write);\n });\n const write = (): void => {\n if (!pending || !storage) return;\n pending = false;\n try {\n storage.setItem(STORAGE_KEY, snapshot());\n } catch {\n // Full or blocked storage: the settings still work for this page.\n }\n };\n return { settings, dispose, flush: write };\n}\n\nfunction browserStorage(): KeyValueStore | null {\n try {\n return typeof localStorage === 'undefined' ? null : localStorage;\n } catch {\n return null;\n }\n}\n\nconst store = createSettings(browserStorage());\nexport const settings: Settings = store.settings;\n// A change made a moment before the tab is closed or reloaded (a breakpoint removed, say)\n// must not be lost to the write delay.\nif (typeof addEventListener === 'function') {\n addEventListener('pagehide', () => store.flush());\n addEventListener('visibilitychange', () => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') store.flush();\n });\n}\n","/**\n * The program store: what the editor holds and what Run would start.\n *\n * Either the snippet (editable text kept in the settings) or a file from the folder the\n * helper runs in (shown read-only; Run starts the file itself, not the text on screen).\n * Breakpoints are kept per file (a program name, or \"node:...\" for one of Node's own\n * files) in the settings, so they are there again after a reload; lib/breakpoints.ts has\n * the rules.\n */\nimport { computed, signal } from '@preact/signals';\nimport type { ReadonlySignal } from '@preact/signals';\nimport type { Breakpoint, ExamplesIndex, FileEntry, ProgramRef } from '@nodejs-map/protocol';\nimport { breakpointsToSend, entriesOf, marksOf, removed, sameMarks, toggled, withEnabled, withMarks } from '../lib/breakpoints.ts';\nimport type { BreakpointEntry, BreakpointMark, BreakpointSet } from '../lib/breakpoints.ts';\nimport type { Settings } from './settings.ts';\nimport { SNIPPET_MAX } from './settings.ts';\n\nexport type Example = ExamplesIndex['examples'][number];\n\nexport type ProgramSource =\n | { kind: 'snippet' }\n | { kind: 'file'; path: string; text: string | null; error: string | null };\n\nexport type ExamplesState = { status: 'none' } | { status: 'loading' } | { status: 'ready'; examples: Example[] } | { status: 'failed'; reason: string };\n\nexport interface ProgramStore {\n readonly source: ReadonlySignal<ProgramSource>;\n /** Snippet name or file path: the name breakpoints and script URLs are matched against. */\n readonly name: ReadonlySignal<string>;\n readonly text: ReadonlySignal<string>;\n readonly readOnly: ReadonlySignal<boolean>;\n /** Breakpoints of the current program, in line order. */\n readonly breakpoints: ReadonlySignal<readonly BreakpointMark[]>;\n /** Every breakpoint there is: of this program, of Node's own files, and those kept for other programs. */\n readonly allBreakpoints: ReadonlySignal<readonly BreakpointEntry[]>;\n /** False while all breakpoints are deactivated. */\n readonly breakpointsActive: ReadonlySignal<boolean>;\n /** The breakpoint data as one value, for lib/runMode.ts. */\n readonly breakpointSet: ReadonlySignal<BreakpointSet>;\n readonly examples: ReadonlySignal<ExamplesState>;\n\n setSnippetText(text: string): void;\n useSnippet(): void;\n loadExample(example: Example): void;\n /** Puts a text in the editor as the snippet, under a file name (an example of the Learn course). */\n loadSnippet(name: string, text: string, module: 'commonjs' | 'esm'): void;\n openFile(path: string): Promise<void>;\n listFiles(dir: string): Promise<FileEntry[]>;\n loadExamples(url: string): Promise<void>;\n /** The breakpoints of one file (reads signals: usable in a render or a computed). */\n marksFor(file: string): BreakpointMark[];\n /** Adds a breakpoint, or removes the one on that line. `file` defaults to the current program. */\n toggleBreakpoint(line: number, file?: string): void;\n setBreakpointEnabled(file: string, line: number, enabled: boolean): void;\n removeBreakpoint(file: string, line: number): void;\n removeAllBreakpoints(): void;\n /** Replaces the breakpoints of one file (edits in the editor moved them). */\n setFileBreakpoints(file: string, marks: readonly BreakpointMark[]): void;\n setBreakpointsActive(active: boolean): void;\n /** What to send in `run`. null while a file is still loading or failed to load. */\n ref(): ProgramRef | null;\n /** What a run of the current program is told: the breakpoints that are on, in protocol form. */\n breakpointList(): Breakpoint[];\n}\n\nexport interface ProgramDeps {\n settings: Pick<Settings, 'snippet' | 'snippetName' | 'module' | 'breakpoints' | 'breakpointsOff' | 'breakpointsActive'>;\n listFiles(dir: string): Promise<FileEntry[]>;\n readFile(path: string): Promise<string>;\n fetchJson(url: string): Promise<unknown>;\n}\n\nconst MAX_EXAMPLES = 200;\n\n/** Keeps what is usable of an examples file. It is ours, but a bad entry must not break the picker. */\nexport function parseExamples(raw: unknown): Example[] {\n if (typeof raw !== 'object' || raw === null) throw new Error('not an object');\n const list = (raw as { examples?: unknown }).examples;\n if (!Array.isArray(list)) throw new Error('no \"examples\" list');\n const out: Example[] = [];\n for (const item of list.slice(0, MAX_EXAMPLES) as unknown[]) {\n if (typeof item !== 'object' || item === null) continue;\n const e = item as Record<string, unknown>;\n if (typeof e['id'] !== 'string' || typeof e['title'] !== 'string' || typeof e['text'] !== 'string') continue;\n if (e['text'].length > SNIPPET_MAX) continue;\n out.push({\n id: e['id'].slice(0, 80),\n title: e['title'].slice(0, 120),\n summary: typeof e['summary'] === 'string' ? e['summary'].slice(0, 600) : '',\n module: e['module'] === 'esm' ? 'esm' : 'commonjs',\n text: e['text'],\n racy: e['racy'] === true,\n });\n }\n return out;\n}\n\n/** A file name for an example: its id, made safe, with the extension of its module kind. */\nexport function exampleFileName(example: Pick<Example, 'id' | 'module'>): string {\n const stem = example.id.replace(/[^\\w.-]+/g, '-').replace(/^[.-]+/, '').slice(0, 60) || 'example';\n return `${stem}${example.module === 'esm' ? '.mjs' : '.js'}`;\n}\n\nexport function createProgramStore(deps: ProgramDeps): ProgramStore {\n const { settings } = deps;\n const source = signal<ProgramSource>({ kind: 'snippet' });\n const examples = signal<ExamplesState>({ status: 'none' });\n let fileTicket = 0;\n\n const name = computed(() => {\n const s = source.value;\n return s.kind === 'file' ? s.path : settings.snippetName.value;\n });\n\n const breakpointSet = computed<BreakpointSet>(() => ({ lines: settings.breakpoints.value, off: settings.breakpointsOff.value }));\n const store = (next: BreakpointSet): void => {\n if (next === breakpointSet.peek()) return;\n if (next.lines !== settings.breakpoints.peek()) settings.breakpoints.value = next.lines as Record<string, number[]>;\n if (next.off !== settings.breakpointsOff.peek()) settings.breakpointsOff.value = next.off as Record<string, number[]>;\n };\n\n return {\n source,\n name,\n text: computed(() => {\n const s = source.value;\n return s.kind === 'file' ? (s.text ?? '') : settings.snippet.value;\n }),\n readOnly: computed(() => source.value.kind === 'file'),\n breakpoints: computed(() => marksOf(breakpointSet.value, name.value)),\n allBreakpoints: computed(() => entriesOf(breakpointSet.value)),\n breakpointsActive: settings.breakpointsActive,\n breakpointSet,\n examples,\n\n setSnippetText(text) {\n if (source.value.kind !== 'snippet' || text.length > SNIPPET_MAX) return;\n settings.snippet.value = text;\n },\n useSnippet() {\n fileTicket++;\n source.value = { kind: 'snippet' };\n },\n loadExample(example) {\n fileTicket++;\n settings.snippet.value = example.text;\n settings.snippetName.value = exampleFileName(example);\n settings.module.value = example.module;\n source.value = { kind: 'snippet' };\n },\n loadSnippet(snippetName, text, module) {\n if (text.length > SNIPPET_MAX || !/^\\w[\\w.-]{0,80}$/.test(snippetName)) return;\n fileTicket++;\n settings.snippet.value = text;\n settings.snippetName.value = snippetName;\n settings.module.value = module;\n source.value = { kind: 'snippet' };\n },\n async openFile(path) {\n const mine = ++fileTicket;\n source.value = { kind: 'file', path, text: null, error: null };\n try {\n const text = await deps.readFile(path);\n if (mine === fileTicket) source.value = { kind: 'file', path, text, error: null };\n } catch (e) {\n if (mine === fileTicket) source.value = { kind: 'file', path, text: null, error: e instanceof Error ? e.message : String(e) };\n }\n },\n listFiles: (dir) => deps.listFiles(dir),\n async loadExamples(url) {\n examples.value = { status: 'loading' };\n try {\n examples.value = { status: 'ready', examples: parseExamples(await deps.fetchJson(url)) };\n } catch (e) {\n examples.value = { status: 'failed', reason: e instanceof Error ? e.message : String(e) };\n }\n },\n marksFor: (file) => marksOf(breakpointSet.value, file),\n toggleBreakpoint(line, file = name.peek()) {\n store(toggled(breakpointSet.peek(), file, line));\n },\n setBreakpointEnabled(file, line, enabled) {\n store(withEnabled(breakpointSet.peek(), file, line, enabled));\n },\n removeBreakpoint(file, line) {\n store(removed(breakpointSet.peek(), file, line));\n },\n removeAllBreakpoints() {\n store({ lines: {}, off: {} });\n },\n setFileBreakpoints(file, marks) {\n const set = breakpointSet.peek();\n if (sameMarks(marksOf(set, file), [...marks].sort((a, b) => a.line - b.line))) return;\n store(withMarks(set, file, marks));\n },\n setBreakpointsActive(active) {\n settings.breakpointsActive.value = active;\n },\n ref() {\n const s = source.value;\n if (s.kind === 'file') return s.text === null ? null : { kind: 'file', path: s.path };\n return { kind: 'snippet', name: settings.snippetName.value, text: settings.snippet.value, module: settings.module.value };\n },\n breakpointList() {\n return breakpointsToSend(breakpointSet.value, settings.breakpointsActive.value, name.value);\n },\n };\n}\n","/**\n * Which areas of the main view are on show: the map, the code, the tabbed panels and the\n * playback bar (the View menu, the × buttons, the restore strips, Alt+1..4).\n *\n * The choice is a setting (`areas`), so it survives a reload. One rule holds always: at\n * least one of map, code and panels stays on screen. Hiding the last one is refused, with\n * a message, and nothing changes.\n *\n * A phone shows the areas differently: the map on top, the panels as a bottom sheet with\n * the code as one of its tabs. There \"Code\" is not an area of its own: it follows the\n * sheet, and the sheet is on show whenever the map is not (so the screen is never empty).\n *\n * Things that need a hidden area bring it back by themselves (`reveal`): see the callers\n * in stores/index.ts.\n */\nimport { computed } from '@preact/signals';\nimport type { ReadonlySignal, Signal } from '@preact/signals';\nimport { AREA_IDS, DEFAULT_AREAS } from './settings.ts';\nimport type { AreaId, AreaVisibility } from './settings.ts';\n\nexport { AREA_IDS, DEFAULT_AREAS };\nexport type { AreaId, AreaVisibility };\n\nexport const AREA_LABEL: Readonly<Record<AreaId, string>> = { map: 'Map', code: 'Code', panels: 'Panels', playback: 'Playback bar' };\n\n/** The digit of each area's shortcut (Alt+digit). */\nexport const AREA_KEY: Readonly<Record<AreaId, string>> = { map: '1', code: '2', panels: '3', playback: '4' };\n\nexport const LAST_AREA_MESSAGE = 'Map, Code and Panels cannot all be hidden: one of them stays open.';\n\nexport interface LayoutDeps {\n areas: Signal<AreaVisibility>;\n narrow: ReadonlySignal<boolean>;\n /** The split positions that \"Reset layout\" puts back, with their defaults. */\n splits: readonly { value: Signal<number>; initial: number }[];\n /** Hiding was refused: say why. */\n onRefused(message: string): void;\n}\n\nexport interface LayoutStore {\n /** What is on screen in the layout in use (on a phone, Code follows the sheet). */\n readonly shown: ReadonlySignal<AreaVisibility>;\n /** False for an area the layout in use has no place for on its own (Code on a phone). */\n applies(area: AreaId): boolean;\n /** Shows or hides an area. False when hiding was refused (it was the last one). */\n set(area: AreaId, on: boolean): boolean;\n toggle(area: AreaId): boolean;\n /** Shows these areas (something needs them on screen). */\n reveal(...areas: AreaId[]): void;\n /** Every area on show; the split positions stay. */\n showAll(): void;\n /** Every area on show and the split positions back to their defaults. */\n reset(): void;\n}\n\nexport function createLayoutStore(deps: LayoutDeps): LayoutStore {\n const { areas, narrow } = deps;\n\n const shown = computed<AreaVisibility>(() => {\n const a = areas.value;\n if (!narrow.value) return a;\n const sheet = a.panels || !a.map;\n return { map: a.map, code: sheet, panels: sheet, playback: a.playback };\n });\n\n const write = (patch: Partial<Record<AreaId, boolean>>): void => {\n const next = { ...areas.value, ...patch };\n if (AREA_IDS.some((id) => next[id] !== areas.value[id])) areas.value = next;\n };\n\n const set = (area: AreaId, on: boolean): boolean => {\n if (narrow.value && area === 'code') area = 'panels';\n if (on) {\n write({ [area]: true });\n return true;\n }\n if (area === 'playback') {\n write({ playback: false });\n return true;\n }\n const a = areas.value;\n const left = narrow.value\n ? area === 'map'\n ? a.panels\n : a.map\n : (['map', 'code', 'panels'] as const).some((id) => id !== area && a[id]);\n if (!left) {\n deps.onRefused(LAST_AREA_MESSAGE);\n return false;\n }\n write({ [area]: false });\n return true;\n };\n\n return {\n shown,\n applies: (area) => !(narrow.value && area === 'code'),\n set,\n toggle: (area) => set(area, !shown.peek()[area]),\n reveal(...wanted) {\n const patch: Partial<Record<AreaId, boolean>> = {};\n for (const area of wanted) {\n patch[area] = true;\n // On a phone the code is a tab of the sheet.\n if (area === 'code' && narrow.peek()) patch.panels = true;\n }\n write(patch);\n },\n showAll: () => write(DEFAULT_AREAS),\n reset() {\n write(DEFAULT_AREAS);\n for (const split of deps.splits) split.value.value = split.initial;\n },\n };\n}\n","/**\n * The Learn store: which view is on screen (the route), the course index, the lesson on\n * show, and what the reader has done - kept in this browser only.\n *\n * Like the other stores it takes its dependencies as arguments (fetching, storage, the\n * address bar) and is tested in Node.\n */\nimport { computed, signal } from '@preact/signals';\nimport type { ReadonlySignal } from '@preact/signals';\nimport type { LearnIndex, LearnLesson } from '@nodejs-map/protocol';\nimport { LEARN_STORAGE_KEY, courseFileUrl, lessonsOf, parseLearnIndex, parseLearnLesson, parseProgress } from '../lib/learn.ts';\nimport { parseRoute, routeHash, sameRoute } from '../lib/route.ts';\nimport type { Route } from '../lib/route.ts';\nimport type { KeyValueStore } from './settings.ts';\n\nexport type LearnIndexState = { status: 'none' } | { status: 'loading' } | { status: 'ready'; index: LearnIndex; url: string } | { status: 'failed'; reason: string };\n\nexport type LearnLessonState =\n | { status: 'none' }\n | { status: 'loading'; id: string }\n | { status: 'ready'; lesson: LearnLesson; url: string }\n | { status: 'failed'; id: string; reason: string };\n\n/** Where \"Back to the lesson\" goes: set when a lesson sends the reader to the main view. */\nexport interface LessonReturn {\n lesson: string;\n /** Scroll position of the lesson column when the reader left. */\n scroll: number;\n}\n\nexport interface LearnStore {\n readonly route: ReadonlySignal<Route>;\n readonly index: ReadonlySignal<LearnIndexState>;\n readonly lesson: ReadonlySignal<LearnLessonState>;\n /** Ids of the lessons marked as done. */\n readonly done: ReadonlySignal<ReadonlySet<string>>;\n readonly introDismissed: ReadonlySignal<boolean>;\n readonly returnTo: ReadonlySignal<LessonReturn | null>;\n /** The first lesson of the course, when the index is there. */\n readonly first: ReadonlySignal<{ id: string; title: string; minutes: number } | null>;\n\n loadIndex(url: string): Promise<void>;\n /** The address changed (load, back/forward, a link): follow it. */\n syncRoute(hash: string): void;\n /** Go to a view: changes the address, which adds a history entry. */\n go(route: Route): void;\n setDone(id: string, done: boolean): void;\n dismissIntro(): void;\n /** Leaving a lesson for the main view: remember where to come back to. */\n leaveFor(lesson: string, scroll: number): void;\n /** The scroll position to restore for this lesson, once. */\n takeScroll(lesson: string): number | null;\n /** Address of a file the lesson on show names (an image, a recording); null when it is outside the course. */\n fileUrl(file: string): string | null;\n hasLesson(id: string): boolean;\n}\n\nexport interface LearnDeps {\n fetchJson(url: string): Promise<unknown>;\n storage: KeyValueStore | null;\n /** Sets the fragment of the address (adds a history entry). */\n setHash(hash: string): void;\n}\n\nexport function createLearnStore(deps: LearnDeps): LearnStore {\n let saved = parseProgress(null);\n try {\n saved = parseProgress(deps.storage?.getItem(LEARN_STORAGE_KEY) ?? null);\n } catch {\n // Storage can be blocked: progress then lives for this page only.\n }\n const route = signal<Route>({ view: 'main' });\n const index = signal<LearnIndexState>({ status: 'none' });\n const lesson = signal<LearnLessonState>({ status: 'none' });\n const done = signal<ReadonlySet<string>>(new Set(saved.done));\n const introDismissed = signal(saved.introDismissed);\n const returnTo = signal<LessonReturn | null>(null);\n let last = saved.last;\n let ticket = 0;\n\n const persist = (): void => {\n try {\n deps.storage?.setItem(LEARN_STORAGE_KEY, JSON.stringify({ done: [...done.value], last, introDismissed: introDismissed.value }));\n } catch {\n // Full or blocked storage: nothing to do.\n }\n };\n\n const entry = (id: string): LearnIndex['chapters'][number]['lessons'][number] | undefined => {\n const state = index.value;\n return state.status === 'ready' ? lessonsOf(state.index).find((l) => l.id === id) : undefined;\n };\n\n /** Shows the lesson the route names (or the one last read, or the first). Needs the index. */\n const showRouteLesson = (): void => {\n const state = index.value;\n const r = route.value;\n if (r.view !== 'learn' || state.status !== 'ready') return;\n const all = lessonsOf(state.index);\n const id = r.lesson ?? (last !== null && all.some((l) => l.id === last) ? last : all[0]?.id) ?? null;\n if (id === null) return;\n const current = lesson.value;\n if ((current.status === 'ready' && current.lesson.id === id) || (current.status === 'loading' && current.id === id)) return;\n const found = entry(id);\n const url = found ? courseFileUrl(state.url, state.url, found.file) : null;\n const mine = ++ticket;\n if (!found || !url) {\n lesson.value = { status: 'failed', id, reason: found ? 'its file is outside the course folder' : 'the course has no lesson with this name' };\n return;\n }\n lesson.value = { status: 'loading', id };\n deps.fetchJson(url).then(\n (raw) => {\n if (mine !== ticket) return;\n try {\n lesson.value = { status: 'ready', lesson: { ...parseLearnLesson(raw), id }, url };\n last = id;\n persist();\n } catch (e) {\n lesson.value = { status: 'failed', id, reason: e instanceof Error ? e.message : String(e) };\n }\n },\n (e: unknown) => {\n if (mine === ticket) lesson.value = { status: 'failed', id, reason: e instanceof Error ? e.message : String(e) };\n },\n );\n };\n\n return {\n route,\n index,\n lesson,\n done,\n introDismissed,\n returnTo,\n first: computed(() => {\n const state = index.value;\n const first = state.status === 'ready' ? lessonsOf(state.index)[0] : undefined;\n return first ? { id: first.id, title: first.title, minutes: first.minutes } : null;\n }),\n\n async loadIndex(url) {\n index.value = { status: 'loading' };\n try {\n index.value = { status: 'ready', index: parseLearnIndex(await deps.fetchJson(url)), url };\n showRouteLesson();\n } catch (e) {\n index.value = { status: 'failed', reason: e instanceof Error ? e.message : String(e) };\n }\n },\n syncRoute(hash) {\n const next = parseRoute(hash);\n if (!sameRoute(next, route.value)) route.value = next;\n showRouteLesson();\n },\n go(next) {\n const hash = routeHash(next);\n if (!sameRoute(next, route.value)) route.value = next;\n deps.setHash(hash);\n showRouteLesson();\n },\n setDone(id, isDone) {\n const next = new Set(done.value);\n if (isDone) next.add(id);\n else next.delete(id);\n done.value = next;\n persist();\n },\n dismissIntro() {\n introDismissed.value = true;\n persist();\n },\n leaveFor(id, scroll) {\n returnTo.value = { lesson: id, scroll };\n },\n takeScroll(id) {\n const back = returnTo.value;\n if (!back || back.lesson !== id) return null;\n returnTo.value = null;\n return back.scroll;\n },\n fileUrl(file) {\n const state = index.value;\n const current = lesson.value;\n return state.status === 'ready' && current.status === 'ready' ? courseFileUrl(state.url, current.url, file) : null;\n },\n hasLesson: (id) => entry(id) !== undefined,\n };\n}\n","/**\n * \"When a run finishes, replay it from the start.\"\n *\n * A typical program is over in a fifth of a second: after pressing Run the view is\n * already at the end and nothing was seen to happen. The real run cannot be slowed down;\n * the replay of what was recorded can. So when a run started with Run ends by itself, the\n * player goes back to the start and plays it at the chosen speed.\n *\n * This file is the decision only, as a pure function. The rule that matters most: the\n * replay must never fight the user. If they touched the transport during the run, pressed\n * Stop, stopped the program in the debugger, or are opening something else, the position\n * stays where it is.\n *\n * There is one Run button; whether the debugger was attached does not matter here. What\n * matters is whether the program was ever stopped: a run that paused (at a breakpoint, on\n * a step, at a gate) was watched as it went, and its timing is not the real one any more.\n */\n\n/** Above this many meaningful steps a run is rewound but not played: at 1x it would take ten minutes. */\nexport const AUTO_REPLAY_MAX_STEPS = 3000;\n\nexport interface AutoReplayInput {\n /** The setting \"When a run finishes, replay it from the start\". */\n enabled: boolean;\n /** The program was stopped at least once during the run: by the debugger or at a gate. */\n paused: boolean;\n /** itself: the program exited on its own. stopped: the user pressed Stop. */\n ended: 'itself' | 'stopped';\n /** The user paused, stepped, dragged the timeline or changed the position in any way during the run. */\n userTookControl: boolean;\n /** A recording or a lesson is being opened. */\n opening: boolean;\n /** Meaningful steps in the finished run (events that are not raw signals). */\n steps: number;\n}\n\n/**\n * - replay: go to the start and play.\n * - rewind: go to the start and wait (the run is very long); say how long it is.\n * - leave: do nothing.\n */\nexport type AutoReplayDecision = 'replay' | 'rewind' | 'leave';\n\nexport function decideAutoReplay(input: AutoReplayInput): AutoReplayDecision {\n if (!input.enabled) return 'leave';\n if (input.paused) return 'leave'; // the user was stepping through it\n if (input.ended !== 'itself') return 'leave';\n if (input.userTookControl || input.opening) return 'leave';\n if (!(input.steps > 0)) return 'leave'; // nothing was recorded: nothing to replay\n return input.steps > AUTO_REPLAY_MAX_STEPS ? 'rewind' : 'replay';\n}\n\n/**\n * What a playback speed means, short enough for a menu entry: at 1x the player takes\n * `stepsPerSecond` steps a second. \"5 steps/s\", \"1.25 steps/s\", \"1 step / 2 s\".\n */\nexport function speedWords(speed: number, stepsPerSecond: number): string {\n const rate = speed * stepsPerSecond;\n if (rate >= 1) return `${Number(rate.toFixed(2))} steps/s`;\n return `1 step / ${Number((1 / rate).toFixed(1))} s`;\n}\n","/**\n * One Run button. What it starts is decided here, as a pure function.\n *\n * A run is started with the debugger (\"debug\" in the helper protocol) only when something\n * asks for it: a breakpoint that is on, in a script this run can reach, or \"pause on the\n * first line\". Otherwise it is a free run: the program runs at full speed with nothing\n * attached, which is the run whose timing is the real one. So the free run stays the\n * choice whenever nothing needs the debugger, and the page says which of the two the\n * button will do before it is pressed.\n */\nimport type { Breakpoint } from '@nodejs-map/protocol';\nimport { appliesTo, breakpointsToSend, entriesOf } from './breakpoints.ts';\nimport type { BreakpointSet } from './breakpoints.ts';\n\nexport interface RunPlanInput {\n breakpoints: BreakpointSet;\n /** False while breakpoints are deactivated (all of them, at once). */\n active: boolean;\n /** Snippet name or file path of the program Run would start. */\n programName: string;\n pauseOnStart: boolean;\n /** Can the selected Node.js be debugged at all? */\n canDebug: boolean;\n /** \"When a run finishes, replay it from the start\". */\n autoReplay: boolean;\n}\n\nexport interface RunPlan {\n mode: 'free' | 'debug';\n /** What `run` carries. Empty for a free run. */\n breakpoints: Breakpoint[];\n pauseOnStart: boolean;\n /** One short line for the page: what pressing Run will do. */\n says: string;\n}\n\nconst count = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`;\n\nexport function planRun(input: RunPlanInput): RunPlan {\n const send = breakpointsToSend(input.breakpoints, input.active, input.programName);\n const wantsDebugger = send.length > 0 || input.pauseOnStart;\n const thenReplays = input.autoReplay ? ', then replays' : '';\n\n if (wantsDebugger && input.canDebug) {\n const stops = `tops at ${count(send.length, 'breakpoint')}`;\n const says = !input.pauseOnStart ? `S${stops}` : send.length > 0 ? `Pauses on the first line, then s${stops}` : 'Pauses on the first line';\n return { mode: 'debug', breakpoints: send, pauseOnStart: input.pauseOnStart, says };\n }\n\n let why: string;\n if (wantsDebugger) {\n why = 'This Node.js cannot be debugged';\n } else {\n // Breakpoints that exist for this program but will not stop it: say why not.\n const mine = entriesOf(input.breakpoints).filter((b) => appliesTo(b, input.programName));\n if (mine.length === 0) why = 'No breakpoints';\n else if (!input.active) why = 'Breakpoints are deactivated';\n else why = mine.length === 1 ? 'The breakpoint is switched off' : 'All breakpoints are switched off';\n }\n return { mode: 'free', breakpoints: [], pauseOnStart: false, says: `${why}: runs at full speed${thenReplays}` };\n}\n","/**\n * The session store: what is on screen (nothing, a live run, or a recording) and the\n * actions that change it (run, stop, debugger and gate commands, open, save, share).\n *\n * Safety rule kept here: a program starts only inside `start()`, which is called only\n * from the Run control (and its shortcut). Opening a recording, a link or a lesson goes through\n * `openRecording*`, which never sends anything to the helper except `stop` for a run\n * that is still going.\n */\nimport { computed, effect, signal } from '@preact/signals';\nimport type { ReadonlySignal } from '@preact/signals';\nimport type { Capabilities, NodeInfo, Phase, RecordingHeader } from '@nodejs-map/event-format';\nimport { FORMAT_VERSION } from '@nodejs-map/event-format';\nimport type { LessonsIndex, ProviderInfo } from '@nodejs-map/protocol';\nimport type { ShareResult } from '@nodejs-map/replay';\nimport { decideAutoReplay } from '../lib/autoReplay.ts';\nimport { planRun } from '../lib/runMode.ts';\nimport type { RunPlan } from '../lib/runMode.ts';\nimport { controlStates } from '../lib/controls.ts';\nimport type { ControlId, ControlState, LiveStatus } from '../lib/controls.ts';\nimport type { ConnectionStore } from './connection.ts';\nimport type { OpenedRecording, PlayerStore } from './player.ts';\nimport type { ProgramStore } from './program.ts';\nimport type { Settings } from './settings.ts';\n\nexport type Lesson = LessonsIndex['lessons'][number];\n\nexport type SessionKind =\n /** Nothing has been run or opened. */\n | 'empty'\n /** A run started from this page (it may have ended). */\n | 'live'\n /** A recording: from a file, a share link or a lesson. Never executed. */\n | 'recording';\n\nexport interface RecordingInfo {\n header: RecordingHeader;\n events: number;\n origin: 'file' | 'link' | 'lesson';\n /** File name as the user's system gave it, or the lesson title. Shown as text. */\n label: string;\n lesson: Lesson | null;\n}\n\n/** phase: stop before the first loop phase of the next run. The others: standing gates, also changeable during a run. */\nexport type GateToggle = 'phase' | 'timer' | 'poolStart' | 'poolPost';\n\nexport type LessonsState =\n | { status: 'none' }\n | { status: 'loading' }\n | { status: 'ready'; lessons: Lesson[]; baseUrl: string }\n | { status: 'failed'; reason: string };\n\nexport interface SaveRequest {\n includeSource: boolean;\n gzip: boolean;\n}\n\nexport interface SessionStore {\n readonly kind: ReadonlySignal<SessionKind>;\n readonly recording: ReadonlySignal<RecordingInfo | null>;\n /** True while a recording is being fetched or decoded. */\n readonly opening: ReadonlySignal<boolean>;\n readonly provider: ReadonlySignal<ProviderInfo | null>;\n readonly liveStatus: ReadonlySignal<LiveStatus>;\n readonly controls: ReadonlySignal<Record<ControlId, ControlState>>;\n /** Capabilities behind what is on screen: of the run or recording when known, else of the selected Node. */\n readonly caps: ReadonlySignal<Capabilities | null>;\n /** Node the run on screen used (or the selected one, before a run). */\n readonly node: ReadonlySignal<NodeInfo | null>;\n readonly gates: ReadonlySignal<Readonly<Record<GateToggle, boolean>>>;\n /** What pressing Run would start right now, and one line that says so (lib/runMode.ts). */\n readonly plan: ReadonlySignal<RunPlan>;\n readonly lessons: ReadonlySignal<LessonsState>;\n /**\n * The finished run is being played back from its start by itself (the setting \"replay\n * when a run finishes\"). Shown in the run badge so that nobody takes the replay for a\n * program that is still running. False again when the replay reaches the end or the\n * user takes the transport.\n */\n readonly replaying: ReadonlySignal<boolean>;\n /** A one-line notice about the run on show (a very long run that was rewound but not played). */\n readonly notice: ReadonlySignal<string | null>;\n /** Counts the automatic replays started: the transport highlights its speed control when it changes. */\n readonly replayStarts: ReadonlySignal<number>;\n /** Text for the live region: the latest thing that happened to the run. */\n readonly announcement: ReadonlySignal<string>;\n /** The latest error of an action, for a visible message. */\n readonly error: ReadonlySignal<string | null>;\n\n /** Run: with the debugger when breakpoints or \"pause on the first line\" ask for it, else at full speed. */\n start(): Promise<void>;\n stop(): Promise<void>;\n debug(action: 'pause' | 'resume' | 'stepOver' | 'stepInto' | 'stepOut'): Promise<void>;\n pauseOrResume(): Promise<void>;\n gate(action: { kind: 'pauseAtNextPhase' } | { kind: 'stepPhase' } | { kind: 'runToPhase'; phase: Phase } | { kind: 'resume' }): Promise<void>;\n setGate(gate: GateToggle, on: boolean): Promise<void>;\n syncBreakpoints(): void;\n handleRunEnded(message: { run: string; code: number | null; signal: string | null }): void;\n\n openRecordingData(data: string | ArrayBuffer | Uint8Array, label: string): Promise<void>;\n openRecordingFragment(fragment: string): Promise<void>;\n openLesson(lesson: Lesson): Promise<void>;\n /**\n * Opens a recording with a guided walk-through from an address the caller has already\n * checked (an example of the Learn course). Like a lesson: shown, never run.\n */\n openGuide(guide: { id: string; title: string; summary: string; url: string; steps: NonNullable<Lesson['steps']> }): Promise<void>;\n closeRecording(): void;\n loadLessons(url: string): Promise<void>;\n /** The header a save or share of the current run or recording would carry. null: nothing to save. */\n headerForSave(includeSource: boolean): RecordingHeader | null;\n save(request: SaveRequest): Promise<{ bytes: Uint8Array; fileName: string } | null>;\n share(includeSource: boolean): Promise<ShareResult | null>;\n announce(text: string): void;\n clearError(): void;\n clearNotice(): void;\n}\n\nexport interface SessionDeps {\n settings: Pick<Settings, 'provider' | 'poolSize' | 'pauseOnStart' | 'sourceLines' | 'autoReplay'>;\n connection: ConnectionStore;\n player: PlayerStore;\n program: ProgramStore;\n /** Fetches a lesson's recording file. */\n fetchBytes(url: string): Promise<ArrayBuffer>;\n fetchJson(url: string): Promise<unknown>;\n pageUrl(): string;\n now(): Date;\n /** The atlas on show, to stamp recordings made here. */\n atlas(): { tag: string; commit: string } | null;\n /** A new run or a newly opened recording is on screen: the map goes back to its fit view. */\n onNewContent?(what: 'run' | 'recording' | 'lesson'): void;\n}\n\nconst MAX_LESSONS = 200;\nconst MAX_STEPS = 200;\n\nexport function parseLessons(raw: unknown): Lesson[] {\n if (typeof raw !== 'object' || raw === null) throw new Error('not an object');\n const list = (raw as { lessons?: unknown }).lessons;\n if (!Array.isArray(list)) throw new Error('no \"lessons\" list');\n const out: Lesson[] = [];\n for (const item of list.slice(0, MAX_LESSONS) as unknown[]) {\n if (typeof item !== 'object' || item === null) continue;\n const l = item as Record<string, unknown>;\n if (typeof l['id'] !== 'string' || typeof l['title'] !== 'string' || typeof l['recording'] !== 'string') continue;\n const lesson: Lesson = {\n id: l['id'].slice(0, 80),\n title: l['title'].slice(0, 120),\n summary: typeof l['summary'] === 'string' ? l['summary'].slice(0, 600) : '',\n recording: l['recording'],\n node: typeof l['node'] === 'string' ? l['node'].slice(0, 20) : '',\n };\n if (Array.isArray(l['steps'])) {\n const steps: NonNullable<Lesson['steps']> = [];\n for (const s of l['steps'].slice(0, MAX_STEPS) as unknown[]) {\n if (typeof s !== 'object' || s === null) continue;\n const step = s as Record<string, unknown>;\n if (typeof step['index'] !== 'number' || !Number.isInteger(step['index']) || step['index'] < 0) continue;\n steps.push({\n index: step['index'],\n title: typeof step['title'] === 'string' ? step['title'].slice(0, 120) : '',\n text: typeof step['text'] === 'string' ? step['text'].slice(0, 2000) : '',\n });\n }\n steps.sort((a, b) => a.index - b.index);\n lesson.steps = steps;\n }\n out.push(lesson);\n }\n return out;\n}\n\n/**\n * URL of a lesson's recording: relative to the index file, and never outside the folder\n * of the index (an index file must not be able to make the app fetch from elsewhere).\n */\nexport function lessonRecordingUrl(indexUrl: string, recording: string): string | null {\n let url: URL;\n let base: URL;\n try {\n base = new URL('.', indexUrl);\n url = new URL(recording, indexUrl);\n } catch {\n return null;\n }\n if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) return null;\n return url.href;\n}\n\nexport function recordingFileName(title: string | undefined, gzip: boolean): string {\n const stem = (title ?? 'recording').replace(/\\.[a-z]{1,4}$/i, '').replace(/[^\\w.-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 60) || 'recording';\n return `${stem}.nodejs-map${gzip ? '.gz' : ''}`;\n}\n\nfunction errorText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\nexport function createSessionStore(deps: SessionDeps): SessionStore {\n const { settings, connection, player, program } = deps;\n const kind = signal<SessionKind>('empty');\n const recording = signal<RecordingInfo | null>(null);\n const opening = signal(false);\n const starting = signal(false);\n /** Between `run.started` and the end of that run. */\n const runActive = signal(false);\n /**\n * The gates as the user set them. With no run they are armed for the next one (sent in\n * `run`); during a run the three standing gates follow `gate.do`. They stay as they\n * are from one run to the next.\n */\n const gates = signal<Readonly<Record<GateToggle, boolean>>>({ phase: false, timer: false, poolStart: false, poolPost: false });\n const lessons = signal<LessonsState>({ status: 'none' });\n const announcement = signal('');\n const error = signal<string | null>(null);\n const replaying = signal(false);\n const notice = signal<string | null>(null);\n const replayStarts = signal(0);\n /** About the live run, for the decision to replay it when it ends. */\n let touchesAtStart = 0;\n /**\n * The debugger has been asked for in this run: it was started with it, or Pause or a\n * breakpoint was sent later (the helper then attaches it). From then on every change\n * of the breakpoints is sent, an empty list too.\n */\n let debuggerInUse = false;\n let stopRequested = false;\n /** The automatic replay has been seen under way: at the start of the run, or playing. */\n let replaySeenPlaying = false;\n let touchesAtReplay = 0;\n\n // The automatic replay is over when the player stops after having got under way (it\n // reached the end), or when the user takes the transport. Nothing restarts it.\n effect(() => {\n const state = player.player.value;\n if (!replaying.value || !state) return;\n if (player.touches() !== touchesAtReplay) {\n replaying.value = false;\n return;\n }\n if (state.playing || state.position === 0) replaySeenPlaying = true;\n if (replaySeenPlaying && !state.playing && state.position > 0) {\n replaying.value = false;\n announcement.value = 'The replay reached the end. Finished run.';\n }\n });\n /** Source text of the program as it was when the live run started (for saving). */\n let liveSource: { name: string; text: string | null; node: NodeInfo } | null = null;\n let openTicket = 0;\n\n const announce = (text: string): void => {\n // The same text twice must still be announced: alternate a trailing no-break space.\n announcement.value = announcement.value === text ? `${text} ` : text;\n };\n\n const provider = computed<ProviderInfo | null>(() => {\n const list = connection.providers.value;\n return list.find((p) => p.id === settings.provider.value) ?? list.find((p) => p.available) ?? list[0] ?? null;\n });\n\n const liveStatus = computed<LiveStatus>(() => {\n if (starting.value) return 'starting';\n if (kind.value !== 'live' || !runActive.value) return 'idle';\n const tail = player.tail.value;\n switch (tail.status) {\n case 'paused':\n return 'paused';\n case 'gated':\n return 'gated';\n case 'ended':\n return 'idle';\n default:\n return 'running'; // the helper said the run started; its first events may not be in yet\n }\n });\n\n const controls = computed(() =>\n controlStates({\n connected: connection.status.value === 'open',\n provider: provider.value,\n notes: connection.notes.value,\n status: liveStatus.value,\n }),\n );\n\n const plan = computed<RunPlan>(() =>\n planRun({\n breakpoints: program.breakpointSet.value,\n active: program.breakpointsActive.value,\n programName: program.name.value,\n pauseOnStart: settings.pauseOnStart.value,\n canDebug: provider.value?.caps.jsDebugger !== false,\n autoReplay: settings.autoReplay.value,\n }),\n );\n\n const caps = computed<Capabilities | null>(() => player.parts.run.value?.caps ?? (kind.value === 'recording' ? null : (provider.value?.caps ?? null)));\n const node = computed<NodeInfo | null>(\n () => player.parts.run.value?.node ?? recording.value?.header.node ?? (kind.value === 'recording' ? null : (provider.value?.node ?? null)),\n );\n\n const fail = (e: unknown): void => {\n const text = errorText(e);\n error.value = text;\n announce(text);\n };\n\n const refuse = (id: ControlId): boolean => {\n const state = controls.value[id];\n if (state.enabled) return false;\n if (state.reason) announce(state.reason);\n return true;\n };\n\n /**\n * Id of the run this page started. Kept here, not read back from the worker: a short\n * run can end before the worker has reported anything.\n */\n let liveRun: string | null = null;\n const activeRun = (): string | null => (runActive.value ? liveRun : null);\n\n /** The `gates` field of `run`: what is armed, for a Node that can stop at those gates. */\n const armedGates = (chosen: ProviderInfo): { gates?: { phase?: boolean; timer?: boolean; poolStart?: boolean; poolPost?: boolean } } => {\n const g = gates.value;\n const can = chosen.caps.gates;\n const out: { phase?: boolean; timer?: boolean; poolStart?: boolean; poolPost?: boolean } = {};\n if (g.phase && can.phase) out.phase = true;\n if (g.timer && can.timer) out.timer = true;\n if (g.poolStart && can.poolStart) out.poolStart = true;\n if (g.poolPost && can.poolPost) out.poolPost = true;\n return Object.keys(out).length > 0 ? { gates: out } : {};\n };\n\n const stopLiveRun = async (): Promise<void> => {\n const run = activeRun();\n if (!run) return;\n try {\n await connection.request({ op: 'stop', run });\n } catch {\n // The run may have ended on its own in the meantime.\n }\n runActive.value = false;\n };\n\n const adoptRecording = async (open: () => Promise<OpenedRecording>, origin: RecordingInfo['origin'], label: string, lesson: Lesson | null): Promise<void> => {\n const mine = ++openTicket;\n error.value = null;\n opening.value = true;\n try {\n await stopLiveRun();\n const opened = await open();\n if (mine !== openTicket) return;\n kind.value = 'recording';\n recording.value = { header: opened.header, events: opened.events, origin, label, lesson };\n replaying.value = false;\n notice.value = null;\n liveSource = null;\n deps.onNewContent?.(lesson ? 'lesson' : 'recording');\n // Start at the beginning, not playing: the user decides when to play.\n player.command({ do: 'pause' });\n player.command({ do: 'seek', position: lesson?.steps?.[0] ? lesson.steps[0].index + 1 : 0 });\n announce(`Opened a recording with ${opened.events} events. Nothing was run.`);\n } catch (e) {\n if (mine !== openTicket) return;\n fail(new Error(`This recording could not be opened: ${errorText(e)}`));\n } finally {\n if (mine === openTicket) opening.value = false;\n }\n };\n\n const headerForSave = (includeSource: boolean): RecordingHeader | null => {\n if (kind.value === 'recording') {\n const info = recording.value;\n if (!info) return null;\n const { sources, ...rest } = info.header;\n return includeSource && sources ? { ...rest, sources } : rest;\n }\n // A live run: described by what was sent in `run`, not by the view (the view is the\n // state at the player's position, and at position 0 it knows nothing yet).\n if (kind.value !== 'live' || !liveSource) return null;\n const atlas = deps.atlas() ?? connection.welcome.value?.atlas ?? null;\n if (!atlas) return null;\n const header: RecordingHeader = {\n format: 'nodejs-map-recording',\n version: FORMAT_VERSION,\n created: deps.now().toISOString(),\n tool: connection.welcome.value?.tool ?? '0.0.0',\n node: liveSource.node,\n atlas: { tag: atlas.tag, commit: atlas.commit },\n title: liveSource.name,\n };\n if (includeSource && liveSource.text !== null) header.sources = [{ name: liveSource.name, text: liveSource.text }];\n return header;\n };\n\n return {\n kind,\n recording,\n opening,\n provider,\n liveStatus,\n controls,\n caps,\n node,\n gates,\n plan,\n lessons,\n announcement,\n error,\n replaying,\n notice,\n replayStarts,\n announce,\n clearError() {\n error.value = null;\n },\n clearNotice() {\n notice.value = null;\n },\n\n async start() {\n if (refuse('run')) return;\n const { mode, breakpoints, pauseOnStart } = plan.value;\n const ref = program.ref();\n const chosen = provider.value;\n if (!ref || !chosen) {\n announce('The program is still loading.');\n return;\n }\n openTicket++; // a recording still being opened must not replace the run\n error.value = null;\n starting.value = true;\n kind.value = 'live';\n recording.value = null;\n liveSource = { name: program.name.value, text: program.text.value, node: chosen.node };\n debuggerInUse = mode === 'debug';\n stopRequested = false;\n replaying.value = false;\n notice.value = null;\n player.newRun();\n player.command({ do: 'follow', on: true });\n deps.onNewContent?.('run');\n try {\n const poolSize = settings.poolSize.value;\n const reply = await connection.request({\n op: 'run',\n program: ref,\n mode,\n provider: chosen.id,\n breakpoints,\n ...(poolSize !== null ? { poolSize } : {}),\n ...(pauseOnStart ? { pauseOnStart: true } : {}),\n // \"Record source lines\": the helper's run option is still called itemLocations.\n ...(settings.sourceLines.value ? { itemLocations: true } : {}),\n ...armedGates(chosen),\n });\n liveRun = reply.run;\n player.setRun(reply.run);\n runActive.value = true;\n // From here on, a play, pause, step or seek is the user taking the player in hand.\n touchesAtStart = player.touches();\n announce(mode === 'debug' ? `Run started. ${plan.peek().says}.` : 'Run started at full speed.');\n } catch (e) {\n fail(new Error(`The run could not start: ${errorText(e)}`));\n } finally {\n starting.value = false;\n }\n },\n\n async stop() {\n if (refuse('stop')) return;\n const run = activeRun();\n if (!run) return;\n stopRequested = true;\n try {\n await connection.request({ op: 'stop', run });\n announce('Stop requested.');\n } catch (e) {\n fail(e);\n }\n },\n\n async debug(action) {\n if (refuse(action)) return;\n const run = activeRun();\n if (!run) return;\n try {\n // Pause in a run started without the debugger: the helper attaches it now, or\n // refuses with a message of its own, which is then shown as it is.\n if (action === 'pause') debuggerInUse = true;\n await connection.request({ op: 'debug.do', run, action });\n } catch (e) {\n fail(e);\n }\n },\n\n async pauseOrResume() {\n await this.debug(liveStatus.value === 'paused' ? 'resume' : 'pause');\n },\n\n async gate(action) {\n const id: ControlId = action.kind === 'resume' ? 'gateResume' : action.kind;\n if (refuse(id)) return;\n const run = activeRun();\n if (!run) return;\n try {\n await connection.request({ op: 'gate.do', run, action });\n } catch (e) {\n fail(e);\n }\n },\n\n async setGate(gate, onOff) {\n const id: ControlId = gate === 'phase' ? 'pauseAtNextPhase' : gate === 'timer' ? 'gateTimer' : gate === 'poolStart' ? 'gatePoolStart' : 'gatePoolPost';\n if (refuse(id)) return;\n const run = activeRun();\n if (!run || gate === 'phase') {\n // No run: armed for the next one. (\"phase\" only ever means \"the next run starts stopped\".)\n gates.value = { ...gates.value, [gate]: onOff };\n announce(onOff ? 'Armed for the next run.' : 'No longer armed.');\n return;\n }\n try {\n await connection.request({ op: 'gate.do', run, action: { kind: 'set', gate, on: onOff } });\n gates.value = { ...gates.value, [gate]: onOff };\n } catch (e) {\n fail(e);\n }\n },\n\n syncBreakpoints() {\n const run = activeRun();\n if (!run) return;\n const breakpoints = program.breakpointList();\n // A run started without the debugger hears of breakpoints only once there is one:\n // the helper attaches the debugger then (or refuses, and its message is shown).\n if (!debuggerInUse && breakpoints.length === 0) return;\n debuggerInUse = true;\n connection.request({ op: 'debug.breakpoints', run, breakpoints }).catch(fail);\n },\n\n handleRunEnded(message) {\n const final = player.runEnded(message.run);\n if (message.run !== liveRun || !runActive.value) return;\n runActive.value = false;\n const ended = message.signal ? `The run was ended by signal ${message.signal}.` : `The run ended with exit code ${String(message.code)}.`;\n announce(ended);\n const run = message.run;\n const touched = player.touches() !== touchesAtStart;\n void final.then((finished) => {\n // Decided once the worker has the final event list (late thread-pool data included).\n if (!finished.current || liveRun !== run || kind.value !== 'live' || runActive.value || starting.value) return;\n const decision = decideAutoReplay({\n enabled: settings.autoReplay.value,\n paused: finished.pauses > 0,\n ended: stopRequested ? 'stopped' : 'itself',\n userTookControl: touched || player.touches() !== touchesAtStart,\n opening: opening.value,\n steps: finished.steps,\n });\n if (decision === 'leave') return;\n player.command({ do: 'pause' });\n player.command({ do: 'seek', position: 0 });\n if (decision === 'rewind') {\n notice.value = `This run has ${finished.steps.toLocaleString('en')} steps. Press play, or drag the timeline.`;\n announce(`${ended} It has ${finished.steps} steps; it is at its start, ready to play.`);\n return;\n }\n replaySeenPlaying = false;\n player.command({ do: 'play' });\n touchesAtReplay = player.touches();\n replaying.value = true;\n replayStarts.value++;\n announce(`${ended} Replaying it from the start at the chosen speed.`);\n });\n },\n\n openRecordingData(data, label) {\n return adoptRecording(() => player.open(data), 'file', label.slice(0, 200), null);\n },\n openRecordingFragment(fragment) {\n return adoptRecording(() => player.openFragment(fragment), 'link', 'Shared link', null);\n },\n async openLesson(lesson) {\n const state = lessons.value;\n const url = state.status === 'ready' ? lessonRecordingUrl(state.baseUrl, lesson.recording) : null;\n if (!url) {\n fail(new Error('This lesson names a recording outside the lessons folder; it was not opened.'));\n return;\n }\n await adoptRecording(async () => player.open(await deps.fetchBytes(url)), 'lesson', lesson.title, lesson);\n },\n async openGuide(guide) {\n const lesson: Lesson = { id: guide.id, title: guide.title, summary: guide.summary, recording: guide.url, node: '', steps: guide.steps };\n await adoptRecording(async () => player.open(await deps.fetchBytes(guide.url)), 'lesson', guide.title, lesson);\n },\n closeRecording() {\n openTicket++;\n opening.value = false;\n recording.value = null;\n kind.value = 'empty';\n player.close();\n announce('Recording closed.');\n },\n async loadLessons(url) {\n const absolute = new URL(url, deps.pageUrl()).href;\n lessons.value = { status: 'loading' };\n try {\n lessons.value = { status: 'ready', lessons: parseLessons(await deps.fetchJson(absolute)), baseUrl: absolute };\n } catch (e) {\n lessons.value = { status: 'failed', reason: errorText(e) };\n }\n },\n\n headerForSave,\n async save(request) {\n const header = headerForSave(request.includeSource);\n if (!header) return null;\n try {\n const bytes = await player.save(header, request.gzip);\n return { bytes, fileName: recordingFileName(header.title, request.gzip) };\n } catch (e) {\n fail(new Error(`The recording could not be saved: ${errorText(e)}`));\n return null;\n }\n },\n async share(includeSource) {\n const header = headerForSave(includeSource);\n if (!header) return null;\n try {\n return await player.share(header);\n } catch (e) {\n fail(new Error(`The link could not be made: ${errorText(e)}`));\n return null;\n }\n },\n };\n}\n","/**\n * The source panel's state: the target on show and its text.\n *\n * The app never ships Node's source. The text is fetched when a target is opened:\n * - for a \"node:...\" script of a live run, from the running program through the helper\n * (works offline, and is the code that is really running);\n * - otherwise the raw file at the atlas commit from raw.githubusercontent.com.\n * Texts are cached in memory for the life of the page. When the text cannot be had, the\n * panel still shows the path, the range and the links.\n */\nimport { signal } from '@preact/signals';\nimport type { ReadonlySignal } from '@preact/signals';\nimport type { SourceTarget } from '../lib/sourceTarget.ts';\n\nexport type SourceText =\n | { status: 'none' }\n | { status: 'loading' }\n | { status: 'ready'; text: string; from: 'github' | 'program' }\n | { status: 'unavailable'; reason: string };\n\nexport interface SourceStore {\n readonly target: ReadonlySignal<SourceTarget | null>;\n readonly text: ReadonlySignal<SourceText>;\n /** Shows a target (already resolved) and fetches its text. */\n show(target: SourceTarget): void;\n /** Shows the target a promise resolves to; an older pending request is dropped. */\n showLater(pending: Promise<SourceTarget>): void;\n clear(): void;\n}\n\nexport interface SourceDeps {\n /** Fetches a raw file; rejects when offline or blocked. */\n fetchText(url: string): Promise<string>;\n /**\n * Source of a script the live run has loaded, through the helper. Resolves to null\n * when there is no live run to ask.\n */\n fetchFromProgram(scriptUrl: string): Promise<string | null>;\n}\n\nexport const MAX_SOURCE_CHARS = 6_000_000;\nconst MAX_CACHED = 40;\n\nexport function createSourceStore(deps: SourceDeps): SourceStore {\n const target = signal<SourceTarget | null>(null);\n const text = signal<SourceText>({ status: 'none' });\n const cache = new Map<string, { text: string; from: 'github' | 'program' }>();\n let ticket = 0;\n\n const remember = (key: string, value: { text: string; from: 'github' | 'program' }): void => {\n cache.delete(key);\n cache.set(key, value);\n if (cache.size > MAX_CACHED) cache.delete(cache.keys().next().value as string);\n };\n\n const load = async (t: SourceTarget, mine: number): Promise<void> => {\n if (!t.path || (!t.raw && !t.scriptUrl)) {\n text.value = { status: 'none' };\n return;\n }\n const key = t.raw ?? `program:${String(t.scriptUrl)}`;\n const cached = cache.get(key);\n if (cached) {\n text.value = { status: 'ready', ...cached };\n return;\n }\n text.value = { status: 'loading' };\n let result: { text: string; from: 'github' | 'program' } | null = null;\n if (t.scriptUrl) {\n try {\n const fromProgram = await deps.fetchFromProgram(t.scriptUrl);\n if (fromProgram !== null) result = { text: fromProgram, from: 'program' };\n } catch {\n // fall through to GitHub\n }\n }\n if (!result && !t.raw) {\n if (mine === ticket) text.value = { status: 'unavailable', reason: 'The text of this file is available only while the program runs.' };\n return;\n }\n if (!result) {\n try {\n result = { text: await deps.fetchText(t.raw as string), from: 'github' };\n } catch {\n if (mine === ticket) {\n text.value = {\n status: 'unavailable',\n reason: 'The text of this file comes from GitHub and needs a connection. The path, the lines and the links below still work.',\n };\n }\n return;\n }\n }\n if (result.text.length > MAX_SOURCE_CHARS) {\n if (mine === ticket) text.value = { status: 'unavailable', reason: 'This file is too large to show here. Open it on GitHub.' };\n return;\n }\n remember(key, result);\n if (mine === ticket) text.value = { status: 'ready', ...result };\n };\n\n return {\n target,\n text,\n show(t) {\n const mine = ++ticket;\n target.value = t;\n void load(t, mine);\n },\n showLater(pending) {\n const mine = ++ticket;\n void pending.then(\n (t) => {\n if (mine !== ticket) return;\n target.value = t;\n void load(t, mine);\n },\n () => undefined,\n );\n },\n clear() {\n ticket++;\n target.value = null;\n text.value = { status: 'none' };\n },\n };\n}\n\n/** fetch for raw source text: no credentials, no referrer. */\nexport async function fetchRawText(url: string): Promise<string> {\n const response = await fetch(url, { credentials: 'omit', referrerPolicy: 'no-referrer', mode: 'cors' });\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n return response.text();\n}\n","/**\n * The selection store: what the user is pointing at. Which box is selected on the map,\n * which dialog is open, which mark is being explained, where the editor should scroll.\n */\nimport { signal } from '@preact/signals';\nimport type { Signal } from '@preact/signals';\nimport type { MarkTarget } from '../lib/certainty.ts';\n\nexport type DialogId = 'legend' | 'help' | 'program' | 'save' | 'share' | 'more' | 'playback';\n\nexport interface EditorReveal {\n /** 1-based lines. */\n start: number;\n end: number;\n /** Changes on every request so that asking for the same lines twice scrolls again. */\n ticket: number;\n}\n\nexport interface UiStore {\n /** True when the narrow layout (map on top, bottom sheet) is in use. */\n readonly narrow: Signal<boolean>;\n readonly dialog: Signal<DialogId | null>;\n /** The fact whose mark was opened: shows the rule dialog. */\n readonly mark: Signal<MarkTarget | null>;\n /** Selected box: an atlas id or a \"u:\" user box id. Shared with the map. */\n readonly selected: Signal<string | null>;\n /** Set to an id to make the map fly there; the map sets it back to null. */\n readonly flyTo: Signal<string | null>;\n /** One line of help under the run controls: why the control last touched is off. */\n readonly hint: Signal<string | null>;\n readonly reveal: Signal<EditorReveal | null>;\n /** Which source file of a recording the editor shows. */\n readonly recordingSource: Signal<number>;\n /** Frame of the paused stack whose scopes are shown (0 = top). */\n readonly frame: Signal<number>;\n /** The \"more\" region under the code header (run options, loop gates) is open. */\n readonly runMore: Signal<boolean>;\n}\n\nexport function createUiStore(): UiStore {\n return {\n narrow: signal(false),\n dialog: signal<DialogId | null>(null),\n mark: signal<MarkTarget | null>(null),\n selected: signal<string | null>(null),\n flyTo: signal<string | null>(null),\n hint: signal<string | null>(null),\n reveal: signal<EditorReveal | null>(null),\n recordingSource: signal(0),\n frame: signal(0),\n runMore: signal(false),\n };\n}\n","/**\n * The composition root: creates the stores with their browser dependencies, wires them\n * together and holds the few effects that span stores. Components import from here and\n * stay thin; the stores themselves (connection, player, program, session, atlas, source,\n * settings, ui) take their dependencies as arguments and are tested in Node.\n */\nimport { computed, effect, signal, untracked } from '@preact/signals';\nimport type { ReadonlySignal } from '@preact/signals';\nimport type { Frame, Loc } from '@nodejs-map/event-format';\nimport type { Platform } from '@nodejs-map/atlas-format';\nimport { FRAGMENT_PREFIX } from '@nodejs-map/replay';\nimport type { StepKind } from '@nodejs-map/replay';\nimport type { MarkTarget } from '../lib/certainty.ts';\nimport { isSameProgram } from '../lib/format.ts';\nimport { milestone } from '../lib/marks.ts';\nimport { actionPlace, buildHighlights } from '../lib/highlights.ts';\nimport { highlightFor, sameHighlight } from '../lib/sourceLine.ts';\nimport type { CodeHighlight } from '../lib/sourceLine.ts';\nimport type { LearnExample } from '@nodejs-map/protocol';\nimport { snippetNameFor } from '../lib/learn.ts';\nimport { webSocketUrl } from '../lib/protocolClient.ts';\nimport type { SocketLike } from '../lib/protocolClient.ts';\nimport { normalizePlatform, targetForAtlasId, targetForNodeFrame } from '../lib/sourceTarget.ts';\nimport { extractUserBoxes, userFileId } from '../lib/userBoxes.ts';\nimport type { MapCodeLine, MapHighlight, UserBox } from '../map/contract.ts';\nimport type { WorkerMessage } from '../worker/protocol.ts';\nimport { createAtlasStore, fetchJson, isSafeTag, withSlash } from './atlas.ts';\nimport { createConnectionStore, parseAppConfig } from './connection.ts';\nimport { OUTPUT_CHUNKS_ON_SHOW, createPlayerStore } from './player.ts';\nimport type { WorkerLike } from './player.ts';\nimport { createProgramStore } from './program.ts';\nimport { createLayoutStore } from './layout.ts';\nimport { createLearnStore } from './learn.ts';\nimport { createSessionStore } from './session.ts';\nimport { DEFAULTS, SPEEDS, settings } from './settings.ts';\nimport type { TabId } from './settings.ts';\nimport { createSourceStore, fetchRawText } from './source.ts';\nimport { createUiStore } from './ui.ts';\n\nexport { settings };\n\nconst pageUrl = (): string => location.href.replace(/#.*$/, '');\n\n// ---- the worker ---------------------------------------------------------------------\n\nfunction startWorker(): WorkerLike {\n const worker = new Worker(new URL('../worker/app.worker.ts', import.meta.url), { type: 'module', name: 'nodejs-map-replay' });\n const like: WorkerLike = {\n postMessage: (message, transfer) => worker.postMessage(message, transfer ?? []),\n onmessage: null,\n onerror: null,\n };\n worker.onmessage = (event: MessageEvent<WorkerMessage>) => like.onmessage?.(event);\n worker.onerror = (event) => like.onerror?.(event);\n return like;\n}\n\nexport const player = createPlayerStore(startWorker(), {\n request(fn) {\n const id = requestAnimationFrame(fn);\n return () => cancelAnimationFrame(id);\n },\n now: () => performance.now(),\n});\n\n// ---- stores -------------------------------------------------------------------------\n\nexport const ui = createUiStore();\n\nexport const connection = createConnectionStore({\n makeSocket: (url) => new WebSocket(url) as unknown as SocketLike,\n onEventsText: (text) => player.eventsText(text),\n onRunEnded: (message) => session.handleRunEnded(message),\n});\n\nexport const program = createProgramStore({\n settings,\n listFiles: async (dir) => (await connection.request({ op: 'files.list', dir })).entries,\n readFile: async (path) => (await connection.request({ op: 'files.read', path })).text,\n fetchJson,\n});\n\nexport const atlas = createAtlasStore({ pageUrl, fetchJson });\n\nexport const session = createSessionStore({\n settings,\n connection,\n player,\n program,\n fetchJson,\n async fetchBytes(url) {\n const response = await fetch(url, { credentials: 'same-origin' });\n if (!response.ok) throw new Error(`the file could not be loaded (HTTP ${response.status})`);\n return response.arrayBuffer();\n },\n pageUrl,\n now: () => new Date(),\n atlas() {\n const state = atlas.state.value;\n return state.status === 'ready' ? { tag: state.tag, commit: state.commit } : null;\n },\n onNewContent() {\n // Start from the whole map, wherever the last run or lesson left it. Nothing here\n // turns \"Move map with the run\" on: the map moves only when the user asks for it.\n fitMap();\n },\n});\n\nexport const source = createSourceStore({\n fetchText: fetchRawText,\n async fetchFromProgram(scriptUrl) {\n // Only a live run can be asked; a recording has no program behind it.\n const run = player.tail.value.run;\n if (session.kind.value !== 'live' || !run || session.liveStatus.value === 'idle') return null;\n return (await connection.request({ op: 'source', run, url: scriptUrl })).text;\n },\n});\n\n/** The Learn page: its route, the course and the reader's progress. */\nexport const learn = createLearnStore({\n fetchJson,\n storage: (() => {\n try {\n return typeof localStorage === 'undefined' ? null : localStorage;\n } catch {\n return null;\n }\n })(),\n setHash(hash) {\n if (location.hash !== hash) location.hash = hash;\n },\n});\n\n/** Which areas of the main view are on show (the View menu). */\nexport const layout = createLayoutStore({\n areas: settings.areas,\n narrow: ui.narrow,\n splits: [\n { value: settings.splitMap, initial: DEFAULTS.splitMap },\n { value: settings.splitEditor, initial: DEFAULTS.splitEditor },\n { value: settings.splitSheet, initial: DEFAULTS.splitSheet },\n ],\n onRefused(message) {\n ui.hint.value = message;\n session.announce(message);\n },\n});\n\n// ---- derived state ------------------------------------------------------------------\n\nexport const helperMode = computed(() => connection.mode.value === 'helper');\n\n/**\n * Is there a run or a recording on screen at all? A computed of its own: components that\n * only need this must not re-render with every view state during playback.\n */\nexport const hasRun = computed(() => player.parts.length.value > 0);\n\n/** The platform whose code locations apply: of the run on screen, else of the selected Node. */\nexport const platform: ReadonlySignal<Platform> = computed(() => normalizePlatform(session.node.value?.platform));\n\nexport interface ShownProgram {\n /** Name the text goes by; script URLs of frames are matched against it. */\n name: string;\n /** null: there is no text to show; `missing` says why. */\n text: string | null;\n missing: string | null;\n readOnly: boolean;\n /** recording: text carried by a recording. program: what Run would start. */\n origin: 'recording' | 'program';\n /** Names of all files of a recording, for the file switcher. */\n files: readonly string[];\n}\n\n/** What the editor shows. */\nexport const shown: ReadonlySignal<ShownProgram> = computed(() => {\n const info = session.recording.value;\n if (session.kind.value === 'recording' && info) {\n const sources = info.header.sources ?? [];\n const pick = sources[Math.min(ui.recordingSource.value, sources.length - 1)];\n if (!pick) {\n return {\n name: info.header.title ?? 'recording',\n text: null,\n missing: 'This recording does not include the text of the program.',\n readOnly: true,\n origin: 'recording',\n files: [],\n };\n }\n return { name: pick.name, text: pick.text, missing: null, readOnly: true, origin: 'recording', files: sources.map((s) => s.name) };\n }\n if (connection.mode.value !== 'helper') {\n // The player has no program of its own: the editor shows what a recording carries.\n return {\n name: 'program',\n text: null,\n missing: connection.mode.value === null ? 'Starting...' : 'Open a recording or a lesson. The text of its program is shown here when the recording includes it.',\n readOnly: true,\n origin: 'program',\n files: [],\n };\n }\n const src = program.source.value;\n if (src.kind === 'file' && src.text === null) {\n return {\n name: src.path,\n text: null,\n missing: src.error ? `This file could not be read: ${src.error}` : 'Reading the file...',\n readOnly: true,\n origin: 'program',\n files: [],\n };\n }\n return { name: program.name.value, text: program.text.value, missing: null, readOnly: program.readOnly.value, origin: 'program', files: [] };\n});\n\n/** \"Your code\" boxes for the map. Filled a moment after the text changes (the parser loads lazily). */\nexport const userBoxes = signal<readonly UserBox[]>([]);\n\n/**\n * What the map lights up. Most steps of a run do not change it; the same array is handed\n * out again then, so the map is not asked to redraw for nothing.\n */\nlet lastHighlights: readonly MapHighlight[] = [];\nexport const highlights: ReadonlySignal<readonly MapHighlight[]> = computed(() => {\n const { focus, loop, main, pool, debug } = player.parts;\n const view = focus.value && loop.value && main.value && pool.value && debug.value ? { focus: focus.value, loop: loop.value, main: main.value, pool: pool.value, debug: debug.value } : null;\n const next = buildHighlights(view, { userBoxes: userBoxes.value, programName: shown.value.name });\n const same =\n next.length === lastHighlights.length &&\n next.every((h, i) => {\n const old = lastHighlights[i] as MapHighlight;\n return h.id === old.id && h.role === old.role && h.certainty === old.certainty && h.badge === old.badge;\n });\n if (!same) lastHighlights = next;\n return lastHighlights;\n});\n\n/**\n * The line of code to highlight at the player's position, and the code view that holds it\n * (lib/sourceLine.ts). The same object is handed out while nothing changed: the code\n * views re-render on identity.\n */\nlet lastCodeHighlight: CodeHighlight | null = null;\nexport const codeHighlight: ReadonlySignal<CodeHighlight | null> = computed(() => {\n const debug = player.parts.debug.value;\n const s = shown.value;\n const next = highlightFor({\n source: player.parts.source.value,\n frames: debug?.paused ? debug.frames : null,\n frame: ui.frame.value,\n programName: s.text === null ? null : s.name,\n });\n if (!sameHighlight(next, lastCodeHighlight)) lastCodeHighlight = next;\n return lastCodeHighlight;\n});\n\n/** The line to mark in the editor, or null. */\nexport const editorMark = computed(() => {\n const h = codeHighlight.value;\n return h && h.where === 'editor' ? h : null;\n});\n\n/** The line to mark in the Source panel: only when the file on show there is the script of the line. */\nexport const sourceMark = computed(() => {\n const h = codeHighlight.value;\n return h && h.where === 'source' && source.target.value?.scriptUrl === h.url ? h : null;\n});\n\n/**\n * The line for the code the map shows inside the user's boxes. From the replay's own\n * `source` (not from a caller frame the user selected): the map shows where the run is.\n */\nlet lastCodeLine: MapCodeLine | null = null;\nexport const codeLine: ReadonlySignal<MapCodeLine | null> = computed(() => {\n const spot = player.parts.source.value;\n const s = shown.value;\n const next: MapCodeLine | null = spot && s.text !== null && isSameProgram(spot.loc.url, s.name) ? { file: userFileId(s.name), line: spot.loc.line, why: spot.why } : null;\n if (next === null || lastCodeLine === null || next.file !== lastCodeLine.file || next.line !== lastCodeLine.line || next.why !== lastCodeLine.why) lastCodeLine = next;\n return lastCodeLine;\n});\n\n// ---- actions that span stores -------------------------------------------------------\n\n/** Shows a panel. `reveal`: the panels come back if they were hidden (false: only select the tab). */\nexport function showTab(tab: TabId, reveal = true): void {\n settings.tab.value = tab;\n if (reveal) layout.reveal('panels');\n // A sheet dragged almost shut would hide the panel that was just asked for.\n if (ui.narrow.value && settings.splitSheet.value > 0.75) settings.splitSheet.value = 0.6;\n}\n\n/** \"Show me where this is\": select the box and fly the map to it. */\nexport function showOnMap(id: string): void {\n layout.reveal('map');\n ui.selected.value = id;\n ui.flyTo.value = id;\n}\n\n/** Opens the source of a map box, a cited id or an event's place. User boxes open in the editor. */\nexport function openSource(id: string): void {\n if (id.startsWith('u:')) {\n const box = userBoxes.value.find((b) => b.id === id);\n if (box?.lines) revealInEditor(box.lines.start, box.lines.end);\n return;\n }\n const state = atlas.state.value;\n if (state.status !== 'ready') {\n source.show({\n title: id,\n description: null,\n atlasId: id,\n path: null,\n start: null,\n end: null,\n line: null,\n scriptUrl: null,\n variant: null,\n github: null,\n githubDev: null,\n raw: null,\n note: 'The map for this Node.js version is not loaded, so this place cannot be resolved to a file.',\n });\n } else {\n source.showLater(targetForAtlasId(state.store, platform.value, id));\n }\n showTab('source');\n}\n\n/** Opens a stack frame: user code in the editor, Node's own JavaScript in the source panel. */\nexport function openFrame(frame: Frame): void {\n if (frame.origin === 'user') {\n revealInEditor(frame.loc.line, frame.loc.line);\n return;\n }\n const state = atlas.state.value;\n source.showLater(targetForNodeFrame(state.status === 'ready' ? state.store : null, frame));\n if (frame.at) ui.selected.value = frame.at;\n showTab('source');\n}\n\n/** Opens a line of code named by an event or a breakpoint: the program in the editor, a \"node:...\" script in the source panel. */\nexport function openLoc(loc: Loc): void {\n if (loc.url.startsWith('node:')) openFrame({ fn: loc.url, loc, origin: 'node' });\n else revealInEditor(loc.line, loc.line);\n}\n\nlet revealTicket = 0;\nexport function revealInEditor(start: number, end: number): void {\n ui.reveal.value = { start, end, ticket: ++revealTicket };\n layout.reveal('code');\n if (ui.narrow.value) showTab('code');\n}\n\n// ---- from a lesson of the Learn course to the main view -------------------------------\n\n/**\n * \"Play the walk-through\": opens the example's recording in the main view, with its steps\n * in the guide panel, at step 1. Nothing is run. `scroll` is where the reader was in the\n * lesson, for \"Back to the lesson\".\n */\nexport async function playExample(lessonId: string, example: LearnExample, scroll: number): Promise<void> {\n const url = example.recording ? learn.fileUrl(example.recording) : null;\n if (!url) {\n session.announce('This example has no recording to play.');\n return;\n }\n learn.leaveFor(lessonId, scroll);\n learn.go({ view: 'main' });\n // The walk-through is read in the code and the guide panel: both come back if hidden.\n layout.reveal('code', 'panels');\n showTab('lessons');\n await session.openGuide({ id: `learn:${example.id}`, title: example.title || example.name, summary: '', url, steps: example.steps ?? [] });\n}\n\n/**\n * \"Run it yourself\" (helper mode): puts the example in the editor as the snippet and\n * presses Run. Called only from that button: a click by the user, like Run itself.\n */\nexport async function runExample(lessonId: string, example: LearnExample, scroll: number): Promise<void> {\n if (!helperMode.value) return;\n learn.leaveFor(lessonId, scroll);\n if (session.kind.value === 'recording') session.closeRecording();\n program.loadSnippet(snippetNameFor(example), example.text, example.module);\n learn.go({ view: 'main' });\n layout.reveal('code');\n if (ui.narrow.value) showTab('code');\n await session.start();\n}\n\n/**\n * A call path named in a lesson: go to the main view and show it with the map panel's own\n * path picker (its steps, its highlights). Where that picker is not on screen (a phone\n * keeps it in a sheet), the map flies to the path's first step instead.\n */\nexport function openPathFromLesson(lessonId: string, pathId: string, scroll: number): void {\n const state = atlas.state.value;\n const path = state.status === 'ready' ? state.store.index.paths.find((p) => p.id === pathId) : undefined;\n if (!path) {\n session.announce(state.status === 'ready' ? 'This call path is not in the map of this Node.js version.' : 'The map is not loaded yet, so the call path cannot be shown.');\n return;\n }\n learn.leaveFor(lessonId, scroll);\n learn.go({ view: 'main' });\n layout.reveal('map');\n requestAnimationFrame(() => {\n const picker = document.querySelector<HTMLSelectElement>('.nm-map__paths select');\n if (picker && [...picker.options].some((o) => o.value === pathId)) {\n picker.value = pathId;\n picker.dispatchEvent(new Event('change', { bubbles: true }));\n return;\n }\n const box = path.steps[0]?.box;\n if (box) showOnMap(box);\n });\n}\n\n/** Moves the player so that the event at `index` is the one applied last. */\nexport function jumpToEvent(index: number): void {\n player.command({ do: 'pause' });\n player.command({ do: 'seek', position: index + 1 });\n}\n\nexport function step(kind: StepKind, direction: 1 | -1): void {\n player.command({ do: 'step', kind, direction });\n}\n\nexport function openMark(target: MarkTarget): void {\n ui.mark.value = target;\n}\n\nexport function changeSpeed(direction: 1 | -1): void {\n const at = SPEEDS.indexOf(settings.speed.value as (typeof SPEEDS)[number]);\n const next = SPEEDS[Math.min(SPEEDS.length - 1, Math.max(0, (at < 0 ? SPEEDS.indexOf(1) : at) + direction))];\n if (next !== undefined) settings.speed.value = next;\n}\n\nexport function toggleTheme(): void {\n const dark =\n settings.theme.value === 'dark' || (settings.theme.value === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);\n settings.theme.value = dark ? 'light' : 'dark';\n}\n\n/** Hands bytes to the browser as a download. The object URL lives only until the click is done. */\nexport function downloadBytes(bytes: Uint8Array, fileName: string, type: string): void {\n const url = URL.createObjectURL(new Blob([bytes as Uint8Array<ArrayBuffer>], { type }));\n const a = document.createElement('a');\n a.href = url;\n a.download = fileName;\n a.rel = 'noopener';\n document.body.append(a);\n a.click();\n a.remove();\n setTimeout(() => URL.revokeObjectURL(url), 10_000);\n}\n\nexport const MAX_OPEN_BYTES = 300 * 1024 * 1024;\n\n/** Opens a recording file the user picked or dropped. The file is read, decoded and shown; nothing runs. */\nexport async function openRecordingFile(file: File): Promise<void> {\n if (file.size > MAX_OPEN_BYTES) {\n session.announce('This file is too large to be a recording.');\n return;\n }\n await session.openRecordingData(await file.arrayBuffer(), file.name);\n}\n\n/**\n * The public address share links point at. The player site is its own address. The\n * helper's page is on 127.0.0.1 and of no use to anyone else: there the address comes\n * from config.json (`playerUrl`), and without one there is no link to give.\n */\nexport function shareBaseUrl(): string | null {\n const config = connection.config.value;\n if (!config) return null;\n return config.mode === 'player' ? pageUrl() : (config.playerUrl ?? null);\n}\n\n// ---- start-up -----------------------------------------------------------------------\n\nexport const bootError = signal<string | null>(null);\n\nfunction fragmentHasRecording(hash: string): boolean {\n return hash.replace(/^#/, '').split('&').some((part) => part.startsWith(FRAGMENT_PREFIX));\n}\n\nasync function openFragmentIfAny(): Promise<void> {\n if (!fragmentHasRecording(location.hash)) return;\n await session.openRecordingFragment(location.hash);\n}\n\n/** Reads config.json and starts the mode it names. Called once from main.tsx after the first paint. */\nexport async function boot(): Promise<void> {\n // The address decides the view from the first frame: a reload of a lesson shows the lesson.\n learn.syncRoute(location.hash);\n let config;\n try {\n config = parseAppConfig(await fetchJson(new URL('config.json', pageUrl()).href));\n } catch (e) {\n bootError.value = `nodejs-map could not read its configuration (config.json): ${e instanceof Error ? e.message : String(e)}`;\n return;\n }\n connection.setConfig(config);\n milestone('config');\n if (config.lessons !== undefined) void session.loadLessons(config.lessons).then(() => milestone('lessons'));\n if (config.learn !== undefined) void learn.loadIndex(new URL(config.learn, pageUrl()).href);\n if (config.mode === 'helper') {\n if (config.examples !== undefined) void program.loadExamples(new URL(config.examples, pageUrl()).href);\n await connection.connect(webSocketUrl(config.ws, pageUrl()));\n const welcome = connection.welcome.value;\n if (welcome) milestone('connected');\n if (welcome?.openFile) void program.openFile(welcome.openFile);\n } else if (!fragmentHasRecording(location.hash) && learn.route.value.view === 'main') {\n // The player starts with nothing open: the gallery is the way in.\n settings.tab.value = 'lessons';\n }\n await openFragmentIfAny();\n addEventListener('hashchange', () => {\n learn.syncRoute(location.hash);\n void openFragmentIfAny();\n });\n}\n\n// ---- effects ------------------------------------------------------------------------\n\n// Theme: the system setting applies unless the user chose one (see styles/tokens.css).\neffect(() => {\n const theme = settings.theme.value;\n if (theme === 'system') delete document.documentElement.dataset['theme'];\n else document.documentElement.dataset['theme'] = theme;\n});\n\n// Narrow layout follows the window.\n{\n const query = matchMedia('(max-width: 760px)');\n ui.narrow.value = query.matches;\n query.addEventListener('change', (e) => {\n ui.narrow.value = e.matches;\n });\n}\n\n// Which atlas to load.\neffect(() => {\n const config = connection.config.value;\n if (!config) return;\n if (config.mode === 'helper') {\n // The welcome names the folder that holds one atlas per tag, and the tag to use\n // (the helper falls back to its bundled atlas when it has none for the user's Node).\n const served = connection.welcome.value?.atlas;\n if (!served) return;\n if (!isSafeTag(served.tag)) {\n atlas.unavailable(served.tag.slice(0, 40), 'the helper named a version this page cannot look up');\n return;\n }\n void atlas.load(`${withSlash(served.baseUrl)}${served.tag}/`, served.tag);\n return;\n }\n // Player: the atlas named by the recording; before one is open, the atlas of the first lesson.\n const header = session.recording.value?.header;\n const lessons = session.lessons.value;\n const tag = header ? header.atlas.tag : lessons.status === 'ready' && lessons.lessons[0] ? `v${lessons.lessons[0].node}` : null;\n if (tag === null) return;\n if (!isSafeTag(tag)) {\n atlas.unavailable(tag.slice(0, 40), 'its version name is not one this site can look up');\n return;\n }\n void atlas.load(`${withSlash(config.atlasBase)}${tag}/`, tag);\n});\n\n// Playback speed is a setting; the worker's player follows it.\neffect(() => {\n const speed = settings.speed.value;\n if (player.ready.value) player.command({ do: 'speed', speed });\n});\n\n// Output chunks are text and can be large: the worker puts them into the view only while\n// the Output panel is on show (the count on the tab does not need them).\neffect(() => {\n const onShow = settings.tab.value === 'output';\n if (player.ready.value) player.setViewCaps({ maxOutput: onShow ? OUTPUT_CHUNKS_ON_SHOW : 0 });\n});\n\n// Breakpoints changed during a run reach the helper: added, removed, switched off, or all\n// deactivated. (In a run started without the debugger the first one makes the helper\n// attach it; see session.syncBreakpoints.)\neffect(() => {\n program.breakpointSet.value;\n program.breakpointsActive.value;\n // Only an edit of the breakpoints sends them: not the run starting or pausing (the\n // run message carries them already, and replacing them while the program starts\n // could make it miss one).\n untracked(() => session.syncBreakpoints());\n});\n\n// A new pause shows its top frame.\neffect(() => {\n player.parts.debug.value?.from?.index;\n ui.frame.value = 0;\n});\n\n// \"Your code\" boxes: parsed a moment after the text settles, with the editor's parser.\n{\n let timer: ReturnType<typeof setTimeout> | undefined;\n let ticket = 0;\n effect(() => {\n const { name, text } = shown.value;\n clearTimeout(timer);\n const mine = ++ticket;\n if (text === null) {\n userBoxes.value = [];\n return;\n }\n timer = setTimeout(() => {\n void import('@lezer/javascript').then(({ parser }) => {\n if (mine !== ticket) return;\n // The file's box carries the text: the map shows the code inside the box when zoomed in.\n const fileId = userFileId(name);\n userBoxes.value = extractUserBoxes(name, text, parser).map((box) => (box.id === fileId ? { ...box, text } : box));\n });\n }, 400);\n });\n}\n\n// A pause of the live program is brought into sight, as in DevTools: the view that holds\n// the script shows the line (the editor for the program, the Source panel for one of\n// Node's own files), and the Stack tab opens on the first pause of a run. Only for the\n// program that is stopped right now: scrubbing through a recorded pause highlights the\n// line where it is but does not switch panels under the user's hands.\n{\n let seenRun: string | null = null;\n let seenPause = -1;\n /** The tab that was on show before a step into Node's code switched to Source: stepping back out returns to it. */\n let tabBeforeSource: TabId | null = null;\n effect(() => {\n const debug = player.parts.debug.value;\n const run = player.tail.value.run;\n if (session.liveStatus.value !== 'paused' || !debug?.paused || !debug.from) return;\n if (player.parts.position.peek() !== player.parts.length.peek()) return;\n const pause = debug.from.index;\n const first = run !== seenRun;\n if (!first && pause === seenPause) return;\n if (first) tabBeforeSource = null;\n seenRun = run;\n seenPause = pause;\n const top = debug.frames[0];\n untracked(() => {\n const narrow = ui.narrow.peek();\n const inProgram = top !== undefined && top.origin !== 'node';\n if (inProgram) {\n // Back in the program (or never left it): the editor shows the line by itself,\n // and comes back if it was hidden.\n layout.reveal('code');\n if (narrow) showTab('code');\n else if (first) showTab('stack', false);\n else if (tabBeforeSource !== null && settings.tab.peek() === 'source') showTab(tabBeforeSource, false);\n tabBeforeSource = null;\n } else if (top) {\n if (settings.tab.peek() !== 'source') tabBeforeSource = first && !narrow ? 'stack' : settings.tab.peek();\n openFrame(top);\n }\n });\n });\n}\n\n// \"Move map with the run\": the map flies to the code that is running - only while the\n// user has turned it on (the transport bar). It is off by default and nothing turns it on\n// by itself: not a replay, not a lesson, not a pause. Highlights on the map update either\n// way, and \"Show on map\" flies there once without turning it on.\n//\n// Which box:\n// - while the player stands still (a lesson step, a manual step, a seek, a pause): the\n// place of the latest event (the view's focus), else the first place where work\n// waits, else the place of the running callback or phase;\n// - while it plays: the place of the running callback or phase only. The focus moves\n// with almost every event, and a map that flies that often cannot be read.\n// How often: only when the box changes, after it has been the box for FOLLOW_SETTLE_MS,\n// and while playing at most once per FOLLOW_GAP_MS.\n// Whose map: the user's. Panning or zooming the map turns it off again.\nconst FOLLOW_SETTLE_MS = 180;\nconst FOLLOW_GAP_MS = 900;\n/** The atlas root: flying to it is \"fit the whole map\" (see map/contract.ts). */\nexport const MAP_FIT_ID = 'o:world';\n\nlet dragFrom: { x: number; y: number } | null = null;\nconst DRAG_PX = 6;\n\nfunction userMovedMap(): void {\n if (!settings.moveMap.value) return;\n settings.moveMap.value = false;\n session.announce('You moved the map, so it no longer moves with the run. Turn \"Move map with the run\" on to let it move again.');\n}\n\n/** Called by the map region with the user's own input on the map. */\nexport function noteMapInteraction(kind: 'down' | 'move' | 'up' | 'zoom', x = 0, y = 0): void {\n if (kind === 'down') dragFrom = { x, y };\n else if (kind === 'move') {\n if (dragFrom && Math.hypot(x - dragFrom.x, y - dragFrom.y) > DRAG_PX) {\n dragFrom = null;\n userMovedMap();\n }\n } else if (kind === 'up') dragFrom = null;\n else userMovedMap();\n}\n\n/** Asks the map for its fit view: a new run or a newly opened recording starts from the whole picture. */\nexport function fitMap(): void {\n ui.flyTo.value = MAP_FIT_ID;\n}\n\n/** The box where the action is at the player's position, or null. `playing`: only the coarse place (see above). */\nfunction actionBox(playing: boolean): string | null {\n const { debug, main, loop, focus } = player.parts;\n const d = debug.value;\n const m = main.value;\n const l = loop.value;\n const f = focus.value;\n if (!d || !m || !l || !f) return null;\n const coarse = actionPlace({ debug: d, main: m, loop: l });\n return playing ? (coarse?.id ?? null) : ((d.paused ? coarse?.id : null) ?? f.at ?? f.waiting[0]?.at ?? coarse?.id ?? null);\n}\n\n/** \"Show on map\": fly once to where the run is now. Does not turn \"Move map with the run\" on. */\nexport function showActionOnMap(): void {\n const id = untracked(() => actionBox(false));\n if (id === null) {\n session.announce(hasRun.peek() ? 'Nothing is running at this point of the run, so there is no place to show.' : 'There is no run to show yet.');\n return;\n }\n showOnMap(id);\n}\n\n{\n let timer: ReturnType<typeof setTimeout> | undefined;\n /** What was last shown on the map. */\n let flownTo: string | null = null;\n let flownAt = 0;\n // A new run or recording: whatever was shown before is forgotten.\n let lastVersionZero = true;\n effect(() => {\n const empty = player.parts.length.value === 0;\n if (empty && !lastVersionZero) flownTo = null;\n lastVersionZero = empty;\n });\n effect(() => {\n if (!settings.moveMap.value) {\n flownTo = null;\n clearTimeout(timer);\n return;\n }\n const playing = player.player.value?.playing === true;\n const id = actionBox(playing);\n if (id === null || id === flownTo) return;\n clearTimeout(timer);\n const wait = Math.max(FOLLOW_SETTLE_MS, playing ? flownAt + FOLLOW_GAP_MS - performance.now() : 0);\n timer = setTimeout(() => {\n if (!settings.moveMap.peek()) return;\n flownTo = id;\n flownAt = performance.now();\n ui.flyTo.value = id;\n }, wait);\n });\n}\n","/**\n * A control button that can be off without disappearing.\n *\n * An unavailable control stays in place, stays focusable (aria-disabled, not the disabled\n * attribute) and says why: the reason is its accessible description and its tooltip, and\n * it appears in the hint strip above the transport bar when the control is focused,\n * hovered or pressed - so keyboard, mouse and touch all get it.\n */\nimport type { ComponentChildren } from 'preact';\nimport { useId } from 'preact/hooks';\nimport type { ControlState } from '../lib/controls.ts';\nimport { session, ui } from '../stores/index.ts';\n\nexport interface CtlProps {\n label: string;\n /** Visible content; defaults to the label. */\n children?: ComponentChildren;\n state?: ControlState;\n onAct(): void;\n /** Keys shown in the tooltip, for example \"F10\". */\n keys?: string;\n /** For toggles: aria-pressed. */\n pressed?: boolean;\n kind?: 'plain' | 'primary' | 'danger';\n class?: string;\n}\n\nexport function Ctl({ label, children, state, onAct, keys, pressed, kind = 'plain', class: extra }: CtlProps) {\n const id = useId();\n const reason = state && !state.enabled ? (state.reason ?? 'Not available.') : null;\n const hint = reason ? `${label}: ${reason}` : null;\n const showHint = (): void => {\n if (hint) ui.hint.value = hint;\n };\n const clearHint = (): void => {\n if (hint && ui.hint.value === hint) ui.hint.value = null;\n };\n return (\n <button\n type=\"button\"\n class={`ctl ctl--${kind}${reason ? ' is-off' : ''}${pressed ? ' is-pressed' : ''}${extra ? ` ${extra}` : ''}`}\n aria-label={label}\n aria-disabled={reason ? 'true' : undefined}\n aria-pressed={pressed === undefined ? undefined : pressed ? 'true' : 'false'}\n aria-describedby={reason ? id : undefined}\n title={hint ?? (keys ? `${label} (${keys})` : label)}\n onFocus={showHint}\n onBlur={clearHint}\n onPointerEnter={showHint}\n onPointerLeave={(e) => {\n // On touch there is no hover to end: the hint stays until the next action.\n if (e.pointerType === 'mouse' && document.activeElement !== e.currentTarget) clearHint();\n }}\n onClick={() => {\n if (hint) {\n ui.hint.value = hint;\n session.announce(hint);\n } else {\n ui.hint.value = null;\n onAct();\n }\n }}\n >\n {children ?? label}\n {reason ? (\n <span id={id} class=\"sr-only\">\n Not available. {reason}\n </span>\n ) : null}\n </button>\n );\n}\n","/**\n * Icons: a small hand-drawn set as inline SVG paths (16 px grid, drawn with the current\n * text colour). Always decorative: the control that holds one carries the label.\n */\n\nconst PATHS = {\n play: 'M4.5 2.8v10.4L13 8z',\n pause: 'M4 3h3v10H4zM9 3h3v10H9z',\n stop: 'M3.5 3.5h9v9h-9z',\n // DevTools' resume: a bar and a triangle.\n resume: 'M3 3h2v10H3zM7 3l7 5-7 5z',\n // A breakpoint tag, and the same tag hollow with a stroke through it.\n breakpoints: 'M2 4h8.2L14 8l-3.8 4H2z',\n breakpointsOff: 'M2 4h8.2L14 8l-3.8 4H2zM3.4 5.4v5.2h6.2L12 8 9.600 5.400zM2.300 13.800L12.700 1.400l1.100 0.900L3.400 14.700z',\n more: 'M8 2.200a1.500 1.500 0 1 0 0 3 1.500 1.500 0 0 0 0-3zm0 4.300a1.500 1.500 0 1 0 0 3 1.500 1.500 0 0 0 0-3zm0 4.300a1.500 1.500 0 1 0 0 3 1.500 1.500 0 0 0 0-3z',\n trash: 'M6 2h4l.6 1.200H13.500v1.500h-11V3.200h2.900zM3.600 5.800h8.800l-.7 8.200H4.300zm2.200 1.600.3 5h1.300l-.2-5zm2.900 0-.2 5h1.300l.3-5z',\n stepForward: 'M3 3l7 5-7 5zM11 3h2v10h-2z',\n stepBack: 'M13 3L6 8l7 5zM3 3h2v10H3z',\n toStart: 'M4 3h2v10H4zM13 3L7 8l6 5z',\n toEnd: 'M10 3h2v10h-2zM3 3l6 5-6 5z',\n stepOver: 'M2.5 9a5.5 5.5 0 0 1 10.3-2.7l1.2-1.6.6 4.6-4.5-.9 1.5-1.2A3.9 3.9 0 0 0 4.1 9zM6.6 11.4a1.6 1.6 0 1 0 3.2 0 1.6 1.6 0 0 0-3.2 0z',\n stepInto: 'M7.2 1.5h1.6v5.9l2-2 1.1 1.1L8 10.4 4.1 6.5l1.1-1.1 2 2zM6.4 12.6a1.6 1.6 0 1 0 3.2 0 1.6 1.6 0 0 0-3.2 0z',\n stepOut: 'M7.2 10.4h1.6V4.5l2 2 1.1-1.1L8 1.5 4.1 5.4l1.1 1.1 2-2zM6.4 12.6a1.6 1.6 0 1 0 3.2 0 1.6 1.6 0 0 0-3.2 0z',\n bug: 'M5.5 3.2A2.6 2.6 0 0 1 8 1.5a2.6 2.6 0 0 1 2.5 1.7l1.4-1 .8 1.2-1.7 1.2c.3.5.5 1.1.5 1.7h2v1.5h-2v1.2l1.9 1.3-.8 1.3-1.5-1A3.5 3.5 0 0 1 8 13.5a3.5 3.5 0 0 1-3.1-2l-1.5 1-.8-1.2 1.9-1.3V7.8h-2V6.3h2c0-.6.2-1.2.5-1.7L3.3 3.4l.8-1.2z',\n close: 'M3.6 2.5L8 6.9l4.4-4.4 1.1 1.1L9.1 8l4.4 4.4-1.1 1.1L8 9.1l-4.4 4.4-1.1-1.1L6.9 8 2.5 3.6z',\n help: 'M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13zm-.8 9.2h1.6v1.6H7.2zM8 3.7c1.5 0 2.6 1 2.6 2.3 0 1-.6 1.6-1.2 2-.5.4-.7.6-.7 1.2H7.3c0-1.1.5-1.6 1.1-2 .5-.4.8-.6.8-1.1 0-.5-.5-.9-1.2-.9s-1.2.4-1.3 1.1L5.2 6C5.4 4.600 6.500 3.700 8 3.700z',\n theme: 'M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13zM8 3v10A5 5 0 0 1 8 3z',\n map: 'M8 1.5c-2.5 0-4.500 1.900-4.500 4.400 0 3.100 4.500 8.600 4.500 8.600s4.500-5.500 4.500-8.600c0-2.500-2-4.400-4.500-4.400zm0 6.200a1.800 1.800 0 1 1 0-3.600 1.800 1.800 0 0 1 0 3.600z',\n code: 'M5.600 3.800l1.100 1.100L3.600 8l3.100 3.100-1.100 1.100L1.400 8zM10.400 3.800l4.200 4.200-4.200 4.200-1.100-1.100L12.400 8 9.300 4.900z',\n external: 'M9 2h5v5h-1.500V4.600L7.600 9.500 6.500 8.400l4.900-4.900H9zM3 4h4v1.500H4.500v6h6V9H12v4H3z',\n save: 'M3 2h8l2 2v10H3zM5 3.500v3h5v-3zM5 9.500v3h6v-3z',\n open: 'M2 3.500h4.500l1.500 1.500H14v8H2zM3.500 6.500v5h9v-5z',\n share: 'M12 1.800a2.200 2.200 0 1 1-1.800 3.500L6.400 7.300a2.200 2.200 0 0 1 0 1.400l3.800 2a2.200 2.200 0 1 1-.7 1.300l-3.800-2a2.200 2.200 0 1 1 0-4l3.800-2A2.200 2.200 0 0 1 12 1.800z',\n follow: 'M8 1.500a6.500 6.500 0 1 0 0 13 6.500 6.500 0 0 0 0-13zM8 3a5 5 0 1 1 0 10A5 5 0 0 1 8 3zm0 2.500a2.500 2.500 0 1 0 0 5 2.500 2.500 0 0 0 0-5z',\n chevronUp: 'M8 4.500l5.500 5.500-1.100 1.100L8 6.700l-4.400 4.400L2.500 10z',\n chevronDown: 'M8 11.500L2.500 6l1.100-1.100L8 9.300l4.400-4.400L13.500 6z',\n chevronRight: 'M11.500 8L6 13.500l-1.100-1.100L9.300 8 4.900 3.600 6 2.500z',\n jump: 'M2 7.200h8.300L7.700 4.600l1.100-1.100L13.300 8l-4.500 4.500-1.100-1.100 2.600-2.600H2z',\n legend: 'M8 1.500a6.500 6.500 0 1 0 0 13 6.500 6.500 0 0 0 0-13zm-.800 5.700h1.600v4.500H7.200zm0-2.900h1.600v1.600H7.200z',\n} as const;\n\nexport type IconName = keyof typeof PATHS;\n\nexport function Icon({ name }: { name: IconName }) {\n return (\n <svg class=\"icon\" viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" aria-hidden=\"true\" focusable=\"false\">\n <path d={PATHS[name]} fill=\"currentColor\" fill-rule=\"evenodd\" />\n </svg>\n );\n}\n","/**\n * The controls in the header of the code panel (helper mode only), laid out like the\n * toolbar of DevTools' Sources panel: one Run button, Stop while a program runs, then\n * Resume / Pause, Step over, Step into, Step out and \"Deactivate breakpoints\", and one\n * \"more\" button for what is needed less often (the options of the next run and the event\n * loop gates of the probe build).\n *\n * There is one Run button and no Debug button: Run stops at breakpoints when there are\n * any, and otherwise runs the program at full speed (lib/runMode.ts decides; the strip\n * under the header says which, before the button is pressed).\n *\n * Every control is enabled from the capabilities of the selected Node (lib/controls.ts).\n * A control that is off stays where it is and says why: as its accessible description\n * and tooltip, and in the hint strip when it is focused, hovered or pressed.\n *\n * Height matters here: every row of controls is a row the code does not get. So this is\n * one row that never wraps (on a narrow screen the buttons are icons), and the options\n * are behind \"more\".\n *\n * Gates are chosen BEFORE a run as well as during one: a real program is over in a few\n * milliseconds, so nobody could stop it by clicking. With no run the gate buttons are\n * toggles that arm gates for the next run (sent with Run); during a run they act at once.\n */\nimport type { Phase } from '@nodejs-map/event-format';\nimport { useState } from 'preact/hooks';\nimport { gateGroupReason } from '../lib/controls.ts';\nimport { PHASE_LABEL } from '../lib/format.ts';\nimport { Ctl } from '../shell/Ctl.tsx';\nimport { Icon } from '../shell/icons.tsx';\nimport { program, session, settings, ui } from '../stores/index.ts';\nimport { POOL_SIZE_MAX } from '../stores/settings.ts';\n\nconst PHASES: readonly Phase[] = ['timers', 'pending', 'idle', 'prepare', 'poll', 'check', 'closing'];\n\n/** How Node.js loads the snippet. In the header on a wide screen, under \"more\" on a narrow one. */\nexport function ModuleSelect() {\n return (\n <select\n class=\"select codehead__module\"\n aria-label=\"How Node.js loads the snippet\"\n title=\"How Node.js loads the snippet: as a CommonJS script or as an ES module\"\n value={settings.module.value}\n onChange={(e) => {\n settings.module.value = (e.currentTarget as HTMLSelectElement).value === 'esm' ? 'esm' : 'commonjs';\n }}\n >\n <option value=\"commonjs\">CommonJS</option>\n <option value=\"esm\">ES module</option>\n </select>\n );\n}\n\nfunction Options() {\n const snippet = program.source.value.kind === 'snippet';\n const poolSize = settings.poolSize.value;\n const debuggerNote = session.controls.value.debug.reason;\n return (\n <div class=\"runopts\" role=\"group\" aria-label=\"Options for the next run\">\n {ui.narrow.value && snippet ? (\n <label class=\"field field--inline\">\n <span class=\"field__label\">Module</span>\n <ModuleSelect />\n </label>\n ) : null}\n <label class=\"field field--inline\" title=\"UV_THREADPOOL_SIZE for the next run. Empty leaves the environment alone (libuv's default is 4).\">\n <span class=\"field__label\">Pool size</span>\n <input\n class=\"input input--num\"\n type=\"number\"\n inputMode=\"numeric\"\n min={1}\n max={POOL_SIZE_MAX}\n placeholder=\"default\"\n value={poolSize ?? ''}\n onChange={(e) => {\n const raw = (e.currentTarget as HTMLInputElement).value.trim();\n const n = Number(raw);\n settings.poolSize.value = raw !== '' && Number.isInteger(n) && n >= 1 && n <= POOL_SIZE_MAX ? n : null;\n }}\n />\n </label>\n <label class=\"check\" title={debuggerNote ?? 'Run stops at the first statement of the program, as if there were a breakpoint on it'}>\n <input\n type=\"checkbox\"\n checked={settings.pauseOnStart.value}\n onChange={(e) => {\n settings.pauseOnStart.value = (e.currentTarget as HTMLInputElement).checked;\n }}\n />\n Pause on the first line\n </label>\n <label class=\"check runopts__wide\" title=\"Applies to runs that were never stopped: not after a pause at a breakpoint, not after Stop, and not when you paused, stepped or moved the timeline during the run.\">\n <input\n type=\"checkbox\"\n checked={settings.autoReplay.value}\n onChange={(e) => {\n settings.autoReplay.value = (e.currentTarget as HTMLInputElement).checked;\n }}\n />\n <span>\n When a run finishes, replay it from the start. <span class=\"muted\">Your program runs at full speed; this replays what was recorded, at the speed chosen in the bar below.</span>\n </span>\n </label>\n <label class=\"check runopts__wide\" title=\"The helper captures a stack for every output and for every timer, promise, request and handle, to find the line of your program behind it.\">\n <input\n type=\"checkbox\"\n checked={settings.sourceLines.value}\n onChange={(e) => {\n settings.sourceLines.value = (e.currentTarget as HTMLInputElement).checked;\n }}\n />\n <span>\n Record source lines.{' '}\n <span class=\"muted\">\n Lets a replay highlight the line of code it is at. Adds a little work per timer, promise and output line; in programs with millisecond races it can change which side wins more often.\n </span>\n </span>\n </label>\n </div>\n );\n}\n\nfunction Gates() {\n const controls = session.controls.value;\n const gates = session.gates.value;\n const [phase, setPhase] = useState<Phase>('poll');\n const groupReason = gateGroupReason(controls);\n // Can the selected Node stop at gates at all? (Off for another reason, such as \"nothing\n // is running\", still counts as \"can\".)\n const capable = session.provider.value?.caps.gates.phase === true;\n const status = session.liveStatus.value;\n const live = status === 'running' || status === 'paused' || status === 'gated';\n const armed = armedGates();\n const state = !capable\n ? 'not on this Node.js: needs the probe build'\n : live\n ? 'the program is running: these act now'\n : armed.length > 0\n ? `armed for the next run: ${armed.join(', ')}`\n : 'choose here before you run: a program is over in milliseconds';\n return (\n <div class=\"gates\">\n <p class=\"gates__head\">\n <span class=\"label\">Loop gates</span>\n <span class={`fold__state${armed.length > 0 && capable && !live ? ' fold__state--armed' : ' muted'}`}>{state}</span>\n </p>\n <div class=\"gates__row\" role=\"group\" aria-label=\"Event loop gates (probe build)\">\n {live || !capable ? (\n <Ctl label=\"Pause at the next phase\" state={controls.pauseAtNextPhase} onAct={() => void session.gate({ kind: 'pauseAtNextPhase' })}>\n Next phase\n </Ctl>\n ) : (\n <Ctl label=\"Start the next run stopped at the first phase\" pressed={gates.phase} state={controls.pauseAtNextPhase} onAct={() => void session.setGate('phase', !gates.phase)}>\n Start stopped at the first phase\n </Ctl>\n )}\n <Ctl label=\"Step one phase\" state={controls.stepPhase} onAct={() => void session.gate({ kind: 'stepPhase' })}>\n Step phase\n </Ctl>\n <span class=\"gates__runto\">\n <Ctl label={`Run to the ${PHASE_LABEL[phase]} phase`} state={controls.runToPhase} onAct={() => void session.gate({ kind: 'runToPhase', phase })}>\n Run to\n </Ctl>\n <select class=\"select\" aria-label=\"Phase to run to\" value={phase} onChange={(e) => setPhase((e.currentTarget as HTMLSelectElement).value as Phase)}>\n {PHASES.map((p) => (\n <option key={p} value={p}>\n {PHASE_LABEL[p]}\n </option>\n ))}\n </select>\n </span>\n <span class=\"label gates__title\">Stop before</span>\n <Ctl label=\"Stop before a timer fires\" pressed={gates.timer} state={controls.gateTimer} onAct={() => void session.setGate('timer', !gates.timer)}>\n Timer\n </Ctl>\n <Ctl label=\"Stop before a pool thread starts a job\" pressed={gates.poolStart} state={controls.gatePoolStart} onAct={() => void session.setGate('poolStart', !gates.poolStart)}>\n Pool start\n </Ctl>\n <Ctl label=\"Stop before a pool thread posts its result\" pressed={gates.poolPost} state={controls.gatePoolPost} onAct={() => void session.setGate('poolPost', !gates.poolPost)}>\n Pool post\n </Ctl>\n <Ctl label=\"Resume from the gate\" state={controls.gateResume} onAct={() => void session.gate({ kind: 'resume' })}>\n Resume\n </Ctl>\n </div>\n {groupReason ? <p class=\"gates__why\">{groupReason}</p> : null}\n </div>\n );\n}\n\n/** The gates armed for the next run, in words. */\nexport function armedGates(): string[] {\n const gates = session.gates.value;\n if (session.provider.value?.caps.gates.phase !== true) return [];\n return [gates.phase ? 'stop at the first phase' : null, gates.timer ? 'before timers' : null, gates.poolStart ? 'before pool jobs start' : null, gates.poolPost ? 'before pool results are posted' : null].filter(\n (x): x is string => x !== null,\n );\n}\n\n/** What \"more\" holds: the options of the next run and the gates. Opens under the header and stays until closed. */\nexport function RunMore() {\n if (!ui.runMore.value) return null;\n return (\n <div\n class=\"runmore\"\n id=\"run-more\"\n role=\"region\"\n aria-label=\"Run options and loop gates\"\n onKeyDown={(e) => {\n if (e.key !== 'Escape') return;\n ui.runMore.value = false;\n document.getElementById('run-more-button')?.focus();\n }}\n >\n <Options />\n <Gates />\n </div>\n );\n}\n\n/** Run, Stop, the debugger buttons in DevTools' order, and \"more\". One row. */\nexport function RunButtons() {\n const controls = session.controls.value;\n const status = session.liveStatus.value;\n const paused = status === 'paused';\n const live = status !== 'idle';\n const narrow = ui.narrow.value;\n const active = program.breakpointsActive.value;\n const more = ui.runMore.value;\n const stop = (\n <Ctl label=\"Stop\" kind=\"danger\" keys=\"Ctrl+.\" class={narrow ? 'ctl--icon' : ''} state={controls.stop} onAct={() => void session.stop()}>\n <Icon name=\"stop\" />\n {narrow ? null : <span>Stop</span>}\n </Ctl>\n );\n return (\n <div class=\"toolbar codehead__run\" role=\"toolbar\" aria-label=\"Run and debug\">\n {/* A phone has room for one of the two: Stop takes Run's place while the program runs. */}\n {narrow && live ? null : (\n <Ctl label=\"Run\" kind=\"primary\" keys=\"Ctrl+Enter\" class=\"codehead__runbtn\" state={controls.run} onAct={() => void session.start()}>\n <Icon name=\"play\" />\n <span>Run</span>\n </Ctl>\n )}\n {live ? stop : null}\n <span class=\"toolbar__sep\" aria-hidden=\"true\" />\n {paused ? (\n <Ctl label=\"Resume script execution\" keys=\"F8 or Ctrl+\\\" class=\"ctl--icon\" state={controls.resume} onAct={() => void session.debug('resume')}>\n <Icon name=\"resume\" />\n </Ctl>\n ) : (\n <Ctl label=\"Pause script execution\" keys=\"F8 or Ctrl+\\\" class=\"ctl--icon\" state={controls.pause} onAct={() => void session.debug('pause')}>\n <Icon name=\"pause\" />\n </Ctl>\n )}\n <Ctl label=\"Step over next function call\" keys=\"F10 or Ctrl+'\" class=\"ctl--icon\" state={controls.stepOver} onAct={() => void session.debug('stepOver')}>\n <Icon name=\"stepOver\" />\n </Ctl>\n <Ctl label=\"Step into next function call\" keys=\"F11 or Ctrl+;\" class=\"ctl--icon\" state={controls.stepInto} onAct={() => void session.debug('stepInto')}>\n <Icon name=\"stepInto\" />\n </Ctl>\n <Ctl label=\"Step out of current function\" keys=\"Shift+F11 or Ctrl+Shift+;\" class=\"ctl--icon\" state={controls.stepOut} onAct={() => void session.debug('stepOut')}>\n <Icon name=\"stepOut\" />\n </Ctl>\n <Ctl\n label={active ? 'Deactivate breakpoints' : 'Activate breakpoints'}\n keys=\"Ctrl+F8\"\n class=\"ctl--icon\"\n pressed={!active}\n onAct={() => {\n program.setBreakpointsActive(!active);\n session.announce(active ? 'Breakpoints deactivated: the program will not stop at them.' : 'Breakpoints activated.');\n }}\n >\n <Icon name={active ? 'breakpoints' : 'breakpointsOff'} />\n </Ctl>\n <button\n type=\"button\"\n id=\"run-more-button\"\n class={`ctl ctl--plain ctl--icon${more ? ' is-pressed' : ''}`}\n aria-label=\"More run options\"\n title=\"More: pool size, pause on the first line, replay when finished, record source lines, loop gates\"\n aria-expanded={more ? 'true' : 'false'}\n aria-controls=\"run-more\"\n onClick={() => (ui.runMore.value = !more)}\n >\n <Icon name=\"more\" />\n </button>\n </div>\n );\n}\n","/**\n * Showing and hiding the areas of the main view (stores/layout.ts), three ways:\n * - the View menu in the top bar (a WAI-ARIA menu of checkboxes, with Alt+1..4);\n * - a × button on each area (\"Hide map\");\n * - a restore strip where a hidden area was (\"Map hidden · Show\"), so the way back is\n * always on screen.\n */\nimport { useEffect, useId, useRef, useState } from 'preact/hooks';\nimport { layout, settings, showTab } from '../stores/index.ts';\nimport { AREA_IDS, AREA_KEY, AREA_LABEL } from '../stores/layout.ts';\nimport type { AreaId } from '../stores/layout.ts';\nimport { Icon } from './icons.tsx';\n\nconst mac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);\nconst keysOf = (area: AreaId): string => `${mac ? '⌥' : 'Alt+'}${AREA_KEY[area]}`;\n\n/** Alt+1..4 and the menu items. On a phone \"Code\" opens the Code tab of the sheet. */\nexport function toggleArea(area: AreaId): void {\n if (area === 'code' && !layout.applies('code')) {\n if (layout.shown.peek().panels && settings.tab.peek() === 'code') layout.set('panels', false);\n else showTab('code');\n return;\n }\n layout.toggle(area);\n}\n\nexport function ViewMenu() {\n const [open, setOpen] = useState(false);\n const button = useRef<HTMLButtonElement>(null);\n const menu = useRef<HTMLDivElement>(null);\n const menuId = useId();\n const shown = layout.shown.value;\n const areas = AREA_IDS.filter((a) => layout.applies(a));\n\n const items = (): HTMLElement[] => [...(menu.current?.querySelectorAll<HTMLElement>('[role^=\"menuitem\"]') ?? [])];\n const close = (focusButton: boolean): void => {\n setOpen(false);\n if (focusButton) button.current?.focus();\n };\n\n // Focus the first item when the menu opens; a click anywhere else closes it.\n const [focusAt, setFocusAt] = useState<'first' | 'last'>('first');\n useEffect(() => {\n if (!open) return;\n const list = items();\n (focusAt === 'last' ? list[list.length - 1] : list[0])?.focus();\n const onDown = (e: PointerEvent): void => {\n const target = e.target as Node;\n if (!menu.current?.contains(target) && !button.current?.contains(target)) setOpen(false);\n };\n addEventListener('pointerdown', onDown, true);\n return () => removeEventListener('pointerdown', onDown, true);\n }, [open]);\n\n const onMenuKey = (e: KeyboardEvent): void => {\n const list = items();\n const at = list.indexOf(document.activeElement as HTMLElement);\n let next = -1;\n if (e.key === 'ArrowDown') next = (at + 1) % list.length;\n else if (e.key === 'ArrowUp') next = (at - 1 + list.length) % list.length;\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = list.length - 1;\n else if (e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n close(true);\n return;\n } else if (e.key === 'Tab') {\n setOpen(false);\n return;\n } else if (e.key === ' ' || e.key === 'Enter') {\n // The item's own click runs; keep the key from the player's shortcuts.\n return;\n } else {\n // A letter jumps to the item that starts with it.\n if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {\n const found = list.findIndex((el, i) => i > at && el.textContent?.trim().toLowerCase().startsWith(e.key.toLowerCase()));\n const any = found >= 0 ? found : list.findIndex((el) => el.textContent?.trim().toLowerCase().startsWith(e.key.toLowerCase()));\n if (any >= 0) next = any;\n else return;\n } else return;\n }\n e.preventDefault();\n e.stopPropagation();\n list[next]?.focus();\n };\n\n const act = (fn: () => void): void => {\n fn();\n close(true);\n };\n\n return (\n <div class=\"viewmenu\">\n <button\n ref={button}\n type=\"button\"\n class=\"ctl ctl--plain topbar__view\"\n aria-haspopup=\"menu\"\n aria-expanded={open ? 'true' : 'false'}\n aria-controls={open ? menuId : undefined}\n title=\"Show or hide the map, the code, the panels and the playback bar\"\n onClick={() => {\n setFocusAt('first');\n setOpen(!open);\n }}\n onKeyDown={(e) => {\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n e.preventDefault();\n e.stopPropagation();\n setFocusAt(e.key === 'ArrowUp' ? 'last' : 'first');\n setOpen(true);\n }\n }}\n >\n View\n <Icon name=\"chevronDown\" />\n </button>\n {open ? (\n <div ref={menu} id={menuId} class=\"viewmenu__list\" role=\"menu\" aria-label=\"View\" onKeyDown={onMenuKey}>\n {areas.map((area) => (\n <button\n key={area}\n type=\"button\"\n class=\"viewmenu__item\"\n role=\"menuitemcheckbox\"\n aria-checked={shown[area] ? 'true' : 'false'}\n aria-keyshortcuts={`Alt+${AREA_KEY[area]}`}\n tabIndex={-1}\n onClick={() => act(() => layout.toggle(area))}\n >\n <span class=\"viewmenu__check\" aria-hidden=\"true\">{shown[area] ? '✓' : ''}</span>\n <span class=\"viewmenu__label\">{AREA_LABEL[area]}</span>\n <kbd class=\"viewmenu__keys\" aria-hidden=\"true\">{keysOf(area)}</kbd>\n </button>\n ))}\n <div class=\"viewmenu__sep\" role=\"separator\" />\n <button type=\"button\" class=\"viewmenu__item\" role=\"menuitem\" tabIndex={-1} onClick={() => act(() => layout.showAll())}>\n <span class=\"viewmenu__check\" aria-hidden=\"true\" />\n <span class=\"viewmenu__label\">Show all</span>\n </button>\n <button type=\"button\" class=\"viewmenu__item\" role=\"menuitem\" tabIndex={-1} title=\"Show every area and put the dividers back where they started\" onClick={() => act(() => layout.reset())}>\n <span class=\"viewmenu__check\" aria-hidden=\"true\" />\n <span class=\"viewmenu__label\">Reset layout</span>\n </button>\n </div>\n ) : null}\n </div>\n );\n}\n\n/** The × on an area: \"Hide map\". */\nexport function AreaClose({ area, class: extra }: { area: AreaId; class?: string }) {\n const name = `Hide ${AREA_LABEL[area].toLowerCase()}`;\n return (\n <button\n type=\"button\"\n class={`ctl ctl--plain ctl--icon areaclose${extra ? ` ${extra}` : ''}`}\n aria-label={name}\n title={`${name} (${keysOf(area)}; View menu to bring it back)`}\n onClick={() => layout.set(area, false)}\n >\n <Icon name=\"close\" />\n </button>\n );\n}\n\n/** Where a hidden area was: one button that brings it back. */\nexport function RestoreStrip({ area, vertical = false }: { area: AreaId; vertical?: boolean }) {\n return (\n <button type=\"button\" class={`restore restore--${area}${vertical ? ' restore--vertical' : ''}`} title={`Show ${AREA_LABEL[area].toLowerCase()} (${keysOf(area)})`} onClick={() => layout.set(area, true)}>\n <span class=\"restore__name\">{AREA_LABEL[area]} hidden</span>\n <span class=\"restore__dot\"> · </span>\n <span class=\"restore__show\">Show</span>\n </button>\n );\n}\n","/**\n * The code panel: one header row (what the text is on the left; Run and the debugger\n * buttons on the right, in helper mode), a one-line strip that says what is going on\n * (what Run will do, \"Running...\", \"Paused on breakpoint - line 3\"), then the text.\n *\n * What the text is depends on what is on screen (stores/index.ts `shown`):\n * - the snippet: editable, with breakpoints;\n * - a file of the helper's folder: read-only (Run starts the file itself), with breakpoints;\n * - the source carried by a recording: read-only, never run.\n *\n * The line the run or replay is at is highlighted in the text (stores/index.ts\n * `editorMark`): strongly, with an arrow in the gutter, where the debugger is stopped;\n * quietly, with a tag in words, for the lines a replay can only vouch for.\n */\nimport { CodeView } from './CodeView.tsx';\nimport { ModuleSelect, RunButtons, RunMore, armedGates } from './RunControls.tsx';\nimport { baseName } from '../lib/format.ts';\nimport { pauseWords } from '../lib/sourceLine.ts';\nimport { Ctl } from '../shell/Ctl.tsx';\nimport { Icon } from '../shell/icons.tsx';\nimport { AreaClose } from '../shell/ViewMenu.tsx';\nimport { editorMark, hasRun, helperMode, player, program, session, shown, ui } from '../stores/index.ts';\n\n/** Left side of the header: the program picker (helper mode), or what the read-only text is. */\nfunction What() {\n const s = shown.value;\n const recording = s.origin === 'recording';\n if (recording) {\n return (\n <div class=\"codehead__what\">\n {s.files.length > 1 ? (\n <select\n class=\"select\"\n aria-label=\"File of the recording\"\n value={Math.min(ui.recordingSource.value, s.files.length - 1)}\n onChange={(e) => {\n ui.recordingSource.value = Number((e.currentTarget as HTMLSelectElement).value);\n }}\n >\n {s.files.map((name, i) => (\n <option key={i} value={i}>\n {name}\n </option>\n ))}\n </select>\n ) : (\n <span class=\"codehead__name mono ellipsis\" title={s.name}>\n {s.name}\n </span>\n )}\n <span class=\"codehead__kind muted ellipsis\" title=\"The text the recording carries. It is shown read-only and is never run.\">\n from the recording · never run\n </span>\n </div>\n );\n }\n if (!helperMode.value) {\n return (\n <div class=\"codehead__what\">\n <span class=\"codehead__name mono ellipsis\">{s.name}</span>\n <span class=\"codehead__kind muted\">read-only</span>\n </div>\n );\n }\n const file = program.source.value.kind === 'file';\n return (\n <div class=\"codehead__what\">\n {/* On a phone the picker is in the top bar: this row is for the buttons. */}\n {ui.narrow.value ? null : (\n <button type=\"button\" class=\"ctl ctl--plain codehead__program\" aria-haspopup=\"dialog\" title=\"Choose what to run: the snippet, an example or a file\" onClick={() => (ui.dialog.value = 'program')}>\n <Icon name=\"code\" />\n <span class=\"ellipsis mono\">{s.name}</span>\n <Icon name=\"chevronDown\" />\n </button>\n )}\n {ui.narrow.value ? null : file ? (\n <span class=\"codehead__kind muted ellipsis\" title=\"A file on disk is shown read-only here; Run starts the file itself\">\n file · read-only here\n </span>\n ) : (\n <ModuleSelect />\n )}\n </div>\n );\n}\n\nconst REAL_TIME_WHY =\n 'An official Node.js can be stopped only at a JavaScript statement. The operating system, the timers and the thread pool threads are not stopped with it: timers keep coming due and pool work keeps finishing while you look, so what happens after this pause may come in a different order than in a run without pauses. The probe build can freeze the loop clock and hold the pool threads instead.';\nconst FROZEN_WHY =\n 'The probe build holds the loop clock and the thread pool threads during this pause, so timers do not come due and no pool work starts or is handed back. Not held: work already running on a pool thread, Date.now(), the operating system and network peers.';\n\n/** The pause, in one line: where, why, the two buttons used most, and what a pause does to time. */\nfunction PausedStrip() {\n const debug = player.parts.debug.value;\n if (!debug?.paused) return null;\n const controls = session.controls.value;\n const top = debug.frames[0];\n const s = shown.value;\n const mark = editorMark.value;\n // The actions belong to a program that is stopped right now, not to a recording of a pause.\n const atTail = player.parts.live.value && player.parts.position.peek() === player.parts.length.peek();\n const canAct = session.liveStatus.value === 'paused' && atTail;\n const where = top ? (mark && mark.kind === 'paused' ? `line ${top.loc.line}` : `${top.origin === 'node' ? top.loc.url : baseName(top.loc.url)}, line ${top.loc.line}`) : null;\n const elsewhere = top && !(mark && mark.kind === 'paused') && top.origin !== 'node' && s.text !== null;\n return (\n <div class=\"codestrip codestrip--paused\" role=\"status\">\n <span class=\"codestrip__main\">\n <strong>\n {canAct ? pauseWords(debug.reason) : `${pauseWords(debug.reason)} (recorded)`}\n {where ? ` - ${where}` : ''}\n </strong>\n {elsewhere ? <span class=\"muted\"> · in a file that is not open here</span> : null}\n </span>\n {canAct ? (\n <span class=\"codestrip__acts\">\n <Ctl label=\"Resume\" keys=\"F8\" state={controls.resume} onAct={() => void session.debug('resume')}>\n <Icon name=\"resume\" />\n <span>Resume</span>\n </Ctl>\n <Ctl label=\"Step over\" keys=\"F10\" state={controls.stepOver} onAct={() => void session.debug('stepOver')}>\n <Icon name=\"stepOver\" />\n <span>Step over</span>\n </Ctl>\n </span>\n ) : null}\n <details class=\"codestrip__time\">\n <summary title=\"Why, and what it means for what you see\">\n {debug.timeKeptRunning ? 'Real time keeps running' : 'The clock is frozen'}\n <span class=\"codestrip__wide\"> while paused</span> · why\n </summary>\n <p>{debug.timeKeptRunning ? REAL_TIME_WHY : FROZEN_WHY}</p>\n </details>\n </div>\n );\n}\n\n/** The strip between the header and the text. One line; always the same height. */\nfunction Strip() {\n const debug = player.parts.debug.value;\n const helper = helperMode.value;\n const status = session.liveStatus.value;\n const kind = session.kind.value;\n if (debug?.paused) return <PausedStrip />;\n\n // A run or recording that names no line of source: say once, here, why nothing is highlighted.\n const tail = player.tail.value;\n const noLines = hasRun.value && !tail.located && tail.status !== 'running' && tail.status !== 'idle' && tail.length > 0;\n const noLinesNote = noLines ? (\n <span class=\"codestrip__note muted\" title=\"The line highlight needs events that name a line of the program. This run has none.\">\n No line is highlighted: {kind === 'recording' ? 'this recording has no source lines' : 'this run recorded no source lines (switch on \"Record source lines\" under More)'}.\n </span>\n ) : null;\n\n // The line the replay is at, in words as well: the tag at the end of a long line can be\n // out of sight. The strip keeps its place while the replay moves (no jumping text below).\n const mark = editorMark.value;\n const lineNote =\n hasRun.value && tail.located && status === 'idle' ? (\n mark && mark.tag ? (\n <span class=\"codestrip__line\">\n Line {mark.line}: {mark.tag}\n </span>\n ) : (\n <span class=\"codestrip__line muted\">{mark ? `Line ${mark.line}` : 'No line: no JavaScript of this program is running at this point'}</span>\n )\n ) : null;\n\n if (kind === 'recording') {\n return lineNote || noLinesNote ? (\n <div class=\"codestrip\">\n {lineNote}\n {noLinesNote}\n </div>\n ) : null;\n }\n if (!helper) return null;\n if (status === 'starting') return <div class=\"codestrip codestrip--running\" role=\"status\">Starting...</div>;\n if (status === 'running') {\n return (\n <div class=\"codestrip codestrip--running\" role=\"status\">\n <span class=\"live-dot is-on\" aria-hidden=\"true\" />\n Running...\n </div>\n );\n }\n if (status === 'gated') return <div class=\"codestrip codestrip--running\" role=\"status\">Stopped at a gate (see the message above the map).</div>;\n const plan = session.plan.value;\n const armed = armedGates();\n return (\n <div class=\"codestrip\">\n {kind === 'live' ? lineNote : null}\n <span\n class={`codestrip__plan${plan.mode === 'debug' ? ' codestrip__plan--debug' : ''}`}\n title={`What pressing Run will do: ${plan.says}. With a breakpoint (click a line number) Run stops there; without one the program runs at full speed, which keeps its real timing.`}\n >\n {kind === 'live' && lineNote ? 'Run: ' : ''}\n {plan.says}\n {armed.length > 0 ? ` · gates armed: ${armed.join(', ')}` : ''}\n </span>\n {kind === 'live' ? noLinesNote : null}\n </div>\n );\n}\n\n/**\n * The text. A component of its own: the line mark changes with almost every step of a\n * replay, and nothing else of the code panel has to re-render for it.\n */\nfunction ProgramCode({ text }: { text: string }) {\n const s = shown.value;\n const live = s.origin === 'program' && helperMode.value;\n const reveal = ui.reveal.value;\n const mark = editorMark.value;\n const file = program.name.value;\n return (\n <CodeView\n text={text}\n language=\"javascript\"\n readOnly={s.readOnly}\n label={s.readOnly ? `Program text of ${s.name}, read-only` : `Program text of ${s.name}`}\n onChange={live ? (next) => program.setSnippetText(next) : undefined}\n breakpoints={live ? program.breakpoints.value : undefined}\n breakpointsActive={program.breakpointsActive.value}\n onToggleBreakpoint={live ? (n) => program.toggleBreakpoint(n, file) : undefined}\n onBreakpointsMoved={live ? (marks) => program.setFileBreakpoints(file, marks) : undefined}\n lineMark={mark ? { line: mark.line, kind: mark.kind, tag: mark.tag } : null}\n range={reveal ? { start: reveal.start, end: reveal.end } : null}\n revealKey={reveal?.ticket}\n />\n );\n}\n\nexport function EditorPane() {\n const s = shown.value;\n const helper = helperMode.value;\n const debugNote = session.kind.value === 'live' && session.liveStatus.value !== 'idle' && !s.readOnly ? 'Edits apply to the next run.' : null;\n return (\n <section class=\"editor\" aria-label=\"Program\">\n <div class=\"codehead\">\n <What />\n {helper ? <RunButtons /> : null}\n {/* On a phone the code is a tab of the panels: it is hidden with them. */}\n {ui.narrow.value ? null : <AreaClose area=\"code\" class=\"codehead__close\" />}\n </div>\n {helper ? <RunMore /> : null}\n <Strip />\n {s.text === null ? (\n <p class=\"empty\">{s.missing}</p>\n ) : (\n <ProgramCode text={s.text} />\n )}\n {debugNote ? <p class=\"editor__note muted\">{debugNote}</p> : null}\n </section>\n );\n}\n","/**\n * Keyboard shortcuts as data: the key handler and the help dialog both read this table,\n * so the help can never list a shortcut that does not exist.\n *\n * Shortcuts made of plain letters are ignored while the user types in a field or in the\n * editor. Shortcuts with Ctrl/Cmd or a function key work everywhere.\n */\n\nexport type ShortcutId =\n | 'player.toggle'\n | 'player.stepForward'\n | 'player.stepBack'\n | 'player.eventForward'\n | 'player.eventBack'\n | 'player.callbackForward'\n | 'player.callbackBack'\n | 'player.phaseForward'\n | 'player.phaseBack'\n | 'player.turnForward'\n | 'player.turnBack'\n | 'player.outputForward'\n | 'player.outputBack'\n | 'player.pauseForward'\n | 'player.pauseBack'\n | 'player.start'\n | 'player.end'\n | 'player.slower'\n | 'player.faster'\n | 'player.followLive'\n | 'view.followAction'\n | 'run.run'\n | 'run.stop'\n | 'debug.pauseResume'\n | 'debug.stepOver'\n | 'debug.stepInto'\n | 'debug.stepOut'\n | 'debug.toggleBreakpoints'\n | 'view.showOnMap'\n | 'view.legend'\n | 'view.help'\n | 'view.theme'\n | 'view.tab1'\n | 'view.tab2'\n | 'view.tab3'\n | 'view.tab4'\n | 'view.tab5'\n | 'view.tab6'\n | 'view.tab7'\n | 'view.tab8'\n | 'layout.map'\n | 'layout.code'\n | 'layout.panels'\n | 'layout.playback';\n\nexport type ShortcutGroup = 'Playback' | 'Stepping through the recording' | 'Running and debugging' | 'View';\n\nexport interface KeyCombo {\n /** KeyboardEvent.key, compared without case for single letters. */\n key: string;\n ctrl?: boolean;\n shift?: boolean;\n alt?: boolean;\n /**\n * KeyboardEvent.code to match instead of the key, where the event has one: Option+1 on\n * a Mac reports the key \"¡\", not \"1\".\n */\n code?: string;\n}\n\nexport interface Shortcut {\n id: ShortcutId;\n group: ShortcutGroup;\n label: string;\n combos: readonly KeyCombo[];\n /** Only in helper mode (needs a helper to run code). */\n helperOnly?: boolean;\n}\n\nconst k = (key: string, mods: Omit<KeyCombo, 'key'> = {}): KeyCombo => ({ key, ...mods });\n\nexport const SHORTCUTS: readonly Shortcut[] = [\n { id: 'player.toggle', group: 'Playback', label: 'Play or pause', combos: [k(' '), k('k')] },\n { id: 'player.slower', group: 'Playback', label: 'Slower', combos: [k('-')] },\n { id: 'player.faster', group: 'Playback', label: 'Faster', combos: [k('+'), k('=')] },\n { id: 'player.start', group: 'Playback', label: 'Go to the start', combos: [k('Home')] },\n { id: 'player.end', group: 'Playback', label: 'Go to the end', combos: [k('End')] },\n { id: 'player.followLive', group: 'Playback', label: 'Follow the live run', combos: [k('l')] },\n\n { id: 'player.stepBack', group: 'Stepping through the recording', label: 'Previous step', combos: [k('ArrowLeft')] },\n { id: 'player.stepForward', group: 'Stepping through the recording', label: 'Next step', combos: [k('ArrowRight')] },\n { id: 'player.eventBack', group: 'Stepping through the recording', label: 'Previous event (raw signals too)', combos: [k('ArrowLeft', { shift: true }), k(',')] },\n { id: 'player.eventForward', group: 'Stepping through the recording', label: 'Next event (raw signals too)', combos: [k('ArrowRight', { shift: true }), k('.')] },\n { id: 'player.callbackBack', group: 'Stepping through the recording', label: 'Previous callback', combos: [k('c', { shift: true })] },\n { id: 'player.callbackForward', group: 'Stepping through the recording', label: 'Next callback', combos: [k('c')] },\n { id: 'player.phaseBack', group: 'Stepping through the recording', label: 'Previous loop phase', combos: [k('p', { shift: true })] },\n { id: 'player.phaseForward', group: 'Stepping through the recording', label: 'Next loop phase', combos: [k('p')] },\n { id: 'player.turnBack', group: 'Stepping through the recording', label: 'Previous loop turn', combos: [k('t', { shift: true })] },\n { id: 'player.turnForward', group: 'Stepping through the recording', label: 'Next loop turn', combos: [k('t')] },\n { id: 'player.outputBack', group: 'Stepping through the recording', label: 'Previous output', combos: [k('o', { shift: true })] },\n { id: 'player.outputForward', group: 'Stepping through the recording', label: 'Next output', combos: [k('o')] },\n { id: 'player.pauseBack', group: 'Stepping through the recording', label: 'Previous debugger pause', combos: [k('b', { shift: true })] },\n { id: 'player.pauseForward', group: 'Stepping through the recording', label: 'Next debugger pause', combos: [k('b')] },\n\n { id: 'run.run', group: 'Running and debugging', label: 'Run (stops at breakpoints when there are any)', combos: [k('Enter', { ctrl: true })], helperOnly: true },\n { id: 'run.stop', group: 'Running and debugging', label: 'Stop', combos: [k('.', { ctrl: true })], helperOnly: true },\n { id: 'debug.pauseResume', group: 'Running and debugging', label: 'Pause or resume the program', combos: [k('F8'), k('\\\\', { ctrl: true })], helperOnly: true },\n { id: 'debug.stepOver', group: 'Running and debugging', label: 'Step over', combos: [k('F10'), k(\"'\", { ctrl: true })], helperOnly: true },\n { id: 'debug.stepInto', group: 'Running and debugging', label: 'Step into', combos: [k('F11'), k(';', { ctrl: true })], helperOnly: true },\n // Ctrl+Shift+; is \":\" on a US keyboard; other layouts report \";\" with Shift held.\n { id: 'debug.stepOut', group: 'Running and debugging', label: 'Step out', combos: [k('F11', { shift: true }), k(':', { ctrl: true, shift: true }), k(';', { ctrl: true, shift: true })], helperOnly: true },\n { id: 'debug.toggleBreakpoints', group: 'Running and debugging', label: 'Deactivate or activate all breakpoints', combos: [k('F8', { ctrl: true })], helperOnly: true },\n\n { id: 'view.followAction', group: 'View', label: 'Move the map with the run: on or off', combos: [k('f')] },\n { id: 'view.showOnMap', group: 'View', label: 'Show on the map where the run is now (once)', combos: [k('m')] },\n { id: 'view.legend', group: 'View', label: 'Open the certainty legend', combos: [k('i')] },\n { id: 'view.theme', group: 'View', label: 'Switch between light and dark', combos: [k('d', { shift: true })] },\n { id: 'view.help', group: 'View', label: 'Show keyboard shortcuts', combos: [k('?'), k('F1')] },\n { id: 'view.tab1', group: 'View', label: 'Show panel 1 to 8', combos: [k('1')] },\n { id: 'view.tab2', group: 'View', label: 'Show panel 2', combos: [k('2')] },\n { id: 'view.tab3', group: 'View', label: 'Show panel 3', combos: [k('3')] },\n { id: 'view.tab4', group: 'View', label: 'Show panel 4', combos: [k('4')] },\n { id: 'view.tab5', group: 'View', label: 'Show panel 5', combos: [k('5')] },\n { id: 'view.tab6', group: 'View', label: 'Show panel 6', combos: [k('6')] },\n { id: 'view.tab7', group: 'View', label: 'Show panel 7', combos: [k('7')] },\n { id: 'view.tab8', group: 'View', label: 'Show panel 8', combos: [k('8')] },\n // Alt+digit: the plain digits pick a panel, Ctrl+digit is the browser's tab switch.\n { id: 'layout.map', group: 'View', label: 'Show or hide the map', combos: [k('1', { alt: true, code: 'Digit1' })] },\n { id: 'layout.code', group: 'View', label: 'Show or hide the code', combos: [k('2', { alt: true, code: 'Digit2' })] },\n { id: 'layout.panels', group: 'View', label: 'Show or hide the panels', combos: [k('3', { alt: true, code: 'Digit3' })] },\n { id: 'layout.playback', group: 'View', label: 'Show or hide the playback bar', combos: [k('4', { alt: true, code: 'Digit4' })] },\n];\n\n/** The fields of a keyboard event the matcher reads. */\nexport interface KeyLike {\n key: string;\n ctrlKey: boolean;\n metaKey: boolean;\n shiftKey: boolean;\n altKey: boolean;\n code?: string;\n}\n\nfunction isPrintable(key: string): boolean {\n return key.length === 1;\n}\n\nfunction comboMatches(combo: KeyCombo, e: KeyLike): boolean {\n const ctrl = e.ctrlKey || e.metaKey; // Cmd on macOS stands in for Ctrl\n if (Boolean(combo.ctrl) !== ctrl) return false;\n if (Boolean(combo.alt) !== e.altKey) return false;\n if (combo.code !== undefined && e.code) return e.code === combo.code && Boolean(combo.shift) === e.shiftKey;\n const letter = /^[a-z]$/i.test(combo.key);\n if (letter) {\n // Letters: Shift is part of the combo (\"c\" and \"Shift+c\" differ).\n return e.key.toLowerCase() === combo.key.toLowerCase() && Boolean(combo.shift) === e.shiftKey;\n }\n if (isPrintable(combo.key) && combo.key !== ' ') {\n // Punctuation: the key value already includes the effect of Shift (\"?\" is Shift+/ on\n // many layouts), so Shift is checked only when the combo asks for it.\n // With Ctrl held it is: Ctrl+; steps into, Ctrl+Shift+; steps out.\n return e.key === combo.key && (combo.shift || combo.ctrl ? Boolean(combo.shift) === e.shiftKey : true);\n }\n return e.key === combo.key && Boolean(combo.shift) === e.shiftKey;\n}\n\n/**\n * The shortcut for a key event, or null.\n * `typing` is true when the focus is in a text field or the code editor: shortcuts that\n * are plain characters then belong to the field.\n */\nexport function matchShortcut(e: KeyLike, typing: boolean, helperMode: boolean): ShortcutId | null {\n for (const s of SHORTCUTS) {\n if (s.helperOnly && !helperMode) continue;\n for (const combo of s.combos) {\n if (!comboMatches(combo, e)) continue;\n const plain = !combo.ctrl && !combo.alt && !/^F\\d+$/.test(combo.key);\n if (typing && plain) continue;\n return s.id;\n }\n }\n return null;\n}\n\nconst KEY_WORDS: Readonly<Record<string, string>> = {\n ' ': 'Space',\n ArrowLeft: '←',\n ArrowRight: '→',\n ArrowUp: '↑',\n ArrowDown: '↓',\n};\n\n/** The keys of a combo as they are shown in the help dialog: [\"Ctrl\", \"Shift\", \"Enter\"]. */\nexport function comboKeys(combo: KeyCombo, mac = false): string[] {\n const keys: string[] = [];\n if (combo.ctrl) keys.push(mac ? '⌘' : 'Ctrl');\n if (combo.alt) keys.push(mac ? '⌥' : 'Alt');\n if (combo.shift) keys.push('Shift');\n keys.push(KEY_WORDS[combo.key] ?? (combo.key.length === 1 ? combo.key.toUpperCase() : combo.key));\n return keys;\n}\n","/**\n * Geometry of the timeline scrubber: between pixels, buckets, event indexes and player\n * positions. Pure; the drawing itself is in transport/Timeline.tsx.\n */\nimport type { TimelineSummary } from '@nodejs-map/replay';\n\n/**\n * The bucket that holds the event at `index`. Works for both axes: `start` (index of the\n * first event of each bucket) never decreases, so the bucket is the last one whose start\n * is at or before the index.\n */\nexport function bucketForIndex(summary: Pick<TimelineSummary, 'start' | 'width'>, index: number): number {\n const { start, width } = summary;\n if (width <= 0) return 0;\n let lo = 0;\n let hi = width - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if ((start[mid] as number) <= index) lo = mid;\n else hi = mid - 1;\n }\n return lo;\n}\n\n/**\n * Horizontal place of a player position, as a fraction 0..1 of the scrubber.\n * Position P means \"the first P events are applied\"; the cursor sits after event P - 1.\n */\nexport function fractionOfPosition(summary: Pick<TimelineSummary, 'start' | 'events' | 'width' | 'axis' | 'from' | 'to' | 'length'>, position: number): number {\n if (summary.length <= 0 || summary.width <= 0) return 0;\n const p = Math.min(Math.max(0, position), summary.length);\n if (summary.axis === 'index') {\n const span = summary.to - summary.from;\n return span <= 0 ? 0 : Math.min(1, Math.max(0, (p - summary.from) / span));\n }\n if (p <= 0) return 0;\n const bucket = bucketForIndex(summary, p - 1);\n const first = summary.start[bucket] as number;\n const count = summary.events[bucket] as number;\n const within = count > 0 ? Math.min(1, (p - first) / count) : 1;\n return Math.min(1, (bucket + within) / summary.width);\n}\n\n/** What to tell the player for a click at `fraction` (0..1) of the scrubber. */\nexport function seekForFraction(\n summary: Pick<TimelineSummary, 'axis' | 'from' | 'to' | 'length'>,\n fraction: number,\n): { do: 'seek'; position: number } | { do: 'seekTime'; t: number } {\n const f = Math.min(1, Math.max(0, fraction));\n if (summary.axis === 'time') return { do: 'seekTime', t: summary.from + f * (summary.to - summary.from) };\n return { do: 'seek', position: Math.min(summary.length, Math.max(0, Math.round(summary.from + f * (summary.to - summary.from)))) };\n}\n\n/** Bar height 0..1 for a count, on a square-root scale so that single events stay visible next to bursts. */\nexport function barHeight(count: number, max: number): number {\n if (count <= 0 || max <= 0) return 0;\n return Math.min(1, Math.sqrt(count / max));\n}\n\n/** The number of buckets to ask for at a pixel width: one per 2 px, within sane bounds. */\nexport function bucketsForWidth(cssWidth: number): number {\n return Math.min(1000, Math.max(50, Math.floor(cssWidth / 2)));\n}\n","/** Small hooks and key handlers shared by the panels. */\nimport { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';\nimport type { RefObject } from 'preact';\n\n/** Height and width of an element, kept current with a ResizeObserver. */\nexport function useElementSize<T extends HTMLElement>(): [RefObject<T | null>, { width: number; height: number }] {\n const ref = useRef<T>(null);\n const [size, setSize] = useState({ width: 0, height: 0 });\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n const update = (): void => {\n const width = el.clientWidth;\n const height = el.clientHeight;\n setSize((old) => (old.width === width && old.height === height ? old : { width, height }));\n };\n update();\n const observer = new ResizeObserver(update);\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n return [ref, size];\n}\n\nfunction mediaMatches(query: string): boolean {\n return typeof matchMedia === 'function' && matchMedia(query).matches;\n}\n\nexport function useMedia(query: string): boolean {\n const [matches, setMatches] = useState(() => mediaMatches(query));\n useEffect(() => {\n const list = matchMedia(query);\n const update = (): void => setMatches(list.matches);\n update();\n list.addEventListener('change', update);\n return () => list.removeEventListener('change', update);\n }, [query]);\n return matches;\n}\n\n/** Row height of dense lists: 24 px with a mouse, 44 px on touch screens (see styles/base.css). */\nexport function useRowHeight(): number {\n return useMedia('(pointer: coarse)') ? 44 : 24;\n}\n\n/**\n * Keys for a list of rows. The list is one tab stop: Up, Down, Home and End move the\n * focus between the elements marked data-row. On the focused row, M presses its \"show on\n * the map\" button, I opens its certainty mark and J its \"go to the event\" button - the\n * row's small buttons are out of the tab order, these keys are how the keyboard reaches\n * them. Use as the onKeyDown of the list container.\n */\nexport function listKeyDown(e: KeyboardEvent): void {\n if (e.ctrlKey || e.metaKey || e.altKey) return;\n const container = e.currentTarget as HTMLElement;\n const active = document.activeElement as HTMLElement | null;\n const key = e.key;\n\n if (key === 'm' || key === 'i' || key === 'j') {\n const row = active?.closest<HTMLElement>('[data-rowbox]');\n if (!row || !container.contains(row)) return;\n const selector = key === 'm' ? '[data-act=\"map\"]' : key === 'i' ? '.mark' : '[data-act=\"jump\"]';\n const button = row.querySelector<HTMLElement>(selector);\n if (!button) return;\n e.preventDefault();\n e.stopPropagation();\n button.click();\n return;\n }\n\n if (key !== 'ArrowDown' && key !== 'ArrowUp' && key !== 'Home' && key !== 'End') return;\n const rows = [...container.querySelectorAll<HTMLElement>('[data-row]')];\n if (rows.length === 0) return;\n const at = active ? rows.indexOf(active) : -1;\n let next = at;\n if (key === 'ArrowDown') next = Math.min(rows.length - 1, at + 1);\n else if (key === 'ArrowUp') next = Math.max(0, at - 1);\n else if (key === 'Home') next = 0;\n else next = rows.length - 1;\n if (next === at || next < 0) return;\n e.preventDefault();\n e.stopPropagation();\n for (const row of rows) row.tabIndex = -1;\n const target = rows[next] as HTMLElement;\n target.tabIndex = 0;\n target.focus();\n}\n\n/** Keys of listKeyDown, for the help dialog. */\nexport const LIST_KEYS: readonly { keys: readonly string[]; label: string }[] = [\n { keys: ['↑', '↓'], label: 'Move between rows of a list' },\n { keys: ['Enter'], label: 'Go to the event of the row' },\n { keys: ['M'], label: 'Show the row on the map' },\n { keys: ['I'], label: 'Explain the certainty mark of the row' },\n];\n","/**\n * The scrubber: the whole run in one strip, drawn on a canvas from replay's timeline\n * summary, with markers for loop turns, output and pauses, and the player's position.\n *\n * It is a slider for assistive technology and the keyboard, and takes mouse and touch\n * drags.\n *\n * The strip is drawn only when the run, the width or the theme changes. The player's\n * position is not on the canvas: the cursor and the dimming of what has not been reached\n * are two elements moved with a transform, so during playback nothing is redrawn or laid\n * out for it.\n */\nimport { useEffect, useLayoutEffect, useRef } from 'preact/hooks';\nimport { CERTAINTY_CODES, PHASE_CODES, TIMELINE_CLASSES } from '@nodejs-map/replay';\nimport type { TimelineMarkers, TimelineSummary } from '@nodejs-map/replay';\nimport { formatMicros } from '../lib/format.ts';\nimport { barHeight, bucketForIndex, bucketsForWidth, fractionOfPosition, seekForFraction } from '../lib/timelineMath.ts';\nimport { useElementSize } from '../shell/hooks.ts';\nimport { player, settings, step } from '../stores/index.ts';\n\n/** Height of the strip in CSS px when the element has not been measured yet. */\nconst HEIGHT = 44;\n\n/** CSS variable for each timeline class that is drawn as part of a bar. */\nconst BAR_CLASSES: readonly { index: number; color: string }[] = [\n ['cb.nextTick', '--q-nextTick'],\n ['cb.microtask', '--q-microtask'],\n ['cb.timers', '--q-timers'],\n ['cb.immediate', '--q-immediate'],\n ['cb.pool', '--q-pool'],\n ['cb.io', '--q-io'],\n ['cb.close', '--q-close'],\n ['cb.other', '--ink-3'],\n].map(([name, color]) => ({ index: TIMELINE_CLASSES.indexOf(name as (typeof TIMELINE_CLASSES)[number]), color: color as string }));\n\nconst PHASE_COLOR: Readonly<Record<string, string>> = {\n timers: '--q-timers',\n pending: '--q-pool',\n idle: '--line-strong',\n prepare: '--line-strong',\n poll: '--q-io',\n check: '--q-immediate',\n closing: '--q-close',\n};\n\ninterface Drawn {\n summary: TimelineSummary | null;\n markers: TimelineMarkers | null;\n width: number;\n height: number;\n theme: string;\n}\n\n/**\n * Colours come from the theme's custom properties. Reading them makes the browser\n * recalculate styles, so they are read once per theme and kept.\n */\nlet colorCache: { key: string; get: (name: string) => string } | null = null;\nfunction themeColors(canvas: HTMLCanvasElement, theme: string): (name: string) => string {\n const key = `${theme}|${matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'}`;\n if (colorCache?.key === key) return colorCache.get;\n const css = getComputedStyle(canvas);\n const colors = new Map<string, string>();\n const get = (name: string): string => {\n let value = colors.get(name);\n if (value === undefined) {\n value = css.getPropertyValue(name).trim() || '#888';\n colors.set(name, value);\n }\n return value;\n };\n // Look up everything now: the computed style object must not be asked again later.\n for (const name of ['--surface-2', '--line-strong', '--warn', '--ink-3', '--ink', '--danger', ...BAR_CLASSES.map((c) => c.color), ...Object.values(PHASE_COLOR)]) get(name);\n colorCache = { key, get: (name) => colors.get(name) ?? '#888' };\n return colorCache.get;\n}\n\nfunction draw(canvas: HTMLCanvasElement, d: Drawn): void {\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n const dpr = Math.min(3, window.devicePixelRatio || 1);\n const w = Math.max(1, Math.floor(d.width));\n const H = d.height > 0 ? Math.floor(d.height) : HEIGHT;\n if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(H * dpr)) {\n canvas.width = Math.round(w * dpr);\n canvas.height = Math.round(H * dpr);\n }\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n const color = themeColors(canvas, d.theme);\n ctx.clearRect(0, 0, w, H);\n ctx.fillStyle = color('--surface-2');\n ctx.fillRect(0, 0, w, H);\n\n const s = d.summary;\n if (!s || s.length === 0 || s.width === 0) return;\n const bw = w / s.width;\n const classes = TIMELINE_CLASSES.length;\n const bandH = 5;\n const barTop = bandH + 2;\n const barBottom = H - 9;\n const barSpan = barBottom - barTop;\n\n // Tallest bucket, for the bar scale.\n let max = 1;\n for (let b = 0; b < s.width; b++) {\n let total = 0;\n for (const c of BAR_CLASSES) total += s.counts[b * classes + c.index] as number;\n if (total > max) max = total;\n }\n\n const pauseColor = color('--warn');\n for (let b = 0; b < s.width; b++) {\n const x = b * bw;\n // Phase band along the top. Line style repeats the certainty: solid observed,\n // every second pixel column for inferred, every third for model.\n const phase = PHASE_CODES[s.phase[b] as number];\n if (phase) {\n const certainty = CERTAINTY_CODES[s.phaseCertainty[b] as number];\n const skip = certainty === 'inferred' ? 2 : certainty === 'model' ? 3 : 1;\n if (b % skip === 0) {\n ctx.fillStyle = color(PHASE_COLOR[phase] ?? '--line-strong');\n ctx.fillRect(x, 0, Math.max(1, bw - (skip > 1 ? 0.5 : 0)), bandH);\n }\n }\n // Callbacks started in this bucket, stacked by the queue they came from.\n let total = 0;\n for (const c of BAR_CLASSES) total += s.counts[b * classes + c.index] as number;\n if (total > 0) {\n const full = Math.max(2, barHeight(total, max) * barSpan);\n let y = barBottom;\n for (const c of BAR_CLASSES) {\n const n = s.counts[b * classes + c.index] as number;\n if (n === 0) continue;\n const h = (n / total) * full;\n ctx.fillStyle = color(c.color);\n ctx.fillRect(x, y - h, Math.max(1, bw - 0.5), h);\n y -= h;\n }\n } else if ((s.events[b] as number) > 0) {\n ctx.fillStyle = color('--line-strong');\n ctx.fillRect(x, barBottom - 1, Math.max(1, bw - 0.5), 1);\n }\n // Paused: hatched, so it reads without colour.\n if (s.paused[b]) {\n ctx.strokeStyle = pauseColor;\n ctx.lineWidth = 1;\n ctx.save();\n ctx.beginPath();\n ctx.rect(x, barTop, bw, barSpan);\n ctx.clip();\n ctx.beginPath();\n for (let k = -H; k < bw + H; k += 4) {\n ctx.moveTo(x + k, barBottom);\n ctx.lineTo(x + k + barSpan, barTop);\n }\n ctx.stroke();\n ctx.restore();\n }\n }\n\n // Markers along the bottom edge.\n const m = d.markers;\n if (m) {\n const xOfIndex = (index: number): number => (bucketForIndex(s, index) + 0.5) * bw;\n if (m.turnIndex.length > 0 && m.turnIndex.length <= w / 3) {\n ctx.fillStyle = color('--ink-3');\n for (let i = 0; i < m.turnIndex.length; i++) ctx.fillRect(Math.round(xOfIndex(m.turnIndex[i] as number)), H - 7, 1, 7);\n }\n const stdout = color('--ink');\n const stderr = color('--danger');\n let lastX = -10;\n for (let i = 0; i < m.outputIndex.length; i++) {\n const x = Math.round(xOfIndex(m.outputIndex[i] as number));\n if (x === lastX) continue;\n lastX = x;\n if (m.outputStream[i] === 1) {\n ctx.fillStyle = stderr;\n ctx.beginPath();\n ctx.moveTo(x - 2.5, H - 1);\n ctx.lineTo(x + 2.5, H - 1);\n ctx.lineTo(x, H - 6);\n ctx.fill();\n } else {\n ctx.fillStyle = stdout;\n ctx.fillRect(x - 1, H - 4, 3, 3);\n }\n }\n ctx.fillStyle = pauseColor;\n for (const pause of m.pauses) {\n const x0 = xOfIndex(pause.index);\n ctx.fillRect(Math.round(x0) - 1, barTop, 2, barSpan);\n }\n }\n}\n\nexport function Timeline() {\n const [wrap, size] = useElementSize<HTMLDivElement>();\n const canvas = useRef<HTMLCanvasElement>(null);\n const cursor = useRef<HTMLDivElement>(null);\n const future = useRef<HTMLDivElement>(null);\n const frame = useRef(0);\n const summary = player.timeline.value;\n const markers = player.markers.value;\n const state = player.player.value;\n const axis = settings.timelineAxis.value;\n const theme = settings.theme.value;\n const position = state?.position ?? 0;\n const length = state?.length ?? 0;\n\n useEffect(() => {\n if (size.width > 0) player.setTimeline(bucketsForWidth(size.width), axis);\n }, [size.width, axis]);\n\n useEffect(() => {\n cancelAnimationFrame(frame.current);\n frame.current = requestAnimationFrame(() => {\n if (canvas.current) draw(canvas.current, { summary, markers, width: size.width, height: size.height, theme });\n });\n return () => cancelAnimationFrame(frame.current);\n // A summary or marker list of the same version is the same picture, even when the\n // worker sent it again as a new object.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [summary?.version, summary?.width, summary?.axis, summary?.length, markers?.version, markers?.outputIndex.length, size.width, size.height, theme]);\n\n // The position: two transforms, set through the CSSOM.\n useLayoutEffect(() => {\n const x = summary && summary.length > 0 ? fractionOfPosition(summary, position) * size.width : 0;\n cursor.current?.style.setProperty('transform', `translateX(${Math.min(Math.max(0, size.width - 2), Math.max(0, Math.round(x) - 1))}px)`);\n future.current?.style.setProperty('transform', `translateX(${x}px)`);\n }, [summary, position, size.width]);\n\n // The system theme can change under a \"system\" setting.\n useEffect(() => {\n const query = matchMedia('(prefers-color-scheme: dark)');\n const redraw = (): void => {\n if (canvas.current) draw(canvas.current, { summary: player.timeline.peek(), markers: player.markers.peek(), width: canvas.current.clientWidth, height: canvas.current.clientHeight, theme: 'system' });\n };\n query.addEventListener('change', redraw);\n return () => query.removeEventListener('change', redraw);\n }, []);\n\n const seekAt = (clientX: number): void => {\n const el = wrap.current;\n if (!el || !summary || summary.length === 0) return;\n const rect = el.getBoundingClientRect();\n player.command({ do: 'pause' });\n player.command(seekForFraction(summary, (clientX - rect.left) / Math.max(1, rect.width)));\n };\n\n const pending = useRef<number | null>(null);\n const empty = length === 0;\n return (\n <div\n ref={wrap}\n class={`timeline${empty ? ' is-empty' : ''}`}\n role=\"slider\"\n tabIndex={0}\n aria-label=\"Position in the run\"\n aria-valuemin={0}\n aria-valuemax={length}\n aria-valuenow={position}\n aria-valuetext={empty ? 'No events' : `After event ${position} of ${length}, at ${formatMicros(state?.t ?? 0)}`}\n aria-disabled={empty ? 'true' : undefined}\n onPointerDown={(e) => {\n if (e.button !== 0 || empty) return;\n (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n seekAt(e.clientX);\n }}\n onPointerMove={(e) => {\n if (!(e.currentTarget as HTMLElement).hasPointerCapture(e.pointerId)) return;\n // At most one seek per frame while dragging.\n const x = e.clientX;\n if (pending.current !== null) cancelAnimationFrame(pending.current);\n pending.current = requestAnimationFrame(() => {\n pending.current = null;\n seekAt(x);\n });\n }}\n onKeyDown={(e) => {\n if (empty || e.ctrlKey || e.metaKey || e.altKey) return;\n const jump = Math.max(1, Math.round(length / 10));\n let handled = true;\n if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') step(e.shiftKey ? 'event' : 'step', -1);\n else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') step(e.shiftKey ? 'event' : 'step', 1);\n else if (e.key === 'PageDown') player.command({ do: 'seek', position: Math.max(0, position - jump) });\n else if (e.key === 'PageUp') player.command({ do: 'seek', position: Math.min(length, position + jump) });\n else if (e.key === 'Home') player.command({ do: 'seek', position: 0 });\n else if (e.key === 'End') player.command({ do: 'seek', position: length });\n else handled = false;\n if (handled) {\n e.preventDefault();\n e.stopPropagation();\n }\n }}\n >\n <canvas ref={canvas} class=\"timeline__canvas\" aria-hidden=\"true\" />\n <div ref={future} class=\"timeline__future\" hidden={empty} />\n <div ref={cursor} class=\"timeline__cursor\" hidden={empty} />\n {empty ? <span class=\"timeline__empty muted\">The run will appear here.</span> : null}\n </div>\n );\n}\n","/**\n * The transport bar: play and pause, speed, stepping back and forward by a chosen unit,\n * the scrubber, and the \"live\" switch that keeps the player at the end of a running run.\n *\n * Wide screens: one row, the scrubber between the buttons and the read-out.\n * Narrow screens: the scrubber on top and one compact row under it (step back, play,\n * step forward, position, and one button that opens the speed and stepping options).\n */\nimport { signal } from '@preact/signals';\nimport { useEffect, useRef, useState } from 'preact/hooks';\nimport { DEFAULT_STEPS_PER_SECOND } from '@nodejs-map/replay';\nimport type { StepKind } from '@nodejs-map/replay';\nimport { speedWords } from '../lib/autoReplay.ts';\nimport { formatMicros, formatMillis } from '../lib/format.ts';\nimport { Ctl } from '../shell/Ctl.tsx';\nimport { Icon } from '../shell/icons.tsx';\nimport { AreaClose } from '../shell/ViewMenu.tsx';\nimport { helperMode, player, session, settings, showActionOnMap, step, ui } from '../stores/index.ts';\nimport { SPEEDS } from '../stores/settings.ts';\nimport { Timeline } from './Timeline.tsx';\n\nconst STEP_UNITS: readonly { kind: StepKind; label: string; hint: string }[] = [\n { kind: 'step', label: 'Step', hint: 'One meaningful event; raw signals ride along' },\n { kind: 'event', label: 'Event', hint: 'One event of the list, raw signals included' },\n { kind: 'callback', label: 'Callback', hint: 'To the start of the next or previous callback' },\n { kind: 'phase', label: 'Phase', hint: 'To the next or previous loop phase' },\n { kind: 'turn', label: 'Loop turn', hint: 'To the next or previous loop turn' },\n { kind: 'output', label: 'Output', hint: 'To the next or previous write to stdout or stderr' },\n { kind: 'pause', label: 'Pause', hint: 'To the next or previous debugger pause or gate stop' },\n];\n\n/** The unit of the two step buttons. Not a setting: it resets with the page. */\nexport const stepUnit = signal<StepKind>('step');\n\nconst off = (reason: string) => ({ enabled: false, reason });\nconst on = { enabled: true, reason: null };\n\nexport function StepUnitSelect() {\n return (\n <select\n class=\"select\"\n aria-label=\"What the step buttons move by\"\n value={stepUnit.value}\n onChange={(e) => {\n stepUnit.value = (e.currentTarget as HTMLSelectElement).value as StepKind;\n }}\n >\n {STEP_UNITS.map((u) => (\n <option key={u.kind} value={u.kind} title={u.hint}>\n by {u.label.toLowerCase()}\n </option>\n ))}\n </select>\n );\n}\n\n/** \"1x is about five steps a second\": said in the title of the speed control and next to it when a replay starts. */\nexport const SPEED_HINT = `1× is about ${DEFAULT_STEPS_PER_SECOND === 5 ? 'five' : String(DEFAULT_STEPS_PER_SECOND)} steps a second`;\n\n/**\n * True for a few seconds after an automatic replay starts: the speed control is then\n * highlighted, because that is the moment a person wants it. A pulse where motion is\n * welcome, a steady outline where it is not (see styles/transport.css).\n */\nfunction useReplayFlash(): boolean {\n const starts = session.replayStarts.value;\n const [flash, setFlash] = useState(false);\n const seen = useRef(starts);\n useEffect(() => {\n if (starts === seen.current) return;\n seen.current = starts;\n setFlash(true);\n const timer = setTimeout(() => setFlash(false), 3500);\n return () => clearTimeout(timer);\n }, [starts]);\n return flash;\n}\n\nexport function SpeedSelect({ flash = false }: { flash?: boolean }) {\n return (\n <select\n class={`select transport__speed${flash ? ' is-flash' : ''}`}\n // The name stays short and stable (scripts and the map's own checks find the control\n // by it); the hint is its description, through the title.\n aria-label=\"Playback speed\"\n title={`Playback speed. ${SPEED_HINT}.`}\n value={String(settings.speed.value)}\n onChange={(e) => {\n const v = Number((e.currentTarget as HTMLSelectElement).value);\n if ((SPEEDS as readonly number[]).includes(v)) settings.speed.value = v;\n }}\n >\n {SPEEDS.map((s) => (\n <option key={s} value={String(s)}>\n {s}× ({speedWords(s, DEFAULT_STEPS_PER_SECOND)})\n </option>\n ))}\n </select>\n );\n}\n\nexport function Transport() {\n const state = player.player.value;\n const length = state?.length ?? 0;\n const position = state?.position ?? 0;\n const empty = length === 0;\n const nothing = off('There is no run or recording to play yet.');\n const atStart = position <= 0;\n const atEnd = position >= length;\n const unit = STEP_UNITS.find((u) => u.kind === stepUnit.value) ?? (STEP_UNITS[0] as (typeof STEP_UNITS)[number]);\n const live = state?.live ?? false;\n const dead = state?.deadTime ?? null;\n const narrow = ui.narrow.value;\n const flash = useReplayFlash();\n\n const back = (\n <Ctl label={`Back one ${unit.label.toLowerCase()}`} keys=\"←\" class=\"ctl--icon\" state={empty ? nothing : atStart ? off('Already at the start.') : on} onAct={() => step(unit.kind, -1)}>\n <Icon name=\"stepBack\" />\n </Ctl>\n );\n const play = (\n <Ctl\n label={state?.playing ? 'Pause playback' : 'Play'}\n keys=\"Space\"\n kind=\"primary\"\n class=\"ctl--icon transport__play\"\n state={empty ? nothing : on}\n onAct={() => {\n // Play from the end starts over, as people expect from a player.\n if (!state?.playing && atEnd && !live) player.command({ do: 'seek', position: 0 });\n player.command({ do: 'toggle' });\n }}\n >\n <Icon name={state?.playing ? 'pause' : 'play'} />\n </Ctl>\n );\n const forward = (\n <Ctl label={`Forward one ${unit.label.toLowerCase()}`} keys=\"→\" class=\"ctl--icon\" state={empty ? nothing : atEnd ? off('Already at the end.') : on} onAct={() => step(unit.kind, 1)}>\n <Icon name=\"stepForward\" />\n </Ctl>\n );\n\n // The map stays still unless the user asks: a toggle (off by default, its state in\n // words), and next to it a button that flies there once.\n const moveMap = settings.moveMap.value;\n const follow = (\n <>\n <Ctl\n label={`Move map with the run: ${moveMap ? 'on' : 'off'}`}\n keys=\"F\"\n pressed={moveMap}\n class=\"transport__follow\"\n onAct={() => {\n settings.moveMap.value = !moveMap;\n }}\n >\n <Icon name=\"follow\" />\n <span class=\"transport__follow-word\">Move map with the run</span>\n <span class=\"transport__follow-state\">{moveMap ? 'On' : 'Off'}</span>\n </Ctl>\n <Ctl label=\"Show on map: fly once to where the run is now\" keys=\"M\" class=\"transport__show\" state={empty ? nothing : on} onAct={() => showActionOnMap()}>\n <Icon name=\"map\" />\n <span class=\"transport__follow-word\">Show on map</span>\n </Ctl>\n </>\n );\n\n if (narrow) {\n return (\n <footer class=\"transport\" aria-label=\"Playback\">\n <Timeline />\n <div class=\"toolbar transport__buttons\" role=\"toolbar\" aria-label=\"Playback controls\">\n {back}\n {play}\n {forward}\n <span class=\"transport__pos num\" aria-hidden=\"true\">\n {empty ? '-' : `${position} / ${length}`}\n </span>\n {follow}\n <button type=\"button\" class={`ctl ctl--plain transport__menu${flash ? ' is-flash' : ''}`} title={`Speed and stepping. ${SPEED_HINT}.`} aria-haspopup=\"dialog\" aria-label={`Playback options: speed ${settings.speed.value}×, stepping by ${unit.label.toLowerCase()}`} onClick={() => (ui.dialog.value = 'playback')}>\n {settings.speed.value}× · {unit.label.toLowerCase()}\n </button>\n <AreaClose area=\"playback\" />\n </div>\n </footer>\n );\n }\n\n return (\n <footer class=\"transport\" aria-label=\"Playback\">\n <div class=\"toolbar transport__buttons\" role=\"toolbar\" aria-label=\"Playback controls\">\n <Ctl label=\"Go to the start\" keys=\"Home\" class=\"ctl--icon\" state={empty ? nothing : atStart ? off('Already at the start.') : on} onAct={() => player.command({ do: 'seek', position: 0 })}>\n <Icon name=\"toStart\" />\n </Ctl>\n {back}\n {play}\n {forward}\n <Ctl label=\"Go to the end\" keys=\"End\" class=\"ctl--icon\" state={empty ? nothing : atEnd ? off('Already at the end.') : on} onAct={() => player.command({ do: 'seek', position: length })}>\n <Icon name=\"toEnd\" />\n </Ctl>\n <span title={unit.hint}>\n <StepUnitSelect />\n </span>\n <SpeedSelect flash={flash} />\n {flash ? (\n <span class=\"transport__speedhint\" role=\"note\">\n Replaying. Speed: {SPEED_HINT}.\n </span>\n ) : null}\n </div>\n\n <Timeline />\n\n <div class=\"transport__status\">\n {/* Also here, where the eye is while it plays (and the top bar's badge is hidden in a small window). */}\n {session.replaying.value ? (\n <span class=\"badge badge--replay\" title=\"The program itself is over. This plays back what was recorded, from the start.\">\n Replay\n </span>\n ) : null}\n <span class=\"transport__pos num\" aria-hidden=\"true\">\n {empty ? '-' : `${position} / ${length}`}\n <span class=\"muted\"> · {empty ? '' : formatMicros(state?.t ?? 0)}</span>\n </span>\n {dead ? (\n <span class=\"transport__dead muted\" role=\"status\">\n {dead.during === 'nothing' ? `Skipping ${formatMillis(dead.ms)} in which the loop only waited` : `Skipping ${formatMillis(dead.ms)} in which JavaScript ran without events`}\n </span>\n ) : null}\n {follow}\n <button\n type=\"button\"\n class=\"ctl ctl--plain\"\n aria-pressed={settings.timelineAxis.value === 'time' ? 'true' : 'false'}\n title=\"Draw the strip by time instead of by event count. By time, long waits take room and bursts are narrow.\"\n onClick={() => {\n settings.timelineAxis.value = settings.timelineAxis.value === 'time' ? 'index' : 'time';\n }}\n >\n {settings.timelineAxis.value === 'time' ? 'By time' : 'By events'}\n </button>\n {/* The player site has no live runs: there the control could never be anything but off. */}\n {helperMode.value ? (\n <Ctl\n label=\"Follow the live run\"\n keys=\"L\"\n pressed={Boolean(state?.follow && live)}\n state={live ? on : off('Only while a run is in progress. A recording or a finished run has no live end to follow.')}\n onAct={() => player.command({ do: 'follow', on: !(state?.follow ?? false) })}\n >\n <span class={`live-dot${state?.following ? ' is-on' : ''}`} aria-hidden=\"true\" />\n Live\n </Ctl>\n ) : null}\n <AreaClose area=\"playback\" />\n </div>\n </footer>\n );\n}\n","/**\n * Banners: the few things that must not be missed. Kept short and stacked under the top\n * bar: a lost helper, a map built for another Node.js version, problems opening or\n * running something, and - whenever JavaScript is paused on an official build - the\n * reminder that real time kept running.\n */\nimport type { ComponentChildren } from 'preact';\nimport { PHASE_LABEL, formatMillis, oneLine } from '../lib/format.ts';\nimport { lessonsOf } from '../lib/learn.ts';\nimport { routeHash } from '../lib/route.ts';\nimport { atlas, bootError, connection, hasRun, learn, player, session } from '../stores/index.ts';\nimport { Ctl } from './Ctl.tsx';\nimport { Icon } from './icons.tsx';\n\nfunction Banner({ kind, children, onDismiss, role = 'status' }: { kind: 'info' | 'warn' | 'error'; children: ComponentChildren; onDismiss?: () => void; role?: 'status' | 'alert' }) {\n return (\n <div class={`banner banner--${kind}`} role={role}>\n <div class=\"banner__text\">{children}</div>\n {onDismiss ? (\n <button type=\"button\" class=\"ctl ctl--plain ctl--icon\" aria-label=\"Dismiss this message\" onClick={onDismiss}>\n <Icon name=\"close\" />\n </button>\n ) : null}\n </div>\n );\n}\n\nfunction PausedBanner() {\n const debug = player.parts.debug.value;\n if (!debug) return null;\n // A debugger pause itself is shown where the code is: the strip over the editor says\n // where and why, and that real time keeps running (editor/EditorPane.tsx).\n if (debug.paused) return null;\n if (debug.gate.stopped) return <GateBanner />;\n const last = debug.lastPause;\n if (last && last.timeKeptRunning && debug.pauses > 0) {\n return (\n <Banner kind=\"info\">\n This run was paused {debug.pauses} time{debug.pauses === 1 ? '' : 's'} before this point (last for {formatMillis(last.pausedMs)}). Real time kept running during the pauses, so the order of\n what follows may differ from a run without pauses.\n </Banner>\n );\n }\n return null;\n}\n\nconst GATE_WORDS: Readonly<Record<string, string>> = {\n phase: 'before a loop phase',\n turn: 'at the start of a loop turn',\n timer: \"before Node's timer callback\",\n poolStart: 'a pool thread holds a job it has not started',\n poolPost: 'a pool thread holds a finished job it has not posted',\n poolDone: 'the loop holds a result before its done-callback',\n manual: 'stopped on request',\n};\n\n/** The target is stopped at a gate (probe build): what is held, what is not, and the two ways on. */\nfunction GateBanner() {\n const debug = player.parts.debug.value;\n if (!debug) return null;\n const gate = debug.gate;\n const controls = session.controls.value;\n // The actions belong to a program that is stopped right now, not to a recording of one.\n const canAct = session.liveStatus.value === 'gated' && player.parts.live.value && player.parts.position.peek() === player.parts.length.peek();\n const where = [gate.phase ? `${PHASE_LABEL[gate.phase]} phase` : null, gate.job ? `job ${oneLine(gate.job, 24)}` : null].filter(Boolean).join(', ');\n return (\n <Banner kind=\"warn\">\n <div class=\"gatebanner\">\n <div>\n <strong>\n Stopped at the {gate.gate ?? '?'} gate{gate.gate && GATE_WORDS[gate.gate] ? `: ${GATE_WORDS[gate.gate]}` : ''}\n {where ? ` (${where})` : ''}.\n </strong>{' '}\n {debug.clock.frozen ? 'The loop clock is frozen and the pool threads are held, so timers do not come due and no new pool work starts.' : 'The program is held inside Node.js, between JavaScript callbacks.'}{' '}\n Not held: work already running on a pool thread, Date.now(), the operating system and network peers.\n </div>\n {canAct ? (\n <div class=\"gatebanner__acts\">\n <Ctl label=\"Step one phase\" kind=\"primary\" state={controls.stepPhase} onAct={() => void session.gate({ kind: 'stepPhase' })} />\n <Ctl label=\"Resume from the gate\" state={controls.gateResume} onAct={() => void session.gate({ kind: 'resume' })}>\n Resume\n </Ctl>\n </div>\n ) : null}\n </div>\n </Banner>\n );\n}\n\nfunction VersionNotice() {\n const welcome = connection.welcome.value;\n const chosen = session.provider.value;\n if (!welcome || welcome.atlas.matchesNode) return null;\n return (\n <Banner kind=\"warn\">\n <strong>The map is for another Node.js version.</strong> It was built for {welcome.atlas.tag}\n {chosen ? `; your Node.js is ${chosen.node.version}` : ''}. Boxes and line numbers may be slightly off for your version. Links still open the code of {welcome.atlas.tag}.\n </Banner>\n );\n}\n\n/**\n * The main view's links to the Learn page: \"Back to the lesson\" after a lesson sent the\n * reader here, and on a first visit (nothing run, nothing open) the way to the first lesson.\n */\nfunction LearnLinks() {\n const back = learn.returnTo.value;\n const index = learn.index.value;\n if (learn.route.value.view !== 'main') return null;\n if (back) {\n const title = index.status === 'ready' ? lessonsOf(index.index).find((l) => l.id === back.lesson)?.title : undefined;\n return (\n <Banner kind=\"info\">\n <div class=\"learnlinks\">\n <button type=\"button\" class=\"ctl ctl--primary learn-back\" onClick={() => learn.go({ view: 'learn', lesson: back.lesson })}>\n Back to the lesson\n </button>\n {title ? <span class=\"muted ellipsis\">{title}</span> : null}\n </div>\n </Banner>\n );\n }\n const first = learn.first.value;\n if (!first || learn.introDismissed.value || hasRun.value || session.opening.value || session.kind.value === 'recording') return null;\n return (\n <Banner kind=\"info\" onDismiss={() => learn.dismissIntro()}>\n New here?{' '}\n <a class=\"learn-intro\" href={routeHash({ view: 'learn', lesson: first.id })} onClick={() => learn.dismissIntro()}>\n Start the course: what nodejs-map is and how to read it\n </a>\n </Banner>\n );\n}\n\nexport function Banners() {\n const boot = bootError.value;\n const status = connection.status.value;\n const connError = connection.error.value;\n const notices = connection.notices.value;\n const sessionError = session.error.value;\n const problem = player.problem.value;\n const atlasState = atlas.state.value;\n const recording = session.recording.value;\n return (\n <div class=\"banners\">\n {boot ? (\n <Banner kind=\"error\" role=\"alert\">\n {boot}\n </Banner>\n ) : null}\n {status === 'connecting' ? <Banner kind=\"info\">Connecting to the helper...</Banner> : null}\n {(status === 'closed' || status === 'failed') && connError ? (\n <Banner kind=\"error\" role=\"alert\">\n {connError} Recordings can still be opened and played.\n </Banner>\n ) : null}\n <VersionNotice />\n {recording && atlasState.status === 'missing' ? (\n <Banner kind=\"warn\">\n This recording was made on Node.js {recording.header.node.version}. The map for {atlasState.tag} is not available here, so the map stays empty; the panels show the recording in full.\n </Banner>\n ) : null}\n {session.opening.value ? <Banner kind=\"info\">Opening the recording. Nothing is being run.</Banner> : null}\n {session.notice.value ? (\n <Banner kind=\"info\" onDismiss={() => session.clearNotice()}>\n {session.notice.value}\n </Banner>\n ) : null}\n {sessionError ? (\n <Banner kind=\"error\" role=\"alert\" onDismiss={() => session.clearError()}>\n {sessionError}\n </Banner>\n ) : null}\n {problem ? <Banner kind=\"warn\">{problem}</Banner> : null}\n {notices.map((notice) => (\n <Banner key={notice.id} kind={notice.level} onDismiss={() => connection.dismiss(notice.id)}>\n {notice.text}\n </Banner>\n ))}\n <PausedBanner />\n <LearnLinks />\n </div>\n );\n}\n","/**\n * The honesty mark. One glyph per certainty, the same everywhere:\n *\n * observed solid ring with a filled centre\n * inferred dashed ring, open\n * model dotted ring, open\n *\n * The mark is a button: it opens the \"how we know\" dialog with the rule and the Node\n * source the rule cites. Inside long lists it is taken out of the tab order (the list\n * offers a key for it); elsewhere it is a normal tab stop.\n */\nimport type { Certainty } from '@nodejs-map/event-format';\nimport type { Fact } from '@nodejs-map/replay';\nimport { CERTAINTY_LABEL } from '../lib/certainty.ts';\nimport { openMark } from '../stores/index.ts';\n\nconst DASH: Readonly<Record<Certainty, string | undefined>> = {\n observed: undefined,\n // Circumference of r=5 is 31.4: four dashes, or ten dots (zero-length dashes with round caps).\n inferred: '4.6 3.25',\n model: '0.01 3.13',\n};\n\nexport function MarkGlyph({ c }: { c: Certainty }) {\n return (\n <svg class={`mark-glyph mark-glyph--${c}`} viewBox=\"0 0 14 14\" width=\"14\" height=\"14\" aria-hidden=\"true\" focusable=\"false\">\n <circle cx=\"7\" cy=\"7\" r=\"5\" fill=\"none\" stroke=\"currentColor\" stroke-width={c === 'model' ? 2 : 1.75} stroke-dasharray={DASH[c]} stroke-linecap={c === 'model' ? 'round' : 'butt'} />\n {c === 'observed' ? <circle cx=\"7\" cy=\"7\" r=\"2.4\" fill=\"currentColor\" /> : null}\n </svg>\n );\n}\n\nexport interface MarkProps {\n c: Certainty;\n /** Rule id from the event, if it named one. */\n rule?: string | null;\n /** Index of the event the fact comes from. */\n index?: number | null;\n /** What the fact is, in a few words, for the label and the dialog title. */\n subject: string;\n /** False inside lists that manage their own keyboard navigation. */\n tabbable?: boolean;\n}\n\nexport function Mark({ c, rule = null, index = null, subject, tabbable = true }: MarkProps) {\n return (\n <button\n type=\"button\"\n class={`mark mark--${c}`}\n aria-label={`${CERTAINTY_LABEL[c]}. How we know: ${subject}`}\n title={`${CERTAINTY_LABEL[c]} - how we know`}\n tabIndex={tabbable ? 0 : -1}\n data-certainty={c}\n onClick={(e) => {\n e.stopPropagation();\n openMark({ certainty: c, ruleId: rule, index, subject });\n }}\n >\n <MarkGlyph c={c} />\n </button>\n );\n}\n\n/** The mark of a replay Fact. Renders nothing when there is no fact to mark. */\nexport function FactMark({ fact, subject, tabbable }: { fact: Fact | null | undefined; subject: string; tabbable?: boolean }) {\n if (!fact) return null;\n return <Mark c={fact.c} rule={fact.rule} index={fact.index} subject={subject} {...(tabbable === undefined ? {} : { tabbable })} />;\n}\n","/**\n * The top bar: what is on screen (program or recording), which Node runs it, recordings\n * (open, save, share), the certainty legend, the theme and help.\n */\nimport { CERTAINTIES, CERTAINTY_LABEL } from '../lib/certainty.ts';\nimport { connection, hasRun, helperMode, learn, openRecordingFile, session, settings, shown, toggleTheme, ui } from '../stores/index.ts';\nimport { Ctl } from './Ctl.tsx';\nimport { Icon } from './icons.tsx';\nimport { MarkGlyph } from './Mark.tsx';\nimport { ViewMenu } from './ViewMenu.tsx';\n\nexport function ProviderSelect() {\n const providers = connection.providers.value;\n const chosen = session.provider.value;\n if (providers.length === 0) return null;\n const busy = session.liveStatus.value !== 'idle';\n return (\n <label class=\"field field--inline topbar__provider\" title={busy ? 'Applies to the next run' : 'The Node.js binary that runs your program'}>\n <span class=\"field__label\">Node</span>\n <select\n class=\"select\"\n value={chosen?.id ?? ''}\n onChange={(e) => {\n const id = (e.currentTarget as HTMLSelectElement).value;\n if (id === 'user' || id === 'pinned' || id === 'probe') settings.provider.value = id;\n }}\n >\n {providers.map((p) => (\n <option key={p.id} value={p.id} disabled={!p.available}>\n {p.title}\n {p.available ? '' : ` - not available${p.why ? `: ${p.why}` : ''}`}\n </option>\n ))}\n </select>\n </label>\n );\n}\n\n/** What is on screen. `compact` (narrow screens): the badge and the title only, on one line. */\nfunction What({ compact = false }: { compact?: boolean }) {\n const kind = session.kind.value;\n const recording = session.recording.value;\n const helper = helperMode.value;\n if (kind === 'recording' && recording) {\n return (\n <div class=\"topbar__what\">\n <span class=\"badge badge--recording\" title=\"A recording is played back from its event list. Nothing is run.\">\n Recording\n </span>\n <span class=\"topbar__name ellipsis\" title={recording.label}>\n {recording.lesson?.title ?? recording.header.title ?? recording.label}\n </span>\n {compact ? null : (\n <>\n <span class=\"muted topbar__detail ellipsis\">\n Node {recording.header.node.version} · {recording.events} events{recording.origin === 'link' ? ' · from a link' : recording.origin === 'lesson' ? ' · lesson' : ''}\n </span>\n <button type=\"button\" class=\"ctl ctl--plain\" onClick={() => session.closeRecording()}>\n {helper ? 'Close and return to the editor' : 'Close'}\n </button>\n </>\n )}\n </div>\n );\n }\n if (!helper) {\n return (\n <div class=\"topbar__what topbar__what--plain\">\n <span class=\"muted\">Player: opens recordings and lessons. It cannot run code.</span>\n </div>\n );\n }\n const status = session.liveStatus.value;\n const ended = kind === 'live' && status === 'idle' && hasRun.value;\n // The finished run is being played back by itself: said in the badge, so that nobody\n // takes the replay for a program that is still running. A phone's one-row bar has room\n // for one word; the whole sentence is then the badge's title (and was announced).\n const replaying = ended && session.replaying.value;\n const REPLAYING = 'Finished - replaying from the start';\n return (\n <div class=\"topbar__what\">\n {/* On a wide screen the program picker is in the header of the code panel, next to Run. */}\n {!ui.narrow.value ? null : <button type=\"button\" class=\"ctl ctl--plain topbar__program\" aria-haspopup=\"dialog\" title=\"Choose what to run: the snippet, an example or a file\" onClick={() => (ui.dialog.value = 'program')}>\n <Icon name=\"code\" />\n <span class=\"ellipsis\">{shown.value.name}</span>\n <Icon name=\"chevronDown\" />\n </button>}\n {kind === 'live' ? (\n <span class={`badge badge--${replaying ? 'replay' : status === 'idle' ? 'ended' : 'live'}`} title={replaying ? `${REPLAYING}. The program itself is over; this plays back what was recorded.` : undefined}>\n {status === 'starting' ? 'Starting' : status === 'running' ? 'Live run' : status === 'paused' ? 'Live run, paused' : status === 'gated' ? 'Live run, at a gate' : replaying ? (ui.narrow.value ? 'Replaying' : REPLAYING) : ended ? 'Finished run' : 'Run'}\n </span>\n ) : null}\n </div>\n );\n}\n\nfunction Legend() {\n return (\n <button type=\"button\" class=\"ctl ctl--plain topbar__legend\" aria-haspopup=\"dialog\" title=\"What the three marks mean (I)\" onClick={() => (ui.dialog.value = 'legend')}>\n {CERTAINTIES.map((c) => (\n <span key={c} class={`legend-item mark--${c}`}>\n <MarkGlyph c={c} />\n <span class=\"legend-item__word\">{CERTAINTY_LABEL[c]}</span>\n </span>\n ))}\n </button>\n );\n}\n\n/** Open, Save and Share. In the top bar on a wide screen; in the \"More\" dialog on a narrow one. */\nexport function RecordingActions({ words = false }: { words?: boolean }) {\n const fileInput = (e: Event): void => {\n const input = e.currentTarget as HTMLInputElement;\n const file = input.files?.[0];\n input.value = '';\n if (!file) return;\n if (ui.dialog.value === 'more') ui.dialog.value = null;\n void openRecordingFile(file);\n };\n const nothing = { enabled: false, reason: 'There is no run or recording yet.' };\n const can = hasRun.value ? { enabled: true, reason: null } : nothing;\n const word = words ? 'topbar__word topbar__word--always' : 'topbar__word';\n return (\n <div class=\"toolbar\" role=\"toolbar\" aria-label=\"Recordings\">\n <label class=\"ctl ctl--plain ctl--file\" title=\"Open a recording file. It is played back; nothing is run.\">\n <Icon name=\"open\" />\n <span class={word}>Open</span>\n <input type=\"file\" class=\"sr-only\" accept=\".nodejs-map,.gz,.ndjson,.txt,application/gzip,text/plain\" aria-label=\"Open a recording file\" onChange={fileInput} />\n </label>\n <Ctl label=\"Save as a recording file\" state={can} onAct={() => (ui.dialog.value = 'save')}>\n <Icon name=\"save\" />\n <span class={word}>Save</span>\n </Ctl>\n <Ctl label=\"Share as a link\" state={can} onAct={() => (ui.dialog.value = 'share')}>\n <Icon name=\"share\" />\n <span class={word}>Share</span>\n </Ctl>\n </div>\n );\n}\n\n/** The two views: the map with the code and panels, and the Learn page. Plain links: the address is the route. */\nfunction Views() {\n const learning = learn.route.value.view === 'learn';\n return (\n <nav class=\"topbar__views\" aria-label=\"Views\">\n <a class=\"ctl ctl--plain topbar__viewlink\" href=\"#/\" aria-current={learning ? undefined : 'page'}>\n Map\n </a>\n <a class=\"ctl ctl--plain topbar__viewlink topbar__learn\" href=\"#/learn\" aria-current={learning ? 'page' : undefined}>\n Learn\n </a>\n </nav>\n );\n}\n\nexport function TopBar() {\n const helper = helperMode.value;\n if (ui.narrow.value) {\n // A phone has no room for a row of buttons: the legend stays, the rest is one tap away.\n return (\n <header class=\"topbar\">\n <h1 class=\"topbar__brand\">nodejs-map</h1>\n <Views />\n <ViewMenu />\n <What compact />\n <button type=\"button\" class=\"ctl ctl--plain topbar__more\" aria-haspopup=\"dialog\" aria-label=\"More: open, save, share, legend, theme, help\" onClick={() => (ui.dialog.value = 'more')}>\n More\n </button>\n </header>\n );\n }\n return (\n <header class=\"topbar\">\n <h1 class=\"topbar__brand\">nodejs-map</h1>\n <Views />\n <ViewMenu />\n <What />\n <div class=\"topbar__right\">\n {helper ? <ProviderSelect /> : null}\n <RecordingActions />\n <Legend />\n <button type=\"button\" class=\"ctl ctl--plain ctl--icon\" aria-label=\"Switch between light and dark\" title=\"Light or dark (Shift+D)\" onClick={toggleTheme}>\n <Icon name=\"theme\" />\n </button>\n <button type=\"button\" class=\"ctl ctl--plain ctl--icon\" aria-label=\"Keyboard shortcuts and help\" aria-haspopup=\"dialog\" title=\"Keyboard shortcuts (?)\" onClick={() => (ui.dialog.value = 'help')}>\n <Icon name=\"help\" />\n </button>\n </div>\n </header>\n );\n}\n","/**\n * A modal dialog on the native <dialog> element: the browser traps focus and closes on\n * Escape. Focus goes back to the control that opened the dialog when it closes.\n */\nimport type { ComponentChildren } from 'preact';\nimport { useEffect, useId, useRef } from 'preact/hooks';\nimport { Icon } from './icons.tsx';\n\nexport interface DialogProps {\n title: string;\n onClose(): void;\n children: ComponentChildren;\n /** Wider layout for dialogs with lists or source links. */\n wide?: boolean;\n}\n\nexport function Dialog({ title, onClose, children, wide }: DialogProps) {\n const ref = useRef<HTMLDialogElement>(null);\n const titleId = useId();\n /**\n * False once this dialog is on its way out. The element's `close` event is delivered\n * later, as its own task; by then another dialog may be open, and a late call of\n * onClose would close that one.\n */\n const alive = useRef(true);\n const requestClose = (): void => {\n if (alive.current) onClose();\n };\n\n useEffect(() => {\n const dialog = ref.current;\n if (!dialog) return;\n const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n if (!dialog.open) dialog.showModal();\n return () => {\n alive.current = false;\n if (dialog.open) dialog.close();\n // The element is removed in the same step, so the browser's own \"return focus to\n // the opener\" may not happen; do it by hand.\n if (opener?.isConnected && (document.activeElement === document.body || document.activeElement === null || dialog.contains(document.activeElement))) opener.focus();\n };\n }, []);\n\n return (\n <dialog\n ref={ref}\n class={`dialog${wide ? ' dialog--wide' : ''}`}\n aria-labelledby={titleId}\n onClose={requestClose}\n onCancel={(e) => {\n // Let our state drive the closing so Escape and the close button take one path.\n e.preventDefault();\n requestClose();\n }}\n onClick={(e) => {\n if (e.target === ref.current) requestClose(); // a click on the backdrop\n }}\n >\n <header class=\"dialog__head\">\n <h2 id={titleId} class=\"dialog__title\">\n {title}\n </h2>\n <button type=\"button\" class=\"ctl ctl--plain ctl--icon\" aria-label=\"Close\" onClick={requestClose}>\n <Icon name=\"close\" />\n </button>\n </header>\n <div class=\"dialog__body\">{children}</div>\n </dialog>\n );\n}\n","/**\n * The dialogs: the certainty legend, the rule behind a mark, keyboard help, the program\n * picker, and save / share for recordings. One is open at a time (stores/ui.ts).\n */\nimport { useEffect, useState } from 'preact/hooks';\nimport type { Rule } from '@nodejs-map/event-format';\nimport type { FileEntry } from '@nodejs-map/protocol';\nimport { SHARE_LINK_SAFE_CHARS } from '@nodejs-map/replay';\nimport type { ShareResult } from '@nodejs-map/replay';\nimport { CERTAINTIES, CERTAINTY_LABEL, CERTAINTY_MEANING, RULE_PLATFORM_LABEL, findRule } from '../lib/certainty.ts';\nimport { SHORTCUTS, comboKeys } from '../lib/shortcuts.ts';\nimport type { Shortcut, ShortcutGroup } from '../lib/shortcuts.ts';\nimport { targetForAtlasId } from '../lib/sourceTarget.ts';\nimport type { SourceTarget } from '../lib/sourceTarget.ts';\nimport {\n atlas,\n connection,\n downloadBytes,\n helperMode,\n jumpToEvent,\n openRecordingFile,\n openSource,\n platform,\n player,\n program,\n session,\n settings,\n shareBaseUrl,\n showOnMap,\n showTab,\n toggleTheme,\n ui,\n} from '../stores/index.ts';\nimport { SPEED_HINT, SpeedSelect, StepUnitSelect } from '../transport/Transport.tsx';\nimport { ProviderSelect, RecordingActions } from './TopBar.tsx';\nimport { Dialog } from './Dialog.tsx';\nimport { LIST_KEYS } from './hooks.ts';\nimport { Icon } from './icons.tsx';\nimport { MarkGlyph } from './Mark.tsx';\n\nconst close = (): void => {\n ui.dialog.value = null;\n};\n\n// ---- legend --------------------------------------------------------------------------\n\nfunction LegendDialog() {\n return (\n <Dialog title=\"How sure is each thing on screen?\" onClose={close}>\n <p class=\"dialog__lead\">\n Everything nodejs-map shows about your program carries one of three marks. The shape of the mark tells them apart; the colour only repeats it.\n </p>\n <ul class=\"legend\">\n {CERTAINTIES.map((c) => (\n <li key={c} class={`legend__row edge edge--${c}`}>\n <span class={`mark-inline mark--${c}`}>\n <MarkGlyph c={c} />\n </span>\n <div>\n <strong>{CERTAINTY_LABEL[c]}</strong>\n <span class=\"muted\"> · {c === 'observed' ? 'solid' : c === 'inferred' ? 'dashed' : 'dotted'} line</span>\n <p>{CERTAINTY_MEANING[c]}</p>\n </div>\n </li>\n ))}\n </ul>\n <p>\n The same three line styles mark the left edge of rows, the lit segment of the phase ring, the phase band of the timeline and the highlights on the map. Select any mark to read how that\n fact is known: for an inferred or model fact, the rule that produced it and the Node.js source the rule relies on.\n </p>\n </Dialog>\n );\n}\n\n// ---- the rule behind a mark -------------------------------------------------------------\n\nfunction Citation({ id }: { id: string }) {\n const state = atlas.state.value;\n const os = platform.value;\n const [target, setTarget] = useState<SourceTarget | null>(null);\n useEffect(() => {\n let live = true;\n setTarget(null);\n if (state.status !== 'ready') return;\n void targetForAtlasId(state.store, os, id).then((t) => {\n if (live) setTarget(t);\n });\n return () => {\n live = false;\n };\n }, [id, state, os]);\n\n const lines = target && target.start !== null && target.end !== null ? `#L${target.start}-L${target.end}` : '';\n return (\n <li class=\"cite\">\n <div class=\"cite__main\">\n <span class=\"cite__title\">{target ? target.title : id}</span>\n {target?.path ? (\n <span class=\"cite__path mono muted\">\n {target.path}\n {lines}\n </span>\n ) : (\n <span class=\"cite__path mono muted\">{state.status === 'ready' ? (target ? (target.note ?? id) : 'Looking it up...') : id}</span>\n )}\n </div>\n <div class=\"cite__acts\">\n {target?.github ? (\n <a class=\"ctl ctl--plain\" href={target.github} target=\"_blank\" rel=\"noreferrer noopener\">\n <Icon name=\"external\" />\n <span>GitHub</span>\n </a>\n ) : null}\n <button\n type=\"button\"\n class=\"ctl ctl--plain\"\n onClick={() => {\n ui.mark.value = null;\n openSource(id);\n }}\n >\n Read here\n </button>\n <button\n type=\"button\"\n class=\"ctl ctl--plain ctl--icon\"\n aria-label={`Show ${target?.title ?? id} on the map`}\n title=\"Show on the map\"\n onClick={() => {\n ui.mark.value = null;\n showOnMap(id);\n }}\n >\n <Icon name=\"map\" />\n </button>\n </div>\n </li>\n );\n}\n\nfunction RuleBody({ rule }: { rule: Rule }) {\n const state = atlas.state.value;\n return (\n <section class=\"rule\" aria-label={`Rule ${rule.id}`}>\n <h3 class=\"rule__title\">\n <span class=\"rule__id mono\">{rule.id}</span> {rule.title}\n </h3>\n <p class=\"rule__statement\">{rule.statement}</p>\n <dl class=\"facts\">\n <div>\n <dt>Produces</dt>\n <dd>\n <span class={`mark-inline mark--${rule.yields}`}>\n <MarkGlyph c={rule.yields} />\n </span>{' '}\n {CERTAINTY_LABEL[rule.yields].toLowerCase()} facts\n </dd>\n </div>\n <div>\n <dt>Holds on</dt>\n <dd>{RULE_PLATFORM_LABEL[rule.platform]}</dd>\n </div>\n </dl>\n <h4 class=\"label\">Node.js source this rule relies on</h4>\n {state.status !== 'ready' ? (\n <p class=\"callout callout--info\">The map data is not loaded, so the citations below are shown by their ids and cannot be turned into links to files.</p>\n ) : null}\n <ul class=\"cites\">\n {rule.cites.map((id) => (\n <Citation key={id} id={id} />\n ))}\n </ul>\n </section>\n );\n}\n\nfunction MarkDialog() {\n const target = ui.mark.value;\n if (!target) return null;\n const rule = findRule(target.ruleId);\n const done = (): void => {\n ui.mark.value = null;\n };\n return (\n <Dialog title=\"How we know\" onClose={done} wide>\n <p class=\"markdlg__subject\">{target.subject}</p>\n <p class={`markdlg__certainty edge edge--${target.certainty}`}>\n <span class={`mark-inline mark--${target.certainty}`}>\n <MarkGlyph c={target.certainty} />\n </span>\n <span>\n <strong>{CERTAINTY_LABEL[target.certainty]}.</strong> {CERTAINTY_MEANING[target.certainty]}\n </span>\n </p>\n {rule ? (\n <RuleBody rule={rule} />\n ) : target.ruleId ? (\n <p class=\"callout callout--warn\">\n The event names rule <span class=\"mono\">{target.ruleId}</span>, which this version of nodejs-map does not know. The recording may come from a newer version.\n </p>\n ) : target.certainty === 'observed' ? (\n <p>No rule was needed: the fact is shown as Node.js reported it.</p>\n ) : (\n <p class=\"callout callout--warn\">This fact is not observed, yet its event names no rule. That is a defect in what produced the event; treat the fact with care.</p>\n )}\n {target.index !== null ? (\n <p class=\"dialog__acts\">\n <button\n type=\"button\"\n class=\"ctl ctl--plain\"\n onClick={() => {\n const index = target.index;\n done();\n if (index !== null) {\n jumpToEvent(index);\n showTab('events');\n }\n }}\n >\n <Icon name=\"jump\" />\n <span>Go to event {target.index + 1}</span>\n </button>\n </p>\n ) : null}\n </Dialog>\n );\n}\n\n// ---- help -------------------------------------------------------------------------------\n\nconst GROUPS: readonly ShortcutGroup[] = ['Playback', 'Stepping through the recording', 'Running and debugging', 'View'];\nconst HIDDEN_IN_HELP = new Set(['view.tab2', 'view.tab3', 'view.tab4', 'view.tab5', 'view.tab6', 'view.tab7', 'view.tab8']);\n\nfunction Keys({ keys }: { keys: readonly string[] }) {\n return (\n <span class=\"keys\">\n {keys.map((key, i) => (\n <kbd key={i}>{key}</kbd>\n ))}\n </span>\n );\n}\n\nfunction ShortcutRow({ shortcut, mac }: { shortcut: Shortcut; mac: boolean }) {\n const tabs = shortcut.id === 'view.tab1';\n return (\n <tr>\n <th scope=\"row\">{shortcut.label}</th>\n <td>\n {tabs ? (\n <Keys keys={['1', '…', '8']} />\n ) : (\n shortcut.combos.map((combo, i) => (\n <span key={i}>\n {i > 0 ? <span class=\"muted\"> or </span> : null}\n <Keys keys={comboKeys(combo, mac)} />\n </span>\n ))\n )}\n </td>\n </tr>\n );\n}\n\nfunction HelpDialog() {\n const helper = helperMode.value;\n const mac = /Mac|iPhone|iPad/.test(navigator.platform);\n return (\n <Dialog title=\"Keyboard shortcuts\" onClose={close} wide>\n <p class=\"dialog__lead\">Single-key shortcuts work whenever you are not typing in the editor or in a field. Tab leaves the editor.</p>\n {GROUPS.map((group) => {\n const rows = SHORTCUTS.filter((s) => s.group === group && !HIDDEN_IN_HELP.has(s.id) && (helper || !s.helperOnly));\n if (rows.length === 0) return null;\n return (\n <table key={group} class=\"keytable\">\n <caption class=\"label\">{group}</caption>\n <tbody>\n {rows.map((s) => (\n <ShortcutRow key={s.id} shortcut={s} mac={mac} />\n ))}\n </tbody>\n </table>\n );\n })}\n <table class=\"keytable\">\n <caption class=\"label\">In lists and panels</caption>\n <tbody>\n {LIST_KEYS.map((row) => (\n <tr key={row.label}>\n <th scope=\"row\">{row.label}</th>\n <td>\n <Keys keys={row.keys} />\n </td>\n </tr>\n ))}\n {helper ? (\n <tr>\n <th scope=\"row\">Toggle a breakpoint on the current line (in the editor)</th>\n <td>\n <Keys keys={['F9']} />\n </td>\n </tr>\n ) : null}\n </tbody>\n </table>\n {helper ? <p class=\"muted\">Some browsers keep F11 for full screen; Ctrl+; and Ctrl+Shift+; always work for step into and step out.</p> : null}\n {helper ? (\n <section class=\"helpnote\">\n <h3 class=\"label\">What a pause stops</h3>\n <p>\n {connection.notes.value.frozenClock ??\n 'On an official Node.js build a breakpoint stops JavaScript only: the clock, the thread pool and the operating system keep running, which can change what happens next.'}{' '}\n The probe build can hold the loop clock and the pool threads during a pause; the operating system and network peers are never held.\n </p>\n </section>\n ) : null}\n </Dialog>\n );\n}\n\n// ---- program picker (helper mode) -------------------------------------------------------\n\nfunction FileBrowser() {\n const [dir, setDir] = useState('');\n const [state, setState] = useState<{ status: 'loading' } | { status: 'ready'; entries: FileEntry[] } | { status: 'failed'; reason: string }>({ status: 'loading' });\n useEffect(() => {\n let live = true;\n setState({ status: 'loading' });\n program.listFiles(dir).then(\n (entries) => {\n if (live) setState({ status: 'ready', entries: entries.slice(0, 2000) });\n },\n (e: unknown) => {\n if (live) setState({ status: 'failed', reason: e instanceof Error ? e.message : String(e) });\n },\n );\n return () => {\n live = false;\n };\n }, [dir]);\n\n const parent = dir.includes('/') ? dir.slice(0, dir.lastIndexOf('/')) : '';\n const folder = connection.welcome.value?.folder ?? 'folder';\n return (\n <div class=\"files\">\n <p class=\"files__where mono\">\n {folder}/{dir}\n </p>\n {state.status === 'loading' ? <p class=\"muted\">Reading the folder...</p> : null}\n {state.status === 'failed' ? <p class=\"warn-text\">The folder could not be read: {state.reason}</p> : null}\n {state.status === 'ready' ? (\n <ul class=\"files__list\">\n {dir !== '' ? (\n <li>\n <button type=\"button\" class=\"files__entry\" onClick={() => setDir(parent)}>\n <Icon name=\"chevronUp\" />\n <span>Up one folder</span>\n </button>\n </li>\n ) : null}\n {state.entries.length === 0 ? <li class=\"muted\">This folder is empty.</li> : null}\n {state.entries.map((entry) => {\n const name = entry.path.includes('/') ? entry.path.slice(entry.path.lastIndexOf('/') + 1) : entry.path;\n const runnable = /\\.(?:m?js|cjs)$/i.test(name);\n return (\n <li key={entry.path}>\n {entry.kind === 'dir' ? (\n <button type=\"button\" class=\"files__entry\" onClick={() => setDir(entry.path)}>\n <Icon name=\"open\" />\n <span class=\"mono\">{name}/</span>\n </button>\n ) : (\n <button\n type=\"button\"\n class=\"files__entry\"\n disabled={!runnable}\n title={runnable ? 'Show this file; Run starts it' : 'Only .js, .mjs and .cjs files can be run'}\n onClick={() => {\n void program.openFile(entry.path);\n close();\n }}\n >\n <Icon name=\"code\" />\n <span class=\"mono\">{name}</span>\n </button>\n )}\n </li>\n );\n })}\n </ul>\n ) : null}\n </div>\n );\n}\n\nfunction ProgramDialog() {\n const examples = program.examples.value;\n const source = program.source.value;\n return (\n <Dialog title=\"Choose a program\" onClose={close} wide>\n <p class=\"dialog__lead\">Choosing a program only shows it. It runs when you press Run.</p>\n <section class=\"pick\">\n <h3 class=\"label\">Editor snippet</h3>\n <button\n type=\"button\"\n class=\"card\"\n onClick={() => {\n program.useSnippet();\n close();\n }}\n >\n <span class=\"card__title\">Edit a snippet{source.kind === 'snippet' ? ' (current)' : ''}</span>\n <span class=\"card__text\">Your text is kept in this browser between visits.</span>\n </button>\n </section>\n <section class=\"pick\">\n <h3 class=\"label\">Examples</h3>\n {examples.status === 'ready' && examples.examples.length > 0 ? (\n <ul class=\"cards cards--dense\">\n {examples.examples.map((example) => (\n <li key={example.id}>\n <button\n type=\"button\"\n class=\"card\"\n onClick={() => {\n program.loadExample(example);\n close();\n }}\n >\n <span class=\"card__title\">{example.title}</span>\n <span class=\"card__text\">{example.summary}</span>\n {example.racy ? <span class=\"card__meta muted\">The output order is a race and can differ between runs.</span> : null}\n </button>\n </li>\n ))}\n </ul>\n ) : (\n <p class=\"muted\">{examples.status === 'loading' ? 'Loading the examples...' : examples.status === 'failed' ? `The examples could not be loaded: ${examples.reason}` : 'This copy has no built-in examples.'}</p>\n )}\n <p class=\"muted\">Loading an example replaces the text of the snippet.</p>\n </section>\n <section class=\"pick\">\n <h3 class=\"label\">A file from the folder nodejs-map was started in</h3>\n <FileBrowser />\n </section>\n </Dialog>\n );\n}\n\n// ---- save and share -----------------------------------------------------------------------\n\nfunction SourceChoice({ value, onChange }: { value: boolean; onChange(v: boolean): void }) {\n const can = Boolean(session.headerForSave(true)?.sources?.length);\n return (\n <fieldset class=\"choice\">\n <legend>Include the text of the program?</legend>\n <label class=\"check\">\n <input type=\"radio\" name=\"include-source\" checked={!value} onChange={() => onChange(false)} />\n No. The recording holds the events and the output only.\n </label>\n <label class=\"check\">\n <input type=\"radio\" name=\"include-source\" checked={value} disabled={!can} onChange={() => onChange(true)} />\n Yes. Anyone who gets the recording can read the program.\n </label>\n {can ? null : <p class=\"muted\">The text of the program is not available for this run, so it cannot be included.</p>}\n <p class=\"muted\">Either way the recording contains everything the program printed.</p>\n </fieldset>\n );\n}\n\nfunction SaveDialog() {\n const [include, setInclude] = useState(false);\n const [gzip, setGzip] = useState(true);\n const [busy, setBusy] = useState(false);\n return (\n <Dialog title=\"Save the recording\" onClose={close}>\n <SourceChoice value={include} onChange={setInclude} />\n <label class=\"check\">\n <input type=\"checkbox\" checked={gzip} onChange={(e) => setGzip((e.currentTarget as HTMLInputElement).checked)} />\n Compress the file (gzip). Uncompressed, it is plain text you can read.\n </label>\n <p class=\"dialog__acts\">\n <button\n type=\"button\"\n class=\"ctl ctl--primary\"\n disabled={busy}\n onClick={() => {\n setBusy(true);\n void session.save({ includeSource: include, gzip }).then((saved) => {\n setBusy(false);\n if (!saved) return;\n downloadBytes(saved.bytes, saved.fileName, gzip ? 'application/gzip' : 'text/plain');\n session.announce(`Saved ${saved.fileName}.`);\n close();\n });\n }}\n >\n <Icon name=\"save\" />\n <span>{busy ? 'Saving...' : 'Save file'}</span>\n </button>\n </p>\n {session.error.value ? <p class=\"warn-text\">{session.error.value}</p> : null}\n </Dialog>\n );\n}\n\nfunction ShareDialog() {\n const [include, setInclude] = useState(false);\n const [result, setResult] = useState<ShareResult | null>(null);\n const [busy, setBusy] = useState(false);\n const [copied, setCopied] = useState(false);\n const base = shareBaseUrl();\n const link = result?.ok && base ? `${base}#${result.fragment}` : null;\n\n useEffect(() => {\n setResult(null);\n setCopied(false);\n }, [include]);\n\n return (\n <Dialog title=\"Share as a link\" onClose={close}>\n <p class=\"dialog__lead\">A share link carries the whole recording in the part of the address after “#”. That part is not sent to any server; whoever opens the link plays the recording, nothing is run.</p>\n <SourceChoice value={include} onChange={setInclude} />\n <p class=\"dialog__acts\">\n <button\n type=\"button\"\n class=\"ctl ctl--primary\"\n disabled={busy}\n onClick={() => {\n setBusy(true);\n void session.share(include).then((r) => {\n setBusy(false);\n setResult(r);\n });\n }}\n >\n <Icon name=\"share\" />\n <span>{busy ? 'Making the link...' : 'Make the link'}</span>\n </button>\n </p>\n {result && !result.ok ? (\n <div class=\"callout callout--warn\">\n <p>\n This recording is too big for a link: it would take {result.length.toLocaleString('en')} characters and the limit is {result.limit.toLocaleString('en')}. Share the file instead.\n </p>\n <p class=\"dialog__acts\">\n <button type=\"button\" class=\"ctl ctl--plain\" onClick={() => (ui.dialog.value = 'save')}>\n <Icon name=\"save\" />\n <span>Save the file</span>\n </button>\n </p>\n </div>\n ) : null}\n {result?.ok && link ? (\n <div class=\"sharelink\">\n <label class=\"field\">\n <span class=\"field__label\">Link ({result.length.toLocaleString('en')} characters)</span>\n <input class=\"input mono\" type=\"text\" readOnly value={link} onFocus={(e) => (e.currentTarget as HTMLInputElement).select()} />\n </label>\n <p class=\"dialog__acts\">\n <button\n type=\"button\"\n class=\"ctl ctl--plain\"\n onClick={() => {\n navigator.clipboard.writeText(link).then(\n () => setCopied(true),\n () => setCopied(false),\n );\n }}\n >\n {copied ? 'Copied' : 'Copy the link'}\n </button>\n </p>\n {result.fitsEverywhere ? null : (\n <p class=\"muted\">This link is longer than {SHARE_LINK_SAFE_CHARS.toLocaleString('en')} characters. Browsers open it, but some chat and mail programs cut long links; if it arrives broken, share the file.</p>\n )}\n </div>\n ) : null}\n {result?.ok && !link ? (\n <div class=\"callout callout--info\">\n <p>\n The recording fits in a link ({result.length.toLocaleString('en')} characters), but this page runs on your own machine and its address works for nobody else. Save the file and open it\n in the nodejs-map player website to get a link others can use.\n </p>\n <p class=\"dialog__acts\">\n <button type=\"button\" class=\"ctl ctl--plain\" onClick={() => (ui.dialog.value = 'save')}>\n <Icon name=\"save\" />\n <span>Save the file</span>\n </button>\n </p>\n </div>\n ) : null}\n {session.error.value ? <p class=\"warn-text\">{session.error.value}</p> : null}\n </Dialog>\n );\n}\n\n// ---- \"More\" (narrow screens) -----------------------------------------------------------------\n\nfunction MoreDialog() {\n const recording = session.recording.value;\n const helper = helperMode.value;\n return (\n <Dialog title=\"More\" onClose={close}>\n {recording ? (\n <div class=\"more__now\">\n <p>\n <strong>{recording.lesson?.title ?? recording.header.title ?? recording.label}</strong>\n <br />\n <span class=\"muted\">\n Recording · Node {recording.header.node.version} · {recording.events} events. It is played back; nothing is run.\n </span>\n </p>\n <button\n type=\"button\"\n class=\"ctl ctl--plain\"\n onClick={() => {\n session.closeRecording();\n close();\n }}\n >\n {helper ? 'Close the recording and return to the editor' : 'Close the recording'}\n </button>\n </div>\n ) : helper ? null : (\n <p class=\"muted\">This is the player: it opens recordings and lessons. It cannot run code.</p>\n )}\n {helper ? <ProviderSelect /> : null}\n <RecordingActions words />\n <p class=\"dialog__acts\">\n <button type=\"button\" class=\"ctl ctl--plain\" onClick={() => (ui.dialog.value = 'legend')}>\n {CERTAINTIES.map((c) => (\n <span key={c} class={`mark-inline mark--${c}`}>\n <MarkGlyph c={c} />\n </span>\n ))}\n <span>What the marks mean</span>\n </button>\n <button type=\"button\" class=\"ctl ctl--plain\" onClick={toggleTheme}>\n <Icon name=\"theme\" />\n <span>Light or dark</span>\n </button>\n <button type=\"button\" class=\"ctl ctl--plain\" onClick={() => (ui.dialog.value = 'help')}>\n <Icon name=\"help\" />\n <span>Help</span>\n </button>\n </p>\n </Dialog>\n );\n}\n\n// ---- playback options (narrow screens) ---------------------------------------------------------\n\nfunction PlaybackDialog() {\n const state = player.player.value;\n const length = state?.length ?? 0;\n const live = state?.live ?? false;\n return (\n <Dialog title=\"Playback\" onClose={close}>\n <div class=\"playback\">\n <label class=\"field\">\n <span class=\"field__label\">Speed</span>\n <SpeedSelect />\n <span class=\"field__hint muted\">{SPEED_HINT}.</span>\n </label>\n <label class=\"field\">\n <span class=\"field__label\">The step buttons move by</span>\n <StepUnitSelect />\n </label>\n </div>\n <p class=\"dialog__acts\">\n <button type=\"button\" class=\"ctl ctl--plain\" disabled={length === 0} onClick={() => player.command({ do: 'seek', position: 0 })}>\n <Icon name=\"toStart\" />\n <span>Go to the start</span>\n </button>\n <button type=\"button\" class=\"ctl ctl--plain\" disabled={length === 0} onClick={() => player.command({ do: 'seek', position: length })}>\n <Icon name=\"toEnd\" />\n <span>Go to the end</span>\n </button>\n </p>\n <label class=\"check\">\n <input\n type=\"checkbox\"\n checked={settings.timelineAxis.value === 'time'}\n onChange={(e) => {\n settings.timelineAxis.value = (e.currentTarget as HTMLInputElement).checked ? 'time' : 'index';\n }}\n />\n Draw the strip by time instead of by event count\n </label>\n {helperMode.value ? (\n <label class=\"check\">\n <input type=\"checkbox\" checked={Boolean(state?.follow)} disabled={!live} onChange={(e) => player.command({ do: 'follow', on: (e.currentTarget as HTMLInputElement).checked })} />\n Follow the live run{live ? '' : ' (only while a run is in progress)'}\n </label>\n ) : null}\n </Dialog>\n );\n}\n\n/** Drag a recording file onto the window to open it. */\nexport function useDropToOpen(): void {\n useEffect(() => {\n const hasFiles = (e: DragEvent): boolean => Boolean(e.dataTransfer && [...e.dataTransfer.types].includes('Files'));\n const over = (e: DragEvent): void => {\n if (!hasFiles(e)) return;\n e.preventDefault();\n if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';\n document.documentElement.classList.add('is-dropping');\n };\n const leave = (): void => document.documentElement.classList.remove('is-dropping');\n const drop = (e: DragEvent): void => {\n leave();\n if (!hasFiles(e)) return;\n e.preventDefault();\n const file = e.dataTransfer?.files[0];\n if (file) void openRecordingFile(file);\n };\n addEventListener('dragover', over);\n addEventListener('dragleave', leave);\n addEventListener('drop', drop);\n return () => {\n removeEventListener('dragover', over);\n removeEventListener('dragleave', leave);\n removeEventListener('drop', drop);\n };\n }, []);\n}\n\nexport function Dialogs() {\n if (ui.mark.value) return <MarkDialog />;\n switch (ui.dialog.value) {\n case 'legend':\n return <LegendDialog />;\n case 'help':\n return <HelpDialog />;\n case 'program':\n return <ProgramDialog />;\n case 'save':\n return <SaveDialog />;\n case 'share':\n return <ShareDialog />;\n case 'more':\n return <MoreDialog />;\n case 'playback':\n return <PlaybackDialog />;\n default:\n return null;\n }\n}\n","/**\n * Stand-in for the map panel, used until src/map/index.ts exists (and briefly while its\n * chunk loads). It satisfies the contract and shows plain text only: no boxes, no sample\n * data - every box on the map must come from the atlas build.\n *\n * It honours the one duty the contract gives the map towards the shell: when `flyTo` is\n * set, it is set back to null.\n */\nimport { useSignalEffect } from '@preact/signals';\nimport type { MapPanelProps } from '../map/contract.ts';\n\nexport function MapStandIn({ flyTo }: MapPanelProps) {\n useSignalEffect(() => {\n if (flyTo.value !== null) flyTo.value = null;\n });\n return <p class=\"map__status\">Map loading...</p>;\n}\n","/**\n * The map region. The shell owns the frame around the map and decides which atlas it\n * gets; everything inside is the map panel (src/map/, built separately, see\n * map/contract.ts).\n *\n * The panel is found at build time with import.meta.glob: when src/map/index.ts exists it\n * is loaded as its own chunk (so the first paint does not wait for the renderer); until\n * then the stand-in below is mounted. No box is ever drawn by the shell: with no atlas,\n * or no map panel, the region shows plain text.\n */\nimport type { ComponentType } from 'preact';\nimport { useEffect, useState } from 'preact/hooks';\nimport type { MapPanelProps } from '../map/contract.ts';\nimport { atlas, codeLine, highlights, noteMapInteraction, openSource, platform, ui, userBoxes } from '../stores/index.ts';\nimport { MapStandIn } from './MapStandIn.tsx';\nimport { AreaClose } from './ViewMenu.tsx';\n\ntype MapModule = { MapPanel: ComponentType<MapPanelProps> };\nconst found = import.meta.glob<MapModule>('../map/index.{ts,tsx}');\nconst loadMap = Object.values(found)[0];\n\nexport function MapRegion() {\n const state = atlas.state.value;\n const [Panel, setPanel] = useState<ComponentType<MapPanelProps> | null>(null);\n const [failed, setFailed] = useState(false);\n\n useEffect(() => {\n if (!loadMap) return;\n let live = true;\n loadMap().then(\n (m) => {\n // A component is a function: wrap it so setState does not call it as an updater.\n if (live) setPanel(() => m.MapPanel);\n },\n () => {\n if (live) setFailed(true);\n },\n );\n return () => {\n live = false;\n };\n }, []);\n\n let body;\n if (state.status === 'none') {\n body = <p class=\"map__status\">The map appears when a recording or a lesson is open: each recording names the Node.js version whose map it needs.</p>;\n } else if (state.status === 'loading') {\n body = <p class=\"map__status\">Loading the map of Node.js {state.tag}...</p>;\n } else if (state.status === 'missing') {\n body = (\n <p class=\"map__status\" role=\"alert\">\n The map of Node.js {state.tag} is not available here ({state.reason}). The panels still show the run; places cannot be shown on a map or opened as source.\n </p>\n );\n } else if (failed) {\n body = (\n <p class=\"map__status\" role=\"alert\">\n The map could not be loaded. Reload the page to try again.\n </p>\n );\n } else {\n const props: MapPanelProps = {\n atlas: state.store,\n atlasBase: state.base,\n platform: platform.value,\n highlights,\n userBoxes,\n codeLine,\n selected: ui.selected,\n flyTo: ui.flyTo,\n onOpenSource: openSource,\n };\n // The key remounts the panel when another atlas is loaded.\n body = Panel ? <Panel key={state.commit} {...props} /> : <MapStandIn key={state.commit} {...props} />;\n }\n\n return (\n <section\n class=\"map\"\n aria-label=\"Map of Node.js\"\n // The user's own panning and zooming turns \"Move map with the run\" off (stores/index.ts).\n // A drag, the wheel, and the map's own keys count; a plain click on a box does not.\n onPointerDownCapture={(e) => noteMapInteraction('down', e.clientX, e.clientY)}\n onPointerMoveCapture={(e) => {\n if (e.buttons !== 0 || e.pointerType === 'touch') noteMapInteraction('move', e.clientX, e.clientY);\n }}\n onPointerUpCapture={() => noteMapInteraction('up')}\n onPointerCancelCapture={() => noteMapInteraction('up')}\n onWheelCapture={() => noteMapInteraction('zoom')}\n onKeyDownCapture={(e) => {\n const typing = e.target instanceof HTMLInputElement || e.target instanceof HTMLSelectElement;\n if (!typing && (e.key.startsWith('Arrow') || e.key === '+' || e.key === '-' || e.key === '=' || e.key === '0')) noteMapInteraction('zoom');\n }}\n >\n {body}\n <AreaClose area=\"map\" />\n </section>\n );\n}\n","/**\n * The event log behind the Events panel: a filtered, windowed read over the whole event\n * list. Runs in the worker. The page asks for the rows it shows (a few dozen) and gets\n * small plain rows back; it never holds the list.\n *\n * The same class tracks what the run is doing at its tail (running, paused, at a gate),\n * because the run controls need that even while the player looks at an earlier position.\n */\nimport type { Certainty, EventKind, NmEvent, SourceId } from '@nodejs-map/event-format';\nimport { SIGNAL_KINDS } from '@nodejs-map/replay';\nimport { KIND_GROUP, LOG_GROUPS, summarizeEvent } from './format.ts';\nimport type { LogGroup } from './format.ts';\n\nexport interface LogFilter {\n /** Groups to show. */\n groups: readonly LogGroup[];\n /** Certainties to show. */\n certainty: readonly Certainty[];\n}\n\nexport const ALL_GROUPS_FILTER: LogFilter = { groups: LOG_GROUPS, certainty: ['observed', 'inferred', 'model'] };\n\n/** One row of the Events panel. Plain data, cheap to post. */\nexport interface LogRow {\n /** Index of the event in the run. */\n index: number;\n t: number;\n k: string;\n c: Certainty;\n src: SourceId;\n rule: string | null;\n at: string | null;\n approx: boolean;\n text: string;\n}\n\nexport interface LogWindow {\n /** Rows that match the filter in the whole run. */\n total: number;\n /** Row number of rows[0] in the filtered list. */\n offset: number;\n rows: LogRow[];\n /**\n * Row number, in the filtered list, of the latest matching event at or before the\n * position asked for (-1: none). The panel marks it as \"now\".\n */\n cursorRow: number;\n /** Events in the run when this was read. */\n length: number;\n /** True when the filter lets every event through: row n is then the event at index n. */\n all: boolean;\n /** The position cursorRow was worked out for. */\n position: number;\n}\n\n/**\n * Where the cursor is in a window that was read for another position, when that can be\n * told from the rows at hand: the row of the latest event before `position`. Returns\n * undefined when the answer lies outside the rows (the worker must be asked).\n */\nexport function cursorRowIn(window: LogWindow, position: number): number | undefined {\n if (window.all) return Math.min(position, window.total) - 1;\n const rows = window.rows;\n const first = rows[0];\n const last = rows[rows.length - 1];\n if (!first || !last) return window.total === 0 ? -1 : undefined;\n if (position <= first.index) return window.offset === 0 ? -1 : undefined;\n if (position > last.index + 1) return window.offset + rows.length === window.total ? window.total - 1 : undefined;\n let lo = 0;\n let hi = rows.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if ((rows[mid] as LogRow).index < position) lo = mid + 1;\n else hi = mid;\n }\n return window.offset + lo - 1;\n}\n\nexport type TailStatus = 'idle' | 'running' | 'paused' | 'gated' | 'ended';\n\nexport interface TailState {\n status: TailStatus;\n mode: 'free' | 'debug' | null;\n length: number;\n /** Times the program was stopped so far: debugger pauses and gate stops. */\n pauses: number;\n /** Some event names a line of source (an output, an item or a pause with a location). False: no line can be highlighted for this run. */\n located: boolean;\n}\n\n/** Does this event name a line of code? */\nfunction hasLocation(e: NmEvent): boolean {\n if ((e as { loc?: unknown }).loc !== undefined) return true;\n return e.k === 'debug.paused' && e.frames.length > 0;\n}\n\nconst CERTAINTY_BIT: Readonly<Record<Certainty, number>> = { observed: 1, inferred: 2, model: 4 };\n\nfunction filterKey(f: LogFilter): string {\n return `${[...f.groups].sort().join(',')}|${[...f.certainty].sort().join(',')}`;\n}\n\nfunction toRow(e: NmEvent, index: number): LogRow {\n let text: string;\n try {\n text = summarizeEvent(e);\n } catch {\n text = String(e.k); // a malformed event must not break the list\n }\n return {\n index,\n t: e.t,\n k: e.k,\n c: e.c,\n src: e.src,\n rule: e.rule ?? null,\n at: e.at ?? null,\n approx: e.tq !== undefined,\n text,\n };\n}\n\nfunction statusAfter(e: NmEvent): TailStatus | null {\n switch (e.k) {\n case 'run.start':\n return 'running';\n case 'run.end':\n return 'ended';\n case 'debug.paused':\n return 'paused';\n case 'gate.stopped':\n return 'gated';\n case 'debug.resumed':\n case 'gate.released':\n return 'running';\n default:\n return null;\n }\n}\n\nexport class LogIndex {\n #events: NmEvent[] = [];\n /** Indexes of the events that match the current filter, ascending. Grown in place. */\n #matches = new Uint32Array(1024);\n #matchCount = 0;\n /** Events already tested against the filter. */\n #scanned = 0;\n #key = filterKey(ALL_GROUPS_FILTER);\n #groupOn: ReadonlySet<LogGroup> = new Set(LOG_GROUPS);\n #certaintyMask = 7;\n #all = true;\n /** [event index, status] of every event that changes the tail status, ascending. */\n #statusMarks: Array<[number, TailStatus]> = [];\n #mode: 'free' | 'debug' | null = null;\n /** Index of the first event that names a line of source; -1: none so far. */\n #firstLocated = -1;\n\n get length(): number {\n return this.#events.length;\n }\n\n reset(): void {\n this.#events = [];\n this.#matchCount = 0;\n this.#scanned = 0;\n this.#statusMarks = [];\n this.#mode = null;\n this.#firstLocated = -1;\n }\n\n /** The `events` message: keep the first `base` events, then append. Returns false when `base` leaves a gap. */\n apply(base: number, events: readonly NmEvent[]): boolean {\n if (!Number.isInteger(base) || base < 0 || base > this.#events.length) return false;\n if (base < this.#events.length) {\n this.#events.length = base;\n if (this.#scanned > base) {\n this.#scanned = base;\n let n = this.#matchCount;\n while (n > 0 && (this.#matches[n - 1] as number) >= base) n--;\n this.#matchCount = n;\n }\n while (this.#statusMarks.length > 0 && (this.#statusMarks[this.#statusMarks.length - 1] as [number, TailStatus])[0] >= base) {\n this.#statusMarks.pop();\n }\n if (this.#firstLocated >= base) this.#firstLocated = -1;\n }\n for (let i = 0; i < events.length; i++) {\n const e = events[i] as NmEvent;\n const index = this.#events.length;\n this.#events.push(e);\n if (typeof e !== 'object' || e === null) continue;\n const status = statusAfter(e);\n if (status) this.#statusMarks.push([index, status]);\n if (e.k === 'run.start') this.#mode = e.mode === 'debug' ? 'debug' : 'free';\n if (this.#firstLocated < 0 && hasLocation(e)) this.#firstLocated = index;\n }\n return true;\n }\n\n /** Meaningful steps in the list: events that are not raw signals (what the player's \"step\" stops at). */\n steps(): number {\n let n = 0;\n for (const e of this.#events) if (typeof e === 'object' && e !== null && !SIGNAL_KINDS.has(e.k)) n++;\n return n;\n }\n\n tail(): TailState {\n const last = this.#statusMarks[this.#statusMarks.length - 1];\n let pauses = 0;\n for (const [, status] of this.#statusMarks) if (status === 'paused' || status === 'gated') pauses++;\n return { status: last ? last[1] : 'idle', mode: this.#mode, length: this.#events.length, pauses, located: this.#firstLocated >= 0 };\n }\n\n #matchesFilter(e: NmEvent): boolean {\n if (typeof e !== 'object' || e === null) return this.#all;\n if (this.#all) return true;\n const group = KIND_GROUP[e.k as EventKind];\n if (group !== undefined && !this.#groupOn.has(group)) return false;\n // An unknown kind (newer format) is shown whenever any group is on: hiding it would hide evidence.\n return ((CERTAINTY_BIT[e.c] ?? 0) & this.#certaintyMask) !== 0;\n }\n\n #setFilter(filter: LogFilter): void {\n const key = filterKey(filter);\n if (key === this.#key) return;\n this.#key = key;\n this.#groupOn = new Set(filter.groups);\n this.#certaintyMask = filter.certainty.reduce((m, c) => m | (CERTAINTY_BIT[c] ?? 0), 0);\n this.#all = this.#groupOn.size === LOG_GROUPS.length && this.#certaintyMask === 7;\n this.#matchCount = 0;\n this.#scanned = 0;\n }\n\n #scan(): void {\n if (this.#all) {\n this.#scanned = this.#events.length;\n return;\n }\n for (let i = this.#scanned; i < this.#events.length; i++) {\n if (!this.#matchesFilter(this.#events[i] as NmEvent)) continue;\n if (this.#matchCount === this.#matches.length) {\n const bigger = new Uint32Array(this.#matches.length * 2);\n bigger.set(this.#matches);\n this.#matches = bigger;\n }\n this.#matches[this.#matchCount++] = i;\n }\n this.#scanned = this.#events.length;\n }\n\n /** Row number of the latest match with event index < position, or -1. */\n #rowBefore(position: number): number {\n if (this.#all) return Math.min(position, this.#events.length) - 1;\n let lo = 0;\n let hi = this.#matchCount;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if ((this.#matches[mid] as number) < position) lo = mid + 1;\n else hi = mid;\n }\n return lo - 1;\n }\n\n /**\n * Rows [offset, offset + limit) of the filtered list. `position` is the player position\n * (events applied); the row of the event applied last, or the nearest match before it,\n * comes back as cursorRow.\n */\n window(filter: LogFilter, offset: number, limit: number, position: number): LogWindow {\n this.#setFilter(filter);\n this.#scan();\n const total = this.#all ? this.#events.length : this.#matchCount;\n const from = Math.max(0, Math.min(Math.trunc(offset), total));\n const to = Math.max(from, Math.min(from + Math.max(0, Math.min(Math.trunc(limit), 500)), total));\n const rows: LogRow[] = [];\n for (let row = from; row < to; row++) {\n const index = this.#all ? row : (this.#matches[row] as number);\n const e = this.#events[index];\n if (e === undefined) break;\n rows.push(\n typeof e === 'object' && e !== null\n ? toRow(e, index)\n : { index, t: 0, k: '?', c: 'model', src: 'helper', rule: null, at: null, approx: false, text: 'Malformed event' },\n );\n }\n return { total, offset: from, rows, cursorRow: this.#rowBefore(position), length: this.#events.length, all: this.#all, position };\n }\n\n /** One event, for the \"go to this event\" detail. */\n eventAt(index: number): NmEvent | null {\n return this.#events[index] ?? null;\n }\n}\n","/**\n * memo: a component that re-renders only when its props differ by `same`. The few lines\n * of preact/compat's memo, without pulling in compat. Used for rows of long lists, which\n * are re-rendered many times a second during playback while most of them do not change.\n */\nimport type { ComponentChildren, FunctionComponent } from 'preact';\n\ninterface WithShouldUpdate<P> {\n props: P;\n shouldComponentUpdate?: (next: P) => boolean;\n}\n\nexport function memo<P extends object>(render: (props: P) => ComponentChildren, same: (a: P, b: P) => boolean): FunctionComponent<P> {\n function Memo(this: WithShouldUpdate<P>, props: P): ComponentChildren {\n // Preact calls a function component with its component instance as `this`.\n this.shouldComponentUpdate = (next: P) => !same(this.props, next);\n return render(props);\n }\n Memo.displayName = `memo(${render.name || 'component'})`;\n return Memo as unknown as FunctionComponent<P>;\n}\n","/**\n * Windowing for long lists: which rows to render for a scroll position. Pure.\n *\n * Browsers cap the height of an element (about 33 million pixels in Chrome, less\n * elsewhere). A million rows of 24 px would pass it, so above MAX_SCROLL_PX the list is\n * scaled: the scroll height stays at the cap and the scroll position maps linearly onto\n * the rows. Scrolling is then coarser per pixel but every row stays reachable.\n */\n\nexport const MAX_SCROLL_PX = 8_000_000;\n\nexport interface VirtualWindow {\n /** First row to render (inclusive) and one past the last. */\n first: number;\n end: number;\n /** Height of the scrollable spacer in px. */\n totalHeight: number;\n /** Where to place the first rendered row, in px from the top of the spacer. */\n offset: number;\n}\n\nexport function virtualWindow(scrollTop: number, viewportHeight: number, rowHeight: number, count: number, overscan = 6): VirtualWindow {\n if (count <= 0 || rowHeight <= 0) return { first: 0, end: 0, totalHeight: 0, offset: 0 };\n const natural = count * rowHeight;\n const totalHeight = Math.min(natural, MAX_SCROLL_PX);\n const visible = Math.max(1, Math.ceil(viewportHeight / rowHeight));\n const maxScroll = Math.max(0, totalHeight - viewportHeight);\n const top = Math.min(Math.max(0, scrollTop), maxScroll);\n let firstVisible: number;\n if (natural <= MAX_SCROLL_PX) {\n firstVisible = Math.floor(top / rowHeight);\n } else {\n const maxFirst = Math.max(0, count - visible);\n firstVisible = maxScroll === 0 ? 0 : Math.round((top / maxScroll) * maxFirst);\n }\n const first = Math.max(0, firstVisible - overscan);\n const end = Math.min(count, firstVisible + visible + overscan);\n // Rendered rows are positioned relative to the scroll position so that the first\n // visible row sits at the top of the viewport in both the natural and the scaled case.\n const offset = natural <= MAX_SCROLL_PX ? first * rowHeight : top - (firstVisible - first) * rowHeight;\n return { first, end, totalHeight, offset };\n}\n\n/**\n * The scrollTop that brings `row` into view, or null when it already is.\n *\n * mode \"nearest\" moves as little as possible. Mode \"page\" is for following a row that\n * keeps moving (the current event during playback): when the row leaves the view the\n * list jumps so that the row sits a third of the way in, with room ahead of it. The list\n * then scrolls once per two thirds of a screen instead of once per row, which is both\n * calmer to read and much less work.\n */\nexport function scrollTopForRow(row: number, scrollTop: number, viewportHeight: number, rowHeight: number, count: number, mode: 'nearest' | 'page' = 'nearest'): number | null {\n if (count <= 0 || row < 0 || row >= count) return null;\n const natural = count * rowHeight;\n if (natural <= MAX_SCROLL_PX) {\n const top = row * rowHeight;\n const maxScroll = Math.max(0, natural - viewportHeight);\n const lead = mode === 'page' ? Math.floor(viewportHeight / 3 / rowHeight) * rowHeight : 0;\n if (top < scrollTop) return Math.max(0, mode === 'page' ? Math.min(maxScroll, top + rowHeight + lead - viewportHeight) : top);\n if (top + rowHeight > scrollTop + viewportHeight) return Math.min(maxScroll, mode === 'page' ? Math.max(0, top - lead) : top + rowHeight - viewportHeight);\n return null;\n }\n const visible = Math.max(1, Math.ceil(viewportHeight / rowHeight));\n const maxFirst = Math.max(1, count - visible);\n const maxScroll = Math.max(0, MAX_SCROLL_PX - viewportHeight);\n const firstVisible = Math.round((Math.min(scrollTop, maxScroll) / Math.max(1, maxScroll)) * maxFirst);\n if (row >= firstVisible && row < firstVisible + visible - 1) return null;\n const target = Math.min(maxFirst, Math.max(0, row - Math.floor(visible / 2)));\n return (target / maxFirst) * maxScroll;\n}\n","/**\n * A list that renders only the rows in view. Rows have one fixed height.\n * The list is one tab stop; the caller handles its keys (see the Events panel).\n *\n * Built for playback, where the row to keep in view changes many times a second:\n * the scroll position is kept in a ref (what we last set or were told), so following the\n * current row never reads layout back from the DOM, and one change of row costs one\n * render and one write of scrollTop.\n */\nimport type { ComponentChildren } from 'preact';\nimport { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';\nimport { scrollTopForRow, virtualWindow } from '../lib/virtual.ts';\nimport { useElementSize } from './hooks.ts';\n\n/** How long after writing scrollTop a scroll event is treated as ours. */\nconst OWN_SCROLL_MS = 80;\n\nexport interface VirtualListProps {\n count: number;\n rowHeight: number;\n renderRow(index: number): ComponentChildren;\n /** Called with the rows now rendered, so the caller can load them. */\n onWindow?(first: number, end: number): void;\n /** Keep this row in view; the list scrolls only when the value changes. */\n keepVisible?: number | null;\n label: string;\n class?: string;\n onKeyDown?: (e: KeyboardEvent) => void;\n activeDescendant?: string | undefined;\n}\n\nexport function VirtualList({ count, rowHeight, renderRow, onWindow, keepVisible = null, label, class: extra, onKeyDown, activeDescendant }: VirtualListProps) {\n const [ref, size] = useElementSize<HTMLDivElement>();\n /** The scroll position as we know it: set by us, or reported by a scroll event. */\n const top = useRef(0);\n const [, rerender] = useState(0);\n const spacer = useRef<HTMLDivElement>(null);\n const rows = useRef<HTMLDivElement>(null);\n\n // Follow the row to keep in view. Decided during render, from our own record of the\n // scroll position, and written to the DOM right here - before this render changes any\n // row. At this point the list's layout is still clean, so the browser can scroll\n // without laying anything out; written after the rows changed (in an effect), the same\n // assignment forces a synchronous layout of the whole list on every jump.\n const kept = useRef('');\n /** Until this time a scroll event is taken to be the echo of our own write. */\n const ownScrollUntil = useRef(0);\n const keepKey = `${String(keepVisible)}|${size.height > 0 ? 1 : 0}|${rowHeight}`;\n if (keepKey !== kept.current) {\n kept.current = keepKey;\n if (keepVisible !== null && size.height > 0) {\n const wanted = scrollTopForRow(keepVisible, top.current, size.height, rowHeight, count, 'page');\n if (wanted !== null) {\n top.current = wanted;\n if (ref.current) {\n ref.current.scrollTop = wanted;\n ownScrollUntil.current = performance.now() + OWN_SCROLL_MS;\n }\n }\n }\n }\n\n const win = virtualWindow(top.current, size.height, rowHeight, count, 3);\n\n // Sizes and offsets are numbers that change while scrolling: set through the CSSOM\n // (allowed by the Content-Security-Policy; a style attribute would not be).\n useLayoutEffect(() => {\n spacer.current?.style.setProperty('height', `${win.totalHeight}px`);\n rows.current?.style.setProperty('transform', `translateY(${win.offset}px)`);\n }, [win.totalHeight, win.offset]);\n\n useEffect(() => {\n onWindow?.(win.first, win.end);\n }, [win.first, win.end, onWindow]);\n\n const items: ComponentChildren[] = [];\n for (let i = win.first; i < win.end; i++) items.push(renderRow(i));\n\n return (\n <div\n ref={ref}\n class={`vlist${extra ? ` ${extra}` : ''}`}\n role=\"listbox\"\n tabIndex={0}\n aria-label={label}\n aria-activedescendant={activeDescendant}\n onScroll={(e) => {\n // Our own write comes back as a scroll event. Reading scrollTop then would force\n // a layout (the rows have changed since); we know the value, so skip the read.\n if (performance.now() < ownScrollUntil.current) return;\n const now = (e.currentTarget as HTMLElement).scrollTop;\n if (Math.abs(now - top.current) < 1) return;\n top.current = now;\n rerender((n) => n + 1);\n }}\n onKeyDown={onKeyDown}\n >\n <div ref={spacer} class=\"vlist__spacer\">\n <div ref={rows} class=\"vlist__rows\">\n {items}\n </div>\n </div>\n </div>\n );\n}\n","/** Pieces shared by the live panels: rows, item chips, row actions, empty states. */\nimport type { ComponentChildren } from 'preact';\nimport type { Certainty, QueueName } from '@nodejs-map/event-format';\nimport { ASYNC_TYPE_AT, ASYNC_TYPE_INFO } from '@nodejs-map/atlas-format';\nimport type { Fact, ItemRef } from '@nodejs-map/replay';\nimport { baseName, formatMicros, isSameProgram, itemKindWords, oneLine } from '../lib/format.ts';\nimport { Icon } from '../shell/icons.tsx';\nimport { Mark } from '../shell/Mark.tsx';\nimport { jumpToEvent, revealInEditor, showOnMap, shown } from '../stores/index.ts';\n\n/** \"Show on the map\" for anything that has an atlas id. Renders nothing without one. */\nexport function MapButton({ at, what }: { at: string | null | undefined; what: string }) {\n if (!at) return null;\n return (\n <button type=\"button\" class=\"row__act\" data-act=\"map\" tabIndex={-1} aria-label={`Show ${what} on the map`} title=\"Show on the map (M)\" onClick={() => showOnMap(at)}>\n <Icon name=\"map\" />\n </button>\n );\n}\n\n/** Where in the user's program an item was created, as a button that scrolls the editor there. */\nexport function LocButton({ item }: { item: ItemRef }) {\n const loc = item.loc;\n if (!loc) return null;\n const text = `${baseName(loc.url)}:${loc.line}`;\n if (!isSameProgram(loc.url, shown.value.name)) return <span class=\"row__loc mono muted\">{text}</span>;\n return (\n <button type=\"button\" class=\"row__loc link mono\" tabIndex={-1} title=\"Show this line in the editor\" onClick={() => revealInEditor(loc.line, loc.line)}>\n {text}\n </button>\n );\n}\n\n/** A compact label for an async item: its kind in plain words, its id, its label. */\nexport function ItemChip({ item, queue }: { item: ItemRef; queue?: QueueName | null | undefined }) {\n const words = item.label ? oneLine(item.label, 40) : itemKindWords(item.type);\n return (\n <span class={`chip${queue ? ` chip--${queue}` : ''}`} title={ASYNC_TYPE_INFO[item.type]?.meaning ?? `async_hooks type ${item.type}`}>\n <span class=\"chip__kind\">{words ?? item.type}</span>\n <span class=\"chip__id num\">#{item.id}</span>\n {/* The raw async_hooks type stays on show, as the secondary text. */}\n {words ? <span class=\"chip__label\">{item.type}</span> : null}\n </span>\n );\n}\n\nexport function itemMapId(item: ItemRef): string | undefined {\n return ASYNC_TYPE_AT[item.type];\n}\n\nexport interface RowProps {\n /** The fact the row shows: its certainty sets the row's edge and mark; activating the row goes to its event. */\n fact: Fact | null;\n /** Certainty when there is no single fact behind the row. */\n certainty?: Certainty;\n rule?: string | null;\n /** What the row is, for labels: \"timer #4 in the timers queue\". */\n subject: string;\n children: ComponentChildren;\n /** Right-aligned details. */\n meta?: ComponentChildren;\n mapId?: string | null | undefined;\n /** Marks the row (head of a queue, current frame). */\n tag?: string | undefined;\n selected?: boolean;\n onActivate?: (() => void) | undefined;\n /** First row of its list: the list's tab stop. */\n first?: boolean;\n}\n\n/**\n * One row of a list in a panel. The row itself is the keyboard target (data-row); its\n * mark and map button are reached with I and M (see listKeyDown).\n */\nexport function Row({ fact, certainty, rule, subject, children, meta, mapId, tag, selected, onActivate, first }: RowProps) {\n const c = fact?.c ?? certainty ?? 'observed';\n const activate = onActivate ?? (fact ? () => jumpToEvent(fact.index) : undefined);\n return (\n <li class={`row edge edge--${c}${selected ? ' is-selected' : ''}`} data-rowbox>\n <Mark c={c} rule={fact?.rule ?? rule ?? null} index={fact?.index ?? null} subject={subject} tabbable={false} />\n <button\n type=\"button\"\n class=\"row__main\"\n data-row\n tabIndex={first ? 0 : -1}\n aria-current={selected ? 'true' : undefined}\n title={fact ? `Go to event ${fact.index + 1} at ${formatMicros(fact.t)}` : undefined}\n onClick={activate}\n >\n {tag ? <span class=\"row__tag\">{tag}</span> : null}\n {children}\n </button>\n {meta ? <span class=\"row__meta\">{meta}</span> : null}\n <MapButton at={mapId} what={subject} />\n </li>\n );\n}\n\nexport function Empty({ children }: { children: ComponentChildren }) {\n return <p class=\"empty\">{children}</p>;\n}\n\nexport function Section({ title, count, aside, children, class: extra }: { title: string; count?: number | string; aside?: ComponentChildren; children: ComponentChildren; class?: string }) {\n return (\n <section class={`section${extra ? ` ${extra}` : ''}`}>\n <header class=\"section__head\">\n <h3 class=\"label\">{title}</h3>\n {count !== undefined ? <span class=\"section__count num\">{count}</span> : null}\n {aside ? <span class=\"section__aside\">{aside}</span> : null}\n </header>\n {children}\n </section>\n );\n}\n\n/** The panel message when there is nothing to show at all. */\nexport function NoRun({ helper }: { helper: boolean }) {\n return (\n <Empty>\n {helper ? 'Nothing to show yet. Press Run to start the program, or open a recording.' : 'Nothing to show yet. Open a recording or pick a lesson.'}\n </Empty>\n );\n}\n","/**\n * Events: the event list of the run, virtualised, with filters. Each row carries its\n * certainty mark and its source; activating a row moves the player there.\n *\n * The page never holds the list. It asks the worker for the rows around the ones in view\n * and keeps the last answer; rows not loaded yet are drawn as blanks.\n *\n * Built to stay cheap during playback, when the position changes many times a second:\n * the worker is asked again only when the rows at hand no longer cover what is on show\n * (or the run or the filter changed), the \"now\" row is worked out from the rows at hand,\n * and a row re-renders only when its own event or its \"now\"/\"not reached\" state changes.\n */\nimport { signal } from '@preact/signals';\nimport { useCallback, useEffect, useRef, useState } from 'preact/hooks';\nimport type { Certainty } from '@nodejs-map/event-format';\nimport { CERTAINTIES, CERTAINTY_LABEL } from '../lib/certainty.ts';\nimport { LOG_GROUPS, LOG_GROUP_LABEL, SOURCE_HELP, SOURCE_LABEL, formatMicros } from '../lib/format.ts';\nimport type { LogGroup } from '../lib/format.ts';\nimport { cursorRowIn } from '../lib/logIndex.ts';\nimport type { LogFilter, LogRow, LogWindow } from '../lib/logIndex.ts';\nimport { useRowHeight } from '../shell/hooks.ts';\nimport { Mark, MarkGlyph } from '../shell/Mark.tsx';\nimport { memo } from '../shell/memo.ts';\nimport { VirtualList } from '../shell/VirtualList.tsx';\nimport { helperMode, jumpToEvent, openMark, player, showOnMap } from '../stores/index.ts';\nimport { MapButton, NoRun } from './parts.tsx';\n\n/** Rows asked for beyond the ones on show, each side. */\nconst MARGIN = 60;\n/** Ask again when fewer loaded rows than this remain beyond the ones on show. */\nconst LOW_WATER = 12;\n\n// The filters outlive the panel: switching tabs must not reset them. Raw signals are off\n// at first; they are evidence, and most of the time they are noise.\nconst groupsOn = signal<readonly LogGroup[]>(LOG_GROUPS.filter((g) => g !== 'signals'));\nconst certaintyOn = signal<readonly Certainty[]>(CERTAINTIES);\nconst followCursor = signal(true);\n\nfunction toggle<T>(list: readonly T[], value: T): T[] {\n return list.includes(value) ? list.filter((v) => v !== value) : [...list, value];\n}\n\ninterface EventRowProps {\n row: number;\n /** undefined: not loaded yet. */\n event: LogRow | undefined;\n now: boolean;\n future: boolean;\n}\n\nconst EventRow = memo<EventRowProps>(\n function EventRow({ row, event: r, now, future }) {\n if (!r) return <div class=\"ev ev--blank\" id={`ev-${row}`} role=\"option\" aria-selected=\"false\" />;\n return (\n <div id={`ev-${row}`} class={`ev edge edge--${r.c}${now ? ' is-now' : ''}${future ? ' is-future' : ''}`} role=\"option\" aria-selected={now ? 'true' : 'false'}>\n <Mark c={r.c} rule={r.rule} index={r.index} subject={r.text} tabbable={false} />\n <span class=\"ev__n num\">{r.index + 1}</span>\n <span class=\"ev__t num\" title={r.approx ? 'The order of this event against its neighbours is approximate' : undefined}>\n {r.approx ? '~' : ''}\n {formatMicros(r.t)}\n </span>\n <button type=\"button\" class=\"ev__text\" tabIndex={-1} title={r.k} onClick={() => jumpToEvent(r.index)}>\n {r.text}\n </button>\n <span class=\"ev__src muted\" title={SOURCE_HELP[r.src] ?? r.src}>\n {SOURCE_LABEL[r.src] ?? r.src}\n {r.rule ? ` · ${r.rule}` : ''}\n </span>\n <MapButton at={r.at} what=\"this event's place\" />\n </div>\n );\n },\n (a, b) =>\n a.row === b.row &&\n a.now === b.now &&\n a.future === b.future &&\n // Rows come as fresh objects with every answer; an event is the same when these are.\n (a.event === b.event || (a.event !== undefined && b.event !== undefined && a.event.index === b.event.index && a.event.text === b.event.text && a.event.c === b.event.c && a.event.t === b.event.t)),\n);\n\nexport function EventsPanel() {\n const rowHeight = useRowHeight();\n const groups = groupsOn.value;\n const certainty = certaintyOn.value;\n const follow = followCursor.value;\n const [data, setData] = useState<LogWindow | null>(null);\n /** Rows on show, as the list last reported them. */\n const shownRows = useRef({ first: 0, end: 0 });\n const busy = useRef(false);\n const again = useRef(false);\n const version = player.parts.version.value;\n const position = player.parts.position.value;\n const length = player.parts.length.value;\n const latest = useRef({ groups, certainty, position, version });\n latest.current = { groups, certainty, position, version };\n /** Filter and run version of `data`. */\n const dataKey = useRef<{ groups: readonly LogGroup[]; certainty: readonly Certainty[]; version: number } | null>(null);\n\n const load = useCallback((): void => {\n if (busy.current) {\n again.current = true;\n return;\n }\n busy.current = true;\n const asked = latest.current;\n const filter: LogFilter = { groups: asked.groups, certainty: asked.certainty };\n const { first, end } = shownRows.current;\n const offset = Math.max(0, first - MARGIN);\n const limit = Math.max(1, end - first) + 2 * MARGIN;\n player\n .log(filter, offset, limit, asked.position)\n .then((window) => {\n // An answer for an older filter would show rows of another list for a moment.\n if (latest.current.groups === asked.groups && latest.current.certainty === asked.certainty) {\n dataKey.current = { groups: asked.groups, certainty: asked.certainty, version: asked.version };\n setData(window);\n }\n })\n .catch(() => undefined)\n .finally(() => {\n busy.current = false;\n if (again.current) {\n again.current = false;\n load();\n }\n });\n }, []);\n\n // Where the cursor is: from the rows at hand when they can tell, else as last answered.\n const local = data ? cursorRowIn(data, position) : undefined;\n const cursorRow = local ?? (data && data.position === position ? data.cursorRow : -1);\n const total = data?.total ?? 0;\n\n /** Do the rows at hand cover the rows on show, with some to spare on both sides? */\n const dataRef = useRef(data);\n dataRef.current = data;\n const covered = useCallback((first: number, end: number): boolean => {\n const d = dataRef.current;\n if (!d) return false;\n return d.offset <= Math.max(0, first - LOW_WATER) && d.offset + d.rows.length >= Math.min(d.total, end + LOW_WATER);\n }, []);\n\n const stale = !dataKey.current || dataKey.current.groups !== groups || dataKey.current.certainty !== certainty || dataKey.current.version !== version;\n const needCursor = local === undefined && (!data || data.position !== position);\n useEffect(() => {\n if (stale || needCursor || !covered(shownRows.current.first, shownRows.current.end)) load();\n }, [stale, needCursor, data, load, covered]);\n\n const onWindow = useCallback(\n (first: number, end: number): void => {\n shownRows.current = { first, end };\n if (!covered(first, end)) load();\n },\n [load, covered],\n );\n\n if (length === 0) return <NoRun helper={helperMode.value} />;\n\n const rowAt = (row: number): LogRow | undefined => (data && row >= data.offset ? data.rows[row - data.offset] : undefined);\n\n const onKeyDown = (e: KeyboardEvent): void => {\n if (e.ctrlKey || e.metaKey || e.altKey) return;\n const move = e.key === 'ArrowDown' ? 1 : e.key === 'ArrowUp' ? -1 : e.key === 'PageDown' ? 20 : e.key === 'PageUp' ? -20 : 0;\n const current = rowAt(cursorRow);\n if (move !== 0 || e.key === 'Home' || e.key === 'End') {\n e.preventDefault();\n e.stopPropagation();\n const target = e.key === 'Home' ? 0 : e.key === 'End' ? total - 1 : Math.min(total - 1, Math.max(0, cursorRow + move));\n const row = rowAt(target);\n followCursor.value = true;\n if (row) jumpToEvent(row.index);\n else {\n // Not loaded: ask for that part of the list; the next key press will find it.\n shownRows.current = { first: Math.max(0, target - 10), end: target + 10 };\n load();\n }\n return;\n }\n if (!current) return;\n if (e.key === 'i') {\n e.preventDefault();\n e.stopPropagation();\n openMark({ certainty: current.c, ruleId: current.rule, index: current.index, subject: current.text });\n } else if (e.key === 'm' && current.at) {\n e.preventDefault();\n e.stopPropagation();\n showOnMap(current.at);\n }\n };\n\n return (\n <div class=\"events\">\n <div class=\"events__filters\" role=\"group\" aria-label=\"Filter the event list\">\n <div class=\"filter-row\">\n {LOG_GROUPS.map((g) => (\n <button key={g} type=\"button\" class={`pill${groups.includes(g) ? ' is-on' : ''}`} aria-pressed={groups.includes(g) ? 'true' : 'false'} onClick={() => (groupsOn.value = toggle(groups, g))}>\n {LOG_GROUP_LABEL[g]}\n </button>\n ))}\n </div>\n <div class=\"filter-row\">\n {CERTAINTIES.map((c) => (\n <button key={c} type=\"button\" class={`pill pill--mark${certainty.includes(c) ? ' is-on' : ''}`} aria-pressed={certainty.includes(c) ? 'true' : 'false'} onClick={() => (certaintyOn.value = toggle(certainty, c))}>\n <span class={`mark-inline mark--${c}`}>\n <MarkGlyph c={c} />\n </span>\n {CERTAINTY_LABEL[c]}\n </button>\n ))}\n <label class=\"check\">\n <input type=\"checkbox\" checked={follow} onChange={(e) => (followCursor.value = (e.currentTarget as HTMLInputElement).checked)} />\n Keep the current event in view\n </label>\n <span class=\"events__count num muted\">\n {total} of {data?.length ?? length} events\n </span>\n </div>\n </div>\n <VirtualList\n class=\"events__list\"\n label=\"Events of the run. Up and Down move the player; I explains the mark; M shows the place on the map.\"\n count={total}\n rowHeight={rowHeight}\n onWindow={onWindow}\n keepVisible={follow && cursorRow >= 0 ? cursorRow : null}\n onKeyDown={onKeyDown}\n activeDescendant={cursorRow >= 0 ? `ev-${cursorRow}` : undefined}\n renderRow={(row) => {\n const event = rowAt(row);\n return <EventRow key={row} row={row} event={event} now={row === cursorRow} future={event !== undefined && event.index >= position} />;\n }}\n />\n </div>\n );\n}\n","/**\n * Lessons: a gallery of recordings with a little guidance (player mode), shown as\n * \"Examples\" in helper mode together with the programs the editor can load.\n *\n * Opening a lesson opens its recording - nothing is run. Its steps are listed beside the\n * player; choosing a step moves the player to that step's event.\n */\nimport { listKeyDown } from '../shell/hooks.ts';\nimport { helperMode, player, program, session, showTab, ui } from '../stores/index.ts';\nimport type { Lesson } from '../stores/session.ts';\nimport { Empty, Section } from './parts.tsx';\n\n/**\n * An open lesson. In this order, because the sheet on a phone shows only the top of the\n * panel: the title and text of the current step, Previous / Next, and only then (folded\n * away) what the lesson is about and the list of all its steps.\n */\nfunction OpenLesson({ lesson }: { lesson: Lesson }) {\n const steps = lesson.steps ?? [];\n const position = player.parts.position.value;\n let current = -1;\n for (let i = 0; i < steps.length; i++) if ((steps[i]?.index ?? Infinity) < position) current = i;\n const go = (i: number): void => {\n const step = steps[i];\n if (!step) return;\n player.command({ do: 'pause' });\n player.command({ do: 'seek', position: step.index + 1 });\n };\n const step = steps[current];\n return (\n <section class=\"lesson\" aria-label={`Lesson: ${lesson.title}`}>\n {steps.length === 0 ? (\n <>\n <h3 class=\"lesson__step\">{lesson.title}</h3>\n <p class=\"lesson__text\">{lesson.summary || 'This lesson has no written steps. Press play, or step through it.'}</p>\n </>\n ) : (\n <>\n <h3 class=\"lesson__step\" aria-live=\"polite\">\n {step ? (\n <>\n <span class=\"lesson__n num\">\n {current + 1}/{steps.length}\n </span>{' '}\n {step.title || `Event ${step.index + 1}`}\n </>\n ) : (\n lesson.title\n )}\n </h3>\n <p class=\"lesson__text\">{step ? step.text : lesson.summary || 'Press Next step to begin.'}</p>\n <div class=\"steps__nav\">\n <button type=\"button\" class=\"ctl ctl--plain\" disabled={current <= 0} onClick={() => go(current - 1)}>\n Previous step\n </button>\n <button type=\"button\" class=\"ctl ctl--primary\" disabled={current >= steps.length - 1} onClick={() => go(current + 1)}>\n Next step\n </button>\n </div>\n <details class=\"lesson__more\">\n <summary>About this lesson, and all {steps.length} steps</summary>\n <p class=\"lesson__title\">{lesson.title}</p>\n {lesson.summary ? <p class=\"lessons__summary\">{lesson.summary}</p> : null}\n <ol class=\"steps\" onKeyDown={listKeyDown} aria-label=\"Steps of the lesson\">\n {steps.map((each, i) => (\n <li key={i} class={`step${i === current ? ' is-current' : ''}`} data-rowbox>\n <button type=\"button\" class=\"step__head\" data-row tabIndex={i === Math.max(0, current) ? 0 : -1} aria-current={i === current ? 'step' : undefined} onClick={() => go(i)}>\n <span class=\"step__n num\">{i + 1}</span>\n <span class=\"step__title\">{each.title || `Event ${each.index + 1}`}</span>\n <span class=\"num muted\">event {each.index + 1}</span>\n </button>\n </li>\n ))}\n </ol>\n </details>\n </>\n )}\n </section>\n );\n}\n\nfunction Gallery() {\n const state = session.lessons.value;\n if (state.status === 'none') return <Empty>This copy of nodejs-map has no recorded lessons.</Empty>;\n if (state.status === 'loading') return <Empty>Loading the lessons...</Empty>;\n if (state.status === 'failed') return <p class=\"empty warn-text\">The lessons could not be loaded: {state.reason}</p>;\n if (state.lessons.length === 0) return <Empty>There are no lessons yet.</Empty>;\n const openId = session.recording.value?.lesson?.id ?? null;\n return (\n <ul class=\"cards\">\n {state.lessons.map((lesson) => (\n <li key={lesson.id}>\n <button type=\"button\" class={`card${lesson.id === openId ? ' is-open' : ''}`} disabled={session.opening.value} onClick={() => void session.openLesson(lesson)}>\n <span class=\"card__title\">{lesson.title}</span>\n <span class=\"card__text\">{lesson.summary}</span>\n <span class=\"card__meta muted\">\n Recording{lesson.node ? ` made on Node ${lesson.node}` : ''}\n {lesson.steps?.length ? ` · ${lesson.steps.length} steps` : ''} · opens without running anything\n </span>\n </button>\n </li>\n ))}\n </ul>\n );\n}\n\nfunction Programs() {\n const state = program.examples.value;\n if (state.status === 'none') return null;\n return (\n <Section title=\"Programs to run\">\n {state.status === 'loading' ? <Empty>Loading the examples...</Empty> : null}\n {state.status === 'failed' ? <p class=\"empty warn-text\">The examples could not be loaded: {state.reason}</p> : null}\n {state.status === 'ready' ? (\n <ul class=\"cards\">\n {state.examples.map((example) => (\n <li key={example.id}>\n <button\n type=\"button\"\n class=\"card\"\n onClick={() => {\n program.loadExample(example);\n session.announce(`Loaded ${example.title} into the editor. It has not been run.`);\n if (ui.narrow.value) showTab('code');\n }}\n >\n <span class=\"card__title\">{example.title}</span>\n <span class=\"card__text\">{example.summary}</span>\n <span class=\"card__meta muted\">\n {example.module === 'esm' ? 'ES module' : 'CommonJS'}\n {example.racy ? ' · the output order is a race and can differ between runs' : ''} · loads into the editor, runs only when you press Run\n </span>\n </button>\n </li>\n ))}\n </ul>\n ) : null}\n </Section>\n );\n}\n\nexport function LessonsPanel() {\n const helper = helperMode.value;\n const lesson = session.recording.value?.lesson ?? null;\n const lists = (\n <>\n {helper ? <Programs /> : null}\n <Section title={helper ? 'Recorded lessons' : 'Lessons'}>\n <Gallery />\n </Section>\n </>\n );\n return (\n <div class=\"panel-scroll lessons\">\n {lesson ? (\n <>\n <OpenLesson lesson={lesson} />\n {/* The gallery steps aside while a lesson is open. */}\n <details class=\"lesson__more\">\n <summary>{helper ? 'Other examples and lessons' : 'Other lessons'}</summary>\n {lists}\n </details>\n </>\n ) : (\n lists\n )}\n </div>\n );\n}\n","/**\n * Now: what the main thread is doing at the player's position, where the event loop is,\n * and why the current callback ran (the chain of who scheduled whom).\n *\n * Each section is its own component and reads only its own part of the view\n * (stores/player.ts `parts`), so during playback a section re-renders only when what it\n * shows has changed.\n */\nimport { useEffect, useState } from 'preact/hooks';\nimport type { Certainty, Phase } from '@nodejs-map/event-format';\nimport { PHASE_IDS } from '@nodejs-map/atlas-format';\nimport { PERSISTENT_HANDLE_TYPES } from '@nodejs-map/replay';\nimport type { CallbackFrame, ItemView } from '@nodejs-map/replay';\nimport { PHASE_RING_RULE } from '../lib/certainty.ts';\nimport { PHASE_LABEL, QUEUE_LABEL, formatMicros, formatMillis, itemTitle, oneLine, plural } from '../lib/format.ts';\nimport { listKeyDown } from '../shell/hooks.ts';\nimport { FactMark, Mark } from '../shell/Mark.tsx';\nimport { hasRun, helperMode, platform, player, session, showOnMap } from '../stores/index.ts';\nimport { Empty, ItemChip, LocButton, NoRun, Row, Section, itemMapId } from './parts.tsx';\n\nconst parts = player.parts;\n\n/** The seven phases as a ring, clockwise from the top, in the order uv_run runs them. */\nconst RING: readonly Phase[] = ['timers', 'pending', 'idle', 'prepare', 'poll', 'check', 'closing'];\n\nconst DASH: Readonly<Record<Certainty, string | undefined>> = { observed: undefined, inferred: '7 4', model: '1.5 4' };\n\nfunction arc(index: number, count: number, radius: number): string {\n const gap = 0.07;\n const a0 = (index / count) * 2 * Math.PI - Math.PI / 2 + gap;\n const a1 = ((index + 1) / count) * 2 * Math.PI - Math.PI / 2 - gap;\n const p = (a: number): string => `${(50 + radius * Math.cos(a)).toFixed(2)} ${(50 + radius * Math.sin(a)).toFixed(2)}`;\n return `M ${p(a0)} A ${radius} ${radius} 0 0 1 ${p(a1)}`;\n}\nconst ARCS = RING.map((_, i) => arc(i, RING.length, 40));\n\nfunction PhaseRing() {\n const loop = parts.loop.value;\n if (!loop) return null;\n const current = loop.phase;\n const certainty = loop.phaseFrom?.c ?? 'inferred';\n const os = platform.value;\n const osName = os === 'win32' ? 'Windows' : os === 'darwin' ? 'macOS' : 'Linux';\n return (\n <div class=\"ring\">\n <svg class=\"ring__svg\" viewBox=\"0 0 100 100\" role=\"img\" aria-label={current ? `Event loop phase: ${PHASE_LABEL[current]}` : 'Event loop: no phase known at this point'}>\n {RING.map((phase, i) => {\n const lit = phase === current;\n return (\n <path\n key={phase}\n d={ARCS[i]}\n class={`ring__seg${lit ? ` is-lit ring__seg--${certainty}` : ''}`}\n fill=\"none\"\n stroke-width={lit ? 9 : 5}\n stroke-dasharray={lit ? DASH[certainty] : undefined}\n stroke-linecap=\"butt\"\n />\n );\n })}\n <text x=\"50\" y=\"47\" text-anchor=\"middle\" class=\"ring__turn-label\">\n turn\n </text>\n <text x=\"50\" y=\"62\" text-anchor=\"middle\" class=\"ring__turn\">\n {loop.turn ?? '-'}\n </text>\n </svg>\n <div class=\"ring__side\">\n <ol class=\"ring__list\" aria-label=\"Loop phases in the order libuv runs them\" onKeyDown={listKeyDown}>\n {RING.map((phase, i) => {\n const lit = phase === current;\n return (\n <li key={phase} class={`ring__item${lit ? ' is-lit' : ''}`} data-rowbox>\n <button\n type=\"button\"\n class=\"ring__phase\"\n data-row\n tabIndex={i === 0 ? 0 : -1}\n aria-current={lit ? 'step' : undefined}\n title={`Show the ${PHASE_LABEL[phase]} phase on the map`}\n onClick={() => showOnMap(PHASE_IDS[phase])}\n >\n <span class=\"ring__n num\">{i + 1}</span>\n {PHASE_LABEL[phase]}\n </button>\n {lit ? <FactMark fact={loop.phaseFrom} subject={`the loop is in the ${PHASE_LABEL[phase]} phase`} tabbable={false} /> : null}\n </li>\n );\n })}\n </ol>\n <p class=\"ring__note\">\n <Mark c=\"model\" rule={PHASE_RING_RULE} subject=\"the ring of loop phases\" />\n <span>\n Order of uv_run in libuv{session.node.value ? ` ${session.node.value.uv}` : ''} on {osName}.{' '}\n {os === 'win32'\n ? 'On Windows, finished I/O and thread pool results are delivered in the pending step, right after poll.'\n : `On ${osName}, thread pool results and most I/O callbacks are delivered inside the poll step.`}\n </span>\n </p>\n {loop.turn !== null ? (\n <p class=\"ring__fact\">\n <FactMark fact={loop.turnFrom} subject={`loop turn ${loop.turn}`} />\n <span>Loop turn {loop.turn}</span>\n </p>\n ) : null}\n {!current && loop.lastPhase ? (\n <p class=\"ring__fact\">\n <FactMark fact={loop.lastPhase.left} subject={`the loop left the ${PHASE_LABEL[loop.lastPhase.phase]} phase`} />\n <span>Between phases. Last one: {PHASE_LABEL[loop.lastPhase.phase]}.</span>\n </p>\n ) : null}\n {loop.lastSample ? (\n <p class=\"ring__fact\">\n <FactMark fact={loop.lastSample.from} subject=\"libuv loop counters\" />\n <span class=\"num\">\n libuv counters: loop count {loop.lastSample.loopCount}, events {loop.lastSample.events}, waiting {loop.lastSample.eventsWaiting}\n </span>\n </p>\n ) : null}\n </div>\n </div>\n );\n}\n\nfunction viaWords(frame: CallbackFrame): string {\n const queue = frame.queue ? ` from ${QUEUE_LABEL[frame.queue].toLowerCase()}` : '';\n switch (frame.via) {\n case 'phase':\n return `Taken${queue} by the event loop${frame.phase ? ` in the ${PHASE_LABEL[frame.phase]} phase` : ''}.`;\n case 'nextTick':\n return `Taken${queue} by the nextTick drain, after the previous callback returned.`;\n case 'microtask':\n return `Taken${queue} by the microtask drain, after the nextTick queue was empty.`;\n default:\n return 'How it got onto the main thread is not known from the events.';\n }\n}\n\n/**\n * Is the running callback the close callback of a handle? The view says so when the item\n * came from the close queue. Otherwise the `callback.start` event may carry `close`; it\n * is looked up for handles only (the one kind of item that has close callbacks).\n */\nfunction useIsCloseCallback(frame: CallbackFrame | undefined): boolean {\n const [seen, setSeen] = useState<{ index: number; close: boolean } | null>(null);\n const index = frame?.from.index ?? -1;\n const ask = frame !== undefined && frame.queue !== 'close' && PERSISTENT_HANDLE_TYPES.has(frame.item.type);\n useEffect(() => {\n if (!ask) return;\n let live = true;\n player\n .query({ what: 'events', from: index, to: index + 1 })\n .then((answer) => {\n const event = answer.entries[0]?.event;\n if (live) setSeen({ index, close: event?.k === 'callback.start' && event.close === true });\n })\n .catch(() => undefined);\n return () => {\n live = false;\n };\n }, [index, ask]);\n return frame?.queue === 'close' || (seen !== null && seen.index === index && seen.close);\n}\n\nfunction MainThread() {\n const main = parts.main.value;\n const status = parts.run.value?.status ?? 'idle';\n const top = main?.stack[main.stack.length - 1];\n const closing = useIsCloseCallback(main?.doing === 'callback' ? top : undefined);\n if (!main) return null;\n if (main.doing === 'callback' && top) {\n return (\n <div>\n <p class=\"now__line\">\n <FactMark fact={top.from} subject={`the callback of ${itemTitle(top.item)} is running`} />\n <span>\n Running the {closing ? 'close callback' : 'callback'} of <ItemChip item={top.item} queue={top.queue} />\n {top.depth > 0 ? <span class=\"muted\"> (started inside another callback)</span> : null}\n </span>\n </p>\n <p class=\"now__line\">\n {top.viaFrom ? <FactMark fact={top.viaFrom} subject={`how ${itemTitle(top.item)} reached the main thread`} /> : <span class=\"mark-gap\" />}\n <span>{viaWords(top)}</span>\n </p>\n </div>\n );\n }\n if (main.doing === 'main') {\n return (\n <p class=\"now__line\">\n <FactMark fact={main.from} subject=\"the main script is running\" />\n <span>Running the main script: the program's top-level code, before the event loop starts turning.</span>\n </p>\n );\n }\n return (\n <p class=\"now__line\">\n {main.from ? <FactMark fact={main.from} subject=\"no JavaScript is running\" /> : <span class=\"mark-gap\" />}\n <span>\n {status === 'idle' ? 'The run has not started.' : status === 'ended' ? 'The run has ended.' : 'No JavaScript is running: the main thread is in the event loop, between callbacks.'}\n </span>\n </p>\n );\n}\n\n/** \"Why did this run?\": the item of the current callback, then who scheduled it, up to the main script. */\nfunction TriggerChain() {\n const main = parts.main.value;\n const version = parts.version.value;\n const top = main?.stack[main.stack.length - 1];\n const id = top?.item.id ?? null;\n const [chain, setChain] = useState<{ id: number; items: ItemView[] } | null>(null);\n\n useEffect(() => {\n if (id === null) return;\n let live = true;\n player\n .query({ what: 'why', id })\n .then((answer) => {\n if (live) setChain({ id, items: answer.chain });\n })\n .catch(() => undefined);\n return () => {\n live = false;\n };\n }, [id, version]);\n\n if (id === null) return <Empty>No callback is running at this point, so there is no chain to show.</Empty>;\n const items = chain && chain.id === id ? chain.items : [];\n if (items.length === 0) return <Empty>Reading the chain...</Empty>;\n return (\n <ol class=\"rows chain\" onKeyDown={listKeyDown} aria-label=\"Why this callback ran, newest first\">\n {items.map((item, i) => (\n <Row\n key={item.id}\n fact={item.created ?? item.lastStart}\n certainty=\"inferred\"\n subject={item.created ? `${itemTitle(item)} was created` : `${itemTitle(item)} exists`}\n mapId={itemMapId(item)}\n tag={i === 0 ? 'running' : 'scheduled it'}\n first={i === 0}\n meta={<LocButton item={item} />}\n >\n <ItemChip item={item} queue={item.queues[0] ?? null} />\n {item.created ? null : <span class=\"muted\"> created before recording began</span>}\n </Row>\n ))}\n <li class=\"row row--plain\">\n <span class=\"mark-gap\" />\n <span class=\"row__text muted\">{(items[items.length - 1]?.trigger ?? 0) <= 1 ? 'which the main script scheduled.' : 'whose own trigger was not recorded.'}</span>\n </li>\n </ol>\n );\n}\n\n/** Position and time: the only part of the panel that changes on every step. */\nfunction PositionLine() {\n return (\n <dd class=\"num\">\n {plural(parts.position.value, 'event')} of {parts.length.value} · {formatMicros(parts.t.value)}\n </dd>\n );\n}\n\nfunction RunFacts() {\n const run = parts.run.value;\n if (!run) return null;\n const words =\n run.status === 'idle'\n ? 'Not started'\n : run.status === 'running'\n ? 'Running'\n : run.status === 'paused'\n ? 'Paused at a JavaScript statement'\n : run.status === 'gate'\n ? 'Stopped at a gate'\n : run.signal\n ? `Ended by ${run.signal}`\n : `Ended, exit code ${String(run.exitCode)}`;\n return (\n <dl class=\"facts\">\n <div>\n <dt>Program</dt>\n <dd>\n {run.program ?? '-'} {run.mode ? <span class=\"muted\">({run.mode === 'debug' ? 'debug run' : 'free run'})</span> : null}\n </dd>\n </div>\n <div>\n <dt>State</dt>\n <dd>\n {words} <FactMark fact={run.status === 'ended' ? run.ended : run.started} subject={`run state: ${words}`} />\n </dd>\n </div>\n <div>\n <dt>Position</dt>\n <PositionLine />\n </div>\n {run.node ? (\n <div>\n <dt>Node.js</dt>\n <dd>\n {run.node.version}{' '}\n <span class=\"muted\">\n ({run.node.platform} {run.node.arch}, libuv {run.node.uv}, pool size {run.poolSize ?? '?'})\n </span>\n </dd>\n </div>\n ) : null}\n </dl>\n );\n}\n\n/** Messages from the tool itself (\"thread pool events may be missing here\"): part of being honest about the data. */\nfunction Notes() {\n const notes = parts.notes.value;\n if (!notes || notes.items.length === 0) return null;\n return (\n <Section title=\"Notes from the tool\" count={notes.total}>\n <ul class=\"notes\">\n {notes.items.map((note) => (\n <li key={note.seq} class={`now__line${note.level === 'warn' ? ' warn-text' : ''}`}>\n <FactMark fact={note.from} subject=\"a note from nodejs-map\" />\n <span>{oneLine(note.text, 400)}</span>\n </li>\n ))}\n </ul>\n </Section>\n );\n}\n\nfunction LastPause() {\n const debug = parts.debug.value;\n const last = debug?.lastPause;\n if (!debug || !last || debug.paused) return null;\n return (\n <p class=\"now__line muted\">\n <FactMark fact={last.resumed} subject=\"the latest debugger pause\" />\n <span>\n Last pause: {formatMillis(last.pausedMs)}.{last.timeKeptRunning ? ' Real time kept running during it.' : ''}\n </span>\n </p>\n );\n}\n\nfunction Problems() {\n const problems = parts.problems.value;\n if (!problems || problems.unknown + problems.malformed + problems.inconsistent === 0) return null;\n return (\n <p class=\"now__line warn-text\">\n <span class=\"mark-gap\" />\n <span>\n This event list has problems: {problems.unknown} of unknown kind, {problems.malformed} malformed, {problems.inconsistent} that disagree with earlier events. The view may be incomplete.\n </span>\n </p>\n );\n}\n\nexport function NowPanel() {\n if (!hasRun.value) return <NoRun helper={helperMode.value} />;\n return (\n <div class=\"panel-scroll now\">\n <RunFacts />\n <Section title=\"Main thread\">\n <div class=\"now__doing\">\n <MainThread />\n </div>\n </Section>\n <Section title=\"Event loop\">\n <PhaseRing />\n </Section>\n <Section title=\"Why this callback ran\">\n <TriggerChain />\n </Section>\n <Notes />\n <LastPause />\n <Problems />\n </div>\n );\n}\n","/**\n * Output: what the program wrote to stdout and stderr up to the player's position. Each\n * chunk is one write; activating it moves the player to the event that wrote it.\n *\n * Program output is untrusted text. It is rendered as text nodes only, control characters\n * are not interpreted (no ANSI colours, no links), and stderr is told apart by a label\n * and an edge as well as by colour.\n */\nimport { useEffect, useRef } from 'preact/hooks';\nimport type { OutputChunk } from '@nodejs-map/replay';\nimport { baseName, formatMicros } from '../lib/format.ts';\nimport { listKeyDown } from '../shell/hooks.ts';\nimport { Mark } from '../shell/Mark.tsx';\nimport { hasRun, helperMode, jumpToEvent, openLoc, player } from '../stores/index.ts';\nimport { Empty, NoRun } from './parts.tsx';\n\n/** Characters shown per chunk; a longer write is cut with a note. */\nconst MAX_CHUNK_CHARS = 20_000;\n\n/** Removes ANSI escape sequences and makes other control characters visible. */\nexport function cleanOutput(text: string): string {\n return text\n .slice(0, MAX_CHUNK_CHARS)\n // eslint-disable-next-line no-control-regex\n .replace(/\\u001b\\[[0-9;?]*[ -/]*[@-~]/g, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/g, '�');\n}\n\nfunction Chunk({ chunk, first }: { chunk: OutputChunk; first: boolean }) {\n const cut = chunk.text.length > MAX_CHUNK_CHARS;\n return (\n <li class={`out out--${chunk.stream}`} data-rowbox>\n <button\n type=\"button\"\n class=\"out__text mono\"\n data-row\n tabIndex={first ? 0 : -1}\n title={`${chunk.stream}, event ${chunk.index + 1} at ${formatMicros(chunk.t)}. Activate to go there.`}\n onClick={() => jumpToEvent(chunk.index)}\n >\n {chunk.stream === 'stderr' ? <span class=\"out__tag\">stderr</span> : null}\n {cleanOutput(chunk.text)}\n {cut ? <span class=\"muted\"> … ({chunk.text.length - MAX_CHUNK_CHARS} more characters)</span> : null}\n </button>\n {/* The line of the program that made this write, when the run recorded source lines. */}\n {chunk.loc ? (\n <button\n type=\"button\"\n class=\"out__loc mono\"\n title={`Written by line ${chunk.loc.line} of ${chunk.loc.url}. Activate to see the line.`}\n onClick={() => {\n if (chunk.loc) openLoc(chunk.loc);\n }}\n >\n {baseName(chunk.loc.url)}:{chunk.loc.line}\n </button>\n ) : null}\n </li>\n );\n}\n\nexport function OutputPanel() {\n const output = player.parts.output.value;\n const scroller = useRef<HTMLDivElement>(null);\n const total = output?.total ?? 0;\n\n // Keep the newest output in view, unless the user scrolled up to read.\n const pinned = useRef(true);\n useEffect(() => {\n const el = scroller.current;\n if (el && pinned.current) el.scrollTop = el.scrollHeight;\n }, [total]);\n\n if (!hasRun.value || !output) return <NoRun helper={helperMode.value} />;\n return (\n <div\n class=\"panel-scroll output\"\n ref={scroller}\n onScroll={(e) => {\n const el = e.currentTarget as HTMLElement;\n pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;\n }}\n >\n <p class=\"note\">\n <Mark c=\"observed\" subject=\"program output\" />\n <span>\n {output.total} write{output.total === 1 ? '' : 's'} so far, read from the program's stdout and stderr by the helper.\n {output.total > output.chunks.length ? ` Showing the latest ${output.chunks.length}.` : ''}\n </span>\n </p>\n {output.chunks.length === 0 ? (\n <Empty>{output.total > 0 ? 'Reading the output...' : 'The program has written nothing up to this point.'}</Empty>\n ) : (\n <ol class=\"outs\" aria-label=\"Program output, oldest first\" onKeyDown={listKeyDown}>\n {output.chunks.map((chunk, i) => (\n <Chunk key={chunk.seq} chunk={chunk} first={i === 0} />\n ))}\n </ol>\n )}\n </div>\n );\n}\n","/**\n * Thread pool: one lane per pool thread with the job it runs, the line of jobs waiting\n * for a thread, and jobs that are finished but whose result has not reached the loop.\n */\nimport { WELL_KNOWN } from '@nodejs-map/atlas-format';\nimport type { PoolJobView, PoolThreadView } from '@nodejs-map/replay';\nimport { formatMicros, itemTitle, oneLine } from '../lib/format.ts';\nimport { listKeyDown } from '../shell/hooks.ts';\nimport { FactMark } from '../shell/Mark.tsx';\nimport { hasRun, helperMode, jumpToEvent, player, session } from '../stores/index.ts';\nimport { Empty, ItemChip, MapButton, NoRun, Row, Section } from './parts.tsx';\n\nconst parts = player.parts;\n\nconst MAX_ROWS = 60;\n\nfunction jobWords(job: PoolJobView): string {\n return `${job.kind}${job.op ? ` ${oneLine(job.op, 30)}` : ''}`;\n}\n\nfunction JobBody({ job }: { job: PoolJobView }) {\n return (\n <>\n <span class=\"chip chip--pool\">\n <span class=\"chip__kind\">{jobWords(job)}</span>\n <span class=\"chip__id mono\">{oneLine(job.job, 18)}</span>\n </span>\n {job.item ? (\n <>\n {' for '}\n <ItemChip item={job.item} />\n </>\n ) : (\n <span class=\"muted\"> owner not known</span>\n )}\n </>\n );\n}\n\nfunction Lane({ thread }: { thread: PoolThreadView }) {\n const job = thread.job;\n const fact = job ? (job.started ?? job.queued) : null;\n return (\n <li class={`lane${job ? ' is-busy' : ''} edge edge--${fact?.c ?? 'observed'}`} data-rowbox>\n <div class=\"lane__id\">\n <span class=\"lane__n\">Thread {thread.thread}</span>\n <span class=\"lane__tid num muted\" title={thread.tid !== null ? 'Operating-system thread id, as Node reported it' : 'Node did not report a thread id for this lane'}>\n {thread.tid !== null ? `tid ${thread.tid}` : 'no tid'}\n </span>\n </div>\n <div class=\"lane__job\">\n {job ? (\n <>\n <FactMark fact={fact} subject={`pool thread ${thread.thread} runs job ${job.job}`} tabbable={false} />\n <button type=\"button\" class=\"row__main\" data-row tabIndex={-1} title={fact ? `Go to event ${fact.index + 1}` : undefined} onClick={() => fact && jumpToEvent(fact.index)}>\n <JobBody job={job} />\n </button>\n {job.started ? <span class=\"num muted\">since {formatMicros(job.started.t)}</span> : null}\n <MapButton at={job.at ?? WELL_KNOWN.poolWorker.id} what={`pool thread ${thread.thread}`} />\n </>\n ) : (\n <span class=\"muted lane__idle\">idle</span>\n )}\n </div>\n <span class=\"lane__count num muted\" title={thread.extra ? 'The events showed this thread although it is above the pool size' : 'Jobs this thread has started so far'}>\n {thread.jobs} job{thread.jobs === 1 ? '' : 's'}\n {thread.extra ? ' · beyond the pool size' : ''}\n </span>\n </li>\n );\n}\n\nfunction JobList({ jobs, total, label, tag, which }: { jobs: PoolJobView[]; total: number; label: string; tag: string; which: 'queued' | 'finished' }) {\n if (jobs.length === 0) return <Empty>None.</Empty>;\n const shown = jobs.slice(0, MAX_ROWS);\n return (\n <ol class=\"rows\" onKeyDown={listKeyDown} aria-label={label}>\n {shown.map((job, i) => {\n const fact = which === 'queued' ? job.queued : (job.finished ?? job.started ?? job.queued);\n return (\n <Row\n key={job.job}\n fact={fact}\n certainty=\"inferred\"\n subject={`pool job ${job.job} ${which === 'queued' ? 'waits for a thread' : 'is finished and waits for delivery'}`}\n tag={i === 0 ? tag : undefined}\n first={i === 0}\n mapId={job.at ?? (which === 'queued' ? WELL_KNOWN.poolSubmit.id : WELL_KNOWN.poolDone.id)}\n meta={\n <>\n {job.thread !== null ? <span class=\"muted num\">thread {job.thread}</span> : null}\n {fact ? <span class=\"muted num\">since {formatMicros(fact.t)}</span> : null}\n </>\n }\n >\n <JobBody job={job} />\n </Row>\n );\n })}\n {total > shown.length ? (\n <li class=\"row row--plain\">\n <span class=\"mark-gap\" />\n <span class=\"row__text muted\">and {total - shown.length} more.</span>\n </li>\n ) : null}\n </ol>\n );\n}\n\nfunction Notice() {\n const how = session.caps.value?.poolThreads ?? null;\n if (how === 'delayed') {\n // One line, with the rest a click away: the lanes and the waiting line must stay in view.\n return (\n <details class=\"callout callout--info callout--fold\">\n <summary>\n <strong>Exact, but delayed.</strong> <span class=\"callout__more\">more</span>\n </summary>\n <p>\n Thread ids and job times are the ones Node reported, so they are exact. On an official build they come from trace events, which arrive later than the rest: during a live run this panel\n can lag behind the other panels, and the helper re-orders the event list when they arrive.\n </p>\n </details>\n );\n }\n if (how === 'none') {\n return (\n <p class=\"callout callout--warn\" role=\"note\">\n This Node.js gives no thread pool data. The lanes below stay empty; requests that use the pool are still listed under \"Requests with the pool\".\n </p>\n );\n }\n return null;\n}\n\nexport function PoolPanel() {\n const pool = parts.pool.value;\n const requests = parts.queues.pool.value;\n if (!hasRun.value || !pool || !requests) return <NoRun helper={helperMode.value} />;\n const held = pool.held;\n return (\n <div class=\"panel-scroll pool\">\n <Notice />\n {pool.leftAtEnd ? (\n <p class=\"callout callout--warn\" role=\"note\">\n The run ended with thread pool work unfinished or undelivered: what is still listed below never reached its callback.\n </p>\n ) : null}\n {held ? (\n <p class=\"now__line\">\n <FactMark fact={held.from} subject={`a gate holds pool job ${held.job}`} />\n <span>\n Held at the {held.gate} gate: job <span class=\"mono\">{oneLine(held.job, 18)}</span>{' '}\n {held.where === 'loop' ? 'is with the loop, before its done-callback' : held.thread !== null ? `is on thread ${held.thread}` : 'is on a pool thread'}.\n </span>\n </p>\n ) : null}\n <Section\n title=\"Threads\"\n {...(pool.size !== null ? { count: `pool size ${pool.size}` } : {})}\n aside={pool.sizeFrom ? <FactMark fact={pool.sizeFrom} subject={`the thread pool has ${String(pool.size)} threads`} /> : undefined}\n >\n {pool.threads.length === 0 ? (\n <Empty>No pool thread has been seen yet. libuv creates the threads on the first job.</Empty>\n ) : (\n <ol class=\"lanes\" onKeyDown={listKeyDown} aria-label=\"Thread pool threads\">\n {pool.threads.map((thread) => (\n <Lane key={thread.thread} thread={thread} />\n ))}\n </ol>\n )}\n </Section>\n {/* Side by side when there is room: the waiting line is the point of many a lesson step. */}\n <div class=\"pool__lines\">\n <Section title=\"Waiting for a thread\" count={pool.waiting.length}>\n <JobList jobs={pool.waiting} total={pool.waiting.length} label=\"Jobs waiting for a pool thread, oldest first\" tag=\"next\" which=\"queued\" />\n </Section>\n <Section title=\"Finished, not delivered\" count={pool.done.length}>\n <JobList jobs={pool.done} total={pool.done.length} label=\"Finished jobs whose result has not reached the loop, oldest first\" tag=\"next\" which=\"finished\" />\n </Section>\n </div>\n <Section title=\"Requests with the pool\" count={requests.total}>\n {requests.total === 0 ? (\n <Empty>None.</Empty>\n ) : (\n <ol class=\"rows\" onKeyDown={listKeyDown} aria-label=\"Async requests whose work is with the thread pool\">\n {requests.entries.slice(0, MAX_ROWS).map((entry, i) => (\n <Row key={entry.item.id} fact={entry.from} subject={`${itemTitle(entry.item)} is with the thread pool`} first={i === 0} mapId={entry.at ?? WELL_KNOWN.poolSubmit.id} meta={<span class=\"muted num\">since {formatMicros(entry.from.t)}</span>}>\n <ItemChip item={entry.item} queue=\"pool\" />\n </Row>\n ))}\n </ol>\n )}\n </Section>\n <Section title=\"Totals\">\n <dl class=\"facts facts--inline\">\n <div>\n <dt>queued</dt>\n <dd class=\"num\">{pool.counts.queued}</dd>\n </div>\n <div>\n <dt>started</dt>\n <dd class=\"num\">{pool.counts.started}</dd>\n </div>\n <div>\n <dt>finished</dt>\n <dd class=\"num\">{pool.counts.finished}</dd>\n </div>\n <div>\n <dt>delivered</dt>\n <dd class=\"num\">{pool.counts.delivered}</dd>\n </div>\n </dl>\n {pool.tids.length > 0 ? (\n <ul class=\"tids\" aria-label=\"Real thread ids seen in trace events\">\n {pool.tids.map((tid) => (\n <li key={tid.tid} class=\"tids__item\">\n <FactMark fact={tid.from} subject={`thread ${tid.tid} reported by Node`} />\n <span class=\"num\">tid {tid.tid}</span>\n <span class=\"muted\">\n {tid.busy ? `busy with ${oneLine(tid.name, 30)}` : 'idle'} · {tid.starts} started, {tid.ends} finished\n </span>\n </li>\n ))}\n </ul>\n ) : null}\n </Section>\n </div>\n );\n}\n","/**\n * Queues: where work waits. nextTick, microtasks, timers, immediates, pending I/O and\n * close callbacks, each as an ordered list with the head marked. Timers show their delay,\n * when they are due and, once they ran, how late.\n *\n * Each queue is its own component reading its own part of the view: a step that touches\n * one queue re-renders that queue only.\n */\nimport type { QueueName } from '@nodejs-map/event-format';\nimport type { TimerView } from '@nodejs-map/replay';\nimport { QUEUE_HELP, QUEUE_LABEL, formatMicros, formatMillis, itemTitle } from '../lib/format.ts';\nimport { listKeyDown } from '../shell/hooks.ts';\nimport { FactMark } from '../shell/Mark.tsx';\nimport { hasRun, helperMode, player } from '../stores/index.ts';\nimport { Empty, ItemChip, LocButton, NoRun, Row, Section, itemMapId } from './parts.tsx';\n\nconst parts = player.parts;\n\n/** Rows drawn per queue; the rest is summed up in one line. Keeps a frame cheap when a queue holds thousands. */\nconst MAX_ROWS = 60;\n\n/** The thread pool's requests have their own panel. */\nconst QUEUES: readonly QueueName[] = ['nextTick', 'microtask', 'timers', 'immediate', 'io', 'close'];\n\nfunction QueueHead({ name, total }: { name: QueueName; total: number }) {\n return (\n <header class=\"section__head queue__head\" title={QUEUE_HELP[name]}>\n <span class={`swatch swatch--${name}`} aria-hidden=\"true\" />\n <h3 class=\"label\">{QUEUE_LABEL[name]}</h3>\n <span class=\"section__count num\">{total}</span>\n </header>\n );\n}\n\nfunction More({ shown, total }: { shown: number; total: number }) {\n if (total <= shown) return null;\n return (\n <li class=\"row row--plain\">\n <span class=\"mark-gap\" />\n <span class=\"row__text muted\">and {total - shown} more behind these.</span>\n </li>\n );\n}\n\n/** Said once a run has ended with work still waiting: it never ran. */\nfunction LeftAtEnd({ what }: { what: string }) {\n return (\n <p class=\"note\">\n <span class=\"mark-gap\" />\n <span>The run ended with {what} still waiting here. They never ran.</span>\n </p>\n );\n}\n\nfunction Queue({ name }: { name: QueueName }) {\n const queue = parts.queues[name].value;\n if (!queue) return null;\n const entries = queue.entries.slice(0, MAX_ROWS);\n return (\n <section class={`section queue queue--${queue.name}`}>\n <QueueHead name={queue.name} total={queue.total} />\n {queue.total === 0 ? (\n <Empty>Empty.</Empty>\n ) : (\n <ol class=\"rows\" onKeyDown={listKeyDown} aria-label={`${QUEUE_LABEL[queue.name]}, next to run first`}>\n {entries.map((entry, i) => (\n <Row\n key={entry.item.id}\n fact={entry.from}\n subject={`${itemTitle(entry.item)} waits in ${QUEUE_LABEL[queue.name].toLowerCase()}`}\n tag={i === 0 ? (queue.name === 'io' ? 'oldest' : 'next') : undefined}\n first={i === 0}\n mapId={entry.at ?? itemMapId(entry.item)}\n meta={\n <>\n {entry.runs > 0 ? <span class=\"muted num\">ran {entry.runs}×</span> : null}\n <LocButton item={entry.item} />\n <span class=\"num muted\">since {formatMicros(entry.from.t)}</span>\n </>\n }\n >\n <ItemChip item={entry.item} queue={queue.name} />\n </Row>\n ))}\n <More shown={entries.length} total={queue.total} />\n </ol>\n )}\n {queue.leftAtEnd ? <LeftAtEnd what={queue.total === 1 ? 'this item' : 'these items'} /> : null}\n </section>\n );\n}\n\n/** \"due in 0.7 ms\": the one thing here that changes with every step, so it reads the time itself. */\nfunction Due({ timer }: { timer: TimerView }) {\n const dueIn = (timer.dueT - parts.t.value) / 1000;\n return (\n <span class=\"num due\">\n <FactMark fact={timer.dueFrom} subject={`when ${itemTitle(timer.item)} is due`} tabbable={false} />\n {dueIn >= 0 ? `due in ${formatMillis(dueIn)}` : `overdue by ${formatMillis(-dueIn)}`}\n </span>\n );\n}\n\nfunction timerMeta(timer: TimerView) {\n return (\n <>\n <LocButton item={timer.item} />\n <span class=\"num\">{formatMillis(timer.delayMs)}</span>\n {timer.state === 'waiting' ? <Due timer={timer} /> : null}\n {timer.lateMs !== null && timer.state !== 'waiting' ? (\n <span class=\"num due\">\n <FactMark fact={timer.dueFrom} subject={`how late ${itemTitle(timer.item)} ran`} tabbable={false} />\n ran {formatMillis(Math.max(0, timer.lateMs))} late\n </span>\n ) : null}\n </>\n );\n}\n\nfunction Timers() {\n const timers = parts.timers.value;\n if (!timers) return null;\n const active = timers.active.slice(0, MAX_ROWS);\n const recent = timers.recent.slice(-8).reverse();\n const waitingTotal = timers.counts.waiting + timers.counts.running;\n return (\n <section class=\"section queue queue--timers\">\n <QueueHead name=\"timers\" total={waitingTotal} />\n {active.length === 0 ? (\n <Empty>No timer is waiting.</Empty>\n ) : (\n <ol class=\"rows\" onKeyDown={listKeyDown} aria-label=\"Timers, soonest due first\">\n {active.map((timer, i) => (\n <Row\n key={timer.item.id}\n fact={timer.armed}\n subject={`${itemTitle(timer.item)} is ${timer.state === 'running' ? 'running' : 'waiting'}`}\n tag={timer.state === 'running' ? 'running' : i === 0 ? 'due first' : undefined}\n first={i === 0}\n mapId={itemMapId(timer.item)}\n meta={timerMeta(timer)}\n >\n <ItemChip item={timer.item} queue=\"timers\" />\n {timer.repeat ? <span class=\"muted\"> repeats</span> : null}\n </Row>\n ))}\n <More shown={active.length} total={waitingTotal} />\n </ol>\n )}\n {timers.leftAtEnd ? <LeftAtEnd what={waitingTotal === 1 ? 'this timer' : 'these timers'} /> : null}\n {timers.fired.count > 0 && timers.fired.last ? (\n <p class=\"note\">\n <FactMark fact={timers.fired.last.from} subject=\"Node's libuv timer came due\" />\n <span>\n Node's one libuv timer has come due {timers.fired.count} time{timers.fired.count === 1 ? '' : 's'}\n {timers.fired.last.lateMs !== null ? `; last time ${formatMillis(timers.fired.last.lateMs)} late` : ''}.\n </span>\n </p>\n ) : null}\n {recent.length > 0 ? (\n <details class=\"recent\">\n <summary>Finished or cleared ({timers.counts.done + timers.counts.cleared})</summary>\n <ol class=\"rows\" onKeyDown={listKeyDown} aria-label=\"Timers that ran or were cleared, latest first\">\n {recent.map((timer, i) => (\n <Row\n key={timer.item.id}\n fact={timer.cleared ?? timer.lastRun ?? timer.set}\n subject={`${itemTitle(timer.item)} ${timer.state === 'cleared' ? 'was cleared' : 'ran'}`}\n tag={timer.state === 'cleared' ? 'cleared' : 'ran'}\n first={i === 0}\n mapId={itemMapId(timer.item)}\n meta={timerMeta(timer)}\n >\n <ItemChip item={timer.item} queue=\"timers\" />\n </Row>\n ))}\n </ol>\n </details>\n ) : null}\n </section>\n );\n}\n\nfunction Elsewhere() {\n const pool = parts.queues.pool.value?.total ?? 0;\n return (\n <Section title=\"Elsewhere\">\n <p class=\"note\">\n <span class=\"mark-gap\" />\n <span>\n {pool} request{pool === 1 ? '' : 's'} with the thread pool: see the Thread pool panel. {parts.itemCount.value} async items seen so far.\n </span>\n </p>\n </Section>\n );\n}\n\nexport function QueuesPanel() {\n if (!hasRun.value) return <NoRun helper={helperMode.value} />;\n return (\n <div class=\"panel-scroll queues\">\n {QUEUES.map((name) => (name === 'timers' ? <Timers key={name} /> : <Queue key={name} name={name} />))}\n <Elsewhere />\n </div>\n );\n}\n","/**\n * Source: one file of Node's own source at the atlas commit, with the range of the opened\n * box highlighted and scrolled into view. The text is fetched on demand (stores/source.ts)\n * and shown read-only; without a connection the path, the lines and the links remain.\n */\nimport { GITHUB_DEV_NOTE } from '@nodejs-map/atlas-format';\nimport { CodeView } from '../editor/CodeView.tsx';\nimport { languageOfPath } from '../lib/sourceTarget.ts';\nimport { Icon } from '../shell/icons.tsx';\nimport { scriptUrlOfPath } from '../lib/breakpoints.ts';\nimport { atlas, helperMode, program, showOnMap, source, sourceMark } from '../stores/index.ts';\nimport { Empty } from './parts.tsx';\n\nexport function SourcePanel() {\n const target = source.target.value;\n const text = source.text.value;\n const state = atlas.state.value;\n\n if (!target) {\n return (\n <div class=\"panel-scroll source\">\n <Empty>\n Open a box on the map, a stack frame, an event or a rule citation to read its code here. When the program is stopped inside Node's own JavaScript, the file and the line are shown here by\n themselves. Node's source is not part of this app: it is fetched from GitHub at the exact commit of the Node.js version, when you open it.\n </Empty>\n </div>\n );\n }\n\n const lines = target.start !== null && target.end !== null ? (target.start === target.end ? `line ${target.start}` : `lines ${target.start}-${target.end}`) : null;\n // Breakpoints work in Node's own JavaScript too: the file key is the script's \"node:...\" name.\n const script = helperMode.value && target.path ? (target.scriptUrl ?? scriptUrlOfPath(target.path)) : null;\n const mark = sourceMark.value;\n return (\n <div class=\"source\">\n <header class=\"source__head\">\n <div class=\"source__title\">\n <h3 class=\"source__name\">{target.title}</h3>\n {target.atlasId ? (\n <button type=\"button\" class=\"ctl ctl--plain ctl--icon\" aria-label=\"Show on the map\" title=\"Show on the map\" onClick={() => target.atlasId && showOnMap(target.atlasId)}>\n <Icon name=\"map\" />\n </button>\n ) : null}\n </div>\n {target.description ? <p class=\"source__desc\">{target.description}</p> : null}\n {target.path ? (\n <p class=\"source__path mono\">\n {target.path}\n {lines ? <span class=\"muted\"> · {lines}</span> : null}\n {state.status === 'ready' ? <span class=\"muted\"> · Node {state.tag} @ {state.commit.slice(0, 10)}</span> : null}\n </p>\n ) : null}\n {target.variant ? <p class=\"source__variant mono muted\">when: {target.variant}</p> : null}\n <div class=\"source__bar\">\n {target.github ? (\n <a class=\"ctl ctl--plain\" href={target.github} target=\"_blank\" rel=\"noreferrer noopener\">\n <Icon name=\"external\" />\n <span>Open on GitHub</span>\n </a>\n ) : null}\n {target.githubDev ? (\n <a class=\"ctl ctl--plain\" href={target.githubDev} target=\"_blank\" rel=\"noreferrer noopener\" title={GITHUB_DEV_NOTE}>\n <Icon name=\"external\" />\n <span>\n Open in web editor <span class=\"muted\">(needs GitHub sign-in)</span>\n </span>\n </a>\n ) : null}\n </div>\n </header>\n {target.note ? <p class=\"callout callout--info\">{target.note}</p> : null}\n {text.status === 'loading' ? <Empty>Fetching the text...</Empty> : null}\n {text.status === 'unavailable' ? <p class=\"callout callout--warn\">{text.reason}</p> : null}\n {text.status === 'ready' && target.path ? (\n <>\n <CodeView\n text={text.text}\n language={languageOfPath(target.path)}\n readOnly={true}\n label={`Source of ${target.path}, read-only`}\n range={target.start !== null && target.end !== null ? { start: target.start, end: target.end } : null}\n lineMark={mark ? { line: mark.line, kind: mark.kind, tag: mark.tag } : null}\n breakpoints={script ? program.marksFor(script) : undefined}\n breakpointsActive={program.breakpointsActive.value}\n onToggleBreakpoint={script ? (line) => program.toggleBreakpoint(line, script) : undefined}\n revealKey={`${target.path}:${String(target.start)}:${String(target.line)}`}\n />\n <p class=\"source__from muted\">\n {text.from === 'program'\n ? 'Text read from the running program through the helper.'\n : 'Text fetched from raw.githubusercontent.com at this commit; it is kept in memory only.'}\n </p>\n </>\n ) : null}\n </div>\n );\n}\n","/**\n * Breakpoints, call stack and scopes: the debugger's sidebar.\n *\n * The Breakpoints list is like the one in DevTools: every breakpoint with its file and\n * line and the text of the line, a checkbox to switch one off without removing it, a\n * button to remove it, and \"remove all\". It is there with or without a run.\n *\n * The JavaScript stack exists only where the debugger paused (it is part of the\n * `debug.paused` event, so a recording has it too). Variables are different: they are\n * read from the paused program through the helper, so they exist only for the pause a\n * live run is in right now. All values arrive as text from the helper and are rendered\n * as text.\n */\nimport { useEffect, useState } from 'preact/hooks';\nimport type { Frame } from '@nodejs-map/event-format';\nimport type { ScopeInfo, ScopeVariable } from '@nodejs-map/protocol';\nimport type { DebugView } from '@nodejs-map/replay';\nimport { appliesTo, isNodeFile } from '../lib/breakpoints.ts';\nimport type { BreakpointEntry } from '../lib/breakpoints.ts';\nimport { baseName, itemTitle, oneLine } from '../lib/format.ts';\nimport { listKeyDown } from '../shell/hooks.ts';\nimport { Icon } from '../shell/icons.tsx';\nimport { FactMark } from '../shell/Mark.tsx';\nimport { connection, hasRun, helperMode, openFrame, openLoc, player, program, session, source, ui } from '../stores/index.ts';\nimport { Empty, ItemChip, LocButton, NoRun, Row, Section, itemMapId } from './parts.tsx';\n\nconst parts = player.parts;\n\nconst MAX_VARIABLES = 500;\nconst MAX_DEPTH = 8;\n\ntype Loaded<T> = { status: 'loading' } | { status: 'ready'; value: T } | { status: 'failed'; reason: string };\n\nfunction useRequest<T>(key: string, load: () => Promise<T>): Loaded<T> {\n const [state, setState] = useState<{ key: string; loaded: Loaded<T> }>({ key, loaded: { status: 'loading' } });\n useEffect(() => {\n let live = true;\n setState({ key, loaded: { status: 'loading' } });\n load().then(\n (value) => {\n if (live) setState({ key, loaded: { status: 'ready', value } });\n },\n (e: unknown) => {\n if (live) setState({ key, loaded: { status: 'failed', reason: e instanceof Error ? e.message : String(e) } });\n },\n );\n return () => {\n live = false;\n };\n // `load` is a fresh closure on every render; the key says when to run it again.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [key]);\n return state.key === key ? state.loaded : { status: 'loading' };\n}\n\nfunction Variables({ run, objectId, depth, pauseKey }: { run: string; objectId: string; depth: number; pauseKey: string }) {\n const loaded = useRequest<ScopeVariable[]>(`${pauseKey}|${objectId}`, async () => (await connection.request({ op: 'debug.props', run, objectId })).variables);\n if (loaded.status === 'loading') return <p class=\"vars__note muted\">Reading...</p>;\n if (loaded.status === 'failed') return <p class=\"vars__note warn-text\">Could not read the values: {loaded.reason}</p>;\n const all = loaded.value;\n if (all.length === 0) return <p class=\"vars__note muted\">Empty.</p>;\n return (\n <ul class=\"vars\">\n {all.slice(0, MAX_VARIABLES).map((v, i) => (\n <Variable key={`${i}:${v.name}`} run={run} variable={v} depth={depth} pauseKey={pauseKey} />\n ))}\n {all.length > MAX_VARIABLES ? <li class=\"vars__note muted\">and {all.length - MAX_VARIABLES} more that are not shown.</li> : null}\n </ul>\n );\n}\n\nfunction Variable({ run, variable, depth, pauseKey }: { run: string; variable: ScopeVariable; depth: number; pauseKey: string }) {\n const [open, setOpen] = useState(false);\n const expandable = variable.objectId !== undefined && depth < MAX_DEPTH;\n const body = (\n <>\n <span class=\"vars__name mono\">{oneLine(variable.name, 80)}</span>\n <span class=\"vars__sep\">: </span>\n <span class={`vars__value mono vars__value--${/^[a-z]+$/.test(variable.type) ? variable.type : 'other'}`}>{oneLine(variable.preview, 200)}</span>\n </>\n );\n return (\n <li class=\"vars__item\">\n {expandable ? (\n <button type=\"button\" class=\"vars__toggle\" aria-expanded={open ? 'true' : 'false'} onClick={() => setOpen(!open)}>\n <Icon name={open ? 'chevronDown' : 'chevronRight'} />\n {body}\n </button>\n ) : (\n <span class=\"vars__leaf\">{body}</span>\n )}\n {open && variable.objectId !== undefined ? <Variables run={run} objectId={variable.objectId} depth={depth + 1} pauseKey={pauseKey} /> : null}\n </li>\n );\n}\n\nfunction Scope({ run, scope, pauseKey, startOpen }: { run: string; scope: ScopeInfo; pauseKey: string; startOpen: boolean }) {\n const [open, setOpen] = useState(startOpen);\n return (\n <li class=\"scope\">\n <button type=\"button\" class=\"scope__head\" aria-expanded={open ? 'true' : 'false'} onClick={() => setOpen(!open)}>\n <Icon name={open ? 'chevronDown' : 'chevronRight'} />\n <span class=\"label\">{oneLine(scope.kind, 30)}</span>\n {scope.name ? <span class=\"mono muted\"> {oneLine(scope.name, 60)}</span> : null}\n </button>\n {open ? <Variables run={run} objectId={scope.objectId} depth={0} pauseKey={pauseKey} /> : null}\n </li>\n );\n}\n\nfunction Scopes({ debug, frame }: { debug: DebugView; frame: number }) {\n const run = player.tail.value.run;\n // Variables come from the program as it is paused right now: the player must be at the live end.\n const atEnd = parts.position.value === parts.length.value;\n const liveNow = session.kind.value === 'live' && session.liveStatus.value === 'paused' && atEnd && run !== null;\n const pauseKey = `${String(run)}|${debug.from?.index ?? -1}|${frame}`;\n if (!liveNow || run === null) {\n return (\n <Empty>\n {session.kind.value === 'recording'\n ? 'Variables are not part of a recording: they can be read only from a program that is paused right now.'\n : 'Variables can be read only at the pause the program is in right now. Move the player to the end of the run to see them.'}\n </Empty>\n );\n }\n return <ScopeList key={pauseKey} run={run} frame={frame} pauseKey={pauseKey} />;\n}\n\nfunction ScopeList({ run, frame, pauseKey }: { run: string; frame: number; pauseKey: string }) {\n const loaded = useRequest<ScopeInfo[]>(pauseKey, async () => (await connection.request({ op: 'debug.scopes', run, frame })).scopes);\n if (loaded.status === 'loading') return <Empty>Reading the scopes...</Empty>;\n if (loaded.status === 'failed') return <p class=\"empty warn-text\">Could not read the scopes: {loaded.reason}</p>;\n if (loaded.value.length === 0) return <Empty>This frame has no scopes.</Empty>;\n return (\n <ul class=\"scopes\">\n {loaded.value.map((scope, i) => (\n <Scope key={`${i}:${scope.objectId}`} run={run} scope={scope} pauseKey={pauseKey} startOpen={i === 0} />\n ))}\n </ul>\n );\n}\n\nfunction frameWhere(frame: Frame): string {\n return `${frame.origin === 'node' ? frame.loc.url : baseName(frame.loc.url)}:${frame.loc.line}`;\n}\n\nfunction PausedStack({ debug }: { debug: DebugView }) {\n const frames = debug.frames;\n const selected = Math.min(ui.frame.value, frames.length - 1);\n return (\n <>\n <Section title=\"Call stack\" count={frames.length} aside={<span class=\"muted\">paused: {debug.reason ?? 'unknown reason'}</span>}>\n <ol class=\"rows\" onKeyDown={listKeyDown} aria-label=\"JavaScript call stack, innermost first\">\n {frames.map((frame, i) => (\n <Row\n key={i}\n fact={debug.from}\n subject={`stack frame ${frame.fn || '(anonymous)'}`}\n selected={i === selected}\n first={i === 0}\n mapId={frame.at ?? null}\n tag={frame.origin === 'node' ? 'node' : frame.origin === 'other' ? 'other' : undefined}\n meta={<span class=\"mono muted\">{frameWhere(frame)}</span>}\n onActivate={() => {\n ui.frame.value = i;\n openFrame(frame);\n }}\n >\n <span class=\"mono\">{oneLine(frame.fn || '(anonymous)', 80)}</span>\n </Row>\n ))}\n </ol>\n </Section>\n <Section title={`Scopes of frame ${selected + 1}`}>\n <Scopes debug={debug} frame={selected} />\n </Section>\n </>\n );\n}\n\nfunction CallbackStack() {\n const stack = parts.main.value?.stack ?? [];\n return (\n <Section title=\"Callbacks on the main thread\" count={stack.length}>\n {stack.length === 0 ? (\n <Empty>No callback is running at this point.</Empty>\n ) : (\n <ol class=\"rows\" onKeyDown={listKeyDown} aria-label=\"Callbacks on the main thread, innermost first\">\n {[...stack].reverse().map((frame, i) => (\n <Row key={frame.from.index} fact={frame.from} subject={`the callback of ${itemTitle(frame.item)}`} first={i === 0} mapId={itemMapId(frame.item)} meta={<LocButton item={frame.item} />}>\n <ItemChip item={frame.item} queue={frame.queue} />\n </Row>\n ))}\n </ol>\n )}\n <p class=\"note\">\n <span class=\"mark-gap\" />\n <span>\n The JavaScript call stack is recorded only where the debugger pauses.{' '}\n {helperMode.value ? 'Click a line number to set a breakpoint, then press Run, to see it.' : 'This position is not a pause.'}\n </span>\n </p>\n </Section>\n );\n}\n\n/** The text of a breakpoint's line, when the page has the text of that file at hand. */\nfunction lineText(entry: BreakpointEntry, lines: readonly string[] | null, nodeLines: readonly string[] | null): string {\n const from = isNodeFile(entry.file) ? nodeLines : lines;\n return oneLine((from?.[entry.line - 1] ?? '').trim(), 120);\n}\n\nfunction Breakpoints() {\n const all = program.allBreakpoints.value;\n const active = program.breakpointsActive.value;\n const name = program.name.value;\n // Texts at hand: the program in the editor, and the Node file open in the Source panel.\n const lines = program.text.value.split('\\n');\n const target = source.target.value;\n const text = source.text.value;\n const nodeFile = target?.scriptUrl ?? null;\n const nodeLines = text.status === 'ready' ? text.text.split('\\n') : null;\n // What the helper said about a breakpoint it could not set (one in Node's own code added\n // while the program runs): shown next to that breakpoint, in the helper's words.\n const warnings = (parts.notes.value?.items ?? []).filter((n) => n.level === 'warn' && /breakpoint/i.test(n.text));\n return (\n <Section\n title=\"Breakpoints\"\n count={all.length}\n class=\"bps\"\n aside={\n all.length > 0 ? (\n <button type=\"button\" class=\"ctl ctl--plain bps__clear\" onClick={() => program.removeAllBreakpoints()}>\n Remove all\n </button>\n ) : null\n }\n >\n {all.length === 0 ? (\n <Empty>No breakpoints. Click a line number in the code to set one: Run then stops there, and you can step line by line.</Empty>\n ) : (\n <ul class=\"bps__list\" aria-label=\"Breakpoints\">\n {all.map((b) => {\n const mine = appliesTo(b, name);\n const where = `${b.file}:${b.line}`;\n const warning = warnings.findLast((n) => n.text.includes(`${b.file} line ${b.line}`));\n return (\n <li key={where} class={`bp${b.enabled && active ? '' : ' bp--off'}${warning ? ' bp--warned' : ''}`}>\n <input\n type=\"checkbox\"\n class=\"bp__on\"\n checked={b.enabled}\n aria-label={`Breakpoint at ${where}: on`}\n title={b.enabled ? 'Switch this breakpoint off without removing it' : 'Switch this breakpoint on'}\n onChange={(e) => program.setBreakpointEnabled(b.file, b.line, (e.currentTarget as HTMLInputElement).checked)}\n />\n <button\n type=\"button\"\n class=\"bp__where\"\n disabled={!mine}\n title={mine ? 'Show this line' : 'Kept for another program: it does not apply to the program in the editor'}\n onClick={() => openLoc({ url: b.file, line: b.line })}\n >\n <span class=\"bp__tag mono\">{where}</span>\n <span class=\"bp__text mono\">{mine ? lineText(b, lines, nodeFile === b.file ? nodeLines : null) : 'another program'}</span>\n </button>\n <button type=\"button\" class=\"ctl ctl--plain ctl--icon bp__remove\" aria-label={`Remove the breakpoint at ${where}`} title=\"Remove this breakpoint\" onClick={() => program.removeBreakpoint(b.file, b.line)}>\n <Icon name=\"close\" />\n </button>\n {warning ? (\n <p class=\"bp__note warn-text\" role=\"note\">\n {oneLine(warning.text, 400)}\n </p>\n ) : null}\n </li>\n );\n })}\n </ul>\n )}\n {!active && all.length > 0 ? (\n <p class=\"note\">\n <span class=\"mark-gap\" />\n <span>\n Breakpoints are deactivated: the program does not stop at them.{' '}\n <button type=\"button\" class=\"linklike\" onClick={() => program.setBreakpointsActive(true)}>\n Activate them\n </button>\n </span>\n </p>\n ) : null}\n </Section>\n );\n}\n\nexport function StackPanel() {\n const debug = parts.debug.value;\n const helper = helperMode.value;\n if (!hasRun.value || !debug) {\n return helper ? (\n <div class=\"panel-scroll stack\">\n <Breakpoints />\n <NoRun helper={true} />\n </div>\n ) : (\n <NoRun helper={false} />\n );\n }\n return (\n <div class=\"panel-scroll stack\">\n {helper ? <Breakpoints /> : null}\n {debug.paused ? (\n <PausedStack debug={debug} />\n ) : debug.gate.stopped ? (\n <>\n <p class=\"now__line\">\n <FactMark fact={debug.gate.from} subject=\"the program is stopped at a gate\" />\n <span>\n Stopped at the {debug.gate.gate ?? '?'} gate{debug.gate.phase ? ` (${debug.gate.phase} phase)` : ''}. No JavaScript is on the stack: the program is held inside Node, between\n JavaScript callbacks.\n </span>\n </p>\n <CallbackStack />\n </>\n ) : (\n <CallbackStack />\n )}\n </div>\n );\n}\n","/**\n * The tabbed panels. On a wide screen they sit under the editor; on a narrow one they are\n * the bottom sheet and the editor becomes one of the tabs (\"Code\").\n *\n * Tabs follow the WAI-ARIA tabs pattern: one tab stop, arrow keys move between tabs and\n * select them. Only the selected panel is rendered; panels keep their state in stores.\n */\nimport type { ComponentType } from 'preact';\nimport { useEffect, useLayoutEffect, useRef } from 'preact/hooks';\nimport { EditorPane } from '../editor/EditorPane.tsx';\nimport { EventsPanel } from '../panels/EventsPanel.tsx';\nimport { LessonsPanel } from '../panels/LessonsPanel.tsx';\nimport { NowPanel } from '../panels/NowPanel.tsx';\nimport { OutputPanel } from '../panels/OutputPanel.tsx';\nimport { PoolPanel } from '../panels/PoolPanel.tsx';\nimport { QueuesPanel } from '../panels/QueuesPanel.tsx';\nimport { SourcePanel } from '../panels/SourcePanel.tsx';\nimport { StackPanel } from '../panels/StackPanel.tsx';\nimport { helperMode, player, settings, showTab, ui } from '../stores/index.ts';\nimport type { TabId } from '../stores/settings.ts';\nimport { AreaClose } from './ViewMenu.tsx';\n\ninterface TabDef {\n id: TabId;\n label: string;\n panel: ComponentType;\n /** A small count next to the label. */\n badge?: () => number | null;\n}\n\nconst TABS: readonly TabDef[] = [\n { id: 'code', label: 'Code', panel: EditorPane },\n { id: 'now', label: 'Now', panel: NowPanel },\n { id: 'stack', label: 'Stack', panel: StackPanel },\n {\n id: 'queues',\n label: 'Queues',\n panel: QueuesPanel,\n badge: () => {\n const q = player.parts.queues;\n const n = (name: 'nextTick' | 'microtask' | 'timers' | 'immediate' | 'io' | 'close'): number => q[name].value?.total ?? 0;\n return n('nextTick') + n('microtask') + n('timers') + n('immediate') + n('io') + n('close');\n },\n },\n { id: 'pool', label: 'Thread pool', panel: PoolPanel, badge: () => player.parts.queues.pool.value?.total ?? null },\n { id: 'output', label: 'Output', panel: OutputPanel, badge: () => player.parts.output.value?.total ?? null },\n { id: 'events', label: 'Events', panel: EventsPanel },\n { id: 'source', label: 'Source', panel: SourcePanel },\n { id: 'lessons', label: 'Lessons', panel: LessonsPanel },\n];\n\n/** The tabs on show, in order. The editor is a tab only in the narrow layout. */\nexport function visibleTabs(narrow: boolean): readonly TabDef[] {\n return narrow ? TABS : TABS.filter((t) => t.id !== 'code');\n}\n\nexport function Panels() {\n const narrow = ui.narrow.value;\n const tabs = visibleTabs(narrow);\n const helper = helperMode.value;\n const wanted = settings.tab.value;\n const active = tabs.find((t) => t.id === wanted) ?? (tabs.find((t) => t.id === 'now') as TabDef);\n const Panel = active.panel;\n\n // Keep the selected tab fully inside the strip, and mark the edges the strip can still\n // scroll towards (they are faded, so that a cut-off tab reads as \"more this way\").\n const strip = useRef<HTMLDivElement>(null);\n // A count is drawn only when it is above zero; its width depends on its number of digits.\n const widths = tabs.map((t) => { const n = t.badge?.() ?? 0; return n > 0 ? String(Math.min(n, 1000)).length : 0; }).join('');\n const markEdges = (): void => {\n const el = strip.current;\n if (!el) return;\n el.classList.toggle('can-left', el.scrollLeft > 2);\n el.classList.toggle('can-right', el.scrollLeft + el.clientWidth < el.scrollWidth - 2);\n };\n useLayoutEffect(() => {\n const el = strip.current;\n const tab = el?.querySelector<HTMLElement>(`#tab-${active.id}`);\n if (el && tab) {\n // The strip's own scroll position only: scrollIntoView could move the page as well.\n const pad = 24;\n if (tab.offsetLeft - pad < el.scrollLeft) el.scrollLeft = Math.max(0, tab.offsetLeft - pad);\n else if (tab.offsetLeft + tab.offsetWidth + pad > el.scrollLeft + el.clientWidth) el.scrollLeft = tab.offsetLeft + tab.offsetWidth + pad - el.clientWidth;\n }\n markEdges();\n // The counts on the tabs change their widths (a count appears, or gains a digit): then too.\n }, [active.id, narrow, tabs.length, widths]);\n useEffect(() => {\n const el = strip.current;\n if (!el) return;\n const observer = new ResizeObserver(markEdges);\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n\n const onKeyDown = (e: KeyboardEvent): void => {\n const at = tabs.indexOf(active);\n let next = -1;\n if (e.key === 'ArrowRight') next = (at + 1) % tabs.length;\n else if (e.key === 'ArrowLeft') next = (at - 1 + tabs.length) % tabs.length;\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = tabs.length - 1;\n if (next < 0) return;\n e.preventDefault();\n e.stopPropagation();\n const tab = tabs[next] as TabDef;\n showTab(tab.id);\n (e.currentTarget as HTMLElement).querySelector<HTMLElement>(`#tab-${tab.id}`)?.focus();\n };\n\n return (\n <section class={`panels${narrow ? ' panels--sheet' : ''}`} aria-label=\"Panels\">\n <div class=\"panels__bar\">\n <div class=\"tabs\" role=\"tablist\" aria-label=\"Panels\" ref={strip} onKeyDown={onKeyDown} onScroll={markEdges}>\n {tabs.map((tab) => {\n const selected = tab.id === active.id;\n const count = tab.badge?.() ?? null;\n const label = tab.id === 'lessons' && helper ? 'Examples' : tab.label;\n return (\n <button\n key={tab.id}\n id={`tab-${tab.id}`}\n type=\"button\"\n role=\"tab\"\n class={`tab${selected ? ' is-selected' : ''}`}\n aria-selected={selected ? 'true' : 'false'}\n aria-controls=\"tabpanel\"\n tabIndex={selected ? 0 : -1}\n onClick={() => showTab(tab.id)}\n >\n {label}\n {count !== null && count > 0 ? <span class=\"tab__count num\">{count > 999 ? '999+' : count}</span> : null}\n </button>\n );\n })}\n </div>\n <AreaClose area=\"panels\" />\n </div>\n <div id=\"tabpanel\" class=\"panels__body\" role=\"tabpanel\" aria-labelledby={`tab-${active.id}`}>\n <Panel />\n </div>\n </section>\n );\n}\n","/**\n * A draggable divider between two panes. Works with mouse, touch and keyboard (arrow keys\n * move it by 2%, Home and End go to the limits). The position is a fraction of the\n * container given to the first pane; the parent stores it in the settings.\n */\nimport type { Signal } from '@preact/signals';\nimport { SPLIT_MAX, SPLIT_MIN } from '../stores/settings.ts';\n\nexport interface SplitterProps {\n /** x: the divider is a vertical bar between left and right. y: a horizontal bar between top and bottom. */\n axis: 'x' | 'y';\n value: Signal<number>;\n label: string;\n min?: number;\n max?: number;\n class?: string;\n}\n\nexport function Splitter({ axis, value, label, min = SPLIT_MIN, max = SPLIT_MAX, class: extra }: SplitterProps) {\n const clamp = (v: number): number => Math.min(max, Math.max(min, v));\n const fromPointer = (e: PointerEvent): void => {\n const bar = e.currentTarget as HTMLElement;\n const container = bar.parentElement;\n if (!container) return;\n const rect = container.getBoundingClientRect();\n const fraction = axis === 'x' ? (e.clientX - rect.left) / rect.width : (e.clientY - rect.top) / rect.height;\n if (Number.isFinite(fraction)) value.value = clamp(fraction);\n };\n\n return (\n <div\n class={`splitter splitter--${axis}${extra ? ` ${extra}` : ''}`}\n role=\"separator\"\n tabIndex={0}\n aria-orientation={axis === 'x' ? 'vertical' : 'horizontal'}\n aria-label={label}\n aria-valuemin={Math.round(min * 100)}\n aria-valuemax={Math.round(max * 100)}\n aria-valuenow={Math.round(value.value * 100)}\n onPointerDown={(e) => {\n if (e.button !== 0) return;\n (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n e.preventDefault();\n }}\n onPointerMove={(e) => {\n if ((e.currentTarget as HTMLElement).hasPointerCapture(e.pointerId)) fromPointer(e);\n }}\n onKeyDown={(e) => {\n const back = axis === 'x' ? 'ArrowLeft' : 'ArrowUp';\n const forward = axis === 'x' ? 'ArrowRight' : 'ArrowDown';\n let next: number | null = null;\n if (e.key === back) next = value.value - 0.04;\n else if (e.key === forward) next = value.value + 0.04;\n else if (e.key === 'Home') next = min;\n else if (e.key === 'End') next = max;\n if (next === null) return;\n e.preventDefault();\n e.stopPropagation();\n value.value = clamp(next);\n }}\n />\n );\n}\n","/**\n * The screen. Wide: the map on the left, the editor over the tabbed panels on the right,\n * the transport bar along the bottom, a slim bar on top. Narrow (phones): the map on top,\n * the panels as a bottom sheet, the transport bar pinned below.\n *\n * Both layouts render the same components; the difference is CSS plus where the editor\n * lives (its own pane, or the \"Code\" tab).\n */\nimport type { ComponentType } from 'preact';\nimport { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';\nimport { EditorPane } from '../editor/EditorPane.tsx';\nimport { matchShortcut } from '../lib/shortcuts.ts';\nimport type { ShortcutId } from '../lib/shortcuts.ts';\nimport { changeSpeed, helperMode, layout as layoutStore, learn, player, program, session, settings, showActionOnMap, showTab, step, toggleTheme, ui } from '../stores/index.ts';\nimport { Transport } from '../transport/Transport.tsx';\nimport { Banners } from './Banners.tsx';\nimport { Dialogs, useDropToOpen } from './Dialogs.tsx';\nimport { MapRegion } from './MapRegion.tsx';\nimport { Panels, visibleTabs } from './Panels.tsx';\nimport { SHEET_MAX, SHEET_MIN } from '../stores/settings.ts';\nimport { Splitter } from './Splitter.tsx';\nimport { TopBar } from './TopBar.tsx';\nimport { RestoreStrip, toggleArea } from './ViewMenu.tsx';\n\nfunction isTyping(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n // The code editor is in a shadow root: its events arrive retargeted to the host element.\n if (target.isContentEditable || target.closest('.code__cm')) return true;\n const tag = target.tagName;\n if (tag === 'TEXTAREA' || tag === 'SELECT') return true;\n if (tag === 'INPUT') {\n const type = (target as HTMLInputElement).type;\n return type !== 'checkbox' && type !== 'radio' && type !== 'button' && type !== 'file';\n }\n return false;\n}\n\nfunction run(id: ShortcutId): void {\n switch (id) {\n case 'player.toggle':\n return player.command({ do: 'toggle' });\n case 'player.stepForward':\n return step('step', 1);\n case 'player.stepBack':\n return step('step', -1);\n case 'player.eventForward':\n return step('event', 1);\n case 'player.eventBack':\n return step('event', -1);\n case 'player.callbackForward':\n return step('callback', 1);\n case 'player.callbackBack':\n return step('callback', -1);\n case 'player.phaseForward':\n return step('phase', 1);\n case 'player.phaseBack':\n return step('phase', -1);\n case 'player.turnForward':\n return step('turn', 1);\n case 'player.turnBack':\n return step('turn', -1);\n case 'player.outputForward':\n return step('output', 1);\n case 'player.outputBack':\n return step('output', -1);\n case 'player.pauseForward':\n return step('pause', 1);\n case 'player.pauseBack':\n return step('pause', -1);\n case 'player.start':\n return player.command({ do: 'seek', position: 0 });\n case 'player.end':\n return player.command({ do: 'seek', position: player.player.value?.length ?? 0 });\n case 'player.slower':\n return changeSpeed(-1);\n case 'player.faster':\n return changeSpeed(1);\n case 'player.followLive':\n return player.command({ do: 'follow', on: !(player.player.value?.follow ?? false) });\n case 'view.followAction':\n settings.moveMap.value = !settings.moveMap.value;\n session.announce(settings.moveMap.value ? 'The map now moves with the run.' : 'The map no longer moves with the run.');\n return;\n case 'view.showOnMap':\n return showActionOnMap();\n case 'run.run':\n return void session.start();\n case 'run.stop':\n return void session.stop();\n case 'debug.pauseResume':\n return void session.pauseOrResume();\n case 'debug.stepOver':\n return void session.debug('stepOver');\n case 'debug.stepInto':\n return void session.debug('stepInto');\n case 'debug.stepOut':\n return void session.debug('stepOut');\n case 'debug.toggleBreakpoints': {\n const active = !program.breakpointsActive.value;\n program.setBreakpointsActive(active);\n session.announce(active ? 'Breakpoints activated.' : 'Breakpoints deactivated: the program will not stop at them.');\n return;\n }\n case 'view.legend':\n ui.dialog.value = 'legend';\n return;\n case 'view.help':\n ui.dialog.value = 'help';\n return;\n case 'view.theme':\n return toggleTheme();\n case 'layout.map':\n return toggleArea('map');\n case 'layout.code':\n return toggleArea('code');\n case 'layout.panels':\n return toggleArea('panels');\n case 'layout.playback':\n return toggleArea('playback');\n default: {\n const n = Number(id.slice('view.tab'.length));\n const tab = visibleTabs(ui.narrow.value)[n - 1];\n if (tab) showTab(tab.id);\n }\n }\n}\n\nfunction useShortcuts(): void {\n useEffect(() => {\n const onKey = (e: KeyboardEvent): void => {\n if (e.defaultPrevented || e.isComposing) return;\n // While a dialog is open the keys belong to it (Escape closes it natively).\n if (document.querySelector('dialog[open]')) return;\n // The Learn page is for reading: its keys scroll and follow links, they do not play a run.\n if (learn.route.value.view === 'learn') return;\n const target = e.target;\n // Space and Enter on a focused button must press the button, not play the recording.\n if ((e.key === ' ' || e.key === 'Enter') && target instanceof HTMLElement && target.closest('button, a, summary, [role=\"tab\"], [role=\"slider\"], [role=\"separator\"], input, select')) {\n if (!(e.ctrlKey || e.metaKey)) return;\n }\n const id = matchShortcut(e, isTyping(target), helperMode.value);\n if (!id) return;\n e.preventDefault();\n run(id);\n };\n addEventListener('keydown', onKey);\n return () => removeEventListener('keydown', onKey);\n }, []);\n}\n\n/** The hint strip: why the control under focus, pointer or finger is off. */\nfunction Hint() {\n const hint = ui.hint.value;\n useEffect(() => {\n if (!hint) return;\n const timer = setTimeout(() => {\n if (ui.hint.value === hint) ui.hint.value = null;\n }, 8000);\n return () => clearTimeout(timer);\n }, [hint]);\n if (!hint) return null;\n return <p class=\"hint\">{hint}</p>;\n}\n\n/** The Learn page, loaded as its own chunk the first time it is opened. */\nlet learnModule: Promise<{ LearnView: ComponentType }> | null = null;\nfunction LearnSlot() {\n const [View, setView] = useState<ComponentType | null>(null);\n const [failed, setFailed] = useState(false);\n useEffect(() => {\n let live = true;\n learnModule ??= import('../learn/LearnView.tsx');\n learnModule.then(\n (m) => {\n if (live) setView(() => m.LearnView);\n },\n () => {\n learnModule = null;\n if (live) setFailed(true);\n },\n );\n return () => {\n live = false;\n };\n }, []);\n return (\n <div class=\"learn-slot\">\n {View ? <View /> : <p class=\"empty\">{failed ? 'The Learn page could not be loaded. Reload the page to try again.' : 'Loading the Learn page...'}</p>}\n </div>\n );\n}\n\nexport function App() {\n const narrow = ui.narrow.value;\n const learning = learn.route.value.view === 'learn';\n const layout = useRef<HTMLDivElement>(null);\n const side = useRef<HTMLDivElement>(null);\n const splitMap = settings.splitMap.value;\n const splitEditor = settings.splitEditor.value;\n const splitSheet = settings.splitSheet.value;\n useShortcuts();\n useDropToOpen();\n\n // Split positions are numbers that change while dragging: set as custom properties\n // through the CSSOM (a style attribute would need 'unsafe-inline' in the CSP).\n useLayoutEffect(() => {\n layout.current?.style.setProperty('--split-map', String(splitMap));\n layout.current?.style.setProperty('--split-sheet', String(splitSheet));\n side.current?.style.setProperty('--split-editor', String(splitEditor));\n }, [splitMap, splitEditor, splitSheet, narrow]);\n\n // Hidden areas stay mounted (display: none): the map, the editor and the panels keep\n // their state, and come back as they were. A restore strip takes the hidden area's edge.\n const shown = layoutStore.shown.value;\n const noSide = !shown.code && !shown.panels;\n const layoutClass = `layout${shown.map ? '' : ' layout--nomap'}${narrow ? (shown.panels ? '' : ' layout--nopanels') : noSide ? ' layout--noside' : ''}`;\n const sideClass = `side${shown.code ? '' : ' side--nocode'}${shown.panels ? '' : ' side--nopanels'}`;\n\n return (\n <div class={`app${narrow ? ' app--narrow' : ''}${learning ? ' app--learn' : ''}${shown.playback ? '' : ' app--noplayback'}`}>\n {learning || !shown.panels ? null : (\n <a class=\"skip\" href=\"#tabpanel\">\n Skip to the panels\n </a>\n )}\n <TopBar />\n <Banners />\n {learning ? <LearnSlot /> : null}\n {/* The main view stays mounted behind the Learn page: the map, the editor and the run keep their state. */}\n <div class={layoutClass} ref={layout} hidden={learning}>\n <MapRegion />\n {shown.map ? null : <RestoreStrip area=\"map\" vertical={!narrow} />}\n {narrow ? (\n <>\n <Splitter axis=\"y\" value={settings.splitSheet} min={SHEET_MIN} max={SHEET_MAX} class=\"splitter--sheet\" label=\"Drag to give the panels more or less height\" />\n <Panels />\n {shown.panels ? null : <RestoreStrip area=\"panels\" />}\n </>\n ) : (\n <>\n <Splitter axis=\"x\" value={settings.splitMap} class=\"splitter--map\" label=\"Resize the map and the side panels\" />\n <div class={sideClass} ref={side}>\n {shown.code ? null : <RestoreStrip area=\"code\" />}\n <EditorPane />\n <Splitter axis=\"y\" value={settings.splitEditor} class=\"splitter--editor\" label=\"Resize the editor and the panels\" />\n <Panels />\n {shown.panels ? null : <RestoreStrip area=\"panels\" />}\n </div>\n {noSide ? (\n <div class=\"restore-col\">\n <RestoreStrip area=\"code\" vertical />\n <RestoreStrip area=\"panels\" vertical />\n </div>\n ) : null}\n </>\n )}\n </div>\n {learning ? null : <Hint />}\n <Transport />\n {shown.playback || learning ? null : <RestoreStrip area=\"playback\" />}\n <p class=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {session.announcement.value}\n </p>\n <Dialogs />\n </div>\n );\n}\n","/**\n * Entry point. Order matters for the first paint: render the shell first (it needs only\n * this bundle), then read config.json and start the mode it names. CodeMirror, the map\n * panel and the atlas arrive later as their own chunks; the worker starts on its own\n * thread.\n */\nimport { render } from 'preact';\nimport { milestone } from './lib/marks.ts';\nimport { App } from './shell/App.tsx';\nimport { boot } from './stores/index.ts';\n\nmilestone('script');\nconst root = document.getElementById('app');\nif (root) {\n root.textContent = '';\n render(<App />, root);\n milestone('rendered');\n void boot();\n}\n"],"ignoreList":[0,2,3,12,13],"mappings":";AAAA,IAAIA,EAAEC,EAAEC,EAAEC,EAAEC,EAAEC,EAAEC,EAAEC,EAAEC,EAAEC,EAAEC,EAAIC,EAAE,OAAO,IAAI,IAAI,EAAEC,EAAE,CAAC,EAAEC,EAAE,CAAC,EAAEC,EAAE,0BAA0BC,EAAE,MAAM,QAAQC,EAAEH,EAAE,MAAMI,EAAE,OAAO,OAAO,SAASC,EAAEC,EAAE,CAACA,GAAGA,EAAE,YAAYA,EAAE,OAAO,CAAC,CAAC,SAASC,EAAED,EAAE,EAAEE,EAAE,CAAC,IAAIC,EAAE,EAAEC,EAAE,EAAE,CAAC,EAAEC,EAAE,UAAU,OAAO,IAAID,KAAK,EAASA,GAAP,MAASD,EAAE,EAAEC,GAAUA,GAAP,OAAsB,OAAOJ,GAAnB,WAAqB,EAAE,EAAEI,GAAG,EAAEA,GAAG,EAAEA,GAAG,OAAOC,EAAE,IAAI,EAAE,SAASA,EAAE,EAAER,EAAE,KAAK,UAAU,CAAC,EAAEK,GAAGI,EAAEN,EAAE,EAAEG,EAAE,EAAE,IAAI,CAAC,CAA0P,SAASG,EAAEJ,EAAEC,EAAE,EAAEC,EAAE,EAAE,CAAC,IAAIC,EAAE,CAAC,KAAKH,EAAE,MAAMC,EAAE,IAAI,EAAE,IAAIC,EAAE,IAAI,KAAK,GAAG,KAAK,IAAI,EAAE,IAAI,KAAK,IAAI,KAAK,YAAYZ,EAAE,IAAI,GAAG,EAAEV,EAAE,IAAI,GAAG,IAAI,CAAC,EAAE,MAAM,CAAC,GAAGD,EAAE,OAAOA,EAAE,MAAMwB,CAAC,EAAEA,CAAC,CAAmC,SAASE,EAAEP,EAAE,CAAC,OAAOA,EAAE,QAAQ,CAAC,SAASQ,EAAER,EAAE,EAAE,CAAC,KAAK,MAAMA,EAAE,KAAK,QAA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