google-maps-fetch 0.0.0-stage → 0.1.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.
package/dist/compat.js ADDED
@@ -0,0 +1,1215 @@
1
+ import {
2
+ MapsError,
3
+ createPlaces,
4
+ createRoutes,
5
+ createTransport,
6
+ seconds
7
+ } from "./chunk-KSK2WERM.js";
8
+
9
+ // src/legacy/params.ts
10
+ var pair = /^\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*$/;
11
+ var parseLatLng = (value) => {
12
+ const m = pair.exec(value);
13
+ return m ? { latitude: Number(m[1]), longitude: Number(m[2]) } : void 0;
14
+ };
15
+ var toLatLng = (value) => {
16
+ if (typeof value === "string") {
17
+ const parsed = parseLatLng(value);
18
+ if (!parsed) throw new Error(`google-maps-fetch/compat: expected "lat,lng" but got "${value}"`);
19
+ return parsed;
20
+ }
21
+ if (Array.isArray(value)) return { latitude: value[0], longitude: value[1] };
22
+ if ("lat" in value) return { latitude: value.lat, longitude: value.lng };
23
+ return { latitude: value.latitude, longitude: value.longitude };
24
+ };
25
+ var toLiteral = (value) => ({ lat: value?.latitude ?? 0, lng: value?.longitude ?? 0 });
26
+ var latLngString = (value) => {
27
+ if (typeof value === "string") return value;
28
+ const { latitude, longitude } = toLatLng(value);
29
+ return `${latitude},${longitude}`;
30
+ };
31
+ var toWaypoint = (value) => {
32
+ if (typeof value !== "string") return { location: { latLng: toLatLng(value) } };
33
+ const via = value.startsWith("via:");
34
+ const v = via ? value.slice(4) : value;
35
+ if (v.startsWith("enc:")) throw new Error('google-maps-fetch/compat: encoded-polyline waypoints ("enc:...") are not supported');
36
+ const coords = parseLatLng(v);
37
+ const point = v.startsWith("place_id:") ? { placeId: v.slice(9) } : coords ? { location: { latLng: coords } } : { address: v };
38
+ return via ? { ...point, via: true } : point;
39
+ };
40
+ var addressOf = (value) => {
41
+ if (value === void 0) return "";
42
+ if (typeof value !== "string") return latLngString(value);
43
+ const v = value.startsWith("via:") ? value.slice(4) : value;
44
+ return v.startsWith("place_id:") ? "" : v;
45
+ };
46
+ var metresPerDegree = 111320;
47
+ var circleToRectangle = (center, radius) => {
48
+ const dLat = radius / metresPerDegree;
49
+ const dLng = radius / (metresPerDegree * Math.max(Math.cos(center.latitude * Math.PI / 180), 0.01));
50
+ return {
51
+ rectangle: {
52
+ low: { latitude: Math.max(center.latitude - dLat, -90), longitude: Math.max(center.longitude - dLng, -180) },
53
+ high: { latitude: Math.min(center.latitude + dLat, 90), longitude: Math.min(center.longitude + dLng, 180) }
54
+ }
55
+ };
56
+ };
57
+ var parseLocationBias = (value) => {
58
+ if (!value || value === "ipbias") return void 0;
59
+ const [kind, rest = ""] = value.split(/:(.*)/s);
60
+ if (kind === "point") return { circle: { center: toLatLng(rest), radius: 0 } };
61
+ if (kind === "circle") {
62
+ const [radius, center] = rest.split("@");
63
+ return { circle: { center: toLatLng(center), radius: Number(radius) } };
64
+ }
65
+ if (kind === "rectangle") {
66
+ const [low, high] = rest.split("|");
67
+ return { rectangle: { low: toLatLng(low), high: toLatLng(high) } };
68
+ }
69
+ throw new Error(`google-maps-fetch/compat: unrecognised locationbias "${value}"`);
70
+ };
71
+ var isLatLngObject = (v) => "lat" in v && "lng" in v || "latitude" in v && "longitude" in v;
72
+ var serializeValue = (value) => {
73
+ if (value === void 0 || value === null) return void 0;
74
+ if (value instanceof Date) return String(Math.round(value.getTime() / 1e3));
75
+ if (Array.isArray(value)) {
76
+ if (value.length === 2 && value.every((n) => typeof n === "number")) return value.join(",");
77
+ return value.map(serializeValue).join("|");
78
+ }
79
+ if (typeof value === "object") {
80
+ if (isLatLngObject(value)) return latLngString(value);
81
+ if ("northeast" in value && "southwest" in value) {
82
+ const { northeast, southwest } = value;
83
+ return `${latLngString(southwest)}|${latLngString(northeast)}`;
84
+ }
85
+ return Object.entries(value).map(([k, v]) => `${k}:${v}`).join("|");
86
+ }
87
+ return String(value);
88
+ };
89
+ var serializeParams = (params) => {
90
+ const out = {};
91
+ for (const [k, v] of Object.entries(params)) {
92
+ const s = serializeValue(v);
93
+ if (s !== void 0) out[k] = s;
94
+ }
95
+ return out;
96
+ };
97
+ var priceLevels = [
98
+ "PRICE_LEVEL_FREE",
99
+ "PRICE_LEVEL_INEXPENSIVE",
100
+ "PRICE_LEVEL_MODERATE",
101
+ "PRICE_LEVEL_EXPENSIVE",
102
+ "PRICE_LEVEL_VERY_EXPENSIVE"
103
+ ];
104
+ var priceRange = (min, max) => {
105
+ if (min == null && max == null) return void 0;
106
+ const levels = priceLevels.slice(Math.max(min ?? 0, 1), (max ?? 4) + 1);
107
+ return levels.length ? levels : void 0;
108
+ };
109
+ var priceLevelNumber = (level) => {
110
+ const i = level ? priceLevels.indexOf(level) : -1;
111
+ return i === -1 ? void 0 : i;
112
+ };
113
+ var strip = (o) => {
114
+ for (const k of Object.keys(o)) if (o[k] === void 0) delete o[k];
115
+ return o;
116
+ };
117
+
118
+ // src/legacy/places.ts
119
+ var addressTypes = ["street_address", "premise", "subpremise", "route"];
120
+ var primaryTypes = (types) => {
121
+ if (!types) return void 0;
122
+ const list = types.split("|");
123
+ if (list.some((t) => t === "geocode" || t === "establishment")) return void 0;
124
+ return [...new Set(list.flatMap((t) => t === "address" ? addressTypes : [t]))].slice(0, 5);
125
+ };
126
+ var regionCodes = (components) => {
127
+ if (!components) return void 0;
128
+ const list = (Array.isArray(components) ? components : components.split("|")).map((c) => /^country:(.+)$/.exec(c.trim())?.[1]).filter((c) => !!c);
129
+ return list.length ? list : void 0;
130
+ };
131
+ var autocompleteRequest = (p) => {
132
+ const circle = p.location ? { center: toLatLng(p.location), radius: p.radius ?? 0 } : void 0;
133
+ const restrict = p.strictbounds && circle && circle.radius > 0;
134
+ return strip({
135
+ input: p.input,
136
+ sessionToken: p.sessiontoken,
137
+ inputOffset: p.offset,
138
+ origin: p.origin ? toLatLng(p.origin) : void 0,
139
+ locationBias: circle && !restrict ? { circle } : void 0,
140
+ locationRestriction: circle && restrict ? { circle } : void 0,
141
+ languageCode: p.language,
142
+ regionCode: p.region,
143
+ includedPrimaryTypes: primaryTypes(p.types),
144
+ includedRegionCodes: regionCodes(p.components)
145
+ });
146
+ };
147
+ var substrings = (ranges) => (ranges ?? []).map((r) => ({ offset: r.startOffset ?? 0, length: r.endOffset - (r.startOffset ?? 0) }));
148
+ var terms = (description) => {
149
+ let offset = 0;
150
+ return description.split(", ").map((value) => {
151
+ const term = { offset, value };
152
+ offset += value.length + 2;
153
+ return term;
154
+ });
155
+ };
156
+ var toPrediction = (p) => {
157
+ const placeId = "placeId" in p ? p.placeId : "";
158
+ return strip({
159
+ description: p.text.text,
160
+ place_id: placeId,
161
+ reference: placeId,
162
+ types: "types" in p && p.types || [],
163
+ matched_substrings: substrings(p.text.matches),
164
+ structured_formatting: {
165
+ main_text: p.structuredFormat?.mainText.text ?? p.text.text,
166
+ main_text_matched_substrings: substrings(p.structuredFormat?.mainText.matches),
167
+ secondary_text: p.structuredFormat?.secondaryText?.text ?? "",
168
+ secondary_text_matched_substrings: substrings(p.structuredFormat?.secondaryText?.matches)
169
+ },
170
+ terms: terms(p.text.text),
171
+ distance_meters: "distanceMeters" in p ? p.distanceMeters : void 0
172
+ });
173
+ };
174
+ var fieldMap = {
175
+ place_id: ["id"],
176
+ name: ["displayName"],
177
+ formatted_address: ["formattedAddress"],
178
+ geometry: ["location", "viewport"],
179
+ "geometry/location": ["location"],
180
+ "geometry/location/lat": ["location"],
181
+ "geometry/location/lng": ["location"],
182
+ "geometry/viewport": ["viewport"],
183
+ address_component: ["addressComponents"],
184
+ address_components: ["addressComponents"],
185
+ adr_address: ["adrFormatAddress"],
186
+ business_status: ["businessStatus"],
187
+ permanently_closed: ["businessStatus"],
188
+ icon: ["iconMaskBaseUri"],
189
+ icon_mask_base_uri: ["iconMaskBaseUri"],
190
+ icon_background_color: ["iconBackgroundColor"],
191
+ plus_code: ["plusCode"],
192
+ type: ["types"],
193
+ types: ["types"],
194
+ url: ["googleMapsUri"],
195
+ utc_offset: ["utcOffsetMinutes"],
196
+ vicinity: ["shortFormattedAddress"],
197
+ formatted_phone_number: ["nationalPhoneNumber"],
198
+ international_phone_number: ["internationalPhoneNumber"],
199
+ opening_hours: ["regularOpeningHours", "currentOpeningHours"],
200
+ current_opening_hours: ["currentOpeningHours"],
201
+ website: ["websiteUri"],
202
+ price_level: ["priceLevel"],
203
+ rating: ["rating"],
204
+ user_ratings_total: ["userRatingCount"],
205
+ photo: ["photos"],
206
+ photos: ["photos"],
207
+ review: ["reviews"],
208
+ reviews: ["reviews"],
209
+ editorial_summary: ["editorialSummary"],
210
+ secondary_opening_hours: ["regularSecondaryOpeningHours", "currentSecondaryOpeningHours"],
211
+ wheelchair_accessible_entrance: ["accessibilityOptions"],
212
+ // legacy fields with nothing to fetch in the new API
213
+ id: [],
214
+ scope: [],
215
+ reference: [],
216
+ html_attributions: []
217
+ };
218
+ var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
219
+ var snake = (s) => s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
220
+ var toFields = (fields, prefix = "") => [
221
+ ...new Set(
222
+ [].concat(fields).flatMap((f) => f.split(",")).map((f) => f.trim()).filter(Boolean).flatMap((f) => (fieldMap[f] ?? [camel(f)]).map((n) => prefix + n))
223
+ )
224
+ ];
225
+ var hhmm = (t) => `${String(t.hour).padStart(2, "0")}${String(t.minute).padStart(2, "0")}`;
226
+ var toHours = (hours, openNow) => hours && strip({
227
+ open_now: openNow ?? hours.openNow,
228
+ periods: (hours.periods ?? []).map((p) => ({
229
+ open: { day: p.open.day, time: hhmm(p.open) },
230
+ ...p.close ? { close: { day: p.close.day, time: hhmm(p.close) } } : {}
231
+ })),
232
+ weekday_text: hours.weekdayDescriptions ?? []
233
+ });
234
+ var mapped = /* @__PURE__ */ new Set([
235
+ "name",
236
+ "id",
237
+ "displayName",
238
+ "formattedAddress",
239
+ "location",
240
+ "viewport",
241
+ "addressComponents",
242
+ "adrFormatAddress",
243
+ "businessStatus",
244
+ "iconMaskBaseUri",
245
+ "iconBackgroundColor",
246
+ "plusCode",
247
+ "types",
248
+ "googleMapsUri",
249
+ "utcOffsetMinutes",
250
+ "shortFormattedAddress",
251
+ "nationalPhoneNumber",
252
+ "internationalPhoneNumber",
253
+ "regularOpeningHours",
254
+ "currentOpeningHours",
255
+ "websiteUri",
256
+ "priceLevel",
257
+ "rating",
258
+ "userRatingCount",
259
+ "photos",
260
+ "reviews",
261
+ "editorialSummary",
262
+ "accessibilityOptions",
263
+ "regularSecondaryOpeningHours",
264
+ "currentSecondaryOpeningHours"
265
+ ]);
266
+ var toSecondaryHours = (hours) => hours?.map((h) => ({ ...toHours(h, void 0), type: h.secondaryHoursType }));
267
+ var toLegacyPlace = (p) => {
268
+ const place = strip({
269
+ place_id: p.id,
270
+ name: p.displayName?.text,
271
+ formatted_address: p.formattedAddress,
272
+ geometry: p.location || p.viewport ? strip({
273
+ location: toLiteral(p.location),
274
+ viewport: p.viewport ? { northeast: toLiteral(p.viewport.high), southwest: toLiteral(p.viewport.low) } : void 0
275
+ }) : void 0,
276
+ address_components: p.addressComponents?.map((c) => ({ long_name: c.longText, short_name: c.shortText, types: c.types })),
277
+ adr_address: p.adrFormatAddress,
278
+ business_status: p.businessStatus,
279
+ permanently_closed: p.businessStatus === "CLOSED_PERMANENTLY" ? true : void 0,
280
+ // the legacy icon was a PNG URL; Google says to append an image suffix to the mask base
281
+ icon: p.iconMaskBaseUri && `${p.iconMaskBaseUri}.png`,
282
+ icon_mask_base_uri: p.iconMaskBaseUri,
283
+ icon_background_color: p.iconBackgroundColor,
284
+ plus_code: p.plusCode && strip({ global_code: p.plusCode.globalCode, compound_code: p.plusCode.compoundCode }),
285
+ types: p.types,
286
+ url: p.googleMapsUri,
287
+ utc_offset: p.utcOffsetMinutes,
288
+ vicinity: p.shortFormattedAddress,
289
+ formatted_phone_number: p.nationalPhoneNumber,
290
+ international_phone_number: p.internationalPhoneNumber,
291
+ opening_hours: toHours(p.regularOpeningHours, p.currentOpeningHours?.openNow),
292
+ current_opening_hours: toHours(p.currentOpeningHours, void 0),
293
+ website: p.websiteUri,
294
+ price_level: priceLevelNumber(p.priceLevel),
295
+ rating: p.rating,
296
+ user_ratings_total: p.userRatingCount,
297
+ photos: p.photos?.map((ph) => ({
298
+ // the new photo name; pass it back to placePhoto as photoreference
299
+ photo_reference: ph.name,
300
+ width: ph.widthPx,
301
+ height: ph.heightPx,
302
+ html_attributions: (ph.authorAttributions ?? []).map((a) => a.uri ? `<a href="${a.uri}">${a.displayName}</a>` : a.displayName)
303
+ })),
304
+ reviews: p.reviews?.map(
305
+ (r) => strip({
306
+ author_name: r.authorAttribution?.displayName ?? "",
307
+ author_url: r.authorAttribution?.uri,
308
+ profile_photo_url: r.authorAttribution?.photoUri,
309
+ rating: r.rating,
310
+ text: (r.text ?? r.originalText)?.text ?? "",
311
+ language: (r.text ?? r.originalText)?.languageCode,
312
+ relative_time_description: r.relativePublishTimeDescription,
313
+ time: r.publishTime ? Math.floor(Date.parse(r.publishTime) / 1e3) : void 0
314
+ })
315
+ ),
316
+ editorial_summary: p.editorialSummary && strip({ overview: p.editorialSummary.text, language: p.editorialSummary.languageCode }),
317
+ secondary_opening_hours: toSecondaryHours(p.regularSecondaryOpeningHours ?? p.currentSecondaryOpeningHours),
318
+ wheelchair_accessible_entrance: p.accessibilityOptions?.wheelchairAccessibleEntrance
319
+ });
320
+ for (const [k, v] of Object.entries(p)) if (!mapped.has(k) && v !== void 0) place[snake(k)] = v;
321
+ return place;
322
+ };
323
+ var textSearchRequest = (p) => strip({
324
+ textQuery: p.query ?? "",
325
+ regionCode: p.region,
326
+ languageCode: p.language,
327
+ locationBias: p.location ? { circle: { center: toLatLng(p.location), radius: p.radius ?? 0 } } : void 0,
328
+ includedType: p.type,
329
+ openNow: p.opennow,
330
+ priceLevels: priceRange(p.minprice, p.maxprice),
331
+ pageToken: p.pagetoken
332
+ });
333
+ var nearbyPlan = (p) => {
334
+ const center = toLatLng(p.location);
335
+ const radius = p.rankby === "distance" || p.radius == null ? 5e4 : p.radius;
336
+ const byDistance = p.rankby === "distance";
337
+ if (p.keyword || p.name || p.opennow || p.minprice != null || p.maxprice != null || p.pagetoken) {
338
+ return {
339
+ kind: "text",
340
+ request: strip({
341
+ textQuery: [p.keyword, p.name].filter(Boolean).join(" ") || (p.type ?? "places").replace(/_/g, " "),
342
+ locationRestriction: circleToRectangle(center, radius),
343
+ includedType: p.type,
344
+ openNow: p.opennow,
345
+ priceLevels: priceRange(p.minprice, p.maxprice),
346
+ rankPreference: byDistance ? "DISTANCE" : void 0,
347
+ languageCode: p.language,
348
+ pageToken: p.pagetoken
349
+ })
350
+ };
351
+ }
352
+ return {
353
+ kind: "nearby",
354
+ request: strip({
355
+ locationRestriction: { circle: { center, radius } },
356
+ includedTypes: p.type ? [p.type] : void 0,
357
+ rankPreference: byDistance ? "DISTANCE" : "POPULARITY",
358
+ languageCode: p.language
359
+ })
360
+ };
361
+ };
362
+
363
+ // src/legacy/routes.ts
364
+ var modes = { driving: "DRIVE", walking: "WALK", bicycling: "BICYCLE", transit: "TRANSIT" };
365
+ var legacyModes = { DRIVE: "DRIVING", WALK: "WALKING", BICYCLE: "BICYCLING", TRANSIT: "TRANSIT" };
366
+ var transitModes = { bus: "BUS", subway: "SUBWAY", train: "TRAIN", tram: "LIGHT_RAIL", rail: "RAIL" };
367
+ var timestamp = (t) => new Date(typeof t === "number" ? t * 1e3 : t).toISOString();
368
+ var routeOptions = (p) => {
369
+ const travelMode = modes[p.mode ?? "driving"] ?? p.mode.toUpperCase();
370
+ const options = { travelMode };
371
+ let trafficAware = false;
372
+ if (travelMode === "DRIVE" && p.departure_time !== void 0) {
373
+ trafficAware = true;
374
+ options.routingPreference = p.traffic_model ? "TRAFFIC_AWARE_OPTIMAL" : "TRAFFIC_AWARE";
375
+ if (p.departure_time !== "now") options.departureTime = timestamp(p.departure_time);
376
+ if (p.traffic_model) options.trafficModel = p.traffic_model.toUpperCase();
377
+ }
378
+ if (travelMode === "TRANSIT") {
379
+ if (p.departure_time !== void 0 && p.departure_time !== "now") options.departureTime = timestamp(p.departure_time);
380
+ if (p.arrival_time !== void 0) options.arrivalTime = timestamp(p.arrival_time);
381
+ const preferences = strip({
382
+ allowedTravelModes: p.transit_mode?.map((m) => transitModes[m] ?? m.toUpperCase()),
383
+ routingPreference: p.transit_routing_preference?.toUpperCase()
384
+ });
385
+ if (Object.keys(preferences).length) options.transitPreferences = preferences;
386
+ }
387
+ if (p.avoid?.length) {
388
+ options.routeModifiers = strip({
389
+ avoidTolls: p.avoid.includes("tolls") || void 0,
390
+ avoidHighways: p.avoid.includes("highways") || void 0,
391
+ avoidFerries: p.avoid.includes("ferries") || void 0,
392
+ avoidIndoor: p.avoid.includes("indoor") || void 0
393
+ });
394
+ }
395
+ options.languageCode = p.language ?? "en";
396
+ if (p.region) options.regionCode = p.region;
397
+ if (p.units) options.units = p.units.toUpperCase();
398
+ return { options, trafficAware };
399
+ };
400
+ var distance = (metres, text) => ({
401
+ value: metres ?? 0,
402
+ text: text ?? `${((metres ?? 0) / 1e3).toFixed(1)} km`
403
+ });
404
+ var duration = (d, text) => {
405
+ const value = Math.round(seconds(d) ?? 0);
406
+ const minutes = Math.max(1, Math.round(value / 60));
407
+ return { value, text: text ?? (minutes === 1 ? "1 min" : `${minutes} mins`) };
408
+ };
409
+ var maneuver = (m) => !m || m === "DEPART" || m === "NAME_CHANGE" || m === "MANEUVER_UNSPECIFIED" ? void 0 : m.toLowerCase().replace(/_/g, "-");
410
+ var directionsFields = [
411
+ "routes.description",
412
+ "routes.warnings",
413
+ "routes.viewport",
414
+ "routes.polyline.encodedPolyline",
415
+ "routes.optimizedIntermediateWaypointIndex",
416
+ "routes.legs.distanceMeters",
417
+ "routes.legs.duration",
418
+ "routes.legs.staticDuration",
419
+ "routes.legs.startLocation",
420
+ "routes.legs.endLocation",
421
+ "routes.legs.localizedValues",
422
+ "routes.legs.steps.distanceMeters",
423
+ "routes.legs.steps.staticDuration",
424
+ "routes.legs.steps.startLocation",
425
+ "routes.legs.steps.endLocation",
426
+ "routes.legs.steps.polyline.encodedPolyline",
427
+ "routes.legs.steps.navigationInstruction",
428
+ "routes.legs.steps.localizedValues",
429
+ "routes.legs.steps.travelMode"
430
+ ];
431
+ var directionsPlan = (p) => {
432
+ let waypoints = p.waypoints ?? [];
433
+ let optimize = p.optimize;
434
+ if (waypoints[0] === "optimize:true") {
435
+ optimize = true;
436
+ waypoints = waypoints.slice(1);
437
+ }
438
+ const { options, trafficAware } = routeOptions(p);
439
+ const request = strip({
440
+ ...options,
441
+ origin: toWaypoint(p.origin),
442
+ destination: toWaypoint(p.destination),
443
+ intermediates: waypoints.length ? waypoints.map(toWaypoint) : void 0,
444
+ computeAlternativeRoutes: p.alternatives || void 0,
445
+ optimizeWaypointOrder: optimize || void 0
446
+ });
447
+ const legStops = waypoints.filter((w) => !(typeof w === "string" && w.startsWith("via:")));
448
+ return { request, trafficAware, stops: [p.origin, ...legStops, p.destination], intermediates: legStops.length };
449
+ };
450
+ var toLegacyRoute = (r, plan) => {
451
+ const order = (r.optimizedIntermediateWaypointIndex ?? []).filter((i) => i >= 0);
452
+ const optimized = order.length === plan.intermediates;
453
+ const stops = optimized ? [plan.stops[0], ...order.map((i) => plan.stops[i + 1]), plan.stops[plan.stops.length - 1]] : plan.stops;
454
+ return strip({
455
+ summary: r.description ?? "",
456
+ legs: (r.legs ?? []).map(
457
+ (leg, i) => strip({
458
+ steps: (leg.steps ?? []).map(
459
+ (s) => strip({
460
+ html_instructions: s.navigationInstruction?.instructions ?? "",
461
+ distance: distance(s.distanceMeters, s.localizedValues?.distance?.text),
462
+ duration: duration(s.staticDuration, s.localizedValues?.staticDuration?.text),
463
+ start_location: toLiteral(s.startLocation?.latLng),
464
+ end_location: toLiteral(s.endLocation?.latLng),
465
+ polyline: { points: s.polyline?.encodedPolyline ?? "" },
466
+ travel_mode: (s.travelMode && legacyModes[s.travelMode]) ?? s.travelMode ?? "",
467
+ maneuver: maneuver(s.navigationInstruction?.maneuver)
468
+ })
469
+ ),
470
+ distance: distance(leg.distanceMeters, leg.localizedValues?.distance?.text),
471
+ // legacy duration never included traffic; staticDuration is the same thing
472
+ duration: leg.staticDuration ? duration(leg.staticDuration, leg.localizedValues?.staticDuration?.text) : duration(leg.duration, leg.localizedValues?.duration?.text),
473
+ duration_in_traffic: plan.trafficAware ? duration(leg.duration, leg.localizedValues?.duration?.text) : void 0,
474
+ start_location: toLiteral(leg.startLocation?.latLng),
475
+ end_location: toLiteral(leg.endLocation?.latLng),
476
+ start_address: addressOf(stops[i]),
477
+ end_address: addressOf(stops[i + 1])
478
+ })
479
+ ),
480
+ waypoint_order: optimized ? order : Array.from({ length: plan.intermediates }, (_, i) => i),
481
+ overview_polyline: { points: r.polyline?.encodedPolyline ?? "" },
482
+ bounds: r.viewport ? { northeast: toLiteral(r.viewport.high), southwest: toLiteral(r.viewport.low) } : void 0,
483
+ copyrights: `Map data \xA9${(/* @__PURE__ */ new Date()).getFullYear()} Google`,
484
+ warnings: r.warnings ?? []
485
+ });
486
+ };
487
+ var matrixFields = [
488
+ "originIndex",
489
+ "destinationIndex",
490
+ "status",
491
+ "condition",
492
+ "distanceMeters",
493
+ "duration",
494
+ "staticDuration",
495
+ "localizedValues"
496
+ ];
497
+ var matrixPlan = (p) => {
498
+ const { options, trafficAware } = routeOptions(p);
499
+ const { routeModifiers, ...rest } = options;
500
+ return {
501
+ request: {
502
+ ...rest,
503
+ origins: p.origins.map((o) => ({ waypoint: toWaypoint(o), ...routeModifiers ? { routeModifiers } : {} })),
504
+ destinations: p.destinations.map((d) => ({ waypoint: toWaypoint(d) }))
505
+ },
506
+ trafficAware
507
+ };
508
+ };
509
+ var toElement = (e, trafficAware) => {
510
+ if (e.status?.code) return { status: "NOT_FOUND" };
511
+ if (e.condition === "ROUTE_NOT_FOUND") return { status: "ZERO_RESULTS" };
512
+ return strip({
513
+ status: "OK",
514
+ distance: distance(e.distanceMeters, e.localizedValues?.distance?.text),
515
+ duration: e.staticDuration ? duration(e.staticDuration, e.localizedValues?.staticDuration?.text) : duration(e.duration, e.localizedValues?.duration?.text),
516
+ duration_in_traffic: trafficAware ? duration(e.duration, e.localizedValues?.duration?.text) : void 0
517
+ });
518
+ };
519
+ var toLegacyMatrix = (elements, p, trafficAware) => {
520
+ const rows = p.origins.map(() => ({ elements: p.destinations.map(() => ({ status: "NOT_FOUND" })) }));
521
+ for (const e of elements) {
522
+ const row = rows[e.originIndex];
523
+ if (row && e.destinationIndex < row.elements.length) row.elements[e.destinationIndex] = toElement(e, trafficAware);
524
+ }
525
+ return { origin_addresses: p.origins.map(addressOf), destination_addresses: p.destinations.map(addressOf), rows };
526
+ };
527
+
528
+ // src/legacy/enums.ts
529
+ var PlaceIdScope = /* @__PURE__ */ ((PlaceIdScope2) => {
530
+ PlaceIdScope2["APP"] = "APP";
531
+ PlaceIdScope2["GOOGLE"] = "GOOGLE";
532
+ return PlaceIdScope2;
533
+ })(PlaceIdScope || {});
534
+ var PlaceType1 = /* @__PURE__ */ ((PlaceType12) => {
535
+ PlaceType12["accounting"] = "accounting";
536
+ PlaceType12["airport"] = "airport";
537
+ PlaceType12["amusement_park"] = "amusement_park";
538
+ PlaceType12["aquarium"] = "aquarium";
539
+ PlaceType12["art_gallery"] = "art_gallery";
540
+ PlaceType12["atm"] = "atm";
541
+ PlaceType12["bakery"] = "bakery";
542
+ PlaceType12["bank"] = "bank";
543
+ PlaceType12["bar"] = "bar";
544
+ PlaceType12["beauty_salon"] = "beauty_salon";
545
+ PlaceType12["bicycle_store"] = "bicycle_store";
546
+ PlaceType12["book_store"] = "book_store";
547
+ PlaceType12["bowling_alley"] = "bowling_alley";
548
+ PlaceType12["bus_station"] = "bus_station";
549
+ PlaceType12["cafe"] = "cafe";
550
+ PlaceType12["campground"] = "campground";
551
+ PlaceType12["car_dealer"] = "car_dealer";
552
+ PlaceType12["car_rental"] = "car_rental";
553
+ PlaceType12["car_repair"] = "car_repair";
554
+ PlaceType12["car_wash"] = "car_wash";
555
+ PlaceType12["casino"] = "casino";
556
+ PlaceType12["cemetery"] = "cemetery";
557
+ PlaceType12["church"] = "church";
558
+ PlaceType12["city_hall"] = "city_hall";
559
+ PlaceType12["clothing_store"] = "clothing_store";
560
+ PlaceType12["convenience_store"] = "convenience_store";
561
+ PlaceType12["courthouse"] = "courthouse";
562
+ PlaceType12["dentist"] = "dentist";
563
+ PlaceType12["department_store"] = "department_store";
564
+ PlaceType12["doctor"] = "doctor";
565
+ PlaceType12["drugstore"] = "drugstore";
566
+ PlaceType12["electrician"] = "electrician";
567
+ PlaceType12["electronics_store"] = "electronics_store";
568
+ PlaceType12["embassy"] = "embassy";
569
+ PlaceType12["fire_station"] = "fire_station";
570
+ PlaceType12["florist"] = "florist";
571
+ PlaceType12["funeral_home"] = "funeral_home";
572
+ PlaceType12["furniture_store"] = "furniture_store";
573
+ PlaceType12["gas_station"] = "gas_station";
574
+ PlaceType12["gym"] = "gym";
575
+ PlaceType12["hair_care"] = "hair_care";
576
+ PlaceType12["hardware_store"] = "hardware_store";
577
+ PlaceType12["hindu_temple"] = "hindu_temple";
578
+ PlaceType12["home_goods_store"] = "home_goods_store";
579
+ PlaceType12["hospital"] = "hospital";
580
+ PlaceType12["insurance_agency"] = "insurance_agency";
581
+ PlaceType12["jewelry_store"] = "jewelry_store";
582
+ PlaceType12["laundry"] = "laundry";
583
+ PlaceType12["lawyer"] = "lawyer";
584
+ PlaceType12["library"] = "library";
585
+ PlaceType12["light_rail_station"] = "light_rail_station";
586
+ PlaceType12["liquor_store"] = "liquor_store";
587
+ PlaceType12["local_government_office"] = "local_government_office";
588
+ PlaceType12["locksmith"] = "locksmith";
589
+ PlaceType12["lodging"] = "lodging";
590
+ PlaceType12["meal_delivery"] = "meal_delivery";
591
+ PlaceType12["meal_takeaway"] = "meal_takeaway";
592
+ PlaceType12["mosque"] = "mosque";
593
+ PlaceType12["movie_rental"] = "movie_rental";
594
+ PlaceType12["movie_theater"] = "movie_theater";
595
+ PlaceType12["moving_company"] = "moving_company";
596
+ PlaceType12["museum"] = "museum";
597
+ PlaceType12["night_club"] = "night_club";
598
+ PlaceType12["painter"] = "painter";
599
+ PlaceType12["park"] = "park";
600
+ PlaceType12["parking"] = "parking";
601
+ PlaceType12["pet_store"] = "pet_store";
602
+ PlaceType12["pharmacy"] = "pharmacy";
603
+ PlaceType12["physiotherapist"] = "physiotherapist";
604
+ PlaceType12["plumber"] = "plumber";
605
+ PlaceType12["police"] = "police";
606
+ PlaceType12["post_office"] = "post_office";
607
+ PlaceType12["real_estate_agency"] = "real_estate_agency";
608
+ PlaceType12["restaurant"] = "restaurant";
609
+ PlaceType12["roofing_contractor"] = "roofing_contractor";
610
+ PlaceType12["rv_park"] = "rv_park";
611
+ PlaceType12["school"] = "school";
612
+ PlaceType12["secondary_school"] = "secondary_school";
613
+ PlaceType12["shoe_store"] = "shoe_store";
614
+ PlaceType12["shopping_mall"] = "shopping_mall";
615
+ PlaceType12["spa"] = "spa";
616
+ PlaceType12["stadium"] = "stadium";
617
+ PlaceType12["storage"] = "storage";
618
+ PlaceType12["store"] = "store";
619
+ PlaceType12["subway_station"] = "subway_station";
620
+ PlaceType12["supermarket"] = "supermarket";
621
+ PlaceType12["synagogue"] = "synagogue";
622
+ PlaceType12["taxi_stand"] = "taxi_stand";
623
+ PlaceType12["tourist_attraction"] = "tourist_attraction";
624
+ PlaceType12["train_station"] = "train_station";
625
+ PlaceType12["transit_station"] = "transit_station";
626
+ PlaceType12["travel_agency"] = "travel_agency";
627
+ PlaceType12["university"] = "university";
628
+ PlaceType12["veterinary_care"] = "veterinary_care";
629
+ PlaceType12["zoo"] = "zoo";
630
+ return PlaceType12;
631
+ })(PlaceType1 || {});
632
+ var PlaceType2 = /* @__PURE__ */ ((PlaceType22) => {
633
+ PlaceType22["administrative_area_level_1"] = "administrative_area_level_1";
634
+ PlaceType22["administrative_area_level_2"] = "administrative_area_level_2";
635
+ PlaceType22["administrative_area_level_3"] = "administrative_area_level_3";
636
+ PlaceType22["administrative_area_level_4"] = "administrative_area_level_4";
637
+ PlaceType22["administrative_area_level_5"] = "administrative_area_level_5";
638
+ PlaceType22["archipelago"] = "archipelago";
639
+ PlaceType22["colloquial_area"] = "colloquial_area";
640
+ PlaceType22["continent"] = "continent";
641
+ PlaceType22["country"] = "country";
642
+ PlaceType22["establishment"] = "establishment";
643
+ PlaceType22["finance"] = "finance";
644
+ PlaceType22["floor"] = "floor";
645
+ PlaceType22["food"] = "food";
646
+ PlaceType22["general_contractor"] = "general_contractor";
647
+ PlaceType22["geocode"] = "geocode";
648
+ PlaceType22["health"] = "health";
649
+ PlaceType22["intersection"] = "intersection";
650
+ PlaceType22["landmark"] = "landmark";
651
+ PlaceType22["locality"] = "locality";
652
+ PlaceType22["natural_feature"] = "natural_feature";
653
+ PlaceType22["neighborhood"] = "neighborhood";
654
+ PlaceType22["place_of_worship"] = "place_of_worship";
655
+ PlaceType22["plus_code"] = "plus_code";
656
+ PlaceType22["point_of_interest"] = "point_of_interest";
657
+ PlaceType22["political"] = "political";
658
+ PlaceType22["post_box"] = "post_box";
659
+ PlaceType22["postal_code"] = "postal_code";
660
+ PlaceType22["postal_code_prefix"] = "postal_code_prefix";
661
+ PlaceType22["postal_code_suffix"] = "postal_code_suffix";
662
+ PlaceType22["postal_town"] = "postal_town";
663
+ PlaceType22["premise"] = "premise";
664
+ PlaceType22["room"] = "room";
665
+ PlaceType22["route"] = "route";
666
+ PlaceType22["street_address"] = "street_address";
667
+ PlaceType22["street_number"] = "street_number";
668
+ PlaceType22["sublocality"] = "sublocality";
669
+ PlaceType22["sublocality_level_1"] = "sublocality_level_1";
670
+ PlaceType22["sublocality_level_2"] = "sublocality_level_2";
671
+ PlaceType22["sublocality_level_3"] = "sublocality_level_3";
672
+ PlaceType22["sublocality_level_4"] = "sublocality_level_4";
673
+ PlaceType22["sublocality_level_5"] = "sublocality_level_5";
674
+ PlaceType22["subpremise"] = "subpremise";
675
+ PlaceType22["town_square"] = "town_square";
676
+ return PlaceType22;
677
+ })(PlaceType2 || {});
678
+ var AspectRatingType = /* @__PURE__ */ ((AspectRatingType2) => {
679
+ AspectRatingType2["appeal"] = "appeal";
680
+ AspectRatingType2["atmosphere"] = "atmosphere";
681
+ AspectRatingType2["decor"] = "decor";
682
+ AspectRatingType2["facilities"] = "facilities";
683
+ AspectRatingType2["food"] = "food";
684
+ AspectRatingType2["overall"] = "overall";
685
+ AspectRatingType2["quality"] = "quality";
686
+ AspectRatingType2["service"] = "service";
687
+ return AspectRatingType2;
688
+ })(AspectRatingType || {});
689
+ var Language = /* @__PURE__ */ ((Language2) => {
690
+ Language2["ar"] = "ar";
691
+ Language2["be"] = "be";
692
+ Language2["bg"] = "bg";
693
+ Language2["bn"] = "bn";
694
+ Language2["ca"] = "ca";
695
+ Language2["cs"] = "cs";
696
+ Language2["da"] = "da";
697
+ Language2["de"] = "de";
698
+ Language2["el"] = "el";
699
+ Language2["en"] = "en";
700
+ Language2["en_Au"] = "en-Au";
701
+ Language2["en_GB"] = "en-GB";
702
+ Language2["es"] = "es";
703
+ Language2["eu"] = "eu";
704
+ Language2["fa"] = "fa";
705
+ Language2["fi"] = "fi";
706
+ Language2["fil"] = "fil";
707
+ Language2["fr"] = "fr";
708
+ Language2["gl"] = "gl";
709
+ Language2["gu"] = "gu";
710
+ Language2["hi"] = "hi";
711
+ Language2["hr"] = "hr";
712
+ Language2["hu"] = "hu";
713
+ Language2["id"] = "id";
714
+ Language2["it"] = "it";
715
+ Language2["iw"] = "iw";
716
+ Language2["ja"] = "ja";
717
+ Language2["kk"] = "kk";
718
+ Language2["kn"] = "kn";
719
+ Language2["ko"] = "ko";
720
+ Language2["ky"] = "ky";
721
+ Language2["lt"] = "lt";
722
+ Language2["lv"] = "lv";
723
+ Language2["mk"] = "mk";
724
+ Language2["ml"] = "ml";
725
+ Language2["mr"] = "mr";
726
+ Language2["my"] = "my";
727
+ Language2["nl"] = "nl";
728
+ Language2["no"] = "no";
729
+ Language2["pa"] = "pa";
730
+ Language2["pl"] = "pl";
731
+ Language2["pt"] = "pt";
732
+ Language2["pt_BR"] = "pt-BR";
733
+ Language2["pt_PT"] = "pt-PT";
734
+ Language2["ro"] = "ro";
735
+ Language2["ru"] = "ru";
736
+ Language2["sk"] = "sk";
737
+ Language2["sl"] = "sl";
738
+ Language2["sq"] = "sq";
739
+ Language2["sr"] = "sr";
740
+ Language2["sv"] = "sv";
741
+ Language2["ta"] = "ta";
742
+ Language2["te"] = "te";
743
+ Language2["th"] = "th";
744
+ Language2["tl"] = "tl";
745
+ Language2["tr"] = "tr";
746
+ Language2["uk"] = "uk";
747
+ Language2["uz"] = "uz";
748
+ Language2["vi"] = "vi";
749
+ Language2["zh_CN"] = "zh-CN";
750
+ Language2["zh_TW"] = "zh-TW";
751
+ return Language2;
752
+ })(Language || {});
753
+ var TransitRoutingPreference = /* @__PURE__ */ ((TransitRoutingPreference2) => {
754
+ TransitRoutingPreference2["less_walking"] = "less_walking";
755
+ TransitRoutingPreference2["fewer_transfers"] = "fewer_transfers";
756
+ return TransitRoutingPreference2;
757
+ })(TransitRoutingPreference || {});
758
+ var DirectionsResponseStatus = /* @__PURE__ */ ((DirectionsResponseStatus2) => {
759
+ DirectionsResponseStatus2["OK"] = "OK";
760
+ DirectionsResponseStatus2["NOT_FOUND"] = "NOT_FOUND";
761
+ DirectionsResponseStatus2["ZERO_RESULTS"] = "ZERO_RESULTS";
762
+ DirectionsResponseStatus2["MAX_WAYPOINTS_EXCEEDED"] = "MAX_WAYPOINTS_EXCEEDED";
763
+ DirectionsResponseStatus2["MAX_ROUTE_LENGTH_EXCEEDED"] = "MAX_ROUTE_LENGTH_EXCEEDED";
764
+ DirectionsResponseStatus2["INVALID_REQUEST"] = "INVALID_REQUEST";
765
+ DirectionsResponseStatus2["OVER_DAILY_LIMIT"] = "OVER_DAILY_LIMIT";
766
+ DirectionsResponseStatus2["OVER_QUERY_LIMIT"] = "OVER_QUERY_LIMIT";
767
+ DirectionsResponseStatus2["REQUEST_DENIED"] = "REQUEST_DENIED";
768
+ DirectionsResponseStatus2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
769
+ return DirectionsResponseStatus2;
770
+ })(DirectionsResponseStatus || {});
771
+ var GeocodedWaypointStatus = /* @__PURE__ */ ((GeocodedWaypointStatus2) => {
772
+ GeocodedWaypointStatus2["OK"] = "OK";
773
+ GeocodedWaypointStatus2["ZERO_RESULTS"] = "ZERO_RESULTS";
774
+ return GeocodedWaypointStatus2;
775
+ })(GeocodedWaypointStatus || {});
776
+ var Maneuver = /* @__PURE__ */ ((Maneuver2) => {
777
+ Maneuver2["turn_slight_left"] = "turn-slight-left";
778
+ Maneuver2["turn_sharp_left"] = "turn-sharp-left";
779
+ Maneuver2["uturn_left"] = "uturn-left";
780
+ Maneuver2["turn_left"] = "turn-left";
781
+ Maneuver2["turn_slight_right"] = "turn-slight-right";
782
+ Maneuver2["turn_sharp_right"] = "turn-sharp-right";
783
+ Maneuver2["uturn_right"] = "uturn-right";
784
+ Maneuver2["turn_right"] = "turn-right";
785
+ Maneuver2["straight"] = "straight";
786
+ Maneuver2["ramp_left"] = "ramp-left";
787
+ Maneuver2["ramp_right"] = "ramp-right";
788
+ Maneuver2["merge"] = "merge";
789
+ Maneuver2["fork_left"] = "fork-left";
790
+ Maneuver2["fork_right"] = "fork-right";
791
+ Maneuver2["ferry"] = "ferry";
792
+ Maneuver2["ferry_train"] = "ferry-train";
793
+ Maneuver2["roundabout_left"] = "roundabout-left";
794
+ Maneuver2["roundabout_right"] = "roundabout-right";
795
+ return Maneuver2;
796
+ })(Maneuver || {});
797
+ var VehicleType = /* @__PURE__ */ ((VehicleType2) => {
798
+ VehicleType2["RAIL"] = "RAIL";
799
+ VehicleType2["METRO_RAIL"] = "METRO_RAIL";
800
+ VehicleType2["SUBWAY"] = "SUBWAY";
801
+ VehicleType2["TRAM"] = "TRAM";
802
+ VehicleType2["MONORAIL"] = "MONORAIL";
803
+ VehicleType2["HEAVY_RAIL"] = "HEAVY_RAIL";
804
+ VehicleType2["COMMUTER_TRAIN"] = "COMMUTER_TRAIN";
805
+ VehicleType2["HIGH_SPEED_TRAIN"] = "HIGH_SPEED_TRAIN";
806
+ VehicleType2["BUS"] = "BUS";
807
+ VehicleType2["INTERCITY_BUS"] = "INTERCITY_BUS";
808
+ VehicleType2["TROLLEYBUS"] = "TROLLEYBUS";
809
+ VehicleType2["SHARE_TAXI"] = "SHARE_TAXI";
810
+ VehicleType2["FERRY"] = "FERRY";
811
+ VehicleType2["CABLE_CAR"] = "CABLE_CAR";
812
+ VehicleType2["GONDOLA_LIFT"] = "GONDOLA_LIFT";
813
+ VehicleType2["FUNICULAR"] = "FUNICULAR";
814
+ VehicleType2["OTHER"] = "OTHER";
815
+ return VehicleType2;
816
+ })(VehicleType || {});
817
+ var GeocodingAddressComponentType = /* @__PURE__ */ ((GeocodingAddressComponentType2) => {
818
+ GeocodingAddressComponentType2["floor"] = "floor";
819
+ GeocodingAddressComponentType2["establishment"] = "establishment";
820
+ GeocodingAddressComponentType2["point_of_interest"] = "point_of_interest";
821
+ GeocodingAddressComponentType2["parking"] = "parking";
822
+ GeocodingAddressComponentType2["post_box"] = "post_box";
823
+ GeocodingAddressComponentType2["postal_town"] = "postal_town";
824
+ GeocodingAddressComponentType2["room"] = "room";
825
+ GeocodingAddressComponentType2["street_number"] = "street_number";
826
+ GeocodingAddressComponentType2["bus_station"] = "bus_station";
827
+ GeocodingAddressComponentType2["train_station"] = "train_station";
828
+ GeocodingAddressComponentType2["transit_station"] = "transit_station";
829
+ return GeocodingAddressComponentType2;
830
+ })(GeocodingAddressComponentType || {});
831
+ var LocationType = /* @__PURE__ */ ((LocationType2) => {
832
+ LocationType2["ROOFTOP"] = "ROOFTOP";
833
+ LocationType2["RANGE_INTERPOLATED"] = "RANGE_INTERPOLATED";
834
+ LocationType2["GEOMETRIC_CENTER"] = "GEOMETRIC_CENTER";
835
+ LocationType2["APPROXIMATE"] = "APPROXIMATE";
836
+ return LocationType2;
837
+ })(LocationType || {});
838
+ var RadioType = /* @__PURE__ */ ((RadioType2) => {
839
+ RadioType2["lte"] = "lte";
840
+ RadioType2["gsm"] = "gsm";
841
+ RadioType2["cdma"] = "cdma";
842
+ RadioType2["wcdma"] = "wcdma";
843
+ return RadioType2;
844
+ })(RadioType || {});
845
+ var ReverseGeocodingLocationType = /* @__PURE__ */ ((ReverseGeocodingLocationType2) => {
846
+ ReverseGeocodingLocationType2["ROOFTOP"] = "ROOFTOP";
847
+ ReverseGeocodingLocationType2["RANGE_INTERPOLATED"] = "RANGE_INTERPOLATED";
848
+ ReverseGeocodingLocationType2["GEOMETRIC_CENTER"] = "GEOMETRIC_CENTER";
849
+ ReverseGeocodingLocationType2["APPROXIMATE"] = "APPROXIMATE";
850
+ return ReverseGeocodingLocationType2;
851
+ })(ReverseGeocodingLocationType || {});
852
+ var GeolocateErrorReason = /* @__PURE__ */ ((GeolocateErrorReason2) => {
853
+ GeolocateErrorReason2["dailyLimitExceeded"] = "dailyLimitExceeded";
854
+ GeolocateErrorReason2["keyInvalid"] = "keyInvalid";
855
+ GeolocateErrorReason2["userRateLimitExceeded"] = "userRateLimitExceeded";
856
+ GeolocateErrorReason2["notFound"] = "notFound";
857
+ GeolocateErrorReason2["parseError"] = "parseError";
858
+ return GeolocateErrorReason2;
859
+ })(GeolocateErrorReason || {});
860
+ var AddressType = { ...PlaceType1, ...PlaceType2 };
861
+
862
+ // src/compat.ts
863
+ var Status = /* @__PURE__ */ ((Status2) => {
864
+ Status2["OK"] = "OK";
865
+ Status2["INVALID_REQUEST"] = "INVALID_REQUEST";
866
+ Status2["MAX_WAYPOINTS_EXCEEDED"] = "MAX_WAYPOINTS_EXCEEDED";
867
+ Status2["MAX_ROUTE_LENGTH_EXCEEDED"] = "MAX_ROUTE_LENGTH_EXCEEDED";
868
+ Status2["OVER_DAILY_LIMIT"] = "OVER_DAILY_LIMIT";
869
+ Status2["OVER_QUERY_LIMIT"] = "OVER_QUERY_LIMIT";
870
+ Status2["REQUEST_DENIED"] = "REQUEST_DENIED";
871
+ Status2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
872
+ Status2["ZERO_RESULTS"] = "ZERO_RESULTS";
873
+ Status2["NOT_FOUND"] = "NOT_FOUND";
874
+ return Status2;
875
+ })(Status || {});
876
+ var TravelMode = /* @__PURE__ */ ((TravelMode2) => {
877
+ TravelMode2["driving"] = "driving";
878
+ TravelMode2["walking"] = "walking";
879
+ TravelMode2["bicycling"] = "bicycling";
880
+ TravelMode2["transit"] = "transit";
881
+ return TravelMode2;
882
+ })(TravelMode || {});
883
+ var TravelRestriction = /* @__PURE__ */ ((TravelRestriction2) => {
884
+ TravelRestriction2["tolls"] = "tolls";
885
+ TravelRestriction2["highways"] = "highways";
886
+ TravelRestriction2["ferries"] = "ferries";
887
+ TravelRestriction2["indoor"] = "indoor";
888
+ return TravelRestriction2;
889
+ })(TravelRestriction || {});
890
+ var UnitSystem = /* @__PURE__ */ ((UnitSystem2) => {
891
+ UnitSystem2["metric"] = "metric";
892
+ UnitSystem2["imperial"] = "imperial";
893
+ return UnitSystem2;
894
+ })(UnitSystem || {});
895
+ var TrafficModel = /* @__PURE__ */ ((TrafficModel2) => {
896
+ TrafficModel2["best_guess"] = "best_guess";
897
+ TrafficModel2["optimistic"] = "optimistic";
898
+ TrafficModel2["pessimistic"] = "pessimistic";
899
+ return TrafficModel2;
900
+ })(TrafficModel || {});
901
+ var TransitMode = /* @__PURE__ */ ((TransitMode2) => {
902
+ TransitMode2["bus"] = "bus";
903
+ TransitMode2["subway"] = "subway";
904
+ TransitMode2["train"] = "train";
905
+ TransitMode2["tram"] = "tram";
906
+ TransitMode2["rail"] = "rail";
907
+ return TransitMode2;
908
+ })(TransitMode || {});
909
+ var PlaceAutocompleteType = /* @__PURE__ */ ((PlaceAutocompleteType2) => {
910
+ PlaceAutocompleteType2["geocode"] = "geocode";
911
+ PlaceAutocompleteType2["address"] = "address";
912
+ PlaceAutocompleteType2["establishment"] = "establishment";
913
+ PlaceAutocompleteType2["regions"] = "(regions)";
914
+ PlaceAutocompleteType2["cities"] = "(cities)";
915
+ return PlaceAutocompleteType2;
916
+ })(PlaceAutocompleteType || {});
917
+ var PlaceInputType = /* @__PURE__ */ ((PlaceInputType2) => {
918
+ PlaceInputType2["textQuery"] = "textquery";
919
+ PlaceInputType2["phoneNumber"] = "phonenumber";
920
+ return PlaceInputType2;
921
+ })(PlaceInputType || {});
922
+ var PlacesNearbyRanking = /* @__PURE__ */ ((PlacesNearbyRanking2) => {
923
+ PlacesNearbyRanking2["prominence"] = "prominence";
924
+ PlacesNearbyRanking2["distance"] = "distance";
925
+ return PlacesNearbyRanking2;
926
+ })(PlacesNearbyRanking || {});
927
+ var respond = (data, status = 200) => ({
928
+ data,
929
+ status,
930
+ statusText: status === 200 ? "OK" : "",
931
+ headers: {},
932
+ config: {}
933
+ });
934
+ var legacyStatuses = {
935
+ INVALID_ARGUMENT: "INVALID_REQUEST" /* INVALID_REQUEST */,
936
+ FAILED_PRECONDITION: "INVALID_REQUEST" /* INVALID_REQUEST */,
937
+ OUT_OF_RANGE: "INVALID_REQUEST" /* INVALID_REQUEST */,
938
+ PERMISSION_DENIED: "REQUEST_DENIED" /* REQUEST_DENIED */,
939
+ UNAUTHENTICATED: "REQUEST_DENIED" /* REQUEST_DENIED */,
940
+ RESOURCE_EXHAUSTED: "OVER_QUERY_LIMIT" /* OVER_QUERY_LIMIT */,
941
+ NOT_FOUND: "NOT_FOUND" /* NOT_FOUND */
942
+ };
943
+ var detailsFields = ["place_id", "formatted_address", "geometry", "address_components"];
944
+ var textSearchFields = ["place_id", "name", "formatted_address", "geometry", "types", "business_status"];
945
+ var nearbyFields = ["place_id", "name", "vicinity", "geometry", "types", "business_status"];
946
+ var Client = class {
947
+ constructor(options = {}) {
948
+ this.transports = /* @__PURE__ */ new Map();
949
+ // search requests by the page token they issued: the legacy API let callers fetch a page with the token alone
950
+ this.pages = /* @__PURE__ */ new Map();
951
+ this.options = options;
952
+ this.experienceId = options.experienceId ?? [];
953
+ }
954
+ setExperienceId(...ids) {
955
+ this.experienceId = ids;
956
+ }
957
+ clearExperienceId() {
958
+ this.experienceId = [];
959
+ }
960
+ getExperienceId() {
961
+ return this.experienceId;
962
+ }
963
+ transport(key) {
964
+ if (!key) throw new Error("google-maps-fetch/compat: params.key is required (client ID and URL signing are not supported)");
965
+ const id = this.experienceId.join(",");
966
+ const cacheKey = `${key}
967
+ ${id}`;
968
+ let send = this.transports.get(cacheKey);
969
+ if (!send) {
970
+ const { timeout, retries, headers } = this.options.config ?? {};
971
+ send = createTransport({
972
+ key,
973
+ fetch: this.options.fetch,
974
+ timeout,
975
+ retries,
976
+ headers: { ...headers, ...id ? { "X-GOOG-MAPS-EXPERIENCE-ID": id } : {} }
977
+ });
978
+ this.transports.set(cacheKey, send);
979
+ }
980
+ return send;
981
+ }
982
+ /** The request to send for a page: the one that issued the token, when only the token was given */
983
+ paged(request, pagetoken) {
984
+ const first = pagetoken ? this.pages.get(pagetoken) : void 0;
985
+ return first ? { ...first, pageToken: pagetoken } : request;
986
+ }
987
+ remember(request, token) {
988
+ if (!token) return;
989
+ const { pageToken: _, ...first } = request;
990
+ this.pages.set(token, first);
991
+ if (this.pages.size > 100) this.pages.delete(this.pages.keys().next().value);
992
+ }
993
+ // Legacy web services answered errors with HTTP 200 and a status field, so callers check data.status.
994
+ // API errors resolve the same way; network errors and timeouts still throw.
995
+ async call(request, empty, work) {
996
+ const send = this.transport(request.params?.key);
997
+ try {
998
+ return respond(await work(send, { timeout: request.timeout, signal: request.signal }));
999
+ } catch (e) {
1000
+ if (e instanceof MapsError && e.status > 0) {
1001
+ return respond({ ...empty, status: legacyStatuses[e.code] ?? "UNKNOWN_ERROR" /* UNKNOWN_ERROR */, error_message: e.message }, e.status);
1002
+ }
1003
+ throw e;
1004
+ }
1005
+ }
1006
+ // APIs that aren't legacy (Geocoding, Elevation, Time Zone, Roads, Geolocation) are called as they are
1007
+ passthrough(request, url, empty, method = "GET", body) {
1008
+ const { key: _, ...params } = request.params ?? {};
1009
+ return this.call(
1010
+ request,
1011
+ empty,
1012
+ (send, call) => send({ method, url, keyIn: "query", query: serializeParams(params), body }, call)
1013
+ );
1014
+ }
1015
+ placeAutocomplete(request) {
1016
+ return this.call(request, { predictions: [] }, async (send, call) => {
1017
+ const res = await createPlaces(send).autocomplete(autocompleteRequest(request.params), call);
1018
+ const predictions = (res.suggestions ?? []).flatMap((s) => s.placePrediction ? [toPrediction(s.placePrediction)] : []);
1019
+ return { status: predictions.length ? "OK" /* OK */ : "ZERO_RESULTS" /* ZERO_RESULTS */, predictions };
1020
+ });
1021
+ }
1022
+ placeQueryAutocomplete(request) {
1023
+ return this.call(request, { predictions: [] }, async (send, call) => {
1024
+ const res = await createPlaces(send).autocomplete({ ...autocompleteRequest(request.params), includeQueryPredictions: true }, call);
1025
+ const predictions = (res.suggestions ?? []).flatMap((s) => {
1026
+ const p = s.placePrediction ?? s.queryPrediction;
1027
+ return p ? [toPrediction(p)] : [];
1028
+ });
1029
+ return { status: predictions.length ? "OK" /* OK */ : "ZERO_RESULTS" /* ZERO_RESULTS */, predictions };
1030
+ });
1031
+ }
1032
+ placeDetails(request) {
1033
+ return this.call(
1034
+ request,
1035
+ { result: {}, html_attributions: [] },
1036
+ async (send, call) => {
1037
+ const { place_id, fields = detailsFields, language, region, sessiontoken } = request.params;
1038
+ const place = await createPlaces(send).get(place_id, {
1039
+ ...call,
1040
+ fields: toFields(fields),
1041
+ languageCode: language,
1042
+ regionCode: region,
1043
+ sessionToken: sessiontoken
1044
+ });
1045
+ return { status: "OK" /* OK */, result: toLegacyPlace(place), html_attributions: [] };
1046
+ }
1047
+ );
1048
+ }
1049
+ findPlaceFromText(request) {
1050
+ return this.call(request, { candidates: [] }, async (send, call) => {
1051
+ const { input, fields = ["place_id"], locationbias, language } = request.params;
1052
+ const res = await createPlaces(send).searchText(
1053
+ {
1054
+ textQuery: input,
1055
+ pageSize: 1,
1056
+ languageCode: language,
1057
+ ...locationbias ? { locationBias: parseLocationBias(locationbias) } : {}
1058
+ },
1059
+ { ...call, fields: toFields(fields, "places.") }
1060
+ );
1061
+ const candidates = (res.places ?? []).map(toLegacyPlace);
1062
+ return { status: candidates.length ? "OK" /* OK */ : "ZERO_RESULTS" /* ZERO_RESULTS */, candidates };
1063
+ });
1064
+ }
1065
+ textSearch(request) {
1066
+ return this.call(request, { results: [], html_attributions: [] }, async (send, call) => {
1067
+ const fields = [...toFields(request.params.fields ?? textSearchFields, "places."), "nextPageToken"];
1068
+ const body = this.paged(textSearchRequest(request.params), request.params.pagetoken);
1069
+ const res = await createPlaces(send).searchText(body, { ...call, fields });
1070
+ this.remember(body, res.nextPageToken);
1071
+ const results = (res.places ?? []).map(toLegacyPlace);
1072
+ return {
1073
+ status: results.length ? "OK" /* OK */ : "ZERO_RESULTS" /* ZERO_RESULTS */,
1074
+ results,
1075
+ html_attributions: [],
1076
+ ...res.nextPageToken ? { next_page_token: res.nextPageToken } : {}
1077
+ };
1078
+ });
1079
+ }
1080
+ placesNearby(request) {
1081
+ return this.call(request, { results: [], html_attributions: [] }, async (send, call) => {
1082
+ const { pagetoken } = request.params;
1083
+ const first = pagetoken ? this.pages.get(pagetoken) : void 0;
1084
+ if (pagetoken && !first && request.params.location === void 0) {
1085
+ throw new MapsError(
1086
+ "google-maps-fetch/compat: this pagetoken was not issued by this client; repeat the original parameters with it",
1087
+ 400,
1088
+ "INVALID_ARGUMENT"
1089
+ );
1090
+ }
1091
+ const plan = first ? { kind: "text", request: { ...first, pageToken: pagetoken } } : nearbyPlan(request.params);
1092
+ const fields = toFields(request.params.fields ?? nearbyFields, "places.");
1093
+ const places = createPlaces(send);
1094
+ const res = plan.kind === "nearby" ? await places.searchNearby(plan.request, { ...call, fields }) : await places.searchText(plan.request, { ...call, fields: [...fields, "nextPageToken"] });
1095
+ const results = (res.places ?? []).map(toLegacyPlace);
1096
+ const token = "nextPageToken" in res ? res.nextPageToken : void 0;
1097
+ if (plan.kind === "text") this.remember(plan.request, token);
1098
+ return {
1099
+ status: results.length ? "OK" /* OK */ : "ZERO_RESULTS" /* ZERO_RESULTS */,
1100
+ results,
1101
+ html_attributions: [],
1102
+ ...token ? { next_page_token: token } : {}
1103
+ };
1104
+ });
1105
+ }
1106
+ /**
1107
+ * Image bytes for a photo. photoreference is a photo name from a result's photos (places/.../photos/...).
1108
+ * Returns an ArrayBuffer, as the legacy client did by default.
1109
+ */
1110
+ async placePhoto(request) {
1111
+ const { photoreference, maxwidth, maxheight, key } = request.params;
1112
+ if (!photoreference.startsWith("places/")) {
1113
+ throw new Error(
1114
+ 'google-maps-fetch/compat: photoreference must be a Places API (New) photo name ("places/.../photos/..."), as returned in photos[]'
1115
+ );
1116
+ }
1117
+ const send = this.transport(key);
1118
+ const call = { timeout: request.timeout, signal: request.signal };
1119
+ const { photoUri } = await createPlaces(send).photo(photoreference, { ...call, maxWidthPx: maxwidth, maxHeightPx: maxheight });
1120
+ const ms = request.timeout ?? this.options.config?.timeout ?? 1e4;
1121
+ const signal = request.signal ?? (ms > 0 && typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(ms) : void 0);
1122
+ const res = await (this.options.fetch ?? globalThis.fetch)(photoUri, { signal });
1123
+ if (!res.ok) throw new MapsError(`google-maps-fetch/compat: photo download failed with HTTP ${res.status}`, res.status, "UNKNOWN");
1124
+ const contentType = res.headers.get("content-type");
1125
+ return { ...respond(await res.arrayBuffer()), headers: contentType ? { "content-type": contentType } : {} };
1126
+ }
1127
+ directions(request) {
1128
+ return this.call(
1129
+ request,
1130
+ { routes: [], geocoded_waypoints: [], available_travel_modes: [] },
1131
+ async (send, call) => {
1132
+ const plan = directionsPlan(request.params);
1133
+ const res = await createRoutes(send).compute(plan.request, { ...call, fields: directionsFields });
1134
+ const routes = (res.routes ?? []).map((r) => toLegacyRoute(r, plan));
1135
+ return { status: routes.length ? "OK" /* OK */ : "ZERO_RESULTS" /* ZERO_RESULTS */, routes, geocoded_waypoints: [], available_travel_modes: [] };
1136
+ }
1137
+ );
1138
+ }
1139
+ distancematrix(request) {
1140
+ return this.call(request, { origin_addresses: [], destination_addresses: [], rows: [] }, async (send, call) => {
1141
+ const { request: body, trafficAware } = matrixPlan(request.params);
1142
+ const elements = await createRoutes(send).matrix(body, { ...call, fields: matrixFields });
1143
+ return { status: "OK" /* OK */, ...toLegacyMatrix(elements, request.params, trafficAware) };
1144
+ });
1145
+ }
1146
+ geocode(request) {
1147
+ return this.passthrough(request, "https://maps.googleapis.com/maps/api/geocode/json", {
1148
+ results: []
1149
+ });
1150
+ }
1151
+ reverseGeocode(request) {
1152
+ return this.passthrough(request, "https://maps.googleapis.com/maps/api/geocode/json", {
1153
+ results: []
1154
+ });
1155
+ }
1156
+ elevation(request) {
1157
+ return this.passthrough(request, "https://maps.googleapis.com/maps/api/elevation/json", {
1158
+ results: []
1159
+ });
1160
+ }
1161
+ timezone(request) {
1162
+ return this.passthrough(request, "https://maps.googleapis.com/maps/api/timezone/json", {});
1163
+ }
1164
+ geolocate(request) {
1165
+ return this.passthrough(
1166
+ request,
1167
+ "https://www.googleapis.com/geolocation/v1/geolocate",
1168
+ {},
1169
+ "POST",
1170
+ request.data ?? {}
1171
+ );
1172
+ }
1173
+ nearestRoads(request) {
1174
+ return this.passthrough(request, "https://roads.googleapis.com/v1/nearestRoads", {
1175
+ snappedPoints: []
1176
+ });
1177
+ }
1178
+ snapToRoads(request) {
1179
+ return this.passthrough(
1180
+ request,
1181
+ "https://roads.googleapis.com/v1/snapToRoads",
1182
+ { snappedPoints: [] }
1183
+ );
1184
+ }
1185
+ };
1186
+ export {
1187
+ AddressType,
1188
+ AspectRatingType,
1189
+ Client,
1190
+ DirectionsResponseStatus as DirectionsReponseStatus,
1191
+ DirectionsResponseStatus,
1192
+ GeocodedWaypointStatus,
1193
+ GeocodingAddressComponentType,
1194
+ GeolocateErrorReason,
1195
+ Language,
1196
+ LocationType,
1197
+ Maneuver,
1198
+ MapsError,
1199
+ PlaceAutocompleteType,
1200
+ PlaceIdScope,
1201
+ PlaceInputType,
1202
+ PlaceType1,
1203
+ PlaceType2,
1204
+ PlacesNearbyRanking,
1205
+ RadioType,
1206
+ ReverseGeocodingLocationType,
1207
+ Status,
1208
+ TrafficModel,
1209
+ TransitMode,
1210
+ TransitRoutingPreference,
1211
+ TravelMode,
1212
+ TravelRestriction,
1213
+ UnitSystem,
1214
+ VehicleType
1215
+ };