@mountaya/studio 0.0.0-stage → 0.2.0

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 (521) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +917 -2
  5. package/dist/agent/index.cjs +2600 -0
  6. package/dist/agent/index.cjs.map +1 -0
  7. package/dist/agent/index.d.cts +1237 -0
  8. package/dist/agent/index.d.ts +1237 -0
  9. package/dist/agent/index.js +2581 -0
  10. package/dist/agent/index.js.map +1 -0
  11. package/dist/chunk-3Oi_Zrtm.js +9 -0
  12. package/dist/chunk-3Oi_Zrtm.js.map +1 -0
  13. package/dist/chunk-B18OPIu_.js +6 -0
  14. package/dist/chunk-B18OPIu_.js.map +1 -0
  15. package/dist/chunk-B5Uz3Qct.cjs +15 -0
  16. package/dist/chunk-B5Uz3Qct.cjs.map +1 -0
  17. package/dist/chunk-BBEJwkd3.d.cts +839 -0
  18. package/dist/chunk-BIEc_SkR.cjs +29 -0
  19. package/dist/chunk-BIEc_SkR.cjs.map +1 -0
  20. package/dist/chunk-BKMFOe-N.js +171 -0
  21. package/dist/chunk-BKMFOe-N.js.map +1 -0
  22. package/dist/chunk-BP4uy7E1.d.ts +11583 -0
  23. package/dist/chunk-BSHTsFiB.js +1403 -0
  24. package/dist/chunk-BSHTsFiB.js.map +1 -0
  25. package/dist/chunk-BTUUABGI.js +17 -0
  26. package/dist/chunk-BTUUABGI.js.map +1 -0
  27. package/dist/chunk-BaPiaz5X.cjs +115 -0
  28. package/dist/chunk-BaPiaz5X.cjs.map +1 -0
  29. package/dist/chunk-BeCVpkYr.cjs +542 -0
  30. package/dist/chunk-BeCVpkYr.cjs.map +1 -0
  31. package/dist/chunk-BgngsvK8.cjs +6202 -0
  32. package/dist/chunk-BgngsvK8.cjs.map +1 -0
  33. package/dist/chunk-BhInd7CJ.d.cts +253 -0
  34. package/dist/chunk-Bn6ZbxkS.cjs +27 -0
  35. package/dist/chunk-By9ZnkVI.js +60 -0
  36. package/dist/chunk-By9ZnkVI.js.map +1 -0
  37. package/dist/chunk-BzqPhxsz.cjs +367 -0
  38. package/dist/chunk-BzqPhxsz.cjs.map +1 -0
  39. package/dist/chunk-C2mMX81q.d.ts +443 -0
  40. package/dist/chunk-C2rr9Q0V.cjs +1402 -0
  41. package/dist/chunk-C2rr9Q0V.cjs.map +1 -0
  42. package/dist/chunk-CDJCbwIQ.d.cts +78 -0
  43. package/dist/chunk-CLGvBOVH.d.cts +1654 -0
  44. package/dist/chunk-COdw1dc6.d.ts +525 -0
  45. package/dist/chunk-CQCJnT2i.d.ts +511 -0
  46. package/dist/chunk-CSyHY67q.cjs +353 -0
  47. package/dist/chunk-CSyHY67q.cjs.map +1 -0
  48. package/dist/chunk-CiK1Iqrv.js +950 -0
  49. package/dist/chunk-CiK1Iqrv.js.map +1 -0
  50. package/dist/chunk-CmJBgSwZ.cjs +24 -0
  51. package/dist/chunk-CmJBgSwZ.cjs.map +1 -0
  52. package/dist/chunk-CnrsRK2u.cjs +83 -0
  53. package/dist/chunk-CnrsRK2u.cjs.map +1 -0
  54. package/dist/chunk-Co782_9r.js +326 -0
  55. package/dist/chunk-Co782_9r.js.map +1 -0
  56. package/dist/chunk-Csr3KDpZ.cjs +32 -0
  57. package/dist/chunk-Csr3KDpZ.cjs.map +1 -0
  58. package/dist/chunk-CwkmccXv.js +89 -0
  59. package/dist/chunk-CwkmccXv.js.map +1 -0
  60. package/dist/chunk-D0Q4iL9B.cjs +255 -0
  61. package/dist/chunk-D0Q4iL9B.cjs.map +1 -0
  62. package/dist/chunk-DFwiSzUS.cjs +72 -0
  63. package/dist/chunk-DFwiSzUS.cjs.map +1 -0
  64. package/dist/chunk-DIFayl2P.d.cts +443 -0
  65. package/dist/chunk-DIGF58ux.d.cts +525 -0
  66. package/dist/chunk-DKuuuld5.js +101 -0
  67. package/dist/chunk-DKuuuld5.js.map +1 -0
  68. package/dist/chunk-DMePkFEo.js +5054 -0
  69. package/dist/chunk-DMePkFEo.js.map +1 -0
  70. package/dist/chunk-DO5SIBgu.js +305 -0
  71. package/dist/chunk-DO5SIBgu.js.map +1 -0
  72. package/dist/chunk-DOQ_7eE5.d.ts +6662 -0
  73. package/dist/chunk-DThaaNeb.d.cts +15 -0
  74. package/dist/chunk-DThaaNeb.d.ts +15 -0
  75. package/dist/chunk-DUQzjUJy.d.ts +78 -0
  76. package/dist/chunk-DX37IPhV.cjs +1903 -0
  77. package/dist/chunk-DX37IPhV.cjs.map +1 -0
  78. package/dist/chunk-Damps5Tk.cjs +155 -0
  79. package/dist/chunk-Damps5Tk.cjs.map +1 -0
  80. package/dist/chunk-DbK5PhpJ.d.ts +1654 -0
  81. package/dist/chunk-De0vAASv.d.ts +253 -0
  82. package/dist/chunk-DhSZ7YZt.d.cts +6662 -0
  83. package/dist/chunk-DjEvqvPA.cjs +43 -0
  84. package/dist/chunk-DjEvqvPA.cjs.map +1 -0
  85. package/dist/chunk-DkwDzwvu.d.cts +121 -0
  86. package/dist/chunk-DkwDzwvu.d.ts +121 -0
  87. package/dist/chunk-Dmszv9If.js +71 -0
  88. package/dist/chunk-Dmszv9If.js.map +1 -0
  89. package/dist/chunk-Dp_ftNWY.d.cts +511 -0
  90. package/dist/chunk-DsHQySz0.js +31 -0
  91. package/dist/chunk-DsHQySz0.js.map +1 -0
  92. package/dist/chunk-DwoUyHHh.js +281 -0
  93. package/dist/chunk-DwoUyHHh.js.map +1 -0
  94. package/dist/chunk-IaIDQflj.d.cts +2315 -0
  95. package/dist/chunk-IaIDQflj.d.ts +2315 -0
  96. package/dist/chunk-cVXLsZfL.d.ts +839 -0
  97. package/dist/chunk-mIaCX9EJ.d.cts +11583 -0
  98. package/dist/chunk-nJQxbOwQ.cjs +8962 -0
  99. package/dist/chunk-nJQxbOwQ.cjs.map +1 -0
  100. package/dist/chunk-o9jaxhCO.js +8852 -0
  101. package/dist/chunk-o9jaxhCO.js.map +1 -0
  102. package/dist/chunk-p-Tt_Lwz.js +14 -0
  103. package/dist/chunk-p-Tt_Lwz.js.map +1 -0
  104. package/dist/engines/index.cjs +2091 -0
  105. package/dist/engines/index.cjs.map +1 -0
  106. package/dist/engines/index.d.cts +2176 -0
  107. package/dist/engines/index.d.ts +2176 -0
  108. package/dist/engines/index.js +2075 -0
  109. package/dist/engines/index.js.map +1 -0
  110. package/dist/handlers/index.cjs +53 -0
  111. package/dist/handlers/index.cjs.map +1 -0
  112. package/dist/handlers/index.d.cts +403 -0
  113. package/dist/handlers/index.d.ts +403 -0
  114. package/dist/handlers/index.js +33 -0
  115. package/dist/handlers/index.js.map +1 -0
  116. package/dist/index.cjs +3511 -0
  117. package/dist/index.cjs.map +1 -0
  118. package/dist/index.d.cts +8 -0
  119. package/dist/index.d.ts +8 -0
  120. package/dist/index.js +3033 -0
  121. package/dist/index.js.map +1 -0
  122. package/dist/plugins/index.cjs +510 -0
  123. package/dist/plugins/index.cjs.map +1 -0
  124. package/dist/plugins/index.d.cts +296 -0
  125. package/dist/plugins/index.d.ts +296 -0
  126. package/dist/plugins/index.js +489 -0
  127. package/dist/plugins/index.js.map +1 -0
  128. package/dist/seams/index.cjs +89 -0
  129. package/dist/seams/index.cjs.map +1 -0
  130. package/dist/seams/index.d.cts +452 -0
  131. package/dist/seams/index.d.ts +452 -0
  132. package/dist/seams/index.js +49 -0
  133. package/dist/seams/index.js.map +1 -0
  134. package/dist/strings/fr/index.cjs +2135 -0
  135. package/dist/strings/fr/index.cjs.map +1 -0
  136. package/dist/strings/fr/index.d.cts +17 -0
  137. package/dist/strings/fr/index.d.ts +17 -0
  138. package/dist/strings/fr/index.js +2130 -0
  139. package/dist/strings/fr/index.js.map +1 -0
  140. package/dist/strings/index.cjs +2384 -0
  141. package/dist/strings/index.cjs.map +1 -0
  142. package/dist/strings/index.d.cts +3 -0
  143. package/dist/strings/index.d.ts +3 -0
  144. package/dist/strings/index.js +2353 -0
  145. package/dist/strings/index.js.map +1 -0
  146. package/dist/testing/index.cjs +230 -0
  147. package/dist/testing/index.cjs.map +1 -0
  148. package/dist/testing/index.d.cts +246 -0
  149. package/dist/testing/index.d.ts +246 -0
  150. package/dist/testing/index.js +219 -0
  151. package/dist/testing/index.js.map +1 -0
  152. package/dist/time/index.cjs +28 -0
  153. package/dist/time/index.cjs.map +1 -0
  154. package/dist/time/index.d.cts +41 -0
  155. package/dist/time/index.d.ts +41 -0
  156. package/dist/time/index.js +23 -0
  157. package/dist/time/index.js.map +1 -0
  158. package/package.json +224 -4
  159. package/src/agent/engines/agentThreads.ts +1601 -0
  160. package/src/agent/engines/directorChat.ts +500 -0
  161. package/src/agent/index.ts +67 -0
  162. package/src/agent/rules/agentEditLock.ts +115 -0
  163. package/src/agent/rules/agentErrorCopy.ts +44 -0
  164. package/src/agent/rules/copilotOrganization.ts +36 -0
  165. package/src/agent/rules/playbook.gen.ts +444 -0
  166. package/src/agent/rules/router.ts +518 -0
  167. package/src/agent/rules/stateDelta.ts +29 -0
  168. package/src/agent/rules/studioRouter.ts +123 -0
  169. package/src/agent/rules/surfaces.gen.ts +633 -0
  170. package/src/agent/rules/threadsUrl.ts +48 -0
  171. package/src/agent/rules/transcriptObserver.ts +90 -0
  172. package/src/agent/stores/agentThreads.ts +451 -0
  173. package/src/bus/contracts/noData.ts +18 -0
  174. package/src/bus/contracts/shared.ts +172 -0
  175. package/src/bus/contracts/studioTools.ts +224 -0
  176. package/src/bus/rules/bus.ts +857 -0
  177. package/src/bus/rules/confirmation.ts +22 -0
  178. package/src/bus/rules/defineRegistry.ts +24 -0
  179. package/src/bus/rules/errors.ts +401 -0
  180. package/src/bus/rules/handlerErrors.ts +103 -0
  181. package/src/bus/rules/handlerRegistry.ts +627 -0
  182. package/src/bus/rules/inputSchema.ts +232 -0
  183. package/src/bus/rules/invalidInput.ts +441 -0
  184. package/src/bus/rules/lateBoundTools.ts +100 -0
  185. package/src/bus/rules/studioRegistry.ts +324 -0
  186. package/src/bus/rules/studioToolBus.ts +73 -0
  187. package/src/bus/rules/types.ts +804 -0
  188. package/src/chrome/contracts/alert.ts +42 -0
  189. package/src/chrome/contracts/itinerary.ts +26 -0
  190. package/src/chrome/contracts/map.ts +23 -0
  191. package/src/chrome/contracts/overlay.ts +46 -0
  192. package/src/chrome/contracts/panel.ts +29 -0
  193. package/src/chrome/contracts/question.ts +52 -0
  194. package/src/chrome/contracts/selection.ts +26 -0
  195. package/src/chrome/contracts/sidenav.ts +23 -0
  196. package/src/chrome/contracts/snapshot.ts +319 -0
  197. package/src/chrome/contracts/state.ts +22 -0
  198. package/src/chrome/contracts/tabs.ts +56 -0
  199. package/src/chrome/handlers/alert.ts +91 -0
  200. package/src/chrome/handlers/introspection.ts +180 -0
  201. package/src/chrome/handlers/panels.ts +42 -0
  202. package/src/chrome/handlers/question.ts +24 -0
  203. package/src/chrome/handlers/sidenav.ts +116 -0
  204. package/src/chrome/handlers/snapshot.ts +451 -0
  205. package/src/chrome/handlers/stateDelta.ts +125 -0
  206. package/src/chrome/handlers/tabs.ts +143 -0
  207. package/src/chrome/handlers/timestamp.ts +19 -0
  208. package/src/chrome/rules/agentSelectors.ts +210 -0
  209. package/src/chrome/rules/mapAlert.ts +13 -0
  210. package/src/chrome/rules/question.ts +25 -0
  211. package/src/chrome/rules/tabs.ts +13 -0
  212. package/src/chrome/stores/activeDraftSession.ts +134 -0
  213. package/src/chrome/stores/chrome.ts +527 -0
  214. package/src/chrome/stores/uiStore.ts +575 -0
  215. package/src/collab/contracts/collab.ts +261 -0
  216. package/src/collab/handlers/collab.ts +468 -0
  217. package/src/collab/rules/toolNames.ts +33 -0
  218. package/src/collab/stores/collab.ts +899 -0
  219. package/src/collections/contracts/collection.ts +182 -0
  220. package/src/collections/handlers/collectionAttach.ts +141 -0
  221. package/src/collections/handlers/collections.ts +499 -0
  222. package/src/collections/handlers/heldCollection.ts +42 -0
  223. package/src/collections/handlers/restCollections.ts +386 -0
  224. package/src/collections/rules/collections.ts +138 -0
  225. package/src/collections/rules/entityCollections.ts +53 -0
  226. package/src/collections/stores/collections.ts +133 -0
  227. package/src/data/contracts/data.ts +233 -0
  228. package/src/data/contracts/itinerary.ts +71 -0
  229. package/src/data/handlers/activityResolve.ts +76 -0
  230. package/src/data/handlers/data.ts +200 -0
  231. package/src/data/handlers/graphql.ts +26 -0
  232. package/src/data/handlers/mutationSink.ts +1577 -0
  233. package/src/data/handlers/profile.ts +83 -0
  234. package/src/data/handlers/writeThrough.ts +417 -0
  235. package/src/data/rules/cache.ts +181 -0
  236. package/src/data/rules/dataTypes.ts +40 -0
  237. package/src/data/rules/keys.ts +106 -0
  238. package/src/data/rules/persistence.ts +1058 -0
  239. package/src/data/rules/requestBody.ts +43 -0
  240. package/src/data/rules/restErrors.ts +354 -0
  241. package/src/data/rules/sessionSurface.ts +156 -0
  242. package/src/data/rules/toolResultData.ts +73 -0
  243. package/src/data/rules/uuid.ts +24 -0
  244. package/src/edit/contracts/edit.ts +37 -0
  245. package/src/edit/contracts/itinerary.ts +57 -0
  246. package/src/edit/handlers/draftCommit.ts +257 -0
  247. package/src/edit/handlers/editDiscard.ts +34 -0
  248. package/src/edit/handlers/editLock.ts +949 -0
  249. package/src/edit/handlers/editor.ts +203 -0
  250. package/src/edit/handlers/formUnsaved.ts +24 -0
  251. package/src/edit/rules/draftMetadata.ts +117 -0
  252. package/src/edit/rules/editKeyboard.ts +222 -0
  253. package/src/edit/rules/editShortcuts.ts +102 -0
  254. package/src/edit/rules/editTooltip.ts +174 -0
  255. package/src/edit/rules/editorTaken.ts +49 -0
  256. package/src/edit/rules/history.ts +26 -0
  257. package/src/edit/rules/unsavedWork.ts +60 -0
  258. package/src/edit/stores/editorReservation.ts +70 -0
  259. package/src/edit/stores/formsUnsaved.ts +54 -0
  260. package/src/embed/contracts/embed.ts +48 -0
  261. package/src/embed/engines/embedFraming.ts +1329 -0
  262. package/src/embed/engines/embedReady.ts +353 -0
  263. package/src/embed/engines/framingPageSession.ts +169 -0
  264. package/src/embed/handlers/embed.ts +130 -0
  265. package/src/embed/rules/allowedDomains.ts +71 -0
  266. package/src/embed/rules/bridgeMessages.ts +224 -0
  267. package/src/embed/rules/defaults.ts +173 -0
  268. package/src/embed/rules/displaySeed.ts +115 -0
  269. package/src/embed/rules/embedAllowlist.ts +146 -0
  270. package/src/embed/rules/embedConstraints.ts +215 -0
  271. package/src/embed/rules/embedElements.ts +277 -0
  272. package/src/embed/rules/embedSectionFields.ts +126 -0
  273. package/src/embed/rules/embedSecurity.ts +116 -0
  274. package/src/embed/rules/fieldDependencies.ts +89 -0
  275. package/src/embed/rules/fieldOptions.ts +138 -0
  276. package/src/embed/rules/layerOptions.ts +161 -0
  277. package/src/embed/rules/readyProtocol.ts +66 -0
  278. package/src/embed/rules/safetyRules.ts +215 -0
  279. package/src/embed/rules/snippet.ts +531 -0
  280. package/src/embed/rules/tableCode.ts +270 -0
  281. package/src/embed/stores/embed.ts +60 -0
  282. package/src/embed/stores/embedContent.ts +77 -0
  283. package/src/engines/index.ts +81 -0
  284. package/src/handlers/index.ts +66 -0
  285. package/src/index.ts +1065 -0
  286. package/src/itinerary/contracts/itinerary.ts +705 -0
  287. package/src/itinerary/engines/itineraryPace.ts +612 -0
  288. package/src/itinerary/engines/profileMarker.ts +238 -0
  289. package/src/itinerary/handlers/importStaging.ts +352 -0
  290. package/src/itinerary/handlers/itinerary.ts +572 -0
  291. package/src/itinerary/handlers/itineraryDuplicate.ts +177 -0
  292. package/src/itinerary/handlers/itineraryExport.ts +117 -0
  293. package/src/itinerary/handlers/itineraryImport.ts +783 -0
  294. package/src/itinerary/handlers/itineraryPublish.ts +118 -0
  295. package/src/itinerary/handlers/itinerarySelection.ts +354 -0
  296. package/src/itinerary/handlers/itinerarySuggest.ts +1186 -0
  297. package/src/itinerary/handlers/itineraryUnpublish.ts +101 -0
  298. package/src/itinerary/handlers/publicationScope.ts +118 -0
  299. package/src/itinerary/handlers/restItineraries.ts +752 -0
  300. package/src/itinerary/handlers/restItineraryExport.ts +70 -0
  301. package/src/itinerary/handlers/restItineraryImport.ts +311 -0
  302. package/src/itinerary/handlers/restItineraryPace.ts +87 -0
  303. package/src/itinerary/handlers/restItineraryRecord.ts +36 -0
  304. package/src/itinerary/handlers/suggestParams.ts +379 -0
  305. package/src/itinerary/handlers/suggestStaging.ts +363 -0
  306. package/src/itinerary/handlers/surfaceOpen.ts +389 -0
  307. package/src/itinerary/rules/activity.ts +139 -0
  308. package/src/itinerary/rules/analysis.ts +42 -0
  309. package/src/itinerary/rules/ceiling.ts +49 -0
  310. package/src/itinerary/rules/createFlow.ts +107 -0
  311. package/src/itinerary/rules/densify.ts +440 -0
  312. package/src/itinerary/rules/draftSurface.ts +219 -0
  313. package/src/itinerary/rules/editorView.ts +83 -0
  314. package/src/itinerary/rules/export.ts +159 -0
  315. package/src/itinerary/rules/friendlyName.ts +77 -0
  316. package/src/itinerary/rules/import.ts +1050 -0
  317. package/src/itinerary/rules/importFiles.ts +140 -0
  318. package/src/itinerary/rules/importTotals.ts +77 -0
  319. package/src/itinerary/rules/liveSegment.ts +712 -0
  320. package/src/itinerary/rules/lngLat.ts +17 -0
  321. package/src/itinerary/rules/mapSync.ts +100 -0
  322. package/src/itinerary/rules/previewRender.ts +416 -0
  323. package/src/itinerary/rules/profileReadout.ts +216 -0
  324. package/src/itinerary/rules/routing.ts +707 -0
  325. package/src/itinerary/rules/suggest.ts +522 -0
  326. package/src/itinerary/rules/suggestionPreview.ts +119 -0
  327. package/src/itinerary/rules/view.ts +61 -0
  328. package/src/itinerary/stores/importSession.ts +319 -0
  329. package/src/itinerary/stores/itinerary.ts +331 -0
  330. package/src/itinerary/stores/itineraryDuplicate.ts +76 -0
  331. package/src/itinerary/stores/sessionIdentity.ts +43 -0
  332. package/src/itinerary/stores/suggestSession.ts +418 -0
  333. package/src/layers/contracts/itinerary.ts +46 -0
  334. package/src/layers/contracts/overlay.ts +132 -0
  335. package/src/layers/handlers/enrichment.ts +36 -0
  336. package/src/layers/handlers/overlay.ts +406 -0
  337. package/src/layers/handlers/restLayers.ts +94 -0
  338. package/src/layers/handlers/tiles.ts +25 -0
  339. package/src/layers/rules/layers.ts +212 -0
  340. package/src/layers/rules/overlayInstant.ts +12 -0
  341. package/src/layers/rules/reachabilityIcon.ts +18 -0
  342. package/src/layers/rules/readout.ts +102 -0
  343. package/src/layers/stores/layers.ts +262 -0
  344. package/src/map/contracts/contextmenu.ts +33 -0
  345. package/src/map/contracts/geolocate.ts +37 -0
  346. package/src/map/contracts/map.ts +146 -0
  347. package/src/map/contracts/streetview.ts +53 -0
  348. package/src/map/contracts/terrain.ts +152 -0
  349. package/src/map/handlers/contextMenu.ts +135 -0
  350. package/src/map/handlers/geolocate.ts +52 -0
  351. package/src/map/handlers/map.ts +391 -0
  352. package/src/map/handlers/streetview.ts +94 -0
  353. package/src/map/handlers/terrain.ts +663 -0
  354. package/src/map/rules/baseTerrain.ts +75 -0
  355. package/src/map/rules/clickTargets.ts +464 -0
  356. package/src/map/rules/constraints.ts +32 -0
  357. package/src/map/rules/contextMenuReadout.ts +67 -0
  358. package/src/map/rules/coordinates.ts +71 -0
  359. package/src/map/rules/itineraryFit.ts +8 -0
  360. package/src/map/rules/mapEvents.ts +64 -0
  361. package/src/map/rules/mapProjection.ts +476 -0
  362. package/src/map/rules/terrainReading.ts +62 -0
  363. package/src/plugins/contracts/ids.ts +66 -0
  364. package/src/plugins/contracts/plugin.ts +202 -0
  365. package/src/plugins/contracts/slots.ts +137 -0
  366. package/src/plugins/engines/studioPlugin.ts +1365 -0
  367. package/src/plugins/index.ts +111 -0
  368. package/src/plugins/rules/contributions.ts +152 -0
  369. package/src/plugins/rules/errors.ts +60 -0
  370. package/src/plugins/rules/ids.ts +42 -0
  371. package/src/plugins/rules/validation.ts +249 -0
  372. package/src/rules/listeners.ts +57 -0
  373. package/src/rules/origin.ts +13 -0
  374. package/src/rules/storeWrite.ts +37 -0
  375. package/src/rules/types.ts +136 -0
  376. package/src/seams/index.ts +79 -0
  377. package/src/seams/rules/clock.ts +28 -0
  378. package/src/seams/rules/formatters.ts +211 -0
  379. package/src/seams/rules/ids.ts +102 -0
  380. package/src/seams/rules/links.ts +66 -0
  381. package/src/seams/rules/navigation.ts +222 -0
  382. package/src/seams/rules/notify.ts +49 -0
  383. package/src/seams/rules/persistenceDrawer.ts +220 -0
  384. package/src/seams/rules/saveFile.ts +101 -0
  385. package/src/seams/rules/seams.ts +156 -0
  386. package/src/seams/rules/storage.ts +116 -0
  387. package/src/search/contracts/overlay.ts +74 -0
  388. package/src/search/contracts/search.ts +197 -0
  389. package/src/search/handlers/pois.ts +57 -0
  390. package/src/search/handlers/search.ts +280 -0
  391. package/src/search/rules/params.ts +925 -0
  392. package/src/search/rules/poiGroups.ts +138 -0
  393. package/src/search/rules/searchFetch.ts +139 -0
  394. package/src/search/rules/timeWindow.ts +30 -0
  395. package/src/search/stores/search.ts +51 -0
  396. package/src/segments/contracts/itinerary.ts +433 -0
  397. package/src/segments/contracts/segment.ts +35 -0
  398. package/src/segments/engines/segmentDraft.ts +926 -0
  399. package/src/segments/handlers/chainGuards.ts +67 -0
  400. package/src/segments/handlers/directions.ts +44 -0
  401. package/src/segments/handlers/itineraryEcho.ts +45 -0
  402. package/src/segments/handlers/roadAccessDialog.ts +34 -0
  403. package/src/segments/handlers/segment.ts +111 -0
  404. package/src/segments/handlers/segmentEdit.ts +1341 -0
  405. package/src/segments/handlers/segmentGroups.ts +347 -0
  406. package/src/segments/handlers/segmentStructure.ts +1144 -0
  407. package/src/segments/rules/chain.ts +196 -0
  408. package/src/segments/rules/chainModel.ts +217 -0
  409. package/src/segments/rules/colors.ts +11 -0
  410. package/src/segments/rules/commit.ts +76 -0
  411. package/src/segments/rules/draft.ts +90 -0
  412. package/src/segments/rules/draftDisposition.ts +43 -0
  413. package/src/segments/rules/draftSegmentEdit.ts +129 -0
  414. package/src/segments/rules/engine.ts +222 -0
  415. package/src/segments/rules/groupSave.ts +234 -0
  416. package/src/segments/rules/hazardPrompt.ts +60 -0
  417. package/src/segments/rules/itineraryEcho.ts +40 -0
  418. package/src/segments/rules/liveSegmentProjection.ts +55 -0
  419. package/src/segments/rules/merge.ts +51 -0
  420. package/src/segments/rules/metrics.ts +456 -0
  421. package/src/segments/rules/naming.ts +168 -0
  422. package/src/segments/rules/segmentArming.ts +144 -0
  423. package/src/segments/rules/splitPick.ts +84 -0
  424. package/src/segments/rules/viaSimplify.ts +230 -0
  425. package/src/segments/stores/directions.ts +77 -0
  426. package/src/segments/stores/roadAccessDialog.ts +58 -0
  427. package/src/segments/stores/segmentEdit.ts +922 -0
  428. package/src/segments/stores/segmentGroupEdit.ts +84 -0
  429. package/src/segments/stores/segmentSplit.ts +77 -0
  430. package/src/share/contracts/share.ts +39 -0
  431. package/src/share/contracts/shareLink.ts +63 -0
  432. package/src/share/engines/shareLink.ts +1053 -0
  433. package/src/share/handlers/share.ts +47 -0
  434. package/src/share/handlers/shareLink.ts +231 -0
  435. package/src/share/handlers/shareScope.ts +54 -0
  436. package/src/share/rules/link.ts +89 -0
  437. package/src/share/rules/shareLink.ts +218 -0
  438. package/src/share/rules/targets.ts +92 -0
  439. package/src/share/rules/viewConfig.ts +95 -0
  440. package/src/share/stores/share.ts +58 -0
  441. package/src/strings/fr/index.ts +18 -0
  442. package/src/strings/fr/rules/fr.ts +2368 -0
  443. package/src/strings/index.ts +98 -0
  444. package/src/strings/rules/confirmCopy.ts +156 -0
  445. package/src/strings/rules/draftToolNames.ts +94 -0
  446. package/src/strings/rules/en.ts +2519 -0
  447. package/src/strings/rules/failureAlert.ts +115 -0
  448. package/src/strings/rules/formError.ts +400 -0
  449. package/src/strings/rules/maneuvers.ts +107 -0
  450. package/src/strings/rules/outputOptions.ts +126 -0
  451. package/src/strings/rules/publicationState.ts +100 -0
  452. package/src/strings/rules/routeHazardCopy.ts +62 -0
  453. package/src/strings/rules/searchLabels.ts +50 -0
  454. package/src/strings/rules/segmentChainVerbs.ts +62 -0
  455. package/src/strings/rules/studioCopy.ts +130 -0
  456. package/src/strings/rules/unitOptions.ts +119 -0
  457. package/src/testing/checkedBus.ts +226 -0
  458. package/src/testing/index.ts +30 -0
  459. package/src/testing/plugins.ts +106 -0
  460. package/src/testing/studio.ts +267 -0
  461. package/src/testing/urlSeam.ts +153 -0
  462. package/src/time/index.ts +12 -0
  463. package/src/time/rules/sun.ts +78 -0
  464. package/src/video/contracts/cameraSchemas.ts +266 -0
  465. package/src/video/contracts/profileSchemas.ts +37 -0
  466. package/src/video/contracts/video.ts +601 -0
  467. package/src/video/handlers/video.ts +1638 -0
  468. package/src/video/handlers/videoDirector.ts +114 -0
  469. package/src/video/rules/previewRefresh.ts +76 -0
  470. package/src/video/rules/profileSource.ts +51 -0
  471. package/src/video/rules/routeSpans.ts +79 -0
  472. package/src/video/rules/shotDefaults.ts +28 -0
  473. package/src/video/rules/stepOrder.ts +17 -0
  474. package/src/video/rules/videoSnapshot.ts +136 -0
  475. package/src/video/stores/directorThreads.ts +167 -0
  476. package/src/video/stores/videoExport.ts +290 -0
  477. package/src/viewer/contracts/preferences.ts +40 -0
  478. package/src/viewer/handlers/preferences.ts +91 -0
  479. package/src/viewer/rules/capabilities.ts +42 -0
  480. package/src/viewer/rules/config.ts +266 -0
  481. package/src/viewer/rules/context.ts +375 -0
  482. package/src/viewer/rules/ownership.ts +134 -0
  483. package/src/viewer/rules/platformViewer.ts +199 -0
  484. package/src/viewer/rules/scope.ts +197 -0
  485. package/src/viewer/rules/url.ts +145 -0
  486. package/src/viewer/rules/viewer.ts +307 -0
  487. package/src/viewer/rules/viewerSeam.ts +49 -0
  488. package/src/viewer/rules/viewerUnits.ts +34 -0
  489. package/src/waypoints/contracts/itinerary.ts +417 -0
  490. package/src/waypoints/handlers/poiWaypointStyle.ts +32 -0
  491. package/src/waypoints/handlers/waypointDetailsDialog.ts +38 -0
  492. package/src/waypoints/handlers/waypointEdit.ts +1073 -0
  493. package/src/waypoints/rules/amenities.ts +30 -0
  494. package/src/waypoints/rules/defaults.ts +31 -0
  495. package/src/waypoints/rules/details.ts +213 -0
  496. package/src/waypoints/rules/detailsDraft.ts +312 -0
  497. package/src/waypoints/rules/detailsPreview.ts +76 -0
  498. package/src/waypoints/rules/detailsSave.ts +356 -0
  499. package/src/waypoints/rules/draftDirty.ts +45 -0
  500. package/src/waypoints/rules/icons.ts +32 -0
  501. package/src/waypoints/rules/liveWaypoint.ts +63 -0
  502. package/src/waypoints/rules/naming.ts +185 -0
  503. package/src/waypoints/rules/sections.ts +77 -0
  504. package/src/waypoints/rules/waypointDraft.ts +62 -0
  505. package/src/waypoints/stores/waypointDetails.ts +62 -0
  506. package/src/waypoints/stores/waypointEdit.ts +566 -0
  507. package/src/zones/contracts/collection.ts +37 -0
  508. package/src/zones/contracts/zone.ts +528 -0
  509. package/src/zones/engines/zoneForm.ts +1773 -0
  510. package/src/zones/handlers/restZones.ts +287 -0
  511. package/src/zones/handlers/zonePublish.ts +206 -0
  512. package/src/zones/handlers/zoneUnpublish.ts +56 -0
  513. package/src/zones/handlers/zones.ts +2254 -0
  514. package/src/zones/rules/geometry.ts +946 -0
  515. package/src/zones/rules/zoneDefaults.ts +34 -0
  516. package/src/zones/rules/zoneDraft.ts +54 -0
  517. package/src/zones/rules/zoneForm.ts +563 -0
  518. package/src/zones/rules/zoneMetadata.ts +29 -0
  519. package/src/zones/rules/zoneSource.ts +87 -0
  520. package/src/zones/rules/zoneSourceRefusal.ts +104 -0
  521. package/src/zones/stores/zoneEdit.ts +998 -0
