google-maps-fetch 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,246 @@
1
+ // src/http.ts
2
+ var MapsError = class extends Error {
3
+ constructor(message, status, code, body) {
4
+ super(message);
5
+ this.status = status;
6
+ this.code = code;
7
+ this.body = body;
8
+ this.name = "MapsError";
9
+ }
10
+ /** Same shape as an axios error's response, for code written against axios-based clients */
11
+ get response() {
12
+ return this.status ? { status: this.status, data: this.body } : void 0;
13
+ }
14
+ };
15
+ var retryable = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
16
+ var httpCodes = {
17
+ 400: "INVALID_ARGUMENT",
18
+ 401: "UNAUTHENTICATED",
19
+ 403: "PERMISSION_DENIED",
20
+ 404: "NOT_FOUND",
21
+ 429: "RESOURCE_EXHAUSTED",
22
+ 500: "INTERNAL",
23
+ 503: "UNAVAILABLE",
24
+ 504: "DEADLINE_EXCEEDED"
25
+ };
26
+ var fieldMask = (fields) => Array.isArray(fields) ? fields.join(",") : fields;
27
+ var withQuery = (url, query = {}) => {
28
+ const params = new URLSearchParams();
29
+ for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, String(v));
30
+ const qs = params.toString();
31
+ return qs ? `${url}?${qs}` : url;
32
+ };
33
+ var parse = (text) => {
34
+ try {
35
+ return JSON.parse(text);
36
+ } catch {
37
+ return text;
38
+ }
39
+ };
40
+ var wait = (ms, signal) => new Promise((resolve, reject) => {
41
+ if (signal?.aborted) return reject(signal.reason);
42
+ const onAbort = () => {
43
+ clearTimeout(timer);
44
+ reject(signal?.reason);
45
+ };
46
+ const timer = setTimeout(() => {
47
+ signal?.removeEventListener("abort", onAbort);
48
+ resolve();
49
+ }, ms);
50
+ signal?.addEventListener("abort", onAbort, { once: true });
51
+ });
52
+ var backoff = (attempt) => 250 * 2 ** attempt + Math.random() * 100;
53
+ var maxRetryAfter = 3e4;
54
+ var retryAfter = (value) => {
55
+ if (!value) return void 0;
56
+ const s = Number(value);
57
+ if (!Number.isNaN(s)) return Math.max(0, s * 1e3);
58
+ const date = Date.parse(value);
59
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
60
+ };
61
+ function createTransport({ key, fetch: f = globalThis.fetch, timeout = 1e4, retries = 2, headers = {} }) {
62
+ if (!key) throw new Error("google-maps-fetch: an API key is required");
63
+ if (typeof f !== "function") throw new Error("google-maps-fetch: no fetch available; pass one with the fetch option");
64
+ return async function send(request, call = {}) {
65
+ const { method, body, fields, keyIn = "header" } = request;
66
+ const url = withQuery(request.url, keyIn === "query" ? { ...request.query, key } : request.query);
67
+ const requestHeaders = { ...headers };
68
+ if (keyIn === "header") requestHeaders["X-Goog-Api-Key"] = key;
69
+ if (fields !== void 0) requestHeaders["X-Goog-FieldMask"] = fieldMask(fields);
70
+ if (body !== void 0) requestHeaders["Content-Type"] = "application/json";
71
+ const ms = call.timeout ?? timeout;
72
+ for (let attempt = 0; ; attempt++) {
73
+ if (call.signal?.aborted) throw call.signal.reason;
74
+ const controller = new AbortController();
75
+ let timedOut = false;
76
+ const timer = ms > 0 ? setTimeout(() => {
77
+ timedOut = true;
78
+ controller.abort();
79
+ }, ms) : void 0;
80
+ const onAbort = () => controller.abort();
81
+ call.signal?.addEventListener("abort", onAbort, { once: true });
82
+ let error;
83
+ let delay;
84
+ try {
85
+ const res = await f(url, {
86
+ method,
87
+ headers: requestHeaders,
88
+ body: body === void 0 ? void 0 : JSON.stringify(body),
89
+ signal: controller.signal
90
+ });
91
+ const text = await res.text();
92
+ const data = text ? parse(text) : void 0;
93
+ if (res.ok) return data;
94
+ const payload = Array.isArray(data) ? data[0] : data;
95
+ const e = payload?.error;
96
+ error = new MapsError(
97
+ e?.message ?? payload?.error_message ?? `HTTP ${res.status}`,
98
+ res.status,
99
+ e?.status ?? payload?.status ?? httpCodes[res.status] ?? "UNKNOWN",
100
+ data
101
+ );
102
+ if (!retryable.has(res.status)) throw error;
103
+ delay = retryAfter(res.headers.get("retry-after"));
104
+ if (delay !== void 0 && delay > maxRetryAfter) throw error;
105
+ } catch (e) {
106
+ if (e instanceof MapsError) throw e;
107
+ if (call.signal?.aborted) throw call.signal.reason;
108
+ error = timedOut ? new MapsError(`google-maps-fetch: no response within ${ms}ms`, 0, "TIMEOUT") : new MapsError(`google-maps-fetch: ${e?.message ?? "network error"}`, 0, "NETWORK_ERROR", e);
109
+ } finally {
110
+ clearTimeout(timer);
111
+ call.signal?.removeEventListener("abort", onAbort);
112
+ }
113
+ if (attempt >= retries) throw error;
114
+ await wait(delay ?? backoff(attempt), call.signal);
115
+ }
116
+ };
117
+ }
118
+
119
+ // src/util.ts
120
+ var toLatLng = (value) => {
121
+ if (Array.isArray(value)) return { latitude: value[0], longitude: value[1] };
122
+ if ("lat" in value) return { latitude: value.lat, longitude: value.lng };
123
+ return { latitude: value.latitude, longitude: value.longitude };
124
+ };
125
+ var isWaypoint = (value) => "location" in value || "placeId" in value || "address" in value;
126
+ var toWaypoint = (value) => {
127
+ if (typeof value === "string") return { address: value };
128
+ if (!Array.isArray(value) && isWaypoint(value)) return value;
129
+ return { location: { latLng: toLatLng(value) } };
130
+ };
131
+ var seconds = (duration) => duration === void 0 ? void 0 : parseFloat(duration);
132
+ var newSessionToken = () => globalThis.crypto.randomUUID();
133
+
134
+ // src/places.ts
135
+ var base = "https://places.googleapis.com/v1";
136
+ var placeFields = ["id", "formattedAddress", "location"];
137
+ var searchTextFields = ["places.id", "places.displayName", "places.formattedAddress", "places.location", "nextPageToken"];
138
+ var searchNearbyFields = ["places.id", "places.displayName", "places.formattedAddress", "places.location", "places.types"];
139
+ var placePath = (id) => id.startsWith("places/") ? id : `places/${encodeURIComponent(id)}`;
140
+ function createPlaces(send) {
141
+ const autocomplete = ({ ...request }, { fields, ...call } = {}) => send({ method: "POST", url: `${base}/places:autocomplete`, body: request, fields }, call);
142
+ const get = (id, { fields = placeFields, languageCode, regionCode, sessionToken, ...call } = {}) => send({ method: "GET", url: `${base}/${placePath(id)}`, query: { languageCode, regionCode, sessionToken }, fields }, call);
143
+ const searchText = (request, { fields = searchTextFields, ...call } = {}) => send({ method: "POST", url: `${base}/places:searchText`, body: request, fields }, call);
144
+ const searchNearby = (request, { fields = searchNearbyFields, ...call } = {}) => send({ method: "POST", url: `${base}/places:searchNearby`, body: request, fields }, call);
145
+ const photo = (name, { maxWidthPx, maxHeightPx, ...call } = {}) => send(
146
+ {
147
+ method: "GET",
148
+ url: `${base}/${name}/media`,
149
+ // Google needs at least one size
150
+ query: { maxWidthPx: maxWidthPx ?? (maxHeightPx ? void 0 : 800), maxHeightPx, skipHttpRedirect: true }
151
+ },
152
+ call
153
+ );
154
+ const session = () => {
155
+ let token = newSessionToken();
156
+ return {
157
+ get token() {
158
+ return token;
159
+ },
160
+ autocomplete: (request, options) => autocomplete({ ...request, sessionToken: token }, options),
161
+ get: async (id, options) => {
162
+ try {
163
+ return await get(id, { ...options, sessionToken: token });
164
+ } finally {
165
+ token = newSessionToken();
166
+ }
167
+ }
168
+ };
169
+ };
170
+ return { autocomplete, get, searchText, searchNearby, photo, session };
171
+ }
172
+
173
+ // src/routes.ts
174
+ var routeFields = [
175
+ "routes.distanceMeters",
176
+ "routes.duration",
177
+ "routes.staticDuration",
178
+ "routes.polyline.encodedPolyline",
179
+ "routes.localizedValues"
180
+ ];
181
+ var matrixFields = [
182
+ "originIndex",
183
+ "destinationIndex",
184
+ "status",
185
+ "condition",
186
+ "distanceMeters",
187
+ "duration",
188
+ "staticDuration",
189
+ "localizedValues"
190
+ ];
191
+ var isMatrixEntry = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && "waypoint" in value;
192
+ var toOrigin = (value) => isMatrixEntry(value) ? value : { waypoint: toWaypoint(value) };
193
+ var toDestination = (value) => isMatrixEntry(value) ? value : { waypoint: toWaypoint(value) };
194
+ var has = (fields, field) => {
195
+ const list = (Array.isArray(fields) ? fields : fields.split(",")).map((f) => f.trim());
196
+ return list.includes("*") || list.includes(field);
197
+ };
198
+ function createRoutes(send) {
199
+ const compute = ({ origin, destination, intermediates, ...rest }, { fields = routeFields, ...call } = {}) => send(
200
+ {
201
+ method: "POST",
202
+ url: "https://routes.googleapis.com/directions/v2:computeRoutes",
203
+ body: {
204
+ ...rest,
205
+ origin: toWaypoint(origin),
206
+ destination: toWaypoint(destination),
207
+ ...intermediates ? { intermediates: intermediates.map(toWaypoint) } : {}
208
+ },
209
+ fields
210
+ },
211
+ call
212
+ );
213
+ const matrix = async ({ origins, destinations, ...rest }, { fields = matrixFields, ...call } = {}) => {
214
+ const elements = await send(
215
+ {
216
+ method: "POST",
217
+ url: "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix",
218
+ body: { ...rest, origins: origins.map(toOrigin), destinations: destinations.map(toDestination) },
219
+ fields
220
+ },
221
+ call
222
+ );
223
+ return (elements ?? []).map((e) => ({
224
+ ...e,
225
+ ...has(fields, "originIndex") ? { originIndex: e.originIndex ?? 0 } : {},
226
+ ...has(fields, "destinationIndex") ? { destinationIndex: e.destinationIndex ?? 0 } : {}
227
+ }));
228
+ };
229
+ return { compute, matrix };
230
+ }
231
+
232
+ export {
233
+ MapsError,
234
+ createTransport,
235
+ toLatLng,
236
+ toWaypoint,
237
+ seconds,
238
+ newSessionToken,
239
+ placeFields,
240
+ searchTextFields,
241
+ searchNearbyFields,
242
+ createPlaces,
243
+ routeFields,
244
+ matrixFields,
245
+ createRoutes
246
+ };