@mountaya/studio 0.0.0-stage → 0.1.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 (524) hide show
  1. package/CHANGELOG.md +39 -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 +2854 -0
  6. package/dist/agent/index.cjs.map +1 -0
  7. package/dist/agent/index.d.cts +1257 -0
  8. package/dist/agent/index.d.ts +1257 -0
  9. package/dist/agent/index.js +2818 -0
  10. package/dist/agent/index.js.map +1 -0
  11. package/dist/bus-BwiNiXdH.d.ts +514 -0
  12. package/dist/bus-DzmhPwdK.d.cts +514 -0
  13. package/dist/chainModel-B23pEP_1.d.cts +127 -0
  14. package/dist/chainModel-B23pEP_1.d.ts +127 -0
  15. package/dist/chunk-2HFY7ETU.js +5721 -0
  16. package/dist/chunk-2HFY7ETU.js.map +1 -0
  17. package/dist/chunk-355TOXSB.js +72 -0
  18. package/dist/chunk-355TOXSB.js.map +1 -0
  19. package/dist/chunk-4ZCUZVSV.js +10275 -0
  20. package/dist/chunk-4ZCUZVSV.js.map +1 -0
  21. package/dist/chunk-6HEKY3NF.js +95 -0
  22. package/dist/chunk-6HEKY3NF.js.map +1 -0
  23. package/dist/chunk-7GFLGGBX.cjs +8 -0
  24. package/dist/chunk-7GFLGGBX.cjs.map +1 -0
  25. package/dist/chunk-7NBRCENN.cjs +19 -0
  26. package/dist/chunk-7NBRCENN.cjs.map +1 -0
  27. package/dist/chunk-AF5GCXE3.js +8 -0
  28. package/dist/chunk-AF5GCXE3.js.map +1 -0
  29. package/dist/chunk-CJDIFRGZ.cjs +2005 -0
  30. package/dist/chunk-CJDIFRGZ.cjs.map +1 -0
  31. package/dist/chunk-CNPZY7N3.js +349 -0
  32. package/dist/chunk-CNPZY7N3.js.map +1 -0
  33. package/dist/chunk-DZJHTWSF.cjs +45 -0
  34. package/dist/chunk-DZJHTWSF.cjs.map +1 -0
  35. package/dist/chunk-EABIHHWA.js +42 -0
  36. package/dist/chunk-EABIHHWA.js.map +1 -0
  37. package/dist/chunk-EKZWV6RS.cjs +415 -0
  38. package/dist/chunk-EKZWV6RS.cjs.map +1 -0
  39. package/dist/chunk-EOKRXXAC.cjs +24 -0
  40. package/dist/chunk-EOKRXXAC.cjs.map +1 -0
  41. package/dist/chunk-F73W2ZTJ.js +1126 -0
  42. package/dist/chunk-F73W2ZTJ.js.map +1 -0
  43. package/dist/chunk-H4DVOZ5O.js +1897 -0
  44. package/dist/chunk-H4DVOZ5O.js.map +1 -0
  45. package/dist/chunk-HI52PBFT.cjs +10314 -0
  46. package/dist/chunk-HI52PBFT.cjs.map +1 -0
  47. package/dist/chunk-IDBXFBLG.cjs +1225 -0
  48. package/dist/chunk-IDBXFBLG.cjs.map +1 -0
  49. package/dist/chunk-LBWTJZUJ.js +297 -0
  50. package/dist/chunk-LBWTJZUJ.js.map +1 -0
  51. package/dist/chunk-NCLA6DKD.cjs +310 -0
  52. package/dist/chunk-NCLA6DKD.cjs.map +1 -0
  53. package/dist/chunk-O4MC5DPD.js +19 -0
  54. package/dist/chunk-O4MC5DPD.js.map +1 -0
  55. package/dist/chunk-OP37FKW6.cjs +98 -0
  56. package/dist/chunk-OP37FKW6.cjs.map +1 -0
  57. package/dist/chunk-OQSYFH3Z.cjs +5945 -0
  58. package/dist/chunk-OQSYFH3Z.cjs.map +1 -0
  59. package/dist/chunk-PACIO4NS.cjs +26 -0
  60. package/dist/chunk-PACIO4NS.cjs.map +1 -0
  61. package/dist/chunk-PSZ2R3TC.cjs +75 -0
  62. package/dist/chunk-PSZ2R3TC.cjs.map +1 -0
  63. package/dist/chunk-QFO5CZG2.cjs +136 -0
  64. package/dist/chunk-QFO5CZG2.cjs.map +1 -0
  65. package/dist/chunk-QL63MUEW.cjs +140 -0
  66. package/dist/chunk-QL63MUEW.cjs.map +1 -0
  67. package/dist/chunk-RFUPPVZO.js +17 -0
  68. package/dist/chunk-RFUPPVZO.js.map +1 -0
  69. package/dist/chunk-RPG2LWMP.js +23 -0
  70. package/dist/chunk-RPG2LWMP.js.map +1 -0
  71. package/dist/chunk-TIBXK6B7.cjs +12 -0
  72. package/dist/chunk-TIBXK6B7.cjs.map +1 -0
  73. package/dist/chunk-UU65VNEV.js +381 -0
  74. package/dist/chunk-UU65VNEV.js.map +1 -0
  75. package/dist/chunk-VGX6TR2I.js +209 -0
  76. package/dist/chunk-VGX6TR2I.js.map +1 -0
  77. package/dist/chunk-WUTDDBVP.js +130 -0
  78. package/dist/chunk-WUTDDBVP.js.map +1 -0
  79. package/dist/chunk-WVQQLKCI.cjs +224 -0
  80. package/dist/chunk-WVQQLKCI.cjs.map +1 -0
  81. package/dist/chunk-WZYXG3SE.js +111 -0
  82. package/dist/chunk-WZYXG3SE.js.map +1 -0
  83. package/dist/chunk-XDI2X3KE.js +6 -0
  84. package/dist/chunk-XDI2X3KE.js.map +1 -0
  85. package/dist/chunk-XKHLRIC7.cjs +381 -0
  86. package/dist/chunk-XKHLRIC7.cjs.map +1 -0
  87. package/dist/context-DNtd2WUv.d.cts +11666 -0
  88. package/dist/context-DgB72Bur.d.ts +11666 -0
  89. package/dist/directorThreads-CqmvsV8b.d.cts +80 -0
  90. package/dist/directorThreads-CqmvsV8b.d.ts +80 -0
  91. package/dist/en-Bu4Ti9Ev.d.cts +2315 -0
  92. package/dist/en-Bu4Ti9Ev.d.ts +2315 -0
  93. package/dist/engines/index.cjs +3446 -0
  94. package/dist/engines/index.cjs.map +1 -0
  95. package/dist/engines/index.d.cts +2216 -0
  96. package/dist/engines/index.d.ts +2216 -0
  97. package/dist/engines/index.js +3416 -0
  98. package/dist/engines/index.js.map +1 -0
  99. package/dist/handlers/index.cjs +99 -0
  100. package/dist/handlers/index.cjs.map +1 -0
  101. package/dist/handlers/index.d.cts +445 -0
  102. package/dist/handlers/index.d.ts +445 -0
  103. package/dist/handlers/index.js +42 -0
  104. package/dist/handlers/index.js.map +1 -0
  105. package/dist/index.cjs +4562 -0
  106. package/dist/index.cjs.map +1 -0
  107. package/dist/index.d.cts +7297 -0
  108. package/dist/index.d.ts +7297 -0
  109. package/dist/index.js +3223 -0
  110. package/dist/index.js.map +1 -0
  111. package/dist/plugins/index.cjs +977 -0
  112. package/dist/plugins/index.cjs.map +1 -0
  113. package/dist/plugins/index.d.cts +313 -0
  114. package/dist/plugins/index.d.ts +313 -0
  115. package/dist/plugins/index.js +933 -0
  116. package/dist/plugins/index.js.map +1 -0
  117. package/dist/saveFile-j-1kkApx.d.cts +123 -0
  118. package/dist/saveFile-j-1kkApx.d.ts +123 -0
  119. package/dist/seams/index.cjs +152 -0
  120. package/dist/seams/index.cjs.map +1 -0
  121. package/dist/seams/index.d.cts +485 -0
  122. package/dist/seams/index.d.ts +485 -0
  123. package/dist/seams/index.js +79 -0
  124. package/dist/seams/index.js.map +1 -0
  125. package/dist/shareLink-B6hlt942.d.ts +144 -0
  126. package/dist/shareLink-C7rIMb7x.d.ts +527 -0
  127. package/dist/shareLink-CnTxxXjp.d.cts +144 -0
  128. package/dist/shareLink-DyZVYH2V.d.cts +527 -0
  129. package/dist/strings/fr/index.cjs +2121 -0
  130. package/dist/strings/fr/index.cjs.map +1 -0
  131. package/dist/strings/fr/index.d.cts +19 -0
  132. package/dist/strings/fr/index.d.ts +19 -0
  133. package/dist/strings/fr/index.js +2119 -0
  134. package/dist/strings/fr/index.js.map +1 -0
  135. package/dist/strings/index.cjs +2678 -0
  136. package/dist/strings/index.cjs.map +1 -0
  137. package/dist/strings/index.d.cts +731 -0
  138. package/dist/strings/index.d.ts +731 -0
  139. package/dist/strings/index.js +2644 -0
  140. package/dist/strings/index.js.map +1 -0
  141. package/dist/studioPlugin-C3C7VjMy.d.ts +847 -0
  142. package/dist/studioPlugin-Cf3OBNUv.d.cts +847 -0
  143. package/dist/tabs-B2nRO4p_.d.cts +15 -0
  144. package/dist/tabs-B2nRO4p_.d.ts +15 -0
  145. package/dist/testing/index.cjs +292 -0
  146. package/dist/testing/index.cjs.map +1 -0
  147. package/dist/testing/index.d.cts +306 -0
  148. package/dist/testing/index.d.ts +306 -0
  149. package/dist/testing/index.js +284 -0
  150. package/dist/testing/index.js.map +1 -0
  151. package/dist/time/index.cjs +28 -0
  152. package/dist/time/index.cjs.map +1 -0
  153. package/dist/time/index.d.cts +43 -0
  154. package/dist/time/index.d.ts +43 -0
  155. package/dist/time/index.js +26 -0
  156. package/dist/time/index.js.map +1 -0
  157. package/dist/types-BzJRV6UI.d.cts +845 -0
  158. package/dist/types-BzJRV6UI.d.ts +845 -0
  159. package/dist/zoneForm-CdYNtnnA.d.cts +320 -0
  160. package/dist/zoneForm-mG85yt5e.d.ts +320 -0
  161. package/package.json +225 -4
  162. package/src/agent/engines/agentThreads.ts +1601 -0
  163. package/src/agent/engines/directorChat.ts +500 -0
  164. package/src/agent/index.ts +67 -0
  165. package/src/agent/rules/agentEditLock.ts +115 -0
  166. package/src/agent/rules/agentErrorCopy.ts +44 -0
  167. package/src/agent/rules/copilotOrganization.ts +36 -0
  168. package/src/agent/rules/playbook.gen.ts +444 -0
  169. package/src/agent/rules/router.ts +518 -0
  170. package/src/agent/rules/stateDelta.ts +28 -0
  171. package/src/agent/rules/studioRouter.ts +123 -0
  172. package/src/agent/rules/surfaces.gen.ts +633 -0
  173. package/src/agent/rules/threadsUrl.ts +48 -0
  174. package/src/agent/rules/transcriptObserver.ts +90 -0
  175. package/src/agent/stores/agentThreads.ts +454 -0
  176. package/src/bus/contracts/noData.ts +18 -0
  177. package/src/bus/contracts/shared.ts +172 -0
  178. package/src/bus/contracts/studioTools.ts +224 -0
  179. package/src/bus/rules/bus.ts +858 -0
  180. package/src/bus/rules/confirmation.ts +22 -0
  181. package/src/bus/rules/defineRegistry.ts +26 -0
  182. package/src/bus/rules/errors.ts +401 -0
  183. package/src/bus/rules/handlerErrors.ts +103 -0
  184. package/src/bus/rules/handlerRegistry.ts +627 -0
  185. package/src/bus/rules/inputSchema.ts +232 -0
  186. package/src/bus/rules/invalidInput.ts +441 -0
  187. package/src/bus/rules/lateBoundTools.ts +100 -0
  188. package/src/bus/rules/studioRegistry.ts +324 -0
  189. package/src/bus/rules/studioToolBus.ts +73 -0
  190. package/src/bus/rules/types.ts +805 -0
  191. package/src/chrome/contracts/alert.ts +42 -0
  192. package/src/chrome/contracts/itinerary.ts +26 -0
  193. package/src/chrome/contracts/map.ts +23 -0
  194. package/src/chrome/contracts/overlay.ts +46 -0
  195. package/src/chrome/contracts/panel.ts +29 -0
  196. package/src/chrome/contracts/question.ts +52 -0
  197. package/src/chrome/contracts/selection.ts +26 -0
  198. package/src/chrome/contracts/sidenav.ts +23 -0
  199. package/src/chrome/contracts/snapshot.ts +319 -0
  200. package/src/chrome/contracts/state.ts +22 -0
  201. package/src/chrome/contracts/tabs.ts +56 -0
  202. package/src/chrome/handlers/alert.ts +91 -0
  203. package/src/chrome/handlers/introspection.ts +180 -0
  204. package/src/chrome/handlers/panels.ts +42 -0
  205. package/src/chrome/handlers/question.ts +24 -0
  206. package/src/chrome/handlers/sidenav.ts +116 -0
  207. package/src/chrome/handlers/snapshot.ts +451 -0
  208. package/src/chrome/handlers/stateDelta.ts +125 -0
  209. package/src/chrome/handlers/tabs.ts +143 -0
  210. package/src/chrome/handlers/timestamp.ts +19 -0
  211. package/src/chrome/rules/agentSelectors.ts +210 -0
  212. package/src/chrome/rules/mapAlert.ts +13 -0
  213. package/src/chrome/rules/question.ts +25 -0
  214. package/src/chrome/rules/tabs.ts +13 -0
  215. package/src/chrome/stores/activeDraftSession.ts +134 -0
  216. package/src/chrome/stores/chrome.ts +527 -0
  217. package/src/chrome/stores/uiStore.ts +573 -0
  218. package/src/collab/contracts/collab.ts +261 -0
  219. package/src/collab/handlers/collab.ts +468 -0
  220. package/src/collab/rules/toolNames.ts +33 -0
  221. package/src/collab/stores/collab.ts +899 -0
  222. package/src/collections/contracts/collection.ts +182 -0
  223. package/src/collections/handlers/collectionAttach.ts +141 -0
  224. package/src/collections/handlers/collections.ts +499 -0
  225. package/src/collections/handlers/heldCollection.ts +42 -0
  226. package/src/collections/handlers/restCollections.ts +386 -0
  227. package/src/collections/rules/collections.ts +138 -0
  228. package/src/collections/rules/entityCollections.ts +53 -0
  229. package/src/collections/stores/collections.ts +133 -0
  230. package/src/data/contracts/data.ts +233 -0
  231. package/src/data/contracts/itinerary.ts +71 -0
  232. package/src/data/handlers/activityResolve.ts +76 -0
  233. package/src/data/handlers/data.ts +200 -0
  234. package/src/data/handlers/graphql.ts +26 -0
  235. package/src/data/handlers/mutationSink.ts +1577 -0
  236. package/src/data/handlers/profile.ts +83 -0
  237. package/src/data/handlers/writeThrough.ts +417 -0
  238. package/src/data/rules/cache.ts +181 -0
  239. package/src/data/rules/dataTypes.ts +40 -0
  240. package/src/data/rules/keys.ts +106 -0
  241. package/src/data/rules/persistence.ts +1058 -0
  242. package/src/data/rules/requestBody.ts +43 -0
  243. package/src/data/rules/restErrors.ts +354 -0
  244. package/src/data/rules/sessionSurface.ts +156 -0
  245. package/src/data/rules/toolResultData.ts +73 -0
  246. package/src/data/rules/uuid.ts +24 -0
  247. package/src/edit/contracts/edit.ts +37 -0
  248. package/src/edit/contracts/itinerary.ts +57 -0
  249. package/src/edit/handlers/draftCommit.ts +257 -0
  250. package/src/edit/handlers/editDiscard.ts +34 -0
  251. package/src/edit/handlers/editLock.ts +949 -0
  252. package/src/edit/handlers/editor.ts +203 -0
  253. package/src/edit/handlers/formUnsaved.ts +24 -0
  254. package/src/edit/rules/draftMetadata.ts +117 -0
  255. package/src/edit/rules/editKeyboard.ts +222 -0
  256. package/src/edit/rules/editShortcuts.ts +102 -0
  257. package/src/edit/rules/editTooltip.ts +174 -0
  258. package/src/edit/rules/editorTaken.ts +49 -0
  259. package/src/edit/rules/history.ts +26 -0
  260. package/src/edit/rules/unsavedWork.ts +60 -0
  261. package/src/edit/stores/editorReservation.ts +70 -0
  262. package/src/edit/stores/formsUnsaved.ts +54 -0
  263. package/src/embed/contracts/embed.ts +48 -0
  264. package/src/embed/engines/embedFraming.ts +1329 -0
  265. package/src/embed/engines/embedReady.ts +353 -0
  266. package/src/embed/engines/framingPageSession.ts +169 -0
  267. package/src/embed/handlers/embed.ts +130 -0
  268. package/src/embed/rules/allowedDomains.ts +71 -0
  269. package/src/embed/rules/bridgeMessages.ts +224 -0
  270. package/src/embed/rules/defaults.ts +173 -0
  271. package/src/embed/rules/displaySeed.ts +115 -0
  272. package/src/embed/rules/embedAllowlist.ts +146 -0
  273. package/src/embed/rules/embedConstraints.ts +215 -0
  274. package/src/embed/rules/embedElements.ts +277 -0
  275. package/src/embed/rules/embedSectionFields.ts +126 -0
  276. package/src/embed/rules/embedSecurity.ts +116 -0
  277. package/src/embed/rules/fieldDependencies.ts +87 -0
  278. package/src/embed/rules/fieldOptions.ts +138 -0
  279. package/src/embed/rules/layerOptions.ts +161 -0
  280. package/src/embed/rules/readyProtocol.ts +66 -0
  281. package/src/embed/rules/safetyRules.ts +213 -0
  282. package/src/embed/rules/snippet.ts +531 -0
  283. package/src/embed/rules/tableCode.ts +269 -0
  284. package/src/embed/stores/embed.ts +60 -0
  285. package/src/embed/stores/embedContent.ts +77 -0
  286. package/src/engines/index.ts +81 -0
  287. package/src/handlers/index.ts +66 -0
  288. package/src/index.ts +1086 -0
  289. package/src/itinerary/contracts/itinerary.ts +705 -0
  290. package/src/itinerary/engines/itineraryPace.ts +612 -0
  291. package/src/itinerary/engines/profileMarker.ts +238 -0
  292. package/src/itinerary/handlers/importStaging.ts +352 -0
  293. package/src/itinerary/handlers/itinerary.ts +572 -0
  294. package/src/itinerary/handlers/itineraryDuplicate.ts +177 -0
  295. package/src/itinerary/handlers/itineraryExport.ts +117 -0
  296. package/src/itinerary/handlers/itineraryImport.ts +783 -0
  297. package/src/itinerary/handlers/itineraryPublish.ts +118 -0
  298. package/src/itinerary/handlers/itinerarySelection.ts +354 -0
  299. package/src/itinerary/handlers/itinerarySuggest.ts +1186 -0
  300. package/src/itinerary/handlers/itineraryUnpublish.ts +101 -0
  301. package/src/itinerary/handlers/publicationScope.ts +118 -0
  302. package/src/itinerary/handlers/restItineraries.ts +752 -0
  303. package/src/itinerary/handlers/restItineraryExport.ts +70 -0
  304. package/src/itinerary/handlers/restItineraryImport.ts +311 -0
  305. package/src/itinerary/handlers/restItineraryPace.ts +87 -0
  306. package/src/itinerary/handlers/restItineraryRecord.ts +36 -0
  307. package/src/itinerary/handlers/suggestParams.ts +379 -0
  308. package/src/itinerary/handlers/suggestStaging.ts +363 -0
  309. package/src/itinerary/handlers/surfaceOpen.ts +389 -0
  310. package/src/itinerary/rules/activity.ts +139 -0
  311. package/src/itinerary/rules/analysis.ts +42 -0
  312. package/src/itinerary/rules/ceiling.ts +49 -0
  313. package/src/itinerary/rules/createFlow.ts +107 -0
  314. package/src/itinerary/rules/densify.ts +440 -0
  315. package/src/itinerary/rules/draftSurface.ts +219 -0
  316. package/src/itinerary/rules/editorView.ts +83 -0
  317. package/src/itinerary/rules/export.ts +159 -0
  318. package/src/itinerary/rules/friendlyName.ts +77 -0
  319. package/src/itinerary/rules/import.ts +1052 -0
  320. package/src/itinerary/rules/importFiles.ts +140 -0
  321. package/src/itinerary/rules/importTotals.ts +77 -0
  322. package/src/itinerary/rules/liveSegment.ts +712 -0
  323. package/src/itinerary/rules/lngLat.ts +17 -0
  324. package/src/itinerary/rules/mapSync.ts +100 -0
  325. package/src/itinerary/rules/previewRender.ts +416 -0
  326. package/src/itinerary/rules/profileReadout.ts +216 -0
  327. package/src/itinerary/rules/routing.ts +707 -0
  328. package/src/itinerary/rules/suggest.ts +522 -0
  329. package/src/itinerary/rules/suggestionPreview.ts +119 -0
  330. package/src/itinerary/rules/view.ts +61 -0
  331. package/src/itinerary/stores/importSession.ts +319 -0
  332. package/src/itinerary/stores/itinerary.ts +331 -0
  333. package/src/itinerary/stores/itineraryDuplicate.ts +76 -0
  334. package/src/itinerary/stores/sessionIdentity.ts +43 -0
  335. package/src/itinerary/stores/suggestSession.ts +418 -0
  336. package/src/layers/contracts/itinerary.ts +46 -0
  337. package/src/layers/contracts/overlay.ts +132 -0
  338. package/src/layers/handlers/enrichment.ts +36 -0
  339. package/src/layers/handlers/overlay.ts +406 -0
  340. package/src/layers/handlers/restLayers.ts +94 -0
  341. package/src/layers/handlers/tiles.ts +25 -0
  342. package/src/layers/rules/layers.ts +212 -0
  343. package/src/layers/rules/overlayInstant.ts +12 -0
  344. package/src/layers/rules/reachabilityIcon.ts +18 -0
  345. package/src/layers/rules/readout.ts +102 -0
  346. package/src/layers/stores/layers.ts +262 -0
  347. package/src/map/contracts/contextmenu.ts +33 -0
  348. package/src/map/contracts/geolocate.ts +37 -0
  349. package/src/map/contracts/map.ts +146 -0
  350. package/src/map/contracts/streetview.ts +53 -0
  351. package/src/map/contracts/terrain.ts +152 -0
  352. package/src/map/handlers/contextMenu.ts +135 -0
  353. package/src/map/handlers/geolocate.ts +52 -0
  354. package/src/map/handlers/map.ts +391 -0
  355. package/src/map/handlers/streetview.ts +94 -0
  356. package/src/map/handlers/terrain.ts +663 -0
  357. package/src/map/rules/baseTerrain.ts +75 -0
  358. package/src/map/rules/clickTargets.ts +464 -0
  359. package/src/map/rules/constraints.ts +32 -0
  360. package/src/map/rules/contextMenuReadout.ts +67 -0
  361. package/src/map/rules/coordinates.ts +71 -0
  362. package/src/map/rules/itineraryFit.ts +8 -0
  363. package/src/map/rules/mapEvents.ts +64 -0
  364. package/src/map/rules/mapProjection.ts +476 -0
  365. package/src/map/rules/terrainReading.ts +62 -0
  366. package/src/plugins/contracts/ids.ts +66 -0
  367. package/src/plugins/contracts/plugin.ts +200 -0
  368. package/src/plugins/contracts/slots.ts +137 -0
  369. package/src/plugins/engines/studioPlugin.ts +1365 -0
  370. package/src/plugins/index.ts +111 -0
  371. package/src/plugins/rules/contributions.ts +152 -0
  372. package/src/plugins/rules/errors.ts +60 -0
  373. package/src/plugins/rules/ids.ts +42 -0
  374. package/src/plugins/rules/validation.ts +249 -0
  375. package/src/rules/listeners.ts +57 -0
  376. package/src/rules/origin.ts +13 -0
  377. package/src/rules/storeWrite.ts +37 -0
  378. package/src/rules/types.ts +136 -0
  379. package/src/seams/index.ts +79 -0
  380. package/src/seams/rules/clock.ts +28 -0
  381. package/src/seams/rules/formatters.ts +209 -0
  382. package/src/seams/rules/ids.ts +102 -0
  383. package/src/seams/rules/links.ts +66 -0
  384. package/src/seams/rules/navigation.ts +222 -0
  385. package/src/seams/rules/notify.ts +49 -0
  386. package/src/seams/rules/persistenceDrawer.ts +220 -0
  387. package/src/seams/rules/saveFile.ts +101 -0
  388. package/src/seams/rules/seams.ts +156 -0
  389. package/src/seams/rules/storage.ts +116 -0
  390. package/src/search/contracts/overlay.ts +74 -0
  391. package/src/search/contracts/search.ts +197 -0
  392. package/src/search/handlers/pois.ts +57 -0
  393. package/src/search/handlers/search.ts +280 -0
  394. package/src/search/rules/params.ts +925 -0
  395. package/src/search/rules/poiGroups.ts +138 -0
  396. package/src/search/rules/searchFetch.ts +139 -0
  397. package/src/search/rules/timeWindow.ts +30 -0
  398. package/src/search/stores/search.ts +51 -0
  399. package/src/segments/contracts/itinerary.ts +433 -0
  400. package/src/segments/contracts/segment.ts +35 -0
  401. package/src/segments/engines/segmentDraft.ts +926 -0
  402. package/src/segments/handlers/chainGuards.ts +67 -0
  403. package/src/segments/handlers/directions.ts +44 -0
  404. package/src/segments/handlers/itineraryEcho.ts +45 -0
  405. package/src/segments/handlers/roadAccessDialog.ts +34 -0
  406. package/src/segments/handlers/segment.ts +111 -0
  407. package/src/segments/handlers/segmentEdit.ts +1341 -0
  408. package/src/segments/handlers/segmentGroups.ts +347 -0
  409. package/src/segments/handlers/segmentStructure.ts +1144 -0
  410. package/src/segments/rules/chain.ts +196 -0
  411. package/src/segments/rules/chainModel.ts +217 -0
  412. package/src/segments/rules/colors.ts +11 -0
  413. package/src/segments/rules/commit.ts +76 -0
  414. package/src/segments/rules/draft.ts +90 -0
  415. package/src/segments/rules/draftDisposition.ts +43 -0
  416. package/src/segments/rules/draftSegmentEdit.ts +129 -0
  417. package/src/segments/rules/engine.ts +222 -0
  418. package/src/segments/rules/groupSave.ts +234 -0
  419. package/src/segments/rules/hazardPrompt.ts +60 -0
  420. package/src/segments/rules/itineraryEcho.ts +40 -0
  421. package/src/segments/rules/liveSegmentProjection.ts +55 -0
  422. package/src/segments/rules/merge.ts +51 -0
  423. package/src/segments/rules/metrics.ts +456 -0
  424. package/src/segments/rules/naming.ts +168 -0
  425. package/src/segments/rules/segmentArming.ts +144 -0
  426. package/src/segments/rules/splitPick.ts +84 -0
  427. package/src/segments/rules/viaSimplify.ts +230 -0
  428. package/src/segments/stores/directions.ts +77 -0
  429. package/src/segments/stores/roadAccessDialog.ts +58 -0
  430. package/src/segments/stores/segmentEdit.ts +922 -0
  431. package/src/segments/stores/segmentGroupEdit.ts +84 -0
  432. package/src/segments/stores/segmentSplit.ts +77 -0
  433. package/src/share/contracts/share.ts +39 -0
  434. package/src/share/contracts/shareLink.ts +63 -0
  435. package/src/share/engines/shareLink.ts +1053 -0
  436. package/src/share/handlers/share.ts +47 -0
  437. package/src/share/handlers/shareLink.ts +231 -0
  438. package/src/share/handlers/shareScope.ts +54 -0
  439. package/src/share/rules/link.ts +89 -0
  440. package/src/share/rules/shareLink.ts +218 -0
  441. package/src/share/rules/targets.ts +92 -0
  442. package/src/share/rules/viewConfig.ts +95 -0
  443. package/src/share/stores/share.ts +58 -0
  444. package/src/strings/fr/index.ts +18 -0
  445. package/src/strings/fr/rules/fr.ts +2368 -0
  446. package/src/strings/index.ts +98 -0
  447. package/src/strings/rules/confirmCopy.ts +156 -0
  448. package/src/strings/rules/draftToolNames.ts +94 -0
  449. package/src/strings/rules/en.ts +2519 -0
  450. package/src/strings/rules/failureAlert.ts +115 -0
  451. package/src/strings/rules/formError.ts +400 -0
  452. package/src/strings/rules/maneuvers.ts +107 -0
  453. package/src/strings/rules/outputOptions.ts +126 -0
  454. package/src/strings/rules/publicationState.ts +100 -0
  455. package/src/strings/rules/routeHazardCopy.ts +62 -0
  456. package/src/strings/rules/searchLabels.ts +50 -0
  457. package/src/strings/rules/segmentChainVerbs.ts +62 -0
  458. package/src/strings/rules/studioCopy.ts +130 -0
  459. package/src/strings/rules/unitOptions.ts +119 -0
  460. package/src/testing/checkedBus.ts +226 -0
  461. package/src/testing/index.ts +34 -0
  462. package/src/testing/plugins.ts +106 -0
  463. package/src/testing/studio.ts +267 -0
  464. package/src/testing/urlSeam.ts +153 -0
  465. package/src/time/index.ts +12 -0
  466. package/src/time/rules/sun.ts +78 -0
  467. package/src/video/contracts/cameraSchemas.ts +266 -0
  468. package/src/video/contracts/profileSchemas.ts +37 -0
  469. package/src/video/contracts/video.ts +601 -0
  470. package/src/video/handlers/video.ts +1638 -0
  471. package/src/video/handlers/videoDirector.ts +114 -0
  472. package/src/video/rules/previewRefresh.ts +76 -0
  473. package/src/video/rules/profileSource.ts +51 -0
  474. package/src/video/rules/routeSpans.ts +79 -0
  475. package/src/video/rules/shotDefaults.ts +28 -0
  476. package/src/video/rules/stepOrder.ts +17 -0
  477. package/src/video/rules/videoSnapshot.ts +136 -0
  478. package/src/video/stores/directorThreads.ts +167 -0
  479. package/src/video/stores/videoExport.ts +290 -0
  480. package/src/viewer/contracts/preferences.ts +40 -0
  481. package/src/viewer/handlers/preferences.ts +91 -0
  482. package/src/viewer/rules/capabilities.ts +42 -0
  483. package/src/viewer/rules/config.ts +266 -0
  484. package/src/viewer/rules/context.ts +375 -0
  485. package/src/viewer/rules/ownership.ts +134 -0
  486. package/src/viewer/rules/platformViewer.ts +198 -0
  487. package/src/viewer/rules/scope.ts +197 -0
  488. package/src/viewer/rules/url.ts +145 -0
  489. package/src/viewer/rules/viewer.ts +307 -0
  490. package/src/viewer/rules/viewerSeam.ts +49 -0
  491. package/src/viewer/rules/viewerUnits.ts +34 -0
  492. package/src/waypoints/contracts/itinerary.ts +417 -0
  493. package/src/waypoints/handlers/poiWaypointStyle.ts +32 -0
  494. package/src/waypoints/handlers/waypointDetailsDialog.ts +38 -0
  495. package/src/waypoints/handlers/waypointEdit.ts +1073 -0
  496. package/src/waypoints/rules/amenities.ts +30 -0
  497. package/src/waypoints/rules/defaults.ts +31 -0
  498. package/src/waypoints/rules/details.ts +213 -0
  499. package/src/waypoints/rules/detailsDraft.ts +312 -0
  500. package/src/waypoints/rules/detailsPreview.ts +76 -0
  501. package/src/waypoints/rules/detailsSave.ts +356 -0
  502. package/src/waypoints/rules/draftDirty.ts +45 -0
  503. package/src/waypoints/rules/icons.ts +32 -0
  504. package/src/waypoints/rules/liveWaypoint.ts +63 -0
  505. package/src/waypoints/rules/naming.ts +185 -0
  506. package/src/waypoints/rules/sections.ts +77 -0
  507. package/src/waypoints/rules/waypointDraft.ts +62 -0
  508. package/src/waypoints/stores/waypointDetails.ts +62 -0
  509. package/src/waypoints/stores/waypointEdit.ts +566 -0
  510. package/src/zones/contracts/collection.ts +37 -0
  511. package/src/zones/contracts/zone.ts +528 -0
  512. package/src/zones/engines/zoneForm.ts +1773 -0
  513. package/src/zones/handlers/restZones.ts +287 -0
  514. package/src/zones/handlers/zonePublish.ts +206 -0
  515. package/src/zones/handlers/zoneUnpublish.ts +56 -0
  516. package/src/zones/handlers/zones.ts +2254 -0
  517. package/src/zones/rules/geometry.ts +946 -0
  518. package/src/zones/rules/zoneDefaults.ts +34 -0
  519. package/src/zones/rules/zoneDraft.ts +54 -0
  520. package/src/zones/rules/zoneForm.ts +563 -0
  521. package/src/zones/rules/zoneMetadata.ts +29 -0
  522. package/src/zones/rules/zoneSource.ts +87 -0
  523. package/src/zones/rules/zoneSourceRefusal.ts +104 -0
  524. package/src/zones/stores/zoneEdit.ts +998 -0
