@chaosity/location-client 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +107 -4
  2. package/dist/cjs/client/GeoPlacesClient.d.ts +13 -2
  3. package/dist/cjs/client/GeoPlacesClient.js +59 -9
  4. package/dist/cjs/index.d.ts +1 -1
  5. package/dist/cjs/index.js +3 -2
  6. package/dist/cjs/maps/createTransformRequest.d.ts +2 -0
  7. package/dist/cjs/maps/createTransformRequest.js +45 -1
  8. package/dist/cjs/maps/mapStyle.d.ts +3 -1
  9. package/dist/cjs/maps/mapStyle.js +24 -19
  10. package/dist/cjs/maps/staticMap.d.ts +3 -1
  11. package/dist/cjs/maps/staticMap.js +18 -12
  12. package/dist/cjs/server/LocationServiceConnector.d.ts +56 -7
  13. package/dist/cjs/server/LocationServiceConnector.js +210 -32
  14. package/dist/cjs/server/getClientConfig.d.ts +76 -3
  15. package/dist/cjs/server/getClientConfig.js +152 -74
  16. package/dist/cjs/transport/errors.d.ts +30 -0
  17. package/dist/cjs/transport/errors.js +40 -0
  18. package/dist/cjs/transport/http.d.ts +36 -0
  19. package/dist/cjs/transport/http.js +118 -15
  20. package/dist/cjs/types/index.d.ts +37 -1
  21. package/dist/client/GeoPlacesClient.d.ts +13 -2
  22. package/dist/client/GeoPlacesClient.js +59 -9
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +2 -2
  25. package/dist/maps/createTransformRequest.d.ts +2 -0
  26. package/dist/maps/createTransformRequest.js +45 -1
  27. package/dist/maps/mapStyle.d.ts +3 -1
  28. package/dist/maps/mapStyle.js +25 -20
  29. package/dist/maps/staticMap.d.ts +3 -1
  30. package/dist/maps/staticMap.js +19 -13
  31. package/dist/server/LocationServiceConnector.d.ts +56 -7
  32. package/dist/server/LocationServiceConnector.js +211 -33
  33. package/dist/server/getClientConfig.d.ts +76 -3
  34. package/dist/server/getClientConfig.js +149 -74
  35. package/dist/transport/errors.d.ts +30 -0
  36. package/dist/transport/errors.js +38 -0
  37. package/dist/transport/http.d.ts +36 -0
  38. package/dist/transport/http.js +116 -14
  39. package/dist/types/index.d.ts +37 -1
  40. package/package.json +1 -1
@@ -12,8 +12,38 @@ import { LocationServiceException } from '../errors/LocationServiceException.js'
12
12
  * { message: "Unauthorized" } API Gateway's own responses
13
13
  */
14
14
  export declare function parseErrorResponse(status: number, statusText: string, body: string, headers?: Headers): LocationServiceException;
15
+ /**
16
+ * The API has rejected this token: a 401, and only a 401.
17
+ *
18
+ * The authorizer throws `Unauthorized` for a token it cannot verify or that has
19
+ * expired, and API Gateway turns that into a 401. Its other refusals — no
20
+ * domain configured for the application, an Origin the application does not
21
+ * allow — are a Deny policy or a service 403, and a fresh token changes
22
+ * neither. Retrying those sends the same doomed request twice, for the same
23
+ * answer — which is the whole cost, since the service meters successful
24
+ * requests and no error response is billed whatever its status.
25
+ *
26
+ * Shared by both send paths so the browser client and the server connector
27
+ * cannot come to different conclusions about the same response.
28
+ */
29
+ export declare function isTokenRejected(err: unknown): boolean;
15
30
  /**
16
31
  * `Retry-After` is either delta-seconds or an HTTP date. Both are legal and the
17
32
  * API sends the first; a date is handled so a proxy or gateway cannot surprise us.
18
33
  */
19
34
  export declare function parseRetryAfter(value: string | null | undefined): number | undefined;
35
+ /**
36
+ * No token to send, so nothing is sent.
37
+ *
38
+ * Every send path resolves a token before it builds a request, and every one of
39
+ * them can come up empty — a provider that has not initialised, a server action
40
+ * that returned nothing, credentials that are not configured. Sending anyway
41
+ * puts the literal string `Bearer undefined` on the wire, which the API answers
42
+ * with a 401 the caller then has to work backwards from — a whole round trip,
43
+ * paid for out of the caller's own deadline, to be told what it already knew.
44
+ * The map fetches did exactly that until #37.
45
+ *
46
+ * `advice` says what to check, because that differs by path: a server connector
47
+ * wants its client credentials looked at, a browser map wants its token source.
48
+ */
49
+ export declare function noTokenAvailable(advice: string): LocationServiceException;
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseErrorResponse = parseErrorResponse;
4
+ exports.isTokenRejected = isTokenRejected;
4
5
  exports.parseRetryAfter = parseRetryAfter;