@@ -0,0 +1,1365 @@
1
+ import { MountayaElementsError } from "@mountaya/elements/errors";
2
+
3
+ import { notifyListeners, surfaceFault } from "../../rules/listeners.js";
4
+ import type { StudioTool, StudioToolContext } from "../../viewer/rules/context.js";
5
+ import type { StudioPlugin, StudioPluginEntry, StudioSlotEntry } from "../contracts/plugin.js";
6
+ import type { StudioPluginSlot, StudioPluginTarget } from "../contracts/slots.js";
7
+ import { isStudioContributionAvailable, sortStudioContributions } from "../rules/contributions.js";
8
+ import { StudioPluginError } from "../rules/errors.js";
9
+ import { qualifyStudioContributionId } from "../rules/ids.js";
10
+ import type { StudioPluginDefect, StudioPluginValidationScope } from "../rules/validation.js";
11
+ import { validateStudioPlugin } from "../rules/validation.js";
12
+
13
+ /**
14
+ * The machine that holds what is installed and answers what each slot has in it.
15
+ *
16
+ * An `engines` file rather than a `rules` one, by the three-part test the layout convention
17
+ * states: it is constructed over something (a tool sink), it holds mutable state (the index, the
18
+ * listeners, the install counter) and it has a lifetime a binding drives. It is
19
+ * `SearchEngine`'s shape exactly: a framework-free state machine with a `subscribe`, which
20
+ * a React binding reads through `useSyncExternalStore` and a Flutter one through a
21
+ * `ChangeNotifier`.
22
+ */
23
+
24
+ /**
25
+ * The array EVERY empty slot answers with, shared and frozen.
26
+ *
27
+ * This is the load-bearing line of the whole file. `at(slot)` is a `useSyncExternalStore`
28
+ * snapshot, and a snapshot getter that builds a new value per call is an infinite render loop,
29
+ * so a studio with no plugins installed, which is every studio by default, would spin. One
30
+ * shared array means every empty slot is one identity, and `at("map.controls") ===
31
+ * at("zone.menu")` is true and harmless.
32
+ */
33
+ const NO_CONTRIBUTIONS: readonly never[] = Object.freeze([]);
34
+
35
+ /**
36
+ * StudioPluginToolSink is where a plugin's tools go, structurally.
37
+ *
38
+ * A `ToolBus` satisfies it with no adapter, which is the entire design: naming the class here
39
+ * would put the bus (the playbook, the Zod render, the confirmation machinery) in the graph of
40
+ * an entry whose job is to hold a list. Declared with METHOD syntax rather than arrow
41
+ * properties, which makes the parameters bivariant and is what lets the bus's own
42
+ * `register(tool: Tool<TCtx>)` satisfy `register(tool: StudioTool)`.
43
+ *
44
+ * `registered` is asked for one thing only (the names already taken), so its element type is
45
+ * the narrowest shape that answers: a return type is covariant, so the bus's richer `Tool` list
46
+ * satisfies it unchanged.
47
+ *
48
+ * `unregister` answers whether the name left the sink. A sink may refuse to release a name it
49
+ * holds, as a `ToolBus` does for a vendor segment it reserves: the tool then stays on it, and
50
+ * the registry keeps the name as its plugin's own, so the same declaration installs again and
51
+ * the same tool is met where it was left.
52
+ *
53
+ * After a release the sink refused, the registry asks `registered` whether the name is still
54
+ * listed, and asks again before it meets a kept tool: a name the sink does not list by then is
55
+ * registered as a new tool, and a fault thrown from that read refuses the plugin as one thrown
56
+ * from `register` does.
57
+ *
58
+ * How a kept name is read later follows from what `registered` listed when the sink kept it.
59
+ * Where it listed the very tool `register` was given, the kept tool is found by identity:
60
+ * another object under that name later is another tool, the one the sink's owner registered
61
+ * since. The name is then taken, so an install of the plugin is refused with `tool_name_taken`,
62
+ * and an attach offers the sink the plugin's tool and is refused in the sink's own words. Where
63
+ * it listed another object, as a sink that wraps what it holds does, on every call, the kept
64
+ * tool is found by name, and what stands there is taken for the tool handed over.
65
+ *
66
+ * The registry asks a name back only where it put the tool itself. A fault thrown by
67
+ * `unregister` or `registered` while a name is taken back interrupts nothing: the plugin leaves
68
+ * the registry, the subscribers are told, and the fault reaches the program as an uncaught error
69
+ * on a microtask.
70
+ */
71
+ export interface StudioPluginToolSink {
72
+ register(tool: StudioTool): void;
73
+ registered(): readonly { readonly name: string }[];
74
+ unregister(name: string): boolean;
75
+ }
76
+
77
+ /**
78
+ * StudioPluginRunOutcome is how a `run` ended, and it never includes "rejected".
79
+ *
80
+ * - `ran`: the verb ran to completion, promise and all.
81
+ * - `threw`: the verb throws or rejects, and the throw is caught here.
82
+ * - `gated`: its gate does not pass at the click. A menu can outlive the entitlement that
83
+ * opened it.
84
+ * - `inert`: the contribution is a `view` with no `run`, so there was nothing to call.
85
+ * - `unknown`: the plugin was uninstalled, or its declaration replaced, since the menu drew.
86
+ */
87
+ export type StudioPluginRunOutcome = "gated" | "inert" | "ran" | "threw" | "unknown";
88
+
89
+ /**
90
+ * StudioPluginRunEvent is one `run`, reported to {@link StudioPluginEngine.observe}.
91
+ *
92
+ * The deliberate twin of `ToolDispatchEvent`: an outcome, a latency, and what it was about. A
93
+ * host already sending tool dispatches to their telemetry gets plugin actions in the same shape,
94
+ * which is what makes "which plugin is slow" answerable without a second pipeline.
95
+ */
96
+ export interface StudioPluginRunEvent {
97
+ /** What was thrown, present only on `threw`. */
98
+ readonly error?: unknown;
99
+ readonly latencyMs: number;
100
+ readonly outcome: StudioPluginRunOutcome;
101
+ readonly pluginId: string;
102
+ readonly qualifiedId: string;
103
+ readonly slot: StudioPluginSlot;
104
+ }
105
+
106
+ /**
107
+ * StudioPluginObserver receives one event per `run`.
108
+ *
109
+ * One that throws changes no outcome and stops no observer after it: its fault reaches the
110
+ * program as an uncaught error on a microtask.
111
+ */
112
+ export type StudioPluginObserver = (event: StudioPluginRunEvent) => void;
113
+
114
+ /**
115
+ * StudioPluginRefusalReporter is how a caller hears that ONE declaration was refused, without the
116
+ * refusal taking the rest of the batch with it.
117
+ *
118
+ * Supplied, a refused plugin is reported and skipped; omitted, the refusal throws. That is the
119
+ * split between the two callers this object has. A host reconciling a declared list is running
120
+ * inside somebody else's render tree, where a throw unmounts the studio over one malformed
121
+ * plugin: the studio being gone is a worse report than the item being missing. A direct caller
122
+ * asked for one install and has a `catch` to put it in.
123
+ *
124
+ * `unknown` rather than {@link StudioPluginError}, because a validation defect is not the only way
125
+ * a plugin is refused: the sink can throw on a tool name it already holds, and that value is the
126
+ * sink's. Narrow with `isStudioPluginError` to read the defect list when there is one. A reporter
127
+ * that itself throws stops nothing, as an observer that throws stops nothing: its fault reaches
128
+ * the program as an uncaught error on a microtask.
129
+ *
130
+ * `plugin` is always a declaration: an object, which a reporter reads `plugin.id` off with no
131
+ * narrowing of its own. A member of a declared list that is no object, a `null` off a manifest
132
+ * among them, is handed to no reporter. {@link StudioPluginEngine.sync} surfaces its refusal as
133
+ * an uncaught error on a microtask, as a fault of the list's author, and applies the rest of the
134
+ * list. A seed surfaces none: see {@link StudioPluginEngineOptions.onRefused}.
135
+ *
136
+ * A declared list is told of a refusal once for as long as it goes on stating it: the seed and
137
+ * every {@link StudioPluginEngine.sync} after it report a declaration refused again in the same
138
+ * words to nobody. A refusal is told again once the list stopped stating its declaration and
139
+ * states it again, and when the declaration is refused in other words.
140
+ *
141
+ * A list written inline is told once all the same, though its members are other objects each
142
+ * time it is stated: a declaration is found again by the id it states. A member that states
143
+ * none is found by what it is, a value that is no object by itself, any function as a function
144
+ * and any object as an object, and is told apart there by the words of its refusal.
145
+ *
146
+ * A plugin a sink refuses when it is attached is reported by
147
+ * {@link StudioPluginEngine.attachTools}. The reconciliation after it meets the declaration
148
+ * anew and may refuse it in other words, for the name the sink holds: a declared list that
149
+ * states the plugin is told of that refusal by the attach alone.
150
+ */
151
+ export type StudioPluginRefusalReporter<TView = never> = (
152
+ error: unknown,
153
+ plugin: StudioPlugin<TView>,
154
+ ) => void;
155
+
156
+ /**
157
+ * What a plugin engine is built with. Every member is optional: `new StudioPluginEngine()`
158
+ * is valid.
159
+ */
160
+ export interface StudioPluginEngineOptions<TView = never> {
161
+ /**
162
+ * Plugins installed AT CONSTRUCTION, before anything can subscribe.
163
+ *
164
+ * It is what makes a plugin visible on the surface's FIRST paint rather than after the host's
165
+ * first effect, which matters for anything already open when the studio mounts, and is
166
+ * invisible in a test that flushes effects before asserting.
167
+ *
168
+ * These are DECLARED, in {@link StudioPluginEngine.sync}'s sense: this list is the same list
169
+ * a host then reconciles, so a later `sync([])` takes them back. An `install()` call is the
170
+ * other path and is never reconciled away.
171
+ *
172
+ * @default undefined, and nothing is installed at construction
173
+ */
174
+ readonly install?: readonly StudioPlugin<TView>[] | undefined;
175
+ /**
176
+ * Where a refused seed is reported. Omitted, the construction throws on the first refused seed
177
+ * and asks the sink for every tool a seed registered, so a sink that releases what it is asked
178
+ * for is left as it was found. A sink that keeps a name, as a `ToolBus` does for a vendor
179
+ * segment it reserves, still holds that tool.
180
+ *
181
+ * The constructor's half of {@link StudioPluginEngine.sync}'s reporter, and it is what lets a
182
+ * binding seed at construction (inside a render) without a malformed plugin taking the tree
183
+ * down with it.
184
+ *
185
+ * A seed that is no object is handed to no reporter and is skipped: nothing is queued from a
186
+ * construction, which a binding runs inside a render. The first
187
+ * {@link StudioPluginEngine.sync} of a list that still states the member surfaces its refusal.
188
+ */
189
+ readonly onRefused?: StudioPluginRefusalReporter<TView> | undefined;
190
+ /**
191
+ * Where a plugin's declared tools are registered. Omitted, they are validated and not registered.
192
+ *
193
+ * For a caller holding a sink already. A binding whose sink is rebuilt during the engine's
194
+ * lifetime (a React host whose bus is a memo) passes none and drives
195
+ * {@link StudioPluginEngine.attachTools} from an effect instead.
196
+ */
197
+ readonly tools?: StudioPluginToolSink | undefined;
198
+ }
199
+
200
+ /** The per-slot index, keyed so `at` resolves a slot to ITS entry type with no cast. */
201
+ type SlotIndex<TView> = {
202
+ [TSlot in StudioPluginSlot]: readonly StudioSlotEntry<TSlot, TView>[];
203
+ };
204
+
205
+ /**
206
+ * An empty index: every slot on the shared empty array.
207
+ *
208
+ * Written out slot by slot rather than built from the schema's `options`, which is what makes it
209
+ * cast-free AND total: a slot added to the enum fails at this literal, the same way it fails at
210
+ * `StudioPluginSlotTargets`. A `fromEntries` over the options would be shorter and would need a
211
+ * cast to say the one thing worth saying here.
212
+ */
213
+ const emptyIndex = <TView>(): SlotIndex<TView> => ({
214
+ "itinerary.menu": NO_CONTRIBUTIONS,
215
+ "map.contextMenu": NO_CONTRIBUTIONS,
216
+ "map.controls": NO_CONTRIBUTIONS,
217
+ "profile.header": NO_CONTRIBUTIONS,
218
+ "profile.plot": NO_CONTRIBUTIONS,
219
+ "segment.menu": NO_CONTRIBUTIONS,
220
+ "waypoint.menu": NO_CONTRIBUTIONS,
221
+ "zone.menu": NO_CONTRIBUTIONS,
222
+ });
223
+
224
+ /** What a batch does with each refusal, and how it ends. See {@link refusalsFor}. */
225
+ interface StudioPluginRefusals<TView> {
226
+ /** Hears each refusal of the batch. */
227
+ readonly reporter: StudioPluginRefusalReporter<TView>;
228
+ /** Ends the batch: throws the first refusal nobody was handed, and otherwise does nothing. */
229
+ readonly settle: () => void;
230
+ }
231
+
232
+ /**
233
+ * refusalsFor is what a batch does with each refusal: `sync` and `attachTools` go through every
234
+ * plugin they were handed before any refusal leaves.
235
+ *
236
+ * With a reporter, `reporter` is the caller's own. With none, it keeps the first refusal and
237
+ * `settle` throws it, so the batch ends with everything applied that could be and the
238
+ * subscribers told.
239
+ *
240
+ * A function beside the class and no member of it: a member that answers a reporter would put
241
+ * `TView` in an input position on {@link StudioPluginEngine}, for the reason
242
+ * {@link StudioPluginEngine.attachTools} gives for taking its reporter as a parameter.
243
+ */
244
+ const refusalsFor = <TView>(
245
+ onRefused: StudioPluginRefusalReporter<TView> | undefined,
246
+ ): StudioPluginRefusals<TView> => {
247
+ if (onRefused !== undefined) {
248
+ return { reporter: onRefused, settle: () => undefined };
249
+ }
250
+
251
+ let first: { readonly error: unknown } | undefined;
252
+
253
+ return {
254
+ reporter: (error) => {
255
+ first ??= { error };
256
+ },
257
+ settle: () => {
258
+ if (first !== undefined) {
259
+ throw first.error;
260
+ }
261
+ },
262
+ };
263
+ };
264
+
265
+ /**
266
+ * declaredId reads the id a declaration states, or undefined for a value that states none.
267
+ *
268
+ * A declaration may come off a wire with no type behind it, and `validateStudioPlugin` is total
269
+ * over what one can hold. The registry reads the id ahead of that validation, to know which
270
+ * installed plugin a declaration speaks of, so the read is as total: a value that is no object,
271
+ * and an id that is no string, state no id.
272
+ */
273
+ const declaredId = (plugin: unknown): string | undefined =>
274
+ typeof plugin === "object" && plugin !== null && "id" in plugin && typeof plugin.id === "string"
275
+ ? plugin.id
276
+ : undefined;
277
+
278
+ /**
279
+ * RefusalsTold is what a declared list was told of: the words of each refusal, by what finds its
280
+ * member again when the list is stated anew.
281
+ *
282
+ * A list written inline is another array of other objects each time it is stated, so no member
283
+ * is found again by its identity. A declaration is found by the id it states, and one that
284
+ * states none by {@link unnamedSubject}.
285
+ *
286
+ * A map for each, because a member that is a text and a declaration whose id is that text are
287
+ * different subjects.
288
+ */
289
+ interface RefusalsTold {
290
+ /**
291
+ * The words each declaration that states an id was refused in. `null` stands for a plugin a
292
+ * sink refused when it was attached: the reconciliation after it refuses the declaration in
293
+ * words of its own, and that refusal is the one already told.
294
+ */
295
+ readonly byId: Map<string, string | null>;
296
+ /** The words the members that state no id were refused in, by {@link unnamedSubject}. */
297
+ readonly unnamed: Map<unknown, Set<string>>;
298
+ }
299
+
300
+ /** noRefusalsTold is the memory of a list that was told of nothing. */
301
+ const noRefusalsTold = (): RefusalsTold => ({ byId: new Map(), unnamed: new Map() });
302
+
303
+ /**
304
+ * unnamedSubject is what finds a member that states no id again when its list is stated anew.
305
+ *
306
+ * A value that is no object is found by itself. A function and an object have nothing a second
307
+ * statement repeats, since one written inline is another each time: every function is the one
308
+ * subject `Function`, every object the one subject `Object`, and the words of its refusal are
309
+ * what tells one such member from the next.
310
+ */
311
+ const unnamedSubject = (member: unknown): unknown => {
312
+ if (typeof member === "function") {
313
+ return Function;
314
+ }
315
+
316
+ return typeof member === "object" && member !== null ? Object : member;
317
+ };
318
+
319
+ /**
320
+ * refusalWords reads a refusal as text, which is how one refusal of a declaration is told from
321
+ * another: an error's name and message, and any other value as `String` prints it.
322
+ */
323
+ const refusalWords = (error: unknown): string => {
324
+ if (error instanceof Error) {
325
+ return `${error.name}: ${error.message}`;
326
+ }
327
+
328
+ try {
329
+ return String(error);
330
+ } catch {
331
+ return "";
332
+ }
333
+ };
334
+
335
+ /**
336
+ * noteRefusal writes one refusal into `told`, and answers whether `before` already held it: in
337
+ * the same words, or in any for a plugin refused at an attach.
338
+ */
339
+ const noteRefusal = (
340
+ told: RefusalsTold,
341
+ before: RefusalsTold,
342
+ member: unknown,
343
+ error: unknown,
344
+ ): boolean => {
345
+ const id = declaredId(member);
346
+ const words = refusalWords(error);
347
+
348
+ if (id === undefined) {
349
+ const subject = unnamedSubject(member);
350
+ const stated = told.unnamed.get(subject) ?? new Set<string>();
351
+ told.unnamed.set(subject, stated.add(words));
352
+
353
+ return before.unnamed.get(subject)?.has(words) === true;
354
+ }
355
+
356
+ const held = before.byId.get(id);
357
+ told.byId.set(id, words);
358
+
359
+ return held === words || held === null;
360
+ };
361
+
362
+ /**
363
+ * declaredListReporter is the reporter a declared list is read with: the caller's own, held to
364
+ * what {@link StudioPluginRefusalReporter} states.
365
+ *
366
+ * A refusal `before` already holds is reported to nobody ({@link noteRefusal}), which is what
367
+ * holds a refusal to one report while a list goes on stating it. `told` receives every refusal
368
+ * of this reading that somebody could be told of, and is what the next reading is held against.
369
+ *
370
+ * A member that is no object is handed to no reporter. Its refusal goes to `surface`, and where
371
+ * the reading has none it is told to nobody and left out of `told`, so the next reading that
372
+ * still states the member surfaces it.
373
+ */
374
+ const declaredListReporter =
375
+ <TView>(
376
+ onRefused: StudioPluginRefusalReporter<TView>,
377
+ told: RefusalsTold,
378
+ before: RefusalsTold,
379
+ surface: ((fault: unknown) => void) | undefined,
380
+ ): StudioPluginRefusalReporter<TView> =>
381
+ (error, plugin) => {
382
+ const member: unknown = plugin;
383
+ if (typeof member !== "object" || member === null) {
384
+ if (surface !== undefined && !noteRefusal(told, before, member, error)) {
385
+ surface(error);
386
+ }
387
+
388
+ return;
389
+ }
390
+
391
+ if (!noteRefusal(told, before, member, error)) {
392
+ onRefused(error, plugin);
393
+ }
394
+ };
395
+
396
+ /**
397
+ * A name a sink would not release: the plugin that brought it, the tool it handed over, and
398
+ * whether the sink listed that very tool when it kept the name.
399
+ *
400
+ * A sink that lists what it is given lets the registry tell its own tool from one the sink's
401
+ * owner registered under the name since. A sink that wraps what it holds does not, and its kept
402
+ * name is read by name alone.
403
+ */
404
+ interface KeptTool {
405
+ readonly listedAsGiven: boolean;
406
+ readonly pluginId: string;
407
+ readonly tool: StudioTool;
408
+ }
409
+
410
+ /**
411
+ * isStillKept reports whether what a sink lists under a kept name is the tool the registry
412
+ * handed over: listed at all, and the very tool where the sink lists what it is given.
413
+ */
414
+ const isStillKept = (held: KeptTool, listed: { readonly name: string } | undefined): boolean =>
415
+ listed !== undefined && (!held.listedAsGiven || listed === held.tool);
416
+
417
+ /**
418
+ * StudioPluginEngine holds the installed plugins and the per-slot index a surface renders.
419
+ *
420
+ * Three properties carry the design, and each is a decision rather than an implementation
421
+ * detail:
422
+ *
423
+ * **1. `at(slot)` is materialised and sorted at MUTATION time, and is the same array between
424
+ * changes.** Only the slots a plugin actually touched are rebuilt; every empty one is the one
425
+ * shared frozen array. This is the `useSyncExternalStore` snapshot contract, and a `?? []` at
426
+ * the call site breaks it.
427
+ *
428
+ * **2. `at` does NOT resolve gates.** A gate reads the tool context, which changes underneath
429
+ * this object with nothing to notify it, so a gated snapshot could not be stable by
430
+ * construction. The split: `at(slot)` is the store, `availableStudioContributions(entries, ctx)`
431
+ * is the render-time filter.
432
+ *
433
+ * **3. `install` is ATOMIC**, unlike `ToolBus.registerAll`. Validate everything, register the
434
+ * tools with rollback, then mutate the index, which cannot fail. The bus is non-atomic because
435
+ * registration is a startup fact and a partial bus on a thrown startup is the correct outcome;
436
+ * an install is a LIFECYCLE operation on code the host may not have written, and it can happen
437
+ * at any point in a session.
438
+ *
439
+ * @example
440
+ * ```ts
441
+ * declare const bus: ToolBus<StudioToolContext>;
442
+ *
443
+ * const engine = new StudioPluginEngine({ tools: bus });
444
+ * engine.install({ contributions: [], id: "acme.huts" });
445
+ * ```
446
+ */
447
+ export class StudioPluginEngine<TView = never> {
448
+ private readonly listeners = new Set<() => void>();
449
+ private readonly observers = new Set<StudioPluginObserver>();
450
+
451
+ /** The installed declarations, by id, in install order. */
452
+ private readonly plugins = new Map<string, StudioPlugin<TView>>();
453
+
454
+ /** Each plugin's resolved entries, by id, in declaration order. */
455
+ private readonly entries = new Map<string, readonly StudioPluginEntry<TView>[]>();
456
+
457
+ /**
458
+ * Every tool name THIS registry owns, mapped to the plugin that brought it.
459
+ *
460
+ * Ownership rather than registration state, which is the difference that matters while there is
461
+ * no sink: {@link attachTools} is allowed to arrive late, and the names a plugin claimed have to
462
+ * be known before then, both to re-register them when a sink appears and to refuse a second
463
+ * plugin claiming the same one in the meantime.
464
+ */
465
+ private readonly toolNames = new Map<string, string>();
466
+
467
+ /**
468
+ * The tools this registry put on the attached sink, by name: the ones it registered there and
469
+ * the ones it adopted where the sink had kept them.
470
+ *
471
+ * It is what {@link withdraw} reads before it asks the sink for a name back. A name that is
472
+ * not here was never this registry's on that sink, whoever holds it there, and is never asked
473
+ * for. Empty while no sink is attached.
474
+ */
475
+ private readonly placed = new Map<string, StudioTool>();
476
+
477
+ /**
478
+ * The names each sink would not release, by sink: each with the plugin that brought it and
479
+ * the tool that plugin declared.
480
+ *
481
+ * A sink answers `unregister` with false for a name it keeps. The tool is then on the sink
482
+ * with no installed plugin behind it, and this map is what lets the plugin's own declaration
483
+ * meet that sink again, by a new install or by a new attach: the name reads as the plugin's
484
+ * and the held tool is adopted where it stands. An entry is a fact about its sink and stands
485
+ * while another sink is attached, so a registry that returns to a sink it left finds its
486
+ * tools there. Keyed weakly, so a sink that is gone keeps nothing alive.
487
+ *
488
+ * An entry is what the registry remembers, and the sink decides: its owner may take a kept
489
+ * name off it at any time. So a kept name is met again only while the sink still lists it,
490
+ * which {@link register} reads before it adopts, and an entry the sink no longer lists is
491
+ * forgotten there.
492
+ */
493
+ private readonly unreleased = new WeakMap<StudioPluginToolSink, Map<string, KeptTool>>();
494
+
495
+ /**
496
+ * The ids a DECLARED list owns, which is the only thing {@link sync} may take back.
497
+ *
498
+ * The two install paths compose rather than competing, and this set is what makes that true. A
499
+ * host's `install` array is one authority and a settings screen calling `install()` is another;
500
+ * a reconciliation that dropped every id absent from its own list would silently uninstall the
501
+ * other's the moment the array's identity changed. Seeded by the constructor's `install`,
502
+ * because that is the same declared list the host then syncs.
503
+ */
504
+ private readonly declared = new Set<string>();
505
+
506
+ /**
507
+ * What the declared list read last was told of, which holds each refusal to one report while
508
+ * the list goes on stating it. See {@link declaredListReporter}.
509
+ */
510
+ private told: RefusalsTold = noRefusalsTold();
511
+
512
+ private index: SlotIndex<TView> = emptyIndex<TView>();
513
+ private sequence = 0;
514
+ private revision = 0;
515
+
516
+ /** The installed declarations as {@link installed} hands them back, or null when stale. */
517
+ private snapshot: readonly StudioPlugin<TView>[] | null = null;
518
+
519
+ private sink: StudioPluginToolSink | undefined;
520
+
521
+ constructor(options: StudioPluginEngineOptions<TView> = {}) {
522
+ this.sink = options.tools;
523
+
524
+ // The seed is a declared list like any a host reconciles later, so what it is told of here
525
+ // is not told again by the reconciliation of the same list.
526
+ //
527
+ // A seed that is no object is surfaced by no construction. A binding constructs inside a
528
+ // render, and a throw queued there would fire for a render its framework discards and for
529
+ // a server's, where an uncaught error ends the process: the first reconciliation of a list
530
+ // that still states the member surfaces it.
531
+ const told = noRefusalsTold();
532
+ const onRefused =
533
+ options.onRefused === undefined
534
+ ? undefined
535
+ : declaredListReporter(options.onRefused, told, this.told, undefined);
536
+
537
+ try {
538
+ for (const plugin of options.install ?? []) {
539
+ if (this.take(plugin, onRefused)) {
540
+ this.declared.add(plugin.id);
541
+ }
542
+ }
543
+
544
+ this.told = told;
545
+ } catch (error) {
546
+ // With no reporter the first refused seed ends the construction. Nothing will ever hold
547
+ // this registry, so it asks the sink for what the earlier seeds put on it before the
548
+ // refusal leaves: a construction that throws leaves a sink that releases its names as it
549
+ // found it.
550
+ this.dispose();
551
+
552
+ throw error;
553
+ }
554
+ }
555
+
556
+ /**
557
+ * at returns the installed contributions for one slot, sorted, UNGATED.
558
+ *
559
+ * The same array between mutations, as the class docblock states. Cast-free, which is why the
560
+ * index is a mapped-type record rather than a `Map`: the one member every render touches is the
561
+ * one that should not need a cast.
562
+ */
563
+ at<TSlot extends StudioPluginSlot>(slot: TSlot): readonly StudioSlotEntry<TSlot, TView>[] {
564
+ return this.index[slot];
565
+ }
566
+
567
+ /**
568
+ * installed returns the declarations currently installed, in install order.
569
+ *
570
+ * Materialised once per change and handed back by reference until the next one, for the reason
571
+ * this file's opening comment gives about `at`: a getter shaped like a snapshot will be read as
572
+ * one (`useSyncExternalStore(engine.subscribe, engine.installed)` is the obvious thing for
573
+ * a consumer holding the engine to write), and a fresh array per call is an infinite render
574
+ * loop. An arrow PROPERTY for the same reason {@link subscribe} is one: it is passed detached.
575
+ */
576
+ readonly installed = (): readonly StudioPlugin<TView>[] => {
577
+ this.snapshot ??= Object.freeze([...this.plugins.values()]);
578
+
579
+ return this.snapshot;
580
+ };
581
+
582
+ /**
583
+ * version is a counter that changes whenever any slot does.
584
+ *
585
+ * The scalar a `useSyncExternalStore` reads, so the binding subscribes once for the whole
586
+ * engine rather than once per slot, and the per-slot arrays stay plain reads inside the
587
+ * memo that filters them. An arrow PROPERTY for the same reason {@link subscribe} is one.
588
+ */
589
+ readonly version = (): number => this.revision;
590
+
591
+ /**
592
+ * subscribe registers a listener called after any change, and returns the detach.
593
+ *
594
+ * An arrow PROPERTY rather than a method, and this is not style: `useSyncExternalStore` calls
595
+ * it detached from the object (`useSyncExternalStore(engine.subscribe, …)`), so a method
596
+ * would arrive with `this` unbound and throw on the first render that reads it.
597
+ */
598
+ readonly subscribe = (listener: () => void): (() => void) => {
599
+ this.listeners.add(listener);
600
+
601
+ return () => {
602
+ this.listeners.delete(listener);
603
+ };
604
+ };
605
+
606
+ /** observe registers a per-`run` telemetry observer and returns the detach. */
607
+ observe(observer: StudioPluginObserver): () => void {
608
+ this.observers.add(observer);
609
+
610
+ return () => {
611
+ this.observers.delete(observer);
612
+ };
613
+ }
614
+
615
+ /**
616
+ * attachTools points the engine at a tool sink, moving every installed plugin's tools onto it.
617
+ *
618
+ * The sink is a LIFETIME rather than a construction fact, and this is the member that says so. An
619
+ * engine outlives the bus a binding built for it (a React host rebuilds the bus whenever its
620
+ * handlers, its grants or its confirm gate move), and an engine holding the one it was
621
+ * constructed with would keep registering a plugin's verbs onto a bus nothing dispatches
622
+ * through. It is also the only way an engine a CONSUMER constructed, and handed to the studio,
623
+ * ever reaches a bus at all.
624
+ *
625
+ * It is total in both directions: the outgoing sink gives every name back, the incoming one
626
+ * receives every installed plugin's tools, and `null` detaches. A sink that REFUSES a plugin's
627
+ * tools (a name it already holds) costs that plugin its install, reported through the refusal
628
+ * reporter, because a plugin whose contributions are on the menu and whose verbs are on no bus
629
+ * is half-installed in the one way nothing downstream can see.
630
+ *
631
+ * A detach moves tools and no ownership. The names stay their plugins' while no sink is
632
+ * attached, so a second plugin claiming one is refused when it is installed, and the tools go
633
+ * onto the sink that arrives next.
634
+ *
635
+ * With no reporter the first refusal is thrown, and only once every other plugin's tools are
636
+ * on the incoming sink and the subscribers have heard: a throw never leaves a later plugin on
637
+ * the menu with its verbs on no sink.
638
+ *
639
+ * With a reporter, a refused plugin a declared list states is told of here once: the
640
+ * reconciliation after this attach reports its refusal to nobody, in whatever words it reads
641
+ * there. See {@link StudioPluginRefusalReporter}.
642
+ *
643
+ * It does not notify on its own: moving tools between buses changes no slot. A refusal does
644
+ * change one, and that notifies.
645
+ *
646
+ * `onRefused` is a parameter here rather than a construction option, as it is on {@link sync},
647
+ * and deliberately: a reporter held as a FIELD would put `TView` in an input position on this
648
+ * class, which is what keeps `StudioPluginEngine<never>` (the engine a bare
649
+ * `new StudioPluginEngine()` builds) assignable to the bound one a React host takes.
650
+ */
651
+ attachTools(
652
+ sink: StudioPluginToolSink | null,
653
+ onRefused?: StudioPluginRefusalReporter<TView>,
654
+ ): void {
655
+ // What the outgoing sink would not release stays on it and is remembered against it, so a
656
+ // new attach of that sink, whenever it comes, finds the tools where they were left. The
657
+ // names stay their plugins' through the move: ownership is no fact about a sink.
658
+ const outgoing = this.sink;
659
+ if (outgoing !== undefined) {
660
+ for (const [name, owner] of [...this.toolNames]) {
661
+ this.withdraw(name, owner, outgoing);
662
+ }
663
+ }
664
+
665
+ this.sink = sink ?? undefined;
666
+
667
+ if (sink === null) {
668
+ return;
669
+ }
670
+
671
+ const refusals = refusalsFor(onRefused);
672
+ let dropped = false;
673
+
674
+ // Over the declarations rather than over `toolNames`, because the sink is the thing that can
675
+ // refuse: a plugin's tools land together or its install is taken back.
676
+ for (const plugin of [...this.plugins.values()]) {
677
+ try {
678
+ this.register(plugin, sink);
679
+ } catch (error) {
680
+ // Read ahead of the drop, which takes the id off the declared list.
681
+ const stated = this.declared.has(plugin.id);
682
+ this.drop(plugin.id);
683
+ dropped = true;
684
+ this.report(error, plugin, refusals.reporter);
685
+
686
+ // A declared list that goes on stating the plugin offers it to this sink at every
687
+ // reconciliation. The first one meets the declaration anew and may refuse it at the
688
+ // validation, for the name the sink holds, where this attach was refused in the sink's
689
+ // own words: the same refusal, told here, whatever it reads there.
690
+ if (onRefused !== undefined && stated) {
691
+ this.told.byId.set(plugin.id, null);
692
+ }
693
+ }
694
+ }
695
+
696
+ if (dropped) {
697
+ this.notify();
698
+ }
699
+
700
+ refusals.settle();
701
+ }
702
+
703
+ /**
704
+ * install validates a plugin, registers its tools and indexes its contributions, or refuses
705
+ * the whole thing.
706
+ *
707
+ * It throws a {@link StudioPluginError} carrying EVERY defect, because an install a host asked
708
+ * for and did not get has to be loud: a plugin that silently failed to install is a menu item
709
+ * that is missing, which reads as the studio being broken rather than as the plugin being
710
+ * malformed. A sink that refuses one of the plugin's tools throws ITS OWN error through here
711
+ * unchanged, after the rollback, so a caller catching this catches both kinds.
712
+ *
713
+ * A value that is no declaration at all, `null` off a manifest for one, is refused the same
714
+ * way: a {@link StudioPluginError} whose defect says it states no id.
715
+ *
716
+ * What it installs is never reconciled away: {@link sync} owns the ids a DECLARED list brought,
717
+ * and this is the other path. A settings screen installing on demand and a host declaring an
718
+ * array compose rather than competing, until the same id appears in the declared list, which
719
+ * takes ownership of it.
720
+ *
721
+ * @throws StudioPluginError carrying every defect of a declaration the validation refuses.
722
+ * @throws whatever the tool sink throws for a tool it refuses, after the rollback.
723
+ */
724
+ install(plugin: StudioPlugin<TView>): void {
725
+ this.adopt(plugin);
726
+ this.notify();
727
+ }
728
+
729
+ /**
730
+ * uninstall removes a plugin and everything it brought, reporting whether it was there.
731
+ *
732
+ * It takes back only the tool names THIS engine registered for THIS plugin (tracked as they
733
+ * are registered rather than recomputed from the declaration), which is what guarantees an
734
+ * uninstall can never take a `studio.*` verb, or another plugin's, down with it.
735
+ */
736
+ uninstall(pluginId: string): boolean {
737
+ if (!this.drop(pluginId)) {
738
+ return false;
739
+ }
740
+
741
+ this.notify();
742
+
743
+ return true;
744
+ }
745
+
746
+ /**
747
+ * sync reconciles the installed set against a declared list, and notifies at most once.
748
+ *
749
+ * It reconciles by ID for install and uninstall, and ADDITIONALLY replaces a stored
750
+ * declaration when the plugin's object reference changed: rebuilding the touched slots, and
751
+ * re-registering bus tools only when the tool-name list actually differs.
752
+ *
753
+ * Replacing on reference is the one place this departs from a pure by-id reconciliation, and
754
+ * the reason is a real trap: a host that changes language and passes new labels under the same
755
+ * ids would otherwise see nothing change. It is safe HERE because the notification flows
756
+ * strictly DOWN (every subscriber is a menu below the host, and a menu re-rendering never
757
+ * re-renders the host), so there is no cycle to fall into.
758
+ *
759
+ * What it costs is a host who writes the array inline: the menus beneath them re-render
760
+ * whenever the host does. Hoist the declarations to module scope, which is the natural way to
761
+ * write them, and nothing churns.
762
+ *
763
+ * **It removes only what a DECLARED list installed.** An id that arrived through
764
+ * {@link install} (a settings screen, a marketplace loading one on demand) is another
765
+ * authority's, and a reconciliation that dropped it would make the two paths compete for the
766
+ * engine rather than compose in it. A declaration naming that id takes ownership of it from
767
+ * then on.
768
+ *
769
+ * `onRefused` decides what a malformed declaration costs. Supplied, it is reported and skipped
770
+ * and every other declaration still lands; omitted, the first refusal is thrown once every
771
+ * declaration that could be applied has been and the subscribers have heard. A binding
772
+ * reconciling inside a render tree passes one: see {@link StudioPluginRefusalReporter}.
773
+ *
774
+ * A member of the list that is no object is one more malformed declaration: refused where it
775
+ * stands, with the defect of a declaration that states no id. With no reporter it is thrown as
776
+ * any refusal is. With one it is handed to nobody, since a reporter is handed a declaration:
777
+ * its refusal is surfaced on a microtask. Subscribers hear of what the list applied whatever
778
+ * leaves this call.
779
+ *
780
+ * A refusal is reported, or surfaced, once while the list goes on stating it, the seed's list
781
+ * included and a list written inline as well: see {@link StudioPluginRefusalReporter}. With no
782
+ * reporter every call throws its first refusal, since each call is one its caller asked for.
783
+ */
784
+ sync(
785
+ plugins: readonly StudioPlugin<TView>[],
786
+ onRefused?: StudioPluginRefusalReporter<TView>,
787
+ ): void {
788
+ // By the id each declaration states. One that states none, a value that is no object among
789
+ // them, is keyed by itself: it names no installed plugin, and it is refused where it stands
790
+ // in the list.
791
+ const next = new Map<string | object, StudioPlugin<TView>>();
792
+ for (const plugin of plugins) {
793
+ next.set(declaredId(plugin) ?? {}, plugin);
794
+ }
795
+
796
+ const told = noRefusalsTold();
797
+ const refusals = refusalsFor(
798
+ onRefused === undefined
799
+ ? undefined
800
+ : declaredListReporter(onRefused, told, this.told, surfaceFault),
801
+ );
802
+ let changed = false;
803
+
804
+ try {
805
+ for (const id of [...this.declared]) {
806
+ if (!next.has(id)) {
807
+ this.drop(id);
808
+ changed = true;
809
+ }
810
+ }
811
+
812
+ // Over the MAP rather than the array, so a list naming one id twice is reconciled once
813
+ // rather than replacing the first declaration with the second on every pass.
814
+ for (const [id, plugin] of next) {
815
+ if (typeof id !== "string") {
816
+ this.take(plugin, refusals.reporter);
817
+ continue;
818
+ }
819
+
820
+ if (this.reconcile(id, plugin, refusals.reporter)) {
821
+ changed = true;
822
+ }
823
+ }
824
+ } finally {
825
+ // What this list was told of is what the next one is held against, whatever leaves.
826
+ this.told = told;
827
+
828
+ // Whatever leaves the loop, the subscribers hear of what it applied before it left.
829
+ if (changed) {
830
+ this.notify();
831
+ }
832
+ }
833
+
834
+ refusals.settle();
835
+ }
836
+
837
+ /**
838
+ * reconcile brings one declaration of a declared list in under its id: installed where the id
839
+ * is new, replaced where its reference changed, and left where it is the one installed.
840
+ *
841
+ * @returns Whether a slot may have changed: a plugin was installed, replaced, or lost to a
842
+ * sink that refused its replacement.
843
+ */
844
+ private reconcile(
845
+ id: string,
846
+ plugin: StudioPlugin<TView>,
847
+ onRefused: StudioPluginRefusalReporter<TView>,
848
+ ): boolean {
849
+ const current = this.plugins.get(id);
850
+
851
+ if (current === plugin) {
852
+ // Already installed, unchanged, and now DECLARED, whichever path first brought it.
853
+ this.declared.add(id);
854
+
855
+ return false;
856
+ }
857
+
858
+ if (current === undefined) {
859
+ if (!this.take(plugin, onRefused)) {
860
+ return false;
861
+ }
862
+
863
+ this.declared.add(id);
864
+
865
+ return true;
866
+ }
867
+
868
+ // Reference equality, not a deep compare. A host holding their declarations still is the
869
+ // case this is tuned for, and a structural walk of every contribution on every host
870
+ // render would cost more than the re-render it saves.
871
+ //
872
+ // Validated BEFORE the incumbent is dropped, against a scope with its own id and its own
873
+ // tool names taken out: otherwise a refused replacement costs the host a working plugin,
874
+ // which is the one outcome neither reporting nor throwing can put right.
875
+ let defects: readonly StudioPluginDefect[];
876
+ try {
877
+ defects = validateStudioPlugin(plugin, this.scope(id, true));
878
+ } catch (error) {
879
+ // The sink would not say what it holds, so nothing could be validated against it. The
880
+ // replacement is refused with the sink's own error and its incumbent stands, as a
881
+ // declaration met for the first time is refused for the same fault.
882
+ this.report(error, plugin, onRefused);
883
+
884
+ return false;
885
+ }
886
+
887
+ if (defects.length > 0) {
888
+ this.report(new StudioPluginError(defects), plugin, onRefused);
889
+
890
+ return false;
891
+ }
892
+
893
+ this.drop(id);
894
+
895
+ // Validation cannot refuse it now: the scope it just passed is the one this drop
896
+ // produced. A SINK still can, and that leaves the id uninstalled with the reporter told:
897
+ // the one case this method does not make atomic, and the only one where the refusal comes
898
+ // from outside the registry.
899
+ if (this.take(plugin, onRefused)) {
900
+ this.declared.add(id);
901
+ }
902
+
903
+ return true;
904
+ }
905
+
906
+ /**
907
+ * run invokes a contribution's verb and reports how it ended. It ALWAYS resolves.
908
+ *
909
+ * It re-checks two things the caller cannot, because a menu can outlive both: that the entry is
910
+ * still installed (a plugin uninstalled, or its declaration replaced, while the dropdown was
911
+ * open) and that its gate still passes (an entitlement that lapsed mid-session). Neither is a
912
+ * throw: a stale click is a no-op with a reason, not a crash.
913
+ *
914
+ * `onError` is how the thrown value reaches a caller that has to report it. The outcome alone
915
+ * cannot carry one, and an observer is registered per ENGINE rather than per call, so a
916
+ * binding wanting to hand the failure to a host seam beside the contribution it came from
917
+ * passes this. It is called at most once, before the promise resolves. An `onError` that itself
918
+ * throws leaves the outcome `threw`, and its fault is surfaced on a microtask.
919
+ */
920
+ async run<TSlot extends StudioPluginSlot>(
921
+ entry: StudioSlotEntry<TSlot, TView>,
922
+ ctx: StudioToolContext,
923
+ target: StudioPluginTarget<TSlot>,
924
+ onError?: (error: unknown) => void,
925
+ ): Promise<StudioPluginRunOutcome> {
926
+ const start = performance.now();
927
+ const report = (outcome: StudioPluginRunOutcome, error?: unknown): StudioPluginRunOutcome => {
928
+ this.emit({
929
+ ...(error === undefined ? {} : { error }),
930
+ latencyMs: performance.now() - start,
931
+ outcome,
932
+ pluginId: entry.pluginId,
933
+ qualifiedId: entry.qualifiedId,
934
+ slot: entry.slot,
935
+ });
936
+
937
+ return outcome;
938
+ };
939
+
940
+ // IDENTITY, not the qualified id, which is what makes the second half of `unknown`'s meaning
941
+ // ("its declaration replaced") actually reachable: a qualified id survives a replacement
942
+ // unchanged, so matching on it would run the OLD closure against the NEW gate's menu. `adopt`
943
+ // builds a fresh entry object every time, so identity is exactly the documented semantics.
944
+ if (!this.index[entry.slot].some((live) => live === entry)) {
945
+ return report("unknown");
946
+ }
947
+
948
+ if (!isStudioContributionAvailable(entry, ctx)) {
949
+ return report("gated");
950
+ }
951
+
952
+ const verb = entry.run;
953
+ if (verb === undefined) {
954
+ return report("inert");
955
+ }
956
+
957
+ try {
958
+ await verb(ctx, target);
959
+ } catch (error) {
960
+ try {
961
+ onError?.(error);
962
+ } catch (fault) {
963
+ // `run` ALWAYS resolves with the verb's own outcome, so a reporter that throws while it
964
+ // reports changes nothing here. Its fault is the caller's defect and is surfaced apart.
965
+ surfaceFault(fault);
966
+ }
967
+
968
+ return report("threw", error);
969
+ }
970
+
971
+ return report("ran");
972
+ }
973
+
974
+ /**
975
+ * dispose uninstalls everything and drops every listener and observer.
976
+ *
977
+ * It leaves an EMPTY engine rather than a poisoned one (installing into it afterwards works),
978
+ * because the alternative breaks React's StrictMode, where an effect's cleanup runs between
979
+ * two runs of the effect itself.
980
+ *
981
+ * An empty engine was told of nothing: a list declared after it is told of its refusals as a
982
+ * list stated for the first time is.
983
+ */
984
+ dispose(): void {
985
+ const had = this.plugins.size > 0;
986
+
987
+ for (const id of [...this.plugins.keys()]) {
988
+ this.drop(id);
989
+ }
990
+
991
+ this.told = noRefusalsTold();
992
+
993
+ // Before the listeners are dropped, and only when a slot actually emptied. A disposal is a
994
+ // change like any other to anything still subscribed: a surface that outlives the registry
995
+ // it was reading has to be told the menu is empty, not left drawing the version it last saw.
996
+ if (had) {
997
+ this.notify();
998
+ }
999
+
1000
+ this.listeners.clear();
1001
+ this.observers.clear();
1002
+ }
1003
+
1004
+ /**
1005
+ * adopt is install without the notification: validate, register with rollback, then index.
1006
+ *
1007
+ * The order is the atomicity. Validation reads and changes nothing; tool registration is the
1008
+ * only step that can fail, and it unwinds its own partial work; indexing is pure mutation of
1009
+ * state this object owns and cannot throw. So a refused install leaves the bus and every slot
1010
+ * exactly as they were.
1011
+ *
1012
+ * A sink that keeps a name it is asked for is the one exception, and {@link register} states
1013
+ * what becomes of that name.
1014
+ */
1015
+ private adopt(plugin: StudioPlugin<TView>): void {
1016
+ // The id is read as the validation reads it: a declaration that states none collides with
1017
+ // nothing, and the validation below refuses it with the defect that says so.
1018
+ const defects = validateStudioPlugin(plugin, this.scope(declaredId(plugin) ?? "", false));
1019
+ if (defects.length > 0) {
1020
+ throw new StudioPluginError(defects);
1021
+ }
1022
+
1023
+ const sink = this.sink;
1024
+ const declaredTools = Object.values(plugin.tools ?? {}).map((tool) => tool.name);
1025
+ const registered = sink === undefined ? declaredTools : this.register(plugin, sink);
1026
+
1027
+ // Whether or not a sink took them. The map is OWNERSHIP (see its declaration), so a name
1028
+ // claimed while `attachTools` has yet to arrive still collides with a second plugin claiming
1029
+ // it, and is still the list that gets registered when a sink does arrive.
1030
+ for (const name of registered) {
1031
+ this.toolNames.set(name, plugin.id);
1032
+ }
1033
+
1034
+ this.plugins.set(plugin.id, plugin);
1035
+ this.snapshot = null;
1036
+
1037
+ const touched = new Set<StudioPluginSlot>();
1038
+ const resolved = (plugin.contributions ?? []).map((contribution) => {
1039
+ touched.add(contribution.slot);
1040
+
1041
+ // The first of the two localized casts in this file. The spread is over a UNION of
1042
+ // per-slot contribution types, and TypeScript cannot distribute an object spread across
1043
+ // one and keep each member's `slot`/`run` pairing: it widens both independently, which
1044
+ // makes the result assignable to no member of the entry union. Neither cast is `any`,
1045
+ // both are private, and the public `at` is cast-free.
1046
+ return {
1047
+ ...contribution,
1048
+ pluginId: plugin.id,
1049
+ qualifiedId: qualifyStudioContributionId(plugin.id, contribution.id),
1050
+ sequence: this.sequence++,
1051
+ } as StudioPluginEntry<TView>;
1052
+ });
1053
+
1054
+ this.entries.set(plugin.id, resolved);
1055
+ this.rebuild(touched);
1056
+ }
1057
+
1058
+ /**
1059
+ * register puts one plugin's tools on a sink, unwinding its own partial work if one is refused.
1060
+ *
1061
+ * The only step of an adoption that can fail, which is why it is the only one with a rollback
1062
+ * (see {@link install}'s note on atomicity). `instanceof Error` here is the narrow question "is
1063
+ * this already a throwable with a message", not the class-identity check `isStudioPluginError`
1064
+ * exists to avoid: the value is the sink's, and wrapping one that is already an error would
1065
+ * bury the bus's own message one `cause` deeper.
1066
+ *
1067
+ * The rollback asks the sink for each name back through {@link withdraw}, as an uninstall
1068
+ * does. A name the sink keeps is remembered as the plugin's own, so the declaration put right
1069
+ * meets its tool where the refusal left it.
1070
+ *
1071
+ * A name the sink kept from the plugin's earlier install ({@link unreleased}) is adopted
1072
+ * where it stands, and only while the sink still lists it: the sink is read once, when the
1073
+ * first such name is met. A kept name the sink does not list then is forgotten and its tool is
1074
+ * registered as any other. So is a kept name under which the sink lists another tool, where
1075
+ * the sink lists what it is given ({@link isStillKept}): its owner registered that tool since,
1076
+ * the sink is offered the plugin's and answers for the name itself. A sink that throws from
1077
+ * that read refuses the plugin, as one that throws from `register` does.
1078
+ */
1079
+ private register(plugin: StudioPlugin<TView>, sink: StudioPluginToolSink): readonly string[] {
1080
+ const kept = this.unreleased.get(sink);
1081
+ const registered: string[] = [];
1082
+ const adopted: KeptTool[] = [];
1083
+ let listed: ReadonlyMap<string, { readonly name: string }> | undefined;
1084
+
1085
+ try {
1086
+ for (const tool of Object.values(plugin.tools ?? {})) {
1087
+ const held = kept?.get(tool.name);
1088
+
1089
+ if (held?.pluginId === plugin.id) {
1090
+ // What the registry remembers is no proof of what the sink holds: its owner may have
1091
+ // taken the name off it since, while another sink was attached or the plugin was
1092
+ // uninstalled. A tool adopted on the memory alone would be in service on no sink.
1093
+ listed ??= new Map(sink.registered().map((entry) => [entry.name, entry]));
1094
+
1095
+ if (isStillKept(held, listed.get(tool.name))) {
1096
+ // The sink kept this name from the plugin's earlier install. The tool handed over
1097
+ // then is the one in service, so the very same tool is adopted where it stands and
1098
+ // any other would be a declaration the sink can never be given.
1099
+ if (held.tool !== tool) {
1100
+ throw new MountayaElementsError(
1101
+ `plugin ${plugin.id} cannot register ${tool.name}: the tool sink kept that name ` +
1102
+ "from an earlier install and would not release it. Install the declaration " +
1103
+ "that registered it, or stop reserving the plugin's vendor segment on the sink.",
1104
+ );
1105
+ }
1106
+
1107
+ adopted.push(held);
1108
+ continue;
1109
+ }
1110
+
1111
+ kept?.delete(tool.name);
1112
+ }
1113
+
1114
+ sink.register(tool);
1115
+ this.placed.set(tool.name, tool);
1116
+ registered.push(tool.name);
1117
+ }
1118
+ } catch (error) {
1119
+ for (const name of registered) {
1120
+ this.withdraw(name, plugin.id, sink);
1121
+ }
1122
+
1123
+ throw error instanceof Error
1124
+ ? error
1125
+ : new MountayaElementsError(`plugin ${plugin.id} failed to register a tool`, {
1126
+ cause: error,
1127
+ });
1128
+ }
1129
+
1130
+ for (const { tool } of adopted) {
1131
+ this.placed.set(tool.name, tool);
1132
+ kept?.delete(tool.name);
1133
+ }
1134
+
1135
+ return [...adopted.map(({ tool }) => tool.name), ...registered];
1136
+ }
1137
+
1138
+ /**
1139
+ * take is {@link adopt} with the refusal routed rather than thrown. Reports whether it landed.
1140
+ *
1141
+ * The one place the two postures meet: with a reporter a refusal is one plugin's problem, and
1142
+ * without one it is the caller's. Everything above that wants "apply what you can" goes through
1143
+ * here, and the atomicity `adopt` guarantees is untouched either way.
1144
+ */
1145
+ private take(
1146
+ plugin: StudioPlugin<TView>,
1147
+ onRefused: StudioPluginRefusalReporter<TView> | undefined,
1148
+ ): boolean {
1149
+ try {
1150
+ this.adopt(plugin);
1151
+ } catch (error) {
1152
+ this.report(error, plugin, onRefused);
1153
+
1154
+ return false;
1155
+ }
1156
+
1157
+ return true;
1158
+ }
1159
+
1160
+ /** report hands a refusal to the reporter, or rethrows it when there is none. */
1161
+ private report(
1162
+ error: unknown,
1163
+ plugin: StudioPlugin<TView>,
1164
+ onRefused: StudioPluginRefusalReporter<TView> | undefined,
1165
+ ): void {
1166
+ if (onRefused === undefined) {
1167
+ throw error;
1168
+ }
1169
+
1170
+ try {
1171
+ onRefused(error, plugin);
1172
+ } catch (fault) {
1173
+ // This path exists so that one refused plugin does not take its caller down, and a
1174
+ // reporter throwing while it reports one would put that back. Its fault is the caller's
1175
+ // defect, surfaced apart.
1176
+ surfaceFault(fault);
1177
+ }
1178
+ }
1179
+
1180
+ /** drop is uninstall without the notification. Reports whether the plugin was there. */
1181
+ private drop(pluginId: string): boolean {
1182
+ this.declared.delete(pluginId);
1183
+
1184
+ if (!this.plugins.has(pluginId)) {
1185
+ return false;
1186
+ }
1187
+
1188
+ const touched = new Set<StudioPluginSlot>(
1189
+ (this.entries.get(pluginId) ?? []).map((entry) => entry.slot),
1190
+ );
1191
+
1192
+ this.plugins.delete(pluginId);
1193
+ this.entries.delete(pluginId);
1194
+ this.snapshot = null;
1195
+ this.rebuild(touched);
1196
+
1197
+ // The sink last, once the registry's own state says the plugin is gone: nothing the sink
1198
+ // does while a name is taken back leaves the plugin half installed.
1199
+ for (const [name, owner] of [...this.toolNames]) {
1200
+ if (owner === pluginId) {
1201
+ this.toolNames.delete(name);
1202
+
1203
+ if (this.sink !== undefined) {
1204
+ this.withdraw(name, pluginId, this.sink);
1205
+ }
1206
+ }
1207
+ }
1208
+
1209
+ return true;
1210
+ }
1211
+
1212
+ /**
1213
+ * withdraw asks a sink for one name back, and remembers a name the sink would not give up.
1214
+ *
1215
+ * Only a name this registry put there ({@link placed}) is asked for: a name the sink holds
1216
+ * for somebody else was never this registry's to take back.
1217
+ *
1218
+ * `unregister` answers false for a name the sink never held and for one it refuses to release,
1219
+ * so the sink is asked whether it still lists the name. A tool left there stays in service
1220
+ * with no installed plugin behind it, and is remembered with the tool this registry handed
1221
+ * over: see {@link unreleased}. The sink is read by name, since it may hand back another object
1222
+ * than it was given.
1223
+ *
1224
+ * A fault the sink throws here is surfaced on a microtask and leaves through no caller: an
1225
+ * uninstall, a reconciliation and a move between sinks each finish what they were doing.
1226
+ */
1227
+ private withdraw(name: string, pluginId: string, sink: StudioPluginToolSink): void {
1228
+ const tool = this.placed.get(name);
1229
+ if (tool === undefined) {
1230
+ return;
1231
+ }
1232
+
1233
+ this.placed.delete(name);
1234
+
1235
+ let listed: { readonly name: string } | undefined;
1236
+
1237
+ try {
1238
+ if (sink.unregister(name)) {
1239
+ return;
1240
+ }
1241
+
1242
+ listed = sink.registered().find((held) => held.name === name);
1243
+ } catch (fault) {
1244
+ surfaceFault(fault);
1245
+
1246
+ return;
1247
+ }
1248
+
1249
+ if (listed === undefined) {
1250
+ return;
1251
+ }
1252
+
1253
+ const kept = this.unreleased.get(sink) ?? new Map<string, KeptTool>();
1254
+ kept.set(name, { listedAsGiven: listed === tool, pluginId, tool });
1255
+ this.unreleased.set(sink, kept);
1256
+ }
1257
+
1258
+ /**
1259
+ * rebuild re-materialises exactly the slots named, and nothing else.
1260
+ *
1261
+ * Only the touched ones, which is what makes "installing a `segment.menu` plugin leaves
1262
+ * `at('map.controls')` referentially identical" true: the property a memo keyed on a slot's
1263
+ * array depends on.
1264
+ */
1265
+ private rebuild(slots: ReadonlySet<StudioPluginSlot>): void {
1266
+ for (const slot of slots) {
1267
+ const found: StudioPluginEntry<TView>[] = [];
1268
+
1269
+ for (const entries of this.entries.values()) {
1270
+ for (const entry of entries) {
1271
+ if (entry.slot === slot) {
1272
+ found.push(entry);
1273
+ }
1274
+ }
1275
+ }
1276
+
1277
+ // Back to the ONE shared empty array when the last contribution leaves, so a slot that
1278
+ // emptied is identical to one that was never filled.
1279
+ this.setSlot(
1280
+ slot,
1281
+ found.length === 0 ? NO_CONTRIBUTIONS : Object.freeze(sortStudioContributions(found)),
1282
+ );
1283
+ }
1284
+ }
1285
+
1286
+ /**
1287
+ * setSlot writes one slot of the index.
1288
+ *
1289
+ * The second localized cast, and it is the mapped type's: writing through a key whose type is
1290
+ * the whole union makes TypeScript demand a value assignable to EVERY member's value type at
1291
+ * once, which nothing is. Moving the index to a `Map` would trade this cast for one in `at`,
1292
+ * the wrong side of the trade, since `at` is the member every render touches.
1293
+ */
1294
+ private setSlot(slot: StudioPluginSlot, entries: readonly StudioPluginEntry<TView>[]): void {
1295
+ (this.index as Record<StudioPluginSlot, readonly StudioPluginEntry<TView>[]>)[slot] = entries;
1296
+ }
1297
+
1298
+ /**
1299
+ * The collision scope a declaration of `pluginId` is validated against: the ids installed, and
1300
+ * every tool name already taken.
1301
+ *
1302
+ * `replacing` takes the installed plugin of that id back out of it: its id and the names it
1303
+ * brought, including the ones the sink is holding for it. That is what lets a replacement be
1304
+ * validated while its incumbent is still installed. Without it every re-declaration under an
1305
+ * unchanged id would read as `plugin_id_taken` plus one `tool_name_taken` per verb.
1306
+ *
1307
+ * A name the sink kept from an earlier install of the same id is the plugin's own either way,
1308
+ * and taken for every other plugin: see {@link unreleased}. It is the plugin's own only while
1309
+ * what the sink lists under it is still the tool it kept ({@link isStillKept}): a name its
1310
+ * owner gave another tool since is taken, for this plugin as for any other.
1311
+ */
1312
+ private scope(pluginId: string, replacing: boolean): StudioPluginValidationScope {
1313
+ const own = new Set<string>();
1314
+ const tools = new Set<string>();
1315
+ const kept = this.sink === undefined ? undefined : this.unreleased.get(this.sink);
1316
+ const listed = this.sink?.registered() ?? [];
1317
+ const listedByName = new Map(listed.map((tool) => [tool.name, tool]));
1318
+
1319
+ for (const [name, held] of kept ?? []) {
1320
+ if (held.pluginId === pluginId && isStillKept(held, listedByName.get(name))) {
1321
+ own.add(name);
1322
+ }
1323
+ }
1324
+
1325
+ for (const [name, owner] of this.toolNames) {
1326
+ if (replacing && owner === pluginId) {
1327
+ own.add(name);
1328
+ } else {
1329
+ tools.add(name);
1330
+ }
1331
+ }
1332
+
1333
+ for (const tool of listed) {
1334
+ if (!own.has(tool.name)) {
1335
+ tools.add(tool.name);
1336
+ }
1337
+ }
1338
+
1339
+ const installed = new Set(this.plugins.keys());
1340
+ if (replacing) {
1341
+ installed.delete(pluginId);
1342
+ }
1343
+
1344
+ return { installed, tools };
1345
+ }
1346
+
1347
+ /**
1348
+ * notify advances the version FIRST, so a listener reading `at` already sees the new list.
1349
+ *
1350
+ * Every listener is told, by the one rule the package's engines share (`notifyListeners`). A
1351
+ * listener that throws skips no listener after it and never leaves through the `install` or
1352
+ * `sync` that had already changed the state, which would break, from the outside, the
1353
+ * atomicity this class guarantees. Its fault is surfaced on a microtask.
1354
+ */
1355
+ private notify(): void {
1356
+ this.revision += 1;
1357
+
1358
+ notifyListeners(this.listeners);
1359
+ }
1360
+
1361
+ /** emit reports one run to every observer, by the rule {@link notify} follows. */
1362
+ private emit(event: StudioPluginRunEvent): void {
1363
+ notifyListeners(this.observers, event);
1364
+ }
1365
+ }