@mountaya/client 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +1260 -2
  5. package/dist/admin/index.cjs +2895 -0
  6. package/dist/admin/index.cjs.map +1 -0
  7. package/dist/admin/index.d.cts +889 -0
  8. package/dist/admin/index.d.ts +889 -0
  9. package/dist/admin/index.js +204 -0
  10. package/dist/admin/index.js.map +1 -0
  11. package/dist/browser.cjs +5993 -0
  12. package/dist/browser.cjs.map +1 -0
  13. package/dist/browser.d.cts +70 -0
  14. package/dist/browser.d.ts +70 -0
  15. package/dist/browser.js +22 -0
  16. package/dist/browser.js.map +1 -0
  17. package/dist/chunk-CeEX7ayk.d.cts +75531 -0
  18. package/dist/chunk-CeEX7ayk.d.ts +75531 -0
  19. package/dist/chunk-Cg7Dtcb4.js +2987 -0
  20. package/dist/chunk-Cg7Dtcb4.js.map +1 -0
  21. package/dist/chunk-DJqUsgsy.d.ts +1463 -0
  22. package/dist/chunk-DNc8T5K1.js +241 -0
  23. package/dist/chunk-DNc8T5K1.js.map +1 -0
  24. package/dist/chunk-DTxzw3hu.d.cts +1463 -0
  25. package/dist/chunk-DmxQID5X.js +2289 -0
  26. package/dist/chunk-DmxQID5X.js.map +1 -0
  27. package/dist/chunk-DoZt_oIV.d.ts +3991 -0
  28. package/dist/chunk-DpJrqANO.js +11 -0
  29. package/dist/chunk-Dx8mPAdC.d.cts +3991 -0
  30. package/dist/chunk-X2ukY3ho.js +419 -0
  31. package/dist/chunk-X2ukY3ho.js.map +1 -0
  32. package/dist/events/index.cjs +1436 -0
  33. package/dist/events/index.cjs.map +1 -0
  34. package/dist/events/index.d.cts +772 -0
  35. package/dist/events/index.d.ts +772 -0
  36. package/dist/events/index.js +543 -0
  37. package/dist/events/index.js.map +1 -0
  38. package/dist/index.cjs +5992 -0
  39. package/dist/index.cjs.map +1 -0
  40. package/dist/index.d.cts +44 -0
  41. package/dist/index.d.ts +44 -0
  42. package/dist/index.js +21 -0
  43. package/dist/index.js.map +1 -0
  44. package/package.json +126 -4
  45. package/src/admin/index.ts +47 -0
  46. package/src/admin/rules/mountayaAdmin.ts +102 -0
  47. package/src/browser.ts +233 -0
  48. package/src/core/engines/sessionToken.ts +870 -0
  49. package/src/core/rules/auth.ts +1017 -0
  50. package/src/core/rules/clientHeader.ts +28 -0
  51. package/src/core/rules/dates.ts +200 -0
  52. package/src/core/rules/decode.ts +154 -0
  53. package/src/core/rules/envelope.ts +41 -0
  54. package/src/core/rules/errors.ts +1486 -0
  55. package/src/core/rules/graphql.ts +576 -0
  56. package/src/core/rules/headerValue.ts +42 -0
  57. package/src/core/rules/idempotencyKey.ts +64 -0
  58. package/src/core/rules/nullMask.ts +127 -0
  59. package/src/core/rules/nullMasks.gen.ts +428 -0
  60. package/src/core/rules/paginate.ts +316 -0
  61. package/src/core/rules/rateLimit.ts +507 -0
  62. package/src/core/rules/redaction.ts +219 -0
  63. package/src/core/rules/resourceRef.ts +110 -0
  64. package/src/core/rules/responseBody.ts +492 -0
  65. package/src/core/rules/retry.ts +386 -0
  66. package/src/core/rules/selection.ts +416 -0
  67. package/src/core/rules/sessionAnswer.ts +90 -0
  68. package/src/core/rules/sessionSchedule.ts +131 -0
  69. package/src/core/rules/sessionWait.ts +112 -0
  70. package/src/core/rules/transport.ts +2386 -0
  71. package/src/core/rules/version.gen.ts +16 -0
  72. package/src/core/rules/webAddress.ts +165 -0
  73. package/src/core/rules/webAddresses.gen.ts +30 -0
  74. package/src/data/operations.gen.ts +603 -0
  75. package/src/data/schema.gen.ts +8078 -0
  76. package/src/data/selection.gen.ts +472 -0
  77. package/src/events/index.ts +63 -0
  78. package/src/events/rules/agent.ts +439 -0
  79. package/src/events/rules/collab.ts +554 -0
  80. package/src/events/rules/collabNulls.gen.ts +17 -0
  81. package/src/events/rules/eventStream.ts +94 -0
  82. package/src/events/rules/openSseStream.ts +594 -0
  83. package/src/events/rules/sse.ts +349 -0
  84. package/src/index.ts +231 -0
  85. package/src/rest/adminOperations.gen.ts +70 -0
  86. package/src/rest/adminResources.gen.ts +138 -0
  87. package/src/rest/coreOperations.gen.ts +74 -0
  88. package/src/rest/coreResources.gen.ts +244 -0
  89. package/src/rest/dates.gen.ts +217 -0
  90. package/src/rest/operations.gen.ts +4341 -0
  91. package/src/rest/resources.gen.ts +371 -0
  92. package/src/rest/schema.gen.ts +57027 -0
  93. package/src/tiles/operations.gen.ts +206 -0
  94. package/src/tiles/schema.gen.ts +8406 -0
  95. package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
  96. package/src/webhooks/rules/webhookEvent.ts +38 -0
  97. package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
