@mountaya/studio 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/agent/index.cjs +2561 -2815
  3. package/dist/agent/index.cjs.map +1 -1
  4. package/dist/agent/index.d.cts +766 -786
  5. package/dist/agent/index.d.ts +766 -786
  6. package/dist/agent/index.js +2553 -2790
  7. package/dist/agent/index.js.map +1 -1
  8. package/dist/chunk-3Oi_Zrtm.js +9 -0
  9. package/dist/chunk-3Oi_Zrtm.js.map +1 -0
  10. package/dist/chunk-B18OPIu_.js +6 -0
  11. package/dist/chunk-B18OPIu_.js.map +1 -0
  12. package/dist/chunk-B5Uz3Qct.cjs +15 -0
  13. package/dist/chunk-B5Uz3Qct.cjs.map +1 -0
  14. package/dist/chunk-BBEJwkd3.d.cts +839 -0
  15. package/dist/chunk-BIEc_SkR.cjs +29 -0
  16. package/dist/chunk-BIEc_SkR.cjs.map +1 -0
  17. package/dist/chunk-BKMFOe-N.js +171 -0
  18. package/dist/chunk-BKMFOe-N.js.map +1 -0
  19. package/dist/chunk-BP4uy7E1.d.ts +11583 -0
  20. package/dist/chunk-BSHTsFiB.js +1403 -0
  21. package/dist/chunk-BSHTsFiB.js.map +1 -0
  22. package/dist/chunk-BTUUABGI.js +17 -0
  23. package/dist/chunk-BTUUABGI.js.map +1 -0
  24. package/dist/chunk-BaPiaz5X.cjs +115 -0
  25. package/dist/chunk-BaPiaz5X.cjs.map +1 -0
  26. package/dist/chunk-BeCVpkYr.cjs +542 -0
  27. package/dist/chunk-BeCVpkYr.cjs.map +1 -0
  28. package/dist/chunk-BgngsvK8.cjs +6202 -0
  29. package/dist/chunk-BgngsvK8.cjs.map +1 -0
  30. package/dist/chunk-BhInd7CJ.d.cts +253 -0
  31. package/dist/chunk-Bn6ZbxkS.cjs +27 -0
  32. package/dist/chunk-By9ZnkVI.js +60 -0
  33. package/dist/chunk-By9ZnkVI.js.map +1 -0
  34. package/dist/chunk-BzqPhxsz.cjs +367 -0
  35. package/dist/chunk-BzqPhxsz.cjs.map +1 -0
  36. package/dist/chunk-C2mMX81q.d.ts +443 -0
  37. package/dist/chunk-C2rr9Q0V.cjs +1402 -0
  38. package/dist/chunk-C2rr9Q0V.cjs.map +1 -0
  39. package/dist/{directorThreads-CqmvsV8b.d.cts → chunk-CDJCbwIQ.d.cts} +20 -22
  40. package/dist/chunk-CLGvBOVH.d.cts +1654 -0
  41. package/dist/chunk-COdw1dc6.d.ts +525 -0
  42. package/dist/chunk-CQCJnT2i.d.ts +511 -0
  43. package/dist/chunk-CSyHY67q.cjs +353 -0
  44. package/dist/chunk-CSyHY67q.cjs.map +1 -0
  45. package/dist/chunk-CiK1Iqrv.js +950 -0
  46. package/dist/chunk-CiK1Iqrv.js.map +1 -0
  47. package/dist/chunk-CmJBgSwZ.cjs +24 -0
  48. package/dist/chunk-CmJBgSwZ.cjs.map +1 -0
  49. package/dist/chunk-CnrsRK2u.cjs +83 -0
  50. package/dist/chunk-CnrsRK2u.cjs.map +1 -0
  51. package/dist/chunk-Co782_9r.js +326 -0
  52. package/dist/chunk-Co782_9r.js.map +1 -0
  53. package/dist/chunk-Csr3KDpZ.cjs +32 -0
  54. package/dist/chunk-Csr3KDpZ.cjs.map +1 -0
  55. package/dist/chunk-CwkmccXv.js +89 -0
  56. package/dist/chunk-CwkmccXv.js.map +1 -0
  57. package/dist/chunk-D0Q4iL9B.cjs +255 -0
  58. package/dist/chunk-D0Q4iL9B.cjs.map +1 -0
  59. package/dist/chunk-DFwiSzUS.cjs +72 -0
  60. package/dist/chunk-DFwiSzUS.cjs.map +1 -0
  61. package/dist/chunk-DIFayl2P.d.cts +443 -0
  62. package/dist/chunk-DIGF58ux.d.cts +525 -0
  63. package/dist/chunk-DKuuuld5.js +101 -0
  64. package/dist/chunk-DKuuuld5.js.map +1 -0
  65. package/dist/chunk-DMePkFEo.js +5054 -0
  66. package/dist/chunk-DMePkFEo.js.map +1 -0
  67. package/dist/chunk-DO5SIBgu.js +305 -0
  68. package/dist/chunk-DO5SIBgu.js.map +1 -0
  69. package/dist/chunk-DOQ_7eE5.d.ts +6662 -0
  70. package/dist/{tabs-B2nRO4p_.d.ts → chunk-DThaaNeb.d.cts} +2 -2
  71. package/dist/{tabs-B2nRO4p_.d.cts → chunk-DThaaNeb.d.ts} +2 -2
  72. package/dist/{directorThreads-CqmvsV8b.d.ts → chunk-DUQzjUJy.d.ts} +20 -22
  73. package/dist/chunk-DX37IPhV.cjs +1903 -0
  74. package/dist/chunk-DX37IPhV.cjs.map +1 -0
  75. package/dist/chunk-Damps5Tk.cjs +155 -0
  76. package/dist/chunk-Damps5Tk.cjs.map +1 -0
  77. package/dist/chunk-DbK5PhpJ.d.ts +1654 -0
  78. package/dist/chunk-De0vAASv.d.ts +253 -0
  79. package/dist/chunk-DhSZ7YZt.d.cts +6662 -0
  80. package/dist/chunk-DjEvqvPA.cjs +43 -0
  81. package/dist/chunk-DjEvqvPA.cjs.map +1 -0
  82. package/dist/{saveFile-j-1kkApx.d.cts → chunk-DkwDzwvu.d.cts} +7 -9
  83. package/dist/{saveFile-j-1kkApx.d.ts → chunk-DkwDzwvu.d.ts} +7 -9
  84. package/dist/chunk-Dmszv9If.js +71 -0
  85. package/dist/chunk-Dmszv9If.js.map +1 -0
  86. package/dist/chunk-Dp_ftNWY.d.cts +511 -0
  87. package/dist/chunk-DsHQySz0.js +31 -0
  88. package/dist/chunk-DsHQySz0.js.map +1 -0
  89. package/dist/chunk-DwoUyHHh.js +281 -0
  90. package/dist/chunk-DwoUyHHh.js.map +1 -0
  91. package/dist/chunk-IaIDQflj.d.cts +2315 -0
  92. package/dist/chunk-IaIDQflj.d.ts +2315 -0
  93. package/dist/chunk-cVXLsZfL.d.ts +839 -0
  94. package/dist/chunk-mIaCX9EJ.d.cts +11583 -0
  95. package/dist/chunk-nJQxbOwQ.cjs +8962 -0
  96. package/dist/chunk-nJQxbOwQ.cjs.map +1 -0
  97. package/dist/chunk-o9jaxhCO.js +8852 -0
  98. package/dist/chunk-o9jaxhCO.js.map +1 -0
  99. package/dist/chunk-p-Tt_Lwz.js +14 -0
  100. package/dist/chunk-p-Tt_Lwz.js.map +1 -0
  101. package/dist/engines/index.cjs +2046 -3401
  102. package/dist/engines/index.cjs.map +1 -1
  103. package/dist/engines/index.d.cts +1510 -1550
  104. package/dist/engines/index.d.ts +1510 -1550
  105. package/dist/engines/index.js +2039 -3380
  106. package/dist/engines/index.js.map +1 -1
  107. package/dist/handlers/index.cjs +47 -93
  108. package/dist/handlers/index.cjs.map +1 -1
  109. package/dist/handlers/index.d.cts +61 -103
  110. package/dist/handlers/index.d.ts +61 -103
  111. package/dist/handlers/index.js +27 -36
  112. package/dist/handlers/index.js.map +1 -1
  113. package/dist/index.cjs +3347 -4398
  114. package/dist/index.cjs.map +1 -1
  115. package/dist/index.d.cts +8 -7297
  116. package/dist/index.d.ts +8 -7297
  117. package/dist/index.js +2997 -3187
  118. package/dist/index.js.map +1 -1
  119. package/dist/plugins/index.cjs +482 -949
  120. package/dist/plugins/index.cjs.map +1 -1
  121. package/dist/plugins/index.d.cts +44 -61
  122. package/dist/plugins/index.d.ts +44 -61
  123. package/dist/plugins/index.js +471 -915
  124. package/dist/plugins/index.js.map +1 -1
  125. package/dist/seams/index.cjs +77 -140
  126. package/dist/seams/index.cjs.map +1 -1
  127. package/dist/seams/index.d.cts +125 -158
  128. package/dist/seams/index.d.ts +125 -158
  129. package/dist/seams/index.js +41 -71
  130. package/dist/seams/index.js.map +1 -1
  131. package/dist/strings/fr/index.cjs +2130 -2116
  132. package/dist/strings/fr/index.cjs.map +1 -1
  133. package/dist/strings/fr/index.d.cts +3 -5
  134. package/dist/strings/fr/index.d.ts +3 -5
  135. package/dist/strings/fr/index.js +2125 -2114
  136. package/dist/strings/fr/index.js.map +1 -1
  137. package/dist/strings/index.cjs +2331 -2625
  138. package/dist/strings/index.cjs.map +1 -1
  139. package/dist/strings/index.d.cts +3 -731
  140. package/dist/strings/index.d.ts +3 -731
  141. package/dist/strings/index.js +2324 -2615
  142. package/dist/strings/index.js.map +1 -1
  143. package/dist/testing/index.cjs +214 -276
  144. package/dist/testing/index.cjs.map +1 -1
  145. package/dist/testing/index.d.cts +61 -121
  146. package/dist/testing/index.d.ts +61 -121
  147. package/dist/testing/index.js +208 -273
  148. package/dist/testing/index.js.map +1 -1
  149. package/dist/time/index.cjs +23 -23
  150. package/dist/time/index.cjs.map +1 -1
  151. package/dist/time/index.d.cts +5 -7
  152. package/dist/time/index.d.ts +5 -7
  153. package/dist/time/index.js +18 -21
  154. package/dist/time/index.js.map +1 -1
  155. package/package.json +14 -15
  156. package/src/agent/rules/stateDelta.ts +1 -0
  157. package/src/agent/stores/agentThreads.ts +1 -4
  158. package/src/bus/rules/bus.ts +1 -2
  159. package/src/bus/rules/defineRegistry.ts +3 -5
  160. package/src/bus/rules/types.ts +6 -7
  161. package/src/chrome/stores/uiStore.ts +4 -2
  162. package/src/embed/rules/fieldDependencies.ts +2 -0
  163. package/src/embed/rules/safetyRules.ts +2 -0
  164. package/src/embed/rules/tableCode.ts +4 -3
  165. package/src/index.ts +6 -27
  166. package/src/itinerary/rules/import.ts +6 -8
  167. package/src/plugins/contracts/plugin.ts +4 -2
  168. package/src/seams/rules/formatters.ts +5 -3
  169. package/src/testing/index.ts +1 -5
  170. package/src/viewer/rules/platformViewer.ts +1 -0
  171. package/dist/bus-BwiNiXdH.d.ts +0 -514
  172. package/dist/bus-DzmhPwdK.d.cts +0 -514
  173. package/dist/chainModel-B23pEP_1.d.cts +0 -127
  174. package/dist/chainModel-B23pEP_1.d.ts +0 -127
  175. package/dist/chunk-2HFY7ETU.js +0 -5721
  176. package/dist/chunk-2HFY7ETU.js.map +0 -1
  177. package/dist/chunk-355TOXSB.js +0 -72
  178. package/dist/chunk-355TOXSB.js.map +0 -1
  179. package/dist/chunk-4ZCUZVSV.js +0 -10275
  180. package/dist/chunk-4ZCUZVSV.js.map +0 -1
  181. package/dist/chunk-6HEKY3NF.js +0 -95
  182. package/dist/chunk-6HEKY3NF.js.map +0 -1
  183. package/dist/chunk-7GFLGGBX.cjs +0 -8
  184. package/dist/chunk-7GFLGGBX.cjs.map +0 -1
  185. package/dist/chunk-7NBRCENN.cjs +0 -19
  186. package/dist/chunk-7NBRCENN.cjs.map +0 -1
  187. package/dist/chunk-AF5GCXE3.js +0 -8
  188. package/dist/chunk-AF5GCXE3.js.map +0 -1
  189. package/dist/chunk-CJDIFRGZ.cjs +0 -2005
  190. package/dist/chunk-CJDIFRGZ.cjs.map +0 -1
  191. package/dist/chunk-CNPZY7N3.js +0 -349
  192. package/dist/chunk-CNPZY7N3.js.map +0 -1
  193. package/dist/chunk-DZJHTWSF.cjs +0 -45
  194. package/dist/chunk-DZJHTWSF.cjs.map +0 -1
  195. package/dist/chunk-EABIHHWA.js +0 -42
  196. package/dist/chunk-EABIHHWA.js.map +0 -1
  197. package/dist/chunk-EKZWV6RS.cjs +0 -415
  198. package/dist/chunk-EKZWV6RS.cjs.map +0 -1
  199. package/dist/chunk-EOKRXXAC.cjs +0 -24
  200. package/dist/chunk-EOKRXXAC.cjs.map +0 -1
  201. package/dist/chunk-F73W2ZTJ.js +0 -1126
  202. package/dist/chunk-F73W2ZTJ.js.map +0 -1
  203. package/dist/chunk-H4DVOZ5O.js +0 -1897
  204. package/dist/chunk-H4DVOZ5O.js.map +0 -1
  205. package/dist/chunk-HI52PBFT.cjs +0 -10314
  206. package/dist/chunk-HI52PBFT.cjs.map +0 -1
  207. package/dist/chunk-IDBXFBLG.cjs +0 -1225
  208. package/dist/chunk-IDBXFBLG.cjs.map +0 -1
  209. package/dist/chunk-LBWTJZUJ.js +0 -297
  210. package/dist/chunk-LBWTJZUJ.js.map +0 -1
  211. package/dist/chunk-NCLA6DKD.cjs +0 -310
  212. package/dist/chunk-NCLA6DKD.cjs.map +0 -1
  213. package/dist/chunk-O4MC5DPD.js +0 -19
  214. package/dist/chunk-O4MC5DPD.js.map +0 -1
  215. package/dist/chunk-OP37FKW6.cjs +0 -98
  216. package/dist/chunk-OP37FKW6.cjs.map +0 -1
  217. package/dist/chunk-OQSYFH3Z.cjs +0 -5945
  218. package/dist/chunk-OQSYFH3Z.cjs.map +0 -1
  219. package/dist/chunk-PACIO4NS.cjs +0 -26
  220. package/dist/chunk-PACIO4NS.cjs.map +0 -1
  221. package/dist/chunk-PSZ2R3TC.cjs +0 -75
  222. package/dist/chunk-PSZ2R3TC.cjs.map +0 -1
  223. package/dist/chunk-QFO5CZG2.cjs +0 -136
  224. package/dist/chunk-QFO5CZG2.cjs.map +0 -1
  225. package/dist/chunk-QL63MUEW.cjs +0 -140
  226. package/dist/chunk-QL63MUEW.cjs.map +0 -1
  227. package/dist/chunk-RFUPPVZO.js +0 -17
  228. package/dist/chunk-RFUPPVZO.js.map +0 -1
  229. package/dist/chunk-RPG2LWMP.js +0 -23
  230. package/dist/chunk-RPG2LWMP.js.map +0 -1
  231. package/dist/chunk-TIBXK6B7.cjs +0 -12
  232. package/dist/chunk-TIBXK6B7.cjs.map +0 -1
  233. package/dist/chunk-UU65VNEV.js +0 -381
  234. package/dist/chunk-UU65VNEV.js.map +0 -1
  235. package/dist/chunk-VGX6TR2I.js +0 -209
  236. package/dist/chunk-VGX6TR2I.js.map +0 -1
  237. package/dist/chunk-WUTDDBVP.js +0 -130
  238. package/dist/chunk-WUTDDBVP.js.map +0 -1
  239. package/dist/chunk-WVQQLKCI.cjs +0 -224
  240. package/dist/chunk-WVQQLKCI.cjs.map +0 -1
  241. package/dist/chunk-WZYXG3SE.js +0 -111
  242. package/dist/chunk-WZYXG3SE.js.map +0 -1
  243. package/dist/chunk-XDI2X3KE.js +0 -6
  244. package/dist/chunk-XDI2X3KE.js.map +0 -1
  245. package/dist/chunk-XKHLRIC7.cjs +0 -381
  246. package/dist/chunk-XKHLRIC7.cjs.map +0 -1
  247. package/dist/context-DNtd2WUv.d.cts +0 -11666
  248. package/dist/context-DgB72Bur.d.ts +0 -11666
  249. package/dist/en-Bu4Ti9Ev.d.cts +0 -2315
  250. package/dist/en-Bu4Ti9Ev.d.ts +0 -2315
  251. package/dist/shareLink-B6hlt942.d.ts +0 -144
  252. package/dist/shareLink-C7rIMb7x.d.ts +0 -527
  253. package/dist/shareLink-CnTxxXjp.d.cts +0 -144
  254. package/dist/shareLink-DyZVYH2V.d.cts +0 -527
  255. package/dist/studioPlugin-C3C7VjMy.d.ts +0 -847
  256. package/dist/studioPlugin-Cf3OBNUv.d.cts +0 -847
  257. package/dist/types-BzJRV6UI.d.cts +0 -845
  258. package/dist/types-BzJRV6UI.d.ts +0 -845
  259. package/dist/zoneForm-CdYNtnnA.d.cts +0 -320
  260. package/dist/zoneForm-mG85yt5e.d.ts +0 -320
