@tilery/client 0.1.0 → 0.1.5

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,41 @@ 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 back to 2000 tiles, so heavy panning can't grow
162
+ storage until the browser evicts the whole origin. It trims once every 100
163
+ stored tiles (and on the first store after the browser restarts the
164
+ worker), so the cache can briefly hold up to 2099 tiles.
165
+
166
+ This means tiles stay cached even when your token rotates, and tileset updates
167
+ still reach repeat visitors without anyone redeploying the service worker.
168
+
169
+ > **The copied worker doesn't update itself.** `tilery-sw.js` is a copy of
170
+ > `SERVICE_WORKER_CODE` at the version you installed, so a fix to the worker
171
+ > reaches your visitors only when you copy it again after upgrading
172
+ > `@tilery/client` (Option 2 does this on every build). In particular, workers
173
+ > copied before the trim moved to once per 100 stored tiles list the whole
174
+ > cache after every stored tile, which queues new tile requests behind those
175
+ > scans: about 1 s per tile on a full cache in Firefox, growing to several
176
+ > seconds per viewport over a long pan. Re-copy `tilery-sw.js` to get the fix.
91
177
 
92
178
  ## API Reference
93
179
 
@@ -100,8 +186,9 @@ interface TileryClientOptions {
100
186
  // Required: async function that returns { token, exp }
101
187
  getToken: () => Promise<{ token: string; exp: number }>;
102
188
 
103
- // Optional: tile server URL (default: 'https://api.tilery.eu').
104
- // Use 'https://api.test.tilery.eu' to point at the staging environment.
189
+ // Optional: tile server URL (default: 'https://tiles.tilery.eu').
190
+ // Use 'https://tiles.test.tilery.eu' to point at the staging environment.
191
+ // Must be an absolute http(s) URL; a relative path like '/tiles' throws.
105
192
  tileServer?: string;
106
193
 
107
194
  // Optional: seconds before expiry to refresh (default: 60)
@@ -126,12 +213,18 @@ const style = await client.getMapStyle({
126
213
  flavor: "light", // see GET {tileServer}/map/styles for the full list
127
214
  });
128
215
 
216
+ // Keep the map's tile requests on the current token across rotations
217
+ const detach = client.attachToMap(map);
218
+
219
+ // Or compose yourself: MapLibre-compatible transformRequest (bound, sync)
220
+ client.transformRequest(url, resourceType);
221
+
129
222
  // Get URL templates
130
223
  const tileUrl = await client.getTileUrlTemplate();
131
224
  const glyphsUrl = client.getGlyphsUrl();
132
225
  const spriteUrl = client.getSpriteUrl("dark");
133
226
 
134
- // Clean up
227
+ // Clean up (stops the refresh loop and cancels retries)
135
228
  client.destroy();
136
229
  ```
137
230
 
@@ -153,11 +246,95 @@ client.on("sw:registered", (registration) => {
153
246
  client.on("sw:error", (error) => {
154
247
  console.error("Service worker failed:", error);
155
248
  });
249
+
250
+ client.on("balance:exhausted", ({ message, topUp }) => {
251
+ // The account is out of credits and tiles have stopped. Fires once.
252
+ showBanner(message, topUp);
253
+ });
254
+ ```
255
+
256
+ ## When credits run out
257
+
258
+ Tilery is prepaid. Usage beyond what the account's plan includes counts against its credit
259
+ balance within about 1 hour 25 minutes; once the balance can't cover it, serving stops — there is
260
+ no grace period after that (usage served before the stop is collected from the next top-up).
261
+ From then on every tile request answers:
262
+
263
+ ```http
264
+ HTTP/1.1 402 Payment Required
265
+ content-type: application/json
266
+ tilery-balance: exhausted
267
+ cache-control: no-store, private
268
+
269
+ {
270
+ "error": "balance_exhausted",
271
+ "message": "Credit balance is exhausted. Top up to resume serving.",
272
+ "top_up": "https://tilery.eu/app/billing"
273
+ }
274
+ ```
275
+
276
+ Branch on `error` (or on the `tilery-balance` header, which is exposed cross-origin), never
277
+ on the sentence. The 402 is never cached — a stored one would outlive the top-up that fixes
278
+ it.
279
+
280
+ **With the service worker registered**, the SDK sees every tile response and surfaces this
281
+ for you:
282
+
283
+ ```typescript
284
+ const client = new TileryClient({ getToken });
285
+ await client.registerServiceWorker();
286
+
287
+ client.on("balance:exhausted", ({ error, message, topUp }) => {
288
+ // error → "balance_exhausted"
289
+ // message → a sentence you can show a user
290
+ // topUp → where to top up, or "" if the response arrived without a body
291
+ banner.textContent = message;
292
+ banner.querySelector("a").href = topUp || "https://tilery.eu/app/billing";
293
+ });
156
294
  ```
157
295
 
296
+ The event fires **once per client**, however many tiles fail — a blank map is hundreds of
297
+ requests. A tile that serves again resets it, so an account that tops up and later runs dry
298
+ is reported again.
299
+
300
+ **Without the service worker**, tiles are fetched by your map library and this SDK never
301
+ sees the responses. MapLibre surfaces them on its own `error` event:
302
+
303
+ ```typescript
304
+ map.on("error", (event) => {
305
+ if (event.error?.status === 402) {
306
+ showTopUpBanner();
307
+ }
308
+ });
309
+ ```
310
+
311
+ ### Reading the price list
312
+
313
+ `GET https://tilery.eu/api/pricing` is public, cached for five minutes, and says what an
314
+ operation costs:
315
+
316
+ ```json
317
+ {
318
+ "unit": "millicredits",
319
+ "millicredits_per_euro": 250000,
320
+ "operations": {
321
+ "tiles_vector": { "millicredits": 10, "label": "Vector tiles", "order": 10 }
322
+ },
323
+ "overrun_allowance_millicredits": 125000
324
+ }
325
+ ```
326
+
327
+ Millicredits are the wire unit (the app shows credits, 1 000 millicredits each); euros are derived (`millicredits ÷ millicredits_per_euro`), and `operations`
328
+ grows as Tilery prices more of them — read it, rather than hardcoding a rate.
329
+
330
+ `millicredits_per_euro` is Tilery's **display conversion** — what a balance or a spend is roughly
331
+ worth. It is not what a credit pack charges: pack prices are quoted per 1 000 operations from
332
+ the smallest active pack and shown on the pricing page. Divide by this figure to render a euro
333
+ hint, never to predict what a top-up will cost.
334
+
158
335
  ## Backend Token Endpoint
159
336
 
160
- Your backend should exchange an API key for a short-lived JWT. Example with the Tilery API:
337
+ Your backend should exchange an API key for a short-lived access token. Example with the Tilery API:
161
338
 
162
339
  ```typescript
163
340
  // /api/tile-token.ts (your backend)
@@ -184,7 +361,7 @@ const client = new TileryClient({
184
361
 
185
362
  // Get token and build URLs manually
186
363
  const token = await client.getToken();
187
- const tileUrl = `https://api.tilery.eu/tiles/{z}/{x}/{y}?token=${token.token}`;
364
+ const tileUrl = `https://tiles.tilery.eu/map/tiles/vector/{z}/{x}/{y}?token=${token.token}`;
188
365
 
189
366
  // Use with any mapping library
190
367
  const map = new maplibregl.Map({
@@ -213,9 +390,12 @@ You can communicate with the service worker for cache management:
213
390
  // Clear all cached tiles
214
391
  navigator.serviceWorker.controller?.postMessage({ type: "CLEAR_CACHE" });
215
392
 
216
- // Get cache size
393
+ // Get cache size — `entries` counts cached tiles; `usageBytes` is the
394
+ // origin-wide storage estimate (null where the StorageManager API is
395
+ // unavailable). `size` is a legacy alias for `entries`.
217
396
  const channel = new MessageChannel();
218
- channel.port1.onmessage = (e) => console.log("Cache size:", e.data.size);
397
+ channel.port1.onmessage = (e) =>
398
+ console.log(`Cached tiles: ${e.data.entries}, origin storage: ${e.data.usageBytes} bytes`);
219
399
  navigator.serviceWorker.controller?.postMessage({ type: "GET_CACHE_SIZE" }, [channel.port2]);
220
400
  ```
221
401
 
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
  *
@@ -17,24 +41,88 @@ import type { EventListener, MapStyle, MapStyleOptions, TileToken, TileryClientE
17
41
  */
18
42
  export declare class TileryClient {
19
43
  private readonly getTokenFn;
44
+ /**
45
+ * The `tileServer` option without a trailing slash, so every URL is built as
46
+ * `${tileServer}/map/…` and origin checks are `startsWith(`${tileServer}/`)`.
47
+ */
20
48
  private readonly tileServer;
21
49
  private readonly refreshBuffer;
22
50
  private readonly swPath;
23
51
  private currentToken;
24
52
  private refreshTimeout;
25
53
  private tokenPromise;
54
+ private consecutiveFailures;
55
+ private destroyed;
56
+ /** "balance:exhausted" is once per client — see the event's docs. */
57
+ private balanceExhaustedEmitted;
26
58
  private listeners;
59
+ private static emptyListeners;
27
60
  constructor(options: TileryClientOptions);
61
+ /**
62
+ * Listen for the service worker's balance report.
63
+ *
64
+ * Wired here rather than in `registerServiceWorker()` because the worker may
65
+ * already be installed from an earlier page load — a consumer who registers
66
+ * once at deploy time still gets the event on every subsequent visit. Absent
67
+ * `navigator.serviceWorker` (Node, an old browser, a non-secure origin) this
68
+ * is simply a no-op.
69
+ */
70
+ private listenForWorkerMessages;
71
+ /** Bound, so `destroy()` can remove exactly this listener. */
72
+ private readonly onWorkerMessage;
28
73
  /**
29
74
  * Get current valid token, fetching if needed.
30
75
  * Token is cached and auto-refreshed before expiry.
31
76
  */
32
- getToken(): Promise<TileToken>;
77
+ getToken(): Promise<AccessToken>;
33
78
  /**
34
79
  * Get the current token string, or null if not yet fetched.
35
80
  * Does not trigger a fetch - use getToken() for that.
36
81
  */
37
82
  getCurrentTokenString(): string | null;
83
+ /**
84
+ * MapLibre-compatible `transformRequest` that rewrites tile-server URLs to
85
+ * carry the **current** access token at request time — the piece that keeps
86
+ * a map alive across token rotation (styles bake the initial token in once).
87
+ *
88
+ * Rewrites a URL only when it points at this client's `tileServer` **and**
89
+ * either already carries a `token` query param or is a tile request;
90
+ * everything else (foreign hosts, glyphs, sprites, styles) passes through
91
+ * unchanged. Before the first token is fetched, URLs pass through unchanged
92
+ * (the initial style already carries a token).
93
+ *
94
+ * Bound and synchronous, so it can be handed to MapLibre directly:
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * const map = new maplibregl.Map({
99
+ * container: 'map',
100
+ * style: await client.getMapStyle(),
101
+ * transformRequest: client.transformRequest,
102
+ * });
103
+ * ```
104
+ */
105
+ readonly transformRequest: (url: string, _resourceType?: string) => TransformedRequest;
106
+ /**
107
+ * Wire this client into a MapLibre map so tiles keep loading across token
108
+ * rotation: installs {@link transformRequest} via `map.setTransformRequest`
109
+ * and kicks {@link getToken} so the auto-refresh loop is running.
110
+ *
111
+ * Returns a `detach()` function that clears the hook
112
+ * (`map.setTransformRequest(null)`).
113
+ *
114
+ * **Caveat:** this *sets* the map's transformRequest. If you already use
115
+ * your own `transformRequest`, don't call this — compose manually with
116
+ * {@link transformRequest} and pass the composed function at map
117
+ * construction instead.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * const map = new maplibregl.Map({ container: 'map', style });
122
+ * const detach = client.attachToMap(map);
123
+ * ```
124
+ */
125
+ attachToMap(map: MapLike): () => void;
38
126
  /**
39
127
  * Register the service worker for tile caching.
40
128
  * Normalizes cache keys by stripping the token param for long-lived caching.
@@ -83,6 +171,18 @@ export declare class TileryClient {
83
171
  * ```
84
172
  */
85
173
  getMapStyle(options?: MapStyleOptions): Promise<MapStyle>;
174
+ /**
175
+ * Fetch the vector tileset's TileJSON descriptor and inject the current
176
+ * access token into the `tiles` URL template(s). The result can be used
177
+ * directly as a MapLibre/Leaflet/OpenLayers source.
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * const tilejson = await client.getTileJSON();
182
+ * map.addSource('tilery', { type: 'vector', ...tilejson });
183
+ * ```
184
+ */
185
+ getTileJSON(): Promise<TileJSON>;
86
186
  /**
87
187
  * Subscribe to an event.
88
188
  */
@@ -92,12 +192,37 @@ export declare class TileryClient {
92
192
  */
93
193
  off<K extends keyof TileryClientEvents>(event: K, listener: EventListener<TileryClientEvents[K]>): void;
94
194
  /**
95
- * Stop token refresh and clean up.
195
+ * Stop token refresh and clean up. Cancels the refresh timer and any
196
+ * pending failure-backoff retry; an in-flight fetch may still settle but
197
+ * will not schedule anything afterwards.
96
198
  */
97
199
  destroy(): void;
200
+ /**
201
+ * Emit "balance:exhausted", at most once for this client. Both detectors —
202
+ * the service worker's message and the SDK's own fetches — land here, so a
203
+ * page running both reports the stop once.
204
+ */
205
+ private emitBalanceExhausted;
206
+ /**
207
+ * The direct-fetch detector: the SDK's own requests to the tile server.
208
+ *
209
+ * Tiles themselves are fetched by the map library, not by this SDK, so this
210
+ * covers only what the SDK asks for — with the service worker installed, the
211
+ * worker is what sees a failing tile. Never throws: the caller is already on
212
+ * its way to reporting the failure its own way.
213
+ */
214
+ private noteResponse;
98
215
  private emit;
99
216
  private isTokenExpiringSoon;
100
217
  private fetchAndScheduleRefresh;
218
+ /**
219
+ * Timer-path refresh. Honors the same single-flight invariant as
220
+ * `getToken()`: if a mint is already in flight, that mint will schedule the
221
+ * next refresh (or the retry backoff) itself, so this becomes a no-op.
222
+ */
223
+ private refreshNow;
101
224
  private scheduleRefresh;
225
+ private scheduleRetryAfterFailure;
226
+ private setRefreshTimer;
102
227
  }
103
228
  //# 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,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC,OAAO,CAAC,YAAY,CAA0B;IAC9C,OAAO,CAAC,cAAc,CAA8C;IACpE,OAAO,CAAC,YAAY,CAAmC;IAGvD,OAAO,CAAC,SAAS,CAAgE;gBAErE,OAAO,EAAE,mBAAmB;IAOxC;;;OAGG;IACG,QAAQ,IAAI,OAAO,CAAC,SAAS,CAAC;IAoBpC;;;OAGG;IACH,qBAAqB,IAAI,MAAM,GAAG,IAAI;IAItC;;;;;;;;OAQG;IACG,qBAAqB,IAAI,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAqBxE;;;OAGG;IACH,MAAM,CAAC,oBAAoB,IAAI,MAAM;IAIrC;;OAEG;IACH,YAAY,CAAC,OAAO,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM;IASlF;;;OAGG;IACG,kBAAkB,IAAI,OAAO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AC,MAAM,CAAC,CAG1C;IAED;;OAEG;IACH,YAAY,IAAI,MAAM,CAErB;IAED;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEnC;IAED;;;;;;;;;OASG;IACG,WAAW,CAAC,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqClE;IAED;;;;;;;;;;OAUG;IACG,WAAW,IAAI,OAAO,CAAC,QAAQ,CAAC,CAuBrC;IAED;;OAEG;IACH,EAAE,CAAC,CAAC,SAAS,MAAM,kBAAkB,EACnC,KAAK,EAAE,CAAC,EACR,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,129 @@
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";
3
- //#endregion
4
- //#region src/client.ts
1
+ // \0virtual:service-worker-code
2
+ var code = "(()=>{const r=globalThis,i=\"tilery-tiles-v1\",w=/\\/map\\/tiles\\/[a-z0-9_]+\\/\\d+\\/\\d+\\/\\d+/,T=[\"application/x-protobuf\",\"application/vnd.mapbox-vector-tile\",\"application/octet-stream\",\"image/\"],h=2e3,f=100;let c=f,l=!1;const _=\"tilery:balance-exhausted\",u={error:\"balance_exhausted\",message:\"Credit balance is exhausted. Top up to resume serving.\",topUp:\"\"};let d=!1;function m(e){const s=new URL(e);return s.searchParams.delete(\"token\"),s.toString()}function A(e){return w.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;A(s.url)&&e.respondWith(L(e))});const R=10080*60,b=1e3;function C(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+)/),o=a?Number(a[1]):R;return Date.now()-t<=o*b}function g(e){if(!e.ok)return!1;const s=e.headers.get(\"content-type\")??\"\";return T.some(t=>s.startsWith(t))}async function P(e){try{const s=await e.json();if(typeof s==\"object\"&&s!==null){const t={...s};return{error:typeof t.error==\"string\"?t.error:u.error,message:typeof t.message==\"string\"?t.message:u.message,topUp:typeof t.top_up==\"string\"?t.top_up:\"\"}}}catch{}return u}async function U(e){if(d)return;d=!0;const s=await P(e),t=await r.clients.matchAll({includeUncontrolled:!0,type:\"window\"});for(const a of t)a.postMessage({payload:s,type:_})}function E(e){return e.status===402?U(e.clone()):(e.ok&&(d=!1),Promise.resolve())}async function S(e){const s=await e.keys();s.length>h&&await Promise.all(s.slice(0,s.length-h).map(t=>e.delete(t)))}async function y(e,s,t){try{await e.put(s,t)}catch{return}if(c+=1,!(c<f||l)){c=0,l=!0;try{await S(e)}catch{}finally{l=!1}}}async function k(e,s,t){try{const a=await fetch(s);await E(a),g(a)&&await y(e,t,a)}catch{}}async function L(e){const{request:s}=e,t=await caches.open(i),a=m(s.url),o=await t.match(a);if(o)return C(o)||e.waitUntil(k(t,s,a)),o;try{const n=await fetch(s);return e.waitUntil(E(n)),g(n)&&e.waitUntil(y(t,a,n.clone())),n}catch(n){const p=await t.match(a);if(p)return p;throw n}}async function N(){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 o=await a.keys(),n=await N();e.ports[0]?.postMessage({entries:o.length,size:o.length,usageBytes:n})}));break;case\"DELETE_TILE\":t?.url&&e.waitUntil((async()=>{try{const a=m(t.url),n=await(await caches.open(i)).delete(a);e.ports[0]?.postMessage({deleted:n})}catch{e.ports[0]?.postMessage({deleted:!1})}})());break}});})();\n";
3
+ // src/validate.ts
4
+ var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
+ var isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
6
+ /**
7
+ * Checks the fields `getMapStyle` touches: `sources` must be a record of
8
+ * source objects, each of whose `tiles` — optional, e.g. absent on a
9
+ * raster-dem terrain source — must be a `string[]` for token injection, and
10
+ * `layers` must be an array.
11
+ */
12
+ function isMapStyle(value) {
13
+ if (!isRecord$1(value)) return false;
14
+ if (!Array.isArray(value.layers)) return false;
15
+ if (!isRecord$1(value.sources)) return false;
16
+ return Object.values(value.sources).every((source) => isRecord$1(source) && (source.tiles === void 0 || isStringArray(source.tiles)));
17
+ }
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
+ function isTileJSON(value) {
23
+ return isRecord$1(value) && typeof value.tilejson === "string" && isStringArray(value.tiles);
24
+ }
25
+ // src/client.ts
5
26
  var MS_PER_SECOND = 1e3;
6
- var DEFAULT_TILE_SERVER = "https://api.tilery.eu";
27
+ var DEFAULT_TILE_SERVER = "https://tiles.tilery.eu";
7
28
  var DEFAULT_REFRESH_BUFFER = 60;
8
29
  var DEFAULT_SW_PATH = "/tilery-sw.js";
9
30
  /**
31
+ * Minimum delay before any scheduled token refresh. Floors the schedule so a
32
+ * pathological `getToken` result (e.g. an already-expired `exp` from clock
33
+ * skew or an HTTP-cached token response) can never produce a 0 ms mint loop.
34
+ */
35
+ var MIN_REFRESH_DELAY_MS = 5e3;
36
+ /**
37
+ * Base delay for the retry backoff after a failed refresh. Consecutive
38
+ * failures back off at `RETRY_BASE_DELAY_MS · 2ⁿ⁻¹`, capped at
39
+ * {@link MAX_RETRY_DELAY_MS}; a success resets the streak.
40
+ */
41
+ var RETRY_BASE_DELAY_MS = 1e3;
42
+ /** Upper bound for the retry backoff after failed refreshes. */
43
+ var MAX_RETRY_DELAY_MS = 6e4;
44
+ /** `exp` values above `now-in-seconds × 100` are almost certainly unix milliseconds. */
45
+ var MS_EXP_HEURISTIC_FACTOR = 100;
46
+ /**
47
+ * The message the service worker posts to every page when a tile request comes
48
+ * back `402` — the account is out of credits and the map has stopped drawing.
49
+ *
50
+ * Exported so a consumer who wires their own `navigator.serviceWorker`
51
+ * listener (or ships the worker without this client) can recognise it. The
52
+ * same string is spelled in `service-worker.ts`, which cannot import: it is
53
+ * transformed rather than bundled, and ships as a classic script.
54
+ */
55
+ var BALANCE_EXHAUSTED_MESSAGE_TYPE = "tilery:balance-exhausted";
56
+ /** HTTP status the tile API answers with once the credits are gone. */
57
+ var PAYMENT_REQUIRED = 402;
58
+ /** What the SDK says when a 402 carries no readable body. Matches the
59
+ * service worker's own fallback; the top-up URL is never invented. */
60
+ var BALANCE_EXHAUSTED_FALLBACK = {
61
+ error: "balance_exhausted",
62
+ message: "Credit balance is exhausted. Top up to resume serving.",
63
+ topUp: ""
64
+ };
65
+ /** Concrete tile request path: `/map/tiles/{kind}/{z}/{x}/{y}`. */
66
+ var TILE_PATH_PATTERN = /\/map\/tiles\/[a-z0-9_]+\/\d+\/\d+\/\d+/;
67
+ function isRecord(value) {
68
+ return typeof value === "object" && value !== null;
69
+ }
70
+ /** A string field, or the written-out fallback. */
71
+ function stringOr(value, fallback) {
72
+ return typeof value === "string" ? value : fallback;
73
+ }
74
+ /**
75
+ * Narrow whatever arrives — a `postMessage` payload from the service worker,
76
+ * or a parsed 402 body — into the event's shape. `top_up` is the wire
77
+ * spelling; `topUp` is what a worker message already carries.
78
+ */
79
+ function toBalanceExhausted(value) {
80
+ if (!isRecord(value)) return BALANCE_EXHAUSTED_FALLBACK;
81
+ return {
82
+ error: stringOr(value.error, BALANCE_EXHAUSTED_FALLBACK.error),
83
+ message: stringOr(value.message, BALANCE_EXHAUSTED_FALLBACK.message),
84
+ topUp: stringOr(value.topUp ?? value.top_up, "")
85
+ };
86
+ }
87
+ /**
88
+ * True for an absolute `http:`/`https:` URL. A guarded parse rather than
89
+ * `URL.canParse`, which only ships in 2023+ browsers.
90
+ */
91
+ function isAbsoluteHttpUrl(value) {
92
+ try {
93
+ const { protocol } = new URL(value);
94
+ return protocol === "https:" || protocol === "http:";
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
99
+ /**
100
+ * Reject a `tileServer` this client can't serve. A relative one (a same-origin
101
+ * proxy path like `/tiles`) never rotates its token: MapLibre requests absolute
102
+ * URLs, so {@link TileryClient.transformRequest} never matches them, and the
103
+ * served style names tiles.tilery.eu anyway.
104
+ */
105
+ function validateTileServer(tileServer) {
106
+ if (!isAbsoluteHttpUrl(tileServer)) throw new Error(`[TileryClient] tileServer must be an absolute http(s) URL such as ${DEFAULT_TILE_SERVER}; got ${JSON.stringify(tileServer)}. Proxy setups (a same-origin path like /tiles) aren't supported yet.`);
107
+ return tileServer;
108
+ }
109
+ /**
110
+ * Validate a `getToken` result at the boundary. Consumer mistakes (returning
111
+ * the `Response` itself, `exp` in milliseconds, `{ token }` only) must fail
112
+ * loudly here instead of becoming a "never expires" token or a hot mint loop.
113
+ */
114
+ function validateTokenResult(value) {
115
+ const expected = "[TileryClient] getToken must resolve to { token: string, exp: number } (exp in unix seconds)";
116
+ if (!isRecord(value)) throw new TypeError(`${expected}; got ${typeof value}`);
117
+ const { exp, token } = value;
118
+ if (typeof token !== "string" || token.length === 0) throw new TypeError(`${expected}; token is missing or not a non-empty string`);
119
+ if (typeof exp !== "number" || !Number.isFinite(exp)) throw new TypeError(`${expected}; exp is missing or not a finite number`);
120
+ 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");
121
+ return {
122
+ exp,
123
+ token
124
+ };
125
+ }
126
+ /**
10
127
  * Tilery client for managing tile tokens and service worker caching.
11
128
  *
12
129
  * @example
@@ -22,16 +139,59 @@ var DEFAULT_SW_PATH = "/tilery-sw.js";
22
139
  * const style = await client.getMapStyle({ flavor: 'dark' });
23
140
  * ```
24
141
  */
25
- var TileryClient = class {
142
+ var TileryClient = class TileryClient {
143
+ static emptyListeners() {
144
+ return {
145
+ "balance:exhausted": /* @__PURE__ */ new Set(),
146
+ "token:refresh": /* @__PURE__ */ new Set(),
147
+ "token:error": /* @__PURE__ */ new Set(),
148
+ "sw:registered": /* @__PURE__ */ new Set(),
149
+ "sw:error": /* @__PURE__ */ new Set()
150
+ };
151
+ }
26
152
  constructor(options) {
27
153
  this.currentToken = null;
28
154
  this.refreshTimeout = null;
29
155
  this.tokenPromise = null;
30
- this.listeners = /* @__PURE__ */ new Map();
156
+ this.consecutiveFailures = 0;
157
+ this.destroyed = false;
158
+ this.balanceExhaustedEmitted = false;
159
+ this.listeners = TileryClient.emptyListeners();
160
+ this.onWorkerMessage = (event) => {
161
+ if (!("data" in event)) return;
162
+ const { data } = event;
163
+ if (!isRecord(data) || data.type !== "tilery:balance-exhausted") return;
164
+ if (!isRecord(data.payload)) return;
165
+ this.emitBalanceExhausted(toBalanceExhausted(data.payload));
166
+ };
167
+ this.transformRequest = (url, _resourceType) => {
168
+ const token = this.currentToken?.token;
169
+ if (!token) return { url };
170
+ if (!url.startsWith(`${this.tileServer}/`)) return { url };
171
+ const parsed = new URL(url);
172
+ if (!parsed.searchParams.has("token") && !TILE_PATH_PATTERN.test(parsed.pathname)) return { url };
173
+ parsed.searchParams.set("token", token);
174
+ return { url: parsed.toString() };
175
+ };
31
176
  this.getTokenFn = options.getToken;
32
- this.tileServer = options.tileServer ?? DEFAULT_TILE_SERVER;
177
+ const tileServer = validateTileServer(options.tileServer ?? DEFAULT_TILE_SERVER);
178
+ this.tileServer = tileServer.endsWith("/") ? tileServer.slice(0, -1) : tileServer;
33
179
  this.refreshBuffer = options.refreshBuffer ?? DEFAULT_REFRESH_BUFFER;
34
180
  this.swPath = options.serviceWorkerPath ?? DEFAULT_SW_PATH;
181
+ this.listenForWorkerMessages();
182
+ }
183
+ /**
184
+ * Listen for the service worker's balance report.
185
+ *
186
+ * Wired here rather than in `registerServiceWorker()` because the worker may
187
+ * already be installed from an earlier page load — a consumer who registers
188
+ * once at deploy time still gets the event on every subsequent visit. Absent
189
+ * `navigator.serviceWorker` (Node, an old browser, a non-secure origin) this
190
+ * is simply a no-op.
191
+ */
192
+ listenForWorkerMessages() {
193
+ if (typeof navigator === "undefined" || !navigator.serviceWorker) return;
194
+ navigator.serviceWorker.addEventListener("message", this.onWorkerMessage);
35
195
  }
36
196
  /**
37
197
  * Get current valid token, fetching if needed.
@@ -55,6 +215,32 @@ var TileryClient = class {
55
215
  return this.currentToken?.token ?? null;
56
216
  }
57
217
  /**
218
+ * Wire this client into a MapLibre map so tiles keep loading across token
219
+ * rotation: installs {@link transformRequest} via `map.setTransformRequest`
220
+ * and kicks {@link getToken} so the auto-refresh loop is running.
221
+ *
222
+ * Returns a `detach()` function that clears the hook
223
+ * (`map.setTransformRequest(null)`).
224
+ *
225
+ * **Caveat:** this *sets* the map's transformRequest. If you already use
226
+ * your own `transformRequest`, don't call this — compose manually with
227
+ * {@link transformRequest} and pass the composed function at map
228
+ * construction instead.
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * const map = new maplibregl.Map({ container: 'map', style });
233
+ * const detach = client.attachToMap(map);
234
+ * ```
235
+ */
236
+ attachToMap(map) {
237
+ map.setTransformRequest(this.transformRequest);
238
+ this.getToken().catch(() => {});
239
+ return () => {
240
+ map.setTransformRequest(null);
241
+ };
242
+ }
243
+ /**
58
244
  * Register the service worker for tile caching.
59
245
  * Normalizes cache keys by stripping the token param for long-lived caching.
60
246
  *
@@ -96,7 +282,7 @@ var TileryClient = class {
96
282
  const { token, x, y, z } = options;
97
283
  const tok = token ?? this.currentToken?.token;
98
284
  if (!tok) throw new Error("No token available. Call getToken() first.");
99
- return `${this.tileServer}/map/tiles/${z}/${x}/${y}?token=${encodeURIComponent(tok)}`;
285
+ return `${this.tileServer}/map/tiles/vector/${z}/${x}/${y}?token=${encodeURIComponent(tok)}`;
100
286
  }
101
287
  /**
102
288
  * Get the tile URL template with {z}, {x}, {y} placeholders.
@@ -104,7 +290,7 @@ var TileryClient = class {
104
290
  */
105
291
  async getTileUrlTemplate() {
106
292
  const token = await this.getToken();
107
- return `${this.tileServer}/map/tiles/{z}/{x}/{y}?token=${encodeURIComponent(token.token)}`;
293
+ return `${this.tileServer}/map/tiles/vector/{z}/{x}/{y}?token=${encodeURIComponent(token.token)}`;
108
294
  }
109
295
  /**
110
296
  * Get the font (glyph) URL template.
@@ -131,39 +317,100 @@ var TileryClient = class {
131
317
  async getMapStyle(options = {}) {
132
318
  const { flavor = "light" } = options;
133
319
  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();
320
+ if (!res.ok) {
321
+ await this.noteResponse(res);
322
+ throw new Error(`Failed to fetch style "${flavor}": ${res.status} ${res.statusText}`);
323
+ }
324
+ const body = await res.json();
325
+ if (!isMapStyle(body)) throw new Error(`Tile server returned an unexpected style response for "${flavor}"`);
326
+ const style = body;
136
327
  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}`);
328
+ for (const source of Object.values(style.sources)) {
329
+ if (!Array.isArray(source.tiles)) continue;
330
+ source.tiles = source.tiles.map((url) => {
331
+ if (!url.startsWith(`${this.tileServer}/`)) return url;
332
+ return url.includes("?") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`;
333
+ });
334
+ }
138
335
  return style;
139
336
  }
140
337
  /**
338
+ * Fetch the vector tileset's TileJSON descriptor and inject the current
339
+ * access token into the `tiles` URL template(s). The result can be used
340
+ * directly as a MapLibre/Leaflet/OpenLayers source.
341
+ *
342
+ * @example
343
+ * ```ts
344
+ * const tilejson = await client.getTileJSON();
345
+ * map.addSource('tilery', { type: 'vector', ...tilejson });
346
+ * ```
347
+ */
348
+ async getTileJSON() {
349
+ const [token, res] = await Promise.all([this.getToken(), fetch(`${this.tileServer}/map/tiles/vector.json`)]);
350
+ if (!res.ok) {
351
+ await this.noteResponse(res);
352
+ throw new Error(`Failed to fetch TileJSON: ${res.status} ${res.statusText}`);
353
+ }
354
+ const body = await res.json();
355
+ if (!isTileJSON(body)) throw new Error("Tile server returned an unexpected TileJSON response");
356
+ const tilejson = body;
357
+ const tokenParam = `token=${encodeURIComponent(token.token)}`;
358
+ tilejson.tiles = tilejson.tiles.map((url) => url.includes("?") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`);
359
+ return tilejson;
360
+ }
361
+ /**
141
362
  * Subscribe to an event.
142
363
  */
143
364
  on(event, listener) {
144
- if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
145
- this.listeners.get(event).add(listener);
365
+ this.listeners[event].add(listener);
146
366
  }
147
367
  /**
148
368
  * Unsubscribe from an event.
149
369
  */
150
370
  off(event, listener) {
151
- this.listeners.get(event)?.delete(listener);
371
+ this.listeners[event].delete(listener);
152
372
  }
153
373
  /**
154
- * Stop token refresh and clean up.
374
+ * Stop token refresh and clean up. Cancels the refresh timer and any
375
+ * pending failure-backoff retry; an in-flight fetch may still settle but
376
+ * will not schedule anything afterwards.
155
377
  */
156
378
  destroy() {
379
+ this.destroyed = true;
380
+ if (typeof navigator !== "undefined" && navigator.serviceWorker) navigator.serviceWorker.removeEventListener("message", this.onWorkerMessage);
157
381
  if (this.refreshTimeout) {
158
382
  clearTimeout(this.refreshTimeout);
159
383
  this.refreshTimeout = null;
160
384
  }
161
385
  this.currentToken = null;
162
386
  this.tokenPromise = null;
163
- this.listeners.clear();
387
+ this.listeners = TileryClient.emptyListeners();
388
+ }
389
+ /**
390
+ * Emit "balance:exhausted", at most once for this client. Both detectors —
391
+ * the service worker's message and the SDK's own fetches — land here, so a
392
+ * page running both reports the stop once.
393
+ */
394
+ emitBalanceExhausted(payload) {
395
+ if (this.balanceExhaustedEmitted) return;
396
+ this.balanceExhaustedEmitted = true;
397
+ this.emit("balance:exhausted", payload);
398
+ }
399
+ /**
400
+ * The direct-fetch detector: the SDK's own requests to the tile server.
401
+ *
402
+ * Tiles themselves are fetched by the map library, not by this SDK, so this
403
+ * covers only what the SDK asks for — with the service worker installed, the
404
+ * worker is what sees a failing tile. Never throws: the caller is already on
405
+ * its way to reporting the failure its own way.
406
+ */
407
+ async noteResponse(response) {
408
+ if (response.status !== PAYMENT_REQUIRED) return;
409
+ const body = await response.json().catch(() => null);
410
+ this.emitBalanceExhausted(toBalanceExhausted(body));
164
411
  }
165
412
  emit(event, data) {
166
- this.listeners.get(event)?.forEach((listener) => {
413
+ this.listeners[event].forEach((listener) => {
167
414
  try {
168
415
  listener(data);
169
416
  } catch (e) {
@@ -177,35 +424,55 @@ var TileryClient = class {
177
424
  }
178
425
  async fetchAndScheduleRefresh() {
179
426
  try {
180
- const token = await this.getTokenFn();
427
+ const token = validateTokenResult(await this.getTokenFn());
181
428
  this.currentToken = token;
429
+ this.consecutiveFailures = 0;
182
430
  this.scheduleRefresh(token);
183
431
  this.emit("token:refresh", token);
184
432
  return token;
185
433
  } catch (error) {
186
434
  const err = error instanceof Error ? error : new Error(String(error));
435
+ this.consecutiveFailures += 1;
187
436
  this.emit("token:error", err);
437
+ this.scheduleRetryAfterFailure();
188
438
  throw err;
189
439
  }
190
440
  }
441
+ /**
442
+ * Timer-path refresh. Honors the same single-flight invariant as
443
+ * `getToken()`: if a mint is already in flight, that mint will schedule the
444
+ * next refresh (or the retry backoff) itself, so this becomes a no-op.
445
+ */
446
+ refreshNow() {
447
+ if (this.tokenPromise) return;
448
+ const promise = this.fetchAndScheduleRefresh();
449
+ this.tokenPromise = promise;
450
+ promise.catch((error) => {
451
+ console.error("[TileryClient] Token refresh failed:", error);
452
+ }).finally(() => {
453
+ if (this.tokenPromise === promise) this.tokenPromise = null;
454
+ });
455
+ }
191
456
  scheduleRefresh(token) {
192
- if (this.refreshTimeout) clearTimeout(this.refreshTimeout);
193
457
  const now = Math.floor(Date.now() / MS_PER_SECOND);
194
458
  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
- }
459
+ const delayMs = Math.max(MIN_REFRESH_DELAY_MS, (refreshAt - now) * MS_PER_SECOND);
460
+ this.setRefreshTimer(delayMs);
461
+ }
462
+ scheduleRetryAfterFailure() {
463
+ const exponent = Math.max(0, this.consecutiveFailures - 1);
464
+ const delayMs = Math.min(RETRY_BASE_DELAY_MS * 2 ** exponent, MAX_RETRY_DELAY_MS);
465
+ this.setRefreshTimer(delayMs);
466
+ }
467
+ setRefreshTimer(delayMs) {
468
+ if (this.destroyed) return;
469
+ if (this.refreshTimeout) clearTimeout(this.refreshTimeout);
470
+ this.refreshTimeout = setTimeout(() => {
471
+ this.refreshTimeout = null;
472
+ this.refreshNow();
205
473
  }, delayMs);
206
474
  }
207
475
  };
208
- //#endregion
209
- export { code as SERVICE_WORKER_CODE, TileryClient };
476
+ export { BALANCE_EXHAUSTED_MESSAGE_TYPE, MAX_RETRY_DELAY_MS, MIN_REFRESH_DELAY_MS, RETRY_BASE_DELAY_MS, code as SERVICE_WORKER_CODE, TileryClient };
210
477
 
211
478
  //# 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;YACV;AACR,QAAK,eAAe;;;;;;;CAQxB,wBAAuC;AACrC,SAAO,KAAK,cAAc,SAAS;;;;;;;;;;;CAYrC,MAAM,wBAAmE;AACvE,MAAI,OAAO,cAAc,eAAe,EAAE,mBAAmB,YAAY;AACvE,WAAQ,KAAK,+CAA+C;AA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M,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":["isRecord","serviceWorkerCode"],"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 exhausted. Top up to resume serving.\",\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 * True for an absolute `http:`/`https:` URL. A guarded parse rather than\n * `URL.canParse`, which only ships in 2023+ browsers.\n */\nfunction isAbsoluteHttpUrl(value: string): boolean {\n try {\n const { protocol } = new URL(value);\n return protocol === \"https:\" || protocol === \"http:\";\n } catch {\n return false;\n }\n}\n\n/**\n * Reject a `tileServer` this client can't serve. A relative one (a same-origin\n * proxy path like `/tiles`) never rotates its token: MapLibre requests absolute\n * URLs, so {@link TileryClient.transformRequest} never matches them, and the\n * served style names tiles.tilery.eu anyway.\n */\nfunction validateTileServer(tileServer: string): string {\n if (!isAbsoluteHttpUrl(tileServer)) {\n throw new Error(\n `[TileryClient] tileServer must be an absolute http(s) URL such as ${DEFAULT_TILE_SERVER}; got ${JSON.stringify(tileServer)}. Proxy setups (a same-origin path like /tiles) aren't supported yet.`,\n );\n }\n return tileServer;\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 /**\n * The `tileServer` option without a trailing slash, so every URL is built as\n * `${tileServer}/map/…` and origin checks are `startsWith(`${tileServer}/`)`.\n */\n private readonly tileServer: 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 const tileServer = validateTileServer(options.tileServer ?? DEFAULT_TILE_SERVER);\n this.tileServer = tileServer.endsWith(\"/\") ? tileServer.slice(0, -1) : 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.tileServer}/`)) {\n return { url };\n }\n // Parses: tileServer was checked to be an absolute http(s) URL at\n // construction, so a URL under it is one too.\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 };\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.tileServer}/`)) {\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,IAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,IAAM,iBAAiB,UACrB,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ;;;;;;;AAQxE,SAAgB,WAAW,OAAmC;CAC5D,IAAI,CAACA,WAAS,KAAK,GACjB,OAAO;CAET,IAAI,CAAC,MAAM,QAAQ,MAAM,MAAM,GAC7B,OAAO;CAET,IAAI,CAACA,WAAS,MAAM,OAAO,GACzB,OAAO;CAET,OAAO,OAAO,OAAO,MAAM,OAAO,CAAC,CAAC,OACjC,WAAWA,WAAS,MAAM,MAAM,OAAO,UAAU,KAAA,KAAa,cAAc,OAAO,KAAK,EAC3F;AACF;;;;;AAMA,SAAgB,WAAW,OAAmC;CAC5D,OAAOA,WAAS,KAAK,KAAK,OAAO,MAAM,aAAa,YAAY,cAAc,MAAM,KAAK;AAC3F;;AC1BA,IAAM,gBAAgB;AACtB,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;AAC/B,IAAM,kBAAkB;;;;;;AAOxB,IAAa,uBAAuB;;;;;;AAOpC,IAAa,sBAAsB;;AAGnC,IAAa,qBAAqB;;AAGlC,IAAM,0BAA0B;;;;;;;;;;AAWhC,IAAa,iCAAiC;;AAG9C,IAAM,mBAAmB;;;AAIzB,IAAM,6BAA+C;CACnD,OAAO;CACP,SAAS;CACT,OAAO;AACT;;AAGA,IAAM,oBAAoB;AAE1B,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY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AC9B;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;AAwYH,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",w=/\/map\/tiles\/[a-z0-9_]+\/\d+\/\d+\/\d+/,T=["application/x-protobuf","application/vnd.mapbox-vector-tile","application/octet-stream","image/"],h=2e3,f=100;let c=f,l=!1;const _="tilery:balance-exhausted",u={error:"balance_exhausted",message:"Credit balance is exhausted. Top up to resume serving.",topUp:""};let d=!1;function m(e){const s=new URL(e);return s.searchParams.delete("token"),s.toString()}function A(e){return w.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;A(s.url)&&e.respondWith(L(e))});const R=10080*60,b=1e3;function C(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+)/),o=a?Number(a[1]):R;return Date.now()-t<=o*b}function g(e){if(!e.ok)return!1;const s=e.headers.get("content-type")??"";return T.some(t=>s.startsWith(t))}async function P(e){try{const s=await e.json();if(typeof s=="object"&&s!==null){const t={...s};return{error:typeof t.error=="string"?t.error:u.error,message:typeof t.message=="string"?t.message:u.message,topUp:typeof t.top_up=="string"?t.top_up:""}}}catch{}return u}async function U(e){if(d)return;d=!0;const s=await P(e),t=await r.clients.matchAll({includeUncontrolled:!0,type:"window"});for(const a of t)a.postMessage({payload:s,type:_})}function E(e){return e.status===402?U(e.clone()):(e.ok&&(d=!1),Promise.resolve())}async function S(e){const s=await e.keys();s.length>h&&await Promise.all(s.slice(0,s.length-h).map(t=>e.delete(t)))}async function y(e,s,t){try{await e.put(s,t)}catch{return}if(c+=1,!(c<f||l)){c=0,l=!0;try{await S(e)}catch{}finally{l=!1}}}async function k(e,s,t){try{const a=await fetch(s);await E(a),g(a)&&await y(e,t,a)}catch{}}async function L(e){const{request:s}=e,t=await caches.open(i),a=m(s.url),o=await t.match(a);if(o)return C(o)||e.waitUntil(k(t,s,a)),o;try{const n=await fetch(s);return e.waitUntil(E(n)),g(n)&&e.waitUntil(y(t,a,n.clone())),n}catch(n){const p=await t.match(a);if(p)return p;throw n}}async function N(){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 o=await a.keys(),n=await N();e.ports[0]?.postMessage({entries:o.length,size:o.length,usageBytes:n})}));break;case"DELETE_TILE":t?.url&&e.waitUntil((async()=>{try{const a=m(t.url),n=await(await caches.open(i)).delete(a);e.ports[0]?.postMessage({deleted:n})}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,10 @@ 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
35
- * staging environment.
36
- * @default 'https://api.tilery.eu'
34
+ * Tile server URL. Set to `https://tiles.test.tilery.eu` to point at the
35
+ * staging environment. Must be an absolute http(s) URL: the constructor
36
+ * throws on a relative path like `/tiles`.
37
+ * @default 'https://tiles.tilery.eu'
37
38
  */
38
39
  tileServer?: string;
39
40
  /**
@@ -45,6 +46,11 @@ export interface TileryClientOptions {
45
46
  * Path to the service worker script.
46
47
  * Required for Firefox (doesn't support blob: URLs for service workers).
47
48
  * Create a file with: import { SERVICE_WORKER_CODE } from '@tilery/client';
49
+ *
50
+ * Registration always uses scope '/' so the worker controls every page on
51
+ * the origin. If this file is served from a subdirectory (e.g.
52
+ * '/assets/tilery-sw.js'), the server must send a
53
+ * `Service-Worker-Allowed: /` header on it, or registration fails.
48
54
  * @default '/tilery-sw.js'
49
55
  */
50
56
  serviceWorkerPath?: string;
@@ -76,18 +82,98 @@ export interface MapStyle {
76
82
  }>;
77
83
  layers: unknown[];
78
84
  }
85
+ /**
86
+ * TileJSON 3.0 descriptor (https://github.com/mapbox/tilejson-spec) for the
87
+ * vector tileset, served at `GET {tileServer}/map/tiles/vector.json`.
88
+ * `getTileJSON()` injects the access token into `tiles` before returning it.
89
+ */
90
+ export interface TileJSON {
91
+ /** TileJSON spec version (e.g. "3.0.0"). */
92
+ tilejson: string;
93
+ name: string;
94
+ /** Tiling scheme — "xyz". */
95
+ scheme: string;
96
+ /** Tile URL template(s) with `{z}/{x}/{y}` placeholders. */
97
+ tiles: string[];
98
+ minzoom: number;
99
+ maxzoom: number;
100
+ /** `[west, south, east, north]` in WGS84 degrees. */
101
+ bounds: [number, number, number, number];
102
+ attribution: string;
103
+ }
104
+ /**
105
+ * Return shape of {@link TransformRequestFn}: the (possibly rewritten) URL.
106
+ * Structurally compatible with MapLibre's `RequestParameters`.
107
+ */
108
+ export interface TransformedRequest {
109
+ url: string;
110
+ }
111
+ /**
112
+ * A MapLibre-compatible `transformRequest` callback. `resourceType` is
113
+ * MapLibre's `ResourceType` string ("Tile", "Glyphs", …) but is typed as
114
+ * plain `string` so this package needs no maplibre import.
115
+ */
116
+ export type TransformRequestFn = (url: string, resourceType?: string) => TransformedRequest;
117
+ /**
118
+ * Structural subset of `maplibregl.Map` used by `client.attachToMap()`.
119
+ *
120
+ * Kept structural so `@tilery/client` has zero runtime (and zero type)
121
+ * dependencies. Shape checked against maplibre-gl 6.5.0, where
122
+ * `setTransformRequest(transformRequest: RequestTransformFunction | null): this`
123
+ * and passing `null` clears the map's transform. Method syntax (not a
124
+ * property arrow) is deliberate: TS checks method parameters bivariantly,
125
+ * which is what lets `maplibregl.Map` satisfy this interface.
126
+ */
127
+ export interface MapLike {
128
+ setTransformRequest(transformRequest: TransformRequestFn | null): unknown;
129
+ }
130
+ /**
131
+ * What the tile API says when the account has run out of credits: the body of
132
+ * its `402 Payment Required`, in this SDK's spelling (`top_up` on the wire).
133
+ *
134
+ * Usage beyond what the account's plan includes counts against its balance
135
+ * within about 1 hour 25 minutes; once the balance can't cover it, serving stops,
136
+ * with no grace period. That is the state this describes: not "you spent your last credit",
137
+ * but "the balance could not cover usage, 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;;;;;;;;;;;;OAYG;IACH,QAAQ,EAAE,UAAU,CAAC;IAErB;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,OAAO,EAAE,CAAC,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CACb,MAAM,EACN;QACE,IAAI,EAAE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CAAuC;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.5",
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 && tsc -p tsconfig.test.json",
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
  }