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