6
+ exports.noTokenAvailable = noTokenAvailable;
5
7
  const LocationServiceException_js_1 = require("../errors/LocationServiceException.js");
6
8
  /**
7
9
  * Turn a non-2xx response into a LocationServiceException.
@@ -87,6 +89,23 @@ function statusCode(status) {
87
89
  return status >= 500 ? 'InternalException' : 'ServiceException';
88
90
  }
89
91
  }
92
+ /**
93
+ * The API has rejected this token: a 401, and only a 401.
94
+ *
95
+ * The authorizer throws `Unauthorized` for a token it cannot verify or that has
96
+ * expired, and API Gateway turns that into a 401. Its other refusals — no
97
+ * domain configured for the application, an Origin the application does not
98
+ * allow — are a Deny policy or a service 403, and a fresh token changes
99
+ * neither. Retrying those sends the same doomed request twice, for the same
100
+ * answer — which is the whole cost, since the service meters successful
101
+ * requests and no error response is billed whatever its status.
102
+ *
103
+ * Shared by both send paths so the browser client and the server connector
104
+ * cannot come to different conclusions about the same response.
105
+ */
106
+ function isTokenRejected(err) {
107
+ return err instanceof LocationServiceException_js_1.LocationServiceException && err.statusCode === 401;
108
+ }
90
109
  /**
91
110
  * `Retry-After` is either delta-seconds or an HTTP date. Both are legal and the
92
111
  * API sends the first; a date is handled so a proxy or gateway cannot surprise us.
@@ -102,3 +121,24 @@ function parseRetryAfter(value) {
102
121
  return Math.max(0, date - Date.now());
103
122
  return undefined;
104
123
  }
124
+ /**
125
+ * No token to send, so nothing is sent.
126
+ *
127
+ * Every send path resolves a token before it builds a request, and every one of
128
+ * them can come up empty — a provider that has not initialised, a server action
129
+ * that returned nothing, credentials that are not configured. Sending anyway
130
+ * puts the literal string `Bearer undefined` on the wire, which the API answers
131
+ * with a 401 the caller then has to work backwards from — a whole round trip,
132
+ * paid for out of the caller's own deadline, to be told what it already knew.
133
+ * The map fetches did exactly that until #37.
134
+ *
135
+ * `advice` says what to check, because that differs by path: a server connector
136
+ * wants its client credentials looked at, a browser map wants its token source.
137
+ */
138
+ function noTokenAvailable(advice) {
139
+ return new LocationServiceException_js_1.LocationServiceException({
140
+ code: 'InvalidCredentialsException',
141
+ message: `No token available — ${advice}`,
142
+ details: { source: 'client' },
143
+ });
144
+ }
@@ -1,11 +1,38 @@
1
1
  /** Per-attempt timeout. Sits well under the API's own 25 s Lambda ceiling. */
2
2
  export declare const DEFAULT_TIMEOUT_MS = 10000;
3
+ /**
4
+ * Ceiling for the WHOLE call — every attempt plus every wait between them.
5
+ *
6
+ * `timeoutMs` bounds an attempt, not a call, and the gap between those two is
7
+ * where the caller's own deadline disappears. The API answers a spent quota
8
+ * with `Retry-After: 60`, which the retry loop honoured literally: two waits of
9
+ * a minute each, so one call could sit for ~120 s — past any Lambda budget,
10
+ * past any HTTP gateway, and until now uncancellable (#37).
11
+ *
12
+ * 30 s is picked to sit just under the old worst case: three default attempts
13
+ * that all time out, plus their backoff, came to ~30.75 s. The overlap is not
14
+ * quite nothing — when both earlier attempts burn their full 10 s, the third is
15
+ * clamped to the ~9.25 s that remain, so a response arriving in its final
16
+ * ~0.75 s used to succeed and now times out. That window is why this ships in a
17
+ * MINOR rather than a patch. What it buys is that no call can be made to sit
18
+ * out a retry hint longer than the caller has.
19
+ */
20
+ export declare const DEFAULT_OVERALL_TIMEOUT_MS = 30000;
3
21
  export declare const DEFAULT_MAX_ATTEMPTS = 3;