@@ -0,0 +1,3416 @@
1
+ import { embedConstraintsFor, measuredCanvas, resolveFramedError, buildReadyPayload, buildSegmentEditOptions, draftChangeDisposition, routeHazardConfirmation, EMBED_COVER_MAX_MS, PROFILE_MARKER_THROTTLE_MS } from '../chunk-CNPZY7N3.js';
2
+ import { layerToolContext } from '../chunk-RFUPPVZO.js';
3
+ import { zoneSourceRefused } from '../chunk-EABIHHWA.js';
4
+ import { ITINERARY_FIT_MAX_ZOOM, isRetryableShareLinkFailure, tokenlessAnswerRefusal, isShareLinkDisableSettled, shareLinkActions, ZONE_DEFAULT_DISTANCE_RANGE_METERS, ZONE_DEFAULT_TIME_RANGE_SECONDS, zoneSaveRequest, canEditOwnedResource, firstRoutableActivityId, zoneAutoName, parametersOf, activityIdForSlug, activityForId, typedOver, windowOpens, zoneSourceQuery, isZoneMetadataDirty, isZoneSourceDirty, isZoneWindowInvalid, isZoneGeometryDirty, ZONE_PREVIEW_DEBOUNCE_MS } from '../chunk-UU65VNEV.js';
5
+ import { issuedShareTokenSchema, REQUEST_SESSION_TOKEN_MESSAGE, segmentEditSessionMark, synthesizeDraftSegment, DEFAULT_ZONE_MODE, DEFAULT_ZONE_LEVEL, DEFAULT_ZONE_CREATE_METHOD, zoneNameSchema, zoneDescriptionSchema, setSessionTokenMessageSchema, buildLiveSegment } from '../chunk-F73W2ZTJ.js';
6
+ import { surfaceFault, notifyListeners } from '../chunk-RPG2LWMP.js';
7
+ import { isConfirmationWithheld } from '../chunk-O4MC5DPD.js';
8
+ import { failureFromThrown } from '../chunk-WUTDDBVP.js';
9
+ import { segmentGeometries, segmentsForSelection } from '@mountaya/elements/data';
10
+ import { boundsOf, buildSegmentGeometry, DIRECTIONS_VIA_MAX } from '@mountaya/elements/geo';
11
+ import { embedFitPadding } from '@mountaya/elements/profile';
12
+ import { MountayaElementsError } from '@mountaya/elements/errors';
13
+ import { TrailingThrottle, LIVE_SEGMENT_THROTTLE_MS } from '@mountaya/elements/collab';
14
+ import * as z from 'zod';
15
+ import { localizedName } from '@mountaya/elements/i18n';
16
+
17
+ var baseMapContent = { collectionId: null, itineraryId: null };
18
+ var sameContent = (a, b) => a.collectionId === b.collectionId && a.itineraryId === b.itineraryId;
19
+ var isBaseMap = (content) => sameContent(content, baseMapContent);
20
+ var collectionOf = (config) => config.fitCollection === void 0 ? null : config.collection ?? null;
21
+ var expectsCollectionOf = (config) => config.fitCollection !== void 0 && config.expectsCollection === true;
22
+ var expectsContent = (config) => config.expectsItinerary || expectsCollectionOf(config);
23
+ var contentOf = (config) => {
24
+ if (config.itinerary !== null) {
25
+ return { collectionId: null, itineraryId: config.itinerary.id };
26
+ }
27
+ const collection = collectionOf(config);
28
+ return collection === null || config.expectsItinerary ? baseMapContent : { collectionId: collection.id, itineraryId: null };
29
+ };
30
+ var lockSizeOf = (config) => config.lockCanvasSize === void 0 ? config.canvasSize : config.lockCanvasSize;
31
+ var questionOf = (config, client) => ({
32
+ canvasHeight: config.canvasSize?.height ?? null,
33
+ canvasWidth: config.canvasSize?.width ?? null,
34
+ client,
35
+ collectionBounds: collectionOf(config)?.bounds ?? null,
36
+ collectionId: collectionOf(config)?.id ?? null,
37
+ expectsCollection: expectsCollectionOf(config),
38
+ expectsItinerary: config.expectsItinerary,
39
+ itinerary: config.itinerary,
40
+ lockHeight: lockSizeOf(config)?.height ?? null,
41
+ lockWidth: lockSizeOf(config)?.width ?? null,
42
+ measuredPanelHeight: config.measuredPanelHeight,
43
+ showAnalysis: config.sections.showAnalysis,
44
+ showCharacteristics: config.sections.showCharacteristics,
45
+ showElevation: config.sections.showElevation,
46
+ zoomMax: config.zoomRange.zoomMax,
47
+ zoomMin: config.zoomRange.zoomMin
48
+ });
49
+ var sameQuestion = (a, b) => a.client === b.client && a.itinerary === b.itinerary && a.expectsItinerary === b.expectsItinerary && a.collectionId === b.collectionId && sameLock(a.collectionBounds, b.collectionBounds) && a.expectsCollection === b.expectsCollection && Object.is(a.measuredPanelHeight, b.measuredPanelHeight) && Object.is(a.canvasWidth, b.canvasWidth) && Object.is(a.canvasHeight, b.canvasHeight) && Object.is(a.lockWidth, b.lockWidth) && Object.is(a.lockHeight, b.lockHeight) && a.showAnalysis === b.showAnalysis && a.showCharacteristics === b.showCharacteristics && a.showElevation === b.showElevation && Object.is(a.zoomMax, b.zoomMax) && Object.is(a.zoomMin, b.zoomMin);
50
+ var sameSize = (a, b) => a === null || b === null ? a === b : Object.is(a.width, b.width) && Object.is(a.height, b.height);
51
+ var largestOf = (a, b) => {
52
+ const first = measuredCanvas(a);
53
+ const second = measuredCanvas(b);
54
+ if (first === null || second === null) {
55
+ return first ?? second;
56
+ }
57
+ return {
58
+ height: Math.max(first.height, second.height),
59
+ width: Math.max(first.width, second.width)
60
+ };
61
+ };
62
+ var laidOutAtNoArea = (size) => size !== null && Number.isFinite(size.width) && Number.isFinite(size.height) && (size.width <= 0 || size.height <= 0);
63
+ var isEmpty = (constraints) => constraints.maxBounds === void 0 && constraints.maxZoom === void 0 && constraints.minZoom === void 0;
64
+ var sameLock = (a, b) => a === null || a === void 0 || b === null || b === void 0 ? a === b : a.every((edge, index) => Object.is(edge, b[index]));
65
+ var standsAs = (decided, applied) => (decided.maxBounds === void 0 || sameLock(decided.maxBounds, applied.maxBounds)) && (decided.maxZoom === void 0 || Object.is(decided.maxZoom, applied.maxZoom)) && (decided.minZoom === void 0 || Object.is(decided.minZoom, applied.minZoom));
66
+ var sameRange = (a, b) => Object.is(a.zoomMax, b.zoomMax) && Object.is(a.zoomMin, b.zoomMin);
67
+ var EmbedFramingEngine = class {
68
+ config;
69
+ snapshot;
70
+ listeners = /* @__PURE__ */ new Set();
71
+ /** The client the framing below was made on; a replaced one starts from nothing. */
72
+ framingClient = null;
73
+ /** The question the last framing step answered, or null when the next step must run in full. */
74
+ asked = null;
75
+ /** The fit waiting for its paint, or null. */
76
+ pendingFit = null;
77
+ /** The settle with no fit waiting for its paint, or null. */
78
+ pendingReveal = null;
79
+ /**
80
+ * Whether a settle has been reported on {@link framingClient}. Until one has, a publisher's own
81
+ * view settles without waiting for its itinerary, which is what lifts a cold load's cover.
82
+ */
83
+ reported = false;
84
+ /**
85
+ * The constraints the last itinerary or collection framed on {@link framingClient} left
86
+ * standing, or null.
87
+ */
88
+ standing = null;
89
+ /**
90
+ * Every constraint written to {@link framingClient}, each member as it was written last. A
91
+ * member never written is absent, so the first write of anything is news.
92
+ */
93
+ applied = {};
94
+ /**
95
+ * Whether a pan lock stands on {@link framingClient}. The next constraints that decide no lock
96
+ * (the base map alone, an itinerary with no extent) release it.
97
+ */
98
+ locked = false;
99
+ /**
100
+ * Whether a content switch made with nothing framed is still unanswered: an itinerary or a
101
+ * collection is, or was, expected, or the configured id changed, and since then nothing was
102
+ * framed and the base map alone was not set to settle again. A switch that ends with nothing to
103
+ * frame settles the base map again. Answered when that settle starts, not when it paints, so an
104
+ * expectation that rises after it is a wait of its own, owed its own settle.
105
+ */
106
+ awaited;
107
+ /** The configured itinerary's id as last stated, or undefined when it was left out. */
108
+ configuredId;
109
+ /** Whether nobody is watching. A parked engine frames nothing and reports nothing. */
110
+ parked = true;
111
+ disposed = false;
112
+ /**
113
+ * Constructing one holds the configuration and does nothing else: no client is read, framed or
114
+ * constrained. A React binding constructs during a render React is free to throw away, and a
115
+ * constructor with a side effect would leave the discarded copy framing.
116
+ */
117
+ constructor(config) {
118
+ this.config = config;
119
+ const content = contentOf(config);
120
+ this.awaited = isBaseMap(content) && expectsContent(config);
121
+ this.configuredId = config.configuredItineraryId;
122
+ this.snapshot = { bounds: null, framed: false, ...content };
123
+ }
124
+ /** getSnapshot returns the current answer, by reference and stable between changes. */
125
+ getSnapshot() {
126
+ return this.snapshot;
127
+ }
128
+ /**
129
+ * subscribe registers a listener for every change of the snapshot, and returns its own
130
+ * unsubscribe, which is idempotent.
131
+ *
132
+ * The first listener resumes the engine and the last one leaving parks it, which is the whole
133
+ * lifecycle a component can express correctly: React tears an effect down and sets it up again
134
+ * with the same object under StrictMode, so a latch here would leave a live surface bound to a
135
+ * dead engine.
136
+ */
137
+ subscribe(listener) {
138
+ if (this.disposed) {
139
+ return () => void 0;
140
+ }
141
+ const subscription = () => listener();
142
+ this.listeners.add(subscription);
143
+ if (this.parked) {
144
+ this.parked = false;
145
+ this.step();
146
+ }
147
+ return () => {
148
+ if (!this.listeners.delete(subscription) || this.listeners.size > 0 || this.parked) {
149
+ return;
150
+ }
151
+ this.parked = true;
152
+ };
153
+ }
154
+ /**
155
+ * configure replaces the configuration, and frames again only when what a framing is decided
156
+ * from changed.
157
+ *
158
+ * A binding calls it after every render, so it compares the inputs a framing reads (the client
159
+ * and the itinerary by identity, the rest by value) and does nothing more when they are
160
+ * unchanged: `fit`, `fitCollection` and `onFramed` are read when they are used, so a fresh
161
+ * closure per render costs nothing. Parked or not, the snapshot answers for the new content,
162
+ * and for a replaced client, before this returns: unframed, under the active id, until its
163
+ * framing settles. Only the framing waits for a subscriber.
164
+ */
165
+ configure(config) {
166
+ if (this.disposed) {
167
+ return;
168
+ }
169
+ this.config = config;
170
+ if (config.client !== this.framingClient) {
171
+ this.restart(config.client);
172
+ }
173
+ const content = contentOf(config);
174
+ if (!sameContent(content, this.snapshot)) {
175
+ this.asked = null;
176
+ this.publish({ bounds: null, framed: false, ...content });
177
+ }
178
+ const configuredId = config.configuredItineraryId;
179
+ const switched = configuredId !== void 0 && this.configuredId !== void 0 && configuredId !== this.configuredId;
180
+ this.configuredId = configuredId;
181
+ if (isBaseMap(content) && !this.awaited && (expectsContent(config) || switched)) {
182
+ this.awaited = true;
183
+ this.asked = null;
184
+ }
185
+ this.step();
186
+ }
187
+ /**
188
+ * dispose parks the engine and drops every listener, for good: a settle still on its way reports
189
+ * nothing.
190
+ *
191
+ * Idempotent, and every call after it is a no-op rather than an error: an owner torn down
192
+ * mid-load should not have to guard the calls it already queued.
193
+ */
194
+ dispose() {
195
+ if (this.disposed) {
196
+ return;
197
+ }
198
+ this.disposed = true;
199
+ this.parked = true;
200
+ this.pendingFit = null;
201
+ this.pendingReveal = null;
202
+ this.listeners.clear();
203
+ }
204
+ /**
205
+ * step brings the framing in line with the configuration. It runs in full only when the question
206
+ * changed since the last step, when the active itinerary did, or when work the last one started
207
+ * was dropped while parked.
208
+ */
209
+ step() {
210
+ if (this.parked || this.disposed) {
211
+ return;
212
+ }
213
+ const { client } = this.config;
214
+ if (client !== this.framingClient) {
215
+ this.restart(client);
216
+ }
217
+ if (client === null) {
218
+ return;
219
+ }
220
+ const question = questionOf(this.config, client);
221
+ if (this.asked !== null && (sameQuestion(this.asked, question) || sameQuestion(this.asked, this.whileFitting(question)))) {
222
+ return;
223
+ }
224
+ this.asked = question;
225
+ this.frame(client, question);
226
+ }
227
+ /**
228
+ * whileFitting answers `question` as the fit on its way was asked it, when the canvas has since
229
+ * gone to nothing: neither size the configuration states measures anything (see
230
+ * `measuredCanvas`). A canvas with no area has nothing to frame, so it asks nothing new, the fit
231
+ * on its way stands, and a canvas that comes back at the size that fit was asked for is the
232
+ * question already answered. With no fit on its way, or while either size still measures
233
+ * something, the question is the configuration's own.
234
+ *
235
+ * It is read to compare and never to record: another input that changes while the canvas
236
+ * measures nothing is a question of its own, recorded with the sizes the configuration states.
237
+ * It starts no fit while the page has laid the canvas out at no area (see {@link unlaid}), so
238
+ * the canvas that comes back is the one framed for it.
239
+ */
240
+ whileFitting(question) {
241
+ const asked = this.asked;
242
+ if (asked === null || this.pendingFit === null || largestOf(this.config.canvasSize, lockSizeOf(this.config)) !== null) {
243
+ return question;
244
+ }
245
+ return {
246
+ ...question,
247
+ canvasHeight: asked.canvasHeight,
248
+ canvasWidth: asked.canvasWidth,
249
+ lockHeight: asked.lockHeight,
250
+ lockWidth: asked.lockWidth
251
+ };
252
+ }
253
+ /**
254
+ * restart forgets every framing made on the previous client, so a replaced client (or the map
255
+ * arriving) frames and locks from nothing. A settle still on its way for the previous client is
256
+ * dropped.
257
+ */
258
+ restart(client) {
259
+ this.framingClient = client;
260
+ this.asked = null;
261
+ this.pendingFit = null;
262
+ this.pendingReveal = null;
263
+ this.reported = false;
264
+ this.standing = null;
265
+ this.locked = false;
266
+ this.applied = {};
267
+ const content = contentOf(this.config);
268
+ if (this.snapshot.framed || !sameContent(this.snapshot, content)) {
269
+ this.publish({ bounds: null, framed: false, ...content });
270
+ }
271
+ }
272
+ /** frame runs one framing step for `question` on `client`. */
273
+ frame(client, question) {
274
+ const { itinerary, zoomRange } = this.config;
275
+ const deferred = client.hadInitialViewHash();
276
+ const content = contentOf(this.config);
277
+ const collection = collectionOf(this.config);
278
+ if (isBaseMap(content)) {
279
+ this.pendingFit = null;
280
+ if (this.pendingReveal !== null && !isBaseMap(this.pendingReveal)) {
281
+ this.pendingReveal = null;
282
+ }
283
+ if (expectsContent(this.config)) {
284
+ this.awaitContent(client, deferred);
285
+ } else {
286
+ this.showBaseMap(client);
287
+ }
288
+ return;
289
+ }
290
+ this.awaited = false;
291
+ if (this.pendingReveal !== null && isBaseMap(this.pendingReveal)) {
292
+ this.pendingReveal = null;
293
+ }
294
+ if (this.settledFor(content) || this.pendingReveal !== null && sameContent(this.pendingReveal, content)) {
295
+ this.rangeAgain(client, content);
296
+ this.lockAgain(client, content);
297
+ return;
298
+ }
299
+ if (!deferred && (this.unlaid() || this.resizing())) {
300
+ this.awaitResize(client);
301
+ return;
302
+ }
303
+ const bounds = itinerary === null ? collection?.bounds ?? null : boundsOf(segmentGeometries(segmentsForSelection(itinerary, null)));
304
+ const padding = embedFitPadding(
305
+ {
306
+ showAnalysis: question.showAnalysis,
307
+ showCharacteristics: question.showCharacteristics,
308
+ showElevation: question.showElevation
309
+ },
310
+ question.measuredPanelHeight
311
+ );
312
+ const framing = !deferred && bounds !== null ? client.cameraForBounds(bounds, padding, ITINERARY_FIT_MAX_ZOOM) : null;
313
+ const input = {
314
+ bounds,
315
+ // The larger of the two sizes: under a publisher's own view the lock is sized for a canvas
316
+ // the page has laid out and the renderer has yet to resize to. Under a fit the two agree.
317
+ canvasSize: largestOf(this.config.canvasSize, lockSizeOf(this.config)),
318
+ framing,
319
+ padding,
320
+ // Read before the lock is applied: the camera no fit will move, which the lock must hold.
321
+ view: deferred ? client.getViewport() : null,
322
+ zoomRange
323
+ };
324
+ this.standing = { content, input };
325
+ this.constrain(client, embedConstraintsFor(input));
326
+ if (deferred) {
327
+ this.revealWithoutFit(client, bounds, content);
328
+ return;
329
+ }
330
+ const pending = { bounds, ...content };
331
+ this.pendingFit = pending;
332
+ const fitting = itinerary === null && collection !== null && this.config.fitCollection !== void 0 ? this.config.fitCollection(collection.bounds, padding, ITINERARY_FIT_MAX_ZOOM) : this.config.fit(padding);
333
+ fitting.then(() => client.waitForRender()).then(
334
+ () => {
335
+ if (this.pendingFit !== pending) {
336
+ return;
337
+ }
338
+ this.pendingFit = null;
339
+ if (this.parked || this.disposed) {
340
+ this.asked = null;
341
+ return;
342
+ }
343
+ if (this.resizing()) {
344
+ return;
345
+ }
346
+ if (this.asked !== question && this.unlaid()) {
347
+ this.asked = null;
348
+ return;
349
+ }
350
+ this.settle(pending);
351
+ },
352
+ () => {
353
+ if (this.pendingFit === pending) {
354
+ this.pendingFit = null;
355
+ }
356
+ }
357
+ );
358
+ }
359
+ /**
360
+ * resizing reports whether the page has laid the canvas out at a size the renderer has yet to
361
+ * resize to: `lockCanvasSize` measures a canvas `canvasSize` does not state. Never with no
362
+ * `lockCanvasSize`, and never while it measures nothing.
363
+ */
364
+ resizing() {
365
+ const ahead = measuredCanvas(lockSizeOf(this.config));
366
+ return ahead !== null && !sameSize(ahead, measuredCanvas(this.config.canvasSize));
367
+ }
368
+ /**
369
+ * unlaid reports whether the page has laid the canvas out at no area: no size the
370
+ * configuration states measures anything, and one of them, `canvasSize` or `lockCanvasSize`,
371
+ * states a layout with no area (see {@link laidOutAtNoArea}). An embed mounted in a frame
372
+ * nobody is shown yet reads so. Never for a host that states no size at all, or one that is
373
+ * not a number: neither is a layout, and the embed is framed as it stands.
374
+ *
375
+ * A renderer gives a container with no area a canvas of its own default size, so a fit asked
376
+ * for now would frame a canvas nobody sees, and its settle would report a view the reader is
377
+ * never shown.
378
+ */
379
+ unlaid() {
380
+ const { canvasSize } = this.config;
381
+ const lockSize = lockSizeOf(this.config);
382
+ return largestOf(canvasSize, lockSize) === null && (laidOutAtNoArea(canvasSize) || laidOutAtNoArea(lockSize));
383
+ }
384
+ /**
385
+ * awaitResize runs the framing step for an itinerary a fit frames while there is no canvas to
386
+ * frame yet: the page has laid it out at no area (see {@link unlaid}), or the renderer has yet
387
+ * to resize to it (see {@link resizing}). It starts no fit, since one asked for now would
388
+ * frame the canvas as it was, and it leaves a fit already on its way in flight. The step that
389
+ * finds a canvas with an area, at a size the two agree on, frames in full, and the fit it
390
+ * starts replaces that one.
391
+ *
392
+ * What stands on the client meanwhile is what {@link awaitContent} leaves there. The pan lock
393
+ * of the last framing, this itinerary's or the outgoing one's, is widened for the size ahead
394
+ * (see {@link lockAgain}), so the renderer resizes inside it. On a client nothing was framed
395
+ * on, the organization's zoom range applies at once: it reads no canvas, so it has nothing to
396
+ * wait for, and a host whose two sizes never agree is not left with a map no range holds.
397
+ */
398
+ awaitResize(client) {
399
+ if (this.standing === null) {
400
+ this.constrain(client, this.zoomRangeAlone());
401
+ } else {
402
+ this.rangeAgain(client, this.standing.content);
403
+ this.lockAgain(client, this.standing.content);
404
+ }
405
+ }
406
+ /**
407
+ * awaitContent runs the framing step for an itinerary or a collection that is expected and not
408
+ * framed yet: the itinerary's detail is loading, a content switch cleared the outgoing one
409
+ * first, or the collection's specification has not answered.
410
+ *
411
+ * The constraints of the last itinerary or collection framed on this client stay until the next
412
+ * framing replaces them, the zoom floor that framing lowered included; the pan lock among them
413
+ * still follows a canvas that outgrows it (see {@link lockAgain}). On a client nothing was
414
+ * framed on, the organization's zoom range applies at once.
415
+ */
416
+ awaitContent(client, deferred) {
417
+ if (this.standing === null) {
418
+ this.constrain(client, this.zoomRangeAlone());
419
+ } else {
420
+ this.rangeAgain(client, this.standing.content);
421
+ this.lockAgain(client, this.standing.content);
422
+ }
423
+ if (deferred && !this.reported) {
424
+ this.revealWithoutFit(client, null, baseMapContent);
425
+ }
426
+ }
427
+ /**
428
+ * showBaseMap runs the framing step for the base map alone: no itinerary or collection is
429
+ * framed and none is expected. The organization's zoom range applies as it is, the pan lock an
430
+ * itinerary or a collection left standing is released (see {@link constrain}), and the view
431
+ * settles on the map's next render.
432
+ */
433
+ showBaseMap(client) {
434
+ this.standing = null;
435
+ this.constrain(client, this.zoomRangeAlone());
436
+ if (this.awaited) {
437
+ this.awaited = false;
438
+ if (this.snapshot.framed) {
439
+ this.publish({ bounds: null, framed: false, ...baseMapContent });
440
+ }
441
+ }
442
+ this.revealWithoutFit(client, null, baseMapContent);
443
+ }
444
+ /** zoomRangeAlone decides the constraints with no itinerary to lock to: the zoom range alone. */
445
+ zoomRangeAlone() {
446
+ return embedConstraintsFor({
447
+ bounds: null,
448
+ canvasSize: null,
449
+ framing: null,
450
+ padding: 0,
451
+ zoomRange: this.config.zoomRange
452
+ });
453
+ }
454
+ /**
455
+ * rangeAgain applies the configuration's zoom range over the framing of `content` when it is not
456
+ * the range that framing was decided from: the same route, camera, canvas and padding, under
457
+ * the range as it is stated now. The zoom range alone, so the pan lock stays as it is and no
458
+ * camera is moved by a fit.
459
+ *
460
+ * The floor is the one a framing under this range would have set, lowered to the zoom the fit
461
+ * landed on, so a range that arrives late leaves the embed where it would have opened. A range
462
+ * that does not state both ends decides no clamp, so the one on the map is released
463
+ * (see {@link rangeRelease}).
464
+ */
465
+ rangeAgain(client, content) {
466
+ const standing = this.standing;
467
+ const { zoomRange } = this.config;
468
+ if (standing === null || !sameContent(standing.content, content) || sameRange(standing.input.zoomRange, zoomRange)) {
469
+ return;
470
+ }
471
+ const input = { ...standing.input, zoomRange };
472
+ this.standing = { content, input };
473
+ const { maxZoom, minZoom } = embedConstraintsFor(input);
474
+ this.apply(
475
+ client,
476
+ maxZoom !== void 0 && minZoom !== void 0 ? { maxZoom, minZoom } : this.rangeRelease()
477
+ );
478
+ }
479
+ /**
480
+ * rangeRelease is the constraints that release the zoom range this engine wrote to the client:
481
+ * a null for each end, which hands the map back its own window. Nothing while no range of the
482
+ * engine's stands there, so a map no range was written to is told nothing.
483
+ */
484
+ rangeRelease() {
485
+ const { maxZoom, minZoom } = this.applied;
486
+ return typeof maxZoom === "number" || typeof minZoom === "number" ? { maxZoom: null, minZoom: null } : {};
487
+ }
488
+ /**
489
+ * lockAgain widens the pan lock of the framing of `content` when the canvas has outgrown the one
490
+ * it was sized for: the same route, camera and padding, on a canvas as wide as the widest and as
491
+ * tall as the tallest it has been handed since the framing, as `canvasSize` or as
492
+ * `lockCanvasSize`. The lock alone, so the zoom range stays as the framing set it, and no
493
+ * camera is moved.
494
+ *
495
+ * The lock only grows. The renderer keeps its canvas inside the lock at the size the canvas has
496
+ * when the lock is applied, and a new size is handed over before the renderer resizes: a lock
497
+ * sized for a smaller canvas would be narrower than the one the renderer still holds. A canvas
498
+ * that reads unmeasured changes nothing either.
499
+ */
500
+ lockAgain(client, content) {
501
+ const standing = this.standing;
502
+ if (standing === null || !sameContent(standing.content, content) || standing.input.bounds === null) {
503
+ return;
504
+ }
505
+ const sizedFor = measuredCanvas(standing.input.canvasSize);
506
+ const largest = largestOf(sizedFor, largestOf(this.config.canvasSize, lockSizeOf(this.config)));
507
+ if (largest === null || sameSize(sizedFor, largest)) {
508
+ return;
509
+ }
510
+ const input = { ...standing.input, canvasSize: largest };
511
+ this.standing = { content, input };
512
+ const { maxBounds } = embedConstraintsFor(input);
513
+ if (maxBounds !== void 0) {
514
+ this.apply(client, { maxBounds });
515
+ }
516
+ }
517
+ /**
518
+ * constrain applies one framing step's constraints, in one call, and only when they decide
519
+ * something.
520
+ *
521
+ * Constraints that decide no pan lock release the one standing, with a null `maxBounds`: there
522
+ * is no route left to hold the camera to, whether the embed is the base map alone or its next
523
+ * itinerary has no extent. Constraints that decide no zoom range release the one standing the
524
+ * same way (see {@link rangeRelease}): the configuration states none any more.
525
+ */
526
+ constrain(client, decided) {
527
+ const ranged = decided.maxZoom === void 0 ? { ...decided, ...this.rangeRelease() } : decided;
528
+ const constraints = ranged.maxBounds === void 0 && this.locked ? { ...ranged, maxBounds: null } : ranged;
529
+ this.apply(client, constraints);
530
+ if (constraints.maxBounds !== void 0) {
531
+ this.locked = constraints.maxBounds !== null;
532
+ }
533
+ }
534
+ /**
535
+ * apply writes `constraints` to the client, unless they decide nothing or every member they
536
+ * state already stands there as stated. A resize under the zoom range alone, and a framing
537
+ * asked again for the inputs it had, decide what the map already holds, and writing it again
538
+ * would have the renderer enforce an unchanged range and lock once more.
539
+ *
540
+ * The set is written whole when any member is news, so a caller's one call stays one call.
541
+ */
542
+ apply(client, constraints) {
543
+ if (isEmpty(constraints) || standsAs(constraints, this.applied)) {
544
+ return;
545
+ }
546
+ client.setConstraints(constraints);
547
+ this.applied = { ...this.applied, ...constraints };
548
+ }
549
+ /**
550
+ * revealWithoutFit settles the view on the map's next render, for a view no fit will move: an
551
+ * embed of the base map alone, an itinerary that failed to load, or a publisher's own view.
552
+ *
553
+ * Once for what it answers, `content`: a view already settled for it, or settling, is left
554
+ * alone. A settle on its way for anything else is replaced, since both would wait on the same
555
+ * render and only the active one is worth reporting.
556
+ */
557
+ revealWithoutFit(client, bounds, content) {
558
+ if (this.settledFor(content) || this.pendingReveal !== null && sameContent(this.pendingReveal, content)) {
559
+ return;
560
+ }
561
+ const pending = { bounds, ...content };
562
+ this.pendingReveal = pending;
563
+ client.waitForRender().then(
564
+ () => {
565
+ if (this.pendingReveal !== pending) {
566
+ return;
567
+ }
568
+ this.pendingReveal = null;
569
+ if (this.parked || this.disposed) {
570
+ this.asked = null;
571
+ return;
572
+ }
573
+ this.settle(pending);
574
+ },
575
+ () => {
576
+ if (this.pendingReveal === pending) {
577
+ this.pendingReveal = null;
578
+ }
579
+ }
580
+ );
581
+ }
582
+ /**
583
+ * settledFor reports whether the initial view of `content` has settled on the current client.
584
+ * The snapshot is the one record of it: it answers for the active content and reads unframed
585
+ * from a content switch, or a replaced client, until that settle.
586
+ */
587
+ settledFor(content) {
588
+ return this.snapshot.framed && sameContent(this.snapshot, content);
589
+ }
590
+ /**
591
+ * settle reports one settle: through the snapshot, then to `onFramed`. A settle on its way for
592
+ * anything but the active content is dropped before it lands (see {@link frame}), so the
593
+ * snapshot is written only for the content it answers for, and never goes back to a content
594
+ * the reader has left.
595
+ */
596
+ settle(pending) {
597
+ this.reported = true;
598
+ if (sameContent(pending, contentOf(this.config))) {
599
+ this.publish({
600
+ bounds: pending.bounds,
601
+ collectionId: pending.collectionId,
602
+ framed: true,
603
+ itineraryId: pending.itineraryId
604
+ });
605
+ }
606
+ try {
607
+ this.config.onFramed?.(pending.bounds);
608
+ } catch (fault) {
609
+ surfaceFault(fault);
610
+ }
611
+ }
612
+ /** publish shows `snapshot` and tells every listener. */
613
+ publish(snapshot) {
614
+ this.snapshot = snapshot;
615
+ notifyListeners(this.listeners);
616
+ }
617
+ };
618
+ var MAX_TIMER_MS = 2 ** 31 - 1;
619
+
620
+ // src/embed/engines/embedReady.ts
621
+ var coveredSnapshot = { covered: true };
622
+ var revealedSnapshot = { covered: false };
623
+ var timeoutFrom = (timeoutMs) => {
624
+ if (timeoutMs === void 0) {
625
+ return EMBED_COVER_MAX_MS;
626
+ }
627
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMER_MS) {
628
+ throw new MountayaElementsError(
629
+ `EmbedReadyEngine: timeoutMs is ${String(timeoutMs)}; pass a number of milliseconds from 0 to ${MAX_TIMER_MS}, or omit it for ${EMBED_COVER_MAX_MS}.`
630
+ );
631
+ }
632
+ return timeoutMs;
633
+ };
634
+ var EmbedReadyEngine = class {
635
+ config;
636
+ clock;
637
+ timeoutMs;
638
+ snapshot = coveredSnapshot;
639
+ listeners = /* @__PURE__ */ new Set();
640
+ /** The deadline waiting on the clock, or null while none is. */
641
+ deadline = null;
642
+ /** Whether nobody is watching. A parked engine arms nothing and posts nothing. */
643
+ parked = true;
644
+ disposed = false;
645
+ /**
646
+ * Constructing one holds the options and does nothing else: no deadline is armed and nothing is
647
+ * posted. A React binding constructs during a render React is free to throw away, and a
648
+ * constructor with a side effect would leave the discarded copy waiting.
649
+ *
650
+ * @throws {MountayaElementsError} When `timeoutMs` is not a finite number from 0 to
651
+ * 2,147,483,647.
652
+ */
653
+ constructor(options) {
654
+ const { clock, timeoutMs, ...config } = options;
655
+ this.clock = clock;
656
+ this.timeoutMs = timeoutFrom(timeoutMs);
657
+ this.config = config;
658
+ }
659
+ /** getSnapshot returns the current answer, by reference and stable between changes. */
660
+ getSnapshot() {
661
+ return this.snapshot;
662
+ }
663
+ /**
664
+ * subscribe registers a listener for every change of the snapshot, and returns its own
665
+ * unsubscribe, which is idempotent.
666
+ *
667
+ * The first listener resumes the engine and the last one leaving parks it, which is the whole
668
+ * lifecycle a component can express correctly: React tears an effect down and sets it up again
669
+ * with the same object under StrictMode, so a latch here would leave a live surface bound to a
670
+ * dead engine. A binding hands its framework a STABLE `subscribe`; a fresh closure per render
671
+ * parks and resumes on every render.
672
+ */
673
+ subscribe(listener) {
674
+ if (this.disposed) {
675
+ return () => void 0;
676
+ }
677
+ const subscription = () => listener();
678
+ this.listeners.add(subscription);
679
+ if (this.parked) {
680
+ this.parked = false;
681
+ this.arm();
682
+ }
683
+ return () => {
684
+ if (!this.listeners.delete(subscription) || this.listeners.size > 0 || this.parked) {
685
+ return;
686
+ }
687
+ this.parked = true;
688
+ this.disarm();
689
+ };
690
+ }
691
+ /**
692
+ * configure replaces the configuration the next ready event is assembled from. It moves nothing:
693
+ * the deadline stays where it is and a posted event stays posted, so a binding calls it after
694
+ * every render at the cost of an assignment.
695
+ */
696
+ configure(config) {
697
+ if (!this.disposed) {
698
+ this.config = config;
699
+ }
700
+ }
701
+ /**
702
+ * settle reports that the initial view has painted, framed on `bounds` (`[west, south, east,
703
+ * north]`, the itinerary's or the collection's, or null when neither frames it): the cover lifts
704
+ * and a ready event is posted.
705
+ * Called on the cold load and again after every content switch, and each call posts. A call
706
+ * while parked, or after {@link EmbedReadyEngine.dispose}, does nothing.
707
+ */
708
+ settle(bounds) {
709
+ if (this.parked || this.disposed) {
710
+ return;
711
+ }
712
+ const { configuredItineraryId, itineraryFailed } = this.config;
713
+ this.disarm();
714
+ this.reveal();
715
+ this.post(bounds, resolveFramedError(configuredItineraryId, itineraryFailed));
716
+ }
717
+ /**
718
+ * dispose drops the deadline and every listener, for good.
719
+ *
720
+ * Idempotent, and every call after it is a no-op rather than an error: an owner torn down
721
+ * mid-load should not have to guard the calls it already queued.
722
+ */
723
+ dispose() {
724
+ if (this.disposed) {
725
+ return;
726
+ }
727
+ this.disposed = true;
728
+ this.parked = true;
729
+ this.disarm();
730
+ this.listeners.clear();
731
+ }
732
+ /** arm waits out the deadline while the cover is up. */
733
+ arm() {
734
+ if (!this.snapshot.covered || this.deadline !== null) {
735
+ return;
736
+ }
737
+ const deadline = { cancel: () => void 0 };
738
+ this.deadline = deadline;
739
+ deadline.cancel = this.clock.after(this.timeoutMs, () => {
740
+ if (this.deadline !== deadline) {
741
+ return;
742
+ }
743
+ this.deadline = null;
744
+ this.expire();
745
+ });
746
+ }
747
+ /** disarm drops the deadline, if one is armed. */
748
+ disarm() {
749
+ const deadline = this.deadline;
750
+ this.deadline = null;
751
+ deadline?.cancel();
752
+ }
753
+ /**
754
+ * expire lifts the cover at the deadline and says `"timeout"`. It runs only for the deadline the
755
+ * engine still holds, so the engine is watched and nothing has settled: a settle, a park and a
756
+ * dispose each drop the deadline, and a lifted cover arms no other.
757
+ */
758
+ expire() {
759
+ this.reveal();
760
+ this.post(null, "timeout");
761
+ }
762
+ /** post hands one ready event to the host, assembled from the configuration as it stands. */
763
+ post(bounds, error) {
764
+ const { activeItineraryId, activeTerrain, configTerrain, onReady } = this.config;
765
+ const payload = buildReadyPayload({
766
+ activeItineraryId,
767
+ activeTerrain,
768
+ bounds,
769
+ configTerrain,
770
+ error
771
+ });
772
+ try {
773
+ onReady?.(payload);
774
+ } catch (fault) {
775
+ surfaceFault(fault);
776
+ }
777
+ }
778
+ /** reveal lifts the cover, and tells every listener when that is news. */
779
+ reveal() {
780
+ if (this.snapshot === revealedSnapshot) {
781
+ return;
782
+ }
783
+ this.snapshot = revealedSnapshot;
784
+ notifyListeners(this.listeners);
785
+ }
786
+ };
787
+ var FRAMING_PAGE_SESSION_TIMEOUT_MS = 1e4;
788
+ var timeoutFrom2 = (timeoutMs) => {
789
+ if (timeoutMs === void 0) {
790
+ return FRAMING_PAGE_SESSION_TIMEOUT_MS;
791
+ }
792
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {
793
+ throw new MountayaElementsError(
794
+ `askFramingPageForSession: timeoutMs is ${String(timeoutMs)}; pass a number of milliseconds from 1 to ${MAX_TIMER_MS}, or omit it for ${FRAMING_PAGE_SESSION_TIMEOUT_MS}.`
795
+ );
796
+ }
797
+ return timeoutMs;
798
+ };
799
+ var askFramingPageForSession = (options) => {
800
+ const timeoutMs = timeoutFrom2(options.timeoutMs);
801
+ const { clock, embed } = options;
802
+ return new Promise((resolve, reject) => {
803
+ if (Object.is(embed.parent, embed)) {
804
+ reject(
805
+ new MountayaElementsError(
806
+ "askFramingPageForSession: the embed is not framed, so no page can hand it a session token."
807
+ )
808
+ );
809
+ return;
810
+ }
811
+ let cancel = () => {
812
+ };
813
+ const listener = (event) => {
814
+ if (event.source !== embed.parent) {
815
+ return;
816
+ }
817
+ const parsed = setSessionTokenMessageSchema.safeParse(event.data);
818
+ if (!parsed.success) {
819
+ return;
820
+ }
821
+ cancel();
822
+ embed.removeEventListener("message", listener);
823
+ resolve({
824
+ expires_at: new Date(parsed.data.expiresAt),
825
+ token: parsed.data.token,
826
+ user_id: null
827
+ });
828
+ };
829
+ embed.addEventListener("message", listener);
830
+ cancel = clock.after(timeoutMs, () => {
831
+ embed.removeEventListener("message", listener);
832
+ reject(
833
+ new MountayaElementsError(
834
+ `askFramingPageForSession: the framing page answered no session token within ${timeoutMs} ms.`
835
+ )
836
+ );
837
+ });
838
+ embed.parent.postMessage({ type: REQUEST_SESSION_TOKEN_MESSAGE }, "*");
839
+ });
840
+ };
841
+
842
+ // src/itinerary/handlers/restItineraryPace.ts
843
+ var fetchItineraryPace = async (client, itineraryId, { signal, speedKmh, surface }) => {
844
+ const params = {
845
+ itinerary_id: itineraryId,
846
+ // The absent option is omitted rather than sent empty, the shape the export
847
+ // uses: the server reads its own default for an omitted parameter.
848
+ query: {
849
+ speed: speedKmh,
850
+ ...surface === void 0 ? {} : { surface }
851
+ }
852
+ };
853
+ const { data } = await (signal === void 0 ? client.studio.itineraries.getItineraryPace(params) : client.studio.itineraries.getItineraryPace(params, { signal }));
854
+ return {
855
+ bySegmentId: new Map(data.segments.map((segment) => [segment.id, segment])),
856
+ durationSeconds: data.duration
857
+ };
858
+ };
859
+
860
+ // src/itinerary/engines/itineraryPace.ts
861
+ var PACE_DEBOUNCE_MS = 250;
862
+ var PACE_ANSWER_CAPACITY = 32;
863
+ var isRateStep = (shown, next) => shown !== null && shown.client === next.client && shown.itineraryId === next.itineraryId && shown.revision === next.revision && shown.surface === next.surface;
864
+ var revisionKey = (revision) => `${typeof revision}\0${revision ?? ""}`;
865
+ var paceKey = (itineraryId, speedKmh, surface, revision) => [itineraryId, speedKmh, surface ?? "", revision].join("\0");
866
+ var debounceFrom = (debounceMs) => {
867
+ if (debounceMs === void 0) {
868
+ return PACE_DEBOUNCE_MS;
869
+ }
870
+ if (!Number.isFinite(debounceMs) || debounceMs < 0 || debounceMs > MAX_TIMER_MS) {
871
+ throw new MountayaElementsError(
872
+ `ItineraryPaceEngine: debounceMs is ${String(debounceMs)}; pass a number of milliseconds from 0 to ${MAX_TIMER_MS}, or omit it for ${PACE_DEBOUNCE_MS}.`
873
+ );
874
+ }
875
+ return debounceMs;
876
+ };
877
+ var ItineraryPaceEngine = class {
878
+ config;
879
+ debounceMs;
880
+ snapshot = null;
881
+ /** The question the snapshot answers, or null while it is null. */
882
+ shown = null;
883
+ listeners = /* @__PURE__ */ new Set();
884
+ /**
885
+ * The answers the current client has given and the engine keeps, by their {@link paceKey}, in
886
+ * the order they were last read: the first is the least recently read.
887
+ */
888
+ answers = /* @__PURE__ */ new Map();
889
+ /** The re-time on its way, or null. */
890
+ inFlight = null;
891
+ timer = null;
892
+ /** Whether nobody is watching. A parked engine asks for nothing. */
893
+ parked = true;
894
+ disposed = false;
895
+ /**
896
+ * Constructing one holds the options and does nothing else: no timer and no request. A React
897
+ * binding constructs during a render React is free to throw away, and a constructor with a
898
+ * side effect would leave the discarded copy asking.
899
+ *
900
+ * @throws {MountayaElementsError} When `debounceMs` is not a finite number from 0 to
901
+ * 2,147,483,647.
902
+ */
903
+ constructor(options) {
904
+ const { debounceMs, ...config } = options;
905
+ this.debounceMs = debounceFrom(debounceMs);
906
+ this.config = config;
907
+ }
908
+ /** getSnapshot returns the current answer, by reference and stable between changes. */
909
+ getSnapshot() {
910
+ return this.snapshot;
911
+ }
912
+ /**
913
+ * subscribe registers a listener for every change of the snapshot, and returns its own
914
+ * unsubscribe.
915
+ *
916
+ * The first listener resumes the engine and the last one leaving parks it, which is the whole
917
+ * lifecycle a component can express correctly: React tears an effect down and sets it up again
918
+ * with the same object under StrictMode, so a latch here would leave a live surface bound to a
919
+ * dead engine. A binding hands its framework a STABLE `subscribe`; a fresh closure per render
920
+ * parks and resumes on every render.
921
+ *
922
+ * After {@link ItineraryPaceEngine.dispose} the listener is not held and is never told, and
923
+ * the function returned does nothing.
924
+ */
925
+ subscribe(listener) {
926
+ if (this.disposed) {
927
+ return () => void 0;
928
+ }
929
+ this.listeners.add(listener);
930
+ if (this.parked) {
931
+ this.parked = false;
932
+ this.schedule();
933
+ }
934
+ return () => {
935
+ this.listeners.delete(listener);
936
+ if (this.listeners.size > 0 || this.parked) {
937
+ return;
938
+ }
939
+ this.parked = true;
940
+ this.cancelPending();
941
+ this.abandon(null);
942
+ };
943
+ }
944
+ /**
945
+ * configure replaces the configuration, and asks again only when the question changed.
946
+ *
947
+ * A binding calls it on every render, so it compares the question the configuration asks (the
948
+ * itinerary, its revision, the rate, the surface, and whether there is a client at all) and
949
+ * does nothing when that is unchanged and the client is the same object. A client replaced by
950
+ * another is a new question even when the rest is not: the credential it carries decides which
951
+ * copy a re-time without a surface answers for, so the answers the previous client gave are
952
+ * dropped, its request in flight is aborted, and the question is asked again through the new
953
+ * client. Another {@link ItineraryPaceConfig.revision} of the same itinerary is a new question
954
+ * too: the answers kept for that itinerary are dropped, its re-time in flight is aborted, and
955
+ * the snapshot is null until the answer lands.
956
+ *
957
+ * Parked or not, the snapshot is settled for the new configuration before this returns: the
958
+ * answer kept for it, the previous one across a rate step, or null. Only the request waits for a
959
+ * subscriber.
960
+ *
961
+ * After {@link ItineraryPaceEngine.dispose} it does nothing: the configuration is not taken and
962
+ * the snapshot stays the one the engine showed.
963
+ */
964
+ configure(config) {
965
+ if (this.disposed) {
966
+ return;
967
+ }
968
+ const before = this.request()?.key ?? null;
969
+ const replacesClient = config.client !== this.config.client;
970
+ this.config = config;
971
+ if (replacesClient) {
972
+ this.answers.clear();
973
+ this.abandon(null);
974
+ }
975
+ const request = this.request();
976
+ if (request !== null) {
977
+ this.forgetOtherRevisions(request);
978
+ }
979
+ if (replacesClient || (request?.key ?? null) !== before) {
980
+ this.schedule();
981
+ }
982
+ }
983
+ /**
984
+ * dispose drops the pending debounce and every listener and aborts the re-time in flight, for
985
+ * good.
986
+ *
987
+ * It changes nothing a reader holds: {@link ItineraryPaceEngine.getSnapshot} goes on returning
988
+ * the snapshot the engine showed when it was disposed, the answer included, and no listener is
989
+ * told. Idempotent, and every call after it is a no-op rather than an error: an owner torn
990
+ * down mid-step should not have to guard the calls it already queued.
991
+ */
992
+ dispose() {
993
+ if (this.disposed) {
994
+ return;
995
+ }
996
+ this.disposed = true;
997
+ this.parked = true;
998
+ this.cancelPending();
999
+ this.abandon(null);
1000
+ this.listeners.clear();
1001
+ }
1002
+ /** request resolves the current configuration into the re-time it asks for, or null. */
1003
+ request() {
1004
+ const { client, itineraryId, speedKmh, surface } = this.config;
1005
+ if (client === void 0 || !itineraryId || speedKmh === null) {
1006
+ return null;
1007
+ }
1008
+ const revision = revisionKey(this.config.revision);
1009
+ return {
1010
+ client,
1011
+ itineraryId,
1012
+ key: paceKey(itineraryId, speedKmh, surface, revision),
1013
+ revision,
1014
+ speedKmh,
1015
+ surface
1016
+ };
1017
+ }
1018
+ /** readKept answers the answer kept for `key`, which becomes the most recently read. */
1019
+ readKept(key) {
1020
+ const kept = this.answers.get(key);
1021
+ if (kept !== void 0) {
1022
+ this.answers.delete(key);
1023
+ this.answers.set(key, kept);
1024
+ }
1025
+ return kept;
1026
+ }
1027
+ /**
1028
+ * keep holds an answer as the most recently read, and drops the least recently read beyond
1029
+ * {@link PACE_ANSWER_CAPACITY}.
1030
+ */
1031
+ keep(key, kept) {
1032
+ this.answers.delete(key);
1033
+ this.answers.set(key, kept);
1034
+ for (const oldest of this.answers.keys()) {
1035
+ if (this.answers.size <= PACE_ANSWER_CAPACITY) {
1036
+ break;
1037
+ }
1038
+ this.answers.delete(oldest);
1039
+ }
1040
+ }
1041
+ /**
1042
+ * forgetOtherRevisions drops every answer kept for the itinerary `request` names under another
1043
+ * revision than the one it names, two revisions being one as {@link revisionKey} writes them.
1044
+ * Another itinerary's answers stay.
1045
+ */
1046
+ forgetOtherRevisions(request) {
1047
+ for (const [key, kept] of this.answers) {
1048
+ if (kept.itineraryId === request.itineraryId && kept.revision !== request.revision) {
1049
+ this.answers.delete(key);
1050
+ }
1051
+ }
1052
+ }
1053
+ /**
1054
+ * schedule answers the current configuration: at once when it can, after the debounce
1055
+ * otherwise. The re-time in flight for any other question is aborted first, and the previous
1056
+ * answer stays on screen only across a rate step (see {@link isRateStep}). A parked engine
1057
+ * answers as far as it can without asking, and its first subscriber asks the rest.
1058
+ */
1059
+ schedule() {
1060
+ this.cancelPending();
1061
+ if (this.disposed) {
1062
+ return;
1063
+ }
1064
+ const request = this.request();
1065
+ this.abandon(request?.key ?? null);
1066
+ if (request === null) {
1067
+ this.commit(null, null);
1068
+ return;
1069
+ }
1070
+ const kept = this.readKept(request.key);
1071
+ if (kept !== void 0) {
1072
+ this.commit(kept.answer, request);
1073
+ return;
1074
+ }
1075
+ if (!isRateStep(this.shown, request)) {
1076
+ this.commit(null, null);
1077
+ }
1078
+ if (this.parked) {
1079
+ return;
1080
+ }
1081
+ if (this.debounceMs === 0) {
1082
+ this.ask(request);
1083
+ return;
1084
+ }
1085
+ this.timer = setTimeout(() => {
1086
+ this.timer = null;
1087
+ const current = this.request();
1088
+ if (current !== null) {
1089
+ this.ask(current);
1090
+ }
1091
+ }, this.debounceMs);
1092
+ }
1093
+ /**
1094
+ * ask resolves one request, unless the same question is already on its way, in which case the
1095
+ * answer that lands serves it.
1096
+ */
1097
+ ask(request) {
1098
+ const kept = this.readKept(request.key);
1099
+ if (kept !== void 0) {
1100
+ this.commit(kept.answer, request);
1101
+ return;
1102
+ }
1103
+ if (this.inFlight?.key === request.key) {
1104
+ return;
1105
+ }
1106
+ const inFlight = { controller: new AbortController(), key: request.key };
1107
+ this.inFlight = inFlight;
1108
+ fetchItineraryPace(request.client, request.itineraryId, {
1109
+ signal: inFlight.controller.signal,
1110
+ speedKmh: request.speedKmh,
1111
+ surface: request.surface
1112
+ }).then(
1113
+ (answer) => {
1114
+ if (!this.settle(inFlight)) {
1115
+ return;
1116
+ }
1117
+ this.keep(request.key, {
1118
+ answer,
1119
+ itineraryId: request.itineraryId,
1120
+ revision: request.revision
1121
+ });
1122
+ if (this.isLive(request.key)) {
1123
+ this.commit(answer, request);
1124
+ }
1125
+ },
1126
+ () => {
1127
+ if (this.settle(inFlight) && this.isLive(request.key)) {
1128
+ this.commit(null, null);
1129
+ }
1130
+ }
1131
+ );
1132
+ }
1133
+ /**
1134
+ * settle retires a re-time that has landed, and reports whether its answer still counts: false
1135
+ * for one aborted before it landed, whatever its transport delivered.
1136
+ */
1137
+ settle(inFlight) {
1138
+ if (this.inFlight === inFlight) {
1139
+ this.inFlight = null;
1140
+ }
1141
+ return !inFlight.controller.signal.aborted;
1142
+ }
1143
+ /**
1144
+ * abandon aborts the re-time in flight unless it asks `keep`, the key the configuration asks
1145
+ * for now; null keeps none.
1146
+ */
1147
+ abandon(keep) {
1148
+ if (this.inFlight === null || this.inFlight.key === keep) {
1149
+ return;
1150
+ }
1151
+ this.inFlight.controller.abort();
1152
+ this.inFlight = null;
1153
+ }
1154
+ /** isLive reports whether an answer for `key` is still the one the snapshot should show. */
1155
+ isLive(key) {
1156
+ return !this.parked && !this.disposed && this.request()?.key === key;
1157
+ }
1158
+ cancelPending() {
1159
+ if (this.timer !== null) {
1160
+ clearTimeout(this.timer);
1161
+ this.timer = null;
1162
+ }
1163
+ }
1164
+ /** commit shows `snapshot`, the answer to `answers`, and tells every listener when it changed. */
1165
+ commit(snapshot, answers) {
1166
+ if (this.disposed) {
1167
+ return;
1168
+ }
1169
+ this.shown = snapshot === null ? null : answers;
1170
+ if (snapshot === this.snapshot) {
1171
+ return;
1172
+ }
1173
+ this.snapshot = snapshot;
1174
+ notifyListeners(this.listeners);
1175
+ }
1176
+ };
1177
+ var throttleFrom = (throttleMs) => {
1178
+ if (throttleMs === void 0) {
1179
+ return PROFILE_MARKER_THROTTLE_MS;
1180
+ }
1181
+ if (!Number.isFinite(throttleMs) || throttleMs < 0 || throttleMs > MAX_TIMER_MS) {
1182
+ throw new MountayaElementsError(
1183
+ `ProfileMarkerEngine: throttleMs is ${String(throttleMs)}; pass a number of milliseconds from 0 to ${MAX_TIMER_MS}, or omit it for ${PROFILE_MARKER_THROTTLE_MS}.`
1184
+ );
1185
+ }
1186
+ return throttleMs;
1187
+ };
1188
+ var ProfileMarkerEngine = class {
1189
+ throttleMs;
1190
+ listeners = /* @__PURE__ */ new Set();
1191
+ /** The sample the marker rests on, or null while it is cleared. */
1192
+ resting = null;
1193
+ /** The hover waiting for the open window to end, or null while none waits. */
1194
+ held = null;
1195
+ /** The window that is open, or null between two bursts. */
1196
+ timer = null;
1197
+ disposed = false;
1198
+ /**
1199
+ * The constructor reads its option and does nothing else: no timer starts until a hover is
1200
+ * made under a listener.
1201
+ *
1202
+ * @throws {MountayaElementsError} When `throttleMs` is not a finite number from 0 to
1203
+ * 2,147,483,647.
1204
+ */
1205
+ constructor(options = {}) {
1206
+ this.throttleMs = throttleFrom(options.throttleMs);
1207
+ }
1208
+ /** getSnapshot answers the sample the marker rests on, or null while it is cleared. */
1209
+ getSnapshot = () => this.resting;
1210
+ /**
1211
+ * subscribe holds a listener until the release it returns is called, and tells it each time
1212
+ * the marker moves or is cleared.
1213
+ *
1214
+ * The last listener to leave ends the open window and drops the held hover unwritten. After
1215
+ * {@link ProfileMarkerEngine.dispose} the listener is not held and is never told, and the
1216
+ * release does nothing.
1217
+ */
1218
+ subscribe = (listener) => {
1219
+ if (this.disposed) {
1220
+ return () => {
1221
+ };
1222
+ }
1223
+ this.listeners.add(listener);
1224
+ return () => {
1225
+ this.listeners.delete(listener);
1226
+ if (this.listeners.size === 0) {
1227
+ this.endWindow();
1228
+ }
1229
+ };
1230
+ };
1231
+ /**
1232
+ * hover takes one hover of the chart: the sample under the pointer, or null as the pointer
1233
+ * leaves.
1234
+ *
1235
+ * A sample moves the marker at once when no window is open, and waits for the open window to
1236
+ * end otherwise. Null clears the marker at once, whatever is held. After
1237
+ * {@link ProfileMarkerEngine.dispose} it does nothing.
1238
+ */
1239
+ hover(point) {
1240
+ if (this.disposed) {
1241
+ return;
1242
+ }
1243
+ if (point === null) {
1244
+ this.endWindow();
1245
+ this.rest(null);
1246
+ return;
1247
+ }
1248
+ if (this.timer !== null) {
1249
+ this.held = point;
1250
+ return;
1251
+ }
1252
+ this.rest(point);
1253
+ if (this.resting === point) {
1254
+ this.openWindow();
1255
+ }
1256
+ }
1257
+ /**
1258
+ * dispose ends the open window, drops the held hover and every listener, for good. The
1259
+ * snapshot keeps the sample the marker rested on, no listener is told, and every later call
1260
+ * does nothing. Calling it twice is safe.
1261
+ */
1262
+ dispose() {
1263
+ if (this.disposed) {
1264
+ return;
1265
+ }
1266
+ this.disposed = true;
1267
+ this.endWindow();
1268
+ this.listeners.clear();
1269
+ }
1270
+ /** rest moves the marker to `point` and tells the listeners, unless it rests there already. */
1271
+ rest(point) {
1272
+ if (this.resting === point) {
1273
+ return;
1274
+ }
1275
+ this.resting = point;
1276
+ notifyListeners(this.listeners);
1277
+ }
1278
+ /**
1279
+ * openWindow starts the window a write opens, unless one is open already. With nobody
1280
+ * listening, or with a throttle of zero, there is no rate to keep and no window.
1281
+ */
1282
+ openWindow() {
1283
+ if (this.timer !== null || this.throttleMs === 0 || this.listeners.size === 0) {
1284
+ return;
1285
+ }
1286
+ this.timer = setTimeout(() => {
1287
+ this.timer = null;
1288
+ const held = this.held;
1289
+ if (held === null) {
1290
+ return;
1291
+ }
1292
+ this.held = null;
1293
+ this.rest(held);
1294
+ if (this.resting === held) {
1295
+ this.openWindow();
1296
+ }
1297
+ }, this.throttleMs);
1298
+ }
1299
+ /** endWindow closes the open window, if any, and drops the hover it held. */
1300
+ endWindow() {
1301
+ if (this.timer !== null) {
1302
+ clearTimeout(this.timer);
1303
+ }
1304
+ this.timer = null;
1305
+ this.held = null;
1306
+ }
1307
+ };
1308
+
1309
+ // src/segments/rules/hazardPrompt.ts
1310
+ var promptKey = (hazards) => [...hazards].sort().join("|");
1311
+ var createHazardPromptGate = (ask) => {
1312
+ const pending = /* @__PURE__ */ new Map();
1313
+ return (hazards) => {
1314
+ const key = promptKey(hazards);
1315
+ const asking = pending.get(key);
1316
+ if (asking) {
1317
+ return asking;
1318
+ }
1319
+ const answer = ask(hazards).finally(() => {
1320
+ pending.delete(key);
1321
+ });
1322
+ pending.set(key, answer);
1323
+ return answer;
1324
+ };
1325
+ };
1326
+
1327
+ // src/segments/rules/liveSegmentProjection.ts
1328
+ var buildLiveSegmentForDraft = (base, segmentId, itineraryId, mode, route, draftName, draftColor) => buildLiveSegment(
1329
+ base ?? synthesizeDraftSegment({
1330
+ draftColor,
1331
+ draftName,
1332
+ itineraryId,
1333
+ mode,
1334
+ segmentId
1335
+ }),
1336
+ route
1337
+ );
1338
+
1339
+ // src/segments/engines/segmentDraft.ts
1340
+ var idleSnapshot = {
1341
+ armed: false,
1342
+ mode: null,
1343
+ segmentId: null,
1344
+ viaCount: 0
1345
+ };
1346
+ var sameArming = (a, b) => a.client === b.client && a.context === b.context && a.segmentId === b.segmentId && a.mode === b.mode && a.activitySlug === b.activitySlug && a.draftColor === b.draftColor && a.pinnedEnd === b.pinnedEnd && a.pinnedStart === b.pinnedStart && a.seedVias === b.seedVias;
1347
+ var sameListenKey = (a, b) => a.client === b.client && a.context === b.context && a.itineraryId === b.itineraryId && a.mode === b.mode && a.segmentId === b.segmentId;
1348
+ var throttleFrom2 = (throttleMs) => {
1349
+ if (throttleMs === void 0) {
1350
+ return LIVE_SEGMENT_THROTTLE_MS;
1351
+ }
1352
+ if (!Number.isFinite(throttleMs) || throttleMs < 0 || throttleMs > MAX_TIMER_MS) {
1353
+ throw new MountayaElementsError(
1354
+ `SegmentDraftEngine: throttleMs is ${String(throttleMs)}; pass a number of milliseconds from 0 to ${MAX_TIMER_MS}, or omit it for ${LIVE_SEGMENT_THROTTLE_MS}.`
1355
+ );
1356
+ }
1357
+ return throttleMs;
1358
+ };
1359
+ var SegmentDraftEngine = class {
1360
+ config;
1361
+ throttleMs;
1362
+ snapshot = idleSnapshot;
1363
+ subscriptions = /* @__PURE__ */ new Set();
1364
+ /** The store the session is watched in, and the subscription watching it, while running. */
1365
+ watching = null;
1366
+ /** What the open edit was armed with, or null while nothing is armed. */
1367
+ arming = null;
1368
+ /**
1369
+ * What the map client refused to arm, or null. Held until the session it was for closes or one
1370
+ * of its inputs changes, so a session on its way out is not handed to the map again. A park
1371
+ * keeps it: the session it names is still on its way out when the next subscriber arrives.
1372
+ */
1373
+ refused = null;
1374
+ /** The subscription to the armed map's drafts, or null while nothing is armed. */
1375
+ listening = null;
1376
+ /** The handles the armed edit's latest draft holds. */
1377
+ viaCount = 0;
1378
+ /** Whether a reconcile is running, so one a store write starts inside it runs after it. */
1379
+ reconciling = false;
1380
+ /** Whether the store changed during the running reconcile, which then runs again. */
1381
+ stale = false;
1382
+ /** Whether nobody is watching. A parked engine arms nothing and reads no draft. */
1383
+ parked = true;
1384
+ disposed = false;
1385
+ /**
1386
+ * One dialog per hazard question, however many routing round trips ask it. Held for the
1387
+ * engine's life rather than per arming: a gate built beside the routing function would forget
1388
+ * the dialog already on screen, which is the state it exists to track.
1389
+ */
1390
+ hazardGate = createHazardPromptGate(
1391
+ (hazards) => this.askAboutHazards(hazards)
1392
+ );
1393
+ /**
1394
+ * The session's record of accepted hazards, read and written through the store the engine is
1395
+ * configured with when the routing function asks. The store outlives every routing function
1396
+ * the editor is armed with, which is the point: an answer outlives a re-arm.
1397
+ */
1398
+ hazardMemo = {
1399
+ accept: (keys) => {
1400
+ this.config.context.ui.getState().acknowledgeRouteHazards(keys);
1401
+ },
1402
+ accepted: () => this.config.context.ui.getState().segmentEditSession?.acknowledgedRouteHazards ?? []
1403
+ };
1404
+ /**
1405
+ * Constructing one holds the options and does nothing else: nothing is armed, no store is read
1406
+ * and nothing is written. A React binding constructs during a render React is free to throw
1407
+ * away, and a constructor with a side effect would leave the discarded copy acting.
1408
+ *
1409
+ * @throws {MountayaElementsError} When `throttleMs` is not a finite number from 0 to
1410
+ * 2,147,483,647.
1411
+ */
1412
+ constructor(options) {
1413
+ const { throttleMs, ...config } = options;
1414
+ this.throttleMs = throttleFrom2(throttleMs);
1415
+ this.config = config;
1416
+ }
1417
+ /** getSnapshot returns the current answer, by reference and stable between changes. */
1418
+ getSnapshot() {
1419
+ return this.snapshot;
1420
+ }
1421
+ /**
1422
+ * subscribe registers a listener for every change of the snapshot, and returns its own
1423
+ * unsubscribe, which is idempotent.
1424
+ *
1425
+ * The first listener starts the engine and the last one leaving parks it, which is the whole
1426
+ * lifecycle a component can express correctly: React tears an effect down and sets it up again
1427
+ * with the same object under StrictMode, so a latch here would leave a live surface bound to a
1428
+ * dead engine. Each call is its own subscription, so two owners subscribing one shared function
1429
+ * each hold the engine until they release it.
1430
+ */
1431
+ subscribe(listener) {
1432
+ if (this.disposed) {
1433
+ return () => {
1434
+ };
1435
+ }
1436
+ const subscription = { listener };
1437
+ this.subscriptions.add(subscription);
1438
+ if (this.parked) {
1439
+ this.parked = false;
1440
+ this.reconcile();
1441
+ }
1442
+ return () => {
1443
+ if (!this.subscriptions.delete(subscription) || this.subscriptions.size > 0) {
1444
+ return;
1445
+ }
1446
+ if (!this.parked) {
1447
+ this.park();
1448
+ }
1449
+ };
1450
+ }
1451
+ /**
1452
+ * configure replaces the configuration, and arms again only when an arming input changed.
1453
+ *
1454
+ * A binding calls it on every render, so a configuration carrying the same client and the same
1455
+ * context does nothing beyond the assignment: the bus, the collaboration session and the words
1456
+ * are read when they are used. A parked engine keeps the configuration for its next subscriber.
1457
+ */
1458
+ configure(config) {
1459
+ if (this.disposed) {
1460
+ return;
1461
+ }
1462
+ this.config = config;
1463
+ if (!this.parked) {
1464
+ this.reconcile();
1465
+ }
1466
+ }
1467
+ /**
1468
+ * dispose parks the engine and drops every listener, for good.
1469
+ *
1470
+ * Idempotent, and every call after it is a no-op rather than an error: an owner torn down
1471
+ * mid-edit should not have to guard the calls it already queued. A disposed engine writes no
1472
+ * store either: the cancel it dispatched for a refused begin runs on the bus, and a session that
1473
+ * cancel leaves open is not closed by the engine.
1474
+ *
1475
+ * The snapshot of a disposed engine reads `armed: false`. The engine holds a session and no
1476
+ * answer to a question, so there is nothing a reader could keep showing: the session is over
1477
+ * for this engine, and the snapshot says so.
1478
+ */
1479
+ dispose() {
1480
+ if (this.disposed) {
1481
+ return;
1482
+ }
1483
+ this.disposed = true;
1484
+ if (!this.parked) {
1485
+ this.park();
1486
+ }
1487
+ this.subscriptions.clear();
1488
+ }
1489
+ /**
1490
+ * reconcile brings the arming and the draft subscription in line with the store and the
1491
+ * configuration, then publishes the snapshot. A store write it makes, or one a listener makes
1492
+ * while it runs, runs it again once it finishes rather than inside it.
1493
+ */
1494
+ reconcile() {
1495
+ if (this.parked) {
1496
+ return;
1497
+ }
1498
+ if (this.reconciling) {
1499
+ this.stale = true;
1500
+ return;
1501
+ }
1502
+ this.reconciling = true;
1503
+ try {
1504
+ do {
1505
+ this.stale = false;
1506
+ this.step();
1507
+ } while (this.stale && !this.parked);
1508
+ } finally {
1509
+ this.reconciling = false;
1510
+ }
1511
+ this.publish();
1512
+ }
1513
+ /** step is one pass of {@link SegmentDraftEngine.reconcile}. */
1514
+ step() {
1515
+ const { client, context } = this.config;
1516
+ this.watch(context.ui);
1517
+ const state = context.ui.getState();
1518
+ const session = state.segmentEditSession;
1519
+ if (client === null || session === null || session.segmentId === "") {
1520
+ this.unlisten();
1521
+ this.arming = null;
1522
+ this.refused = null;
1523
+ return;
1524
+ }
1525
+ const key = {
1526
+ client,
1527
+ context,
1528
+ itineraryId: state.activeItinerary?.id ?? null,
1529
+ mode: session.mode,
1530
+ segmentId: session.segmentId
1531
+ };
1532
+ if (this.listening !== null && !sameListenKey(this.listening, key)) {
1533
+ this.unlisten();
1534
+ }
1535
+ const arming = {
1536
+ activitySlug: session.activitySlug,
1537
+ client,
1538
+ context,
1539
+ draftColor: session.draftColor,
1540
+ mode: session.mode,
1541
+ pinnedEnd: session.pinnedEnd,
1542
+ pinnedStart: session.pinnedStart,
1543
+ seedVias: session.seedVias,
1544
+ segmentId: session.segmentId
1545
+ };
1546
+ if (this.refused !== null && sameArming(this.refused, arming)) {
1547
+ return;
1548
+ }
1549
+ if (this.arming === null || !sameArming(this.arming, arming)) {
1550
+ try {
1551
+ client.beginSegmentEdit(
1552
+ buildSegmentEditOptions(session, {
1553
+ client: context.api?.client,
1554
+ confirmHazards: this.hazardGate,
1555
+ hazardMemo: this.hazardMemo,
1556
+ onViaCapRefused: () => this.refuseViaCap()
1557
+ })
1558
+ );
1559
+ } catch (refusal) {
1560
+ this.unlisten();
1561
+ this.arming = null;
1562
+ this.refused = arming;
1563
+ this.endRefused(context, segmentEditSessionMark(session), refusal);
1564
+ return;
1565
+ }
1566
+ this.arming = arming;
1567
+ this.refused = null;
1568
+ }
1569
+ if (this.listening === null) {
1570
+ this.listen(key);
1571
+ }
1572
+ }
1573
+ /**
1574
+ * endRefused ends the session whose begin the map client refused, and hands the refusal to the
1575
+ * program.
1576
+ *
1577
+ * The session is ended by `studio.itinerary.segment.editCancel` through `bus`, the tool path
1578
+ * that owns every disposal: it gives back the lock the begin took and ends whatever edit the map
1579
+ * still holds. Where that tool does not answer `ok` (it is refused, it rejects, or the bus
1580
+ * states no result at all), the store's session is closed directly, so no session stays open
1581
+ * over a map that is editing nothing. A parked engine still closes it, since its surface may
1582
+ * mount again. A disposed one writes nothing, as {@link SegmentDraftEngine.dispose} promises:
1583
+ * the session is left to the engine that takes its place, which meets the same refusal.
1584
+ *
1585
+ * The refused session is the one closed directly, and no other: it is told by `mark`, its
1586
+ * {@link segmentEditSessionMark}, so a session begun since on the same segment stays open.
1587
+ *
1588
+ * The refusal names the option the map lacked. It is a defect of the program that armed the
1589
+ * session and not of the store write that woke the engine, so it leaves through
1590
+ * {@link surfaceFault}.
1591
+ *
1592
+ * The reader is told as well, since an uncaught error says nothing on screen and the session
1593
+ * closes under them: an `error` alert in the bundle's `editing.segmentEditBeginFailed`, read
1594
+ * when the refusal is told so a locale change is heard. It is raised after the cancel is asked
1595
+ * for, so a bus that answers one verb at a time ends the session first.
1596
+ */
1597
+ endRefused(context, mark, refusal) {
1598
+ surfaceFault(refusal);
1599
+ const close = () => {
1600
+ if (this.disposed) {
1601
+ return;
1602
+ }
1603
+ const state = context.ui.getState();
1604
+ const open = state.segmentEditSession;
1605
+ if (open !== null && segmentEditSessionMark(open) === mark) {
1606
+ state.cancelSegmentEdit();
1607
+ }
1608
+ };
1609
+ void Promise.resolve(
1610
+ this.config.bus.dispatch(context, "studio.itinerary.segment.editCancel", {})
1611
+ ).then((result) => {
1612
+ if (result?.ok !== true) {
1613
+ close();
1614
+ }
1615
+ }, close);
1616
+ this.raiseAlert(context, {
1617
+ level: "error",
1618
+ message: this.config.strings.editing.segmentEditBeginFailed
1619
+ });
1620
+ }
1621
+ /**
1622
+ * raiseAlert raises one alert through the bus, and holds a bus that rejects it.
1623
+ *
1624
+ * Nothing follows an alert: the map has already declined what the alert reports, and a refused
1625
+ * begin has reached the program through {@link surfaceFault} and is closed by its cancel. So a
1626
+ * rejection is dropped, where one left unhandled would end a Node process with an error that is
1627
+ * none of the package's.
1628
+ */
1629
+ raiseAlert(context, alert) {
1630
+ void Promise.resolve(this.config.bus.dispatch(context, "studio.alert.show", alert)).then(
1631
+ void 0,
1632
+ () => {
1633
+ }
1634
+ );
1635
+ }
1636
+ /** watch follows the store the session lives in, leaving the previous one if it changed. */
1637
+ watch(ui) {
1638
+ if (this.watching?.ui === ui) {
1639
+ return;
1640
+ }
1641
+ this.unwatch();
1642
+ this.watching = { release: ui.subscribe(() => this.reconcile()), ui };
1643
+ }
1644
+ unwatch() {
1645
+ this.watching?.release();
1646
+ this.watching = null;
1647
+ }
1648
+ /** listen starts reading the armed map's drafts for the edit `key` names. */
1649
+ listen(key) {
1650
+ const listening = {
1651
+ ...key,
1652
+ projected: null,
1653
+ release: () => {
1654
+ },
1655
+ // A zero-delay window still coalesces the routes a single turn of the event loop delivers,
1656
+ // so a zero window takes no throttle at all.
1657
+ throttle: this.throttleMs === 0 ? null : new TrailingThrottle(
1658
+ this.throttleMs,
1659
+ (routed) => this.project(listening, routed),
1660
+ // The first route of a burst is the one the reader is waiting on: a drag whose
1661
+ // profile appears one window late reads as lag.
1662
+ { leading: true }
1663
+ )
1664
+ };
1665
+ this.listening = listening;
1666
+ listening.release = key.client.onSegmentDraftChange((draft) => this.receive(listening, draft));
1667
+ }
1668
+ /**
1669
+ * unlisten stops reading the map's drafts, drops the pending route, and clears the live segment,
1670
+ * so a surface opened again over the session reads a clean slot until the next route lands.
1671
+ */
1672
+ unlisten() {
1673
+ const listening = this.listening;
1674
+ if (listening === null) {
1675
+ return;
1676
+ }
1677
+ this.listening = null;
1678
+ this.viaCount = 0;
1679
+ listening.release();
1680
+ listening.throttle?.cancel();
1681
+ listening.context.ui.getState().setSegmentEditLiveSegment(null);
1682
+ }
1683
+ /** receive handles one draft the armed map reported, as the class docblock sets out. */
1684
+ receive(listening, draft) {
1685
+ if (this.listening !== listening) {
1686
+ return;
1687
+ }
1688
+ if (draft.vias.length !== this.viaCount) {
1689
+ this.viaCount = draft.vias.length;
1690
+ this.publish();
1691
+ if (this.listening !== listening) {
1692
+ return;
1693
+ }
1694
+ }
1695
+ const ui = listening.context.ui;
1696
+ const disposition = draftChangeDisposition({
1697
+ agentDriving: ui.getState().agentDriving,
1698
+ programmatic: draft.programmatic
1699
+ });
1700
+ if (disposition === "drop") {
1701
+ return;
1702
+ }
1703
+ if (disposition === "record") {
1704
+ const geometry = buildSegmentGeometry(listening.mode, draft.vias);
1705
+ if (draft.phase === "live") {
1706
+ ui.getState().setSegmentEditLiveDraft(geometry);
1707
+ } else {
1708
+ ui.getState().pushSegmentDraft(geometry);
1709
+ }
1710
+ if (this.listening !== listening) {
1711
+ return;
1712
+ }
1713
+ }
1714
+ if (draft.route) {
1715
+ const projected = listening.projected;
1716
+ if (projected?.route === draft.route && ui.getState().segmentEditSession?.liveSegment === projected.liveSegment) {
1717
+ return;
1718
+ }
1719
+ const routed = {
1720
+ route: draft.route,
1721
+ routedFor: draft.programmatic ? draft.vias : void 0
1722
+ };
1723
+ if (listening.throttle === null) {
1724
+ this.project(listening, routed);
1725
+ } else {
1726
+ listening.throttle.push(routed);
1727
+ }
1728
+ return;
1729
+ }
1730
+ if (draft.phase === "live") {
1731
+ return;
1732
+ }
1733
+ listening.throttle?.cancel();
1734
+ if (disposition === "record") {
1735
+ this.fallBack(listening);
1736
+ }
1737
+ }
1738
+ /**
1739
+ * project writes one route onto the live segment the profile reads, and hands the same segment
1740
+ * to the collaboration session.
1741
+ */
1742
+ project(listening, { route, routedFor }) {
1743
+ if (this.listening !== listening) {
1744
+ return;
1745
+ }
1746
+ const state = listening.context.ui.getState();
1747
+ const itinerary = state.activeItinerary;
1748
+ const session = state.segmentEditSession;
1749
+ const liveSegment = buildLiveSegmentForDraft(
1750
+ itinerary?.segments.find((segment) => segment.id === listening.segmentId),
1751
+ listening.segmentId,
1752
+ itinerary?.id ?? "",
1753
+ session?.mode ?? "directions",
1754
+ route,
1755
+ session?.draftName ?? null,
1756
+ session?.draftColor ?? null
1757
+ );
1758
+ listening.projected = { liveSegment, route };
1759
+ state.setSegmentEditLiveSegment(liveSegment, routedFor);
1760
+ this.config.collab?.sendDraft({ id: listening.segmentId, kind: "segment" }, liveSegment);
1761
+ }
1762
+ /**
1763
+ * fallBack writes what the live segment is once a settled draft resolves no route: nothing for
1764
+ * a persisted segment, which the profile then shows as saved, and the draft's synthetic
1765
+ * segment for one drawn from scratch, which has no saved version to show and would otherwise
1766
+ * lose its row until a route lands.
1767
+ */
1768
+ fallBack(listening) {
1769
+ const state = listening.context.ui.getState();
1770
+ const session = state.segmentEditSession;
1771
+ const persisted = state.activeItinerary?.segments?.find(
1772
+ (segment) => segment.id === listening.segmentId
1773
+ );
1774
+ if (!persisted && session) {
1775
+ state.setSegmentEditLiveSegment(
1776
+ synthesizeDraftSegment({
1777
+ draftColor: session.draftColor,
1778
+ draftName: session.draftName,
1779
+ itineraryId: state.activeItinerary?.id ?? "",
1780
+ mode: session.mode,
1781
+ segmentId: session.segmentId
1782
+ })
1783
+ );
1784
+ return;
1785
+ }
1786
+ state.setSegmentEditLiveSegment(null);
1787
+ }
1788
+ /** refuseViaCap warns that a click was declined at the router's via ceiling. */
1789
+ refuseViaCap() {
1790
+ const { context, strings } = this.config;
1791
+ this.raiseAlert(context, {
1792
+ level: "warning",
1793
+ message: strings.editing.segmentViaCapRefused(DIRECTIONS_VIA_MAX)
1794
+ });
1795
+ }
1796
+ /**
1797
+ * askAboutHazards puts a routed line's new hazards to the context's confirm gate, in the words
1798
+ * the engine was last handed, and adopts the line when the context has no gate.
1799
+ */
1800
+ askAboutHazards(hazards) {
1801
+ const { context, strings } = this.config;
1802
+ if (!context.confirm) {
1803
+ return Promise.resolve(true);
1804
+ }
1805
+ return context.confirm(
1806
+ routeHazardConfirmation(hazards, {
1807
+ closing: strings.editing.routeHazardClosing,
1808
+ hazards: strings.editing.routeHazards,
1809
+ severalTitle: strings.editing.routeHazardsTitle
1810
+ })
1811
+ );
1812
+ }
1813
+ /**
1814
+ * park stops watching and reading, and drops what the running engine armed.
1815
+ *
1816
+ * A refused arming is kept. Its session stays open until the cancel the engine asked for lands,
1817
+ * and a surface mounted again meanwhile would otherwise hand it to the map a second time and ask
1818
+ * for a second cancel, which closes whichever session is open when it runs. A session begun
1819
+ * since holds a seed array of its own, so it never reads as the refused one.
1820
+ */
1821
+ park() {
1822
+ this.parked = true;
1823
+ this.unwatch();
1824
+ this.unlisten();
1825
+ this.arming = null;
1826
+ this.publish();
1827
+ }
1828
+ /** publish settles the snapshot and tells every listener when it changed. */
1829
+ publish() {
1830
+ const listening = this.listening;
1831
+ const next = listening === null ? idleSnapshot : {
1832
+ armed: true,
1833
+ mode: listening.mode,
1834
+ segmentId: listening.segmentId,
1835
+ viaCount: this.viaCount
1836
+ };
1837
+ const current = this.snapshot;
1838
+ if (current.armed === next.armed && current.mode === next.mode && current.segmentId === next.segmentId && current.viaCount === next.viaCount) {
1839
+ return;
1840
+ }
1841
+ this.snapshot = next;
1842
+ if (this.disposed) {
1843
+ return;
1844
+ }
1845
+ notifyListeners(Array.from(this.subscriptions, ({ listener }) => listener));
1846
+ }
1847
+ };
1848
+ z.object({
1849
+ failedCollectionIds: z.array(z.string()).optional()
1850
+ });
1851
+ var mintedShareTokenSchema = z.object({ shareToken: issuedShareTokenSchema.shape.shareToken });
1852
+ var mintedShareToken = (result) => {
1853
+ if (!result.ok) {
1854
+ return null;
1855
+ }
1856
+ const parsed = mintedShareTokenSchema.safeParse(result.data);
1857
+ return parsed.success ? parsed.data.shareToken : null;
1858
+ };
1859
+
1860
+ // src/share/engines/shareLink.ts
1861
+ var skipped = { status: "skipped" };
1862
+ var withheld = { status: "withheld" };
1863
+ var unworded = { failure: null, retryable: true };
1864
+ var sameTarget = (a, b) => a.kind === b.kind && a.id === b.id;
1865
+ var sameActions = (a, b) => a.disable === b.disable && a.rotate === b.rotate;
1866
+ var heldBack = (actions) => ({
1867
+ disable: actions.disable === "ready" ? "waiting" : actions.disable,
1868
+ rotate: actions.rotate === "ready" ? "waiting" : actions.rotate
1869
+ });
1870
+ var answered = async (run, settle) => {
1871
+ let result;
1872
+ try {
1873
+ result = await run();
1874
+ } catch (error) {
1875
+ result = failureFromThrown(error);
1876
+ }
1877
+ return settle(result);
1878
+ };
1879
+ var readToken = (result) => {
1880
+ if (!result.ok) {
1881
+ return { failure: result, retryable: isRetryableShareLinkFailure(result) };
1882
+ }
1883
+ if (result.token === null) {
1884
+ return { token: null };
1885
+ }
1886
+ const issued = issuedShareTokenSchema.safeParse({ shareToken: result.token });
1887
+ return issued.success ? { token: issued.data.shareToken } : unworded;
1888
+ };
1889
+ var ShareLinkEngine = class {
1890
+ config;
1891
+ /** The target the state below answers for, replaced only by one that differs by kind or id. */
1892
+ target;
1893
+ token;
1894
+ known;
1895
+ readFailure = null;
1896
+ mintFailure = null;
1897
+ change = null;
1898
+ reading = false;
1899
+ minting = false;
1900
+ /**
1901
+ * Whether the link has been read under this target, so that no later subscriber reads again:
1902
+ * its token, that none is set, its failure or its read in flight is what the engine holds. A
1903
+ * settled disable raises it, since its reader asked for no link.
1904
+ */
1905
+ asked = false;
1906
+ /**
1907
+ * The action called under this target and not yet answered, a confirmation being asked
1908
+ * included, or null. One slot, because a link takes one management action at a time.
1909
+ */
1910
+ acting = null;
1911
+ /** Whether the confirmation of {@link acting} was approved, so its request is running. */
1912
+ running = false;
1913
+ /** Counts the targets answered for: an answer sent under an earlier one is ignored. */
1914
+ epoch = 0;
1915
+ /**
1916
+ * Counts the requests that left, a read and a create when they are sent and a reset or a
1917
+ * disable at its approval, so each one holds its place in the order they were sent.
1918
+ */
1919
+ sent = 0;
1920
+ /**
1921
+ * The highest place a settled write outranks, or zero while none has settled: a read or a
1922
+ * create sent at or before it has its answer dropped. A reset outranks every request sent by the
1923
+ * time it settles, and a disable the ones sent before it.
1924
+ */
1925
+ outranked = 0;
1926
+ /**
1927
+ * The place of the read or the create whose answer the engine holds, or zero while it holds
1928
+ * none of theirs.
1929
+ */
1930
+ answeredAt = 0;
1931
+ /** The place of the latest read whose answer landed while nobody watched, or zero. */
1932
+ unheard = 0;
1933
+ /** The place of the read whose failure the engine holds, or zero while it holds none. */
1934
+ readFailedAt = 0;
1935
+ /** The place of the create whose failure the engine holds, or zero while it holds none. */
1936
+ mintFailedAt = 0;
1937
+ /** The place of the read sent last, or zero before any, which `reading` follows. */
1938
+ latestRead = 0;
1939
+ /** The place of the create sent last, or zero before any, which `minting` follows. */
1940
+ latestMint = 0;
1941
+ snapshot;
1942
+ subscriptions = /* @__PURE__ */ new Set();
1943
+ /** Whether nobody is watching. A parked engine asks for nothing and runs no command. */
1944
+ parked = true;
1945
+ disposed = false;
1946
+ /**
1947
+ * Constructing one holds the options and does nothing else: nothing is read and no tool is run.
1948
+ * A React binding constructs during a render React is free to throw away, and a constructor
1949
+ * with a side effect would leave the discarded copy reading.
1950
+ */
1951
+ constructor(options) {
1952
+ const { token, ...config } = options;
1953
+ this.config = config;
1954
+ this.target = config.target;
1955
+ this.token = token ?? null;
1956
+ this.known = this.token !== null;
1957
+ this.snapshot = this.compose();
1958
+ }
1959
+ /** getSnapshot returns the current answer, by reference and stable between changes. */
1960
+ getSnapshot() {
1961
+ return this.snapshot;
1962
+ }
1963
+ /**
1964
+ * subscribe registers a listener for every change of the snapshot, and returns its own
1965
+ * unsubscribe, which is idempotent.
1966
+ *
1967
+ * The first listener resumes the engine, which reads the link unless it already has, and the
1968
+ * last one leaving parks it. That is the whole lifecycle a component can express correctly:
1969
+ * React tears an effect down and sets it up again with the same object under StrictMode, so a
1970
+ * latch here would leave a live surface bound to a dead engine. Each call is its own
1971
+ * subscription, so two owners subscribing one shared function each hold the engine until they
1972
+ * release it.
1973
+ */
1974
+ subscribe(listener) {
1975
+ if (this.disposed) {
1976
+ return () => void 0;
1977
+ }
1978
+ const subscription = { listener };
1979
+ this.subscriptions.add(subscription);
1980
+ if (this.parked) {
1981
+ this.parked = false;
1982
+ this.ask();
1983
+ }
1984
+ return () => {
1985
+ if (!this.subscriptions.delete(subscription) || this.subscriptions.size > 0) {
1986
+ return;
1987
+ }
1988
+ this.parked = true;
1989
+ };
1990
+ }
1991
+ /**
1992
+ * configure replaces the configuration, and tells its listeners only when the answer changed.
1993
+ *
1994
+ * A binding calls it on every render, so an unchanged configuration costs a comparison. A
1995
+ * changed capability or scope moves the snapshot's `actions`, and a scope that turns
1996
+ * `"organization"` sends the read a `"pending"` one held. A target that differs by kind or id
1997
+ * is another question: the token, what the engine knew, the failures and the latest change are
1998
+ * dropped, the answer of anything in flight for the previous target is ignored, an action still
1999
+ * running for it holds back none of the new target's, and the link is read again. A parked
2000
+ * engine keeps the configuration for its next subscriber.
2001
+ */
2002
+ configure(config) {
2003
+ if (this.disposed) {
2004
+ return;
2005
+ }
2006
+ this.config = config;
2007
+ if (!sameTarget(this.target, config.target)) {
2008
+ this.target = config.target;
2009
+ this.epoch += 1;
2010
+ this.token = null;
2011
+ this.known = false;
2012
+ this.readFailure = null;
2013
+ this.readFailedAt = 0;
2014
+ this.mintFailure = null;
2015
+ this.mintFailedAt = 0;
2016
+ this.change = null;
2017
+ this.acting = null;
2018
+ this.running = false;
2019
+ this.reading = false;
2020
+ this.minting = false;
2021
+ this.asked = false;
2022
+ }
2023
+ this.publish();
2024
+ if (!this.parked) {
2025
+ this.ask();
2026
+ }
2027
+ }
2028
+ /**
2029
+ * dispose parks the engine and drops every listener, for good.
2030
+ *
2031
+ * Idempotent, and every call after it is a no-op rather than an error: an owner torn down
2032
+ * mid-request should not have to guard the calls it already queued. A request in flight still
2033
+ * reaches the tool it was sent to; its answer changes nothing here.
2034
+ */
2035
+ dispose() {
2036
+ if (this.disposed) {
2037
+ return;
2038
+ }
2039
+ this.disposed = true;
2040
+ this.parked = true;
2041
+ this.subscriptions.clear();
2042
+ }
2043
+ /**
2044
+ * read reads the link again, and resolves once that read has answered.
2045
+ *
2046
+ * The first subscriber reads by itself. This is the retry a surface offers under a
2047
+ * `readFailure` whose `retryable` is true. The previous failure leaves the snapshot while the
2048
+ * read is in flight, so a surface shows its pending state.
2049
+ *
2050
+ * It does nothing, and resolves at once, while a read is in flight, while the scope is not
2051
+ * `"organization"`, while the viewer does not hold `canManage`, while parked, and after
2052
+ * {@link ShareLinkEngine.dispose}. It never rejects.
2053
+ */
2054
+ async read() {
2055
+ if (this.parked || this.disposed || this.reading || !this.mayAsk()) {
2056
+ return;
2057
+ }
2058
+ await this.runAsk("read");
2059
+ }
2060
+ /**
2061
+ * mint creates the link through `studio.shareLink.mint`, and resolves once that create has
2062
+ * answered: the reader's Create, which a surface offers once the snapshot is `known` with no
2063
+ * token. The verb gets or creates, so a link made elsewhere in the meantime is the one it
2064
+ * answers, and no URL already handed out is retired. A refusal is the snapshot's `mintFailure`,
2065
+ * and asking again is its retry.
2066
+ *
2067
+ * It does nothing, and resolves at once, while a create is in flight, while a link is held,
2068
+ * while a reset or a disable of this link is in flight, while the scope is not
2069
+ * `"organization"`, while the viewer does not hold `canManage`, while parked, and after
2070
+ * {@link ShareLinkEngine.dispose}. It never rejects.
2071
+ */
2072
+ async mint() {
2073
+ if (this.parked || this.disposed || this.minting || this.token !== null || this.acting !== null || !this.mayAsk()) {
2074
+ return;
2075
+ }
2076
+ await this.runAsk("mint");
2077
+ }
2078
+ /**
2079
+ * rotate resets the link through `studio.shareLink.rotate`: the token held is retired, every
2080
+ * URL carrying it stops working, and the snapshot takes the one issued in its place.
2081
+ *
2082
+ * The tool bus asks the confirmation inside the dispatch, so the tool runs in a context whose
2083
+ * confirm gate the engine layers over the configured one: the snapshot's `busy` turns
2084
+ * `"rotate"` when the gate approves, never while it is asked. A context with no confirm gate
2085
+ * refuses, as the bus does for one.
2086
+ *
2087
+ * It runs only while the snapshot's `actions.rotate` is `"ready"`, which it is not while a
2088
+ * reset or a disable of this target is in flight (one whose confirmation is still asked
2089
+ * included), and while somebody is watching; otherwise it resolves `"skipped"`. One at a time,
2090
+ * because two writes side by side would leave the token to whichever answer landed last. A
2091
+ * refusal leaves the link, the latest change and a read's or a create's failure as they were.
2092
+ * An answer that lands once the engine answers for another target, or after
2093
+ * {@link ShareLinkEngine.dispose}, changes nothing either, and the outcome still says what the
2094
+ * verb came to.
2095
+ *
2096
+ * It never rejects. A `dispatch` that throws or rejects resolves `"refused"` with the failure
2097
+ * the tool bus builds for a handler that throws, and leaves the reset free to be asked again.
2098
+ * So does an `ok` answer that holds no token, with the `internal` refusal the verb gives for a
2099
+ * link that holds none: its sentence says the link held may no longer open. The engine then
2100
+ * reads the link that stands, and drops the answer of a read or a create sent before the reset,
2101
+ * which may carry the link it retired. That read is sent as the first one is, to a watched
2102
+ * engine under the `"organization"` scope: a parked engine sends it for its next subscriber,
2103
+ * and another scope once it turns `"organization"`.
2104
+ */
2105
+ rotate() {
2106
+ return this.act("rotate");
2107
+ }
2108
+ /**
2109
+ * disable revokes the link through `studio.shareLink.disable`: every URL carrying its token
2110
+ * stops working, and the snapshot holds no token and knows that none is set. No later
2111
+ * subscriber reads it again; {@link ShareLinkEngine.mint} creates another.
2112
+ *
2113
+ * On a `"personal"` resource a `not-found` answer settles it too, with `linkWasActive` false:
2114
+ * no link was active, which is what the reader asked for (`isShareLinkDisableSettled`).
2115
+ *
2116
+ * The confirmation, the `busy` flag (`"disable"`) and the conditions it runs under are
2117
+ * {@link ShareLinkEngine.rotate}'s, read off `actions.disable`.
2118
+ */
2119
+ disable() {
2120
+ return this.act("disable");
2121
+ }
2122
+ /** ask sends the first read of a target, once a scope that can hold a link is known. */
2123
+ ask() {
2124
+ if (this.asked || !this.mayAsk()) {
2125
+ return;
2126
+ }
2127
+ void this.runAsk("read");
2128
+ }
2129
+ /**
2130
+ * mayAsk reports whether the link may be read or created as configured: the resource is an
2131
+ * organization's, and the viewer holds the edit grant every request of its link needs.
2132
+ */
2133
+ mayAsk() {
2134
+ return this.config.scope === "organization" && this.config.canManage;
2135
+ }
2136
+ /**
2137
+ * runAsk sends one read or one create and keeps its answer, unless the engine has moved on by
2138
+ * then or a write sent after it has settled.
2139
+ */
2140
+ async runAsk(kind) {
2141
+ const epoch = this.epoch;
2142
+ this.sent += 1;
2143
+ const place = this.sent;
2144
+ if (kind === "read") {
2145
+ this.latestRead = place;
2146
+ this.asked = true;
2147
+ this.reading = true;
2148
+ this.readFailure = null;
2149
+ this.readFailedAt = 0;
2150
+ } else {
2151
+ this.latestMint = place;
2152
+ this.minting = true;
2153
+ this.mintFailure = null;
2154
+ this.mintFailedAt = 0;
2155
+ }
2156
+ this.publish();
2157
+ const answer = kind === "read" ? await this.sendRead() : await this.sendMint();
2158
+ if (this.disposed || epoch !== this.epoch) {
2159
+ return;
2160
+ }
2161
+ if (kind === "read" && place === this.latestRead) {
2162
+ this.reading = false;
2163
+ }
2164
+ if (kind === "mint" && place === this.latestMint) {
2165
+ this.minting = false;
2166
+ }
2167
+ if (place <= this.outranked || place < this.answeredAt) {
2168
+ this.publish();
2169
+ return;
2170
+ }
2171
+ if (kind === "read" && this.parked) {
2172
+ this.asked = false;
2173
+ this.unheard = place;
2174
+ this.publish();
2175
+ return;
2176
+ }
2177
+ if ("failure" in answer) {
2178
+ if (kind === "read") {
2179
+ this.readFailure = answer;
2180
+ this.readFailedAt = place;
2181
+ } else {
2182
+ this.mintFailure = answer;
2183
+ this.mintFailedAt = place;
2184
+ }
2185
+ this.publish();
2186
+ return;
2187
+ }
2188
+ this.token = answer.token;
2189
+ this.known = true;
2190
+ this.change = kind === "read" ? "read" : "minted";
2191
+ this.answeredAt = place;
2192
+ if (this.readFailedAt < place) {
2193
+ this.readFailure = null;
2194
+ this.readFailedAt = 0;
2195
+ }
2196
+ if (this.mintFailedAt < place) {
2197
+ this.mintFailure = null;
2198
+ this.mintFailedAt = 0;
2199
+ }
2200
+ this.publish();
2201
+ }
2202
+ /** sendRead reads the link through the configured read, a throw answered as a refusal. */
2203
+ async sendRead() {
2204
+ try {
2205
+ return readToken(await this.config.read(this.config.context, this.target));
2206
+ } catch {
2207
+ return unworded;
2208
+ }
2209
+ }
2210
+ /** sendMint creates the link through the bus, a dispatch that throws answered as a refusal. */
2211
+ async sendMint() {
2212
+ try {
2213
+ const result = await this.config.dispatch(
2214
+ this.config.context,
2215
+ "studio.shareLink.mint",
2216
+ this.target
2217
+ );
2218
+ if (!result.ok) {
2219
+ return { failure: result, retryable: isRetryableShareLinkFailure(result) };
2220
+ }
2221
+ const token = mintedShareToken(result);
2222
+ return token === null ? unworded : { token };
2223
+ } catch {
2224
+ return unworded;
2225
+ }
2226
+ }
2227
+ /** act runs one management action and settles the snapshot with its answer. */
2228
+ act(action) {
2229
+ if (this.parked || this.disposed || this.acting !== null || this.snapshot.actions[action] !== "ready") {
2230
+ return Promise.resolve(skipped);
2231
+ }
2232
+ const epoch = this.epoch;
2233
+ const { context, dispatch, scope } = this.config;
2234
+ this.sent += 1;
2235
+ let place = this.sent;
2236
+ const confirming = layerToolContext(context, {
2237
+ confirm: async (request) => {
2238
+ const approved = await context.confirm?.(request) ?? false;
2239
+ if (approved && !this.disposed && epoch === this.epoch) {
2240
+ this.sent += 1;
2241
+ place = this.sent;
2242
+ this.running = true;
2243
+ this.publish();
2244
+ }
2245
+ return approved;
2246
+ }
2247
+ });
2248
+ const target = this.target;
2249
+ this.acting = action;
2250
+ this.publish();
2251
+ if (action === "rotate") {
2252
+ return answered(
2253
+ () => dispatch(confirming, "studio.shareLink.rotate", target),
2254
+ (result) => this.settleRotate(epoch, result)
2255
+ );
2256
+ }
2257
+ return answered(
2258
+ () => dispatch(confirming, "studio.shareLink.disable", target),
2259
+ // The place is read once the answer is in: the gate moves it when it approves.
2260
+ (result) => this.settleDisable(epoch, scope, place, result)
2261
+ );
2262
+ }
2263
+ /**
2264
+ * settleRotate ends a reset with its answer. The token it issued is the newest whatever a read
2265
+ * or a create answered or will answer, so every request sent by now is outranked.
2266
+ *
2267
+ * An `ok` answer that holds no token is refused as the verb refuses a link that holds none,
2268
+ * and the engine was handed no link to show. The server answered `ok` all the same, so it may
2269
+ * have retired the link held: every read and create sent by now is outranked, since its answer
2270
+ * may carry that link, and the engine reads which link stands
2271
+ * ({@link ShareLinkEngine.readStandingLink}). Until that read answers, the link and the latest
2272
+ * change read as they did.
2273
+ */
2274
+ settleRotate(epoch, result) {
2275
+ if (!result.ok) {
2276
+ return this.refuse(epoch, result);
2277
+ }
2278
+ const shareToken = mintedShareToken(result);
2279
+ if (shareToken === null) {
2280
+ this.finish(epoch, () => {
2281
+ this.outranked = this.sent;
2282
+ });
2283
+ this.readStandingLink(epoch);
2284
+ return { failure: tokenlessAnswerRefusal("rotate"), status: "refused" };
2285
+ }
2286
+ this.finish(epoch, () => {
2287
+ this.outranked = this.sent;
2288
+ this.token = shareToken;
2289
+ this.known = true;
2290
+ this.change = "rotated";
2291
+ this.readFailure = null;
2292
+ this.readFailedAt = 0;
2293
+ this.mintFailure = null;
2294
+ this.mintFailedAt = 0;
2295
+ });
2296
+ return { linkWasActive: true, status: "settled" };
2297
+ }
2298
+ /**
2299
+ * readStandingLink reads which link stands, once a reset answered `ok` with no token.
2300
+ *
2301
+ * It is sent while somebody watches a resource whose scope is `"organization"`, the one scope a
2302
+ * read is sent under, for a viewer who holds the grant. On a parked engine, and under a scope or
2303
+ * a grant that takes no read by now, the question is left open: the next subscriber asks it,
2304
+ * or the configuration that takes one does. An engine that was disposed, or that answers for
2305
+ * another target by now, asks nothing.
2306
+ */
2307
+ readStandingLink(epoch) {
2308
+ if (this.disposed || epoch !== this.epoch) {
2309
+ return;
2310
+ }
2311
+ if (this.parked || !this.mayAsk()) {
2312
+ this.asked = false;
2313
+ return;
2314
+ }
2315
+ void this.runAsk("read");
2316
+ }
2317
+ /**
2318
+ * settleDisable ends a disable with its answer, judged under the scope it was sent under and
2319
+ * at the place it left in.
2320
+ */
2321
+ settleDisable(epoch, scope, place, result) {
2322
+ if (!result.ok && !isShareLinkDisableSettled(result, scope)) {
2323
+ return this.refuse(epoch, result);
2324
+ }
2325
+ this.finish(epoch, () => {
2326
+ if (place < this.answeredAt) {
2327
+ return;
2328
+ }
2329
+ this.outranked = place;
2330
+ this.token = null;
2331
+ this.known = true;
2332
+ this.change = "disabled";
2333
+ if (this.readFailedAt < place) {
2334
+ this.readFailure = null;
2335
+ this.readFailedAt = 0;
2336
+ }
2337
+ if (this.mintFailedAt < place) {
2338
+ this.mintFailure = null;
2339
+ this.mintFailedAt = 0;
2340
+ }
2341
+ if (place > this.unheard) {
2342
+ this.asked = true;
2343
+ }
2344
+ });
2345
+ return { linkWasActive: result.ok, status: "settled" };
2346
+ }
2347
+ /**
2348
+ * refuse ends an action whose verb did not run or failed, and answers what it came to:
2349
+ * `"withheld"` for a confirmation nobody approved, `"refused"` with the failure otherwise.
2350
+ * Nothing in the snapshot changes but the action in flight.
2351
+ */
2352
+ refuse(epoch, failure) {
2353
+ this.finish(epoch);
2354
+ return isConfirmationWithheld(failure) ? withheld : { failure, status: "refused" };
2355
+ }
2356
+ /**
2357
+ * finish ends the action in flight: an action may be called again, and the snapshot stops
2358
+ * spinning and takes what `apply` writes, in one change. An engine that was disposed, or that
2359
+ * answers for another target by now, keeps everything as it is: the action it holds, if any,
2360
+ * is the new target's.
2361
+ */
2362
+ finish(epoch, apply) {
2363
+ if (this.disposed || epoch !== this.epoch) {
2364
+ return;
2365
+ }
2366
+ this.acting = null;
2367
+ this.running = false;
2368
+ apply?.();
2369
+ this.publish();
2370
+ }
2371
+ /** compose assembles the snapshot the engine's state stands for now. */
2372
+ compose() {
2373
+ const { canManage, scope } = this.config;
2374
+ const offered = shareLinkActions({ canManage, scope, token: this.token });
2375
+ return {
2376
+ actions: this.acting === null ? offered : heldBack(offered),
2377
+ busy: this.running ? this.acting : null,
2378
+ change: this.change,
2379
+ known: this.known,
2380
+ mintFailure: this.mintFailure,
2381
+ minting: this.minting,
2382
+ readFailure: this.readFailure,
2383
+ reading: this.reading,
2384
+ target: this.target,
2385
+ token: this.token
2386
+ };
2387
+ }
2388
+ /** publish replaces the snapshot when the state moved it, and tells every listener. */
2389
+ publish() {
2390
+ const current = this.snapshot;
2391
+ const next = this.compose();
2392
+ const actions = sameActions(current.actions, next.actions) ? current.actions : next.actions;
2393
+ if (actions === current.actions && next.busy === current.busy && next.change === current.change && next.known === current.known && next.mintFailure === current.mintFailure && next.minting === current.minting && next.readFailure === current.readFailure && next.reading === current.reading && next.target === current.target && next.token === current.token) {
2394
+ return;
2395
+ }
2396
+ this.snapshot = { ...next, actions };
2397
+ notifyListeners([...this.subscriptions].map((subscription) => subscription.listener));
2398
+ }
2399
+ };
2400
+ var queryKeyOf = (source) => source === null ? null : JSON.stringify(source);
2401
+ var noFacts = {
2402
+ createMethod: null,
2403
+ createSerial: 0,
2404
+ inherited: null,
2405
+ origin: null,
2406
+ session: null,
2407
+ zone: null
2408
+ };
2409
+ var factsOf = (state) => {
2410
+ const zone = state.activeZone;
2411
+ const itinerary = state.activeItinerary;
2412
+ return {
2413
+ createMethod: state.zoneCreateMethod,
2414
+ createSerial: state.zoneCreateSerial,
2415
+ // The flag and the itinerary are separate slots: a create inherits only while the itinerary
2416
+ // it was begun inside is still open, and only a create inherits at all.
2417
+ inherited: zone === null && state.zoneCreateInheritsItinerary && itinerary !== null ? {
2418
+ activityId: itinerary.activity_id,
2419
+ itineraryId: itinerary.id,
2420
+ organizationId: itinerary.organization_id ?? null
2421
+ } : null,
2422
+ origin: state.zoneCreateOrigin,
2423
+ session: state.zoneEditSession,
2424
+ zone
2425
+ };
2426
+ };
2427
+ var sameIds = (a, b) => a.length === b.length && a.every((id, index) => id === b[index]);
2428
+ var sameMembers = (a, b) => {
2429
+ const keys = Object.keys(a);
2430
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.is(a[key], b[key]));
2431
+ };
2432
+ var readsSame = (a, b) => a.activeZone === b.activeZone && a.activeItinerary === b.activeItinerary && a.zoneCreateInheritsItinerary === b.zoneCreateInheritsItinerary && a.zoneCreateMethod === b.zoneCreateMethod && a.zoneCreateOrigin === b.zoneCreateOrigin && a.zoneCreateSerial === b.zoneCreateSerial && a.zoneEditSession === b.zoneEditSession;
2433
+ var debounceFrom2 = (debounceMs) => {
2434
+ if (debounceMs === void 0) {
2435
+ return ZONE_PREVIEW_DEBOUNCE_MS;
2436
+ }
2437
+ if (!Number.isFinite(debounceMs) || debounceMs < 0 || debounceMs > MAX_TIMER_MS) {
2438
+ throw new MountayaElementsError(
2439
+ `ZoneFormEngine: debounceMs is ${String(debounceMs)}; pass a number of milliseconds from 0 to ${MAX_TIMER_MS}, or omit it for ${ZONE_PREVIEW_DEBOUNCE_MS}.`
2440
+ );
2441
+ }
2442
+ return debounceMs;
2443
+ };
2444
+ var ZoneFormEngine = class {
2445
+ config;
2446
+ debounceMs;
2447
+ ids;
2448
+ ui;
2449
+ draft = {
2450
+ activityId: null,
2451
+ collectionIds: [],
2452
+ createLevel: DEFAULT_ZONE_LEVEL,
2453
+ createMode: DEFAULT_ZONE_MODE,
2454
+ description: "",
2455
+ endAt: null,
2456
+ name: "",
2457
+ organizationId: null,
2458
+ range: ZONE_DEFAULT_DISTANCE_RANGE_METERS,
2459
+ rangeType: "distance",
2460
+ speedKmh: null,
2461
+ startAt: null,
2462
+ windowOpen: false
2463
+ };
2464
+ /** Whether the name is the reader's own, which stops it following anything. */
2465
+ nameTouched = false;
2466
+ /** Whether the organization is the reader's own choice, null included, which no default fills. */
2467
+ organizationChosen = false;
2468
+ /** The subjects a save is in flight for. A subject saves once at a time, and each on its own. */
2469
+ saving = /* @__PURE__ */ new Set();
2470
+ /** Whether a draw has been asked for and not answered yet. */
2471
+ drawing = false;
2472
+ drawFailure = null;
2473
+ pickFailure = null;
2474
+ /** Counts the origin picks asked for: the refusal of an earlier one is dropped. */
2475
+ pickSerial = 0;
2476
+ /** The origin the last seed read, which a pick that lands moves; undefined until the first. */
2477
+ origin = void 0;
2478
+ saveFailure = null;
2479
+ /**
2480
+ * The latest save's refusal of its reachability query, with the query it was sent with, as
2481
+ * {@link queryKeyOf} writes it; null when the latest save met none.
2482
+ */
2483
+ sourceRefusal = null;
2484
+ previewFailure = null;
2485
+ /** Whether the store's `zoneFormUnsaved` holds this engine's true, written by it. */
2486
+ unsavedWritten = false;
2487
+ /**
2488
+ * Whether the reader changed anything since the subject opened: typed a field, switched the
2489
+ * method or picked an origin. A computed create opens saveable on what it was opened with, and
2490
+ * leaving it untouched loses nothing the reader did, so it is unsaved only once this holds.
2491
+ */
2492
+ touched = false;
2493
+ /** The zone the metadata was seeded from; undefined until the first seed. */
2494
+ bound = void 0;
2495
+ /**
2496
+ * What the failures and a save in flight answer for: the bound zone, or a create, by its
2497
+ * serial, the method it is authored by and the itinerary it inherits from. Null until the
2498
+ * first seed.
2499
+ */
2500
+ subject = null;
2501
+ /**
2502
+ * Counts the subjects a save or a draw can answer for: a refusal sent under an earlier one is
2503
+ * dropped.
2504
+ */
2505
+ subjectEpoch = 0;
2506
+ /**
2507
+ * The create the fields were last seeded for: its serial and the id of the itinerary it
2508
+ * inherits from, and undefined while a zone is bound and before the first seed.
2509
+ */
2510
+ create = void 0;
2511
+ /** The serial of the create the fields were last seeded for, while the last seed was a create. */
2512
+ createSerial = void 0;
2513
+ /** The zone and the catalog the reachability parameters were last seeded from. */
2514
+ sourceSeed = null;
2515
+ /** The store state and the configuration the snapshot was last settled against. */
2516
+ settled = null;
2517
+ /**
2518
+ * The name and the description last judged, with the verdicts, so a pass that moved neither
2519
+ * parses nothing.
2520
+ */
2521
+ judged = null;
2522
+ snapshot;
2523
+ subscriptions = /* @__PURE__ */ new Set();
2524
+ /** Ends the watch on the store, while running. */
2525
+ unwatch = null;
2526
+ /** The key of the preview asked for or waited on; undefined when none has been considered. */
2527
+ previewKey = void 0;
2528
+ /** The preview the pending debounce asks for. */
2529
+ previewInput = null;
2530
+ /**
2531
+ * Counts the questions a preview can answer, and the subjects it can answer for: an answer
2532
+ * from an earlier one is ignored.
2533
+ */
2534
+ previewEpoch = 0;
2535
+ timer = null;
2536
+ /** Whether a reconcile is running, so one started inside it runs after it. */
2537
+ reconciling = false;
2538
+ /** Whether something changed during the running reconcile, which then runs again. */
2539
+ stale = false;
2540
+ /**
2541
+ * Whether nobody is watching. A parked engine watches no store, asks for no preview and answers
2542
+ * no command.
2543
+ */
2544
+ parked = true;
2545
+ disposed = false;
2546
+ /**
2547
+ * Constructing one holds the options and does nothing else: no store is read, no timer armed
2548
+ * and no tool run. A React binding constructs during a render React is free to throw away, and
2549
+ * a constructor with a side effect would leave the discarded copy acting.
2550
+ *
2551
+ * @throws {MountayaElementsError} When `debounceMs` is not a finite number from 0 to
2552
+ * 2,147,483,647.
2553
+ */
2554
+ constructor(options) {
2555
+ const { debounceMs, ids, ui, ...config } = options;
2556
+ this.debounceMs = debounceFrom2(debounceMs);
2557
+ this.ids = ids;
2558
+ this.ui = ui;
2559
+ this.config = config;
2560
+ this.snapshot = this.view(noFacts).snapshot;
2561
+ }
2562
+ /**
2563
+ * getSnapshot returns the current answer, by reference and stable between changes.
2564
+ *
2565
+ * A parked engine settles it on the read: it reads the store and seeds the fields for the zone
2566
+ * bound now, without watching the store, arming a timer or running a tool. So a surface's first
2567
+ * render, and a server's only one, show the bound zone.
2568
+ */
2569
+ getSnapshot() {
2570
+ this.settle();
2571
+ return this.snapshot;
2572
+ }
2573
+ /**
2574
+ * subscribe registers a listener for every change of the snapshot, and returns its own
2575
+ * unsubscribe, which is idempotent.
2576
+ *
2577
+ * The first listener starts the engine and the last one leaving parks it, which is the whole
2578
+ * lifecycle a component can express correctly: React tears an effect down and sets it up again
2579
+ * with the same object under StrictMode, so a latch here would leave a live surface bound to a
2580
+ * dead engine. Each call is its own subscription, so two owners subscribing one shared function
2581
+ * each hold the engine until they release it.
2582
+ */
2583
+ subscribe(listener) {
2584
+ if (this.disposed) {
2585
+ return () => {
2586
+ };
2587
+ }
2588
+ const subscription = { listener };
2589
+ this.subscriptions.add(subscription);
2590
+ if (this.parked) {
2591
+ this.parked = false;
2592
+ this.unwatch = this.ui.subscribe((state) => this.watch(state));
2593
+ this.reconcile();
2594
+ }
2595
+ return () => {
2596
+ if (!this.subscriptions.delete(subscription) || this.subscriptions.size > 0) {
2597
+ return;
2598
+ }
2599
+ if (!this.parked) {
2600
+ this.park();
2601
+ }
2602
+ };
2603
+ }
2604
+ /**
2605
+ * configure replaces the configuration, and settles the form again only when a member changed.
2606
+ *
2607
+ * A binding calls it on every render, so it compares every member by identity and does nothing
2608
+ * when all are the ones it holds. A changed one seeds what waited on it: a catalog that
2609
+ * arrives seeds the activity, collections that arrive are followed, and a name still following
2610
+ * its parameters is written again in the new language. A parked engine keeps the configuration
2611
+ * for its next read.
2612
+ */
2613
+ configure(config) {
2614
+ if (this.disposed || sameMembers(this.config, config)) {
2615
+ return;
2616
+ }
2617
+ this.config = config;
2618
+ if (!this.parked) {
2619
+ this.reconcile();
2620
+ }
2621
+ }
2622
+ /**
2623
+ * dispose parks the engine and drops every listener, for good.
2624
+ *
2625
+ * Idempotent, and every call after it is a no-op rather than an error: an owner torn down
2626
+ * mid-save should not have to guard the calls it already queued. A save in flight still reaches
2627
+ * the tool it was sent to; its answer changes nothing here.
2628
+ */
2629
+ dispose() {
2630
+ if (this.disposed) {
2631
+ return;
2632
+ }
2633
+ this.disposed = true;
2634
+ if (!this.parked) {
2635
+ this.park();
2636
+ }
2637
+ this.subscriptions.clear();
2638
+ }
2639
+ /**
2640
+ * edit writes the given fields, and applies the rule each one carries:
2641
+ *
2642
+ * - `name` makes the name the reader's own, so it stops following the parameters. On a create
2643
+ * whose draft a proposal named it also clears that name from the draft, so the one typed is
2644
+ * shown.
2645
+ * - `name`, `description`, `startAt` and `endAt` clear the previous save's failure.
2646
+ * - `windowOpen: false` clears both bounds, so a hidden window never persists a constraint its
2647
+ * reader cannot see.
2648
+ * - `rangeType` resets `range` to that measure's default and never reinterprets the number,
2649
+ * and a switch to `"distance"` drops the pace, which a distance does not depend on.
2650
+ * - `speedKmh` holds beside a time budget only: on a distance budget it is dropped, so a later
2651
+ * switch to `"time"` starts from the activity's own pace.
2652
+ * - `organizationId` makes the organization the reader's own choice, `null` included: a create
2653
+ * then stays personal beside a `defaultOrganizationId`. On a create whose draft a proposal
2654
+ * filed, or whose draw was armed under another, it is also written on the draft, so the one
2655
+ * picked is shown and saved.
2656
+ * - `level`, while a draw is armed, also runs `studio.zone.setLevel`, which recolours the draft.
2657
+ * A refusal leaves the draft as it was, and the form goes back to the severity it held. On a
2658
+ * create it is also written on the store (`zoneCreatePickedLevel`), which the step of a
2659
+ * proposal that joins the create records, so an undo of the proposal shows it again.
2660
+ *
2661
+ * `rangeType` and `windowOpen` are applied before the fields they reset, so an edit naming both
2662
+ * keeps the value it names. `mode` is the shape a draw is armed with; once armed, and for a
2663
+ * saved zone, the snapshot shows the session's or the zone's own. While the snapshot's
2664
+ * `inherits` is true, `organizationId`, `activityId` and `collectionIds` follow the itinerary
2665
+ * and an edit of one does not hold.
2666
+ *
2667
+ * A call while parked, or after {@link ZoneFormEngine.dispose}, does nothing.
2668
+ */
2669
+ edit(fields) {
2670
+ if (this.parked || this.disposed) {
2671
+ return;
2672
+ }
2673
+ this.touched = true;
2674
+ const { draft } = this;
2675
+ if (fields.rangeType !== void 0) {
2676
+ draft.rangeType = fields.rangeType;
2677
+ draft.range = fields.rangeType === "time" ? ZONE_DEFAULT_TIME_RANGE_SECONDS : ZONE_DEFAULT_DISTANCE_RANGE_METERS;
2678
+ if (fields.rangeType === "distance") {
2679
+ draft.speedKmh = null;
2680
+ }
2681
+ }
2682
+ if (fields.windowOpen !== void 0) {
2683
+ draft.windowOpen = fields.windowOpen;
2684
+ if (!fields.windowOpen) {
2685
+ draft.startAt = null;
2686
+ draft.endAt = null;
2687
+ }
2688
+ }
2689
+ if (fields.name !== void 0) {
2690
+ draft.name = fields.name;
2691
+ this.nameTouched = true;
2692
+ const session = this.ui.getState().zoneEditSession;
2693
+ if (this.bound === null && session?.intent === "create" && session.name !== null) {
2694
+ this.ui.getState().setZoneEditName(null);
2695
+ }
2696
+ }
2697
+ if (fields.description !== void 0) {
2698
+ draft.description = fields.description;
2699
+ }
2700
+ if (fields.startAt !== void 0) {
2701
+ draft.startAt = fields.startAt;
2702
+ }
2703
+ if (fields.endAt !== void 0) {
2704
+ draft.endAt = fields.endAt;
2705
+ }
2706
+ if (fields.name !== void 0 || fields.description !== void 0 || fields.startAt !== void 0 || fields.endAt !== void 0) {
2707
+ this.saveFailure = null;
2708
+ }
2709
+ if (fields.activityId !== void 0) {
2710
+ draft.activityId = fields.activityId;
2711
+ }
2712
+ if (fields.collectionIds !== void 0 && !sameIds(draft.collectionIds, fields.collectionIds)) {
2713
+ draft.collectionIds = [...fields.collectionIds];
2714
+ }
2715
+ if (fields.mode !== void 0) {
2716
+ draft.createMode = fields.mode;
2717
+ }
2718
+ if (fields.organizationId !== void 0) {
2719
+ draft.organizationId = fields.organizationId;
2720
+ this.organizationChosen = true;
2721
+ const session = this.ui.getState().zoneEditSession;
2722
+ if (this.bound === null && session?.intent === "create" && session.organizationId !== fields.organizationId) {
2723
+ this.ui.getState().setZoneEditOrganization(fields.organizationId);
2724
+ }
2725
+ }
2726
+ if (fields.range !== void 0) {
2727
+ draft.range = fields.range;
2728
+ }
2729
+ if (fields.speedKmh !== void 0) {
2730
+ draft.speedKmh = draft.rangeType === "time" ? fields.speedKmh : null;
2731
+ }
2732
+ const held = { level: draft.createLevel, pick: this.ui.getState().zoneCreatePickedLevel };
2733
+ if (fields.level !== void 0) {
2734
+ draft.createLevel = fields.level;
2735
+ if (this.bound === null && held.pick !== fields.level) {
2736
+ this.ui.getState().setZoneCreatePickedLevel(fields.level);
2737
+ }
2738
+ }
2739
+ this.reconcile();
2740
+ if (fields.level !== void 0 && this.snapshot.armed) {
2741
+ void this.recolour(fields.level, held);
2742
+ }
2743
+ }
2744
+ /**
2745
+ * ask runs one tool and answers its result, or null where the host's bus rejected the call.
2746
+ *
2747
+ * A tool bus's dispatch never rejects, and a host's own may. A call it rejects made no answer:
2748
+ * the rejection is held here, so none is left unhandled by a call the form does not await, and
2749
+ * the caller goes on as it does for a tool that did nothing. A save is awaited by its caller
2750
+ * and is not asked through here: its rejection is the caller's to read.
2751
+ */
2752
+ async ask(name, input) {
2753
+ try {
2754
+ return await this.config.dispatch(name, input);
2755
+ } catch {
2756
+ return null;
2757
+ }
2758
+ }
2759
+ /**
2760
+ * recolour sets the armed draft's severity, through `studio.zone.setLevel`. A refusal leaves
2761
+ * the draft painted as it was, and so does a call the bus rejects, so the form goes back to the
2762
+ * severity it held and a create's pick to the one the store held, unless its reader has chosen
2763
+ * another since or the form answers for another subject by then.
2764
+ */
2765
+ async recolour(level, held) {
2766
+ const epoch = this.subjectEpoch;
2767
+ const result = await this.ask("studio.zone.setLevel", { level });
2768
+ if (result?.ok !== true && !this.disposed && epoch === this.subjectEpoch && this.draft.createLevel === level) {
2769
+ this.draft.createLevel = held.level;
2770
+ if (this.bound === null && this.ui.getState().zoneCreatePickedLevel === level) {
2771
+ this.ui.getState().setZoneCreatePickedLevel(held.pick);
2772
+ }
2773
+ this.reconcile();
2774
+ }
2775
+ }
2776
+ /**
2777
+ * setMethod switches how a create is authored, through `studio.zone.setCreateMethod`, and
2778
+ * clears the preview's and the save's failures, which described the method left behind. The
2779
+ * same two are cleared when another caller of that tool switches it. A switch the tool refuses
2780
+ * left no method behind: the two failures stand again, for as long as the form answers for the
2781
+ * same create. A call while parked, or after {@link ZoneFormEngine.dispose}, does nothing.
2782
+ */
2783
+ setMethod(method) {
2784
+ if (this.parked || this.disposed) {
2785
+ return;
2786
+ }
2787
+ this.touched = true;
2788
+ void this.switchMethod(method);
2789
+ }
2790
+ /** switchMethod asks for the switch, and puts back what it cleared when the tool refuses. */
2791
+ async switchMethod(method) {
2792
+ const epoch = this.subjectEpoch;
2793
+ const held = {
2794
+ preview: this.previewFailure,
2795
+ save: this.saveFailure,
2796
+ source: this.sourceRefusal
2797
+ };
2798
+ const answer = this.ask("studio.zone.setCreateMethod", { method });
2799
+ this.saveFailure = null;
2800
+ this.sourceRefusal = null;
2801
+ this.previewFailure = null;
2802
+ this.reconcile();
2803
+ const result = await answer;
2804
+ if (result?.ok === true || this.disposed || epoch !== this.subjectEpoch) {
2805
+ return;
2806
+ }
2807
+ this.saveFailure ??= held.save;
2808
+ this.sourceRefusal ??= held.source;
2809
+ this.previewFailure ??= held.preview;
2810
+ this.reconcile();
2811
+ }
2812
+ /**
2813
+ * beginOriginPick arms the map for the click that places a reachability zone's origin, through
2814
+ * `studio.zone.beginOriginPick`.
2815
+ *
2816
+ * A refusal is kept as the snapshot's `pickFailure`, for as long as the form answers for the
2817
+ * create or the zone the pick was asked for and no later pick was asked.
2818
+ *
2819
+ * A call while parked, or after {@link ZoneFormEngine.dispose}, does nothing.
2820
+ */
2821
+ beginOriginPick() {
2822
+ if (this.parked || this.disposed) {
2823
+ return;
2824
+ }
2825
+ this.touched = true;
2826
+ this.pickFailure = null;
2827
+ this.reconcile();
2828
+ void this.pick();
2829
+ }
2830
+ /** pick asks for the origin pick, and keeps a refusal while it is the latest and its form's. */
2831
+ async pick() {
2832
+ const epoch = this.subjectEpoch;
2833
+ this.pickSerial += 1;
2834
+ const asked = this.pickSerial;
2835
+ const result = await this.ask("studio.zone.beginOriginPick", {});
2836
+ if (result === null || result.ok || this.disposed || epoch !== this.subjectEpoch || asked !== this.pickSerial) {
2837
+ return;
2838
+ }
2839
+ this.pickFailure = result;
2840
+ this.reconcile();
2841
+ }
2842
+ /**
2843
+ * beginDraw arms the map to draw a new zone, through `studio.zone.editBegin`, in the form's
2844
+ * shape and severity and under its organization. The zone's id is minted by the `ids` seam: a
2845
+ * zone cannot persist empty, so the draw session needs a handle before there is a zone to name.
2846
+ *
2847
+ * A refusal is kept as the snapshot's `drawFailure`, for as long as the form answers for the
2848
+ * create the draw was asked for.
2849
+ *
2850
+ * It does nothing while a zone is bound, while a draw or a reshape is armed, while an earlier
2851
+ * call is still unanswered, while no shape is chosen, while parked, or after
2852
+ * {@link ZoneFormEngine.dispose}.
2853
+ */
2854
+ beginDraw() {
2855
+ if (this.parked || this.disposed || this.drawing) {
2856
+ return;
2857
+ }
2858
+ const facts = factsOf(this.ui.getState());
2859
+ const { createLevel, createMode, organizationId } = this.draft;
2860
+ if (facts.zone !== null || facts.session !== null || createMode === null) {
2861
+ return;
2862
+ }
2863
+ this.drawing = true;
2864
+ this.drawFailure = null;
2865
+ this.reconcile();
2866
+ void this.draw({
2867
+ intent: "create",
2868
+ level: createLevel,
2869
+ mode: createMode,
2870
+ organizationId: organizationId ?? void 0,
2871
+ zoneId: this.ids.next()
2872
+ });
2873
+ }
2874
+ /** draw asks for the draw session, and keeps a refusal while its create is the form's. */
2875
+ async draw(input) {
2876
+ const epoch = this.subjectEpoch;
2877
+ const result = await this.ask("studio.zone.editBegin", input);
2878
+ if (result !== null && !result.ok && !this.disposed && epoch === this.subjectEpoch) {
2879
+ this.drawFailure = result;
2880
+ }
2881
+ this.drawing = false;
2882
+ this.reconcile();
2883
+ }
2884
+ /**
2885
+ * save persists the form through the one tool call {@link zoneSaveRequest} routes it to, and
2886
+ * resolves once the tool has answered. It resolves at once, having sent nothing, when a save
2887
+ * of the same zone or the same create is already in flight, when the form has nothing to
2888
+ * send, while parked, and after {@link ZoneFormEngine.dispose}. A save in flight for another
2889
+ * zone holds back no save of this one.
2890
+ *
2891
+ * A refusal is kept as the snapshot's `saveFailure` and the fields stay as typed, so a retry is
2892
+ * one more call. A refusal that lands once the form answers for another zone, or once a create
2893
+ * has switched method or changed the itinerary it inherits from, is dropped: it describes a
2894
+ * form nobody is looking at. One that lands once the form has come back to the zone or the
2895
+ * create it was sent for is kept, since the snapshot read `saving` for it all along. A refusal
2896
+ * of the reachability query the fields stated as the save left is kept as the snapshot's
2897
+ * `sourceFailure` instead, for the surface to show at the query's fields. A create
2898
+ * that lost some of its collections raises a warning through `studio.alert.show`: the zone
2899
+ * exists, and the reader should know where it was not filed.
2900
+ *
2901
+ * It never rejects while `dispatch` does not.
2902
+ */
2903
+ async save() {
2904
+ const { subject } = this;
2905
+ if (this.parked || this.disposed || subject === null || this.saving.has(subject)) {
2906
+ return;
2907
+ }
2908
+ this.saveFailure = null;
2909
+ this.sourceRefusal = null;
2910
+ const request = this.saveRequest();
2911
+ if (request === null) {
2912
+ this.reconcile();
2913
+ return;
2914
+ }
2915
+ const query = queryKeyOf(this.statedSource());
2916
+ this.saving.add(subject);
2917
+ this.reconcile();
2918
+ try {
2919
+ const result = await this.run(request);
2920
+ if (this.disposed) {
2921
+ return;
2922
+ }
2923
+ if (!result.ok) {
2924
+ if (subject !== this.subject) {
2925
+ return;
2926
+ }
2927
+ if (query !== null && zoneSourceRefused(result)) {
2928
+ this.sourceRefusal = { failure: result, query };
2929
+ } else {
2930
+ this.saveFailure = result;
2931
+ }
2932
+ return;
2933
+ }
2934
+ const failed = result.data !== void 0 && "failedCollectionIds" in result.data ? result.data.failedCollectionIds : [];
2935
+ if (failed.length > 0) {
2936
+ void this.ask("studio.alert.show", {
2937
+ level: "warning",
2938
+ message: this.config.strings.zoneForm.collectionAttachWarning(failed.length)
2939
+ });
2940
+ }
2941
+ } finally {
2942
+ this.saving.delete(subject);
2943
+ this.reconcile();
2944
+ }
2945
+ }
2946
+ /** run dispatches a save request, each arm with its own tool's input. */
2947
+ run(request) {
2948
+ switch (request.name) {
2949
+ case "studio.zone.create":
2950
+ return this.config.dispatch(request.name, request.input);
2951
+ case "studio.zone.editCommit":
2952
+ return this.config.dispatch(request.name, request.input);
2953
+ case "studio.zone.update":
2954
+ return this.config.dispatch(request.name, request.input);
2955
+ }
2956
+ }
2957
+ /** saveRequest routes the form as it stands to the tool call that persists it, or to null. */
2958
+ saveRequest() {
2959
+ const facts = factsOf(this.ui.getState());
2960
+ const { fields, method } = this.snapshot;
2961
+ const { zone } = facts;
2962
+ return zoneSaveRequest({
2963
+ canEdit: zone === null || canEditOwnedResource(
2964
+ { createdById: zone.created_by.id, organizationId: zone.organization_id },
2965
+ this.config.userId,
2966
+ this.config.writableOrganizationIds
2967
+ ),
2968
+ fields,
2969
+ method,
2970
+ session: facts.session,
2971
+ source: this.sourceFor(facts, method),
2972
+ zone
2973
+ });
2974
+ }
2975
+ /** statedSource is the reachability query the fields state as the store stands, or null. */
2976
+ statedSource() {
2977
+ return this.sourceFor(factsOf(this.ui.getState()), this.snapshot.method);
2978
+ }
2979
+ /**
2980
+ * publishUnsaved writes whether the form holds something unsaved on the store's
2981
+ * `zoneFormUnsaved`, where `studio.zone.publish` and the publication band read it, when that
2982
+ * answer moved. A parked engine writes nothing: its reads run inside a render, and a form
2983
+ * nobody watches holds nothing for anyone to lose.
2984
+ *
2985
+ * The store hears of the write at once, and so does this engine's own watch, which finds no slot
2986
+ * it reads moved and runs no pass.
2987
+ */
2988
+ publishUnsaved(unsaved) {
2989
+ if (this.parked || this.disposed || unsaved === this.unsavedWritten) {
2990
+ return;
2991
+ }
2992
+ this.unsavedWritten = unsaved;
2993
+ this.ui.getState().setZoneFormUnsaved(unsaved);
2994
+ }
2995
+ /**
2996
+ * park stops watching the store, drops the pending preview and forgets the one in flight. The
2997
+ * unsaved answer it wrote is taken back: a form that unmounts holds nothing any more.
2998
+ */
2999
+ park() {
3000
+ if (this.unsavedWritten) {
3001
+ this.unsavedWritten = false;
3002
+ this.ui.getState().setZoneFormUnsaved(false);
3003
+ }
3004
+ this.parked = true;
3005
+ this.unwatch?.();
3006
+ this.unwatch = null;
3007
+ this.cancelPending();
3008
+ this.previewKey = void 0;
3009
+ this.previewInput = null;
3010
+ this.previewEpoch += 1;
3011
+ }
3012
+ /** settle brings a parked engine's snapshot in line with the store and the configuration. */
3013
+ settle() {
3014
+ if (this.disposed || !this.parked) {
3015
+ return;
3016
+ }
3017
+ const { settled } = this;
3018
+ if (settled !== null && settled.config === this.config && readsSame(settled.state, this.ui.getState())) {
3019
+ return;
3020
+ }
3021
+ this.reconcile();
3022
+ }
3023
+ /**
3024
+ * watch answers one notification of the store: it runs a pass when a slot the form reads
3025
+ * moved, and nothing otherwise, so a hover or a selection costs the form one comparison.
3026
+ */
3027
+ watch(state) {
3028
+ const { settled } = this;
3029
+ if (settled !== null && settled.config === this.config && readsSame(settled.state, state)) {
3030
+ this.settled = { config: settled.config, state };
3031
+ return;
3032
+ }
3033
+ this.reconcile();
3034
+ }
3035
+ /**
3036
+ * reconcile seeds the fields from the store and the configuration, publishes the snapshot and
3037
+ * follows the preview it is worth. A change made while it runs, by a listener or by a tool a
3038
+ * preview runs at once, runs it again once it finishes rather than inside it.
3039
+ */
3040
+ reconcile() {
3041
+ if (this.disposed) {
3042
+ return;
3043
+ }
3044
+ if (this.reconciling) {
3045
+ this.stale = true;
3046
+ return;
3047
+ }
3048
+ this.reconciling = true;
3049
+ try {
3050
+ do {
3051
+ this.stale = false;
3052
+ const state = this.ui.getState();
3053
+ this.settled = { config: this.config, state };
3054
+ const facts = factsOf(state);
3055
+ this.seed(facts);
3056
+ const view = this.view(facts);
3057
+ this.commit(view.snapshot);
3058
+ this.publishUnsaved(view.changed);
3059
+ this.followPreview(view);
3060
+ } while (this.stale && !this.disposed);
3061
+ } finally {
3062
+ this.reconciling = false;
3063
+ }
3064
+ }
3065
+ /** seed brings the fields in line with the bound zone, the create's context and the catalog. */
3066
+ seed(facts) {
3067
+ const { draft } = this;
3068
+ const { activities, defaultOrganizationId, inheritedCollectionIds } = this.config;
3069
+ const { inherited, zone } = facts;
3070
+ const previous = this.bound;
3071
+ if (zone !== previous) {
3072
+ this.bound = zone;
3073
+ if (zone !== null && previous != null && previous.id === zone.id) {
3074
+ this.follow(previous, zone, facts.session);
3075
+ } else {
3076
+ this.seedMetadata(zone);
3077
+ }
3078
+ } else if (zone === null && facts.createSerial !== this.createSerial) {
3079
+ this.seedMetadata(null);
3080
+ }
3081
+ this.createSerial = zone === null ? facts.createSerial : void 0;
3082
+ const create = zone === null ? `${facts.createSerial}:${inherited?.itineraryId ?? ""}` : void 0;
3083
+ const subject = zone === null ? `create:${facts.createMethod ?? DEFAULT_ZONE_CREATE_METHOD}:${create ?? ""}` : `zone:${zone.id}`;
3084
+ if (subject !== this.subject) {
3085
+ this.subject = subject;
3086
+ this.touched = false;
3087
+ this.drawFailure = null;
3088
+ this.pickFailure = null;
3089
+ this.saveFailure = null;
3090
+ this.sourceRefusal = null;
3091
+ this.previewFailure = null;
3092
+ this.subjectEpoch += 1;
3093
+ this.previewEpoch += 1;
3094
+ }
3095
+ if (facts.origin !== this.origin) {
3096
+ this.origin = facts.origin;
3097
+ this.pickFailure = null;
3098
+ }
3099
+ if (facts.session !== null) {
3100
+ this.drawFailure = null;
3101
+ }
3102
+ if (create !== this.create) {
3103
+ this.create = create;
3104
+ if (create !== void 0) {
3105
+ this.resetCreate();
3106
+ }
3107
+ }
3108
+ this.seedParameters(zone);
3109
+ if (zone !== null) {
3110
+ return;
3111
+ }
3112
+ if (inherited) {
3113
+ draft.organizationId = inherited.organizationId;
3114
+ if (!sameIds(draft.collectionIds, inheritedCollectionIds)) {
3115
+ draft.collectionIds = [...inheritedCollectionIds];
3116
+ }
3117
+ if (activities.length > 0) {
3118
+ draft.activityId = inherited.activityId;
3119
+ }
3120
+ } else {
3121
+ if (draft.organizationId === null && !this.organizationChosen) {
3122
+ draft.organizationId = defaultOrganizationId;
3123
+ }
3124
+ if (draft.activityId === null && activities.length > 0) {
3125
+ draft.activityId = firstRoutableActivityId(activities);
3126
+ }
3127
+ }
3128
+ if (!this.nameTouched) {
3129
+ const name = zoneAutoName({
3130
+ activityName: this.activityName(),
3131
+ language: this.config.language,
3132
+ method: facts.createMethod ?? DEFAULT_ZONE_CREATE_METHOD,
3133
+ proposedName: facts.session?.name ?? null,
3134
+ range: draft.range,
3135
+ rangeType: draft.rangeType,
3136
+ strings: this.config.strings.zoneForm
3137
+ });
3138
+ if (name !== null) {
3139
+ draft.name = name;
3140
+ }
3141
+ }
3142
+ }
3143
+ /**
3144
+ * seedParameters brings the reachability parameters in line with the query `zone` is stored
3145
+ * with and with the catalog, and drops an activity the catalog lists no more.
3146
+ */
3147
+ seedParameters(zone) {
3148
+ const { draft } = this;
3149
+ const { activities } = this.config;
3150
+ const seeded = this.sourceSeed;
3151
+ if (seeded?.zone !== zone || seeded.activities !== activities) {
3152
+ this.sourceSeed = { activities, zone };
3153
+ const source = zone?.source;
3154
+ if (source) {
3155
+ const says = parametersOf(activities, source);
3156
+ const earlier = seeded?.zone?.id === zone?.id ? seeded?.zone?.source : void 0;
3157
+ if (seeded && earlier && draft.activityId === activityIdForSlug(seeded.activities, earlier.activity)) {
3158
+ draft.activityId = activityIdForSlug(activities, earlier.activity);
3159
+ }
3160
+ const said = earlier ? parametersOf(activities, earlier) : null;
3161
+ const held = {
3162
+ activityId: draft.activityId,
3163
+ range: draft.range,
3164
+ rangeType: draft.rangeType,
3165
+ speedKmh: draft.speedKmh
3166
+ };
3167
+ if (said === null || sameMembers(held, said) || sameMembers(held, says)) {
3168
+ draft.activityId = says.activityId;
3169
+ draft.rangeType = says.rangeType;
3170
+ draft.range = says.range;
3171
+ draft.speedKmh = says.speedKmh;
3172
+ }
3173
+ }
3174
+ }
3175
+ if (draft.activityId !== null && activities.length > 0 && activityForId(activities, draft.activityId) === null) {
3176
+ const stored = zone?.source?.activity;
3177
+ draft.activityId = stored === void 0 ? null : activityIdForSlug(activities, stored);
3178
+ }
3179
+ }
3180
+ /**
3181
+ * seedMetadata seeds what a zone says from `zone`, and from a create's defaults for none: the
3182
+ * name, the description, the window and the severity.
3183
+ */
3184
+ seedMetadata(zone) {
3185
+ const { draft } = this;
3186
+ draft.name = zone?.name ?? "";
3187
+ draft.description = zone?.description ?? "";
3188
+ draft.startAt = zone?.start_at ?? null;
3189
+ draft.endAt = zone?.end_at ?? null;
3190
+ draft.windowOpen = draft.startAt !== null || draft.endAt !== null;
3191
+ draft.createLevel = zone?.level ?? DEFAULT_ZONE_LEVEL;
3192
+ this.nameTouched = zone !== null;
3193
+ }
3194
+ /**
3195
+ * follow brings the fields in line with the bound zone written again: `previous` is what it
3196
+ * said and `next` what it says now.
3197
+ *
3198
+ * A field the reader has not moved off what the zone said takes what it says now, and so does
3199
+ * one that already says it, which is how the reader's own save lands in its stored spelling.
3200
+ * Any other is what the reader typed and has not saved, and stays. The window is one answer,
3201
+ * its bounds and whether it is open, taken whole from the reader once they moved any of it,
3202
+ * so no bound a collaborator chose is ever paired with one the reader did.
3203
+ *
3204
+ * The severity of a reshape armed on the zone is shown over the form's own, so it follows by
3205
+ * the same rule: while `session` still paints the severity the zone said, it is set to the one
3206
+ * the zone says now, through `studio.zone.setLevel`. One the reader moved is theirs and stays.
3207
+ * Left as it was, the form would read unsaved after a collaborator's change of severity, and
3208
+ * its save would write the old one back.
3209
+ */
3210
+ follow(previous, next, session) {
3211
+ const { draft } = this;
3212
+ if (session !== null && session.zoneId === next.id && session.level === previous.level && next.level !== previous.level) {
3213
+ void this.ask("studio.zone.setLevel", { level: next.level });
3214
+ }
3215
+ if (!typedOver("name", draft.name, previous, next)) {
3216
+ draft.name = next.name;
3217
+ }
3218
+ if (!typedOver("description", draft.description, previous, next)) {
3219
+ draft.description = next.description ?? "";
3220
+ }
3221
+ if (!typedOver("level", draft.createLevel, previous, next)) {
3222
+ draft.createLevel = next.level;
3223
+ }
3224
+ const windowTyped = typedOver("startAt", draft.startAt, previous, next) || typedOver("endAt", draft.endAt, previous, next) || draft.windowOpen !== windowOpens(previous) && draft.windowOpen !== windowOpens(next);
3225
+ if (!windowTyped) {
3226
+ draft.startAt = next.start_at;
3227
+ draft.endAt = next.end_at;
3228
+ draft.windowOpen = windowOpens(next);
3229
+ }
3230
+ }
3231
+ /**
3232
+ * resetCreate returns the fields a create seeds for itself to a create's defaults: where it is
3233
+ * filed, the shape it is drawn in and the parameters it is computed from. What the zone says
3234
+ * is seeded from the zone, bound or not.
3235
+ */
3236
+ resetCreate() {
3237
+ const { draft } = this;
3238
+ this.organizationChosen = false;
3239
+ draft.activityId = null;
3240
+ if (draft.collectionIds.length > 0) {
3241
+ draft.collectionIds = [];
3242
+ }
3243
+ draft.createMode = DEFAULT_ZONE_MODE;
3244
+ draft.organizationId = null;
3245
+ draft.range = ZONE_DEFAULT_DISTANCE_RANGE_METERS;
3246
+ draft.rangeType = "distance";
3247
+ draft.speedKmh = null;
3248
+ }
3249
+ /** activityName is the chosen activity's name in the reader's language, or null. */
3250
+ activityName() {
3251
+ const { activityId } = this.draft;
3252
+ const activity = activityId === null ? null : activityForId(this.config.activities, activityId);
3253
+ return activity ? localizedName(activity, this.config.language) : null;
3254
+ }
3255
+ /** sourceFor is the reachability query the fields state under `facts`, or null. */
3256
+ sourceFor(facts, method) {
3257
+ const { activityId, range, rangeType, speedKmh } = this.draft;
3258
+ const activity = activityId === null ? null : activityForId(this.config.activities, activityId);
3259
+ return zoneSourceQuery({
3260
+ activitySlug: activity?.slug ?? null,
3261
+ method,
3262
+ origin: facts.origin,
3263
+ range,
3264
+ rangeType,
3265
+ speedKmh
3266
+ });
3267
+ }
3268
+ /** view reads the form as it stands under `facts`. */
3269
+ view(facts) {
3270
+ const { draft } = this;
3271
+ const { session, zone } = facts;
3272
+ const method = zone === null ? facts.createMethod ?? DEFAULT_ZONE_CREATE_METHOD : zone.source ? "reachability" : "draw";
3273
+ const fields = {
3274
+ activityId: draft.activityId,
3275
+ collectionIds: draft.collectionIds,
3276
+ description: draft.description,
3277
+ endAt: draft.endAt,
3278
+ // An armed session carries the severity the draft is painted in.
3279
+ level: session?.level ?? draft.createLevel,
3280
+ mode: zone === null ? session?.mode ?? draft.createMode : zone.mode,
3281
+ // A create's draft a proposal named is shown under that name, and under the form's own
3282
+ // where none did or its reader typed over it.
3283
+ name: zone === null ? session?.name ?? draft.name : draft.name,
3284
+ // A create's session carries the organization it is filed under, a proposal's included.
3285
+ organizationId: zone === null ? session?.organizationId ?? draft.organizationId : draft.organizationId,
3286
+ range: draft.range,
3287
+ rangeType: draft.rangeType,
3288
+ speedKmh: draft.speedKmh,
3289
+ startAt: draft.startAt,
3290
+ windowOpen: draft.windowOpen
3291
+ };
3292
+ const source = this.sourceFor(facts, method);
3293
+ const armed = session !== null;
3294
+ const metadataDirty = zone !== null && isZoneMetadataDirty(fields, zone);
3295
+ const sourceDirty = zone !== null && isZoneSourceDirty(source, zone.source);
3296
+ const { descriptionValid, nameValid } = this.judge(fields.name, fields.description);
3297
+ const saving = this.subject !== null && this.saving.has(this.subject);
3298
+ const windowValid = !isZoneWindowInvalid(fields.startAt, fields.endAt);
3299
+ const reachabilityCreate = zone === null && method === "reachability";
3300
+ const previewFailure = source === null ? null : this.previewFailure;
3301
+ const refused = this.sourceRefusal;
3302
+ const sourceFailure = refused !== null && refused.query === queryKeyOf(source) ? refused.failure : null;
3303
+ const unsaved = zone === null ? reachabilityCreate ? source !== null && previewFailure === null : isZoneGeometryDirty(session) : isZoneGeometryDirty(session) || metadataDirty || sourceDirty;
3304
+ const changed = reachabilityCreate ? unsaved && this.touched : unsaved;
3305
+ const preview = source === null ? null : {
3306
+ activity: source.activity,
3307
+ level: fields.level,
3308
+ location: source.location,
3309
+ ranges: [source.range],
3310
+ rangeType: source.range_type,
3311
+ speed: source.speed
3312
+ };
3313
+ return {
3314
+ preview,
3315
+ previewKey: preview === null ? null : JSON.stringify(preview),
3316
+ snapshot: {
3317
+ armed,
3318
+ descriptionValid,
3319
+ drawFailure: this.drawFailure,
3320
+ fields,
3321
+ inherits: facts.inherited !== null,
3322
+ method,
3323
+ nameValid,
3324
+ pickFailure: this.pickFailure,
3325
+ previewFailure,
3326
+ saveFailure: this.saveFailure,
3327
+ saveOffered: reachabilityCreate || armed || metadataDirty || sourceDirty,
3328
+ saveReady: !saving && nameValid && descriptionValid && windowValid && unsaved,
3329
+ saving,
3330
+ sourceFailure,
3331
+ windowValid,
3332
+ zoneId: zone?.id ?? null
3333
+ },
3334
+ changed
3335
+ };
3336
+ }
3337
+ /**
3338
+ * judge holds a name and a description to the bounds the tools hold them to. It parses only a
3339
+ * text it has not just judged, so a pass that moved neither, a drag's every frame among them,
3340
+ * parses nothing.
3341
+ */
3342
+ judge(name, description) {
3343
+ const last = this.judged;
3344
+ if (last !== null && last.name === name && last.description === description) {
3345
+ return last;
3346
+ }
3347
+ const judged = {
3348
+ description,
3349
+ descriptionValid: zoneDescriptionSchema.safeParse(description).success,
3350
+ name,
3351
+ nameValid: zoneNameSchema.safeParse(name).success
3352
+ };
3353
+ this.judged = judged;
3354
+ return judged;
3355
+ }
3356
+ /** commit publishes `next` when it differs from the snapshot, and tells every listener. */
3357
+ commit(next) {
3358
+ const fields = sameMembers(this.snapshot.fields, next.fields) ? this.snapshot.fields : next.fields;
3359
+ const snapshot = { ...next, fields };
3360
+ if (sameMembers(this.snapshot, snapshot)) {
3361
+ return;
3362
+ }
3363
+ this.snapshot = snapshot;
3364
+ notifyListeners(Array.from(this.subscriptions, (subscription) => subscription.listener));
3365
+ }
3366
+ /**
3367
+ * followPreview asks for the preview `view` is worth, after the debounce, unless that very
3368
+ * preview is already asked for or waited on. A parked engine asks for none.
3369
+ */
3370
+ followPreview(view) {
3371
+ if (this.parked || view.previewKey === this.previewKey) {
3372
+ return;
3373
+ }
3374
+ this.cancelPending();
3375
+ this.previewKey = view.previewKey;
3376
+ this.previewInput = view.preview;
3377
+ this.previewEpoch += 1;
3378
+ if (view.preview === null) {
3379
+ this.previewFailure = null;
3380
+ return;
3381
+ }
3382
+ if (this.debounceMs === 0) {
3383
+ this.askPreview();
3384
+ return;
3385
+ }
3386
+ this.timer = setTimeout(() => {
3387
+ this.timer = null;
3388
+ this.askPreview();
3389
+ }, this.debounceMs);
3390
+ }
3391
+ /** askPreview runs the preview waited on, and keeps its answer while its question stands. */
3392
+ askPreview() {
3393
+ const input = this.previewInput;
3394
+ if (input === null) {
3395
+ return;
3396
+ }
3397
+ const epoch = this.previewEpoch;
3398
+ void this.ask("studio.zone.reachabilityPreview", input).then((result) => {
3399
+ if (result === null || epoch !== this.previewEpoch || this.parked) {
3400
+ return;
3401
+ }
3402
+ this.previewFailure = result.ok ? null : result;
3403
+ this.reconcile();
3404
+ });
3405
+ }
3406
+ cancelPending() {
3407
+ if (this.timer !== null) {
3408
+ clearTimeout(this.timer);
3409
+ this.timer = null;
3410
+ }
3411
+ }
3412
+ };
3413
+
3414
+ export { EmbedFramingEngine, EmbedReadyEngine, FRAMING_PAGE_SESSION_TIMEOUT_MS, ItineraryPaceEngine, ProfileMarkerEngine, SegmentDraftEngine, ShareLinkEngine, ZoneFormEngine, askFramingPageForSession };
3415
+ //# sourceMappingURL=index.js.map
3416
+ //# sourceMappingURL=index.js.map