@tilery/client 0.1.0 → 0.1.4

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.
package/README.md CHANGED
@@ -2,14 +2,19 @@
2
2
 
3
3
  Client library for [Tilery.eu](https://tilery.eu) tile API with service worker caching and automatic token refresh.
4
4
 
5
+ > **`TileToken` → `AccessToken` (0.1.1):** the exported `TileToken` type was renamed to
6
+ > **`AccessToken`**. The token shape (`{ token, exp }`) is unchanged — only the type name
7
+ > differs, so update any `import type { TileToken }` to `import type { AccessToken }`.
8
+
5
9
  ## Features
6
10
 
7
- - **Token Management** - Automatic token refresh before expiry
11
+ - **Token Management** - Automatic token refresh before expiry, with retry backoff on failure
12
+ - **Maps that survive rotation** - `attachToMap` keeps tile requests on the current token
8
13
  - **Service Worker Caching** - Long-lived tile cache that survives token rotation
9
14
  - **No CORS Preflight** - Token passed as query parameter, not header
10
15
  - **MapLibre Integration** - Get ready-to-use style objects
11
16
 
12
- > The SDK implements only the JWT/token-exchange flow — that's the safe
17
+ > The SDK implements only the access-token exchange flow — that's the safe
13
18
  > path for browsers (15-minute lifetime, origin-locked, plays well with the
14
19
  > service-worker cache). The Tilery API also accepts an _app-mode_ API key
15
20
  > sent directly as `Authorization: Bearer …` for trusted backends, but
@@ -35,7 +40,7 @@ import maplibregl from "maplibre-gl";
35
40
  // Create client with your token fetcher
36
41
  const client = new TileryClient({
37
42
  getToken: async () => {
38
- // Your backend exchanges API key for short-lived JWT
43
+ // Your backend exchanges API key for short-lived access token
39
44
  const res = await fetch("/api/tile-token", { credentials: "include" });
40
45
  if (!res.ok) throw new Error("Failed to get token");
41
46
  return res.json(); // { token: string, exp: number }
@@ -52,8 +57,62 @@ const map = new maplibregl.Map({
52
57
  center: [10.75, 59.91],
53
58
  zoom: 12,
54
59
  });
60
+
61
+ // Keep tiles loading past the first token's expiry (max 15 min)
62
+ client.attachToMap(map);
63
+ ```
64
+
65
+ ## Keeping the map alive across token rotation
66
+
67
+ Access tokens are short-lived (15 minutes max). The client refreshes **its own** token
68
+ automatically before expiry — but `getMapStyle()` / `getTileJSON()` bake the token they had
69
+ _at call time_ into the tile URLs, so without one extra step the map keeps requesting tiles
70
+ with the original token and starts getting 401s once it expires (the service worker masks
71
+ this in already-visited areas, so it looks like flaky data in newly explored ones).
72
+
73
+ **Option 1 — `attachToMap` (recommended):**
74
+
75
+ ```typescript
76
+ const detach = client.attachToMap(map);
77
+ // later, if you tear the map down:
78
+ detach();
79
+ ```
80
+
81
+ This installs a MapLibre `transformRequest` that rewrites tile-server URLs to carry the
82
+ _current_ token at request time, and starts the refresh loop. Caveat: it **sets** the map's
83
+ `transformRequest` — if you already use your own, compose manually instead:
84
+
85
+ **Option 2 — compose with your own `transformRequest`:**
86
+
87
+ ```typescript
88
+ const map = new maplibregl.Map({
89
+ container: "map",
90
+ style: await client.getMapStyle({ flavor: "dark" }),
91
+ transformRequest: (url, resourceType) => {
92
+ // ...your own rewriting first, then hand non-Tilery URLs back unchanged:
93
+ return client.transformRequest(url, resourceType);
94
+ },
95
+ });
55
96
  ```
56
97
 
98
+ `client.transformRequest` is bound and synchronous. It only touches URLs that point at your
99
+ configured `tileServer` and either already carry a `?token=` param or are tile requests;
100
+ everything else passes through unchanged.
101
+
102
+ **Non-MapLibre libraries (Leaflet, OpenLayers, …):** re-set the source's tile URL template
103
+ whenever the token refreshes:
104
+
105
+ ```typescript
106
+ client.on("token:refresh", async () => {
107
+ const template = await client.getTileUrlTemplate();
108
+ // e.g. Leaflet: layer.setUrl(template) / OpenLayers: source.setUrl(template)
109
+ });
110
+ ```
111
+
112
+ If a refresh fails (network blip, laptop wake), the client retries automatically with capped
113
+ exponential backoff (1 s doubling up to 60 s) and emits `token:error` per failure — no
114
+ consumer action needed.
115
+
57
116
  ## Service Worker Setup
58
117
 
59
118
  The service worker code is bundled in the library. Create a file in your public directory:
@@ -80,14 +139,30 @@ Then register it:
80
139
  await client.registerServiceWorker();
81
140
  ```
82
141
 
83
- The service worker intercepts tile requests and:
142
+ > Registration always uses scope `/` so the worker controls every page on your
143
+ > origin. If you serve the file from a subdirectory (e.g.
144
+ > `/assets/tilery-sw.js` via `serviceWorkerPath`), your server must send a
145
+ > `Service-Worker-Allowed: /` header on that file — otherwise registration
146
+ > fails.
147
+
148
+ The service worker intercepts tile requests (only Tilery's
149
+ `/map/tiles/{kind}/{z}/{x}/{y}` paths — other providers' tiles are left alone)
150
+ and:
84
151
 
85
152
  1. Strips the `?token=` query parameter to create a normalized cache key
86
153
  2. Checks the cache using the normalized key
87
154
  3. On cache miss, fetches with the original URL (including token)
88
- 4. Stores the response under the normalized key
89
-
90
- This means tiles stay cached even when your token rotates!
155
+ 4. Stores the response under the normalized key — only when it actually looks
156
+ like a tile (protobuf/image content type), so a captive portal's HTML can
157
+ never poison the cache
158
+ 5. Serves cached tiles instantly; once a cached tile is older than the server's
159
+ cache policy (its `Cache-Control: max-age`, 7 days for tiles) it is still
160
+ served immediately but refreshed in the background (stale-while-revalidate)
161
+ 6. Trims the oldest entries once the cache exceeds 2000 tiles, so heavy panning
162
+ can't grow storage until the browser evicts the whole origin
163
+
164
+ This means tiles stay cached even when your token rotates, and tileset updates
165
+ still reach repeat visitors without anyone redeploying the service worker.
91
166
 
92
167
  ## API Reference
93
168
 
@@ -100,8 +175,8 @@ interface TileryClientOptions {
100
175
  // Required: async function that returns { token, exp }
101
176
  getToken: () => Promise<{ token: string; exp: number }>;
102
177
 
103
- // Optional: tile server URL (default: 'https://api.tilery.eu').
104
- // Use 'https://api.test.tilery.eu' to point at the staging environment.
178
+ // Optional: tile server URL (default: 'https://tiles.tilery.eu').
179
+ // Use 'https://tiles.test.tilery.eu' to point at the staging environment.
105
180
  tileServer?: string;
106
181
 
107
182
  // Optional: seconds before expiry to refresh (default: 60)
@@ -126,12 +201,18 @@ const style = await client.getMapStyle({
126
201
  flavor: "light", // see GET {tileServer}/map/styles for the full list
127
202
  });
128
203
 
204
+ // Keep the map's tile requests on the current token across rotations
205
+ const detach = client.attachToMap(map);
206
+
207
+ // Or compose yourself: MapLibre-compatible transformRequest (bound, sync)
208
+ client.transformRequest(url, resourceType);
209
+
129
210
  // Get URL templates
130
211
  const tileUrl = await client.getTileUrlTemplate();
131
212
  const glyphsUrl = client.getGlyphsUrl();
132
213
  const spriteUrl = client.getSpriteUrl("dark");
133
214
 
134
- // Clean up
215
+ // Clean up (stops the refresh loop and cancels retries)
135
216
  client.destroy();
136
217
  ```
137
218
 
@@ -153,11 +234,95 @@ client.on("sw:registered", (registration) => {
153
234
  client.on("sw:error", (error) => {
154
235
  console.error("Service worker failed:", error);
155
236
  });
237
+
238
+ client.on("balance:exhausted", ({ message, topUp }) => {
239
+ // The account is out of credits and tiles have stopped. Fires once.
240
+ showBanner(message, topUp);
241
+ });
242
+ ```
243
+
244
+ ## When credits run out
245
+
246
+ Tilery is prepaid. When an account's credit balance reaches zero, serving does not stop
247
+ dead: it continues through the **overrun allowance** — a fixed number of credits, published
248
+ at `GET https://tilery.eu/api/pricing` as `overrun_allowance_millicredits`, billed from the next
249
+ top-up — and stops at the end of it. From then on every tile request answers:
250
+
251
+ ```http
252
+ HTTP/1.1 402 Payment Required
253
+ content-type: application/json
254
+ tilery-balance: exhausted
255
+ cache-control: no-store, private
256
+
257
+ {
258
+ "error": "balance_exhausted",
259
+ "message": "Credit balance is empty, past the overrun allowance.",
260
+ "top_up": "https://tilery.eu/app/credits"
261
+ }
262
+ ```
263
+
264
+ Branch on `error` (or on the `tilery-balance` header, which is exposed cross-origin), never
265
+ on the sentence. The 402 is never cached — a stored one would outlive the top-up that fixes
266
+ it.
267
+
268
+ **With the service worker registered**, the SDK sees every tile response and surfaces this
269
+ for you:
270
+
271
+ ```typescript
272
+ const client = new TileryClient({ getToken });
273
+ await client.registerServiceWorker();
274
+
275
+ client.on("balance:exhausted", ({ error, message, topUp }) => {
276
+ // error → "balance_exhausted"
277
+ // message → a sentence you can show a user
278
+ // topUp → where to top up, or "" if the response arrived without a body
279
+ banner.textContent = message;
280
+ banner.querySelector("a").href = topUp || "https://tilery.eu/app/credits";
281
+ });
156
282
  ```
157
283
 
284
+ The event fires **once per client**, however many tiles fail — a blank map is hundreds of
285
+ requests. A tile that serves again resets it, so an account that tops up and later runs dry
286
+ is reported again.
287
+
288
+ **Without the service worker**, tiles are fetched by your map library and this SDK never
289
+ sees the responses. MapLibre surfaces them on its own `error` event:
290
+
291
+ ```typescript
292
+ map.on("error", (event) => {
293
+ if (event.error?.status === 402) {
294
+ showTopUpBanner();
295
+ }
296
+ });
297
+ ```
298
+
299
+ ### Reading the price list
300
+
301
+ `GET https://tilery.eu/api/pricing` is public, cached for five minutes, and says what an
302
+ operation costs and how far the overrun allowance reaches:
303
+
304
+ ```json
305
+ {
306
+ "unit": "millicredits",
307
+ "millicredits_per_euro": 250000,
308
+ "operations": {
309
+ "tiles_vector": { "millicredits": 10, "label": "Vector tiles", "order": 10 }
310
+ },
311
+ "overrun_allowance_millicredits": 125000
312
+ }
313
+ ```
314
+
315
+ Millicredits are the wire unit (the app shows credits, 1 000 millicredits each); euros are derived (`millicredits ÷ millicredits_per_euro`), and `operations`
316
+ grows as Tilery prices more of them — read it, rather than hardcoding a rate.
317
+
318
+ `millicredits_per_euro` is Tilery's **display conversion** — what a balance or a spend is roughly
319
+ worth. It is not what a credit pack charges: pack prices are quoted per 1 000 operations from
320
+ the smallest active pack and shown on the pricing page. Divide by this figure to render a euro
321
+ hint, never to predict what a top-up will cost.
322
+
158
323
  ## Backend Token Endpoint
159
324
 
160
- Your backend should exchange an API key for a short-lived JWT. Example with the Tilery API:
325
+ Your backend should exchange an API key for a short-lived access token. Example with the Tilery API:
161
326
 
162
327
  ```typescript
163
328
  // /api/tile-token.ts (your backend)
@@ -184,7 +349,7 @@ const client = new TileryClient({
184
349
 
185
350
  // Get token and build URLs manually
186
351
  const token = await client.getToken();
187
- const tileUrl = `https://api.tilery.eu/tiles/{z}/{x}/{y}?token=${token.token}`;
352
+ const tileUrl = `https://tiles.tilery.eu/map/tiles/vector/{z}/{x}/{y}?token=${token.token}`;
188
353
 
189
354
  // Use with any mapping library
190
355
  const map = new maplibregl.Map({
@@ -213,9 +378,12 @@ You can communicate with the service worker for cache management:
213
378
  // Clear all cached tiles
214
379
  navigator.serviceWorker.controller?.postMessage({ type: "CLEAR_CACHE" });
215
380
 
216
- // Get cache size
381
+ // Get cache size — `entries` counts cached tiles; `usageBytes` is the
382
+ // origin-wide storage estimate (null where the StorageManager API is
383
+ // unavailable). `size` is a legacy alias for `entries`.
217
384
  const channel = new MessageChannel();
218
- channel.port1.onmessage = (e) => console.log("Cache size:", e.data.size);
385
+ channel.port1.onmessage = (e) =>
386
+ console.log(`Cached tiles: ${e.data.entries}, origin storage: ${e.data.usageBytes} bytes`);
219
387
  navigator.serviceWorker.controller?.postMessage({ type: "GET_CACHE_SIZE" }, [channel.port2]);
220
388
  ```
221
389
 
package/dist/client.d.ts CHANGED
@@ -1,4 +1,28 @@
1
- import type { EventListener, MapStyle, MapStyleOptions, TileToken, TileryClientEvents, TileryClientOptions } from "./types.js";
1
+ import type { EventListener, MapLike, MapStyle, MapStyleOptions, TileJSON, AccessToken, TileryClientEvents, TileryClientOptions, TransformedRequest } from "./types.js";
2
+ /**
3
+ * Minimum delay before any scheduled token refresh. Floors the schedule so a
4
+ * pathological `getToken` result (e.g. an already-expired `exp` from clock
5
+ * skew or an HTTP-cached token response) can never produce a 0 ms mint loop.
6
+ */
7
+ export declare const MIN_REFRESH_DELAY_MS = 5000;
8
+ /**
9
+ * Base delay for the retry backoff after a failed refresh. Consecutive
10
+ * failures back off at `RETRY_BASE_DELAY_MS · 2ⁿ⁻¹`, capped at
11
+ * {@link MAX_RETRY_DELAY_MS}; a success resets the streak.
12
+ */
13
+ export declare const RETRY_BASE_DELAY_MS = 1000;
14
+ /** Upper bound for the retry backoff after failed refreshes. */
15
+ export declare const MAX_RETRY_DELAY_MS = 60000;
16
+ /**
17
+ * The message the service worker posts to every page when a tile request comes
18
+ * back `402` — the account is out of credits and the map has stopped drawing.
19
+ *
20
+ * Exported so a consumer who wires their own `navigator.serviceWorker`
21
+ * listener (or ships the worker without this client) can recognise it. The
22
+ * same string is spelled in `service-worker.ts`, which cannot import: it is
23
+ * transformed rather than bundled, and ships as a classic script.
24
+ */
25
+ export declare const BALANCE_EXHAUSTED_MESSAGE_TYPE = "tilery:balance-exhausted";
2
26
  /**
3
27
  * Tilery client for managing tile tokens and service worker caching.
4
28
  *
@@ -18,23 +42,85 @@ import type { EventListener, MapStyle, MapStyleOptions, TileToken, TileryClientE
18
42
  export declare class TileryClient {
19
43
  private readonly getTokenFn;
20
44
  private readonly tileServer;
45
+ /** `tileServer` without a trailing slash, for `startsWith(base + "/")` origin checks. */
46
+ private readonly tileServerBase;
21
47
  private readonly refreshBuffer;
22
48
  private readonly swPath;
23
49
  private currentToken;
24
50
  private refreshTimeout;
25
51
  private tokenPromise;
52
+ private consecutiveFailures;
53
+ private destroyed;
54
+ /** "balance:exhausted" is once per client — see the event's docs. */
55
+ private balanceExhaustedEmitted;
26
56
  private listeners;
57
+ private static emptyListeners;
27
58
  constructor(options: TileryClientOptions);
59
+ /**
60
+ * Listen for the service worker's balance report.
61
+ *
62
+ * Wired here rather than in `registerServiceWorker()` because the worker may
63
+ * already be installed from an earlier page load — a consumer who registers
64
+ * once at deploy time still gets the event on every subsequent visit. Absent
65
+ * `navigator.serviceWorker` (Node, an old browser, a non-secure origin) this
66
+ * is simply a no-op.
67
+ */
68
+ private listenForWorkerMessages;
69
+ /** Bound, so `destroy()` can remove exactly this listener. */
70
+ private readonly onWorkerMessage;
28
71
  /**
29
72
  * Get current valid token, fetching if needed.
30
73
  * Token is cached and auto-refreshed before expiry.
31
74
  */
32
- getToken(): Promise<TileToken>;
75
+ getToken(): Promise<AccessToken>;
33
76
  /**
34
77
  * Get the current token string, or null if not yet fetched.
35
78
  * Does not trigger a fetch - use getToken() for that.
36
79
  */
37
80
  getCurrentTokenString(): string | null;
81
+ /**
82
+ * MapLibre-compatible `transformRequest` that rewrites tile-server URLs to
83
+ * carry the **current** access token at request time — the piece that keeps
84
+ * a map alive across token rotation (styles bake the initial token in once).
85
+ *
86
+ * Rewrites a URL only when it points at this client's `tileServer` **and**
87
+ * either already carries a `token` query param or is a tile request;
88
+ * everything else (foreign hosts, glyphs, sprites, styles) passes through
89
+ * unchanged. Before the first token is fetched, URLs pass through unchanged
90
+ * (the initial style already carries a token).
91
+ *
92
+ * Bound and synchronous, so it can be handed to MapLibre directly:
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * const map = new maplibregl.Map({
97
+ * container: 'map',
98
+ * style: await client.getMapStyle(),
99
+ * transformRequest: client.transformRequest,
100
+ * });
101
+ * ```
102
+ */
103
+ readonly transformRequest: (url: string, _resourceType?: string) => TransformedRequest;
104
+ /**
105
+ * Wire this client into a MapLibre map so tiles keep loading across token
106
+ * rotation: installs {@link transformRequest} via `map.setTransformRequest`
107
+ * and kicks {@link getToken} so the auto-refresh loop is running.
108
+ *
109
+ * Returns a `detach()` function that clears the hook
110
+ * (`map.setTransformRequest(null)`).
111
+ *
112
+ * **Caveat:** this *sets* the map's transformRequest. If you already use
113
+ * your own `transformRequest`, don't call this — compose manually with
114
+ * {@link transformRequest} and pass the composed function at map
115
+ * construction instead.
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * const map = new maplibregl.Map({ container: 'map', style });
120
+ * const detach = client.attachToMap(map);
121
+ * ```
122
+ */
123
+ attachToMap(map: MapLike): () => void;
38
124
  /**
39
125
  * Register the service worker for tile caching.
40
126
  * Normalizes cache keys by stripping the token param for long-lived caching.
@@ -83,6 +169,18 @@ export declare class TileryClient {
83
169
  * ```
84
170
  */
85
171
  getMapStyle(options?: MapStyleOptions): Promise<MapStyle>;
172
+ /**
173
+ * Fetch the vector tileset's TileJSON descriptor and inject the current
174
+ * access token into the `tiles` URL template(s). The result can be used
175
+ * directly as a MapLibre/Leaflet/OpenLayers source.
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * const tilejson = await client.getTileJSON();
180
+ * map.addSource('tilery', { type: 'vector', ...tilejson });
181
+ * ```
182
+ */
183
+ getTileJSON(): Promise<TileJSON>;
86
184
  /**
87
185
  * Subscribe to an event.
88
186
  */
@@ -92,12 +190,37 @@ export declare class TileryClient {
92
190
  */
93
191
  off<K extends keyof TileryClientEvents>(event: K, listener: EventListener<TileryClientEvents[K]>): void;
94
192
  /**
95
- * Stop token refresh and clean up.
193
+ * Stop token refresh and clean up. Cancels the refresh timer and any
194
+ * pending failure-backoff retry; an in-flight fetch may still settle but
195
+ * will not schedule anything afterwards.
96
196
  */
97
197
  destroy(): void;
198
+ /**
199
+ * Emit "balance:exhausted", at most once for this client. Both detectors —
200
+ * the service worker's message and the SDK's own fetches — land here, so a
201
+ * page running both reports the stop once.
202
+ */
203
+ private emitBalanceExhausted;
204
+ /**
205
+ * The direct-fetch detector: the SDK's own requests to the tile server.
206
+ *
207
+ * Tiles themselves are fetched by the map library, not by this SDK, so this
208
+ * covers only what the SDK asks for — with the service worker installed, the
209
+ * worker is what sees a failing tile. Never throws: the caller is already on
210
+ * its way to reporting the failure its own way.
211
+ */
212
+ private noteResponse;
98
213
  private emit;
99
214
  private isTokenExpiringSoon;
100
215
  private fetchAndScheduleRefresh;
216
+ /**
217
+ * Timer-path refresh. Honors the same single-flight invariant as
218
+ * `getToken()`: if a mint is already in flight, that mint will schedule the
219
+ * next refresh (or the retry backoff) itself, so this becomes a no-op.
220
+ */
221
+ private refreshNow;
101
222
  private scheduleRefresh;
223
+ private scheduleRetryAfterFailure;
224
+ private setRefreshTimer;
102
225
  }
103
226
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,aAAa,EAEb,QAAQ,EACR,eAAe,EACf,SAAS,EACT,kBAAkB,EAClB,mBAAmB,EACpB,MAAM,YAAY,CAAC;AASpB;;;;;;;;;;;;;;;GAeG;AACH,qB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R,QAAQ,EAAE,aAAa,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,GAC7C,IAAI,CAEN;IAED;;OAEG;IACH,GAAG,CAAC,CAAC,SAAS,MAAM,kBAAkB,EACpC,KAAK,EAAE,CAAC,EACR,QAAQ,EAAE,aAAa,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,GAC7C,IAAI,CAEN;IAED;;;;OAIG;IACH,OAAO,IAAI,IAAI,CAYd;IAID;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAQ5B;;;;;;;OAOG;YACW,YAAY;IAQ1B,OAAO,CAAC,IAAI;IAUZ,OAAO,CAAC,mBAAmB;YAKb,uBAAuB;IAoBrC;;;;OAIG;IACH,OAAO,CAAC,UAAU;IAkBlB,OAAO,CAAC,eAAe;IASvB,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,eAAe;CAYxB"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { TileryClient } from "./client.js";
1
+ export { BALANCE_EXHAUSTED_MESSAGE_TYPE, MAX_RETRY_DELAY_MS, MIN_REFRESH_DELAY_MS, RETRY_BASE_DELAY_MS, TileryClient, } from "./client.js";
2
2
  export { default as SERVICE_WORKER_CODE } from "virtual:service-worker-code";
3
- export type { TileryClientOptions, TileryClientEvents, TileToken, GetTokenFn, MapStyleOptions, MapStyle, EventListener, } from "./types.js";
3
+ export type { BalanceExhausted, TileryClientOptions, TileryClientEvents, AccessToken, GetTokenFn, MapLike, MapStyleOptions, MapStyle, TileJSON, TransformedRequest, TransformRequestFn, EventListener, } from "./types.js";
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAC7E,YAAY,EACV,mBAAmB,EACnB,kBAAkB,EAClB,SAAS,EACT,UAAU,EACV,eAAe,EACf,QAAQ,EACR,aAAa,GACd,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,EAC9B,kBAAkB,EAClB,oBAAoB,EACpB,mBAAmB,EACnB,YAAY,GACb,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAC7E,YAAY,EACV,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,WAAW,EACX,UAAU,EACV,OAAO,EACP,eAAe,EACf,QAAQ,EACR,QAAQ,EACR,kBAAkB,EAClB,kBAAkB,EAClB,aAAa,GACd,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,12 +1,109 @@
1
1
  //#region \0virtual:service-worker-code
2
- var code = "const r=globalThis,c=\"tilery-tiles-v1\",l=/\\/tiles\\/\\d+\\/\\d+\\/\\d+/;function o(e){const t=new URL(e);return t.searchParams.delete(\"token\"),t.toString()}function h(e){return l.test(e)}r.addEventListener(\"install\",e=>{e.waitUntil(r.skipWaiting())}),r.addEventListener(\"activate\",e=>{e.waitUntil(Promise.all([r.clients.claim(),caches.keys().then(t=>Promise.all(t.filter(s=>s.startsWith(\"tilery-\")&&s!==c).map(s=>caches.delete(s))))]))}),r.addEventListener(\"fetch\",e=>{const{request:t}=e;h(t.url)&&e.respondWith(d(t))});async function d(e){const t=await caches.open(c),s=o(e.url),n=await t.match(s);if(n)return n;try{const a=await fetch(e);if(a.ok){const i=a.clone();t.put(s,i)}return a}catch(a){const i=await t.match(s);if(i)return i;throw a}}r.addEventListener(\"message\",e=>{const{type:t,payload:s}=e.data||{};switch(t){case\"CLEAR_CACHE\":e.waitUntil(caches.delete(c).then(()=>{e.ports[0]?.postMessage({success:!0})}));break;case\"GET_CACHE_SIZE\":e.waitUntil(caches.open(c).then(async n=>{const a=await n.keys();e.ports[0]?.postMessage({size:a.length})}));break;case\"DELETE_TILE\":if(s?.url){const n=o(s.url);e.waitUntil(caches.open(c).then(async a=>{const i=await a.delete(n);e.ports[0]?.postMessage({deleted:i})}))}break}});export{};\n";
2
+ var code = "(()=>{const r=globalThis,i=\"tilery-tiles-v1\",m=/\\/map\\/tiles\\/[a-z0-9_]+\\/\\d+\\/\\d+\\/\\d+/,E=[\"application/x-protobuf\",\"application/vnd.mapbox-vector-tile\",\"application/octet-stream\",\"image/\"],p=2e3,w=\"tilery:balance-exhausted\",c={error:\"balance_exhausted\",message:\"Credit balance is empty, past the overrun allowance.\",topUp:\"\"};let l=!1;function d(e){const s=new URL(e);return s.searchParams.delete(\"token\"),s.toString()}function y(e){return m.test(e)}r.addEventListener(\"install\",e=>{e.waitUntil(r.skipWaiting())});r.addEventListener(\"activate\",e=>{e.waitUntil(Promise.all([r.clients.claim(),caches.keys().then(s=>Promise.all(s.filter(t=>t.startsWith(\"tilery-\")&&t!==i).map(t=>caches.delete(t))))]))});r.addEventListener(\"fetch\",e=>{const{request:s}=e;y(s.url)&&e.respondWith(C(e))});const _=10080*60,A=1e3;function T(e){const s=e.headers.get(\"date\"),t=s===null?Number.NaN:Date.parse(s);if(Number.isNaN(t))return!1;const a=e.headers.get(\"cache-control\")?.match(/max-age=(\\d+)/),n=a?Number(a[1]):_;return Date.now()-t<=n*A}function h(e){if(!e.ok)return!1;const s=e.headers.get(\"content-type\")??\"\";return E.some(t=>s.startsWith(t))}async function b(e){try{const s=await e.json();if(typeof s==\"object\"&&s!==null){const t={...s};return{error:typeof t.error==\"string\"?t.error:c.error,message:typeof t.message==\"string\"?t.message:c.message,topUp:typeof t.top_up==\"string\"?t.top_up:\"\"}}}catch{}return c}async function R(e){if(l)return;l=!0;const s=await b(e),t=await r.clients.matchAll({includeUncontrolled:!0,type:\"window\"});for(const a of t)a.postMessage({payload:s,type:w})}function f(e){return e.status===402?R(e.clone()):(e.ok&&(l=!1),Promise.resolve())}async function g(e,s,t){try{await e.put(s,t);const a=await e.keys();a.length>p&&await Promise.all(a.slice(0,a.length-p).map(n=>e.delete(n)))}catch{}}async function U(e,s,t){try{const a=await fetch(s);await f(a),h(a)&&await g(e,t,a)}catch{}}async function C(e){const{request:s}=e,t=await caches.open(i),a=d(s.url),n=await t.match(a);if(n)return T(n)||e.waitUntil(U(t,s,a)),n;try{const o=await fetch(s);return e.waitUntil(f(o)),h(o)&&e.waitUntil(g(t,a,o.clone())),o}catch(o){const u=await t.match(a);if(u)return u;throw o}}async function P(){try{if(typeof navigator>\"u\"||!navigator.storage?.estimate)return null;const{usage:e}=await navigator.storage.estimate();return e??null}catch{return null}}r.addEventListener(\"message\",e=>{const{type:s,payload:t}=e.data||{};switch(s){case\"CLEAR_CACHE\":e.waitUntil(caches.delete(i).then(()=>{e.ports[0]?.postMessage({success:!0})}));break;case\"GET_CACHE_SIZE\":e.waitUntil(caches.open(i).then(async a=>{const n=await a.keys(),o=await P();e.ports[0]?.postMessage({entries:n.length,size:n.length,usageBytes:o})}));break;case\"DELETE_TILE\":t?.url&&e.waitUntil((async()=>{try{const a=d(t.url),o=await(await caches.open(i)).delete(a);e.ports[0]?.postMessage({deleted:o})}catch{e.ports[0]?.postMessage({deleted:!1})}})());break}});})();\n";
3
+ //#endregion
4
+ //#region src/validate.ts
5
+ var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
+ var isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
7
+ /**
8
+ * Checks the fields `getMapStyle` touches: `sources` must be a record of
9
+ * source objects, each of whose `tiles` — optional, e.g. absent on a
10
+ * raster-dem terrain source — must be a `string[]` for token injection, and
11
+ * `layers` must be an array.
12
+ */
13
+ function isMapStyle(value) {
14
+ if (!isRecord$1(value)) return false;
15
+ if (!Array.isArray(value.layers)) return false;
16
+ if (!isRecord$1(value.sources)) return false;
17
+ return Object.values(value.sources).every((source) => isRecord$1(source) && (source.tiles === void 0 || isStringArray(source.tiles)));
18
+ }
19
+ /**
20
+ * Checks the fields `getTileJSON` touches: `tiles` must be a `string[]` for
21
+ * token injection, and `tilejson` must be the spec-version string.
22
+ */
23
+ function isTileJSON(value) {
24
+ return isRecord$1(value) && typeof value.tilejson === "string" && isStringArray(value.tiles);
25
+ }
3
26
  //#endregion
4
27
  //#region src/client.ts
5
28
  var MS_PER_SECOND = 1e3;
6
- var DEFAULT_TILE_SERVER = "https://api.tilery.eu";
29
+ var DEFAULT_TILE_SERVER = "https://tiles.tilery.eu";
7
30
  var DEFAULT_REFRESH_BUFFER = 60;
8
31
  var DEFAULT_SW_PATH = "/tilery-sw.js";
9
32
  /**
33
+ * Minimum delay before any scheduled token refresh. Floors the schedule so a
34
+ * pathological `getToken` result (e.g. an already-expired `exp` from clock
35
+ * skew or an HTTP-cached token response) can never produce a 0 ms mint loop.
36
+ */
37
+ var MIN_REFRESH_DELAY_MS = 5e3;
38
+ /**
39
+ * Base delay for the retry backoff after a failed refresh. Consecutive
40
+ * failures back off at `RETRY_BASE_DELAY_MS · 2ⁿ⁻¹`, capped at
41
+ * {@link MAX_RETRY_DELAY_MS}; a success resets the streak.
42
+ */
43
+ var RETRY_BASE_DELAY_MS = 1e3;
44
+ /** Upper bound for the retry backoff after failed refreshes. */
45
+ var MAX_RETRY_DELAY_MS = 6e4;
46
+ /** `exp` values above `now-in-seconds × 100` are almost certainly unix milliseconds. */
47
+ var MS_EXP_HEURISTIC_FACTOR = 100;
48
+ /**
49
+ * The message the service worker posts to every page when a tile request comes
50
+ * back `402` — the account is out of credits and the map has stopped drawing.
51
+ *
52
+ * Exported so a consumer who wires their own `navigator.serviceWorker`
53
+ * listener (or ships the worker without this client) can recognise it. The
54
+ * same string is spelled in `service-worker.ts`, which cannot import: it is
55
+ * transformed rather than bundled, and ships as a classic script.
56
+ */
57
+ var BALANCE_EXHAUSTED_MESSAGE_TYPE = "tilery:balance-exhausted";
58
+ /** HTTP status the tile API answers with once the credits are gone. */
59
+ var PAYMENT_REQUIRED = 402;
60
+ /** What the SDK says when a 402 carries no readable body. Matches the
61
+ * service worker's own fallback; the top-up URL is never invented. */
62
+ var BALANCE_EXHAUSTED_FALLBACK = {
63
+ error: "balance_exhausted",
64
+ message: "Credit balance is empty, past the overrun allowance.",
65
+ topUp: ""
66
+ };
67
+ /** Concrete tile request path: `/map/tiles/{kind}/{z}/{x}/{y}`. */
68
+ var TILE_PATH_PATTERN = /\/map\/tiles\/[a-z0-9_]+\/\d+\/\d+\/\d+/;
69
+ function isRecord(value) {
70
+ return typeof value === "object" && value !== null;
71
+ }
72
+ /** A string field, or the written-out fallback. */
73
+ function stringOr(value, fallback) {
74
+ return typeof value === "string" ? value : fallback;
75
+ }
76
+ /**
77
+ * Narrow whatever arrives — a `postMessage` payload from the service worker,
78
+ * or a parsed 402 body — into the event's shape. `top_up` is the wire
79
+ * spelling; `topUp` is what a worker message already carries.
80
+ */
81
+ function toBalanceExhausted(value) {
82
+ if (!isRecord(value)) return BALANCE_EXHAUSTED_FALLBACK;
83
+ return {
84
+ error: stringOr(value.error, BALANCE_EXHAUSTED_FALLBACK.error),
85
+ message: stringOr(value.message, BALANCE_EXHAUSTED_FALLBACK.message),
86
+ topUp: stringOr(value.topUp ?? value.top_up, "")
87
+ };
88
+ }
89
+ /**
90
+ * Validate a `getToken` result at the boundary. Consumer mistakes (returning
91
+ * the `Response` itself, `exp` in milliseconds, `{ token }` only) must fail
92
+ * loudly here instead of becoming a "never expires" token or a hot mint loop.
93
+ */
94
+ function validateTokenResult(value) {
95
+ const expected = "[TileryClient] getToken must resolve to { token: string, exp: number } (exp in unix seconds)";
96
+ if (!isRecord(value)) throw new TypeError(`${expected}; got ${typeof value}`);
97
+ const { exp, token } = value;
98
+ if (typeof token !== "string" || token.length === 0) throw new TypeError(`${expected}; token is missing or not a non-empty string`);
99
+ if (typeof exp !== "number" || !Number.isFinite(exp)) throw new TypeError(`${expected}; exp is missing or not a finite number`);
100
+ if (exp > Date.now() / MS_PER_SECOND * MS_EXP_HEURISTIC_FACTOR) console.warn("[TileryClient] getToken returned an exp that looks like unix milliseconds — expected unix seconds");
101
+ return {
102
+ exp,
103
+ token
104
+ };
105
+ }
106
+ /**
10
107
  * Tilery client for managing tile tokens and service worker caching.
11
108
  *
12
109
  * @example
@@ -22,16 +119,63 @@ var DEFAULT_SW_PATH = "/tilery-sw.js";
22
119
  * const style = await client.getMapStyle({ flavor: 'dark' });
23
120
  * ```
24
121
  */
25
- var TileryClient = class {
122
+ var TileryClient = class TileryClient {
123
+ static emptyListeners() {
124
+ return {
125
+ "balance:exhausted": /* @__PURE__ */ new Set(),
126
+ "token:refresh": /* @__PURE__ */ new Set(),
127
+ "token:error": /* @__PURE__ */ new Set(),
128
+ "sw:registered": /* @__PURE__ */ new Set(),
129
+ "sw:error": /* @__PURE__ */ new Set()
130
+ };
131
+ }
26
132
  constructor(options) {
27
133
  this.currentToken = null;
28
134
  this.refreshTimeout = null;
29
135
  this.tokenPromise = null;
30
- this.listeners = /* @__PURE__ */ new Map();
136
+ this.consecutiveFailures = 0;
137
+ this.destroyed = false;
138
+ this.balanceExhaustedEmitted = false;
139
+ this.listeners = TileryClient.emptyListeners();
140
+ this.onWorkerMessage = (event) => {
141
+ if (!("data" in event)) return;
142
+ const { data } = event;
143
+ if (!isRecord(data) || data.type !== "tilery:balance-exhausted") return;
144
+ if (!isRecord(data.payload)) return;
145
+ this.emitBalanceExhausted(toBalanceExhausted(data.payload));
146
+ };
147
+ this.transformRequest = (url, _resourceType) => {
148
+ const token = this.currentToken?.token;
149
+ if (!token) return { url };
150
+ if (!url.startsWith(`${this.tileServerBase}/`)) return { url };
151
+ try {
152
+ const parsed = new URL(url);
153
+ if (!parsed.searchParams.has("token") && !TILE_PATH_PATTERN.test(parsed.pathname)) return { url };
154
+ parsed.searchParams.set("token", token);
155
+ return { url: parsed.toString() };
156
+ } catch {
157
+ return { url };
158
+ }
159
+ };
31
160
  this.getTokenFn = options.getToken;
32
161
  this.tileServer = options.tileServer ?? DEFAULT_TILE_SERVER;
162
+ this.tileServerBase = this.tileServer.endsWith("/") ? this.tileServer.slice(0, -1) : this.tileServer;
33
163
  this.refreshBuffer = options.refreshBuffer ?? DEFAULT_REFRESH_BUFFER;
34
164
  this.swPath = options.serviceWorkerPath ?? DEFAULT_SW_PATH;
165
+ this.listenForWorkerMessages();
166
+ }
167
+ /**
168
+ * Listen for the service worker's balance report.
169
+ *
170
+ * Wired here rather than in `registerServiceWorker()` because the worker may
171
+ * already be installed from an earlier page load — a consumer who registers
172
+ * once at deploy time still gets the event on every subsequent visit. Absent
173
+ * `navigator.serviceWorker` (Node, an old browser, a non-secure origin) this
174
+ * is simply a no-op.
175
+ */
176
+ listenForWorkerMessages() {
177
+ if (typeof navigator === "undefined" || !navigator.serviceWorker) return;
178
+ navigator.serviceWorker.addEventListener("message", this.onWorkerMessage);
35
179
  }
36
180
  /**
37
181
  * Get current valid token, fetching if needed.
@@ -55,6 +199,32 @@ var TileryClient = class {
55
199
  return this.currentToken?.token ?? null;
56
200
  }
57
201
  /**
202
+ * Wire this client into a MapLibre map so tiles keep loading across token
203
+ * rotation: installs {@link transformRequest} via `map.setTransformRequest`
204
+ * and kicks {@link getToken} so the auto-refresh loop is running.
205
+ *
206
+ * Returns a `detach()` function that clears the hook
207
+ * (`map.setTransformRequest(null)`).
208
+ *
209
+ * **Caveat:** this *sets* the map's transformRequest. If you already use
210
+ * your own `transformRequest`, don't call this — compose manually with
211
+ * {@link transformRequest} and pass the composed function at map
212
+ * construction instead.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * const map = new maplibregl.Map({ container: 'map', style });
217
+ * const detach = client.attachToMap(map);
218
+ * ```
219
+ */
220
+ attachToMap(map) {
221
+ map.setTransformRequest(this.transformRequest);
222
+ this.getToken().catch(() => {});
223
+ return () => {
224
+ map.setTransformRequest(null);
225
+ };
226
+ }
227
+ /**
58
228
  * Register the service worker for tile caching.
59
229
  * Normalizes cache keys by stripping the token param for long-lived caching.
60
230
  *
@@ -96,7 +266,7 @@ var TileryClient = class {
96
266
  const { token, x, y, z } = options;
97
267
  const tok = token ?? this.currentToken?.token;
98
268
  if (!tok) throw new Error("No token available. Call getToken() first.");
99
- return `${this.tileServer}/map/tiles/${z}/${x}/${y}?token=${encodeURIComponent(tok)}`;
269
+ return `${this.tileServer}/map/tiles/vector/${z}/${x}/${y}?token=${encodeURIComponent(tok)}`;
100
270
  }
101
271
  /**
102
272
  * Get the tile URL template with {z}, {x}, {y} placeholders.
@@ -104,7 +274,7 @@ var TileryClient = class {
104
274
  */
105
275
  async getTileUrlTemplate() {
106
276
  const token = await this.getToken();
107
- return `${this.tileServer}/map/tiles/{z}/{x}/{y}?token=${encodeURIComponent(token.token)}`;
277
+ return `${this.tileServer}/map/tiles/vector/{z}/{x}/{y}?token=${encodeURIComponent(token.token)}`;
108
278
  }
109
279
  /**
110
280
  * Get the font (glyph) URL template.
@@ -131,39 +301,100 @@ var TileryClient = class {
131
301
  async getMapStyle(options = {}) {
132
302
  const { flavor = "light" } = options;
133
303
  const [token, res] = await Promise.all([this.getToken(), fetch(`${this.tileServer}/map/styles/${encodeURIComponent(flavor)}`)]);
134
- if (!res.ok) throw new Error(`Failed to fetch style "${flavor}": ${res.status} ${res.statusText}`);
135
- const style = await res.json();
304
+ if (!res.ok) {
305
+ await this.noteResponse(res);
306
+ throw new Error(`Failed to fetch style "${flavor}": ${res.status} ${res.statusText}`);
307
+ }
308
+ const body = await res.json();
309
+ if (!isMapStyle(body)) throw new Error(`Tile server returned an unexpected style response for "${flavor}"`);
310
+ const style = body;
136
311
  const tokenParam = `token=${encodeURIComponent(token.token)}`;
137
- for (const source of Object.values(style.sources)) source.tiles = source.tiles.map((url) => url.includes("?") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`);
312
+ for (const source of Object.values(style.sources)) {
313
+ if (!Array.isArray(source.tiles)) continue;
314
+ source.tiles = source.tiles.map((url) => {
315
+ if (!url.startsWith(`${this.tileServerBase}/`)) return url;
316
+ return url.includes("?") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`;
317
+ });
318
+ }
138
319
  return style;
139
320
  }
140
321
  /**
322
+ * Fetch the vector tileset's TileJSON descriptor and inject the current
323
+ * access token into the `tiles` URL template(s). The result can be used
324
+ * directly as a MapLibre/Leaflet/OpenLayers source.
325
+ *
326
+ * @example
327
+ * ```ts
328
+ * const tilejson = await client.getTileJSON();
329
+ * map.addSource('tilery', { type: 'vector', ...tilejson });
330
+ * ```
331
+ */
332
+ async getTileJSON() {
333
+ const [token, res] = await Promise.all([this.getToken(), fetch(`${this.tileServer}/map/tiles/vector.json`)]);
334
+ if (!res.ok) {
335
+ await this.noteResponse(res);
336
+ throw new Error(`Failed to fetch TileJSON: ${res.status} ${res.statusText}`);
337
+ }
338
+ const body = await res.json();
339
+ if (!isTileJSON(body)) throw new Error("Tile server returned an unexpected TileJSON response");
340
+ const tilejson = body;
341
+ const tokenParam = `token=${encodeURIComponent(token.token)}`;
342
+ tilejson.tiles = tilejson.tiles.map((url) => url.includes("?") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`);
343
+ return tilejson;
344
+ }
345
+ /**
141
346
  * Subscribe to an event.
142
347
  */
143
348
  on(event, listener) {
144
- if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
145
- this.listeners.get(event).add(listener);
349
+ this.listeners[event].add(listener);
146
350
  }
147
351
  /**
148
352
  * Unsubscribe from an event.
149
353
  */
150
354
  off(event, listener) {
151
- this.listeners.get(event)?.delete(listener);
355
+ this.listeners[event].delete(listener);
152
356
  }
153
357
  /**
154
- * Stop token refresh and clean up.
358
+ * Stop token refresh and clean up. Cancels the refresh timer and any
359
+ * pending failure-backoff retry; an in-flight fetch may still settle but
360
+ * will not schedule anything afterwards.
155
361
  */
156
362
  destroy() {
363
+ this.destroyed = true;
364
+ if (typeof navigator !== "undefined" && navigator.serviceWorker) navigator.serviceWorker.removeEventListener("message", this.onWorkerMessage);
157
365
  if (this.refreshTimeout) {
158
366
  clearTimeout(this.refreshTimeout);
159
367
  this.refreshTimeout = null;
160
368
  }
161
369
  this.currentToken = null;
162
370
  this.tokenPromise = null;
163
- this.listeners.clear();
371
+ this.listeners = TileryClient.emptyListeners();
372
+ }
373
+ /**
374
+ * Emit "balance:exhausted", at most once for this client. Both detectors —
375
+ * the service worker's message and the SDK's own fetches — land here, so a
376
+ * page running both reports the stop once.
377
+ */
378
+ emitBalanceExhausted(payload) {
379
+ if (this.balanceExhaustedEmitted) return;
380
+ this.balanceExhaustedEmitted = true;
381
+ this.emit("balance:exhausted", payload);
382
+ }
383
+ /**
384
+ * The direct-fetch detector: the SDK's own requests to the tile server.
385
+ *
386
+ * Tiles themselves are fetched by the map library, not by this SDK, so this
387
+ * covers only what the SDK asks for — with the service worker installed, the
388
+ * worker is what sees a failing tile. Never throws: the caller is already on
389
+ * its way to reporting the failure its own way.
390
+ */
391
+ async noteResponse(response) {
392
+ if (response.status !== PAYMENT_REQUIRED) return;
393
+ const body = await response.json().catch(() => null);
394
+ this.emitBalanceExhausted(toBalanceExhausted(body));
164
395
  }
165
396
  emit(event, data) {
166
- this.listeners.get(event)?.forEach((listener) => {
397
+ this.listeners[event].forEach((listener) => {
167
398
  try {
168
399
  listener(data);
169
400
  } catch (e) {
@@ -177,35 +408,56 @@ var TileryClient = class {
177
408
  }
178
409
  async fetchAndScheduleRefresh() {
179
410
  try {
180
- const token = await this.getTokenFn();
411
+ const token = validateTokenResult(await this.getTokenFn());
181
412
  this.currentToken = token;
413
+ this.consecutiveFailures = 0;
182
414
  this.scheduleRefresh(token);
183
415
  this.emit("token:refresh", token);
184
416
  return token;
185
417
  } catch (error) {
186
418
  const err = error instanceof Error ? error : new Error(String(error));
419
+ this.consecutiveFailures += 1;
187
420
  this.emit("token:error", err);
421
+ this.scheduleRetryAfterFailure();
188
422
  throw err;
189
423
  }
190
424
  }
425
+ /**
426
+ * Timer-path refresh. Honors the same single-flight invariant as
427
+ * `getToken()`: if a mint is already in flight, that mint will schedule the
428
+ * next refresh (or the retry backoff) itself, so this becomes a no-op.
429
+ */
430
+ refreshNow() {
431
+ if (this.tokenPromise) return;
432
+ const promise = this.fetchAndScheduleRefresh();
433
+ this.tokenPromise = promise;
434
+ promise.catch((error) => {
435
+ console.error("[TileryClient] Token refresh failed:", error);
436
+ }).finally(() => {
437
+ if (this.tokenPromise === promise) this.tokenPromise = null;
438
+ });
439
+ }
191
440
  scheduleRefresh(token) {
192
- if (this.refreshTimeout) clearTimeout(this.refreshTimeout);
193
441
  const now = Math.floor(Date.now() / MS_PER_SECOND);
194
442
  const refreshAt = token.exp - this.refreshBuffer;
195
- const delayMs = Math.max(0, (refreshAt - now) * MS_PER_SECOND);
196
- this.refreshTimeout = setTimeout(async () => {
197
- try {
198
- this.tokenPromise = this.fetchAndScheduleRefresh();
199
- await this.tokenPromise;
200
- } catch (e) {
201
- console.error("[TileryClient] Token refresh failed:", e);
202
- } finally {
203
- this.tokenPromise = null;
204
- }
443
+ const delayMs = Math.max(MIN_REFRESH_DELAY_MS, (refreshAt - now) * MS_PER_SECOND);
444
+ this.setRefreshTimer(delayMs);
445
+ }
446
+ scheduleRetryAfterFailure() {
447
+ const exponent = Math.max(0, this.consecutiveFailures - 1);
448
+ const delayMs = Math.min(RETRY_BASE_DELAY_MS * 2 ** exponent, MAX_RETRY_DELAY_MS);
449
+ this.setRefreshTimer(delayMs);
450
+ }
451
+ setRefreshTimer(delayMs) {
452
+ if (this.destroyed) return;
453
+ if (this.refreshTimeout) clearTimeout(this.refreshTimeout);
454
+ this.refreshTimeout = setTimeout(() => {
455
+ this.refreshTimeout = null;
456
+ this.refreshNow();
205
457
  }, delayMs);
206
458
  }
207
459
  };
208
460
  //#endregion
209
- export { code as SERVICE_WORKER_CODE, TileryClient };
461
+ export { BALANCE_EXHAUSTED_MESSAGE_TYPE, MAX_RETRY_DELAY_MS, MIN_REFRESH_DELAY_MS, RETRY_BASE_DELAY_MS, code as SERVICE_WORKER_CODE, TileryClient };
210
462
 
211
463
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["// oxlint-disable id-length\nimport type {\n EventListener,\n GetTokenFn,\n MapStyle,\n MapStyleOptions,\n TileToken,\n TileryClientEvents,\n TileryClientOptions,\n} from \"./types.js\";\n\nimport serviceWorkerCode from \"virtual:service-worker-code\";\n\nconst MS_PER_SECOND = 1000;\nconst DEFAULT_TILE_SERVER = \"https://api.tilery.eu\";\nconst DEFAULT_REFRESH_BUFFER = 60;\nconst DEFAULT_SW_PATH = \"/tilery-sw.js\";\n\n/**\n * Tilery client for managing tile tokens and service worker caching.\n *\n * @example\n * ```ts\n * const client = new TileryClient({\n * getToken: async () => {\n * const res = await fetch('/api/tile-token');\n * return res.json();\n * },\n * });\n *\n * await client.registerServiceWorker();\n * const style = await client.getMapStyle({ flavor: 'dark' });\n * ```\n */\nexport class TileryClient {\n private readonly getTokenFn: GetTokenFn;\n private readonly tileServer: string;\n private readonly refreshBuffer: number;\n private readonly swPath: string;\n\n private currentToken: TileToken | null = null;\n private refreshTimeout: ReturnType<typeof setTimeout> | null = null;\n private tokenPromise: Promise<TileToken> | null = null;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private listeners = new Map<keyof TileryClientEvents, Set<EventListener<any>>>();\n\n constructor(options: TileryClientOptions) {\n this.getTokenFn = options.getToken;\n this.tileServer = options.tileServer ?? DEFAULT_TILE_SERVER;\n this.refreshBuffer = options.refreshBuffer ?? DEFAULT_REFRESH_BUFFER;\n this.swPath = options.serviceWorkerPath ?? DEFAULT_SW_PATH;\n }\n\n /**\n * Get current valid token, fetching if needed.\n * Token is cached and auto-refreshed before expiry.\n */\n async getToken(): Promise<TileToken> {\n // Return cached token if still valid (with buffer)\n if (this.currentToken && !this.isTokenExpiringSoon(this.currentToken)) {\n return this.currentToken;\n }\n\n // If already fetching, wait for that promise\n if (this.tokenPromise) {\n return this.tokenPromise;\n }\n\n // Fetch new token\n this.tokenPromise = this.fetchAndScheduleRefresh();\n try {\n return await this.tokenPromise;\n } finally {\n this.tokenPromise = null;\n }\n }\n\n /**\n * Get the current token string, or null if not yet fetched.\n * Does not trigger a fetch - use getToken() for that.\n */\n getCurrentTokenString(): string | null {\n return this.currentToken?.token ?? null;\n }\n\n /**\n * Register the service worker for tile caching.\n * Normalizes cache keys by stripping the token param for long-lived caching.\n *\n * Requires a service worker file at the configured path (default: /tilery-sw.js).\n * Create it with: import { SERVICE_WORKER_CODE } from '@tilery/client';\n *\n * @returns Promise that resolves when registration completes\n */\n async registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) {\n console.warn(\"[TileryClient] Service workers not supported\");\n return null;\n }\n\n try {\n const registration = await navigator.serviceWorker.register(this.swPath, {\n scope: \"/\",\n type: \"classic\",\n });\n this.emit(\"sw:registered\", registration);\n console.log(\"[TileryClient] Service worker registered\");\n return registration;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit(\"sw:error\", err);\n throw err;\n }\n }\n\n /**\n * Get the service worker code as a string.\n * Use this to create the service worker file in your build process.\n */\n static getServiceWorkerCode(): string {\n return serviceWorkerCode;\n }\n\n /**\n * Build a tile URL with the current token as query parameter.\n */\n buildTileUrl(options: { token?: string; z: number; x: number; y: number }): string {\n const { token, x, y, z } = options;\n const tok = token ?? this.currentToken?.token;\n if (!tok) {\n throw new Error(\"No token available. Call getToken() first.\");\n }\n return `${this.tileServer}/map/tiles/${z}/${x}/${y}?token=${encodeURIComponent(tok)}`;\n }\n\n /**\n * Get the tile URL template with {z}, {x}, {y} placeholders.\n * Token is appended as query parameter.\n */\n async getTileUrlTemplate(): Promise<string> {\n const token = await this.getToken();\n return `${this.tileServer}/map/tiles/{z}/{x}/{y}?token=${encodeURIComponent(token.token)}`;\n }\n\n /**\n * Get the font (glyph) URL template.\n */\n getGlyphsUrl(): string {\n return `${this.tileServer}/map/fonts/{fontstack}/{range}.pbf`;\n }\n\n /**\n * Get the sprite URL for a given flavor.\n */\n getSpriteUrl(flavor: string): string {\n return `${this.tileServer}/map/sprites/v4/${flavor}`;\n }\n\n /**\n * Fetch a MapLibre-compatible style from the tile server and inject the\n * current token into the tile source URLs.\n *\n * @example\n * ```ts\n * const style = await client.getMapStyle({ flavor: 'dark' });\n * const map = new maplibregl.Map({ container: 'map', style });\n * ```\n */\n async getMapStyle(options: MapStyleOptions = {}): Promise<MapStyle> {\n const { flavor = \"light\" } = options;\n\n const [token, res] = await Promise.all([\n this.getToken(),\n fetch(`${this.tileServer}/map/styles/${encodeURIComponent(flavor)}`),\n ]);\n\n if (!res.ok) {\n throw new Error(`Failed to fetch style \"${flavor}\": ${res.status} ${res.statusText}`);\n }\n\n const style = (await res.json()) as MapStyle;\n const tokenParam = `token=${encodeURIComponent(token.token)}`;\n\n for (const source of Object.values(style.sources)) {\n source.tiles = source.tiles.map((url) =>\n url.includes(\"?\") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`,\n );\n }\n\n return style;\n }\n\n /**\n * Subscribe to an event.\n */\n on<K extends keyof TileryClientEvents>(\n event: K,\n listener: EventListener<TileryClientEvents[K]>,\n ): void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(listener);\n }\n\n /**\n * Unsubscribe from an event.\n */\n off<K extends keyof TileryClientEvents>(\n event: K,\n listener: EventListener<TileryClientEvents[K]>,\n ): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n /**\n * Stop token refresh and clean up.\n */\n destroy(): void {\n if (this.refreshTimeout) {\n clearTimeout(this.refreshTimeout);\n this.refreshTimeout = null;\n }\n this.currentToken = null;\n this.tokenPromise = null;\n this.listeners.clear();\n }\n\n // ---- Private methods ----\n\n private emit<K extends keyof TileryClientEvents>(event: K, data: TileryClientEvents[K]): void {\n this.listeners.get(event)?.forEach((listener) => {\n try {\n listener(data);\n } catch (e) {\n console.error(`[TileryClient] Error in ${event} listener:`, e);\n }\n });\n }\n\n private isTokenExpiringSoon(token: TileToken): boolean {\n const now = Math.floor(Date.now() / MS_PER_SECOND);\n return token.exp <= now + this.refreshBuffer;\n }\n\n private async fetchAndScheduleRefresh(): Promise<TileToken> {\n try {\n const token = await this.getTokenFn();\n this.currentToken = token;\n this.scheduleRefresh(token);\n this.emit(\"token:refresh\", token);\n return token;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit(\"token:error\", err);\n throw err;\n }\n }\n\n private scheduleRefresh(token: TileToken): void {\n if (this.refreshTimeout) {\n clearTimeout(this.refreshTimeout);\n }\n\n const now = Math.floor(Date.now() / MS_PER_SECOND);\n const refreshAt = token.exp - this.refreshBuffer;\n const delayMs = Math.max(0, (refreshAt - now) * MS_PER_SECOND);\n\n this.refreshTimeout = setTimeout(async () => {\n try {\n this.tokenPromise = this.fetchAndScheduleRefresh();\n await this.tokenPromise;\n } catch (e) {\n // Error already emitted via event\n console.error(\"[TileryClient] Token refresh failed:\", e);\n } finally {\n this.tokenPromise = null;\n }\n }, delayMs);\n }\n}\n"],"mappings":";;;;AAaA,IAAM,gBAAgB;AACtB,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;AAC/B,IAAM,kBAAkB;;;;;;;;;;;;;;;;;AAkBxB,IAAa,eAAb,MAA0B;CAaxB,YAAY,SAA8B;sBAPD;wBACsB;sBACb;mCAG9B,IAAI,KAAwD;AAG9E,OAAK,aAAa,QAAQ;AAC1B,OAAK,aAAa,QAAQ,cAAc;AACxC,OAAK,gBAAgB,QAAQ,iBAAiB;AAC9C,OAAK,SAAS,QAAQ,qBAAqB;;;;;;CAO7C,MAAM,WAA+B;AAEnC,MAAI,KAAK,gBAAgB,CAAC,KAAK,oBAAoB,KAAK,aAAa,CACnE,QAAO,KAAK;AAId,MAAI,KAAK,aACP,QAAO,KAAK;AAId,OAAK,eAAe,KAAK,yBAAyB;AAClD,MAAI;AACF,UAAO,MAAM,KAAK;YAC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iB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;AACrE,QAAK,KAAK,eAAe,IAAI;AAC7B,SAAM;;;CAIV,gBAAwB,OAAwB;AAC9C,MAAI,KAAK,eACP,cAAa,KAAK,eAAe;EAGnC,MAAM,MAAM,KAAK,MAAM,KAAK,KAAK,GAAG,cAAc;EAClD,MAAM,YAAY,MAAM,MAAM,KAAK;EACnC,MAAM,UAAU,KAAK,IAAI,IAAI,YAAY,OAAO,cAAc;AAE9D,OAAK,iBAAiB,WAAW,YAAY;AAC3C,OAAI;AACF,SAAK,eAAe,KAAK,yBAAyB;AAClD,UAAM,KAAK;YACJ,GAAG;AAEV,YAAQ,MAAM,wCAAwC,EAAE;aAChD;AACR,SAAK,eAAe;;KAErB,QAAQ"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/validate.ts","../src/client.ts"],"sourcesContent":["/**\n * Minimal runtime shape checks for JSON fetched from the tile server.\n *\n * The SDK is zero-dependency, so these are hand-rolled guards rather than a\n * schema library. They deliberately verify only the parts of each response the\n * SDK dereferences (plus cheap structural markers) — enough to turn a\n * misbehaving server / intermediary into a typed error instead of an\n * `undefined is not a function` crash inside the consumer's app.\n */\nimport type { MapStyle, TileJSON } from \"./types.js\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isStringArray = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\n/**\n * Checks the fields `getMapStyle` touches: `sources` must be a record of\n * source objects, each of whose `tiles` — optional, e.g. absent on a\n * raster-dem terrain source — must be a `string[]` for token injection, and\n * `layers` must be an array.\n */\nexport function isMapStyle(value: unknown): value is MapStyle {\n if (!isRecord(value)) {\n return false;\n }\n if (!Array.isArray(value.layers)) {\n return false;\n }\n if (!isRecord(value.sources)) {\n return false;\n }\n return Object.values(value.sources).every(\n (source) => isRecord(source) && (source.tiles === undefined || isStringArray(source.tiles)),\n );\n}\n\n/**\n * Checks the fields `getTileJSON` touches: `tiles` must be a `string[]` for\n * token injection, and `tilejson` must be the spec-version string.\n */\nexport function isTileJSON(value: unknown): value is TileJSON {\n return isRecord(value) && typeof value.tilejson === \"string\" && isStringArray(value.tiles);\n}\n","// oxlint-disable id-length\nimport type {\n BalanceExhausted,\n EventListener,\n GetTokenFn,\n MapLike,\n MapStyle,\n MapStyleOptions,\n TileJSON,\n AccessToken,\n TileryClientEvents,\n TileryClientOptions,\n TransformedRequest,\n} from \"./types.js\";\n\nimport serviceWorkerCode from \"virtual:service-worker-code\";\nimport { isMapStyle, isTileJSON } from \"./validate.js\";\n\nconst MS_PER_SECOND = 1000;\nconst DEFAULT_TILE_SERVER = \"https://tiles.tilery.eu\";\nconst DEFAULT_REFRESH_BUFFER = 60;\nconst DEFAULT_SW_PATH = \"/tilery-sw.js\";\n\n/**\n * Minimum delay before any scheduled token refresh. Floors the schedule so a\n * pathological `getToken` result (e.g. an already-expired `exp` from clock\n * skew or an HTTP-cached token response) can never produce a 0 ms mint loop.\n */\nexport const MIN_REFRESH_DELAY_MS = 5_000;\n\n/**\n * Base delay for the retry backoff after a failed refresh. Consecutive\n * failures back off at `RETRY_BASE_DELAY_MS · 2ⁿ⁻¹`, capped at\n * {@link MAX_RETRY_DELAY_MS}; a success resets the streak.\n */\nexport const RETRY_BASE_DELAY_MS = 1_000;\n\n/** Upper bound for the retry backoff after failed refreshes. */\nexport const MAX_RETRY_DELAY_MS = 60_000;\n\n/** `exp` values above `now-in-seconds × 100` are almost certainly unix milliseconds. */\nconst MS_EXP_HEURISTIC_FACTOR = 100;\n\n/**\n * The message the service worker posts to every page when a tile request comes\n * back `402` — the account is out of credits and the map has stopped drawing.\n *\n * Exported so a consumer who wires their own `navigator.serviceWorker`\n * listener (or ships the worker without this client) can recognise it. The\n * same string is spelled in `service-worker.ts`, which cannot import: it is\n * transformed rather than bundled, and ships as a classic script.\n */\nexport const BALANCE_EXHAUSTED_MESSAGE_TYPE = \"tilery:balance-exhausted\";\n\n/** HTTP status the tile API answers with once the credits are gone. */\nconst PAYMENT_REQUIRED = 402;\n\n/** What the SDK says when a 402 carries no readable body. Matches the\n * service worker's own fallback; the top-up URL is never invented. */\nconst BALANCE_EXHAUSTED_FALLBACK: BalanceExhausted = {\n error: \"balance_exhausted\",\n message: \"Credit balance is empty, past the overrun allowance.\",\n topUp: \"\",\n};\n\n/** Concrete tile request path: `/map/tiles/{kind}/{z}/{x}/{y}`. */\nconst TILE_PATH_PATTERN = /\\/map\\/tiles\\/[a-z0-9_]+\\/\\d+\\/\\d+\\/\\d+/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** A string field, or the written-out fallback. */\nfunction stringOr(value: unknown, fallback: string): string {\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Narrow whatever arrives — a `postMessage` payload from the service worker,\n * or a parsed 402 body — into the event's shape. `top_up` is the wire\n * spelling; `topUp` is what a worker message already carries.\n */\nfunction toBalanceExhausted(value: unknown): BalanceExhausted {\n if (!isRecord(value)) {\n return BALANCE_EXHAUSTED_FALLBACK;\n }\n return {\n error: stringOr(value.error, BALANCE_EXHAUSTED_FALLBACK.error),\n message: stringOr(value.message, BALANCE_EXHAUSTED_FALLBACK.message),\n topUp: stringOr(value.topUp ?? value.top_up, \"\"),\n };\n}\n\n/**\n * Validate a `getToken` result at the boundary. Consumer mistakes (returning\n * the `Response` itself, `exp` in milliseconds, `{ token }` only) must fail\n * loudly here instead of becoming a \"never expires\" token or a hot mint loop.\n */\nfunction validateTokenResult(value: unknown): AccessToken {\n const expected =\n \"[TileryClient] getToken must resolve to { token: string, exp: number } (exp in unix seconds)\";\n if (!isRecord(value)) {\n throw new TypeError(`${expected}; got ${typeof value}`);\n }\n const { exp, token } = value;\n if (typeof token !== \"string\" || token.length === 0) {\n throw new TypeError(`${expected}; token is missing or not a non-empty string`);\n }\n if (typeof exp !== \"number\" || !Number.isFinite(exp)) {\n throw new TypeError(`${expected}; exp is missing or not a finite number`);\n }\n if (exp > (Date.now() / MS_PER_SECOND) * MS_EXP_HEURISTIC_FACTOR) {\n console.warn(\n \"[TileryClient] getToken returned an exp that looks like unix milliseconds — expected unix seconds\",\n );\n }\n return { exp, token };\n}\n\n/**\n * Tilery client for managing tile tokens and service worker caching.\n *\n * @example\n * ```ts\n * const client = new TileryClient({\n * getToken: async () => {\n * const res = await fetch('/api/tile-token');\n * return res.json();\n * },\n * });\n *\n * await client.registerServiceWorker();\n * const style = await client.getMapStyle({ flavor: 'dark' });\n * ```\n */\nexport class TileryClient {\n private readonly getTokenFn: GetTokenFn;\n private readonly tileServer: string;\n /** `tileServer` without a trailing slash, for `startsWith(base + \"/\")` origin checks. */\n private readonly tileServerBase: string;\n private readonly refreshBuffer: number;\n private readonly swPath: string;\n\n private currentToken: AccessToken | null = null;\n private refreshTimeout: ReturnType<typeof setTimeout> | null = null;\n private tokenPromise: Promise<AccessToken> | null = null;\n private consecutiveFailures = 0;\n private destroyed = false;\n /** \"balance:exhausted\" is once per client — see the event's docs. */\n private balanceExhaustedEmitted = false;\n\n // Mapped store keeps each event's listener set typed to its payload —\n // no `any` variance workaround needed. Sets are created eagerly so no\n // generic-keyed write is ever required.\n private listeners: {\n [K in keyof TileryClientEvents]: Set<EventListener<TileryClientEvents[K]>>;\n } = TileryClient.emptyListeners();\n\n private static emptyListeners(): TileryClient[\"listeners\"] {\n return {\n \"balance:exhausted\": new Set(),\n \"token:refresh\": new Set(),\n \"token:error\": new Set(),\n \"sw:registered\": new Set(),\n \"sw:error\": new Set(),\n };\n }\n\n constructor(options: TileryClientOptions) {\n this.getTokenFn = options.getToken;\n this.tileServer = options.tileServer ?? DEFAULT_TILE_SERVER;\n this.tileServerBase = this.tileServer.endsWith(\"/\")\n ? this.tileServer.slice(0, -1)\n : this.tileServer;\n this.refreshBuffer = options.refreshBuffer ?? DEFAULT_REFRESH_BUFFER;\n this.swPath = options.serviceWorkerPath ?? DEFAULT_SW_PATH;\n this.listenForWorkerMessages();\n }\n\n /**\n * Listen for the service worker's balance report.\n *\n * Wired here rather than in `registerServiceWorker()` because the worker may\n * already be installed from an earlier page load — a consumer who registers\n * once at deploy time still gets the event on every subsequent visit. Absent\n * `navigator.serviceWorker` (Node, an old browser, a non-secure origin) this\n * is simply a no-op.\n */\n private listenForWorkerMessages(): void {\n if (typeof navigator === \"undefined\" || !navigator.serviceWorker) {\n return;\n }\n navigator.serviceWorker.addEventListener(\"message\", this.onWorkerMessage);\n }\n\n /** Bound, so `destroy()` can remove exactly this listener. */\n private readonly onWorkerMessage = (event: Event): void => {\n if (!(\"data\" in event)) {\n return;\n }\n const { data }: { data: unknown } = event;\n if (!isRecord(data) || data.type !== BALANCE_EXHAUSTED_MESSAGE_TYPE) {\n return;\n }\n if (!isRecord(data.payload)) {\n return;\n }\n this.emitBalanceExhausted(toBalanceExhausted(data.payload));\n };\n\n /**\n * Get current valid token, fetching if needed.\n * Token is cached and auto-refreshed before expiry.\n */\n async getToken(): Promise<AccessToken> {\n // Return cached token if still valid (with buffer)\n if (this.currentToken && !this.isTokenExpiringSoon(this.currentToken)) {\n return this.currentToken;\n }\n\n // If already fetching, wait for that promise\n if (this.tokenPromise) {\n return this.tokenPromise;\n }\n\n // Fetch new token\n this.tokenPromise = this.fetchAndScheduleRefresh();\n try {\n return await this.tokenPromise;\n } finally {\n this.tokenPromise = null;\n }\n }\n\n /**\n * Get the current token string, or null if not yet fetched.\n * Does not trigger a fetch - use getToken() for that.\n */\n getCurrentTokenString(): string | null {\n return this.currentToken?.token ?? null;\n }\n\n /**\n * MapLibre-compatible `transformRequest` that rewrites tile-server URLs to\n * carry the **current** access token at request time — the piece that keeps\n * a map alive across token rotation (styles bake the initial token in once).\n *\n * Rewrites a URL only when it points at this client's `tileServer` **and**\n * either already carries a `token` query param or is a tile request;\n * everything else (foreign hosts, glyphs, sprites, styles) passes through\n * unchanged. Before the first token is fetched, URLs pass through unchanged\n * (the initial style already carries a token).\n *\n * Bound and synchronous, so it can be handed to MapLibre directly:\n *\n * @example\n * ```ts\n * const map = new maplibregl.Map({\n * container: 'map',\n * style: await client.getMapStyle(),\n * transformRequest: client.transformRequest,\n * });\n * ```\n */\n readonly transformRequest = (url: string, _resourceType?: string): TransformedRequest => {\n const token = this.currentToken?.token;\n if (!token) {\n return { url };\n }\n if (!url.startsWith(`${this.tileServerBase}/`)) {\n return { url };\n }\n try {\n const parsed = new URL(url);\n if (!parsed.searchParams.has(\"token\") && !TILE_PATH_PATTERN.test(parsed.pathname)) {\n return { url };\n }\n parsed.searchParams.set(\"token\", token);\n return { url: parsed.toString() };\n } catch {\n // Not an absolute URL we can parse — leave it to the map library.\n return { url };\n }\n };\n\n /**\n * Wire this client into a MapLibre map so tiles keep loading across token\n * rotation: installs {@link transformRequest} via `map.setTransformRequest`\n * and kicks {@link getToken} so the auto-refresh loop is running.\n *\n * Returns a `detach()` function that clears the hook\n * (`map.setTransformRequest(null)`).\n *\n * **Caveat:** this *sets* the map's transformRequest. If you already use\n * your own `transformRequest`, don't call this — compose manually with\n * {@link transformRequest} and pass the composed function at map\n * construction instead.\n *\n * @example\n * ```ts\n * const map = new maplibregl.Map({ container: 'map', style });\n * const detach = client.attachToMap(map);\n * ```\n */\n attachToMap(map: MapLike): () => void {\n map.setTransformRequest(this.transformRequest);\n // Start the token loop even if the consumer never calls getToken()\n // directly. Failures emit token:error and retry with backoff.\n this.getToken().catch(() => {\n // Already surfaced via the token:error event.\n });\n return (): void => {\n map.setTransformRequest(null);\n };\n }\n\n /**\n * Register the service worker for tile caching.\n * Normalizes cache keys by stripping the token param for long-lived caching.\n *\n * Requires a service worker file at the configured path (default: /tilery-sw.js).\n * Create it with: import { SERVICE_WORKER_CODE } from '@tilery/client';\n *\n * @returns Promise that resolves when registration completes\n */\n async registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) {\n console.warn(\"[TileryClient] Service workers not supported\");\n return null;\n }\n\n try {\n const registration = await navigator.serviceWorker.register(this.swPath, {\n scope: \"/\",\n type: \"classic\",\n });\n this.emit(\"sw:registered\", registration);\n console.log(\"[TileryClient] Service worker registered\");\n return registration;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit(\"sw:error\", err);\n throw err;\n }\n }\n\n /**\n * Get the service worker code as a string.\n * Use this to create the service worker file in your build process.\n */\n static getServiceWorkerCode(): string {\n return serviceWorkerCode;\n }\n\n /**\n * Build a tile URL with the current token as query parameter.\n */\n buildTileUrl(options: { token?: string; z: number; x: number; y: number }): string {\n const { token, x, y, z } = options;\n const tok = token ?? this.currentToken?.token;\n if (!tok) {\n throw new Error(\"No token available. Call getToken() first.\");\n }\n return `${this.tileServer}/map/tiles/vector/${z}/${x}/${y}?token=${encodeURIComponent(tok)}`;\n }\n\n /**\n * Get the tile URL template with {z}, {x}, {y} placeholders.\n * Token is appended as query parameter.\n */\n async getTileUrlTemplate(): Promise<string> {\n const token = await this.getToken();\n return `${this.tileServer}/map/tiles/vector/{z}/{x}/{y}?token=${encodeURIComponent(token.token)}`;\n }\n\n /**\n * Get the font (glyph) URL template.\n */\n getGlyphsUrl(): string {\n return `${this.tileServer}/map/fonts/{fontstack}/{range}.pbf`;\n }\n\n /**\n * Get the sprite URL for a given flavor.\n */\n getSpriteUrl(flavor: string): string {\n return `${this.tileServer}/map/sprites/v4/${flavor}`;\n }\n\n /**\n * Fetch a MapLibre-compatible style from the tile server and inject the\n * current token into the tile source URLs.\n *\n * @example\n * ```ts\n * const style = await client.getMapStyle({ flavor: 'dark' });\n * const map = new maplibregl.Map({ container: 'map', style });\n * ```\n */\n async getMapStyle(options: MapStyleOptions = {}): Promise<MapStyle> {\n const { flavor = \"light\" } = options;\n\n const [token, res] = await Promise.all([\n this.getToken(),\n fetch(`${this.tileServer}/map/styles/${encodeURIComponent(flavor)}`),\n ]);\n\n if (!res.ok) {\n await this.noteResponse(res);\n throw new Error(`Failed to fetch style \"${flavor}\": ${res.status} ${res.statusText}`);\n }\n\n const body: unknown = await res.json();\n if (!isMapStyle(body)) {\n throw new Error(`Tile server returned an unexpected style response for \"${flavor}\"`);\n }\n const style = body;\n const tokenParam = `token=${encodeURIComponent(token.token)}`;\n\n for (const source of Object.values(style.sources)) {\n // Only tileServer-hosted tile arrays get the token: a foreign or\n // non-tile source (raster-dem terrain, external overlay) must never\n // receive a live access token, and `tiles` may be absent on such\n // sources.\n if (!Array.isArray(source.tiles)) {\n continue;\n }\n source.tiles = source.tiles.map((url) => {\n if (!url.startsWith(`${this.tileServerBase}/`)) {\n return url;\n }\n return url.includes(\"?\") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`;\n });\n }\n\n return style;\n }\n\n /**\n * Fetch the vector tileset's TileJSON descriptor and inject the current\n * access token into the `tiles` URL template(s). The result can be used\n * directly as a MapLibre/Leaflet/OpenLayers source.\n *\n * @example\n * ```ts\n * const tilejson = await client.getTileJSON();\n * map.addSource('tilery', { type: 'vector', ...tilejson });\n * ```\n */\n async getTileJSON(): Promise<TileJSON> {\n const [token, res] = await Promise.all([\n this.getToken(),\n fetch(`${this.tileServer}/map/tiles/vector.json`),\n ]);\n\n if (!res.ok) {\n await this.noteResponse(res);\n throw new Error(`Failed to fetch TileJSON: ${res.status} ${res.statusText}`);\n }\n\n const body: unknown = await res.json();\n if (!isTileJSON(body)) {\n throw new Error(\"Tile server returned an unexpected TileJSON response\");\n }\n const tilejson = body;\n const tokenParam = `token=${encodeURIComponent(token.token)}`;\n\n tilejson.tiles = tilejson.tiles.map((url) =>\n url.includes(\"?\") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`,\n );\n\n return tilejson;\n }\n\n /**\n * Subscribe to an event.\n */\n on<K extends keyof TileryClientEvents>(\n event: K,\n listener: EventListener<TileryClientEvents[K]>,\n ): void {\n this.listeners[event].add(listener);\n }\n\n /**\n * Unsubscribe from an event.\n */\n off<K extends keyof TileryClientEvents>(\n event: K,\n listener: EventListener<TileryClientEvents[K]>,\n ): void {\n this.listeners[event].delete(listener);\n }\n\n /**\n * Stop token refresh and clean up. Cancels the refresh timer and any\n * pending failure-backoff retry; an in-flight fetch may still settle but\n * will not schedule anything afterwards.\n */\n destroy(): void {\n this.destroyed = true;\n if (typeof navigator !== \"undefined\" && navigator.serviceWorker) {\n navigator.serviceWorker.removeEventListener(\"message\", this.onWorkerMessage);\n }\n if (this.refreshTimeout) {\n clearTimeout(this.refreshTimeout);\n this.refreshTimeout = null;\n }\n this.currentToken = null;\n this.tokenPromise = null;\n this.listeners = TileryClient.emptyListeners();\n }\n\n // ---- Private methods ----\n\n /**\n * Emit \"balance:exhausted\", at most once for this client. Both detectors —\n * the service worker's message and the SDK's own fetches — land here, so a\n * page running both reports the stop once.\n */\n private emitBalanceExhausted(payload: BalanceExhausted): void {\n if (this.balanceExhaustedEmitted) {\n return;\n }\n this.balanceExhaustedEmitted = true;\n this.emit(\"balance:exhausted\", payload);\n }\n\n /**\n * The direct-fetch detector: the SDK's own requests to the tile server.\n *\n * Tiles themselves are fetched by the map library, not by this SDK, so this\n * covers only what the SDK asks for — with the service worker installed, the\n * worker is what sees a failing tile. Never throws: the caller is already on\n * its way to reporting the failure its own way.\n */\n private async noteResponse(response: Response): Promise<void> {\n if (response.status !== PAYMENT_REQUIRED) {\n return;\n }\n const body: unknown = await response.json().catch(() => null);\n this.emitBalanceExhausted(toBalanceExhausted(body));\n }\n\n private emit<K extends keyof TileryClientEvents>(event: K, data: TileryClientEvents[K]): void {\n this.listeners[event].forEach((listener) => {\n try {\n listener(data);\n } catch (e) {\n console.error(`[TileryClient] Error in ${event} listener:`, e);\n }\n });\n }\n\n private isTokenExpiringSoon(token: AccessToken): boolean {\n const now = Math.floor(Date.now() / MS_PER_SECOND);\n return token.exp <= now + this.refreshBuffer;\n }\n\n private async fetchAndScheduleRefresh(): Promise<AccessToken> {\n try {\n const result: unknown = await this.getTokenFn();\n const token = validateTokenResult(result);\n this.currentToken = token;\n this.consecutiveFailures = 0;\n this.scheduleRefresh(token);\n this.emit(\"token:refresh\", token);\n return token;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.consecutiveFailures += 1;\n this.emit(\"token:error\", err);\n // A failure (network, or an invalid getToken result) must not kill the\n // loop: retry with capped exponential backoff.\n this.scheduleRetryAfterFailure();\n throw err;\n }\n }\n\n /**\n * Timer-path refresh. Honors the same single-flight invariant as\n * `getToken()`: if a mint is already in flight, that mint will schedule the\n * next refresh (or the retry backoff) itself, so this becomes a no-op.\n */\n private refreshNow(): void {\n if (this.tokenPromise) {\n return;\n }\n const promise = this.fetchAndScheduleRefresh();\n this.tokenPromise = promise;\n promise\n .catch((error: unknown) => {\n // token:error already emitted and a backoff retry scheduled.\n console.error(\"[TileryClient] Token refresh failed:\", error);\n })\n .finally(() => {\n if (this.tokenPromise === promise) {\n this.tokenPromise = null;\n }\n });\n }\n\n private scheduleRefresh(token: AccessToken): void {\n const now = Math.floor(Date.now() / MS_PER_SECOND);\n const refreshAt = token.exp - this.refreshBuffer;\n // The floor keeps a past-`exp` token (clock skew, HTTP-cached token\n // response) from ever scheduling a 0 ms mint loop.\n const delayMs = Math.max(MIN_REFRESH_DELAY_MS, (refreshAt - now) * MS_PER_SECOND);\n this.setRefreshTimer(delayMs);\n }\n\n private scheduleRetryAfterFailure(): void {\n const exponent = Math.max(0, this.consecutiveFailures - 1);\n const delayMs = Math.min(RETRY_BASE_DELAY_MS * 2 ** exponent, MAX_RETRY_DELAY_MS);\n this.setRefreshTimer(delayMs);\n }\n\n private setRefreshTimer(delayMs: number): void {\n if (this.destroyed) {\n return;\n }\n if (this.refreshTimeout) {\n clearTimeout(this.refreshTimeout);\n }\n this.refreshTimeout = setTimeout(() => {\n this.refreshTimeout = null;\n this.refreshNow();\n }, delayMs);\n }\n}\n"],"mappings":";;;;AAWA,IAAM,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,IAAM,iBAAiB,UACrB,MAAM,QAAQ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;;CAOA,aAA2B;EACzB,IAAI,KAAK,cACP;EAEF,MAAM,UAAU,KAAK,wBAAwB;EAC7C,KAAK,eAAe;EACpB,QACG,OAAO,UAAmB;GAEzB,QAAQ,MAAM,wCAAwC,KAAK;EAC7D,CAAC,CAAC,CACD,cAAc;GACb,IAAI,KAAK,iBAAiB,SACxB,KAAK,eAAe;EAExB,CAAC;CACL;CAEA,gBAAwB,OAA0B;EAChD,MAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,aAAa;EACjD,MAAM,YAAY,MAAM,MAAM,KAAK;EAGnC,MAAM,UAAU,KAAK,IAAI,uBAAuB,YAAY,OAAO,aAAa;EAChF,KAAK,gBAAgB,OAAO;CAC9B;CAEA,4BAA0C;EACxC,MAAM,WAAW,KAAK,IAAI,GAAG,KAAK,sBAAsB,CAAC;EACzD,MAAM,UAAU,KAAK,IAAI,sBAAsB,KAAK,UAAU,kBAAkB;EAChF,KAAK,gBAAgB,OAAO;CAC9B;CAEA,gBAAwB,SAAuB;EAC7C,IAAI,KAAK,WACP;EAEF,IAAI,KAAK,gBACP,aAAa,KAAK,cAAc;EAElC,KAAK,iBAAiB,iBAAiB;GACrC,KAAK,iBAAiB;GACtB,KAAK,WAAW;EAClB,GAAG,OAAO;CACZ;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"service-worker.d.ts","sourceRoot":"","sources":["../src/service-worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAmIH,OAAO,EAAE,CAAC"}
1
+ {"version":3,"file":"service-worker.d.ts","sourceRoot":"","sources":["../src/service-worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgWH,OAAO,EAAE,CAAC"}
package/dist/tilery-sw.js CHANGED
@@ -1 +1 @@
1
- const r=globalThis,c="tilery-tiles-v1",l=/\/tiles\/\d+\/\d+\/\d+/;function o(e){const t=new URL(e);return t.searchParams.delete("token"),t.toString()}function h(e){return l.test(e)}r.addEventListener("install",e=>{e.waitUntil(r.skipWaiting())}),r.addEventListener("activate",e=>{e.waitUntil(Promise.all([r.clients.claim(),caches.keys().then(t=>Promise.all(t.filter(s=>s.startsWith("tilery-")&&s!==c).map(s=>caches.delete(s))))]))}),r.addEventListener("fetch",e=>{const{request:t}=e;h(t.url)&&e.respondWith(d(t))});async function d(e){const t=await caches.open(c),s=o(e.url),n=await t.match(s);if(n)return n;try{const a=await fetch(e);if(a.ok){const i=a.clone();t.put(s,i)}return a}catch(a){const i=await t.match(s);if(i)return i;throw a}}r.addEventListener("message",e=>{const{type:t,payload:s}=e.data||{};switch(t){case"CLEAR_CACHE":e.waitUntil(caches.delete(c).then(()=>{e.ports[0]?.postMessage({success:!0})}));break;case"GET_CACHE_SIZE":e.waitUntil(caches.open(c).then(async n=>{const a=await n.keys();e.ports[0]?.postMessage({size:a.length})}));break;case"DELETE_TILE":if(s?.url){const n=o(s.url);e.waitUntil(caches.open(c).then(async a=>{const i=await a.delete(n);e.ports[0]?.postMessage({deleted:i})}))}break}});export{};
1
+ (()=>{const r=globalThis,i="tilery-tiles-v1",m=/\/map\/tiles\/[a-z0-9_]+\/\d+\/\d+\/\d+/,E=["application/x-protobuf","application/vnd.mapbox-vector-tile","application/octet-stream","image/"],p=2e3,w="tilery:balance-exhausted",c={error:"balance_exhausted",message:"Credit balance is empty, past the overrun allowance.",topUp:""};let l=!1;function d(e){const s=new URL(e);return s.searchParams.delete("token"),s.toString()}function y(e){return m.test(e)}r.addEventListener("install",e=>{e.waitUntil(r.skipWaiting())});r.addEventListener("activate",e=>{e.waitUntil(Promise.all([r.clients.claim(),caches.keys().then(s=>Promise.all(s.filter(t=>t.startsWith("tilery-")&&t!==i).map(t=>caches.delete(t))))]))});r.addEventListener("fetch",e=>{const{request:s}=e;y(s.url)&&e.respondWith(C(e))});const _=10080*60,A=1e3;function T(e){const s=e.headers.get("date"),t=s===null?Number.NaN:Date.parse(s);if(Number.isNaN(t))return!1;const a=e.headers.get("cache-control")?.match(/max-age=(\d+)/),n=a?Number(a[1]):_;return Date.now()-t<=n*A}function h(e){if(!e.ok)return!1;const s=e.headers.get("content-type")??"";return E.some(t=>s.startsWith(t))}async function b(e){try{const s=await e.json();if(typeof s=="object"&&s!==null){const t={...s};return{error:typeof t.error=="string"?t.error:c.error,message:typeof t.message=="string"?t.message:c.message,topUp:typeof t.top_up=="string"?t.top_up:""}}}catch{}return c}async function R(e){if(l)return;l=!0;const s=await b(e),t=await r.clients.matchAll({includeUncontrolled:!0,type:"window"});for(const a of t)a.postMessage({payload:s,type:w})}function f(e){return e.status===402?R(e.clone()):(e.ok&&(l=!1),Promise.resolve())}async function g(e,s,t){try{await e.put(s,t);const a=await e.keys();a.length>p&&await Promise.all(a.slice(0,a.length-p).map(n=>e.delete(n)))}catch{}}async function U(e,s,t){try{const a=await fetch(s);await f(a),h(a)&&await g(e,t,a)}catch{}}async function C(e){const{request:s}=e,t=await caches.open(i),a=d(s.url),n=await t.match(a);if(n)return T(n)||e.waitUntil(U(t,s,a)),n;try{const o=await fetch(s);return e.waitUntil(f(o)),h(o)&&e.waitUntil(g(t,a,o.clone())),o}catch(o){const u=await t.match(a);if(u)return u;throw o}}async function P(){try{if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const{usage:e}=await navigator.storage.estimate();return e??null}catch{return null}}r.addEventListener("message",e=>{const{type:s,payload:t}=e.data||{};switch(s){case"CLEAR_CACHE":e.waitUntil(caches.delete(i).then(()=>{e.ports[0]?.postMessage({success:!0})}));break;case"GET_CACHE_SIZE":e.waitUntil(caches.open(i).then(async a=>{const n=await a.keys(),o=await P();e.ports[0]?.postMessage({entries:n.length,size:n.length,usageBytes:o})}));break;case"DELETE_TILE":t?.url&&e.waitUntil((async()=>{try{const a=d(t.url),o=await(await caches.open(i)).delete(a);e.ports[0]?.postMessage({deleted:o})}catch{e.ports[0]?.postMessage({deleted:!1})}})());break}});})();
package/dist/types.d.ts CHANGED
@@ -1,24 +1,24 @@
1
1
  /**
2
2
  * Token response from the user's token endpoint.
3
3
  */
4
- export interface TileToken {
5
- /** JWT token string */
4
+ export interface AccessToken {
5
+ /** Access token string */
6
6
  token: string;
7
7
  /** Expiry timestamp (unix seconds) */
8
8
  exp: number;
9
9
  }
10
10
  /**
11
- * Async function that fetches a new tile token.
11
+ * Async function that fetches a new access token.
12
12
  * User provides this to keep API key server-side.
13
13
  */
14
- export type GetTokenFn = () => Promise<TileToken>;
14
+ export type GetTokenFn = () => Promise<AccessToken>;
15
15
  /**
16
16
  * Configuration options for TileryClient.
17
17
  */
18
18
  export interface TileryClientOptions {
19
19
  /**
20
- * Async function that returns a tile token.
21
- * Called on init and when token needs refresh.
20
+ * Async function that returns an access token.
21
+ * Called on init and when the token needs refresh.
22
22
  *
23
23
  * @example
24
24
  * ```ts
@@ -31,9 +31,9 @@ export interface TileryClientOptions {
31
31
  */
32
32
  getToken: GetTokenFn;
33
33
  /**
34
- * Tile server URL. Set to `https://api.test.tilery.eu` to point at the
34
+ * Tile server URL. Set to `https://tiles.test.tilery.eu` to point at the
35
35
  * staging environment.
36
- * @default 'https://api.tilery.eu'
36
+ * @default 'https://tiles.tilery.eu'
37
37
  */
38
38
  tileServer?: string;
39
39
  /**
@@ -45,6 +45,11 @@ export interface TileryClientOptions {
45
45
  * Path to the service worker script.
46
46
  * Required for Firefox (doesn't support blob: URLs for service workers).
47
47
  * Create a file with: import { SERVICE_WORKER_CODE } from '@tilery/client';
48
+ *
49
+ * Registration always uses scope '/' so the worker controls every page on
50
+ * the origin. If this file is served from a subdirectory (e.g.
51
+ * '/assets/tilery-sw.js'), the server must send a
52
+ * `Service-Worker-Allowed: /` header on it, or registration fails.
48
53
  * @default '/tilery-sw.js'
49
54
  */
50
55
  serviceWorkerPath?: string;
@@ -76,18 +81,99 @@ export interface MapStyle {
76
81
  }>;
77
82
  layers: unknown[];
78
83
  }
84
+ /**
85
+ * TileJSON 3.0 descriptor (https://github.com/mapbox/tilejson-spec) for the
86
+ * vector tileset, served at `GET {tileServer}/map/tiles/vector.json`.
87
+ * `getTileJSON()` injects the access token into `tiles` before returning it.
88
+ */
89
+ export interface TileJSON {
90
+ /** TileJSON spec version (e.g. "3.0.0"). */
91
+ tilejson: string;
92
+ name: string;
93
+ /** Tiling scheme — "xyz". */
94
+ scheme: string;
95
+ /** Tile URL template(s) with `{z}/{x}/{y}` placeholders. */
96
+ tiles: string[];
97
+ minzoom: number;
98
+ maxzoom: number;
99
+ /** `[west, south, east, north]` in WGS84 degrees. */
100
+ bounds: [number, number, number, number];
101
+ attribution: string;
102
+ }
103
+ /**
104
+ * Return shape of {@link TransformRequestFn}: the (possibly rewritten) URL.
105
+ * Structurally compatible with MapLibre's `RequestParameters`.
106
+ */
107
+ export interface TransformedRequest {
108
+ url: string;
109
+ }
110
+ /**
111
+ * A MapLibre-compatible `transformRequest` callback. `resourceType` is
112
+ * MapLibre's `ResourceType` string ("Tile", "Glyphs", …) but is typed as
113
+ * plain `string` so this package needs no maplibre import.
114
+ */
115
+ export type TransformRequestFn = (url: string, resourceType?: string) => TransformedRequest;
116
+ /**
117
+ * Structural subset of `maplibregl.Map` used by `client.attachToMap()`.
118
+ *
119
+ * Kept structural so `@tilery/client` has zero runtime (and zero type)
120
+ * dependencies. Shape checked against maplibre-gl 6.5.0, where
121
+ * `setTransformRequest(transformRequest: RequestTransformFunction | null): this`
122
+ * and passing `null` clears the map's transform. Method syntax (not a
123
+ * property arrow) is deliberate: TS checks method parameters bivariantly,
124
+ * which is what lets `maplibregl.Map` satisfy this interface.
125
+ */
126
+ export interface MapLike {
127
+ setTransformRequest(transformRequest: TransformRequestFn | null): unknown;
128
+ }
129
+ /**
130
+ * What the tile API says when the account has run out of credits: the body of
131
+ * its `402 Payment Required`, in this SDK's spelling (`top_up` on the wire).
132
+ *
133
+ * Serving continues a little past a zero balance — the **overrun allowance**,
134
+ * published in credits at `GET {tileServer-web}/api/pricing` as
135
+ * `overrun_allowance_millicredits` — and stops at the end of it. That is the state
136
+ * this describes: not "you spent your last credit", but "you are past the
137
+ * allowance and tiles have stopped".
138
+ */
139
+ export interface BalanceExhausted {
140
+ /** Stable machine-readable code; `"balance_exhausted"` today. Branch on
141
+ * this rather than on {@link message}. */
142
+ error: string;
143
+ /** One sentence, safe to show a user. */
144
+ message: string;
145
+ /**
146
+ * Where the account tops up. **Empty** when the 402 arrived without a
147
+ * readable body (an intermediary stripped it) — the SDK never invents a
148
+ * URL, because guessing the wrong environment's dashboard is worse than
149
+ * saying nothing.
150
+ */
151
+ topUp: string;
152
+ }
79
153
  /**
80
154
  * Events emitted by TileryClient.
81
155
  */
82
156
  export interface TileryClientEvents {
83
157
  /** Emitted when token is successfully refreshed */
84
- "token:refresh": TileToken;
158
+ "token:refresh": AccessToken;
85
159
  /** Emitted when token refresh fails */
86
160
  "token:error": Error;
87
161
  /** Emitted when service worker is registered */
88
162
  "sw:registered": ServiceWorkerRegistration;
89
163
  /** Emitted when service worker registration fails */
90
164
  "sw:error": Error;
165
+ /**
166
+ * Emitted the first time a tile request comes back `402` — the account's
167
+ * credits are gone and the map has stopped drawing. **Once per client**,
168
+ * however many tiles fail: a blank map is hundreds of requests, and an
169
+ * event per tile is noise rather than a signal.
170
+ *
171
+ * Seen from either side: the service worker (which watches every tile
172
+ * response) or the SDK's own fetches. A map wired up without the service
173
+ * worker fetches tiles through MapLibre, which the SDK never sees — the
174
+ * README's "When credits run out" shows how to catch that case.
175
+ */
176
+ "balance:exhausted": BalanceExhausted;
91
177
  }
92
178
  /**
93
179
  * Event listener function type.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,uBAAuB;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,sCAAsC;IACtC,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;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AAG,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,KAAK,kBAAkB,CAAC;AAE5F;;;;;;;;;GASG;AACH,MAAM,WAAW,OAAO;IACtB,mBAAmB,CAAC,gBAAgB,EAAE,kBAAkB,GAAG,IAAI,GAAG,OAAO,CAAC;CAC3E;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,gBAAgB;IAC/B;+CAC2C;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,yCAAyC;IACzC,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;OAKG;IACH,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,mDAAmD;IACnD,eAAe,EAAE,WAAW,CAAC;IAC7B,uCAAuC;IACvC,aAAa,EAAE,KAAK,CAAC;IACrB,gDAAgD;IAChD,eAAe,EAAE,yBAAyB,CAAC;IAC3C,qDAAqD;IACrD,UAAU,EAAE,KAAK,CAAC;IAClB;;;;;;;;;;OAUG;IACH,mBAAmB,EAAE,gBAAgB,CAAC;CACvC;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,CAAC"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Minimal runtime shape checks for JSON fetched from the tile server.
3
+ *
4
+ * The SDK is zero-dependency, so these are hand-rolled guards rather than a
5
+ * schema library. They deliberately verify only the parts of each response the
6
+ * SDK dereferences (plus cheap structural markers) — enough to turn a
7
+ * misbehaving server / intermediary into a typed error instead of an
8
+ * `undefined is not a function` crash inside the consumer's app.
9
+ */
10
+ import type { MapStyle, TileJSON } from "./types.js";
11
+ /**
12
+ * Checks the fields `getMapStyle` touches: `sources` must be a record of
13
+ * source objects, each of whose `tiles` — optional, e.g. absent on a
14
+ * raster-dem terrain source — must be a `string[]` for token injection, and
15
+ * `layers` must be an array.
16
+ */
17
+ export declare function isMapStyle(value: unknown): value is MapStyle;
18
+ /**
19
+ * Checks the fields `getTileJSON` touches: `tiles` must be a `string[]` for
20
+ * token injection, and `tilejson` must be the spec-version string.
21
+ */
22
+ export declare function isTileJSON(value: unknown): value is TileJSON;
23
+ //# sourceMappingURL=validate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../src/validate.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAQrD;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAa5D;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tilery/client",
3
- "version": "0.1.0",
3
+ "version": "0.1.4",
4
4
  "description": "Client library for Tilery.eu tile API with service worker caching",
5
5
  "keywords": [
6
6
  "maplibre",
@@ -10,14 +10,11 @@
10
10
  "tiles",
11
11
  "vector-tiles"
12
12
  ],
13
- "license": "MIT",
14
- "author": "Snorre Magnus Davøen",
15
13
  "bugs": {
16
14
  "email": "support@tilery.eu"
17
15
  },
18
- "publishConfig": {
19
- "access": "public"
20
- },
16
+ "license": "MIT",
17
+ "author": "Snorre Magnus Davøen",
21
18
  "files": [
22
19
  "dist",
23
20
  "README.md"
@@ -32,11 +29,16 @@
32
29
  "import": "./dist/index.js"
33
30
  }
34
31
  },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
35
  "scripts": {
36
36
  "build": "vite build && tsc --emitDeclarationOnly",
37
+ "typecheck": "tsc --noEmit",
37
38
  "dev": "vite build --watch",
38
39
  "prepublishOnly": "npm run build",
39
40
  "test": "vitest run",
40
- "test:watch": "vitest"
41
+ "test:watch": "vitest",
42
+ "coverage": "vitest run --coverage"
41
43
  }
42
44
  }