4
22
  export interface RequestOptions {
5
23
  /** Caller cancellation. Aborting rejects with code `AbortedException`. */
6
24
  signal?: AbortSignal;
7
25
  /** Per ATTEMPT, not for the whole call. Default 10 s. */
8
26
  timeoutMs?: number;
27
+ /**
28
+ * The whole call — attempts and the waits between them. Default 30 s.
29
+ *
30
+ * No attempt is given more than what is left of it, and a retry that would
31
+ * have to wait longer than what is left is not made at all: the API's own
32
+ * error comes back instead, `retryAfterMs` intact, so the caller can decide
33
+ * whether to queue the work or drop it.
34
+ */
35
+ overallTimeoutMs?: number;
9
36
  /** `false` disables retries entirely. Default 3 attempts = 2 retries. */
10
37
  retry?: false | {
11
38
  maxAttempts?: number;
@@ -22,3 +49,12 @@ export declare function backoffMs(attempt: number, random?: () => number): numbe
22
49
  * `details.source = 'client'` so it is distinguishable from the API's own 504.
23
50
  */
24
51
  export declare function requestJson<T>(url: string, init: RequestInit, options?: RequestOptions): Promise<T>;
52
+ /**
53
+ * One request answered as a Blob — the static map path.
54
+ *
55
+ * Exists so the two map fetches are not the only calls in the package without
56
+ * a timeout, a retry or a signal: they used their own bare `fetch`, so a
57
+ * network fault there escaped as a raw `TypeError` while the identical fault on
58
+ * any other call arrived as `NetworkException` (#37).
59
+ */
60
+ export declare function requestBlob(url: string, init: RequestInit, options?: RequestOptions): Promise<Blob>;
@@ -3,15 +3,34 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_MAX_ATTEMPTS = exports.DEFAULT_TIMEOUT_MS = void 0;
6
+ exports.DEFAULT_MAX_ATTEMPTS = exports.DEFAULT_OVERALL_TIMEOUT_MS = exports.DEFAULT_TIMEOUT_MS = void 0;
7
7
  exports.backoffMs = backoffMs;
8
8
  exports.requestJson = requestJson;
9
+ exports.requestBlob = requestBlob;
9
10
  const debug_1 = __importDefault(require("debug"));
10
11
  const LocationServiceException_js_1 = require("../errors/LocationServiceException.js");
11
12
  const errors_js_1 = require("./errors.js");
12
13
  const log = (0, debug_1.default)('location-client:transport');
13
14
  /** Per-attempt timeout. Sits well under the API's own 25 s Lambda ceiling. */
14
15
  exports.DEFAULT_TIMEOUT_MS = 10000;
16
+ /**
17
+ * Ceiling for the WHOLE call — every attempt plus every wait between them.
18
+ *
19
+ * `timeoutMs` bounds an attempt, not a call, and the gap between those two is
20
+ * where the caller's own deadline disappears. The API answers a spent quota
21
+ * with `Retry-After: 60`, which the retry loop honoured literally: two waits of
22
+ * a minute each, so one call could sit for ~120 s — past any Lambda budget,
23
+ * past any HTTP gateway, and until now uncancellable (#37).
24
+ *
25
+ * 30 s is picked to sit just under the old worst case: three default attempts
26
+ * that all time out, plus their backoff, came to ~30.75 s. The overlap is not
27
+ * quite nothing — when both earlier attempts burn their full 10 s, the third is
28
+ * clamped to the ~9.25 s that remain, so a response arriving in its final
29
+ * ~0.75 s used to succeed and now times out. That window is why this ships in a
30
+ * MINOR rather than a patch. What it buys is that no call can be made to sit
31
+ * out a retry hint longer than the caller has.
32
+ */
33
+ exports.DEFAULT_OVERALL_TIMEOUT_MS = 30000;
15
34
  exports.DEFAULT_MAX_ATTEMPTS = 3;
16
35
  const BACKOFF_BASE_MS = 250;
17
36
  const BACKOFF_CAP_MS = 4000;
@@ -48,38 +67,86 @@ function backoffMs(attempt, random = Math.random) {
48
67
  const ceiling = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
49
68
  return Math.floor(random() * ceiling);
50
69
  }
51
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
52
70
  /**
53
- * One JSON request, with timeout, cancellation and retry.
71
+ * Sleep, unless the caller aborts first.
54
72
  *
55
- * Every failure leaves as a LocationServiceException — a fetch rejection
56
- * becomes `NetworkException` with the original as `cause`, an abort becomes
57
- * `AbortedException`, a timeout becomes `TimeoutException` with
58
- * `details.source = 'client'` so it is distinguishable from the API's own 504.
73
+ * The timer used to be uncancellable, so an `abort()` during backoff was
74
+ * ignored until it elapsed — up to a whole `Retry-After` — and the loop only
75
+ * noticed at the top of the next attempt (#37). Resolving early is all that is
76
+ * needed: the loop's own pre-attempt check is what raises `AbortedException`,
77
+ * so exactly one place decides what an abort means.
59
78
  */
60
- async function requestJson(url, init, options = {}) {
79
+ function sleep(ms, signal) {
80
+ if (ms <= 0 || signal?.aborted)
81
+ return Promise.resolve();
82
+ return new Promise((resolve) => {
83
+ const done = () => {
84
+ clearTimeout(timer);
85
+ signal?.removeEventListener('abort', done);
86
+ resolve();
87
+ };
88
+ const timer = setTimeout(done, ms);
89
+ signal?.addEventListener('abort', done, { once: true });
90
+ });
91
+ }
92
+ /**
93
+ * One request, with timeout, cancellation and retry.
94
+ *
95
+ * The body is read INSIDE the attempt loop deliberately: a truncated or
96
+ * malformed body is a failed attempt like any other and earns the same
97
+ * wrapping and the same retry as a dropped socket. Handing the `Response` back
98
+ * for the caller to read would move that outside the loop, where a bare
99
+ * `SyntaxError` escapes as itself.
100
+ */
101
+ async function request(url, init, options, read) {
61
102
  const timeoutMs = options.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS;
103
+ const overallTimeoutMs = options.overallTimeoutMs ?? exports.DEFAULT_OVERALL_TIMEOUT_MS;
62
104
  const maxAttempts = options.retry === false
63
105
  ? 1
64
106
  : (options.retry?.maxAttempts ?? exports.DEFAULT_MAX_ATTEMPTS);
107
+ // A request budget of zero attempts is a caller mistake, not a policy. It
108
+ // used to fall straight through the loop and raise `InternalException` for a
109
+ // request that was never made — an error about our own internals, for their
110
+ // typo (#37).
111
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
112
+ throw new LocationServiceException_js_1.LocationServiceException({
113
+ code: 'ValidationException',
114
+ message: `retry.maxAttempts must be a whole number of at least 1; received ${maxAttempts}`,
115
+ details: { source: 'client' },
116
+ });
117
+ }
118
+ const deadline = Date.now() + overallTimeoutMs;
65
119
  let lastError;
66
120
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
67
121
  // Checked before every attempt: a signal aborted during backoff must not fire one more.
68
122
  if (options.signal?.aborted)
69
123
  throw abortedException(options.signal);
70
- const { signal, cleanup } = attemptSignal(options.signal, timeoutMs);
124
+ const budget = deadline - Date.now();
125
+ if (budget <= 0)
126
+ throw lastError ?? overallTimeoutException(overallTimeoutMs);
127
+ // Never longer than what is left of the call, so the per-attempt timeout
128
+ // cannot overrun the budget it sits inside.
129
+ const { signal, cleanup } = attemptSignal(options.signal, Math.min(timeoutMs, budget));
71
130
  try {
72
131
  const response = await fetch(url, { ...init, signal });
73
132
  if (response.ok)
74
- return (await response.json());
133
+ return await read(response);
75
134
  const error = (0, errors_js_1.parseErrorResponse)(response.status, response.statusText, await response.text(), response.headers);
76
135
  lastError = error;
77
136
  if (!error.isRetryable || attempt === maxAttempts - 1)
78
137
  throw error;
79
- log('attempt %d failed (%s), retrying', attempt + 1, error.code);
80
- await sleep(error.retryAfterMs ??
138
+ const wait = error.retryAfterMs ??
81
139
  (0, errors_js_1.parseRetryAfter)(response.headers.get('retry-after')) ??
82
- backoffMs(attempt));
140
+ backoffMs(attempt);
141
+ // Sitting out a 60 s `Retry-After` inside a 30 s budget only delivers the
142
+ // same failure after the caller has already given up. Stop now and hand
143
+ // back what the API said, `retryAfterMs` and all.
144
+ if (wait >= deadline - Date.now()) {
145
+ log('not retrying: a %d ms wait outlasts the remaining budget', wait);
146
+ break;
147
+ }
148
+ log('attempt %d failed (%s), retrying', attempt + 1, error.code);
149
+ await sleep(wait, options.signal);
83
150
  }
84
151
  catch (err) {
85
152
  if (err instanceof LocationServiceException_js_1.LocationServiceException) {
@@ -93,20 +160,48 @@ async function requestJson(url, init, options = {}) {
93
160
  lastError = wrapped;
94
161
  if (!wrapped.isRetryable || attempt === maxAttempts - 1)
95
162
  throw wrapped;
163
+ const wait = backoffMs(attempt);
164
+ if (wait >= deadline - Date.now()) {
165
+ log('not retrying: a %d ms wait outlasts the remaining budget', wait);
166
+ break;
167
+ }
96
168
  log('attempt %d failed (%s), retrying', attempt + 1, wrapped.code);
97
- await sleep(backoffMs(attempt));
169
+ await sleep(wait, options.signal);
98
170
  }
99
171
  finally {
100
172
  cleanup();
101
173
  }
102
174
  }
103
- /* c8 ignore next */
175
+ // Reached when the budget ran out before another attempt could be made, so
176
+ // `lastError` is the API's own answer and is the useful thing to throw.
104
177
  throw (lastError ??
105
178
  new LocationServiceException_js_1.LocationServiceException({
106
179
  code: 'InternalException',
107
180
  message: 'Request failed',
108
181
  }));
109
182
  }
183
+ /**
184
+ * One JSON request, with timeout, cancellation and retry.
185
+ *
186
+ * Every failure leaves as a LocationServiceException — a fetch rejection
187
+ * becomes `NetworkException` with the original as `cause`, an abort becomes
188
+ * `AbortedException`, a timeout becomes `TimeoutException` with
189
+ * `details.source = 'client'` so it is distinguishable from the API's own 504.
190
+ */
191
+ function requestJson(url, init, options = {}) {
192
+ return request(url, init, options, (response) => response.json());
193
+ }
194
+ /**
195
+ * One request answered as a Blob — the static map path.
196
+ *
197
+ * Exists so the two map fetches are not the only calls in the package without
198
+ * a timeout, a retry or a signal: they used their own bare `fetch`, so a
199
+ * network fault there escaped as a raw `TypeError` while the identical fault on
200
+ * any other call arrived as `NetworkException` (#37).
201
+ */
202
+ function requestBlob(url, init, options = {}) {
203
+ return request(url, init, options, (response) => response.blob());
204
+ }
110
205
  function abortedException(signal) {
111
206
  return new LocationServiceException_js_1.LocationServiceException({
112
207
  code: 'AbortedException',
@@ -115,6 +210,14 @@ function abortedException(signal) {
115
210
  cause: signal?.reason,
116
211
  });
117
212
  }
213
+ /** The call's own budget elapsed, rather than one attempt's timeout. */
214
+ function overallTimeoutException(overallTimeoutMs) {
215
+ return new LocationServiceException_js_1.LocationServiceException({
216
+ code: 'TimeoutException',
217
+ message: `Request exceeded its overall timeout of ${overallTimeoutMs} ms`,
218
+ details: { source: 'client' },
219
+ });
220
+ }
118
221
  /**
119
222
  * fetch rejects with a raw `TypeError` for a network fault and a `DOMException`
120
223
  * named AbortError for both cancellation and timeout — indistinguishable from
@@ -1,9 +1,45 @@
1
+ /**
2
+ * At least one of `token`, `getToken` or `refreshToken` must supply a token, or
3
+ * `send` refuses locally with `InvalidCredentialsException` rather than putting
4
+ * `Bearer undefined` on the wire (#37).
5
+ *
6
+ * `token` is optional because a client driven purely by a provider — the shape
7
+ * `@chaosity/location-client-react` uses — has nothing to put there at
8
+ * construction time, and was previously forced to invent a placeholder. It is
9
+ * still required on `ServerClientConfig`, which is a RESULT rather than a
10
+ * configuration: `getClientConfig` always resolves one.
11
+ */
1
12
  export interface ClientConfig {
2
13
  apiUrl: string;
3
- token: string;
14
+ token?: string;
4
15
  /** Optional callback to get the current token dynamically. When provided,
5
16
  * called on every request so token updates are reflected without recreating the client. */
6
17
  getToken?: () => string | undefined;
18
+ /**
19
+ * Asked for a replacement AFTER the API has rejected the current token with a
20
+ * 401, so the request can be retried once instead of failing — and, since
21
+ * #37, asked once BEFORE the first send when neither `getToken` nor `token`
22
+ * yields anything, so a client whose token has not arrived yet does not spend
23
+ * a round trip on `Bearer undefined` to learn that. Both calls mean the same
24
+ * thing to an implementor — "give me a usable token" — so a `refreshToken`
25
+ * that mints or awaits one needs no change; only one that assumes every
26
+ * invocation follows a 401 does.
27
+ *
28
+ * Separate from `getToken` because that one is synchronous by contract — it
29
+ * is read while a request is being built and cannot await anything, so it can
30
+ * only ever return the token already in hand. Nothing in this library could
31
+ * therefore recover from a token revoked, or a secret rotated, before its
32
+ * `exp`: every request failed until the refresh buffer elapsed on its own
33
+ * (#36).
34
+ *
35
+ * Returning `undefined` is not "no replacement": the client then re-reads
36
+ * `getToken`, because a provider refreshing in the background may have landed
37
+ * a new token while the failed request was in flight. What actually decides
38
+ * is the token that comes out of those two — if it is the one just rejected,
39
+ * or there is none, the retry is skipped rather than repeating a request that
40
+ * is going to fail again.
41
+ */
42
+ refreshToken?: () => Promise<string | undefined>;
7
43
  }
8
44
  /**
9
45
  * Minimal interface for AWS SDK command objects.
@@ -31,9 +31,20 @@ export declare class GeoPlacesClient {
31
31
  * case until one is configured in the portal.
32
32
  */
33
33
  getAppConfig(): AppConfigClaims;
34
+ /** Prefer the getToken callback (live ref) over a static token string. */
35
+ private currentToken;
34
36
  /**
35
- * @param options `signal` to cancel, `timeoutMs` per attempt, `retry: false`
36
- * to disable the retry loop. Every failure throws LocationServiceException.
37
+ * A token to send, or a refusal — never `undefined`.
38
+ *
39
+ * `refreshToken` is asked only when there is nothing at all in hand, so a
40
+ * client configured the ordinary way pays nothing for this.
41
+ */
42
+ private ensureToken;
43
+ /**
44
+ * @param options `signal` to cancel, `timeoutMs` per attempt,
45
+ * `overallTimeoutMs` for the whole call, `retry: false` to disable the
46
+ * retry loop. Every failure throws LocationServiceException.
37
47
  */
38
48
  send<TInput, TOutput>(command: TInput, options?: SendOptions): Promise<TOutput>;
49
+ private dispatch;
39
50
  }
@@ -1,5 +1,6 @@
1
1
  import debug from 'debug';
2
2
  import { resolveEndpoint } from '../transport/endpoints.js';
3
+ import { isTokenRejected, noTokenAvailable } from '../transport/errors.js';
3
4
  import { requestJson } from '../transport/http.js';
4
5
  import { roundPositionFields } from '../utils/roundPosition.js';
5
6
  import { readAppConfigClaims } from '../utils/tokenClaims.js';
@@ -32,24 +33,73 @@ export class GeoPlacesClient {
32
33
  * case until one is configured in the portal.
33
34
  */
34
35
  getAppConfig() {
35
- const token = this.clientConfig.getToken?.() ?? this.clientConfig.token;
36
- return readAppConfigClaims(token);
36
+ return readAppConfigClaims(this.currentToken());
37
+ }
38
+ /** Prefer the getToken callback (live ref) over a static token string. */
39
+ currentToken() {
40
+ return this.clientConfig.getToken?.() ?? this.clientConfig.token;
41
+ }
42
+ /**
43
+ * A token to send, or a refusal — never `undefined`.
44
+ *
45
+ * `refreshToken` is asked only when there is nothing at all in hand, so a
46
+ * client configured the ordinary way pays nothing for this.
47
+ */
48
+ async ensureToken() {
49
+ // `||`, not `??`: an empty string is a token source with nothing to give,
50
+ // not a decision to send an empty one. With `??` it survived the coalesce,
51
+ // skipped `refreshToken`, and then failed the check two lines below — so
52
+ // `getToken: () => undefined` got the refresh ask and `getToken: () => ''`
53
+ // did not, which is a distinction no caller means to draw.
54
+ const token = this.currentToken() || (await this.clientConfig.refreshToken?.());
55
+ if (!token) {
56
+ throw noTokenAvailable('the client has no token yet. Pass `token`, or a `getToken`/`refreshToken` that has one.');
57
+ }
58
+ return token;
37
59
  }
38
60
  /**
39
- * @param options `signal` to cancel, `timeoutMs` per attempt, `retry: false`
40
- * to disable the retry loop. Every failure throws LocationServiceException.
61
+ * @param options `signal` to cancel, `timeoutMs` per attempt,
62
+ * `overallTimeoutMs` for the whole call, `retry: false` to disable the
63
+ * retry loop. Every failure throws LocationServiceException.
41
64
  */
42
65
  async send(command, options) {
43
66
  const cmd = command;
44
- const endpoint = resolveEndpoint(cmd);
45
- // Prefer the getToken callback (live ref) over a static token string.
46
- const token = this.clientConfig.getToken?.() ?? this.clientConfig.token;
67
+ const url = `${this.clientConfig.apiUrl}${resolveEndpoint(cmd)}`;
68
+ // The fifth and last place in this package that turns a token into an
69
+ // `Authorization` header, and the last one that would send `Bearer
70
+ // undefined` (#37). The 401 self-heal below cannot cover this case — it
71
+ // needs a request to have been rejected first — so a client whose token
72
+ // source has not produced one yet spent a whole round trip to learn
73
+ // something it already knew. Ask the refresh source instead, and refuse if
74
+ // there is still nothing.
75
+ const token = await this.ensureToken();
76
+ try {
77
+ return await this.dispatch(url, token, cmd, options);
78
+ }
79
+ catch (err) {
80
+ if (!isTokenRejected(err))
81
+ throw err;
82
+ // One shot. `refreshToken` is the only way to actually obtain a new
83
+ // token here — `getToken` is synchronous and returns the one already in
84
+ // hand — but it is re-read as a fallback because a provider that
85
+ // refreshes in the background may have landed a new one while this
86
+ // request was in flight.
87
+ const fresh = (await this.clientConfig.refreshToken?.()) ?? this.currentToken();
88
+ // Nothing new to send. Repeating the request would fail identically — a
89
+ // second round trip for the same 401.
90
+ if (!fresh || fresh === token)
91
+ throw err;
92
+ log('401 — retrying %s once with a refreshed token', cmd.constructor?.name);
93
+ return await this.dispatch(url, fresh, cmd, options);
94
+ }
95
+ }
96
+ dispatch(url, token, cmd, options) {
47
97
  // Resolve the token BEFORE rounding: the precision this application is
48
98
  // entitled to is a claim on it (api#65). Absent claim -> the 3 dp floor.
49
99
  const { biasDecimals } = readAppConfigClaims(token);
50
100
  const input = roundPositionFields(cmd.input, biasDecimals);
51
- log('Sending %s to %s', cmd.constructor?.name, endpoint);
52
- return requestJson(`${this.clientConfig.apiUrl}${endpoint}`, {
101
+ log('Sending %s to %s', cmd.constructor?.name, url);
102
+ return requestJson(url, {
53
103
  method: 'POST',
54
104
  headers: {
55
105
  'Content-Type': 'application/json',
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { GeoPlacesClient } from './client/GeoPlacesClient.js';
2
2
  export type { SendOptions } from './client/GeoPlacesClient.js';
3
- export { DEFAULT_MAX_ATTEMPTS, DEFAULT_TIMEOUT_MS } from './transport/http.js';
3
+ export { DEFAULT_MAX_ATTEMPTS, DEFAULT_OVERALL_TIMEOUT_MS, DEFAULT_TIMEOUT_MS, } from './transport/http.js';
4
4
  export type { RequestOptions } from './transport/http.js';
5
5
  export { TOKEN_REFRESH_BUFFER_SECONDS, readTokenExpiry, } from './auth/tokenRefresh.js';
6
6
  export { LocationServiceException } from './errors/LocationServiceException.js';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Client (Custom - uses our auth instead of AWS SigV4)
2
2
  export { GeoPlacesClient } from './client/GeoPlacesClient.js';
3
- // Transport options — cancellation, per-attempt timeout, retry policy
4
- export { DEFAULT_MAX_ATTEMPTS, DEFAULT_TIMEOUT_MS } from './transport/http.js';
3
+ // Transport options — cancellation, per-attempt timeout, overall budget, retry
4
+ export { DEFAULT_MAX_ATTEMPTS, DEFAULT_OVERALL_TIMEOUT_MS, DEFAULT_TIMEOUT_MS, } from './transport/http.js';
5
5
  // Token refresh policy — shared by the server provider and the React provider
6
6
  export { TOKEN_REFRESH_BUFFER_SECONDS, readTokenExpiry, } from './auth/tokenRefresh.js';
7
7
  // Errors
@@ -3,6 +3,8 @@ import type { RequestTransformFunction } from 'maplibre-gl';
3
3
  * Creates a transformRequest function for MapLibre that adds authentication
4
4
  * and proper Accept headers for AWS Location Service API requests.
5
5
  *
6
+ * The token is attached to our own API and nowhere else — see isOurApi.
7
+ *
6
8
  * @param apiUrl - Base URL of the Location Service API
7
9
  * @param getToken - Callback function that returns the current auth token
8
10
  * @returns MapLibre transformRequest function
@@ -1,14 +1,58 @@
1
+ /**
2
+ * Does this URL belong to our API?
3
+ *
4
+ * This decides who receives the customer's bearer token, and it used to be
5
+ * `url.startsWith(apiUrl)` — a string test standing in for a URL test. For
6
+ * `apiUrl = "https://api.example.com"`, the host `api.example.com.evil.test`
7
+ * is a prefix match, so a style referencing
8
+ * `https://api.example.com.evil.test/tiles/1/2/3` was handed
9
+ * `Authorization: Bearer <token>` and the token left the building (#34).
10
+ *
11
+ * That is reachable because a style descriptor is DATA: its `sprite`, `glyphs`
12
+ * and `sources` entries are URLs the style author chose, and MapLibre asks
13
+ * transformRequest about every one of them. Any style not wholly ours — a
14
+ * customer's own, or one edited through a tool — can name a host it likes.
15
+ *
16
+ * Compared as URLs instead, which also gets host case-folding, default ports
17
+ * (`https://api.test:443` === `https://api.test`) and userinfo right for free,
18
+ * and adds a path check so a shared host serving another tenant under a
19
+ * different base path is not "ours" either.
20
+ *
21
+ * Fails CLOSED: anything that will not parse gets no token. The only way to
22
+ * reach that is a relative `apiUrl` in a runtime with no `location` to resolve
23
+ * it against — i.e. not a browser, which is the only place MapLibre runs.
24
+ */
25
+ function isOurApi(url, apiUrl) {
26
+ const base = typeof location === 'undefined' ? undefined : location.href;
27
+ let ours;
28
+ let theirs;
29
+ try {
30
+ ours = new URL(apiUrl, base);
31
+ theirs = new URL(url, base);
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ if (theirs.origin !== ours.origin)
37
+ return false;
38
+ // Trailing slashes normalised so `/v1` and `/v1/` behave the same; the `/`
39
+ // boundary is what stops `/v1` from matching `/v1-internal`.
40
+ const basePath = ours.pathname.replace(/\/+$/, '');
41
+ return (theirs.pathname === basePath || theirs.pathname.startsWith(`${basePath}/`));
42
+ }
1
43
  /**
2
44
  * Creates a transformRequest function for MapLibre that adds authentication
3
45
  * and proper Accept headers for AWS Location Service API requests.
4
46
  *
47
+ * The token is attached to our own API and nowhere else — see isOurApi.
48
+ *
5
49
  * @param apiUrl - Base URL of the Location Service API
6
50
  * @param getToken - Callback function that returns the current auth token
7
51
  * @returns MapLibre transformRequest function
8
52
  */
9
53
  export function createTransformRequest(apiUrl, getToken) {
10
54
  return (url, _resourceType) => {
11
- if (url.startsWith(apiUrl)) {
55
+ if (isOurApi(url, apiUrl)) {
12
56
  const token = getToken();
13
57
  if (!token) {
14
58
  console.warn('[createTransformRequest] No token available');
@@ -1,4 +1,5 @@
1
1
  import type { StyleSpecification } from 'maplibre-gl';
2
+ import type { RequestOptions } from '../transport/http.js';
2
3
  import type { Buildings, ColorScheme, ContourDensity, MapStyle, Terrain, TrafficMode, TravelMode } from './mapEnums.js';
3
4
  /**
4
5
  * Options for building an AWS Location Service map style URL.
@@ -66,6 +67,7 @@ export declare function buildMapStyleUrl(apiUrl: string, mapStyle: MapStyle, opt
66
67
  * @param mapStyle - Map style name (e.g. 'Standard', 'Monochrome', 'Satellite', 'Hybrid')
67
68
  * @param getToken - Callback returning the current auth token
68
69
  * @param options - Style options; `language` is applied to the descriptor, all others become URL params
70
+ * @param request - Transport options: `signal` to cancel, `timeoutMs`, `overallTimeoutMs`, `retry`
69
71
  * @returns Modified MapLibre StyleSpecification object
70
72
  *
71
73
  * @example
@@ -74,4 +76,4 @@ export declare function buildMapStyleUrl(apiUrl: string, mapStyle: MapStyle, opt
74
76
  */
75
77
  export declare function fetchMapStyle(apiUrl: string, mapStyle: MapStyle, getToken: () => string | undefined, options?: MapStyleOptions & {
76
78
  language?: string;
77
- }): Promise<StyleSpecification>;
79
+ }, request?: RequestOptions): Promise<StyleSpecification>;