@@ -1,1897 +0,0 @@
1
- import { POI_GROUP_IDS, DEFAULT_ENABLED_POI_GROUP_IDS, zoneEditInitialState, waypointEditInitialState, videoExportInitialState, segmentSplitInitialState, segmentGroupEditInitialState, roadAccessDialogInitialState, collectionsInitialState, collabInitialState, chromeInitialState, selectActiveEditEngine, selectedCandidate, agentHandoffTarget, projectOnSegment, segmentLengthMeters, SPLIT_MIN_END_DISTANCE_METERS, DEFAULT_TERRAIN, createZoneEditSlice, createWaypointEditSlice, createVideoExportSlice, createSegmentSplitSlice, createSegmentGroupEditSlice, createRoadAccessDialogSlice, createCollectionsSlice, createCollabSlice, createChromeSlice, studioToolContracts, SUGGESTION_MAX_KEPT } from './chunk-2HFY7ETU.js';
2
- import { isZoneGeometryDirty } from './chunk-UU65VNEV.js';
3
- import { segmentEditInitialState, itineraryInitialState, isSegmentDraftDirty, createSegmentEditSlice, createItinerarySlice } from './chunk-F73W2ZTJ.js';
4
- import { notifyListeners } from './chunk-RPG2LWMP.js';
5
- import { studioSeamAbsences } from './chunk-VGX6TR2I.js';
6
- import { messageOf, failureFromThrown, lockHolderOf, memberOf } from './chunk-WUTDDBVP.js';
7
- import * as z2 from 'zod';
8
- import { MountayaElementsError } from '@mountaya/elements/errors';
9
- import { isEnrichmentCategory, findOverlay, POIS_OVERLAY_SLUG } from '@mountaya/elements/layers';
10
- export { POIS_OVERLAY_SLUG } from '@mountaya/elements/layers';
11
- import { BASEMAP_ATTRIBUTION } from '@mountaya/elements/style';
12
- import { createStore } from 'zustand/vanilla';
13
- import { DIRECTIONS_VIA_MAX, extractVias } from '@mountaya/elements/geo';
14
- import { defaultUnits } from '@mountaya/elements/profile';
15
-
16
- var nameKeyedSchemaKeys = /* @__PURE__ */ new Set([
17
- "$defs",
18
- "patternProperties",
19
- "properties"
20
- ]);
21
- var valueKeyedSchemaKeys = /* @__PURE__ */ new Set(["const", "default", "enum", "examples"]);
22
- var kindsJsonCannotCarry = /* @__PURE__ */ new Set([
23
- "bigint",
24
- "date",
25
- "map",
26
- "nan",
27
- "set",
28
- "symbol"
29
- ]);
30
- var UNION_KEYWORDS = ["anyOf", "oneOf"];
31
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
32
- var isModelInert = (key, entry) => key === "$schema" || key === "additionalProperties" && (typeof entry === "boolean" || isRecord(entry) && Object.keys(entry).length === 0);
33
- var acceptsNothing = (schema) => isRecord(schema) && isRecord(schema.not) && Object.keys(schema.not).length === 0;
34
- var withoutUnsendableArms = (schema) => {
35
- for (const keyword of UNION_KEYWORDS) {
36
- const arms = schema[keyword];
37
- if (!Array.isArray(arms)) {
38
- continue;
39
- }
40
- const kept = arms.filter((arm) => !acceptsNothing(arm));
41
- if (kept.length === arms.length) {
42
- continue;
43
- }
44
- const beside = Object.entries(schema).filter(([key]) => key !== keyword);
45
- const [only] = kept;
46
- if (kept.length === 0) {
47
- return { ...Object.fromEntries(beside), not: {} };
48
- }
49
- if (kept.length === 1 && isRecord(only)) {
50
- return { ...only, ...Object.fromEntries(beside) };
51
- }
52
- return Object.fromEntries(
53
- Object.entries(schema).map(([key, entry]) => [key, key === keyword ? kept : entry])
54
- );
55
- }
56
- return schema;
57
- };
58
- var slim = (value) => {
59
- if (Array.isArray(value)) {
60
- return value.map(slim);
61
- }
62
- if (!isRecord(value)) {
63
- return value;
64
- }
65
- const slimmed = {};
66
- for (const [key, entry] of Object.entries(value)) {
67
- if (isModelInert(key, entry)) {
68
- continue;
69
- }
70
- if (valueKeyedSchemaKeys.has(key)) {
71
- slimmed[key] = entry;
72
- } else if (nameKeyedSchemaKeys.has(key) && isRecord(entry)) {
73
- slimmed[key] = Object.fromEntries(
74
- Object.entries(entry).map(([name, schema]) => [name, slim(schema)])
75
- );
76
- } else {
77
- slimmed[key] = slim(entry);
78
- }
79
- }
80
- return withoutUnsendableArms(slimmed);
81
- };
82
- var renderedSchemas = /* @__PURE__ */ new WeakMap();
83
- var renderInputSchema = (input) => {
84
- const cached = renderedSchemas.get(input);
85
- if (cached) {
86
- return cached;
87
- }
88
- const rendered = slim(
89
- z2.toJSONSchema(input, {
90
- io: "input",
91
- override: ({ jsonSchema, zodSchema }) => {
92
- const { def } = zodSchema._zod;
93
- const coerced = "coerce" in def && def.coerce === true;
94
- if (kindsJsonCannotCarry.has(def.type) && !coerced) {
95
- jsonSchema.not = {};
96
- }
97
- },
98
- unrepresentable: "any"
99
- })
100
- );
101
- renderedSchemas.set(input, rendered);
102
- return rendered;
103
- };
104
-
105
- // src/bus/rules/invalidInput.ts
106
- var MAX_LISTED_PARAMETERS = 8;
107
- var MAX_LISTED_ENUM_VALUES = 12;
108
- var MAX_LISTED_SHAPES = 6;
109
- var isSchemaObject = (schema) => typeof schema === "object" && schema !== null;
110
- var ROOT_POINTER = "#";
111
- var DEFINITION_POINTER = "#/$defs/";
112
- var targetOf = (pointer, root) => {
113
- if (pointer === ROOT_POINTER) {
114
- return root;
115
- }
116
- if (!pointer.startsWith(DEFINITION_POINTER) || root.$defs === void 0) {
117
- return void 0;
118
- }
119
- const name = pointer.slice(DEFINITION_POINTER.length);
120
- return Object.hasOwn(root.$defs, name) ? root.$defs[name] : void 0;
121
- };
122
- var typeWord = (schema) => {
123
- if (Array.isArray(schema.type)) {
124
- return schema.type.join(" | ");
125
- }
126
- return typeof schema.type === "string" ? schema.type : "any";
127
- };
128
- var describeType = (schema, scope) => {
129
- if (!isSchemaObject(schema)) {
130
- return "any";
131
- }
132
- if (typeof schema.$ref === "string") {
133
- const target = targetOf(schema.$ref, scope.root);
134
- if (target === void 0) {
135
- return "any";
136
- }
137
- return scope.reading.includes(schema.$ref) ? typeWord(target) : describeType(target, { reading: [...scope.reading, schema.$ref], root: scope.root });
138
- }
139
- if (acceptsNothing(schema)) {
140
- return "no value a JSON call can carry";
141
- }
142
- if (schema.const !== void 0) {
143
- return JSON.stringify(schema.const);
144
- }
145
- if (Array.isArray(schema.enum) && schema.enum.length > 0) {
146
- const values = schema.enum.slice(0, MAX_LISTED_ENUM_VALUES).map((value) => JSON.stringify(value));
147
- const rest = schema.enum.length - values.length;
148
- return `one of ${values.join(" | ")}${rest > 0 ? ` (+${rest} more)` : ""}`;
149
- }
150
- const branches = schema.anyOf ?? schema.oneOf;
151
- if (Array.isArray(branches) && branches.length > 0) {
152
- return branches.map((branch) => describeType(branch, scope)).join(" | ");
153
- }
154
- if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
155
- return [...new Set(schema.allOf.map((part) => describeType(part, scope)))].join(" & ");
156
- }
157
- if (schema.type === "array") {
158
- return Array.isArray(schema.prefixItems) ? `[${schema.prefixItems.map((item) => describeType(item, scope)).join(", ")}]` : `array of ${describeType(Array.isArray(schema.items) ? void 0 : schema.items, scope)}`;
159
- }
160
- if (schema.type === "object" && schema.properties === void 0 && isSchemaObject(schema.additionalProperties)) {
161
- return `object of ${describeType(schema.additionalProperties, scope)}`;
162
- }
163
- return typeWord(schema);
164
- };
165
- var valueAt = (root, path) => {
166
- let current = root;
167
- try {
168
- for (const key of path) {
169
- if (current === null || typeof current !== "object") {
170
- return void 0;
171
- }
172
- current = current[key];
173
- }
174
- } catch {
175
- return void 0;
176
- }
177
- return current;
178
- };
179
- var pathOf = (path) => path.length > 0 ? path.map((key) => String(key)).join(".") : "(root)";
180
- var typeName = (value) => {
181
- if (Array.isArray(value)) {
182
- return "array";
183
- }
184
- return value === null ? "null" : typeof value;
185
- };
186
- var describeIssue = (issue, rawInput) => {
187
- const path = pathOf(issue.path);
188
- if (issue.code === "invalid_type") {
189
- const received = valueAt(rawInput, issue.path);
190
- return received === void 0 ? `${path} is required and was not supplied` : `${path} must be ${issue.expected}, not ${typeName(received)}`;
191
- }
192
- return `${path}: ${issue.message}`;
193
- };
194
- var describeParameters = (shape, root) => {
195
- const properties = Object.entries(shape.properties ?? {});
196
- if (properties.length === 0) {
197
- return null;
198
- }
199
- const scope = { reading: [ROOT_POINTER], root };
200
- const required = new Set(Array.isArray(shape.required) ? shape.required : []);
201
- const listed = properties.slice(0, MAX_LISTED_PARAMETERS);
202
- const accepted = listed.map(
203
- ([key, value]) => `${key} (${describeType(value, scope)}${required.has(key) ? ", required" : ", optional"})`
204
- ).join(", ");
205
- const omitted = properties.length - listed.length;
206
- return `${accepted}${omitted > 0 ? `, and ${omitted} more` : ""}`;
207
- };
208
- var partsAsOneShape = (parts) => {
209
- const properties = {};
210
- const required = /* @__PURE__ */ new Set();
211
- for (const shapes of parts) {
212
- const [only] = shapes;
213
- if (shapes.length !== 1 || only === void 0) {
214
- return null;
215
- }
216
- Object.assign(properties, only.properties);
217
- for (const name of Array.isArray(only.required) ? only.required : []) {
218
- required.add(name);
219
- }
220
- }
221
- return { properties, required: [...required], type: "object" };
222
- };
223
- var shapesOf = (schema, scope) => {
224
- if (typeof schema.$ref === "string") {
225
- const target = targetOf(schema.$ref, scope.root);
226
- if (target === void 0) {
227
- return [schema];
228
- }
229
- return scope.reading.includes(schema.$ref) ? [] : shapesOf(target, { reading: [...scope.reading, schema.$ref], root: scope.root });
230
- }
231
- const branches = schema.oneOf ?? schema.anyOf;
232
- if (Array.isArray(branches)) {
233
- return branches.flatMap((branch) => isSchemaObject(branch) ? shapesOf(branch, scope) : []);
234
- }
235
- if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
236
- return [partsAsOneShape(schema.allOf.map((part) => shapesOf(part, scope))) ?? schema];
237
- }
238
- return [schema];
239
- };
240
- var selectorOf = (shape, rawInput) => {
241
- const pinned = Object.entries(shape.properties ?? {}).flatMap(
242
- ([key, value]) => isSchemaObject(value) && value.const !== void 0 ? [{ key, literal: value.const }] : []
243
- );
244
- if (pinned.length === 0 || pinned.some(({ key, literal }) => valueAt(rawInput, [key]) !== literal)) {
245
- return null;
246
- }
247
- return pinned.map(({ key, literal }) => `${key} is ${JSON.stringify(literal)}`).join(" and ");
248
- };
249
- var describeAccepted = (schema, rawInput) => {
250
- const shapes = shapesOf(schema, { reading: [ROOT_POINTER], root: schema });
251
- const parametersOf = (shape) => describeParameters(shape, schema);
252
- const [only] = shapes;
253
- if (shapes.length === 1 && only !== void 0) {
254
- const parameters = parametersOf(only);
255
- return parameters === null ? null : `Accepted parameters: ${parameters}.`;
256
- }
257
- if (shapes.every((shape) => parametersOf(shape) === null)) {
258
- return null;
259
- }
260
- const selected = shapes.flatMap((shape) => {
261
- const selector = selectorOf(shape, rawInput);
262
- return selector === null ? [] : [{ selector, shape }];
263
- });
264
- const [chosen] = selected;
265
- if (selected.length === 1 && chosen !== void 0) {
266
- return `Accepted parameters when ${chosen.selector}: ${parametersOf(chosen.shape) ?? "none"}.`;
267
- }
268
- const listed = shapes.slice(0, MAX_LISTED_SHAPES).map((shape, index) => `[${index + 1}] ${parametersOf(shape) ?? "no parameters"}`).join("; ");
269
- const omitted = shapes.length - Math.min(shapes.length, MAX_LISTED_SHAPES);
270
- return `Accepted parameters, in one of these shapes: ${listed}${omitted > 0 ? `; and ${omitted} more` : ""}.`;
271
- };
272
- var describeRejection = (name, input, error, rawInput) => {
273
- const problems = error.issues.map((issue) => describeIssue(issue, rawInput)).join("; ");
274
- let schema;
275
- try {
276
- schema = renderInputSchema(input);
277
- } catch {
278
- return `invalid input for ${name}: ${problems}`;
279
- }
280
- const accepted = describeAccepted(schema, rawInput);
281
- if (accepted === null) {
282
- return `invalid input for ${name}: ${problems}. It takes no parameters.`;
283
- }
284
- return `invalid input for ${name}: ${problems}. ${accepted} Use exactly these names, and send values as their stated types: a number is 12000, not "12000".`;
285
- };
286
- var describeInvalidInput = (name, input, error, rawInput) => {
287
- try {
288
- return describeRejection(name, input, error, rawInput);
289
- } catch {
290
- return `invalid input for ${name}`;
291
- }
292
- };
293
- var toolCapabilitySchema = z2.enum(["authenticated", "editor"]);
294
- var confirmationToneSchema = z2.enum(["affirmative", "cautionary", "destructive"]);
295
- var toolConfirmationSchema = z2.object({
296
- acknowledgeLabel: z2.string().optional(),
297
- confirmLabel: z2.string().optional(),
298
- descriptionLabel: z2.string().optional(),
299
- titleLabel: z2.string().optional(),
300
- tone: confirmationToneSchema.optional()
301
- });
302
- var toolErrorCodes = {
303
- canceled: "canceled",
304
- "capability-denied": "capability-denied",
305
- "collab-locked": "collab-locked",
306
- "confirmation-denied": "confirmation-denied",
307
- "confirmation-timeout": "confirmation-timeout",
308
- conflict: "conflict",
309
- "draft-open": "draft-open",
310
- "edit-in-progress": "edit-in-progress",
311
- forbidden: "forbidden",
312
- internal: "internal",
313
- "invalid-input": "invalid-input",
314
- "limit-reached": "limit-reached",
315
- "no-api": "no-api",
316
- "no-map": "no-map",
317
- "no-session": "no-session",
318
- "not-found": "not-found",
319
- "rate-limited": "rate-limited",
320
- "split-on-end": "split-on-end",
321
- "split-too-far": "split-too-far",
322
- timeout: "timeout",
323
- unavailable: "unavailable",
324
- "unknown-tool": "unknown-tool",
325
- "upgrade-required": "upgrade-required"
326
- };
327
- var toolErrorCodeSchema = z2.enum(toolErrorCodes);
328
- var resolveConfirmationValues = (tool, ctx, input) => {
329
- if (!tool.confirmationValues) {
330
- return void 0;
331
- }
332
- try {
333
- return tool.confirmationValues(ctx, input);
334
- } catch {
335
- return void 0;
336
- }
337
- };
338
- var askConfirmation = async (tool, ctx, input) => {
339
- if (!ctx.confirm) {
340
- return false;
341
- }
342
- try {
343
- return await ctx.confirm({
344
- acknowledge: tool.confirmation,
345
- confirmLabel: tool.confirmation?.confirmLabel,
346
- description: tool.description,
347
- descriptionLabel: tool.confirmation?.descriptionLabel,
348
- input,
349
- name: tool.name,
350
- titleLabel: tool.confirmation?.titleLabel,
351
- tone: tool.confirmation?.tone,
352
- values: resolveConfirmationValues(tool, ctx, input)
353
- });
354
- } catch {
355
- return false;
356
- }
357
- };
358
- var isToolFailure = (value) => typeof value === "object" && value !== null && "ok" in value && value.ok === false && "error" in value && typeof value.error === "string";
359
- var refusalBeforeAsking = (tool, ctx, input, recognizers) => {
360
- if (!tool.precondition) {
361
- return null;
362
- }
363
- try {
364
- const answered = tool.precondition(ctx, input);
365
- if (answered === null || answered === void 0) {
366
- return null;
367
- }
368
- if (isToolFailure(answered)) {
369
- return answered;
370
- }
371
- } catch (err) {
372
- return failureFromThrown(err, recognizers);
373
- }
374
- return {
375
- code: "internal",
376
- error: `the precondition of ${tool.name} answered neither a refusal nor null`,
377
- ok: false
378
- };
379
- };
380
- var playbookDescriptions = (playbook) => new Map((playbook ?? []).map((entry) => [entry.id, entry.description]));
381
- var playbookReadOnly = (playbook) => new Set((playbook ?? []).filter((entry) => entry.kind === "read").map((entry) => entry.id));
382
- var ToolBus = class {
383
- observers = /* @__PURE__ */ new Set();
384
- tools = /* @__PURE__ */ new Map();
385
- /** The model-facing description per tool name, empty when the host supplied no playbook. */
386
- descriptions;
387
- /** The tools a playbook classifies as reads. Absent means "may mutate", the safe default. */
388
- readOnly;
389
- /** The host's own throw classifiers, asked before the generic status table. */
390
- recognizers;
391
- /** The vendor segments whose names {@link unregister} refuses to take back. */
392
- reserved;
393
- /**
394
- * dispatcher is this bus AS the dispatch surface: two methods, and nothing else on the object.
395
- *
396
- * A context's `bus` is typed {@link ToolBusDispatch}, and handing it the whole class would
397
- * make that narrowing a claim the runtime does not keep. The gap is only visible to code that
398
- * does not go through the types (a tool written in plain JavaScript, a handler that cast), and
399
- * those are exactly the callers a narrowed type protects the bus from. Registering,
400
- * unregistering and observing are the OWNER's verbs; a handler chaining into another verb
401
- * needs `dispatch` and nothing more, so it is given nothing more.
402
- *
403
- * Reaching for one of the others through here is a `TypeError` at the call site rather than a
404
- * silent success, which is the difference that matters: a plugin that took a tool off the bus
405
- * would break the studio for the rest of the session with nothing anywhere saying why.
406
- *
407
- * One object per bus, built at construction, so the identity a context carries is stable for
408
- * the bus's life and a memo keyed on `ctx.bus` never churns.
409
- */
410
- dispatcher;
411
- constructor(options = {}) {
412
- this.descriptions = playbookDescriptions(options.playbook);
413
- this.readOnly = playbookReadOnly(options.playbook);
414
- this.recognizers = options.recognizers ?? [];
415
- this.reserved = new Set(options.reserved ?? []);
416
- this.dispatcher = {
417
- dispatch: (ctx, name, rawInput) => this.dispatch(ctx, name, rawInput),
418
- dispatchUnsafe: (ctx, name, rawInput) => this.dispatchUnsafe(ctx, name, rawInput)
419
- };
420
- }
421
- /**
422
- * register adds a tool to the bus. A destructive tool's confirmation policy is parsed against
423
- * toolConfirmationSchema at registration time, so an invalid policy (a typo, a structural
424
- * drift) fails at app startup, not at the first dispatch.
425
- *
426
- * @throws MountayaElementsError when the bus holds a tool under the name already: a name is
427
- * the stable public API, so a replacement is never silent. The message says how to replace
428
- * it: through {@link ToolBus.unregister} first, or, under a `reserved` segment that
429
- * unregister keeps, through the handlers the bus is built with.
430
- * @throws MountayaElementsError when a destructive tool's confirmation policy fails
431
- * toolConfirmationSchema, with the schema's own message.
432
- */
433
- register(tool) {
434
- if (this.tools.has(tool.name)) {
435
- const segment = tool.name.split(".")[0] ?? "";
436
- throw new MountayaElementsError(
437
- this.reserved.has(segment) ? `tool already registered: ${tool.name}. Its "${segment}" segment is reserved on this bus, so unregister keeps it: hand the replacement to the handlers the bus is built with (overrideStudioHandler replaces one studio verb).` : `tool already registered: ${tool.name}. Take it off with unregister("${tool.name}"), then register the replacement.`
438
- );
439
- }
440
- if (tool.requiresConfirmation && tool.confirmation !== void 0) {
441
- const parsed = toolConfirmationSchema.safeParse(tool.confirmation);
442
- if (!parsed.success) {
443
- throw new MountayaElementsError(
444
- `tool ${tool.name} carries an invalid confirmation policy: ${parsed.error.message}`
445
- );
446
- }
447
- }
448
- this.tools.set(tool.name, tool);
449
- }
450
- /**
451
- * registerAll adds every tool in a registry, in the registry's own key order.
452
- *
453
- * A registry (from `defineRegistry`, from `studioRegistry`, or hand-written) is the unit
454
- * tools arrive in, so registering one is one call rather than a loop every consumer writes
455
- * identically. The values are what is registered; the keys are pinned to each tool's `name`
456
- * at the type level by whichever builder produced the record, and are not re-read here.
457
- *
458
- * Not atomic, deliberately. `register` throws on a duplicate name, and a partial registry on
459
- * a thrown bus is the correct outcome: registration happens once at startup, the throw is
460
- * fatal there, and unwinding would only hide which tool collided behind a bus that looks
461
- * empty.
462
- *
463
- * @throws MountayaElementsError when a tool's name is held already, as {@link register} states.
464
- */
465
- registerAll(registry) {
466
- for (const tool of Object.values(registry)) {
467
- this.register(tool);
468
- }
469
- }
470
- /**
471
- * registered returns every tool currently in the bus, in registration order.
472
- * Read-only access so a suite can assert structural properties (Zod schema present,
473
- * capability canonical, no name collision, confirmation policy on destructive tools)
474
- * without reaching into the private registry. The returned array is a fresh copy;
475
- * mutating it does not affect the bus.
476
- */
477
- registered() {
478
- return [...this.tools.values()];
479
- }
480
- /**
481
- * unregister removes a tool by name, reporting whether one was there.
482
- *
483
- * It REPORTS rather than throws, which is the opposite of {@link register} and is the
484
- * opposite case: removing a name nobody holds leaves the bus in exactly the state the caller
485
- * asked for, while registering a name somebody already holds cannot leave it in the state
486
- * BOTH callers asked for. A boolean is what a caller doing bookkeeping wants and what a
487
- * caller cleaning up can ignore.
488
- *
489
- * It exists for the tools a PLUGIN declares, which arrive and leave with the plugin:
490
- * `@mountaya/studio/plugins` registers them on install and takes them back on uninstall.
491
- * Without it an uninstalled plugin's verbs would stay in the model's manifest for the rest of
492
- * the session, and re-installing the same plugin would throw on its own names.
493
- *
494
- * There is nothing to invalidate: `manifest()` is rebuilt per call from this map, so the
495
- * next one already omits the name. A dispatch to it answers `unknown-tool`, which is what a
496
- * name that was never registered answers.
497
- *
498
- * **It refuses a name under a RESERVED vendor segment**, which the host names at construction:
499
- * the studio passes the segments `plugins/contracts/ids` refuses a plugin id for.
500
- *
501
- * It is the SECOND of two answers, and the smaller one. The first is {@link dispatcher}: a
502
- * context's `bus` carries the dispatch surface alone, so code reached through one (a plugin's
503
- * `run`, a chained handler) cannot name this method at all, in TypeScript or out of it. What
504
- * is left holding a concrete bus is its owner: the host that built it, and anything they hand
505
- * it to. This is for THEM, and it is the ordinary mistake it catches (a cleanup unregistering
506
- * the wrong name, a line copy-pasted out of a teardown) which would otherwise leave the studio
507
- * silently unable to save for the rest of the session.
508
- *
509
- * Neither is a sandbox, and neither is trying to be. A plugin runs in the host's own realm: it
510
- * can write the store and dispatch every verb whatever these two do. The boundary that matters
511
- * is still the host's decision to install it; what these buy is that an ACCIDENT fails loudly
512
- * and at the call site instead of quietly and hours later.
513
- *
514
- * A vendor RULE rather than a list of protected names, for the reason `ids.ts` is one: a list
515
- * is right the day it is written and wrong the day the next tool ships. It is also why the
516
- * guard is total where a playbook-derived one would not be: a playbook describes the tools a
517
- * model chooses between, which is a subset of the tools a studio registers.
518
- *
519
- * It costs a HOST nothing: it exists for a plugin's uninstall, and a host disabling one of the
520
- * studio's own features does it through `capabilities` or the studio's config rather than by
521
- * editing the bus.
522
- *
523
- * @returns true when a tool was registered under `name` and is removed; false when none was,
524
- * or when `name` sits under a reserved segment and is kept.
525
- */
526
- unregister(name) {
527
- if (this.reserved.has(name.split(".")[0] ?? "")) {
528
- return false;
529
- }
530
- return this.tools.delete(name);
531
- }
532
- /**
533
- * observe registers a telemetry observer that receives one event per
534
- * dispatch (start to result). Returns an unobserve fn that detaches it.
535
- *
536
- * An observer that throws is answered as {@link ToolDispatchObserver} states. The
537
- * observers held when a dispatch reports are the ones told: one that joins or
538
- * detaches while being told changes that round for nobody. One that mutates the
539
- * bus from inside the callback is on its own.
540
- */
541
- observe(observer) {
542
- this.observers.add(observer);
543
- return () => {
544
- this.observers.delete(observer);
545
- };
546
- }
547
- emit(event) {
548
- notifyListeners(this.observers, event);
549
- }
550
- /**
551
- * refuseInput answers an `invalid-input` refusal with `error` as its narration, and reports
552
- * it to the observers first. One path for a schema that failed the input and one that threw
553
- * while reading it, so both read the same to a caller and to telemetry.
554
- */
555
- refuseInput(capability, name, start, error) {
556
- this.emit({
557
- capability,
558
- errorClass: "invalid-input",
559
- errorCode: "invalid-input",
560
- errorMessage: error,
561
- latencyMs: performance.now() - start,
562
- name,
563
- ok: false
564
- });
565
- return { code: "invalid-input", error, ok: false };
566
- }
567
- /**
568
- * manifest returns the tools available for the given capability set, with
569
- * each input schema rendered as JSON Schema for the LLM. A tool marked
570
- * {@link Tool.agentHidden} is withheld here even when its capability is
571
- * granted: the model never sees a verb the system prompt forbids it to call
572
- * (an edit-session lifecycle verb, a step of a UI chain), while the
573
- * same tool stays fully dispatchable for a human click or an internal tool
574
- * chain. Withholding it here is paired with {@link ToolBus.dispatchFromModel},
575
- * which refuses the same set, so a name the model invents is not merely
576
- * unlisted, it does not run. Each schema is rendered through
577
- * {@link renderInputSchema}, which also drops the keywords the model cannot act
578
- * on.
579
- *
580
- * `surface` narrows the result to a routed subset of tool names. It is
581
- * advisory over what the model can SEE and is never a gate: a tool left out of
582
- * the surface stays fully dispatchable by a human click and by an internal
583
- * tool chain, exactly as `agentHidden` behaves. Omitting it yields every
584
- * permitted tool, which is what a caller with no router does.
585
- */
586
- manifest(capabilities, surface) {
587
- const entries = [];
588
- for (const tool of this.tools.values()) {
589
- if (!capabilities.has(tool.capability) || tool.agentHidden) {
590
- continue;
591
- }
592
- if (surface !== void 0 && !surface.has(tool.name)) {
593
- continue;
594
- }
595
- entries.push({
596
- capability: tool.capability,
597
- description: this.descriptions.get(tool.name) ?? tool.description,
598
- inputSchema: renderInputSchema(tool.input),
599
- name: tool.name,
600
- readOnly: this.readOnly.has(tool.name),
601
- requiresConfirmation: tool.requiresConfirmation ?? false
602
- });
603
- }
604
- return entries;
605
- }
606
- /**
607
- * dispatchUnsafe answers the first refusal in a fixed order and runs the
608
- * handler only past all of them: a name no tool is registered under, a
609
- * capability the context lacks, a raw input (e.g. LLM tool-call args) the
610
- * tool's Zod schema rejects, a refusal the tool's own {@link Tool.precondition}
611
- * gives, and, when the tool is marked
612
- * requiresConfirmation, a ctx.confirm that is declined, absent or failed.
613
- * The bus owns this gate for both human clicks and agent-issued tools; if a
614
- * destructive tool reaches dispatch with no confirm callback in context, it
615
- * is denied (fail-safe). Never trusts unvalidated input.
616
- *
617
- * It always resolves to a structured ToolResult and never rejects: each gate
618
- * returns a failure carrying its machine-readable code (unknown-tool,
619
- * capability-denied, invalid-input, confirmation-denied), and a handler that
620
- * throws is converted to a structured failure (its classified code, or
621
- * "internal") rather than re-thrown. A schema that throws while parsing answers
622
- * invalid-input, since the tool refused the input it was given, and a confirm
623
- * gate that throws answers confirmation-denied, since a question left unanswered
624
- * is not consent. Describing a failure never rejects either:
625
- * {@link failureFromThrown} and {@link describeInvalidInput} are total, so a
626
- * message that cannot be read or printed gives way to a plainer sentence and a
627
- * symbol in an issue path is printed. This is what makes the documented
628
- * "handlers never throw" contract true at the boundary: a caller awaiting a
629
- * dispatch branches on `ok` instead of wrapping the call in try/catch.
630
- *
631
- * "Unsafe" is a TYPE qualifier only: full runtime validation still applies (an
632
- * unregistered name and a schema-rejected input both fail here, structured).
633
- * It is the path for a dynamically-named dispatch (an agent routing an LLM
634
- * tool-call name, the embed bridge mapping a postMessage type, an
635
- * editing keyboard building a tool name from a family prefix) where the name
636
- * (and its input) is a runtime `string`/`unknown` rather than a literal the
637
- * compiler can match against `TInputs`. The typed {@link dispatch} wraps this
638
- * for the common case where the name is a known literal.
639
- */
640
- async dispatchUnsafe(ctx, name, rawInput) {
641
- const start = performance.now();
642
- const tool = this.tools.get(name);
643
- if (!tool) {
644
- this.emit({
645
- errorClass: "unknown-tool",
646
- errorCode: "unknown-tool",
647
- errorMessage: `unknown tool: ${name}`,
648
- latencyMs: performance.now() - start,
649
- name,
650
- ok: false
651
- });
652
- return { code: "unknown-tool", error: `unknown tool: ${name}`, ok: false };
653
- }
654
- if (!ctx.capabilities.has(tool.capability)) {
655
- this.emit({
656
- capability: tool.capability,
657
- errorClass: "capability-denied",
658
- errorCode: "capability-denied",
659
- errorMessage: `capability not granted: ${tool.capability}`,
660
- latencyMs: performance.now() - start,
661
- name,
662
- ok: false
663
- });
664
- return {
665
- code: "capability-denied",
666
- error: `capability not granted: ${tool.capability}`,
667
- ok: false
668
- };
669
- }
670
- let parsed;
671
- try {
672
- parsed = tool.input.safeParse(rawInput);
673
- } catch (err) {
674
- return this.refuseInput(
675
- tool.capability,
676
- name,
677
- start,
678
- `invalid input for ${name}: ${messageOf(err)}`
679
- );
680
- }
681
- if (!parsed.success) {
682
- return this.refuseInput(
683
- tool.capability,
684
- name,
685
- start,
686
- describeInvalidInput(name, tool.input, parsed.error, rawInput)
687
- );
688
- }
689
- const refused = refusalBeforeAsking(tool, ctx, parsed.data, this.recognizers);
690
- if (refused !== null) {
691
- this.emit({
692
- capability: tool.capability,
693
- errorClass: "handler-error",
694
- errorCode: refused.code,
695
- errorMessage: refused.error,
696
- latencyMs: performance.now() - start,
697
- name,
698
- ok: false
699
- });
700
- return refused;
701
- }
702
- if (tool.requiresConfirmation && !await askConfirmation(tool, ctx, parsed.data)) {
703
- this.emit({
704
- capability: tool.capability,
705
- errorClass: "confirmation-denied",
706
- errorCode: "confirmation-denied",
707
- errorMessage: `confirmation required, not granted: ${tool.name}`,
708
- latencyMs: performance.now() - start,
709
- name,
710
- ok: false
711
- });
712
- return {
713
- code: "confirmation-denied",
714
- error: `confirmation required, not granted: ${tool.name}`,
715
- ok: false
716
- };
717
- }
718
- try {
719
- const result = await tool.handler(ctx, parsed.data);
720
- this.emit({
721
- capability: tool.capability,
722
- errorClass: result.ok ? void 0 : "handler-error",
723
- errorCode: result.ok ? void 0 : result.code,
724
- errorMessage: result.ok ? void 0 : result.error,
725
- latencyMs: performance.now() - start,
726
- name,
727
- ok: result.ok
728
- });
729
- return result;
730
- } catch (err) {
731
- const failure = failureFromThrown(err, this.recognizers);
732
- this.emit({
733
- capability: tool.capability,
734
- errorClass: "handler-error",
735
- errorCode: failure.code,
736
- errorMessage: failure.error,
737
- latencyMs: performance.now() - start,
738
- name,
739
- ok: false
740
- });
741
- return failure;
742
- }
743
- }
744
- /**
745
- * dispatchFromModel is the entry point for a tool call the MODEL emitted. It is
746
- * the only dispatch that treats {@link Tool.agentHidden} as a gate rather than a
747
- * manifest filter: a name the model was never shown but produced anyway is
748
- * refused here, so the hidden set stops resting on the model not guessing it.
749
- *
750
- * It is a separate entry point rather than a branch inside dispatchUnsafe on
751
- * `ctx.origin`, because the trust boundary is the MODEL, not the origin tag. A
752
- * hidden tool used as an INTERNAL step (`studio.search.selectResult` lighting
753
- * its pick through `studio.search.highlight` and clearing the last one through
754
- * `studio.search.clearHighlight`) chains through ctx.bus with its caller's own
755
- * context and must keep working. Gating on origin would break exactly those
756
- * chains, and silently where a chain discards the chained result: the outer
757
- * tool would report success for a step that never ran. Keeping the gate on this seam makes that
758
- * failure mode unreachable instead of something each new handler must remember.
759
- *
760
- * The refusal is `forbidden`, not `capability-denied`: the context genuinely
761
- * holds the capability, and mis-stating that would mislead both the model's
762
- * recovery branch and the observer that reads the code.
763
- */
764
- async dispatchFromModel(ctx, name, rawInput) {
765
- const tool = this.tools.get(name);
766
- if (tool?.agentHidden) {
767
- const error = `tool not available to the agent: ${name}`;
768
- this.emit({
769
- capability: tool.capability,
770
- errorClass: "agent-hidden",
771
- errorCode: "forbidden",
772
- errorMessage: error,
773
- latencyMs: 0,
774
- name,
775
- ok: false
776
- });
777
- return { code: "forbidden", error, ok: false };
778
- }
779
- return this.dispatchUnsafe(ctx, name, rawInput);
780
- }
781
- /**
782
- * dispatch is the name-checked, input-checked entry point: the name must be a
783
- * key of this bus's `TInputs`, and the raw input must match that tool's
784
- * pre-parse shape, so a stray field or a wrong tool name is a compile error at
785
- * the call site rather than a silently-stripped field at runtime. It delegates
786
- * straight to {@link dispatchUnsafe}, which still runs the full Zod validation
787
- * the dispatch contract guarantees: the typing is a build-time guard layered
788
- * over the same runtime path, never a replacement for it. On a bus left at the
789
- * default `TInputs`, with {@link ToolDispatchRegistry} not augmented, there is no
790
- * key and this method takes no name: {@link dispatchUnsafe} is the entry point
791
- * there.
792
- *
793
- * It answers the {@link ToolResult} of the named verb's data, read from this bus's
794
- * `TOutputs`, and `data` as `unknown` for a name that map does not hold. Nothing
795
- * is parsed on the way out: what the handler returned is what the caller reads.
796
- */
797
- dispatch(ctx, name, rawInput) {
798
- return this.dispatchUnsafe(ctx, name, rawInput);
799
- }
800
- };
801
- var isStudioToolName = (name) => Object.hasOwn(studioToolContracts, name);
802
- var build = (builder, handlers) => {
803
- const entries = Object.entries(handlers).filter(([, entry]) => entry !== void 0);
804
- const unknown = entries.flatMap(([name]) => isStudioToolName(name) ? [] : [`"${name}"`]);
805
- if (unknown.length > 0) {
806
- throw new MountayaElementsError(
807
- `${builder}: no studio tool is named ${unknown.join(", ")}. A handler map is keyed by studio tool names: correct the key, or register a tool of your own with bus.register().`
808
- );
809
- }
810
- const registry = {};
811
- for (const [name, entry] of entries) {
812
- if (entry === void 0 || !isStudioToolName(name)) {
813
- continue;
814
- }
815
- const definition = typeof entry === "function" ? { handler: entry } : entry;
816
- registry[name] = { ...studioToolContracts[name], ...definition, name };
817
- }
818
- return registry;
819
- };
820
- var registerStudioTools = (bus, handlers) => {
821
- const registry = build("registerStudioTools", handlers);
822
- bus.registerAll(registry);
823
- return registry;
824
- };
825
- var studioRegistry = () => (handlers) => (
826
- // The boundary cast `registerStudioTools` makes, for the reason stated there.
827
- build("studioRegistry", handlers)
828
- );
829
-
830
- // src/embed/stores/embed.ts
831
- var embedInitialState = {
832
- embed: null
833
- };
834
- var createEmbedSlice = (set) => ({
835
- setEmbed: (embed) => set({ embed })
836
- });
837
- var selectEmbed = (state) => state.embed;
838
-
839
- // src/embed/stores/embedContent.ts
840
- var embedContentInitialState = {
841
- embedContent: null
842
- };
843
- var createEmbedContentSlice = (set) => ({
844
- setEmbedContent: (embedContent) => set({ embedContent })
845
- });
846
- var selectEmbedContent = (state) => state.embedContent;
847
-
848
- // src/embed/rules/safetyRules.ts
849
- var gatedBooleanRules = {
850
- withOverlaysControl: "with_overlays_control",
851
- withProfileAnalysis: "with_profile_analysis",
852
- withProfileElevation: "with_profile_elevation"
853
- };
854
- var isGatedBooleanKey = (key) => Object.hasOwn(gatedBooleanRules, key);
855
- var isFieldRestricted = (key, safetyRules) => {
856
- if (!safetyRules || !isGatedBooleanKey(key)) {
857
- return false;
858
- }
859
- return safetyRules[gatedBooleanRules[key]] === false;
860
- };
861
- var ALLOWLIST_WILDCARD = "*";
862
- var allowlistUnrestricted = (allowed) => allowed.length === 0 || allowed.includes(ALLOWLIST_WILDCARD);
863
- var allowlistMode = (allowed, variant) => {
864
- if (allowed.includes(ALLOWLIST_WILDCARD)) {
865
- return "all";
866
- }
867
- if (allowed.length === 0) {
868
- return variant === "cap" ? "none" : "all";
869
- }
870
- return "specific";
871
- };
872
- var allowlistForMode = (mode, variant, selection) => {
873
- if (mode === "all") {
874
- return variant === "cap" ? [ALLOWLIST_WILDCARD] : [];
875
- }
876
- return mode === "none" ? [] : [...selection];
877
- };
878
- var clampConfigToSafetyRules = (config, safetyRules) => {
879
- if (!safetyRules) {
880
- return config;
881
- }
882
- let next = config;
883
- for (const key of Object.keys(gatedBooleanRules).filter(isGatedBooleanKey)) {
884
- if (isFieldRestricted(key, safetyRules) && next[key]) {
885
- next = { ...next, [key]: false };
886
- }
887
- }
888
- return next;
889
- };
890
- var HILLSHADE_OVERLAY_SLUG = "hillshade";
891
- var enrichmentOverlays = (layers) => layers.overlays.filter(isEnrichmentCategory).flatMap((category) => category.children);
892
- var classicOverlays = (layers) => layers.overlays.filter((category) => !isEnrichmentCategory(category)).flatMap((category) => category.children);
893
- var collectAttributions = (layers, activeOverlaySlug, activeEnrichments) => {
894
- const overlays = { overlays: layers.overlays ?? [] };
895
- const active = activeOverlaySlug === null ? null : findOverlay(overlays, activeOverlaySlug);
896
- const enrichmentSources = activeEnrichments.flatMap(
897
- (slug) => findOverlay(overlays, slug)?.sources ?? []
898
- );
899
- const sources = [
900
- ...layers.itineraries?.sources ?? [],
901
- ...layers.zones?.sources ?? [],
902
- ...active?.sources ?? [],
903
- ...enrichmentSources
904
- ];
905
- const seen = /* @__PURE__ */ new Set();
906
- const attributions = [];
907
- for (const source of sources) {
908
- const attribution = source.attribution?.trim();
909
- if (attribution !== void 0 && attribution !== "" && !seen.has(attribution)) {
910
- seen.add(attribution);
911
- attributions.push(attribution);
912
- }
913
- }
914
- if (!seen.has(BASEMAP_ATTRIBUTION)) {
915
- attributions.push(BASEMAP_ATTRIBUTION);
916
- }
917
- return attributions;
918
- };
919
- var filterTerrains = (terrains, allowed) => {
920
- if (allowlistUnrestricted(allowed)) {
921
- return [...terrains];
922
- }
923
- const allowedSlugs = new Set(allowed);
924
- return terrains.filter((terrain) => allowedSlugs.has(terrain.slug));
925
- };
926
- var filterOverlayCategories = (categories, allowed, overlaysEntitled) => {
927
- if (!overlaysEntitled) {
928
- return [];
929
- }
930
- const unrestricted = allowlistUnrestricted(allowed);
931
- const allowedSlugs = new Set(allowed);
932
- return categories.map((category) => ({
933
- ...category,
934
- children: category.children.filter(
935
- (overlay) => unrestricted || allowedSlugs.has(overlay.slug)
936
- )
937
- })).filter((category) => category.children.length > 0);
938
- };
939
- var filterEnrichmentOverlays = (overlays, allowed, overlaysEntitled) => {
940
- if (!overlaysEntitled) {
941
- return [];
942
- }
943
- const unrestricted = allowlistUnrestricted(allowed);
944
- const allowedSlugs = new Set(allowed);
945
- return overlays.filter(
946
- (overlay) => overlay.slug !== POIS_OVERLAY_SLUG && (unrestricted || allowedSlugs.has(overlay.slug))
947
- );
948
- };
949
- var findHillshadeOverlay = (layers) => findOverlay({ overlays: layers.overlays ?? [] }, HILLSHADE_OVERLAY_SLUG, "enrichment");
950
- var directionsTargetSchema = z2.object({
951
- itineraryId: z2.string(),
952
- segmentId: z2.string().nullable()
953
- });
954
- var directionsInitialState = {
955
- directionsTarget: null
956
- };
957
- var createDirectionsSlice = (set) => ({
958
- setDirections: (directionsTarget) => set({ directionsTarget })
959
- });
960
- var selectDirections = (state) => state.directionsTarget;
961
-
962
- // src/share/stores/share.ts
963
- var shareInitialState = {
964
- share: null
965
- };
966
- var createShareSlice = (set) => ({
967
- setShare: (share) => set({ share })
968
- });
969
- var selectShare = (state) => state.share;
970
-
971
- // src/waypoints/stores/waypointDetails.ts
972
- var waypointDetailsInitialState = {
973
- waypointDetailsDialog: null
974
- };
975
- var createWaypointDetailsSlice = (set) => ({
976
- setWaypointDetailsDialog: (waypointDetailsDialog) => set({ waypointDetailsDialog })
977
- });
978
- var selectWaypointDetails = (state) => state.waypointDetailsDialog;
979
-
980
- // src/edit/stores/editorReservation.ts
981
- var editorReservationInitialState = {
982
- editorReservation: null
983
- };
984
- var createEditorReservationSlice = (set) => ({
985
- releaseEditor: (mark) => set((state) => state.editorReservation === mark ? { editorReservation: null } : {}),
986
- reserveEditor: (mark) => set({ editorReservation: mark })
987
- });
988
-
989
- // src/edit/stores/formsUnsaved.ts
990
- var formsUnsavedInitialState = {
991
- itineraryFormUnsaved: false,
992
- waypointDetailsUnsaved: false
993
- };
994
- var memberOf2 = {
995
- itinerary: "itineraryFormUnsaved",
996
- waypointDetails: "waypointDetailsUnsaved"
997
- };
998
- var createFormsUnsavedSlice = (set) => ({
999
- setFormUnsaved: (form, unsaved) => set((state) => state[memberOf2[form]] === unsaved ? {} : { [memberOf2[form]]: unsaved })
1000
- });
1001
-
1002
- // src/itinerary/rules/draftSurface.ts
1003
- var draftSurfaceNames = Object.freeze({
1004
- import: "import",
1005
- suggest: "suggest-itineraries"
1006
- });
1007
- var showingDraftSurface = (state) => {
1008
- if (state.openContent === "import") {
1009
- return state.importSession === null ? null : "import";
1010
- }
1011
- if (state.openContent === "suggest") {
1012
- return state.suggestSession === null ? null : "suggest";
1013
- }
1014
- return null;
1015
- };
1016
- var showingDraftSession = (state) => {
1017
- const surface = showingDraftSurface(state);
1018
- if (surface === null) {
1019
- return null;
1020
- }
1021
- const session = surface === "import" ? state.importSession : state.suggestSession;
1022
- return session?.draft ? session : null;
1023
- };
1024
- var showingDraft = (state) => showingDraftSession(state)?.draft ?? null;
1025
- var draftSessionIdentity = (state, surface) => {
1026
- const session = surface === "import" ? state.importSession : state.suggestSession;
1027
- return session === null ? null : { draftId: session.draftId, sessionId: session.sessionId };
1028
- };
1029
- var holdsDraftSession = (state, surface, sent) => {
1030
- const standing = draftSessionIdentity(state, surface);
1031
- return sent !== null && standing !== null && standing.sessionId === sent.sessionId && standing.draftId === sent.draftId;
1032
- };
1033
- var holdDuringDraftCommit = (ctx, surface, verb) => ctx.ui.getState().editorReservation?.session === surface ? {
1034
- code: "conflict",
1035
- error: `${verb}: the ${draftSurfaceNames[surface]} draft is being saved; send it again once its commit has settled`,
1036
- ok: false
1037
- } : null;
1038
- var holdDuringPreview = (ctx, surface, verb) => {
1039
- const status = surface === "import" ? ctx.ui.getState().importSession?.status : void 0;
1040
- return status?.kind === "settling" || status?.kind === "previewing" ? {
1041
- code: "conflict",
1042
- error: `${verb}: the ${draftSurfaceNames[surface]} draft is being previewed again for a changed option; send it again once the preview lands`,
1043
- ok: false
1044
- } : null;
1045
- };
1046
- var holdDraftWrite = (ctx, surface, verb) => holdDuringDraftCommit(ctx, surface, verb) ?? holdDuringPreview(ctx, surface, verb);
1047
- var holdShowingDraft = (ctx, verb) => {
1048
- const surface = showingDraftSurface(ctx.ui.getState());
1049
- return surface === null ? null : holdDraftWrite(ctx, surface, verb);
1050
- };
1051
-
1052
- // src/itinerary/stores/sessionIdentity.ts
1053
- var minted = 0;
1054
- var mintSessionIdentity = () => {
1055
- minted += 1;
1056
- return minted;
1057
- };
1058
- var editedDraftIdentity = (session, draft) => {
1059
- if (draft === null) {
1060
- return null;
1061
- }
1062
- return session.draft !== null && session.draftId !== null ? session.draftId : mintSessionIdentity();
1063
- };
1064
-
1065
- // src/itinerary/stores/importSession.ts
1066
- var importSessionInitialState = {
1067
- importSession: null
1068
- };
1069
- var createImportSessionSlice = (set) => ({
1070
- closeImport: () => set({ importSession: null }),
1071
- openImport: (provider) => set({
1072
- importSession: {
1073
- activityId: null,
1074
- // Seed no collections; the shell's picker fills them in and the confirm
1075
- // attaches them after the create.
1076
- collectionIds: [],
1077
- draft: null,
1078
- draftGranularity: null,
1079
- draftId: null,
1080
- file: null,
1081
- // Auto: the segmentation follows the recording's own structure (its stops,
1082
- // its gaps, its turnarounds). "single" is reachable only through the tool, and
1083
- // it is not a promise the pipeline can keep on a real track: the hard
1084
- // boundaries and the routability sub-split run under it too, so a long
1085
- // recording still arrives as many segments. Defaulting to the honest one.
1086
- granularity: "auto",
1087
- // Seed private to match the itinerary CREATE flow's default; the
1088
- // shell's privacy Switch flips it before the confirm reads it.
1089
- isPrivate: true,
1090
- name: "",
1091
- // Seed null; the shell's OrganizationSelect writes the resolved default
1092
- // (the user's root org) once it lands. Null means the confirm omits
1093
- // organization_id and the server defaults to the caller's organization.
1094
- organizationId: null,
1095
- preview: null,
1096
- provider,
1097
- sessionId: mintSessionIdentity(),
1098
- status: { kind: "idle" }
1099
- }
1100
- }),
1101
- removeImportDraftSegment: (segmentId) => set((state) => {
1102
- const draft = state.importSession?.draft;
1103
- if (!state.importSession || !draft) {
1104
- return state;
1105
- }
1106
- return {
1107
- importSession: {
1108
- ...state.importSession,
1109
- draft: {
1110
- ...draft,
1111
- segments: draft.segments.filter((segment) => segment.id !== segmentId)
1112
- }
1113
- }
1114
- };
1115
- }),
1116
- setImportActivity: (activityId) => set(
1117
- (state) => state.importSession ? { importSession: { ...state.importSession, activityId } } : state
1118
- ),
1119
- setImportCollections: (collectionIds) => set(
1120
- (state) => state.importSession ? { importSession: { ...state.importSession, collectionIds } } : state
1121
- ),
1122
- setImportDraft: (draft) => set((state) => {
1123
- const session = state.importSession;
1124
- if (!session) {
1125
- return state;
1126
- }
1127
- return {
1128
- importSession: {
1129
- ...session,
1130
- draft,
1131
- draftGranularity: draft === null ? null : session.draftGranularity,
1132
- draftId: editedDraftIdentity(session, draft)
1133
- }
1134
- };
1135
- }),
1136
- setImportDraftSegmentSpeed: (segmentId, speed) => set((state) => {
1137
- const draft = state.importSession?.draft;
1138
- if (!state.importSession || !draft) {
1139
- return state;
1140
- }
1141
- return {
1142
- importSession: {
1143
- ...state.importSession,
1144
- draft: {
1145
- ...draft,
1146
- segments: draft.segments.map(
1147
- (segment) => segment.id === segmentId ? { ...segment, speed } : segment
1148
- )
1149
- }
1150
- }
1151
- };
1152
- }),
1153
- setImportFile: (file) => set(
1154
- (state) => state.importSession ? { importSession: { ...state.importSession, file } } : state
1155
- ),
1156
- setImportGranularity: (granularity) => set(
1157
- (state) => state.importSession ? { importSession: { ...state.importSession, granularity } } : state
1158
- ),
1159
- setImportName: (name) => set(
1160
- (state) => state.importSession ? { importSession: { ...state.importSession, name } } : state
1161
- ),
1162
- setImportOrganization: (organizationId) => set(
1163
- (state) => state.importSession ? { importSession: { ...state.importSession, organizationId } } : state
1164
- ),
1165
- setImportPreview: (preview) => set(
1166
- (state) => state.importSession ? { importSession: { ...state.importSession, preview } } : state
1167
- ),
1168
- setImportPrivate: (isPrivate) => set(
1169
- (state) => state.importSession ? { importSession: { ...state.importSession, isPrivate } } : state
1170
- ),
1171
- setImportProvider: (provider) => set(
1172
- (state) => state.importSession ? { importSession: { ...state.importSession, provider } } : state
1173
- ),
1174
- setImportStatus: (status) => set(
1175
- (state) => state.importSession ? { importSession: { ...state.importSession, status } } : state
1176
- ),
1177
- stageImportDraft: (draft, granularity) => set(
1178
- (state) => state.importSession ? {
1179
- importSession: {
1180
- ...state.importSession,
1181
- draft,
1182
- draftGranularity: granularity ?? null,
1183
- draftId: mintSessionIdentity()
1184
- }
1185
- } : state
1186
- )
1187
- });
1188
- z2.object({
1189
- itineraryId: z2.string()
1190
- });
1191
- var itineraryDuplicateInitialState = {
1192
- itineraryDuplicate: null
1193
- };
1194
- var createItineraryDuplicateSlice = (set) => ({
1195
- setItineraryDuplicate: (itineraryDuplicate) => set({ itineraryDuplicate })
1196
- });
1197
-
1198
- // src/itinerary/stores/suggestSession.ts
1199
- var suggestSessionInitialState = {
1200
- suggestSession: null
1201
- };
1202
- var createSuggestSessionSlice = (set) => ({
1203
- closeSuggest: () => set({ suggestSession: null }),
1204
- openSuggest: (options) => set({
1205
- suggestSession: {
1206
- activityId: null,
1207
- // No delegated pick until the co-pilot's run deliberately selects one;
1208
- // the agent-origin startFrom gate reads this.
1209
- agentSelected: false,
1210
- ascentMeters: null,
1211
- candidates: [],
1212
- // Seed no collections; the shell's picker fills them in and the commit
1213
- // attaches them after the create. Mirrors openImport.
1214
- collectionIds: [],
1215
- // Seed a 10 km target so the form opens on a sensible loop length the
1216
- // user can tune before generating; the distance control edits it.
1217
- distanceMeters: 1e4,
1218
- // No draft until a chosen itinerary is shaped into one.
1219
- draft: null,
1220
- draftId: null,
1221
- end: null,
1222
- // Not exhausted until a generation comes back short of the target count.
1223
- exhausted: false,
1224
- // Seed private to match the itinerary CREATE flow's default; the shell's
1225
- // privacy control flips it before the commit reads it. Mirrors openImport.
1226
- isPrivate: true,
1227
- // No surface has left this session, so nothing of it is held back from the map.
1228
- name: "",
1229
- // Seed null; the shell's OrganizationSelect writes the resolved default.
1230
- // Null means the commit omits organization_id and the server defaults to
1231
- // the caller's organization. Mirrors openImport.
1232
- organizationId: null,
1233
- // Auto-arm the start-point pick on open (the default) so entering the
1234
- // suggest flow locks the map cursor on the start point and the first click
1235
- // sets it: the picking hook reads this slot; setSuggestStart clears it on
1236
- // placement (Escape/cancelPick too). A caller that supplies coordinates
1237
- // directly (the co-pilot's headless session) passes `picking: null` so the
1238
- // cursor is never locked on a pick nobody will click.
1239
- picking: options?.picking === void 0 ? "start" : options.picking,
1240
- routeType: "loop",
1241
- seenSeeds: [],
1242
- selectedSeed: null,
1243
- sessionId: mintSessionIdentity(),
1244
- speedKmh: null,
1245
- start: null,
1246
- status: { kind: "idle" },
1247
- // Add a new segment unless a generate says otherwise; a fresh session
1248
- // never inherits the previous batch's target.
1249
- targetSegmentId: null
1250
- }
1251
- }),
1252
- selectSuggestionCandidate: (seed) => set(
1253
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, selectedSeed: seed } } : state
1254
- ),
1255
- setSuggestActivity: (activityId) => set(
1256
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, activityId } } : state
1257
- ),
1258
- setSuggestAgentSelected: (agentSelected) => set(
1259
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, agentSelected } } : state
1260
- ),
1261
- setSuggestAscent: (ascentMeters) => set(
1262
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, ascentMeters } } : state
1263
- ),
1264
- setSuggestCollections: (collectionIds) => set(
1265
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, collectionIds } } : state
1266
- ),
1267
- setSuggestDistance: (distanceMeters) => set(
1268
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, distanceMeters } } : state
1269
- ),
1270
- setSuggestDraft: (draft) => set((state) => {
1271
- const session = state.suggestSession;
1272
- if (!session) {
1273
- return state;
1274
- }
1275
- return {
1276
- suggestSession: { ...session, draft, draftId: editedDraftIdentity(session, draft) }
1277
- };
1278
- }),
1279
- setSuggestEnd: (end) => set(
1280
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, end } } : state
1281
- ),
1282
- setSuggestionCandidates: (candidates, seenSeeds, exhausted = false) => set((state) => {
1283
- const session = state.suggestSession;
1284
- if (!session) {
1285
- return state;
1286
- }
1287
- const selectedSeed = session.selectedSeed !== null && candidates.some((candidate) => candidate.seed === session.selectedSeed) ? session.selectedSeed : null;
1288
- return {
1289
- suggestSession: { ...session, candidates, exhausted, seenSeeds, selectedSeed }
1290
- };
1291
- }),
1292
- setSuggestionStatus: (status) => set(
1293
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, status } } : state
1294
- ),
1295
- setSuggestName: (name) => set(
1296
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, name } } : state
1297
- ),
1298
- setSuggestOrganization: (organizationId) => set(
1299
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, organizationId } } : state
1300
- ),
1301
- setSuggestPicking: (picking) => set(
1302
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, picking } } : state
1303
- ),
1304
- setSuggestPrivate: (isPrivate) => set(
1305
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, isPrivate } } : state
1306
- ),
1307
- setSuggestRouteType: (routeType) => set(
1308
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, routeType } } : state
1309
- ),
1310
- setSuggestSpeed: (speedKmh) => set(
1311
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, speedKmh } } : state
1312
- ),
1313
- setSuggestStart: (start) => set(
1314
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, start } } : state
1315
- ),
1316
- setSuggestTargetSegment: (targetSegmentId) => set(
1317
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, targetSegmentId } } : state
1318
- ),
1319
- stageSuggestDraft: (draft) => set(
1320
- (state) => state.suggestSession ? { suggestSession: { ...state.suggestSession, draft, draftId: mintSessionIdentity() } } : state
1321
- ),
1322
- toggleSuggestionKeep: (seed) => set((state) => {
1323
- const session = state.suggestSession;
1324
- if (!session) {
1325
- return state;
1326
- }
1327
- const target = session.candidates.find((candidate) => candidate.seed === seed);
1328
- if (!target) {
1329
- return state;
1330
- }
1331
- const keptCount = session.candidates.filter((candidate) => candidate.kept).length;
1332
- if (!target.kept && keptCount >= SUGGESTION_MAX_KEPT) {
1333
- return state;
1334
- }
1335
- return {
1336
- suggestSession: {
1337
- ...session,
1338
- candidates: session.candidates.map(
1339
- (candidate) => candidate.seed === seed ? { ...candidate, kept: !candidate.kept } : candidate
1340
- )
1341
- }
1342
- };
1343
- })
1344
- });
1345
-
1346
- // src/layers/stores/layers.ts
1347
- var toggleSlug = (slugs, slug, enabled) => {
1348
- if (slugs.includes(slug) === enabled) {
1349
- return slugs;
1350
- }
1351
- return enabled ? [...slugs, slug] : slugs.filter((active) => active !== slug);
1352
- };
1353
- var reconcilePoisEnrichment = (enrichments, groups) => {
1354
- const shouldHavePois = groups.length > 0;
1355
- return toggleSlug(enrichments, POIS_OVERLAY_SLUG, shouldHavePois);
1356
- };
1357
- var poiGroupsForSource = (groups, enabled) => {
1358
- if (groups.length > 0 === enabled) {
1359
- return groups;
1360
- }
1361
- return enabled ? [...DEFAULT_ENABLED_POI_GROUP_IDS] : [];
1362
- };
1363
- var knownPoiGroups = new Set(POI_GROUP_IDS);
1364
- var uniquePoiGroups = (groups) => {
1365
- const seen = /* @__PURE__ */ new Set();
1366
- const result = [];
1367
- for (const group of groups) {
1368
- if (knownPoiGroups.has(group) && !seen.has(group)) {
1369
- seen.add(group);
1370
- result.push(group);
1371
- }
1372
- }
1373
- return result;
1374
- };
1375
- var layersInitialState = {
1376
- // Seeded with the POIs source so the default-on critical groups render on the first paint
1377
- // of a map that draws overlays (permittedEnrichmentOverlays draws none for a viewer
1378
- // without `map-overlays`). It stays in lockstep with activePoiGroups below (non-empty),
1379
- // so the `"pois" ∈ activeEnrichments ⇔ activePoiGroups.length > 0` invariant holds from
1380
- // initial state.
1381
- activeEnrichments: [POIS_OVERLAY_SLUG],
1382
- activeOverlay: null,
1383
- activeOverlayCategorySlug: null,
1384
- activePoiGroups: [...DEFAULT_ENABLED_POI_GROUP_IDS],
1385
- overlayTimestamp: null,
1386
- poiFilterNoticeNonce: 0,
1387
- terrain: DEFAULT_TERRAIN,
1388
- terrainVariant: "light"
1389
- };
1390
- var createLayersSlice = (set, get) => ({
1391
- bumpPoiFilterNotice: () => set((state) => ({ poiFilterNoticeNonce: state.poiFilterNoticeNonce + 1 })),
1392
- setActiveOverlay: (activeOverlay) => set({ activeOverlay }),
1393
- setActiveOverlayCategorySlug: (activeOverlayCategorySlug) => set({ activeOverlayCategorySlug }),
1394
- setAllPoiGroups: (enabled) => {
1395
- get().setPoiGroups(enabled ? [...POI_GROUP_IDS] : []);
1396
- },
1397
- setEnrichment: (slug, enabled) => set((state) => {
1398
- if (slug !== POIS_OVERLAY_SLUG) {
1399
- return { activeEnrichments: toggleSlug(state.activeEnrichments, slug, enabled) };
1400
- }
1401
- const groups = poiGroupsForSource(state.activePoiGroups, enabled);
1402
- return {
1403
- activeEnrichments: reconcilePoisEnrichment(state.activeEnrichments, groups),
1404
- activePoiGroups: groups
1405
- };
1406
- }),
1407
- setOverlayTimestamp: (overlayTimestamp) => set({ overlayTimestamp }),
1408
- setPoiGroup: (group, enabled) => set((state) => {
1409
- if (!knownPoiGroups.has(group)) {
1410
- return {};
1411
- }
1412
- const groups = toggleSlug(state.activePoiGroups, group, enabled);
1413
- return {
1414
- activeEnrichments: reconcilePoisEnrichment(state.activeEnrichments, groups),
1415
- activePoiGroups: groups
1416
- };
1417
- }),
1418
- setPoiGroups: (groups) => set((state) => {
1419
- const next = uniquePoiGroups(groups);
1420
- return {
1421
- activeEnrichments: reconcilePoisEnrichment(state.activeEnrichments, next),
1422
- activePoiGroups: next
1423
- };
1424
- }),
1425
- setTerrain: (terrain) => set({ terrain }),
1426
- setTerrainVariant: (terrainVariant) => set({ terrainVariant })
1427
- });
1428
-
1429
- // src/rules/storeWrite.ts
1430
- var resolveWrite = (handed, state) => isWriteFunction(handed) ? handed(state) : handed;
1431
- var isWriteFunction = (handed) => typeof handed === "function";
1432
-
1433
- // src/search/stores/search.ts
1434
- var searchInitialState = {
1435
- searchQuery: "",
1436
- searchViewportScope: true
1437
- };
1438
- var createSearchSlice = (set) => ({
1439
- setSearchQuery: (searchQuery) => set({ searchQuery }),
1440
- setSearchViewportScope: (searchViewportScope) => set({ searchViewportScope })
1441
- });
1442
-
1443
- // src/chrome/stores/activeDraftSession.ts
1444
- var createActiveDraftSlice = (_set, get) => ({
1445
- removeActiveDraftSegment: (segmentId) => {
1446
- const state = get();
1447
- const session = showingDraftSession(state);
1448
- if (session !== null && session === state.importSession) {
1449
- state.removeImportDraftSegment(segmentId);
1450
- return;
1451
- }
1452
- const draft = session?.draft;
1453
- if (!draft) {
1454
- return;
1455
- }
1456
- state.setSuggestDraft({
1457
- ...draft,
1458
- segments: draft.segments.filter((segment) => segment.id !== segmentId)
1459
- });
1460
- },
1461
- setActiveDraft: (draft) => {
1462
- const state = get();
1463
- const session = showingDraftSession(state);
1464
- if (session === null) {
1465
- return;
1466
- }
1467
- if (session === state.importSession) {
1468
- state.setImportDraft(draft);
1469
- return;
1470
- }
1471
- state.setSuggestDraft(draft);
1472
- },
1473
- setActiveDraftSegmentSpeed: (segmentId, speed) => {
1474
- const state = get();
1475
- const session = showingDraftSession(state);
1476
- if (session !== null && session === state.importSession) {
1477
- state.setImportDraftSegmentSpeed(segmentId, speed);
1478
- return;
1479
- }
1480
- const draft = session?.draft;
1481
- if (!draft) {
1482
- return;
1483
- }
1484
- state.setSuggestDraft({
1485
- ...draft,
1486
- segments: draft.segments.map(
1487
- (segment) => segment.id === segmentId ? { ...segment, speed } : segment
1488
- )
1489
- });
1490
- }
1491
- });
1492
-
1493
- // src/chrome/stores/uiStore.ts
1494
- var initialState = {
1495
- ...chromeInitialState,
1496
- ...collabInitialState,
1497
- ...collectionsInitialState,
1498
- ...directionsInitialState,
1499
- ...editorReservationInitialState,
1500
- ...formsUnsavedInitialState,
1501
- ...embedContentInitialState,
1502
- ...embedInitialState,
1503
- ...importSessionInitialState,
1504
- ...itineraryDuplicateInitialState,
1505
- ...itineraryInitialState,
1506
- ...layersInitialState,
1507
- ...roadAccessDialogInitialState,
1508
- ...searchInitialState,
1509
- ...segmentEditInitialState,
1510
- ...segmentGroupEditInitialState,
1511
- ...segmentSplitInitialState,
1512
- ...shareInitialState,
1513
- ...suggestSessionInitialState,
1514
- ...videoExportInitialState,
1515
- ...waypointDetailsInitialState,
1516
- ...waypointEditInitialState,
1517
- ...zoneEditInitialState
1518
- };
1519
- var embedUiBaseline = {
1520
- activeEnrichments: [],
1521
- activePoiGroups: []
1522
- };
1523
- var createUiStore = (overrides) => createStore(
1524
- withUnchangedWritesDropped((set, get, store) => ({
1525
- ...initialState,
1526
- ...overrides,
1527
- ...createActiveDraftSlice(set, get),
1528
- ...createChromeSlice(set, get, store),
1529
- ...createCollabSlice(set, get, store),
1530
- ...createCollectionsSlice(set, get, store),
1531
- ...createDirectionsSlice(set),
1532
- ...createEditorReservationSlice(set),
1533
- ...createFormsUnsavedSlice(set),
1534
- ...createEmbedContentSlice(set),
1535
- ...createEmbedSlice(set),
1536
- ...createImportSessionSlice(set),
1537
- ...createItineraryDuplicateSlice(set),
1538
- ...createItinerarySlice(set, get, store),
1539
- ...createLayersSlice(set, get),
1540
- ...createRoadAccessDialogSlice(set, get, store),
1541
- ...createSearchSlice(set),
1542
- ...createSegmentEditSlice(set, get, store),
1543
- ...createSegmentGroupEditSlice(set, get, store),
1544
- ...createSegmentSplitSlice(set, get, store),
1545
- ...createShareSlice(set),
1546
- ...createSuggestSessionSlice(set),
1547
- ...createVideoExportSlice(set, get, store),
1548
- ...createWaypointDetailsSlice(set),
1549
- ...createWaypointEditSlice(set, get, store),
1550
- ...createZoneEditSlice(set, get, store)
1551
- }))
1552
- );
1553
- var withUnchangedWritesDropped = (creator) => (set, get, store) => {
1554
- const dropping = (...write) => {
1555
- if (write[1] === true) {
1556
- set(write[0], true);
1557
- return;
1558
- }
1559
- const [handed] = write;
1560
- set((state) => {
1561
- const patch = resolveWrite(handed, state);
1562
- return changesNothing(patch, state) ? state : patch;
1563
- });
1564
- };
1565
- store.setState = dropping;
1566
- return creator(dropping, get, store);
1567
- };
1568
- var changesNothing = (patch, state) => {
1569
- for (const key in patch) {
1570
- if (Object.hasOwn(patch, key) && !Object.is(patch[key], state[key])) {
1571
- return false;
1572
- }
1573
- }
1574
- return true;
1575
- };
1576
- var selectProfilePaceKmh = (itineraryId) => (state) => {
1577
- const override = state.profilePace;
1578
- if (!override || !itineraryId || override.itineraryId !== itineraryId) {
1579
- return null;
1580
- }
1581
- return override.speedKmh;
1582
- };
1583
- var selectProfileSheetSnap = (state) => state.profileSheetSnap;
1584
- var selectSegmentViaPrompt = (state) => state.segmentViaPrompt;
1585
- var selectActiveDraftSession = (state) => showingDraftSession(state);
1586
- var selectActiveDraft = (state) => showingDraft(state);
1587
- var selectBaseMapLocked = (state) => selectActiveEditEngine(state) !== null;
1588
- var selectZoneEditDirty = (state) => isZoneGeometryDirty(state.zoneEditSession);
1589
- var selectZoneCreateSetup = (state) => state.openContent === "zone" && state.activeZone === null && state.zoneEditSession === null;
1590
- var selectEditDirtyTick = (state) => state.editDirtyTick;
1591
- var selectVideoExport = (state) => state.videoExport;
1592
- var selectVideoExportPlan = (state) => state.videoExport?.plan ?? null;
1593
- var selectVideoExportRoute = (state) => state.videoExport?.route ?? null;
1594
- var selectVideoExportStatus = (state) => state.videoExport?.status ?? null;
1595
- var selectImportSession = (state) => state.importSession;
1596
- var selectSelectedSuggestionCandidate = (state) => {
1597
- const session = state.suggestSession;
1598
- if (!session || session.draft) {
1599
- return null;
1600
- }
1601
- return selectedCandidate(session);
1602
- };
1603
- var selectAgentHandoffArmed = (state) => {
1604
- const handoff = state.agentHandoff;
1605
- if (!handoff) {
1606
- return false;
1607
- }
1608
- const armed = agentHandoffTarget(state);
1609
- return armed !== null && armed.kind === handoff.kind && armed.id === handoff.id;
1610
- };
1611
- var CONFLICT = "CONFLICT";
1612
- var ANSWER_UNAVAILABLE = "IDEMPOTENCY_ANSWER_UNAVAILABLE";
1613
- var KEY_IN_USE = "IDEMPOTENCY_KEY_IN_USE";
1614
- var PRECONDITION_FAILED_STATUS = 412;
1615
- var REVISION_CONFLICT_NAME = "RevisionConflictError";
1616
- var RevisionConflictError = class extends MountayaElementsError {
1617
- name = REVISION_CONFLICT_NAME;
1618
- };
1619
- var SEGMENT_DELETE_NOT_EDGE_NAME = "SegmentDeleteNotEdgeError";
1620
- var SegmentDeleteNotEdgeError = class extends MountayaElementsError {
1621
- name = SEGMENT_DELETE_NOT_EDGE_NAME;
1622
- /**
1623
- * The server's own sentence for the refusal, already in the reader's language, or undefined
1624
- * where the failure carried none. It is what a surface renders; the message stays technical.
1625
- */
1626
- detail;
1627
- constructor(message, detail, options) {
1628
- super(message, options);
1629
- this.detail = detail;
1630
- }
1631
- };
1632
- var errorName = (error) => {
1633
- if (typeof error !== "object" || error === null || !("name" in error)) {
1634
- return void 0;
1635
- }
1636
- return typeof error.name === "string" ? error.name : void 0;
1637
- };
1638
- var isRevisionConflict = (error) => errorName(error) === REVISION_CONFLICT_NAME;
1639
- var isSegmentDeleteNotEdge = (error) => errorName(error) === SEGMENT_DELETE_NOT_EDGE_NAME;
1640
- var isFailureEntry = (value) => typeof value === "object" && value !== null && "message" in value && typeof value.message === "string";
1641
- var apiFailure = (error) => {
1642
- if (typeof error !== "object" || error === null || !("status" in error && "errors" in error)) {
1643
- return void 0;
1644
- }
1645
- if (typeof error.status !== "number" || !Array.isArray(error.errors)) {
1646
- return void 0;
1647
- }
1648
- return { entries: error.errors.filter(isFailureEntry), status: error.status };
1649
- };
1650
- var isAnswerUnavailable = (error) => {
1651
- const failure = apiFailure(error);
1652
- return failure?.status === 409 && failure.entries[0]?.extensions?.code === ANSWER_UNAVAILABLE;
1653
- };
1654
- var isKeyInUse = (error) => {
1655
- const failure = apiFailure(error);
1656
- return failure?.status === 409 && failure.entries[0]?.extensions?.code === KEY_IN_USE;
1657
- };
1658
- var madeAnswerOf = (error) => {
1659
- if (!isAnswerUnavailable(error)) {
1660
- return void 0;
1661
- }
1662
- const answer = memberOf(error, "answer");
1663
- const etag = memberOf(answer, "etag");
1664
- const location = memberOf(answer, "location");
1665
- return {
1666
- etag: typeof etag === "string" && etag !== "" ? etag : void 0,
1667
- location: typeof location === "string" && location !== "" ? location : void 0
1668
- };
1669
- };
1670
- var createdIdOf = (answer) => {
1671
- if (answer.location === void 0) {
1672
- return void 0;
1673
- }
1674
- const [path = ""] = answer.location.split(/[?#]/, 1);
1675
- const id = path.split("/").findLast((segment) => segment !== "");
1676
- return id === void 0 ? void 0 : decodeURIComponent(id);
1677
- };
1678
- var reconcileMadeWrite = async (write, made) => {
1679
- try {
1680
- return await write();
1681
- } catch (error) {
1682
- const answer = madeAnswerOf(error);
1683
- if (answer === void 0) {
1684
- throw error;
1685
- }
1686
- return made(answer);
1687
- }
1688
- };
1689
- var isChainShapeRefusal = (failure, error) => failure.status === 409 && failure.entries[0]?.extensions?.code === CONFLICT && lockHolderOf(error) === void 0;
1690
- var rethrowSegmentWriteError = (error, write) => {
1691
- if (isAnswerUnavailable(error) || isKeyInUse(error)) {
1692
- throw error;
1693
- }
1694
- const failure = apiFailure(error);
1695
- if (failure !== void 0) {
1696
- const message = error instanceof Error ? error.message : "";
1697
- if (write === "delete" && isChainShapeRefusal(failure, error)) {
1698
- throw new SegmentDeleteNotEdgeError(message, failure.entries[0]?.message, { cause: error });
1699
- }
1700
- if (failure.status === PRECONDITION_FAILED_STATUS || failure.status === 409 && lockHolderOf(error) === void 0) {
1701
- throw new RevisionConflictError(message, { cause: error });
1702
- }
1703
- }
1704
- throw error;
1705
- };
1706
- var hasErrorCode = (error, code) => apiFailure(error)?.entries.some((entry) => entry.extensions?.code === code) ?? false;
1707
- var isPreconditionFailed = (error) => apiFailure(error)?.status === PRECONDITION_FAILED_STATUS;
1708
-
1709
- // src/itinerary/rules/analysis.ts
1710
- var withSegmentAnalysis = (segment) => ({
1711
- ...segment,
1712
- slope_info: segment.slope_info ?? [],
1713
- steps: segment.steps ?? [],
1714
- surface_info: segment.surface_info ?? [],
1715
- trail_difficulty_info: segment.trail_difficulty_info ?? [],
1716
- way_type_info: segment.way_type_info ?? []
1717
- });
1718
- var withItineraryAnalysis = (itinerary) => ({
1719
- ...itinerary,
1720
- segments: itinerary.segments.map(withSegmentAnalysis)
1721
- });
1722
-
1723
- // src/edit/rules/editorTaken.ts
1724
- var SPLIT_PICK_GESTURE = "split-pick";
1725
- var selectEditorTakenBy = (state) => {
1726
- const active = selectActiveEditEngine(state);
1727
- if (active) {
1728
- return active.kind;
1729
- }
1730
- if (state.segmentSplitPick !== null) {
1731
- return SPLIT_PICK_GESTURE;
1732
- }
1733
- return state.editorReservation?.kind ?? null;
1734
- };
1735
-
1736
- // src/waypoints/rules/draftDirty.ts
1737
- var samePoint = (a, b) => a === null || b === null ? a === b : a[0] === b[0] && a[1] === b[1];
1738
- var isWaypointDraftDirty = (session) => {
1739
- if (session === null) {
1740
- return false;
1741
- }
1742
- const { draft, savedDraft } = session;
1743
- if (savedDraft === null) {
1744
- return true;
1745
- }
1746
- return draft.color !== savedDraft.color || draft.icon !== savedDraft.icon || draft.name !== savedDraft.name || !samePoint(draft.lngLat, savedDraft.lngLat) || draft.poiSeed?.sourceFeatureId !== savedDraft.poiSeed?.sourceFeatureId;
1747
- };
1748
-
1749
- // src/edit/rules/unsavedWork.ts
1750
- var isZoneWorkUnsaved = (state) => isZoneGeometryDirty(state.zoneEditSession) || state.zoneFormUnsaved;
1751
- var selectUnsavedWork = (state) => isSegmentDraftDirty(state.segmentEditSession) || isWaypointDraftDirty(state.waypointEditSession) || isZoneWorkUnsaved(state) || state.itineraryFormUnsaved || state.waypointDetailsUnsaved || showingDraft(state) !== null;
1752
-
1753
- // src/segments/rules/chain.ts
1754
- var indexById = (segments) => {
1755
- const indices = /* @__PURE__ */ new Map();
1756
- for (const [index, segment] of segments.entries()) {
1757
- indices.set(segment.id, index);
1758
- }
1759
- return indices;
1760
- };
1761
- var runBoundsFrom = (indices, ids) => {
1762
- const seen = /* @__PURE__ */ new Set();
1763
- let first = Number.POSITIVE_INFINITY;
1764
- let last = Number.NEGATIVE_INFINITY;
1765
- for (const id of ids) {
1766
- const index = indices.get(id);
1767
- if (index === void 0 || seen.has(id)) {
1768
- return null;
1769
- }
1770
- seen.add(id);
1771
- first = Math.min(first, index);
1772
- last = Math.max(last, index);
1773
- }
1774
- if (seen.size === 0) {
1775
- return null;
1776
- }
1777
- return last - first + 1 === seen.size ? { first, last } : null;
1778
- };
1779
- var contiguousRunBounds = (segments, ids) => runBoundsFrom(indexById(segments), ids);
1780
- var isContiguousRun = (segments, ids) => contiguousRunBounds(segments, ids) !== null;
1781
- var toggleableSegmentIds = (segments, keptIds) => {
1782
- const indices = indexById(segments);
1783
- const keptList = [...keptIds];
1784
- const kept = new Set(keptList);
1785
- const toggleable = /* @__PURE__ */ new Set();
1786
- if (kept.size === 0) {
1787
- for (const segment of segments) {
1788
- toggleable.add(segment.id);
1789
- }
1790
- return toggleable;
1791
- }
1792
- const bounds = runBoundsFrom(indices, keptList);
1793
- if (bounds !== null) {
1794
- const head = segments[bounds.first];
1795
- const tail = segments[bounds.last];
1796
- if (head && tail && bounds.last > bounds.first) {
1797
- toggleable.add(head.id);
1798
- toggleable.add(tail.id);
1799
- }
1800
- const above = bounds.first > 0 ? segments[bounds.first - 1] : void 0;
1801
- const below = segments[bounds.last + 1];
1802
- if (above) {
1803
- toggleable.add(above.id);
1804
- }
1805
- if (below) {
1806
- toggleable.add(below.id);
1807
- }
1808
- return toggleable;
1809
- }
1810
- for (const segment of segments) {
1811
- const candidate = kept.has(segment.id) ? keptList.filter((id) => id !== segment.id) : [...keptList, segment.id];
1812
- if (runBoundsFrom(indices, candidate) !== null) {
1813
- toggleable.add(segment.id);
1814
- }
1815
- }
1816
- return toggleable;
1817
- };
1818
- var mergedViaCount = (head, tail) => {
1819
- const headVias = extractVias(head.geojson);
1820
- const tailVias = extractVias(tail.geojson);
1821
- const junction = headVias.at(-1);
1822
- const opening = tailVias.at(0);
1823
- if (junction === void 0 || opening === void 0) {
1824
- return headVias.length + tailVias.length;
1825
- }
1826
- const [junctionLng, junctionLat] = junction;
1827
- const [openingLng, openingLat] = opening;
1828
- const shared = junctionLng === openingLng && junctionLat === openingLat;
1829
- return headVias.length + tailVias.length - (shared ? 1 : 0);
1830
- };
1831
- var exceedsMergeViaCeiling = (head, tail) => head.mode === "directions" && mergedViaCount(head, tail) > DIRECTIONS_VIA_MAX;
1832
-
1833
- // src/segments/rules/splitPick.ts
1834
- var splitPickVerdict = (geojson, lngLat, toleranceMeters) => {
1835
- const projection = projectOnSegment(geojson, lngLat);
1836
- if (!projection) {
1837
- return { code: "invalid-input", ok: false };
1838
- }
1839
- if (!(projection.distanceMeters <= toleranceMeters)) {
1840
- return { code: "split-too-far", ok: false, projection };
1841
- }
1842
- const { fraction } = projection;
1843
- if (isSplitOnEnd(geojson, fraction)) {
1844
- return { code: "split-on-end", ok: false, projection };
1845
- }
1846
- return { fraction, ok: true, projection };
1847
- };
1848
- var isSplitOnEnd = (geojson, fraction) => {
1849
- const lengthMeters = segmentLengthMeters(geojson);
1850
- const headMeters = lengthMeters * fraction;
1851
- return fraction <= 0 || fraction >= 1 || headMeters < SPLIT_MIN_END_DISTANCE_METERS || lengthMeters - headMeters < SPLIT_MIN_END_DISTANCE_METERS;
1852
- };
1853
- var resolveViewerUnits = (preferences) => ({
1854
- language: preferences?.language || defaultUnits.language,
1855
- length: preferences?.length ?? defaultUnits.length,
1856
- pace: preferences?.pace ?? defaultUnits.pace,
1857
- slope: preferences?.slope ?? defaultUnits.slope,
1858
- temperature: preferences?.temperature ?? defaultUnits.temperature
1859
- });
1860
-
1861
- // src/waypoints/rules/defaults.ts
1862
- var makeWaypointId = (ids = studioSeamAbsences.ids) => ids.next();
1863
-
1864
- // src/itinerary/handlers/restItineraryRecord.ts
1865
- var fetchItineraryRecord = async (client, itineraryId, surface) => {
1866
- const body = await client.studio.itineraries.getItinerary({
1867
- itinerary_id: itineraryId,
1868
- query: surface === "published" ? { surface: "published" } : void 0
1869
- });
1870
- return withItineraryAnalysis(body.data);
1871
- };
1872
-
1873
- // src/itinerary/rules/lngLat.ts
1874
- var lngLatOf = (position) => {
1875
- const [lng, lat] = position ?? [];
1876
- return lng !== void 0 && lat !== void 0 && Number.isFinite(lng) && Number.isFinite(lat) ? [lng, lat] : null;
1877
- };
1878
-
1879
- // src/data/rules/uuid.ts
1880
- var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1881
- var hasUuidShape = (value) => uuidPattern.test(value);
1882
-
1883
- // src/data/rules/requestBody.ts
1884
- var declaredBody = (value, fields) => {
1885
- const body = {};
1886
- for (const key of Object.keys(fields)) {
1887
- const member = Reflect.get(value, key);
1888
- if (Object.hasOwn(value, key) && member !== void 0) {
1889
- body[key] = member;
1890
- }
1891
- }
1892
- return body;
1893
- };
1894
-
1895
- export { ALLOWLIST_WILDCARD, HILLSHADE_OVERLAY_SLUG, SPLIT_PICK_GESTURE, SegmentDeleteNotEdgeError, ToolBus, allowlistForMode, allowlistMode, allowlistUnrestricted, clampConfigToSafetyRules, classicOverlays, collectAttributions, confirmationToneSchema, contiguousRunBounds, createUiStore, createdIdOf, declaredBody, describeInvalidInput, directionsTargetSchema, draftSessionIdentity, draftSurfaceNames, embedUiBaseline, enrichmentOverlays, exceedsMergeViaCeiling, fetchItineraryRecord, filterEnrichmentOverlays, filterOverlayCategories, filterTerrains, findHillshadeOverlay, hasErrorCode, hasUuidShape, holdDraftWrite, holdDuringDraftCommit, holdDuringPreview, holdShowingDraft, holdsDraftSession, isAnswerUnavailable, isContiguousRun, isFieldRestricted, isKeyInUse, isPreconditionFailed, isRevisionConflict, isSegmentDeleteNotEdge, isSplitOnEnd, isZoneWorkUnsaved, lngLatOf, makeWaypointId, reconcileMadeWrite, registerStudioTools, resolveViewerUnits, rethrowSegmentWriteError, selectActiveDraft, selectActiveDraftSession, selectAgentHandoffArmed, selectBaseMapLocked, selectDirections, selectEditDirtyTick, selectEditorTakenBy, selectEmbed, selectEmbedContent, selectImportSession, selectProfilePaceKmh, selectProfileSheetSnap, selectSegmentViaPrompt, selectSelectedSuggestionCandidate, selectShare, selectUnsavedWork, selectVideoExport, selectVideoExportPlan, selectVideoExportRoute, selectVideoExportStatus, selectWaypointDetails, selectZoneCreateSetup, selectZoneEditDirty, showingDraft, showingDraftSession, showingDraftSurface, splitPickVerdict, studioRegistry, toggleableSegmentIds, toolCapabilitySchema, toolConfirmationSchema, toolErrorCodeSchema, withItineraryAnalysis, withSegmentAnalysis };
1896
- //# sourceMappingURL=chunk-H4DVOZ5O.js.map
1897
- //# sourceMappingURL=chunk-H4DVOZ5O.js.map