package/README.md CHANGED
@@ -1,3 +1,1261 @@
1
- # Temporary Holding Version
1
+ # @mountaya/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Mountaya API client for JavaScript and TypeScript: the Map Studio API, the Tile API and the
4
+ GraphQL Data API behind one credential. Runs in Node, browsers, workers and React Native, as one
5
+ artifact with no runtime dependencies.
6
+
7
+ ```bash
8
+ npm install @mountaya/client
9
+ ```
10
+
11
+ ## Quickstart
12
+
13
+ ```ts
14
+ import { Mountaya } from "@mountaya/client";
15
+
16
+ const mountaya = new Mountaya({
17
+ credential: { publishableKey: "pk_…" },
18
+ });
19
+
20
+ const { data } = await mountaya.studio.itineraries.getItineraries({ query: { limit: 10 } });
21
+ ```
22
+
23
+ In a browser, import from `@mountaya/client/browser`: the same client, with no secret-key credential
24
+ to leak ([Keeping the secret key out of your bundle](#keeping-the-secret-key-out-of-your-bundle)).
25
+
26
+ Every timestamp the contract declares comes back as a real `Date`, and every other string stays a
27
+ string: a name that happens to be a timestamp is still a name. There is nothing to parse.
28
+
29
+ ## A program you can run
30
+
31
+ No bundler, no DOM, no framework: `node src/main.ts`, on Node's own TypeScript support (Node
32
+ 22.18 or later, the packages' floor).
33
+
34
+ <!-- example: examples/client-node/src/main.ts -->
35
+ ```ts
36
+ import { isMountayaApiError, Mountaya } from "@mountaya/client";
37
+ import { MountayaAdmin } from "@mountaya/client/admin";
38
+
39
+ const publishableKey = process.env.MOUNTAYA_PUBLISHABLE_KEY;
40
+ const secretKey = process.env.MOUNTAYA_SECRET_KEY;
41
+ if (publishableKey === undefined || secretKey === undefined) {
42
+ throw new Error("Set MOUNTAYA_PUBLISHABLE_KEY (pk_…) and MOUNTAYA_SECRET_KEY (sk_…).");
43
+ }
44
+
45
+ try {
46
+ // A server holds the secret key, and mints with it the session token the Data API requires
47
+ // beside the publishable key on every request. The token lives minutes, not days. Minting is
48
+ // the admin unit's, which the server imports beside the client.
49
+ const server = new Mountaya({ credential: { secretKey } });
50
+ const { data: session } = await new MountayaAdmin(server).sessions.postSession({
51
+ body: { publishable_key: publishableKey },
52
+ });
53
+
54
+ const mountaya = new Mountaya({ credential: { publishableKey, sessionToken: session.token } });
55
+
56
+ // Map Studio API. The most recently updated itineraries first, and `updated_at` is a Date:
57
+ // nothing here parses a string.
58
+ const { data: itineraries } = await mountaya.studio.itineraries.getItineraries({
59
+ query: { limit: 5, sort: "-updated_at" },
60
+ });
61
+
62
+ for (const itinerary of itineraries) {
63
+ console.log(`${itinerary.name}, updated ${itinerary.updated_at.toISOString()}`);
64
+ }
65
+
66
+ // Data API. `select` asks for two fields instead of the default full selection, which is
67
+ // the difference between a summary and every coordinate's elevation.
68
+ const { routes } = await mountaya.data.directions(
69
+ {
70
+ activity: "HIKING_AND_TRAIL",
71
+ waypoints: [
72
+ [6.8652, 45.9237],
73
+ [6.9106, 45.901],
74
+ ],
75
+ },
76
+ { select: { routes: { distance: true, duration: true } } },
77
+ );
78
+
79
+ // The API answers in meters and seconds, and the program prints them as they arrive.
80
+ for (const route of routes) {
81
+ console.log(`${Math.round(route.distance)} m in ${Math.round(route.duration)} s`);
82
+ }
83
+ } catch (error) {
84
+ // The platform reported it, so it carries a status and the envelope's own messages. Read by
85
+ // the name its class declares, so an error from a second copy of the package classifies too.
86
+ if (isMountayaApiError(error)) {
87
+ console.error(`${error.status} ${error.code ?? ""}`.trim());
88
+ for (const entry of error.errors) {
89
+ console.error(` ${entry.path?.join(".") ?? "-"}: ${entry.message}`);
90
+ }
91
+ process.exitCode = 1;
92
+ } else {
93
+ throw error;
94
+ }
95
+ }
96
+ ```
97
+
98
+ `examples/client-node/README.md` says what it is for and how to run it.
99
+
100
+ ## Three surfaces
101
+
102
+ ```ts
103
+ // Map Studio API, the map: itineraries, zones, collections, and their catalogs.
104
+ const { data } = await mountaya.studio.itineraries.getItinerary({ itinerary_id });
105
+
106
+ // Data API: routing, search, terrain, isochrones, matrices.
107
+ const route = await mountaya.data.directions({
108
+ activity: "HIKING_AND_TRAIL",
109
+ waypoints: [[6.8652, 45.9237], [6.9106, 45.9010]],
110
+ });
111
+
112
+ // Tile API: the style specification a map library renders from.
113
+ const spec = await mountaya.tiles.getItinerarySpecification({ itinerary_id });
114
+ // `source.tiles` carries the {z}/{x}/{y} URL templates. Hand them to your map library.
115
+ const [template] = spec.data.sources[0].tiles;
116
+ ```
117
+
118
+ The Map Studio API's map half arrives as `studio`, and the organization the map is rendered for
119
+ is [the admin unit](#managing-an-organization)'s, imported apart: one edits a route, the other
120
+ configures who may edit it. Which namespace and which unit an operation belongs to is declared in
121
+ [the contract](https://github.com/mountaya/schemas), so every language's client divides it the
122
+ same way. Method names are the contract's `operationId` verbatim, and each method's doc comment
123
+ names the publishable-key scope it needs, so a 403 tells you which scope to enable.
124
+
125
+ Every resource, params and enum type of the core's Map Studio surface is exported from the package
126
+ root, so you can name what an operation hands you without reaching through a namespace, and every
127
+ one only the admin unit reaches is exported from `@mountaya/client/admin`:
128
+
129
+ ```ts
130
+ import type { ItineraryWithDetails, ZoneCreateParams } from "@mountaya/client";
131
+ import type { OrganizationSettingsPatchParams } from "@mountaya/client/admin";
132
+ ```
133
+
134
+ Both lists are generated from the contract, which states the unit of each type, so they never lag
135
+ an operation. Tile and Data API types
136
+ stay behind `TileSchema` and `DataSchema`, since many of their names collide with Map Studio
137
+ ones. `RestSchema` holds the raw `paths`, `components` and `operations` shapes for anyone
138
+ generating on top of this package.
139
+
140
+ The answer of each Data API operation is the exception: `GeocodeResult`, `DirectionsResult`,
141
+ `SearchResult` and the others are exported from the package root as well as under `DataSchema`,
142
+ so a library that emits declarations can hand an answer on without writing its type:
143
+
144
+ ```ts
145
+ // Compiles under `declaration: true` with no return type written.
146
+ export const findPlaces = (query: string) => mountaya.data.geocode({ query });
147
+ ```
148
+
149
+ A type inside an answer, such as `DataSchema.Place`, has no name at the root, so an export that
150
+ infers one states it: `(): Promise<DataSchema.Place | undefined> => …`. A Map Studio answer that
151
+ holds a geometry names the GeoJSON `Geometry`, which the root exports too.
152
+
153
+ The Data API is GraphQL, and you never write a query. Every operation is a typed method that
154
+ sends a generated full-selection document, so the result comes back complete and typed.
155
+
156
+ The itinerary export answers no JSON, and resolves to a `BinaryBody` carrying the bytes and the
157
+ two headers that describe them:
158
+
159
+ ```ts
160
+ const { bytes, contentType, filename } = await mountaya.studio.itineraries.getItineraryExport({
161
+ itinerary_id,
162
+ query: { format: "gpx" },
163
+ });
164
+ // filename is the name the platform chose: the itinerary's, in your Accept-Language,
165
+ // with the right extension. Content-Disposition is parsed for you, both RFC forms.
166
+ ```
167
+
168
+ The Tile API surfaces specifications only. A tile is not something you fetch: the specification
169
+ hands back each source's URL template with the `{z}`, `{x}` and `{y}` placeholders intact, and a
170
+ map library expands and requests them on its own schedule, which is also the only way the
171
+ credential gets attached. The routes are documented in
172
+ [the Tile API reference](https://docs.mountaya.com/en/tile-api/reference/), and their types stay
173
+ exported under `TileSchema`. To render those tiles on a map, use `@mountaya/elements`
174
+ ([Rendering maps](#rendering-maps)).
175
+
176
+ ### What a method resolves to
177
+
178
+ A Map Studio API or Tile API method resolves to the response **envelope**, with the payload at
179
+ `data`. `extensions.metadata` sits beside it on the operations that document one: the
180
+ `pagination` of a listing, the id of a part a write created, or the work an operation started
181
+ where it answers before that work is done. A write answers the resource whose read it changed,
182
+ and one that removes something and has nothing left to answer resolves to `data: null`.
183
+
184
+ ```ts
185
+ const { data: itinerary } = await mountaya.studio.itineraries.getItinerary({ itinerary_id });
186
+ const { data: itineraries, extensions } = await mountaya.studio.itineraries.getItineraries({
187
+ query: { limit: 10 },
188
+ });
189
+
190
+ console.log(itinerary.etag, itineraries.length, extensions?.metadata?.pagination?.next_cursor);
191
+ ```
192
+
193
+ A resource a write can be made conditional on carries its `etag`, the tag a later write sends
194
+ back as `ifMatch` ([Concurrency](#concurrency)).
195
+
196
+ `MountayaResponse<T>` names the envelope, for a function written over any method's answer:
197
+
198
+ ```ts
199
+ import type { MountayaResponse } from "@mountaya/client";
200
+
201
+ function payloadOf<T>(response: MountayaResponse<T>): T {
202
+ return response.data;
203
+ }
204
+
205
+ const itinerary = payloadOf(await mountaya.studio.itineraries.getItinerary({ itinerary_id }));
206
+ ```
207
+
208
+ A Data API method resolves to the operation's **own field**, with nothing around it, and an
209
+ answer that lacks the field rejects with `MountayaDataError` where a generic GraphQL client hands
210
+ back `undefined`:
211
+
212
+ ```ts
213
+ const { routes } = await mountaya.data.directions({
214
+ activity: "HIKING_AND_TRAIL",
215
+ waypoints: [[6.8652, 45.9237], [6.9106, 45.9010]],
216
+ });
217
+ ```
218
+
219
+ ## Managing an organization
220
+
221
+ The organization behind the map is the admin unit's: its settings, publishable keys, members,
222
+ invitations, usage, billing and webhook endpoints, the acting user's own memberships and
223
+ preferences, and minting a session token. It is `@mountaya/client/admin`, a subpath of this
224
+ package, so there is nothing more to install, and an application that draws a map, edits an
225
+ itinerary or reads the Data API never imports it. `MountayaAdmin` is built over the client, of
226
+ either entry point, and holds its operations bound to that client's credential, retries and error
227
+ classes:
228
+
229
+ ```ts
230
+ import { MountayaAdmin } from "@mountaya/client/admin";
231
+
232
+ const { data: members } = await new MountayaAdmin(mountaya).members.getOrganizationMembers({
233
+ organization_id,
234
+ });
235
+ ```
236
+
237
+ A method resolves to the response envelope, as a Map Studio method of the client does, and a
238
+ second `MountayaAdmin` over the same client holds the same operations, bound once, so building one
239
+ where it is needed costs nothing. Each method's doc comment names what it
240
+ takes: the organization's operations the `management` scope and a session token beside the key, the
241
+ acting user's own reads and writes under `/v1/me` the `studio-embedded` scope and a session token,
242
+ and `postSession` the secret key alone ([Minting a session token](#minting-a-session-token)). The
243
+ unit also receives webhooks ([Receiving webhooks](#receiving-webhooks)), and names every type only
244
+ its operations and its events reach.
245
+
246
+ ## Authentication
247
+
248
+ The credentials compose differently, and each row below says how. Getting this wrong is the most
249
+ common cause of a 401.
250
+
251
+ | Credential | Use it for | Notes |
252
+ |---|---|---|
253
+ | `publishableKey` (`pk_`) | Browser and embedding access | Safe to ship to a client, except a key carrying `management`, which never ships |
254
+ | `sessionToken` (`sess_`) | Scoping a publishable key up to an organization, and naming the user a call acts as | **Accompanies** the key, never replaces it |
255
+ | `secretKey` (`sk_`) | Minting session tokens, server-side only | Never send to a browser |
256
+ | `shareToken` (`share_`) | A share link visitor | **Replaces** the key; read-only |
257
+
258
+ ```ts
259
+ // Public data on the Map Studio and Tile APIs, from anywhere.
260
+ new Mountaya({ credential: { publishableKey: "pk_…" } });
261
+
262
+ // Organization-scoped, in a browser. Mint the token on your server. Every Data API call
263
+ // needs one, as do the `agent` operations and nearly every operation of the admin unit.
264
+ new Mountaya({ credential: { publishableKey: "pk_…", sessionToken } });
265
+ ```
266
+
267
+ The session token is also who a call acts as: your server mints it with `postSession`'s `user_id`
268
+ set to the person signed in, and every request made with it acts as that person. No header names a
269
+ user. An operation that acts as a member (every `studio-embedded` operation, every `management`
270
+ write, every read under `/v1/me`) is answered with a `401` under a token minted without `user_id`,
271
+ so a token minted without `user_id` reads and never writes
272
+ ([The user a call acts as](#the-user-a-call-acts-as)).
273
+
274
+ The client reads what each operation declares and refuses a credential that cannot meet it before
275
+ anything is sent, with a `MountayaConfigurationError` naming the operation: a secret key anywhere
276
+ but `postSession`, a share token where the operation accepts none, no session token where one is
277
+ required, and a token a `SessionTokenEngine` reports as minted without `user_id` where the operation
278
+ acts as a member. The API would answer each with a `401` or a `400` that names none of those
279
+ rules. Only a key's prefix is checked here, so a key that is well-formed but wrong reaches the API.
280
+
281
+ The credential is checked at construction, and one that cannot work throws a
282
+ `MountayaConfigurationError` naming the member and what is wrong; no key or token is quoted. An
283
+ empty or blank key reads as none, which is what an unset environment variable leaves.
284
+ `{ cookie: true }` is a credential of its own, the browser's session (your own sign-in, or a
285
+ gateway on your origin that attaches the real credential); a key credential sends no cookie,
286
+ whatever origin the API is reached at.
287
+
288
+ ### Minting a session token
289
+
290
+ ```ts
291
+ // On your server, and only there.
292
+ import { Mountaya } from "@mountaya/client";
293
+ import { MountayaAdmin } from "@mountaya/client/admin";
294
+
295
+ const secretKey = process.env.MOUNTAYA_SECRET_KEY;
296
+ if (secretKey === undefined) {
297
+ throw new Error("MOUNTAYA_SECRET_KEY is not set.");
298
+ }
299
+
300
+ const server = new Mountaya({ credential: { secretKey } });
301
+ const { data } = await new MountayaAdmin(server).sessions.postSession({
302
+ body: { publishable_key: "pk_…", user_id: userId },
303
+ });
304
+ // Send data.token to the browser. It is short-lived, carries data.expires_at, and names the
305
+ // user it was minted for at data.user_id.
306
+ ```
307
+
308
+ `user_id` is the member the browser acts as, the user your own sign-in vouches for: read it from
309
+ your server's session, never from the request, since a token minted for it lets a page act as
310
+ that member. It must belong to the key's organization, or hold an invitation to it, and any other
311
+ is a `403`. Leave it out for a token that reads and never writes: it reaches the operations that
312
+ act as nobody, and reads content as the key alone does, served what the organization has published
313
+ and never a draft; only such a token for `api` reaches the `management` reads. A `user_id` refused
314
+ with a `403` is held to a rate limit of its own, so minting for somebody who has left never locks
315
+ out the tokens minted for everybody else.
316
+
317
+ `surface` names what the token is for, and the token keeps it for its whole life. Left out, it
318
+ is `api`, the surface of your own clients, whose Data API and Tile API requests count toward the
319
+ organization's limits, allowances and invoice. A token for an Embedded Studio, the editor and its
320
+ read-only viewer alike, is minted with `surface: "studio-embedded"`: it is the only token a
321
+ `studio-embedded` operation accepts, a studio refuses any other before it sends a request, and
322
+ what the studio asks of the Data API and the Tile API is recorded apart and never counted. It is
323
+ minted only for a key that reaches the `studio-embedded` scope, and any other key is a `403`.
324
+
325
+ ```ts
326
+ import { Mountaya } from "@mountaya/client";
327
+ import { MountayaAdmin } from "@mountaya/client/admin";
328
+
329
+ declare const server: Mountaya;
330
+ declare const userId: string;
331
+
332
+ const { data } = await new MountayaAdmin(server).sessions.postSession({
333
+ body: { publishable_key: "pk_…", surface: "studio-embedded", user_id: userId },
334
+ });
335
+ ```
336
+
337
+ ### Following a session token that rotates
338
+
339
+ A session token lives minutes. Hand the client a `SessionTokenEngine` as its `sessionToken`: the
340
+ engine mints through your endpoint, which holds the secret key, and refreshes each token before
341
+ it expires, and the client reads the token it holds at each request, each event-stream open and
342
+ each tile a map built on the client asks for. The client stays one object across every refresh.
343
+
344
+ ```ts
345
+ import { Mountaya, SessionTokenEngine } from "@mountaya/client/browser";
346
+
347
+ // An answer that is not a success rejects, so the engine reports it as `error` and asks again
348
+ // on its schedule.
349
+ const session = new SessionTokenEngine({
350
+ mint: async () => {
351
+ const response = await fetch("/api/mountaya-session");
352
+ if (!response.ok) {
353
+ throw new Error(`The session endpoint answered ${response.status}.`);
354
+ }
355
+
356
+ return response.json();
357
+ },
358
+ });
359
+ // The engine refreshes while something subscribes to it: hold it for the page's life.
360
+ session.subscribe(() => undefined);
361
+
362
+ const mountaya = new Mountaya({
363
+ credential: { publishableKey: "pk_…", sessionToken: session },
364
+ });
365
+ ```
366
+
367
+ A request made while the engine has a mint out and holds no token waits for that mint, bounded by
368
+ the call's `signal` and its `timeoutMs`, and goes out with the token it lands, so a page's first
369
+ reads carry the session rather than going out under the key alone. A request made while nobody
370
+ holds the engine starts its mint the same way. Once the wait ends with no token (the mint
371
+ failed, or minting is disabled), a call that requires a session is refused with a
372
+ `MountayaConfigurationError` whose `cause` is the mint's error, and any other goes out under the
373
+ key alone. In React, `useSessionToken` from `@mountaya/client-react` holds the engine for you.
374
+
375
+ A mint that fails, or times out, is asked again on the engine's schedule: five seconds later, each
376
+ failure in a row waiting twice as long as the last, up to a minute. Each mint is handed the abort
377
+ controller it runs under: hand its `signal` to your request, and abort it to cancel the mint, with
378
+ a reason of your own or none. A mint your application cancels so, or one that rejects with an
379
+ `AbortError`, ends that run of minting: nothing is asked again until a `refresh()`, a new
380
+ subscriber or `setEnabled(true)`.
381
+
382
+ ```ts
383
+ import { SessionTokenEngine } from "@mountaya/client";
384
+
385
+ const engine = new SessionTokenEngine({
386
+ mint: async (call) => {
387
+ const response = await fetch("/api/mountaya-session", { signal: call.signal });
388
+
389
+ return response.json();
390
+ },
391
+ });
392
+ ```
393
+
394
+ The credential a client keeps and a `SessionTokenEngine` snapshot print a session token, a share
395
+ token or a secret key by its prefix alone (`sess_…`), in `JSON.stringify`, `String` and
396
+ `console.log`, and still read it whole. A parsed answer is a plain object, so a returned `Session`,
397
+ `WebhookEndpointWithSecret`, `SetupIntentSession` or `ShareLink` prints every member, its secret
398
+ included: that is this SDK's divergence from the contract's rule that no SDK prints a field the
399
+ model marks secret.
400
+
401
+ `sessionToken` also takes a function, called at each read, for a token kept by other means.
402
+
403
+ ### The user a call acts as
404
+
405
+ A publishable key belongs to an organization rather than to a person, so the person a call acts as
406
+ is the one its session token was minted for. The engine reports that user, from its mint's
407
+ `user_id`, as `userId` in its snapshot, and a client holding it knows whom it acts as:
408
+
409
+ ```ts
410
+ const mountaya = new Mountaya({ credential: { publishableKey: "pk_…", sessionToken: session } });
411
+
412
+ // true under a token minted for a user, false under one minted without `user_id` (the studio
413
+ // then offers no writes), undefined where the client is not told.
414
+ mountaya.transport.actsAsMember;
415
+ ```
416
+
417
+ Where the person changes (a sign-in, an account switch, a sign-out), mint for the new person: the
418
+ client stays the same object. Its `credentialScope`, which keys a query cache, names the user the
419
+ engine reports, so one page that switches account serves nobody what the person before them read;
420
+ a refresh for the same person evicts nothing, and an answer read under the key alone is never
421
+ served to a reader holding a session. A token held as a string keys the cache by the token itself,
422
+ and one held as a function by its presence alone, since the client is not told whom either names.
423
+
424
+ Until the engine's first token lands, the scope names a session and not yet its user, and
425
+ `credentialScopePending` is true. That token refines the scope of the same credential rather than
426
+ replacing it, so a cache holds its reads until the flag turns false and keys each read once, under
427
+ the user the token names. Holding them costs nothing, since a request made before waits for that
428
+ token anyway. `@mountaya/client-react` does so for every read it makes. `subscribeCredentialScope`
429
+ tells a listener each time the scope or its pending flag moves, which is when `actsAsMember` is
430
+ worth reading again.
431
+
432
+ ### Keeping the secret key out of your bundle
433
+
434
+ `@mountaya/client/browser` does not export the secret-key credential at all: its `Mountaya` and
435
+ its `MountayaTransport` take `BrowserClientOptions`, where `{ secretKey }` is a type error. Import
436
+ from it in every browser bundle, a worker's included.
437
+
438
+ ```ts
439
+ import { Mountaya } from "@mountaya/client/browser";
440
+ ```
441
+
442
+ And if a bundler resolves the Node entry into a page anyway, constructing a client with an `sk_`
443
+ where `window` and `document` exist throws `MountayaConfigurationError` rather than shipping the
444
+ key, and so does constructing one in a React Native application, whose bundle every device that
445
+ installs it holds and which resolves no browser entry. A worker holds neither, so the browser
446
+ entry is a worker's defence.
447
+
448
+ The package declares no `browser` export condition that would hand a bundler the browser entry
449
+ under the root specifier, because every condition it publishes is one no toolchain sets on its
450
+ own. `browser` is one several set by default, for a client build and for some server renders and
451
+ test environments as well, so it would swap the entry, and take away the secret-key credential a
452
+ server mints with, wherever a toolchain chose to set it rather than where you asked. Import
453
+ `@mountaya/client/browser` by name in a page's bundle instead: the choice is then yours, and a
454
+ type error says where it was missed.
455
+
456
+ ## Errors
457
+
458
+ Every failure is a typed class. A `402` says something about the organization's agreement:
459
+
460
+ ```ts
461
+ import {
462
+ MountayaBillingError, // 402: a product the organization does not hold, or billing details to complete.
463
+ MountayaForbiddenError, // 403: a missing scope, another organization, a calling page or a role not allowed.
464
+ MountayaRateLimitError, // 429: a limit or a monthly allowance is spent, or a ceiling (LIMIT_REACHED) is reached.
465
+ } from "@mountaya/client";
466
+
467
+ try {
468
+ await mountaya.studio.itineraries.postItinerary({
469
+ body: { activity_id, is_private: true, name: "Tour du Mont Blanc" },
470
+ });
471
+ } catch (error) {
472
+ if (error instanceof MountayaBillingError) {
473
+ return showAgreementNotice(error);
474
+ }
475
+ throw error;
476
+ }
477
+ ```
478
+
479
+ A 402 is answered by changing the agreement or its billing details, not in code: its message names
480
+ the fact in the API's words, and where each remedy is taken. A product of the agreement is changed
481
+ with Mountaya ([talk to us](https://mountaya.com/en/contact/)), and a missing payment method is
482
+ added, or an invoice still owed paid, in the organization's billing settings. Its entry carries
483
+ `PAYMENT_REQUIRED`, which `PAYMENT_REQUIRED_CODE` names. On the Data API it is also how a
484
+ self-serve organization is refused that has no payment method on file, or that still owes invoices
485
+ its payment method could not pay, which keep its subscription from opening.
486
+
487
+ A `429` names its wait in `Retry-After`. A per-minute limit names the seconds left in its
488
+ minute, which the client waits out within the call's budget before it asks again
489
+ ([Retries](#retries)). A spent daily bound names the seconds until the next UTC day, and a spent
490
+ monthly allowance the seconds until the organization's next billing period begins. No budget waits
491
+ for either: the error arrives at once, and retrying it yourself before then is refused again. Read
492
+ `error.retryAfter` and stop calling the surface until it has passed.
493
+
494
+ A ceiling is a `429` too, told apart by its code: `error.hasCode("LIMIT_REACHED")`. It is the seats,
495
+ the published itineraries or the published zones the agreement allows, the invitations an
496
+ organization may have waiting at once, or the itineraries a personal space keeps, and
497
+ `error.metadata` names it as `{ limit, allowed, used }`. It names no wait, so `error.retryAfter` is
498
+ undefined, and the client never repeats it: free a place, or change the agreement with Mountaya.
499
+
500
+ A `412` is a `MountayaPreconditionFailedError`: a conditional write whose `ifMatch` names a tag
501
+ the resource no longer carries ([Concurrency](#concurrency)). Two `409`s answer a write's
502
+ `Idempotency-Key` rather than the write, and each raises a `MountayaConflictError` of its own
503
+ ([Idempotency](#idempotency)): one coded `IDEMPOTENCY_KEY_IN_USE`, which the client asks again
504
+ itself until its wait budget is spent, is a `MountayaIdempotencyKeyInUseError`, the first request
505
+ still running; one coded `IDEMPOTENCY_ANSWER_UNAVAILABLE` is a
506
+ `MountayaIdempotentAnswerUnavailableError`, which says the opposite of every other `409`: the
507
+ write was made, so re-read the resource rather than sending it again.
508
+
509
+ Where a thrown value may come from a second copy of this package (resolved once as ESM and once
510
+ as CJS, or installed twice), `instanceof` answers false against the other copy's classes.
511
+ `isMountayaError` and `isMountayaApiError` classify by the name each class declares instead: the
512
+ first answers for every failure this package raises, and the second for a failure the platform
513
+ answered, which carries `status`, `code` and `errors`.
514
+
515
+ Every API error carries `status`, `errors` (the platform's own messages) and `code`. An entry
516
+ about one field says which: on REST and the Tile API as `path`, from the root of the request
517
+ (`["request", "body", "name"]`), and on the Data API as `extensions.path`, from the root of the
518
+ input (`["input", "waypoints", 0]`). Where the response sends one, an API error also carries
519
+ `metadata`, the envelope's `extensions.metadata` as sent: a `409` refused by a collaborator's lock
520
+ names the member holding it. It carries the answer's `requestId` and `rateLimit` too
521
+ ([Request ids](#request-ids), [Rate limits](#rate-limits)), and `retryAfter`, the whole seconds
522
+ its `Retry-After` named, whatever its status.
523
+
524
+ ```ts
525
+ import { isMountayaApiError } from "@mountaya/client";
526
+
527
+ try {
528
+ await mountaya.studio.itineraries.postItineraryPublication({ itinerary_id });
529
+ } catch (error) {
530
+ const holder = isMountayaApiError(error) ? error.metadata?.holder : undefined;
531
+ if (typeof holder === "object" && holder !== null && "id" in holder) {
532
+ console.warn(`A collaborator holds the lock: ${String(holder.id)}`);
533
+ }
534
+ }
535
+ ```
536
+
537
+ Every class of the family is built as `(message, status, errors, details)`, where `details` is an
538
+ `ApiErrorDetails` (`etag`, `idempotencyKey`, `metadata`, `rateLimit`, `requestId`,
539
+ `retryAfter`), and `errorForStatus` picks
540
+ the class a status maps to, which is what a test double answering as the API would writes:
541
+
542
+ ```ts
543
+ import { errorForStatus, MountayaRateLimitError } from "@mountaya/client";
544
+
545
+ const limited = errorForStatus("getItinerary: 429 RATE_LIMITED", 429, [], { retryAfter: 30 });
546
+ console.log(limited instanceof MountayaRateLimitError); // true
547
+ ```
548
+
549
+ An error's message is written for the log line it ends up in: the call, the status, the code and
550
+ the platform's message (`getItinerary: 403 FORBIDDEN Access is forbidden.`), then, for a `401`,
551
+ `402`, `403`, `412` or `429`, the step to take next, and the request id where the answer named
552
+ one. `MountayaConnectionError` is a failure with no
553
+ answer from the API behind it: the network, an attempt with no response within `timeoutMs`, an
554
+ event stream that delivered nothing for its stall window, or a body that broke off. A success
555
+ whose body does not decode, which something on the network path sent in the API's place, is an
556
+ answer all the same, and raises the base `MountayaApiError` with its status, its request id and
557
+ the parse failure as its `cause`. A call you abort rejects with your signal's own reason, never
558
+ wrapped, wherever it was waiting.
559
+
560
+ A Data API failure answered with an error status climbs the same ladder. A failure carried by a
561
+ `200`, whose body's `errors` say the operation did not happen, raises `MountayaDataError`, which
562
+ extends the same base.
563
+
564
+ ## Retries
565
+
566
+ On by default: two retries with exponential backoff and full jitter, on `429`, `502`, `503`,
567
+ `504` and network failures, an attempt that timed out among them, and on a `409` whose
568
+ `Idempotency-Key` is still in use. A `429` is repeated whatever the operation, but one coded
569
+ `LIMIT_REACHED`, a ceiling no wait lifts, is never repeated; the others where
570
+ the operation declares itself idempotent or the request carried a key, which every write does
571
+ ([Idempotency](#idempotency)). A `4xx` that is a statement about your request is never repeated,
572
+ a `412` least of all.
573
+
574
+ `Retry-After` is read as whole seconds or as an HTTP date, and replaces the schedule: the wait is
575
+ the seconds it names plus up to a second of jitter, so the clients one second refused do not all
576
+ come back in the same millisecond. Every wait of a call comes out of one budget, `maxWaitMs`, a
577
+ minute by default: a wait that does not fit what the waits before it left is not taken, and the
578
+ answer that asked for it rejects as the error its status maps to, which on a `429` is
579
+ `MountayaRateLimitError` carrying `retryAfter`, for you to schedule the retry from.
580
+
581
+ The policy is set per client, and any member of it per call:
582
+
583
+ ```ts
584
+ const client = new Mountaya({
585
+ credential: { publishableKey: "pk_…" },
586
+ retry: { maxRetries: 3, baseDelayMs: 500, maxDelayMs: 30_000, maxWaitMs: 120_000 },
587
+ });
588
+
589
+ // A search box re-querying on every keystroke wants no retries; the client's delays stay.
590
+ await client.studio.itineraries.getItineraries(
591
+ { query: { limit: 5 } },
592
+ { retry: { maxRetries: 0 } },
593
+ );
594
+ ```
595
+
596
+ A member that cannot work throws `MountayaConfigurationError` where it is given, naming the
597
+ member and the value: at construction for a client's policy, and before anything is sent for a
598
+ call's.
599
+
600
+ ## Idempotency
601
+
602
+ Every write (a `POST`, a `PATCH` or a `DELETE`) but `postSession`, `postOrganizationLookup` and
603
+ the two collaboration signals, `postItineraryCollab` and `postZoneCollab`, which a repeat
604
+ restates, sends an `Idempotency-Key`, the same on every attempt of one call. The API answers a key it has
605
+ seen with the answer it stored rather than run the write again, so a write whose answer was lost
606
+ to a dropped connection, a `502`, a `503` or a `504` is asked again safely, and a delete asked
607
+ again is answered with the `200` the first one was. The client draws the key from the runtime's
608
+ cryptographic random source before the first attempt; a runtime with none sends no key, and its
609
+ writes are then repeated only where the operation declares itself idempotent. An operation that
610
+ declares no key sends none, a key you pass it included.
611
+
612
+ Every error a write that sent a key raises carries it as `error.idempotencyKey`, whatever the
613
+ error: a dropped connection, a `5xx` and a body that broke off do not say the write was not made.
614
+ Send the same call again with that key, never a new one, and the write is made once; the
615
+ `onResponse` hook is told `replayed: true` of an answer the API kept for the key and gave again.
616
+
617
+ A caller that asks again itself, after a page reload or from a queue, passes the key it used the
618
+ first time:
619
+
620
+ ```ts
621
+ await mountaya.studio.itineraries.postItinerary(
622
+ { body: { activity_id, is_private: true, name: "Tour du Mont Blanc" }, idempotencyKey },
623
+ );
624
+ ```
625
+
626
+ A key is held for 12 hours. The same key with another request is a `400`, and the same key while
627
+ its first request is still running is a `409` coded `IDEMPOTENCY_KEY_IN_USE`, which the client
628
+ asks again itself, waiting at least the second the answer names each time, for as long as the
629
+ call's `retry.maxWaitMs` lasts: those repeats ask whether the first request has finished, so
630
+ `retry.maxRetries` does not count them. Once the budget is spent it raises
631
+ `MountayaIdempotencyKeyInUseError`; send the same call again with its `idempotencyKey` once its
632
+ `retryAfter` has passed. Every error carries the `retryAfter` its answer named, a `503` the API
633
+ knows the end of among them. A
634
+ `5xx` answered before the write was made keeps nothing, so a write asked again after one runs
635
+ again.
636
+
637
+ A write whose first answer cannot be given again, because it was too large to keep whole or
638
+ because the request failed with a `5xx` after the write was made, is answered on every repeat of
639
+ its key with a `409` coded `IDEMPOTENCY_ANSWER_UNAVAILABLE`. The client never asks again on it,
640
+ since every repeat is answered the same way, and raises `MountayaIdempotentAnswerUnavailableError`:
641
+ the write was made, and its `answer` carries what the first answer said: its `status`, and its
642
+ `location` and `etag` where it carried them. Re-read the resource, at `answer.location` where the
643
+ write created one, rather than sending the write again under a new key, which would make it
644
+ twice:
645
+
646
+ ```ts
647
+ import { MountayaIdempotentAnswerUnavailableError } from "@mountaya/client";
648
+
649
+ try {
650
+ await mountaya.studio.itineraries.postItinerary({
651
+ body: { activity_id, is_private: true, name: "Tour du Mont Blanc" },
652
+ idempotencyKey,
653
+ });
654
+ } catch (error) {
655
+ if (error instanceof MountayaIdempotentAnswerUnavailableError) {
656
+ // The write was made: read what it made rather than making it again.
657
+ const { location } = error.answer;
658
+ if (location !== undefined) {
659
+ await reloadFrom(location);
660
+ }
661
+ }
662
+ }
663
+ ```
664
+
665
+ ## Concurrency
666
+
667
+ A resource a write can be made conditional on carries its `etag`: an itinerary, a zone, a
668
+ collection, an organization and its settings, a publishable key and the AI provider
669
+ configuration. Send it back as `ifMatch`, and the write lands only if nobody changed the resource
670
+ since you read it:
671
+
672
+ ```ts
673
+ import { MountayaPreconditionFailedError } from "@mountaya/client";
674
+
675
+ const { data: itinerary } = await mountaya.studio.itineraries.getItinerary({ itinerary_id });
676
+
677
+ try {
678
+ await mountaya.studio.itineraries.patchItinerary({
679
+ body: { name: "Tour du Mont Blanc, reversed" },
680
+ ifMatch: itinerary.etag,
681
+ itinerary_id,
682
+ });
683
+ } catch (error) {
684
+ if (error instanceof MountayaPreconditionFailedError) {
685
+ // Somebody changed it since: read it again, and decide what the write should be now.
686
+ }
687
+ }
688
+ ```
689
+
690
+ The tag is sent exactly as given, on every attempt, and the client never sends one you did not
691
+ name: a write without one replaces what is there. A stale tag is a `412`, which is never repeated,
692
+ and its `etag` is the tag the resource carries now: read the resource again before you name it.
693
+ An itinerary's tag moves with every write to anything under it, its segments, waypoints and
694
+ publication included, since its read answers them all.
695
+
696
+ ## Rate limits
697
+
698
+ The Data API and the Tile API describe the limits an answer was counted against in its
699
+ `RateLimit-Policy` and `RateLimit` fields. `minute`, and `month`, the monthly allowance unless an
700
+ agreement leaves it unlimited, hold the organization's own clients and, on the Tile API, Mountaya's hosted embed.
701
+ `address` is the bound on one client IP address, which on the Tile API a key with no session
702
+ token, the hosted embed and a share token are held to, and on both APIs a session token minted for
703
+ `studio-embedded` without `user_id`. `member` and `studio-embedded` are the bounds a session token
704
+ minted for `studio-embedded` naming a member is held to, its member's and its organization's.
705
+ `share` is the bound every share link of one organization shares, on the Tile API. The client
706
+ reads them into `rateLimit`, a list of policies each with its `quota`, its `windowSeconds`, what
707
+ is `remaining` and the `resetSeconds` until its window resets, and reports it on every error and
708
+ to the `onResponse` hook, which is told of every answer:
709
+
710
+ ```ts
711
+ const mountaya = new Mountaya({
712
+ credential: { publishableKey: "pk_…", sessionToken },
713
+ onResponse: ({ operationId, rateLimit, requestId, status }) => {
714
+ const minute = rateLimit?.policies.find(({ name }) => name === "minute");
715
+ if (minute?.remaining === 0) {
716
+ console.warn(`${operationId} (${status}, request ${requestId}) spent the minute`);
717
+ }
718
+ },
719
+ });
720
+ ```
721
+
722
+ The state is for observing, never for steering: the client delays no request on it, since an
723
+ organization's figures are its agreement's, and a fault the hook throws changes nothing the call
724
+ answers. The Map Studio API sends neither field; its own limits (reads under a key, imports and
725
+ previews, routed writes, agent runs, collaboration signals, stream opens, invitations, minting)
726
+ answer a `429` with `Retry-After` all the same. `parseRateLimit` reads the two fields off an
727
+ answer the client did not make, a tile a map library fetched for instance.
728
+
729
+ ## Request ids
730
+
731
+ Every answer names its request in `X-Request-Id`, the id the API recorded it under and the one
732
+ thing to quote to support. An error the API answered carries it as `requestId`, its message ends
733
+ on it, and `onResponse` is told it for every answer, a success's included. A failed stream open
734
+ carries it as a failed request does. A `MountayaConnectionError` carries none, since no answer
735
+ came.
736
+
737
+ ## Timeouts
738
+
739
+ Each attempt waits for its response for the client's `timeoutMs`, 30 seconds by default, or for
740
+ the operation's own budget plus five seconds where that is longer: an import, which the API may
741
+ spend up to 55 seconds on, is not abandoned while the API is still running it, and a Data API
742
+ call, which the API spends up to 30 seconds on, waits 35. A call's own `timeoutMs` stands over
743
+ both, longer or shorter:
744
+
745
+ ```ts
746
+ await mountaya.studio.itineraries.getItinerary({ itinerary_id }, { timeoutMs: 5_000 });
747
+ ```
748
+
749
+ The budget bounds each attempt's wait for a response, not the retry sequence and not the body:
750
+ a large export still arriving is not cut off, and only the call's `signal` ends it. An attempt
751
+ that reaches it fails as a `MountayaConnectionError` that says so, and is retried where the call
752
+ is safe to repeat. It bounds a wait for the first session token too.
753
+
754
+ ## Reading a whole listing
755
+
756
+ Every listing of what an organization or its members create is served a page at a time, by an
757
+ opaque cursor: a call names its page size as `limit` (1 to 100, 50 by default), and the answer
758
+ names the cursor of the next page at `extensions.metadata.pagination.next_cursor`, null on the
759
+ last. `paginate` reads such a listing to its end and answers its rows one at a time:
760
+
761
+ ```ts
762
+ import { paginate } from "@mountaya/client";
763
+ import { MountayaAdmin } from "@mountaya/client/admin";
764
+
765
+ const members = [];
766
+ for await (const member of paginate(new MountayaAdmin(mountaya).members.getOrganizationMembers, {
767
+ organization_id,
768
+ })) {
769
+ members.push(member);
770
+ }
771
+ ```
772
+
773
+ It takes a method of the client and that method's own arguments, filters and `sort` included,
774
+ and each row is typed as the method's own. Every request carries those arguments unchanged, since
775
+ a cursor is bound to the filters and the order it was issued under. A page is requested only once
776
+ the rows before it are read, so a loop that stops early leaves the remaining pages unrequested,
777
+ and a `cursor` under `query` starts the walk where an earlier one stopped. The walk ends on a page
778
+ whose `next_cursor` is null, however long the listing is; a page that holds no row and names a
779
+ cursor is followed all the same, since the rows after it may be ones the API left out of it:
780
+
781
+ ```ts
782
+ const controller = new AbortController();
783
+
784
+ const firstHundred = paginate(
785
+ mountaya.studio.itineraries.getItineraries,
786
+ { query: { organization_id, sort: "-updated_at" } },
787
+ { maxPages: 4, pageSize: 25, signal: controller.signal },
788
+ );
789
+ ```
790
+
791
+ - `pageSize` is how many rows a request asks for, from 1 to 100. It defaults to 50.
792
+ - `maxPages` caps the requests one walk makes, for a reader who wants at most that much. A walk
793
+ that reaches it ends with no error and the rest unread. Left out, the walk reads to the last
794
+ page.
795
+ - `retry`, `signal` and `timeoutMs` are a call's own, and every request of the walk is made under
796
+ them. Once the signal aborts, the walk requests no further page and rejects with the signal's
797
+ reason.
798
+
799
+ A listing that names a cursor the walk has already followed would be read again without end, so
800
+ the walk rejects with `MountayaApiError` there rather than answer part of a listing as the whole.
801
+ A free function takes its transport first, so it is passed wrapped:
802
+
803
+ ```ts
804
+ import { MountayaTransport, paginate } from "@mountaya/client";
805
+ import { rest } from "@mountaya/client/admin";
806
+
807
+ const transport = new MountayaTransport({
808
+ credential: { publishableKey: "pk_…", sessionToken },
809
+ });
810
+
811
+ const keys = paginate(
812
+ (args: Parameters<typeof rest.getOrganizationPublishableKeys>[1], options) =>
813
+ rest.getOrganizationPublishableKeys(transport, args, options),
814
+ { organization_id },
815
+ );
816
+ ```
817
+
818
+ What `paginate` answers is an `AsyncIterable`, so `await Array.fromAsync(keys)` collects it in
819
+ one expression. The API reads by keyset, so a row whose sort key does not change is neither
820
+ skipped nor read twice, though a row a write moves across the cursor may be.
821
+
822
+ ## Uploading a file
823
+
824
+ `postItineraryPreview` takes either an uploaded file or an external id, depending on the
825
+ provider. Pass a `FormData` for the file providers (`gpx`, `geojson`, `kml`, `kmz`, `fit`, `tcx`)
826
+ and a plain object for the online ones: the encoding follows the body's type, and `Content-Type`
827
+ is left to `fetch` so the multipart boundary survives.
828
+
829
+ ```ts
830
+ const form = new FormData();
831
+ form.append("provider", "gpx");
832
+ form.append("file", file);
833
+
834
+ const { data } = await mountaya.studio.itineraries.postItineraryPreview({ body: form });
835
+ ```
836
+
837
+ ## Decoding JSON you already hold
838
+
839
+ A method decodes its response's timestamps as it answers, and reads null at a member its type marks
840
+ required and nullable that the response leaves out. JSON that reaches your program some other way, a
841
+ fixture baked into the bundle or a record read back from a cache, passes through no method, and a
842
+ cast leaves every timestamp in it a string behind a type that says `Date`, and every such member it
843
+ leaves out `undefined` behind a type that says null. `decodeRestSchema` gives it the decoding a
844
+ response gets, by the name of the schema it holds:
845
+
846
+ ```ts
847
+ import { decodeRestSchema } from "@mountaya/client";
848
+
849
+ const cached: unknown = JSON.parse(storedItinerary);
850
+ const itinerary = decodeRestSchema("ItineraryWithDetails", cached);
851
+
852
+ // A Date, as `getItinerary` answers one. Under a cast this line throws.
853
+ console.log(itinerary.created_at.getTime());
854
+ ```
855
+
856
+ The name is a key of `RestSchema.components["schemas"]`, and the result is typed as that schema.
857
+ It decodes and does not validate: JSON from a source you do not trust is yours to check first.
858
+ For a list, decode each member:
859
+
860
+ ```ts
861
+ const itineraries = storedItineraries.map((entry) =>
862
+ decodeRestSchema("ItineraryWithDetails", entry),
863
+ );
864
+ ```
865
+
866
+ ## Event streams
867
+
868
+ A collaboration feed and an agent run's events are `text/event-stream` operations, which have no
869
+ end for a request to read to: the client refuses them as methods, before anything is sent. Open
870
+ them from `@mountaya/client/events`, which reads a stream frame by frame over the client's own
871
+ credential and fetch, resumes it after a position, and reports how it closed:
872
+
873
+ ```ts
874
+ import { createAgentTransport } from "@mountaya/client/events";
875
+
876
+ const agent = createAgentTransport(mountaya.transport);
877
+ const { runId } = await agent.startRun({
878
+ message: "Plan a two-day loop from Chamonix.",
879
+ organization_id,
880
+ });
881
+
882
+ let lastEventId: string | undefined;
883
+ const close = agent.subscribe(runId, {
884
+ onClose: (reason) => console.log(`closed: ${reason}`),
885
+ onError: (error) => console.error(error),
886
+ onFrame: ({ event, id }) => {
887
+ lastEventId = id ?? lastEventId;
888
+ console.log(event.type);
889
+ },
890
+ onLastEventId: (position) => {
891
+ lastEventId = position;
892
+ },
893
+ });
894
+ ```
895
+
896
+ To resume after a drop, open again with `{ lastEventId }` as the third argument, and the stream
897
+ replays what followed that position. `createCollabTransport` reads an itinerary's, a zone's or an
898
+ organization's collaboration feed the same way; its `onError` says whether reopening can help,
899
+ with `terminal`. Each of them needs a session token beside the publishable key, and acts as the
900
+ user it names; an open waits for a token a `SessionTokenEngine` has on its way.
901
+
902
+ A stream ends with the credential it was opened with: the API ends it when the session token
903
+ expires or the key is revoked. Both transports close such a stream with the reason `reconnect`,
904
+ and so a close at or after the expiry of the token the open carried: open it again at once, from
905
+ the last event id, with the token the client holds then. A `401` on that open is the credential
906
+ gone, which reopening repeats.
907
+
908
+ ## Receiving webhooks
909
+
910
+ Mountaya delivers each change an organization's webhook endpoints subscribe to as a signed `POST`
911
+ to the endpoint's URL. `constructWebhookEvent` of the admin unit verifies the delivery's
912
+ `Mountaya-Signature` with the endpoint's signing secret and answers the event, typed by its `type`,
913
+ so comparing the type narrows `data` to what it carries:
914
+
915
+ ```ts
916
+ import {
917
+ constructWebhookEvent,
918
+ MountayaWebhookSignatureError,
919
+ type WebhookEvent,
920
+ } from "@mountaya/client/admin";
921
+
922
+ export const POST = async (request: Request): Promise<Response> => {
923
+ let event: WebhookEvent;
924
+ try {
925
+ event = await constructWebhookEvent(
926
+ await request.text(),
927
+ request.headers.get("Mountaya-Signature"),
928
+ webhookSecret,
929
+ );
930
+ } catch (error) {
931
+ if (error instanceof MountayaWebhookSignatureError) {
932
+ return new Response(error.reason, { status: 400 });
933
+ }
934
+ throw error;
935
+ }
936
+
937
+ switch (event.type) {
938
+ case "organization.member.updated":
939
+ // The membership as it is now, and the role it held before the change.
940
+ console.log(event.data.object.role, event.data.previous_attributes?.role);
941
+ break;
942
+ case "collection.deleted":
943
+ console.log(`collection ${event.data.object.id} deleted`);
944
+ break;
945
+ }
946
+
947
+ return new Response(null, { status: 204 });
948
+ };
949
+ ```
950
+
951
+ Pass the body exactly as it arrived, before any JSON parser reads it: the signature covers those
952
+ bytes, and a body parsed and written out again is another string, which does not verify.
953
+ `await request.text()` hands over that body in a runtime built on `Request`; in Express,
954
+ `express.raw({ type: "application/json" })` hands the route a `Buffer`, which is a `Uint8Array` and
955
+ is verified as it is. The secret is the endpoint's, `whsk_` included, answered once by
956
+ `postOrganizationWebhookEndpoint` under `webhooks` of `MountayaAdmin`: keep it on the server that
957
+ receives the deliveries, the one place this function runs.
958
+
959
+ A delivery is refused with `MountayaWebhookSignatureError`, whose `reason` says why: `missing-header`,
960
+ `malformed-header`, `signature` where no `v1` of the header matches, and `timestamp` where the
961
+ signature verifies and was made further from your clock than the tolerance, 300 seconds either way
962
+ unless you pass `{ toleranceSeconds }`. Answer it with a `400`. While a rotated secret overlaps its
963
+ successor the header carries a `v1` for each, and either secret verifies.
964
+
965
+ Your clock is the machine's wall clock unless you pass `{ now }`, the instant to judge the
966
+ timestamp by: a receiver that keeps a clock of its own hands it over, and a test pins the time
967
+ with it rather than faking the system's.
968
+
969
+ ```ts
970
+ import { constructWebhookEvent } from "@mountaya/client/admin";
971
+
972
+ // A delivery recorded at a known instant, verified at it.
973
+ const event = await constructWebhookEvent(recordedBody, recordedSignature, webhookSecret, {
974
+ now: new Date("2026-11-14T09:12:49Z"),
975
+ });
976
+ ```
977
+
978
+ The event's instants are `Date`s, and a member its type marks required and nullable that the
979
+ delivery leaves out is null, as a method answers them; `data.previous_attributes` holds only what
980
+ was sent. Mountaya delivers an event at least once and in no set order, so keep what you act on
981
+ keyed by `event.id`, and answer with a `2xx` within 10 seconds, before any slow work: an attempt
982
+ that is not answered in time is repeated. An event of a type a newer contract added is answered with
983
+ the type it arrived with, which reaches the `default` of a `switch` over the types this release
984
+ knows. `WebhookEvent<"zone.updated">` names the event of one type, and `RestSchema` of the default
985
+ entry keeps the contract's envelope, whose `type` is not tied to its `data`, as
986
+ `getOrganizationWebhookEvents` lists it.
987
+
988
+ Endpoints, past events and their deliveries are managed under `webhooks` of `MountayaAdmin`, which
989
+ takes the `management` scope and a session token beside the key.
990
+
991
+ ## Other options
992
+
993
+ ```ts
994
+ new Mountaya({
995
+ credential: { publishableKey: "pk_…" },
996
+ language: "fr", // Accept-Language, `*` where left out; the platform localizes its messages
997
+ timeoutMs: 30_000, // per attempt, until the response arrives
998
+ baseUrls: { rest: "http://localhost:8080" },
999
+ // A relative base is supported too: "" for same-origin, "/api" behind your own gateway.
1000
+ fetch: myInstrumentedFetch,
1001
+ });
1002
+ ```
1003
+
1004
+ A Data API call takes its own `timeoutMs` beside `select`, as every call does beside `retry`
1005
+ ([Timeouts](#timeouts)). Each option is checked at construction and refused by name with the
1006
+ value; `ClientOptions` states every range.
1007
+
1008
+ A `fetch` of your own that reads the response it hands back, to log it or to cache it, reads a
1009
+ clone (`response.clone()`): a body already read cannot be read again.
1010
+
1011
+ ### The default hosts
1012
+
1013
+ | Surface | Default |
1014
+ | --- | --- |
1015
+ | `rest` | `https://api.mountaya.com` |
1016
+ | `tiles` | `https://tiles.mountaya.com` |
1017
+ | `data` | `https://data.mountaya.com` |
1018
+
1019
+ Pass `baseUrls` to point any surface somewhere else, a local stack or a proxy, one surface at a
1020
+ time. A path or `""` is read against the page's own origin, `location`, which a `<base>` element
1021
+ does not move; where no page names an `http` or `https` origin, as in Node, a path or `""` is
1022
+ refused with a `MountayaConfigurationError` as the client is built: pass an absolute address there.
1023
+
1024
+ ### Persisted queries
1025
+
1026
+ Data API calls send a SHA-256 hash of the query document rather than the document, and upload
1027
+ the document only when the platform answers that it has not seen that hash yet. There is nothing
1028
+ to configure. The first call for a given document costs two requests against the per-minute
1029
+ limit, and every call after it costs one small one. Where `crypto.subtle` is unavailable (a page served
1030
+ over plain HTTP, or React Native without a polyfill) the document is sent in full.
1031
+
1032
+ ## Tree-shaking
1033
+
1034
+ Every operation is also a free function, so importing one pulls in the transport and nothing
1035
+ else. The core's are `rest` of the package root, and the admin unit's are `rest` of
1036
+ `@mountaya/client/admin`:
1037
+
1038
+ ```ts
1039
+ import { MountayaTransport, rest } from "@mountaya/client";
1040
+
1041
+ const transport = new MountayaTransport({ credential: { publishableKey: "pk_…" } });
1042
+ const { data } = await rest.getItineraries(transport);
1043
+ ```
1044
+
1045
+ `MountayaTransport.request` makes a call this client does not bind, under the same credential,
1046
+ retry policy and error classes. It decodes to a `Date` only the instants its `dates` names, a
1047
+ `DateMask` such as `{ data: { created_at: true } }`, and reads what the call declares off its
1048
+ `RequestArgs`: `requiresSecretKey: true` on a call a secret key authenticates,
1049
+ `takesNoCredential: true` on one that takes none (a secret key is refused on a call that states
1050
+ neither), `actsAsMember: true` on one that acts as a member, `takesIdempotencyKey: true` on a
1051
+ write that sends a key, and `serverBudgetMs` where the operation states its own budget.
1052
+
1053
+ ## Rendering maps
1054
+
1055
+ This package is transport only: it never renders anything and never depends on a map library.
1056
+ For MapLibre GL JS rendering, use `@mountaya/elements`, which takes this package as a peer for its
1057
+ types and authenticates MapLibre's own tile requests through a `transformRequest` factory.
1058
+
1059
+ ## Troubleshooting
1060
+
1061
+ ### A call rejects with `MountayaConfigurationError` before any request is sent
1062
+
1063
+ The client reads what each operation declares and refuses a credential that cannot meet it. The
1064
+ message states the rule and opens with the operation it refused:
1065
+
1066
+ - **It "requires a session token beside the publishable key".** Every Data API operation requires
1067
+ one, and so does each Map Studio operation the message names. Mint a token on your server
1068
+ ([Minting a session token](#minting-a-session-token)) and pass it as `sessionToken`. Where the
1069
+ message says the call acts as a member, mint it with `user_id` set to the user it acts as.
1070
+ Where it says the engine holds none, its last mint failed, and the error's `cause` is that
1071
+ failure.
1072
+ - **It "does not take a secret key".** A secret key authenticates `postSession` and nothing else.
1073
+ Keep one client with `{ secretKey }` on the server that mints, and make every other call
1074
+ through a second client built with `{ publishableKey, sessionToken }`, as
1075
+ [the program above](#a-program-you-can-run) does.
1076
+ - **It "acts as the user its session token was minted for", under a token "minted without
1077
+ user_id".** The engine's last mint was made without `user_id`: mint with `user_id` set to the
1078
+ person signed in ([The user a call acts as](#the-user-a-call-acts-as)).
1079
+ - **It names `idempotencyKey` or `ifMatch`.** The value is empty or holds a character no request
1080
+ header carries: pass the key as you drew it, and the `etag` as the API wrote it.
1081
+ - **It "answers an event stream".** A collaboration or agent stream is opened from
1082
+ `@mountaya/client/events` ([Event streams](#event-streams)).
1083
+
1084
+ A call is refused the same way, naming its operation, where its path would not reach the route it
1085
+ is written for (an identifier that is empty, `.` or `..`) or where its body is one
1086
+ `JSON.stringify` refuses.
1087
+
1088
+ ### Constructing a client throws that the credential "carries no publishableKey"
1089
+
1090
+ The key reads as absent: it is missing, or empty or whitespace alone, which is what an unset
1091
+ environment variable leaves (`process.env.MOUNTAYA_PUBLISHABLE_KEY ?? ""`). Set the variable, and
1092
+ pass the value your organization was issued.
1093
+
1094
+ ### A `401` from a client that worked a few minutes earlier
1095
+
1096
+ A session token expires, and `postSession` answers its `expires_at` beside it. A token passed as a
1097
+ string is the one the client sends for its whole life, so every call after that instant rejects
1098
+ with `MountayaAuthenticationError`. Pass a `SessionTokenEngine` as `sessionToken` and hold it
1099
+ subscribed ([Following a session token that rotates](#following-a-session-token-that-rotates)).
1100
+ A `401` on a first call is the other cause its message names: a key the API does not know, or one
1101
+ that is rotated or disabled.
1102
+
1103
+ ### A `401` on every write, under a session token that reads fine
1104
+
1105
+ The token was minted without `user_id`. Every operation that acts as a member (each write, the
1106
+ streams, each read under `/v1/me`) requires a token naming one, and a token minted without `user_id`
1107
+ is a `401` there, however fresh. Mint the token with `user_id` set to the person signed in
1108
+ ([Minting a session token](#minting-a-session-token)). A `403` there is that person lacking the
1109
+ role the call asks.
1110
+
1111
+ ### A `412` on a write that sent `ifMatch`
1112
+
1113
+ The resource changed since the `etag` the write names was read, by somebody else or by another
1114
+ write of yours: every write to an itinerary's segments and waypoints moves the itinerary's tag.
1115
+ Read the resource again and send its new `etag` with the write you still mean to make. The client
1116
+ never repeats a `412` on its own.
1117
+
1118
+ ### A field reads `undefined` on a result that arrived
1119
+
1120
+ One surface's shape is being read on another's result, and
1121
+ [What a method resolves to](#what-a-method-resolves-to) states both. A Map Studio or Tile API
1122
+ method resolves to an envelope, so an itinerary's name is at `result.data.name`. A Data API method
1123
+ resolves to the operation's own field, so `result.routes` is the routes and `result.data` is
1124
+ `undefined`.
1125
+
1126
+ ### A `403` on an operation the key should reach
1127
+
1128
+ `MountayaForbiddenError` is a scope the key does not carry, a resource outside the key's
1129
+ organization, a calling page the organization does not allow, or a member without the role the call
1130
+ asks. A product the organization does not hold is a `MountayaBillingError` instead, and a ceiling a
1131
+ `MountayaRateLimitError` coded `LIMIT_REACHED`. The scope an operation needs is named in its doc comment, which an
1132
+ editor shows on hover: `mountaya.studio.itineraries.getItinerary` and
1133
+ `rest.getItinerary` both name the `publishing` scope, and the `studio-embedded` scope that includes
1134
+ it. Enable that scope on the key: `tiles`, `data` and
1135
+ `management` open the Tile API, the Data API and the account, and of the Map Studio's other
1136
+ operations a read takes `publishing` and one that acts as a member takes `studio-embedded`.
1137
+
1138
+ A request a browser sends names its page, and the API accepts a publishable key only from a page
1139
+ the organization's allowed domains list, before it reads the key's scopes. So a `403` on every
1140
+ call of a page, whatever its scope, names the page: list its host under
1141
+ **Organization → Security** in the Mountaya app, and `localhost` with its port, such as
1142
+ `localhost:5173`, while you develop. Under an agreement, Mountaya lists the sites, so
1143
+ [tell us](https://mountaya.com/en/contact/) each host, and an owner or admin adds
1144
+ `localhost` entries there themself. A request from your server names no page
1145
+ and is never refused for it.
1146
+
1147
+ ### A `402` on an operation whose scope the key carries
1148
+
1149
+ The organization's agreement does not cover the product the scope belongs to, and the API checks
1150
+ the product before the key's scopes, so it answers a `402` where a missing scope alone is a
1151
+ `403`. Enabling a scope on the key does not lift it: it clears once the organization's agreement
1152
+ covers the product. [Talk to us](https://mountaya.com/en/contact/). On the Data API, an
1153
+ organization billed by card is refused the same way while no payment method is on file, and the
1154
+ error's message says so: adding one in the organization's billing settings lifts it.
1155
+
1156
+ ### `error instanceof MountayaApiError` is false for an error this client threw
1157
+
1158
+ A second copy of the package is loaded, resolved once as an ES module and once as CommonJS, or
1159
+ installed twice, and each copy has its own classes. `npm ls @mountaya/client` shows a second
1160
+ install. `isMountayaError` and `isMountayaApiError` answer the same for an error from either copy.
1161
+
1162
+ ### Constructing a client throws that a credential member holds a character no request header carries
1163
+
1164
+ A request header carries printable ASCII alone, and the key or the token holds another character:
1165
+ a line break, a tab or another control character, at either end too (a key read from a file with
1166
+ its closing line break), or a character past ASCII, a letter such as `é` included. A snippet's
1167
+ placeholder is the usual one: `"pk_…"` is written with an ellipsis, and the message says so where
1168
+ it finds one. Pass the value your organization was issued. A client's `language`, a call's
1169
+ `idempotencyKey` and its `ifMatch` are held to the same rule.
1170
+
1171
+ ### `constructWebhookEvent` refuses every delivery with the reason `signature`
1172
+
1173
+ The bytes it verifies are not the bytes Mountaya signed, or the secret is not the one they were
1174
+ signed with. A body a framework already parsed and serialized again differs from the one that
1175
+ arrived, by a space or by the order of its members: read the raw body, as
1176
+ [Receiving webhooks](#receiving-webhooks) does. The secret is the signing secret of the endpoint
1177
+ the delivery was sent to, `whsk_` included, and not another endpoint's or one rotated away.
1178
+
1179
+ ### `constructWebhookEvent` refuses a delivery with the reason `timestamp`
1180
+
1181
+ The signature verifies, and was made further from the receiving machine's clock than the
1182
+ tolerance allows, 300 seconds by default. A delivery a queue held back before it was verified
1183
+ arrives that way, as does one replayed later: verify a delivery as it arrives, then queue it. Where
1184
+ the machine's clock is wrong, set it right; pass `{ toleranceSeconds }` only for a clock that is
1185
+ known to drift.
1186
+
1187
+ ### Constructing a client throws that a secret key must never reach a browser or a mobile application
1188
+
1189
+ The credential is a secret key and the code runs on a page or in a React Native application,
1190
+ where anyone can read a key out of the bundle. Mint a session token on your server and send that
1191
+ to the browser or the app. Importing from `@mountaya/client/browser` turns the same mistake into a
1192
+ type error.
1193
+
1194
+ ## Exports
1195
+
1196
+ Everything below is importable from `@mountaya/client`, which is the default entry point.
1197
+ `@mountaya/client/browser` offers the same contract with the secret-key credential removed: it
1198
+ adds `BrowserClientOptions` in its place, and declares its own `Mountaya` and
1199
+ `MountayaTransport`, which take it. `@mountaya/client/admin` is the admin unit: `MountayaAdmin`,
1200
+ its operations as free functions under `rest`, every type only they and the webhook events reach,
1201
+ and webhook receiving. Every name in a table is imported from the entry point its heading names; the
1202
+ first column says where the package declares it (the kind of module, or the package it is
1203
+ republished from), not what it is and not a second import path.
1204
+
1205
+ <!-- exports:start -->
1206
+
1207
+ <!-- Generated by scripts/generate-readme-exports.mjs. Run `npm run generate:readme`. -->
1208
+
1209
+ #### `@mountaya/client`
1210
+
1211
+ | Declared under | Values | Types |
1212
+ | --- | --- | --- |
1213
+ | engines | `SessionTokenEngine` | `SessionTokenEngineOptions`, `SessionTokenSnapshot` |
1214
+ | rules | `boundFetch`, `decodeRestSchema`, `defaultBaseUrls`, `errorForStatus`, `isMountayaApiError`, `isMountayaError`, `MountayaApiError`, `MountayaAuthenticationError`, `MountayaBadRequestError`, `MountayaBillingError`, `MountayaConfigurationError`, `MountayaConflictError`, `MountayaConnectionError`, `MountayaDataError`, `MountayaError`, `MountayaForbiddenError`, `MountayaIdempotencyKeyInUseError`, `MountayaIdempotentAnswerUnavailableError`, `MountayaMethodNotAllowedError`, `MountayaNotFoundError`, `MountayaPayloadTooLargeError`, `MountayaPreconditionFailedError`, `MountayaRateLimitError`, `MountayaSelectionError`, `MountayaServerError`, `MountayaTransport`, `paginate`, `parseRateLimit`, `PAYMENT_REQUIRED_CODE`, `SCHEMA_VERSION` | `ApiErrorDetails`, `BaseUrlOverrides`, `BinaryBody`, `ClientOptions`, `CookieCredential`, `Credential`, `DataOptions`, `DataResult`, `DateMask`, `ErrorCode`, `ErrorEntry`, `ErrorMetadata`, `FieldTree`, `IdempotentAnswer`, `MountayaResponse`, `PagedResponse`, `PaginateOptions`, `PublishableCredential`, `RateLimitInfo`, `RateLimitPolicy`, `RequestArgs`, `RequestOptions`, `ResourceKind`, `ResourceRef`, `ResponseReport`, `RetryOptions`, `SecretCredential`, `Selected`, `Selection`, `SelectionValue`, `SessionTokenSource`, `ShareCredential`, `StreamSeam`, `Surface` |
1215
+ | `geojson` | none | `Geometry` |
1216
+ | generated from the contract | `data`, `DataSelection`, `rest`, `tiles` | `AcceptedResponse`, `Activity`, `ActivityCapabilities`, `ActivitySlug`, `AgentAwaitingInputEvent`, `AgentBudgetDimension`, `AgentBudgetExhaustedEvent`, `AgentChecksUnmetEvent`, `AgentClientToolManifest`, `AgentCloseInput`, `AgentConfirmInput`, `AgentConfirmRequiredEvent`, `AgentDoneEvent`, `AgentErrorCode`, `AgentErrorEvent`, `AgentManifestUpdateInput`, `AgentMessageDeltaEvent`, `AgentMessageEvent`, `AgentReconnectEvent`, `AgentRun`, `AgentRunCreateParams`, `AgentRunEvent`, `AgentRunEventType`, `AgentRunFeedbackParams`, `AgentRunFeedbackRating`, `AgentRunInputParams`, `AgentRunInputType`, `AgentRunProfile`, `AgentRunReason`, `AgentToolAbandonedEvent`, `AgentToolAbandonedReason`, `AgentToolCallEvent`, `AgentToolCallTarget`, `AgentToolErrorCode`, `AgentToolResultEvent`, `AgentToolResultInput`, `AgentUserMessageInput`, `AnalyzeGeometryResult`, `BadRequestResponse`, `Boundaries`, `CategoryActivities`, `CategoryOverlays`, `CollabChangeAction`, `CollabChangeKind`, `CollabCollectionChangedEvent`, `CollabCursorEvent`, `CollabCursorSignal`, `CollabDraftClearEvent`, `CollabDraftClearSignal`, `CollabDraftUpdateEvent`, `CollabDraftUpdateSignal`, `CollabEntity`, `CollabEntityKind`, `CollabItineraryChangedEvent`, `CollabLock`, `CollabLockAcquiredEvent`, `CollabLockAcquireSignal`, `CollabLockReleasedEvent`, `CollabLockReleaseSignal`, `CollabLockSnapshotEvent`, `CollabMember`, `CollabPosition`, `CollabPresenceJoinEvent`, `CollabPresenceLeaveEvent`, `CollabPresenceSnapshotEvent`, `CollabReconnectEvent`, `CollabSegmentChangedEvent`, `CollabSelectionEvent`, `CollabSelectionKind`, `CollabSelectionRef`, `CollabSelectionSignal`, `CollabSignalParams`, `CollabSignalType`, `CollabStreamEvent`, `CollabStreamEventType`, `CollabWaypointChangedEvent`, `CollabZoneChangedEvent`, `Collection`, `CollectionCount`, `CollectionCreateParams`, `CollectionItinerariesAddParams`, `CollectionItineraryUpdateParams`, `CollectionUpdateParams`, `CollectionZonesAddParams`, `ConflictMetadata`, `ConflictResponse`, `CreatedResponse`, `DataSchema`, `DirectionsResult`, `Elevation`, `ElevationTileSize`, `EmbeddedStudioDefaultProps`, `EmbeddedStudioSafetyRules`, `EmbeddedStudioTheme`, `EmbeddedStudioThemeColors`, `Errors`, `ExportFormat`, `ExportItineraryResult`, `ExportVariant`, `ForbiddenResponse`, `GatewayTimeoutResponse`, `GeocodeResult`, `GeoJSONGeometry`, `GeoJSONGeometryCollection`, `GeoJSONLineString`, `GeoJSONMultiLineString`, `GeoJSONMultiPoint`, `GeoJSONMultiPolygon`, `GeoJSONPoint`, `GeoJSONPolygon`, `HTTPError`, `IdempotentReplayed`, `ImportGranularity`, `ImportProvider`, `ImportRecommendationReason`, `ImportWarning`, `InternalErrorResponse`, `IsochronesResult`, `Itinerary`, `ItineraryCount`, `ItineraryCreateParams`, `ItineraryDirectionsStep`, `ItineraryDuplicateParams`, `ItineraryImportConfirmParams`, `ItineraryImportConfirmSegment`, `ItineraryImportConfirmWaypoint`, `ItineraryImportPreview`, `ItineraryPace`, `ItineraryPaceSegment`, `ItineraryResult`, `ItinerarySegment`, `ItinerarySegmentGroup`, `ItineraryStatus`, `ItineraryUpdateParams`, `ItineraryWaypoint`, `ItineraryWithDetails`, `Language`, `Layers`, `LimitKey`, `ListMetadata`, `LocaleMap`, `Locales`, `ManeuverType`, `MatrixResult`, `NotFoundResponse`, `OkResponse`, `Organization`, `OrganizationLookupParams`, `OrganizationRole`, `OrganizationSettings`, `Overlay`, `OverlayCapabilities`, `OverlayContentType`, `OverlaySupportedCapabilities`, `PaginationMetadata`, `PayloadTooLargeResponse`, `PaymentRequiredResponse`, `PoisResult`, `ProposedCandidate`, `ProposedSegment`, `ProposedWaypoint`, `RangeType`, `ReadSurface`, `RelationToUser`, `ResponseMetadataCreatedPart`, `ResponseMetadataIdempotentAnswer`, `ResponseMetadataLimitReached`, `ResponseMetadataLockConflict`, `ResponseMetadataPatchCollection`, `ResponseMetadataPatchItinerary`, `ResponseMetadataPatchZone`, `ResponseMetadataPostCollection`, `ResponseMetadataPostItinerary`, `ResponseMetadataPostZone`, `RestSchema`, `ReverseGeocodeResult`, `RoadAccessInfo`, `RoadAccessRestrictionType`, `SearchResult`, `SegmentConvertParams`, `SegmentCreateParams`, `SegmentGroupCreateParams`, `SegmentGroupUpdateParams`, `SegmentMode`, `SegmentSplitParams`, `SegmentUpdateParams`, `ServiceUnavailableResponse`, `Session`, `SessionSurface`, `ShareLink`, `SlopeInfo`, `SpeedInfo`, `StreamReconnectReason`, `StudioEntitlement`, `SuccessExtensions`, `SuggestionsResult`, `SurfaceInfo`, `SurfaceType`, `Terrain`, `TerrainGridResult`, `TerrainProfileResult`, `TerrainSamplesResult`, `TerrainTileSize`, `TerrainVariant`, `TerrainVariantAsStyle`, `TerrainVariantAsTiles`, `TerrainVariantConfig`, `TerrainVariants`, `Theme`, `TileLayer`, `TileLayerType`, `TileLegend`, `TileLegendKind`, `TileLegendStep`, `TileSchema`, `TileSource`, `TileSourceSize`, `TileSourceType`, `TooManyRequestsResponse`, `TrailDifficultyInfo`, `TrailDifficultyType`, `UnauthorizedResponse`, `UnitLegend`, `UnitLength`, `UnitPace`, `UnitSlope`, `UnitTemperature`, `WaypointAmenity`, `WaypointContact`, `WaypointCreateParams`, `WaypointIcon`, `WaypointLink`, `WaypointMedia`, `WaypointMode`, `WaypointPhoto`, `WaypointProperty`, `WaypointPropertyFormat`, `WaypointTiming`, `WaypointUpdateParams`, `WayType`, `WayTypeInfo`, `Zone`, `ZoneCreateParams`, `ZoneFeature`, `ZoneLevel`, `ZoneMode`, `ZoneSource`, `ZoneSourceKind`, `ZoneStatus`, `ZoneUpdateParams` |
1217
+ | the entry point | `Mountaya` | none |
1218
+
1219
+ #### `@mountaya/client/admin`
1220
+
1221
+ | Declared under | Values | Types |
1222
+ | --- | --- | --- |
1223
+ | rules | `constructWebhookEvent`, `MountayaAdmin`, `MountayaWebhookSignatureError` | `ConstructWebhookEventOptions`, `WebhookEvent`, `WebhookSignatureFailure` |
1224
+ | generated from the contract | `rest` | `Address`, `AiCredentialField`, `AiProvider`, `AiProviderCatalog`, `AiProviderConfig`, `AiProviderConfigCreateParams`, `AiProviderConfigEventObject`, `AiProviderConfigUpdateParams`, `AssignableOrganizationRole`, `BillingInfo`, `BillingInfoEventObject`, `BillingInfoField`, `BillingInfoTaxIdParams`, `BillingInfoUpdateParams`, `BillingInterval`, `BillingPricing`, `BillingProduct`, `BillingUnitKind`, `Capability`, `CollectionEventObject`, `CollectionItineraryEventObject`, `CollectionShareLinkEventObject`, `CollectionZoneEventObject`, `Invoice`, `InvoiceEventObject`, `InvoiceStatus`, `ItineraryEventObject`, `ItineraryOrigin`, `ItinerarySegmentEventObject`, `ItinerarySegmentGroupEventObject`, `ItineraryShareLinkEventObject`, `ItineraryWaypointEventObject`, `Membership`, `MeterDimension`, `NotificationPreference`, `NotificationPreferences`, `NotificationPreferencesUpdateParams`, `NotificationPreferenceUpdate`, `NotificationType`, `OrganizationBillingPaymentMethodParams`, `OrganizationBillingProvisionParams`, `OrganizationCreateParams`, `OrganizationEntitlementsEventObject`, `OrganizationEventObject`, `OrganizationInvitation`, `OrganizationInvitationCreateParams`, `OrganizationInvitationEventObject`, `OrganizationMember`, `OrganizationMemberDeletionReason`, `OrganizationMemberEventObject`, `OrganizationMemberUpdateParams`, `OrganizationSettingsEventObject`, `OrganizationSettingsPatchParams`, `OrganizationSubscription`, `OrganizationSubscriptionEventObject`, `OrganizationSubscriptionItem`, `OrganizationSubscriptionSummary`, `OrganizationUpdateParams`, `PaymentMethod`, `PaymentMethodCard`, `PaymentMethodEventObject`, `PaymentMethodSepaDebit`, `Preferences`, `PreferencesUpdateParams`, `PromotionCodePreview`, `PublishableKey`, `PublishableKeyCreateParams`, `PublishableKeyEventObject`, `PublishableKeyScope`, `PublishableKeyUpdateParams`, `ResponseMetadataPostOrganizationInvitation`, `SecretKeyEventObject`, `SessionCreateParams`, `SetupIntentSession`, `SubscriptionCollectionMethod`, `SubscriptionDiscount`, `SubscriptionEndReason`, `SubscriptionStatus`, `TaxId`, `UsageClientName`, `UsageDataPoint`, `UsageDataResourceType`, `UsageDataSurface`, `UsageMetric`, `UsageStatusClass`, `UsageTilePoint`, `UsageTileResourceType`, `UsageTileSurface`, `UserInvitation`, `WebhookAttemptOutcome`, `WebhookDelivery`, `WebhookDeliveryAttempt`, `WebhookDeliveryCreateParams`, `WebhookDeliveryOutcome`, `WebhookDeliveryRecipient`, `WebhookDeliveryTestParams`, `WebhookDeliveryTrigger`, `WebhookDeliveryTriggerKind`, `WebhookDeliveryWithAttempts`, `WebhookDestinationKind`, `WebhookEndpoint`, `WebhookEndpointCreateParams`, `WebhookEndpointDisabledReason`, `WebhookEndpointEventObject`, `WebhookEndpointStatus`, `WebhookEndpointUpdateParams`, `WebhookEndpointWithSecret`, `WebhookEventActor`, `WebhookEventActorType`, `WebhookEventCatalogEntry`, `WebhookEventData`, `WebhookEventObject`, `WebhookEventRelatedObject`, `WebhookEventRequest`, `WebhookEventType`, `WebhookEventWithDeliveries`, `WebhookFailureClass`, `WebhookFailureKind`, `WebhookHealth`, `WebhookHealthDestination`, `WebhookHealthFailure`, `WebhookHealthFigures`, `WebhookHealthGranularity`, `WebhookHealthPoint`, `WebhookHealthWindow`, `ZoneEventObject` |
1225
+
1226
+ #### `@mountaya/client/browser`
1227
+
1228
+ | Declared under | Values | Types |
1229
+ | --- | --- | --- |
1230
+ | engines | `SessionTokenEngine` | `SessionTokenEngineOptions`, `SessionTokenSnapshot` |
1231
+ | rules | `boundFetch`, `decodeRestSchema`, `defaultBaseUrls`, `errorForStatus`, `isMountayaApiError`, `isMountayaError`, `MountayaApiError`, `MountayaAuthenticationError`, `MountayaBadRequestError`, `MountayaBillingError`, `MountayaConfigurationError`, `MountayaConflictError`, `MountayaConnectionError`, `MountayaDataError`, `MountayaError`, `MountayaForbiddenError`, `MountayaIdempotencyKeyInUseError`, `MountayaIdempotentAnswerUnavailableError`, `MountayaMethodNotAllowedError`, `MountayaNotFoundError`, `MountayaPayloadTooLargeError`, `MountayaPreconditionFailedError`, `MountayaRateLimitError`, `MountayaSelectionError`, `MountayaServerError`, `paginate`, `parseRateLimit`, `PAYMENT_REQUIRED_CODE`, `SCHEMA_VERSION` | `ApiErrorDetails`, `BaseUrlOverrides`, `BinaryBody`, `CookieCredential`, `DataOptions`, `DataResult`, `DateMask`, `ErrorCode`, `ErrorEntry`, `ErrorMetadata`, `FieldTree`, `IdempotentAnswer`, `MountayaResponse`, `PagedResponse`, `PaginateOptions`, `PublishableCredential`, `RateLimitInfo`, `RateLimitPolicy`, `RequestArgs`, `RequestOptions`, `ResourceKind`, `ResourceRef`, `ResponseReport`, `RetryOptions`, `Selected`, `Selection`, `SelectionValue`, `SessionTokenSource`, `ShareCredential`, `StreamSeam`, `Surface` |
1232
+ | `geojson` | none | `Geometry` |
1233
+ | generated from the contract | `data`, `DataSelection`, `rest`, `tiles` | `AcceptedResponse`, `Activity`, `ActivityCapabilities`, `ActivitySlug`, `AgentAwaitingInputEvent`, `AgentBudgetDimension`, `AgentBudgetExhaustedEvent`, `AgentChecksUnmetEvent`, `AgentClientToolManifest`, `AgentCloseInput`, `AgentConfirmInput`, `AgentConfirmRequiredEvent`, `AgentDoneEvent`, `AgentErrorCode`, `AgentErrorEvent`, `AgentManifestUpdateInput`, `AgentMessageDeltaEvent`, `AgentMessageEvent`, `AgentReconnectEvent`, `AgentRun`, `AgentRunCreateParams`, `AgentRunEvent`, `AgentRunEventType`, `AgentRunFeedbackParams`, `AgentRunFeedbackRating`, `AgentRunInputParams`, `AgentRunInputType`, `AgentRunProfile`, `AgentRunReason`, `AgentToolAbandonedEvent`, `AgentToolAbandonedReason`, `AgentToolCallEvent`, `AgentToolCallTarget`, `AgentToolErrorCode`, `AgentToolResultEvent`, `AgentToolResultInput`, `AgentUserMessageInput`, `AnalyzeGeometryResult`, `BadRequestResponse`, `Boundaries`, `CategoryActivities`, `CategoryOverlays`, `CollabChangeAction`, `CollabChangeKind`, `CollabCollectionChangedEvent`, `CollabCursorEvent`, `CollabCursorSignal`, `CollabDraftClearEvent`, `CollabDraftClearSignal`, `CollabDraftUpdateEvent`, `CollabDraftUpdateSignal`, `CollabEntity`, `CollabEntityKind`, `CollabItineraryChangedEvent`, `CollabLock`, `CollabLockAcquiredEvent`, `CollabLockAcquireSignal`, `CollabLockReleasedEvent`, `CollabLockReleaseSignal`, `CollabLockSnapshotEvent`, `CollabMember`, `CollabPosition`, `CollabPresenceJoinEvent`, `CollabPresenceLeaveEvent`, `CollabPresenceSnapshotEvent`, `CollabReconnectEvent`, `CollabSegmentChangedEvent`, `CollabSelectionEvent`, `CollabSelectionKind`, `CollabSelectionRef`, `CollabSelectionSignal`, `CollabSignalParams`, `CollabSignalType`, `CollabStreamEvent`, `CollabStreamEventType`, `CollabWaypointChangedEvent`, `CollabZoneChangedEvent`, `Collection`, `CollectionCount`, `CollectionCreateParams`, `CollectionItinerariesAddParams`, `CollectionItineraryUpdateParams`, `CollectionUpdateParams`, `CollectionZonesAddParams`, `ConflictMetadata`, `ConflictResponse`, `CreatedResponse`, `DataSchema`, `DirectionsResult`, `Elevation`, `ElevationTileSize`, `EmbeddedStudioDefaultProps`, `EmbeddedStudioSafetyRules`, `EmbeddedStudioTheme`, `EmbeddedStudioThemeColors`, `Errors`, `ExportFormat`, `ExportItineraryResult`, `ExportVariant`, `ForbiddenResponse`, `GatewayTimeoutResponse`, `GeocodeResult`, `GeoJSONGeometry`, `GeoJSONGeometryCollection`, `GeoJSONLineString`, `GeoJSONMultiLineString`, `GeoJSONMultiPoint`, `GeoJSONMultiPolygon`, `GeoJSONPoint`, `GeoJSONPolygon`, `HTTPError`, `IdempotentReplayed`, `ImportGranularity`, `ImportProvider`, `ImportRecommendationReason`, `ImportWarning`, `InternalErrorResponse`, `IsochronesResult`, `Itinerary`, `ItineraryCount`, `ItineraryCreateParams`, `ItineraryDirectionsStep`, `ItineraryDuplicateParams`, `ItineraryImportConfirmParams`, `ItineraryImportConfirmSegment`, `ItineraryImportConfirmWaypoint`, `ItineraryImportPreview`, `ItineraryPace`, `ItineraryPaceSegment`, `ItineraryResult`, `ItinerarySegment`, `ItinerarySegmentGroup`, `ItineraryStatus`, `ItineraryUpdateParams`, `ItineraryWaypoint`, `ItineraryWithDetails`, `Language`, `Layers`, `LimitKey`, `ListMetadata`, `LocaleMap`, `Locales`, `ManeuverType`, `MatrixResult`, `NotFoundResponse`, `OkResponse`, `Organization`, `OrganizationLookupParams`, `OrganizationRole`, `OrganizationSettings`, `Overlay`, `OverlayCapabilities`, `OverlayContentType`, `OverlaySupportedCapabilities`, `PaginationMetadata`, `PayloadTooLargeResponse`, `PaymentRequiredResponse`, `PoisResult`, `ProposedCandidate`, `ProposedSegment`, `ProposedWaypoint`, `RangeType`, `ReadSurface`, `RelationToUser`, `ResponseMetadataCreatedPart`, `ResponseMetadataIdempotentAnswer`, `ResponseMetadataLimitReached`, `ResponseMetadataLockConflict`, `ResponseMetadataPatchCollection`, `ResponseMetadataPatchItinerary`, `ResponseMetadataPatchZone`, `ResponseMetadataPostCollection`, `ResponseMetadataPostItinerary`, `ResponseMetadataPostZone`, `RestSchema`, `ReverseGeocodeResult`, `RoadAccessInfo`, `RoadAccessRestrictionType`, `SearchResult`, `SegmentConvertParams`, `SegmentCreateParams`, `SegmentGroupCreateParams`, `SegmentGroupUpdateParams`, `SegmentMode`, `SegmentSplitParams`, `SegmentUpdateParams`, `ServiceUnavailableResponse`, `Session`, `SessionSurface`, `ShareLink`, `SlopeInfo`, `SpeedInfo`, `StreamReconnectReason`, `StudioEntitlement`, `SuccessExtensions`, `SuggestionsResult`, `SurfaceInfo`, `SurfaceType`, `Terrain`, `TerrainGridResult`, `TerrainProfileResult`, `TerrainSamplesResult`, `TerrainTileSize`, `TerrainVariant`, `TerrainVariantAsStyle`, `TerrainVariantAsTiles`, `TerrainVariantConfig`, `TerrainVariants`, `Theme`, `TileLayer`, `TileLayerType`, `TileLegend`, `TileLegendKind`, `TileLegendStep`, `TileSchema`, `TileSource`, `TileSourceSize`, `TileSourceType`, `TooManyRequestsResponse`, `TrailDifficultyInfo`, `TrailDifficultyType`, `UnauthorizedResponse`, `UnitLegend`, `UnitLength`, `UnitPace`, `UnitSlope`, `UnitTemperature`, `WaypointAmenity`, `WaypointContact`, `WaypointCreateParams`, `WaypointIcon`, `WaypointLink`, `WaypointMedia`, `WaypointMode`, `WaypointPhoto`, `WaypointProperty`, `WaypointPropertyFormat`, `WaypointTiming`, `WaypointUpdateParams`, `WayType`, `WayTypeInfo`, `Zone`, `ZoneCreateParams`, `ZoneFeature`, `ZoneLevel`, `ZoneMode`, `ZoneSource`, `ZoneSourceKind`, `ZoneStatus`, `ZoneUpdateParams` |
1234
+ | the entry point | `Mountaya`, `MountayaTransport` | `BrowserClientOptions`, `MountayaTransport` |
1235
+
1236
+ #### `@mountaya/client/events`
1237
+
1238
+ | Declared under | Values | Types |
1239
+ | --- | --- | --- |
1240
+ | rules | `agentTerminalEventTypes`, `createAgentTransport`, `createCollabTransport`, `decodeAgentFrame`, `decodeCollabFrame`, `MAX_SSE_BUFFER_CHARS`, `openSseStream`, `readEventStream`, `SseBufferOverflowError`, `SseFrameParser` | `AgentEvent`, `AgentInput`, `AgentStreamCloseReason`, `AgentStreamFrame`, `AgentStreamHandlers`, `AgentSubscribeOptions`, `AgentTransport`, `AgentWriteOptions`, `CollabDurableChange`, `CollabEvent`, `CollabSignal`, `CollabSignalResult`, `CollabStreamCloseReason`, `CollabStreamErrorOptions`, `CollabStreamFrame`, `CollabStreamHandlers`, `CollabStreamResource`, `CollabSubscribeOptions`, `CollabTransport`, `EventStreamOutcome`, `FrameHandler`, `OpenSseStreamOptions`, `SseFrame` |
1241
+
1242
+ <!-- exports:end -->
1243
+
1244
+ ## Contributing
1245
+
1246
+ This package is generated into and published from
1247
+ [`mountaya/sdk-typescript`](https://github.com/mountaya/sdk-typescript). Its
1248
+ `*.gen.ts` files come from the public OpenAPI bundles: open an issue against the schema
1249
+ rather than a pull request against generated output.
1250
+
1251
+ [CONTRIBUTING.md](../../CONTRIBUTING.md) covers the rest: the build order the workspace derives,
1252
+ the gates `npm run lint` runs, and what the guard tests are guarding.
1253
+ [CHANGELOG.md](CHANGELOG.md) is what changed. A security issue goes to the address in
1254
+ [SECURITY.md](../../SECURITY.md), not to an issue.
1255
+
1256
+ ## Licence
1257
+
1258
+ Published under the Mountaya SDK License: source-available, for use with the Mountaya services
1259
+ while an agreement with Mountaya is in force. The terms are in [LICENSE.txt](LICENSE.txt), with a
1260
+ French translation in [LICENCE.fr.txt](LICENCE.fr.txt). The Data API is self-serve; the Map Studio API
1261
+ and the Tile API, which this client also calls, come with a signed agreement.