@tileflow/static 0.1.0-alpha.27 → 0.1.0-alpha.28

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/scene.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { S as StaticMapError } from './errors-CSz1xaDx.js';
3
- import { j as StaticSceneInput, i as StaticScene } from './scene-contract-Cr6BNLz0.js';
4
- export { M as MAX_OVERLAY_LATITUDE, S as StaticAttributionMode, a as StaticAttributionPosition, b as StaticAttributionRequest, c as StaticCoordinate, d as StaticMapFormat, g as StaticOverlayPlacement, h as StaticPadding, k as StaticSymbolAnchor, l as StaticSymbolCollision, m as StaticSymbolLabelAppearance, n as StaticSymbolLabelPosition, o as StaticSymbolLanguage, p as isSupportedStaticSymbolCodePoint, s as staticAttributionPositionSchema, q as staticAttributionRequestSchema, r as staticOverlayPlacements, u as staticSceneLimits, v as staticSceneSchema, w as staticSceneSchemaVersion, x as staticSymbolAnchors, y as staticSymbolCollisions, z as staticSymbolLabelAppearances, A as staticSymbolLabelPositions, B as staticSymbolLanguages } from './scene-contract-Cr6BNLz0.js';
3
+ import { a as StaticSceneInput, f as StaticScene } from './scene-contract-NFnIcQtt.js';
4
+ export { M as MAX_OVERLAY_LATITUDE, g as StaticAttributionMode, S as StaticAttributionPosition, h as StaticAttributionRequest, i as StaticCoordinate, j as StaticMapFormat, k as StaticOverlayPlacement, n as StaticPadding, o as StaticSymbolAnchor, q as StaticSymbolCollision, r as StaticSymbolLabelAppearance, t as StaticSymbolLabelPosition, u as StaticSymbolLanguage, v as isSupportedStaticSymbolCodePoint, w as staticAttributionPositionSchema, x as staticAttributionRequestSchema, y as staticOverlayPlacements, z as staticSceneLimits, A as staticSceneSchema, B as staticSceneSchemaVersion, C as staticSymbolAnchors, D as staticSymbolCollisions, E as staticSymbolLabelAppearances, F as staticSymbolLabelPositions, G as staticSymbolLanguages } from './scene-contract-NFnIcQtt.js';
5
5
 
6
6
  declare const autoFitDetailsSchema: z.ZodObject<{
7
7
  overlay: z.ZodOptional<z.ZodObject<{
@@ -82,11 +82,13 @@ declare const staticSymbolTooLargeDetailsSchema: z.ZodObject<{
82
82
  }, z.core.$strict>;
83
83
  type StaticMapRequestErrorDetails = StaticAutoFitDetails | z.infer<typeof staticIconUnavailableDetailsSchema> | z.infer<typeof staticOverlayInvalidDetailsSchema> | z.infer<typeof staticLabelUnsupportedDetailsSchema> | z.infer<typeof staticSymbolTooLargeDetailsSchema>;
84
84
  declare const staticMapRequestErrorResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
85
+ error: z.ZodString;
86
+ retryable: z.ZodLiteral<false>;
85
87
  code: z.ZodLiteral<"AUTO_FIT_EMPTY">;
86
88
  reason: z.ZodLiteral<"NO_FITTABLE_OVERLAYS">;
89
+ }, z.core.$strict>, z.ZodObject<{
87
90
  error: z.ZodString;
88
91
  retryable: z.ZodLiteral<false>;
89
- }, z.core.$strict>, z.ZodObject<{
90
92
  code: z.ZodLiteral<"AUTO_FIT_AMBIGUOUS">;
91
93
  details: z.ZodObject<{
92
94
  overlay: z.ZodOptional<z.ZodObject<{
@@ -124,9 +126,9 @@ declare const staticMapRequestErrorResponseSchema: z.ZodDiscriminatedUnion<[z.Zo
124
126
  }, z.core.$strict>>;
125
127
  }, z.core.$strict>;
126
128
  reason: z.ZodLiteral<"ANTIMERIDIAN_WRAP_REQUIRED">;
129
+ }, z.core.$strict>, z.ZodObject<{
127
130
  error: z.ZodString;
128
131
  retryable: z.ZodLiteral<false>;
129
- }, z.core.$strict>, z.ZodObject<{
130
132
  code: z.ZodLiteral<"AUTO_FIT_IMPOSSIBLE">;
131
133
  details: z.ZodOptional<z.ZodObject<{
132
134
  overlay: z.ZodOptional<z.ZodObject<{
@@ -169,9 +171,9 @@ declare const staticMapRequestErrorResponseSchema: z.ZodDiscriminatedUnion<[z.Zo
169
171
  INSUFFICIENT_VIEWPORT: "INSUFFICIENT_VIEWPORT";
170
172
  PROJECTED_FOOTPRINT_OUTSIDE_VIEWPORT: "PROJECTED_FOOTPRINT_OUTSIDE_VIEWPORT";
171
173
  }>;
174
+ }, z.core.$strict>, z.ZodObject<{
172
175
  error: z.ZodString;
173
176
  retryable: z.ZodLiteral<false>;
174
- }, z.core.$strict>, z.ZodObject<{
175
177
  code: z.ZodLiteral<"STATIC_OVERLAY_INVALID">;
176
178
  details: z.ZodObject<{
177
179
  latitude: z.ZodNumber;
@@ -189,9 +191,9 @@ declare const staticMapRequestErrorResponseSchema: z.ZodDiscriminatedUnion<[z.Zo
189
191
  }, z.core.$strict>;
190
192
  }, z.core.$strict>;
191
193
  reason: z.ZodLiteral<"OVERLAY_LATITUDE_OUT_OF_RANGE">;
194
+ }, z.core.$strict>, z.ZodObject<{
192
195
  error: z.ZodString;
193
196
  retryable: z.ZodLiteral<false>;
194
- }, z.core.$strict>, z.ZodObject<{
195
197
  code: z.ZodLiteral<"STATIC_MAP_LABEL_UNSUPPORTED">;
196
198
  details: z.ZodObject<{
197
199
  codePoint: z.ZodNumber;
@@ -202,9 +204,9 @@ declare const staticMapRequestErrorResponseSchema: z.ZodDiscriminatedUnion<[z.Zo
202
204
  }, z.core.$strict>;
203
205
  }, z.core.$strict>;
204
206
  reason: z.ZodLiteral<"UNSUPPORTED_GLYPH">;
207
+ }, z.core.$strict>, z.ZodObject<{
205
208
  error: z.ZodString;
206
209
  retryable: z.ZodLiteral<false>;
207
- }, z.core.$strict>, z.ZodObject<{
208
210
  code: z.ZodLiteral<"STATIC_MAP_ICON_UNAVAILABLE">;
209
211
  details: z.ZodObject<{
210
212
  icon: z.ZodString;
@@ -218,14 +220,14 @@ declare const staticMapRequestErrorResponseSchema: z.ZodDiscriminatedUnion<[z.Zo
218
220
  ICON_NOT_FOUND: "ICON_NOT_FOUND";
219
221
  MANAGED_SPRITE_REQUIRED: "MANAGED_SPRITE_REQUIRED";
220
222
  }>;
223
+ }, z.core.$strict>, z.ZodObject<{
221
224
  error: z.ZodString;
222
225
  retryable: z.ZodLiteral<false>;
223
- }, z.core.$strict>, z.ZodObject<{
224
226
  code: z.ZodLiteral<"STATIC_MAP_PLACEMENT_UNAVAILABLE">;
225
227
  reason: z.ZodLiteral<"MAP_REDEPLOY_REQUIRED">;
228
+ }, z.core.$strict>, z.ZodObject<{
226
229
  error: z.ZodString;
227
230
  retryable: z.ZodLiteral<false>;
228
- }, z.core.$strict>, z.ZodObject<{
229
231
  code: z.ZodLiteral<"STATIC_MAP_SYMBOL_TOO_LARGE">;
230
232
  details: z.ZodObject<{
231
233
  height: z.ZodNumber;
@@ -238,26 +240,24 @@ declare const staticMapRequestErrorResponseSchema: z.ZodDiscriminatedUnion<[z.Zo
238
240
  width: z.ZodNumber;
239
241
  }, z.core.$strict>;
240
242
  reason: z.ZodLiteral<"COMPOSED_IMAGE_TOO_LARGE">;
243
+ }, z.core.$strict>, z.ZodObject<{
241
244
  error: z.ZodString;
242
245
  retryable: z.ZodLiteral<false>;
243
- }, z.core.$strict>, z.ZodObject<{
244
246
  code: z.ZodLiteral<"STATIC_MAP_ATTRIBUTION_UNSUPPORTED">;
245
247
  reason: z.ZodEnum<{
246
248
  UNSUPPORTED_DECLARATION: "UNSUPPORTED_DECLARATION";
247
249
  UNSUPPORTED_GLYPH: "UNSUPPORTED_GLYPH";
248
250
  }>;
251
+ }, z.core.$strict>, z.ZodObject<{
249
252
  error: z.ZodString;
250
253
  retryable: z.ZodLiteral<false>;
251
- }, z.core.$strict>, z.ZodObject<{
252
254
  code: z.ZodLiteral<"STATIC_MAP_ATTRIBUTION_TOO_LARGE">;
253
255
  reason: z.ZodLiteral<"CONTENT_LIMIT_EXCEEDED">;
256
+ }, z.core.$strict>, z.ZodObject<{
254
257
  error: z.ZodString;
255
258
  retryable: z.ZodLiteral<false>;
256
- }, z.core.$strict>, z.ZodObject<{
257
259
  code: z.ZodLiteral<"STATIC_MAP_ATTRIBUTION_DOES_NOT_FIT">;
258
260
  reason: z.ZodLiteral<"BLOCK_DOES_NOT_FIT">;
259
- error: z.ZodString;
260
- retryable: z.ZodLiteral<false>;
261
261
  }, z.core.$strict>], "code">;
262
262
  type StaticMapRequestErrorResponse = z.infer<typeof staticMapRequestErrorResponseSchema>;
263
263
  type StaticAutoFitErrorResponse = Extract<StaticMapRequestErrorResponse, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tileflow/static",
3
- "version": "0.1.0-alpha.27",
3
+ "version": "0.1.0-alpha.28",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Static map request schemas and helpers for Tileflow.",
6
6
  "type": "module",
@@ -21,18 +21,11 @@
21
21
  "maplibre",
22
22
  "tiles"
23
23
  ],
24
- "main": "./dist/index.js",
25
- "types": "./dist/index.d.ts",
26
24
  "files": [
27
25
  "dist",
28
26
  "LICENSE"
29
27
  ],
30
28
  "exports": {
31
- ".": {
32
- "types": "./dist/index.d.ts",
33
- "import": "./dist/index.js",
34
- "default": "./dist/index.js"
35
- },
36
29
  "./client": {
37
30
  "types": "./dist/client.d.ts",
38
31
  "import": "./dist/client.js",
@@ -61,7 +54,7 @@
61
54
  "zod": "^4.4.3"
62
55
  },
63
56
  "scripts": {
64
- "build": "tsup src/index.ts src/scene.ts src/overlays.ts src/manifest.ts src/client.ts --format esm --dts --clean --splitting && node ../../scripts/canonicalize-zod-enums.mjs dist",
57
+ "build": "tsup src/scene.ts src/overlays.ts src/manifest.ts src/client.ts --format esm --dts --clean --splitting && node ../../scripts/canonicalize-zod-enums.mjs dist",
65
58
  "verify": "pnpm --silent --dir ../.. static-text:check && tsx --test test/*.test.ts",
66
59
  "typecheck": "tsc -p tsconfig.json --noEmit",
67
60
  "lint": "tsc -p tsconfig.json --noEmit"
@@ -1,380 +0,0 @@
1
- import {
2
- StaticMapError,
3
- StaticMapRequestError,
4
- staticMapErrorResponseSchema,
5
- staticMapRequestErrorResponseSchema,
6
- validateStaticScene
7
- } from "./chunk-ALFVZ3PC.js";
8
- import {
9
- isSafeHttpUrl,
10
- jsonByteLength,
11
- stableStringify
12
- } from "./chunk-6DWVCK64.js";
13
-
14
- // src/client.ts
15
- import { z } from "zod";
16
- var maxStaticMapResponseBytes = 64 * 1024;
17
- var staticMapIdempotencyKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$/;
18
- var STATIC_MAP_RESULT_MEDIA_TYPE = "application/vnd.tileflow.static-map-result+json;version=1";
19
- var preparedStaticMapRequestBodies = /* @__PURE__ */ new WeakMap();
20
- var staticMapReadyResultBaseSchema = z.object({
21
- cached: z.boolean(),
22
- hash: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
23
- imageUrl: z.string().trim().url().max(2048).refine(isSafeHttpUrl, { message: "Expected an http(s) URL without credentials" }),
24
- operationId: z.string().min(20).max(68),
25
- remainingUnits: z.number().int().nonnegative().nullable(),
26
- status: z.literal("ready"),
27
- unitCost: z.literal(15)
28
- }).strict();
29
- var safeAttributionTextSchema = z.string().min(1).max(16384).refine(hasNoControlCharacters, { message: "Attribution text contains control characters" });
30
- var staticMapAttributionEntrySchema = z.object({
31
- authority: z.enum(["platform-notice", "team-declared"]),
32
- links: z.array(
33
- z.object({
34
- label: safeAttributionTextSchema,
35
- url: z.string().trim().url().max(2048).refine(isSafeHttpUrl, {
36
- message: "Expected an http(s) URL without credentials or a fragment"
37
- })
38
- }).strict()
39
- ).max(8),
40
- text: safeAttributionTextSchema
41
- }).strict();
42
- var staticMapAttributionResultSchema = z.object({
43
- entries: z.array(staticMapAttributionEntrySchema).max(18),
44
- mode: z.enum(["embedded", "external"]),
45
- position: z.enum(["top-left", "top-right", "bottom-left", "bottom-right"]).nullable()
46
- }).strict().superRefine((result, context) => {
47
- if (result.mode === "external" && result.position !== null || result.mode === "embedded" && result.position === null) {
48
- context.addIssue({
49
- code: "custom",
50
- message: "Attribution position must match its mode",
51
- path: ["position"]
52
- });
53
- }
54
- if (jsonByteLength(result) > 32 * 1024) {
55
- context.addIssue({ code: "custom", message: "Attribution result exceeds 32 KiB" });
56
- }
57
- });
58
- var staticMapHostedResultSchema = staticMapReadyResultBaseSchema.extend({
59
- attribution: staticMapAttributionResultSchema,
60
- resultVersion: z.literal(1)
61
- }).strict();
62
- var staticMapProcessingResultSchema = z.object({
63
- operationId: z.string().min(20).max(68),
64
- retryAfterMs: z.number().int().min(0).max(5e3),
65
- status: z.literal("processing")
66
- }).strict();
67
- function validateStaticMapIdempotencyKey(value) {
68
- if (typeof value !== "string" || !staticMapIdempotencyKeyPattern.test(value)) {
69
- return {
70
- error: "Idempotency key must contain 8-128 ASCII letters, digits, dot, underscore, colon, or hyphen and start with a letter or digit",
71
- ok: false
72
- };
73
- }
74
- return { key: value, ok: true };
75
- }
76
- function createStaticMapIdempotencyKey() {
77
- const key = `static_${crypto.randomUUID()}`;
78
- if (!validateStaticMapIdempotencyKey(key).ok) {
79
- throw new Error("Unable to create a valid Tileflow Static Maps idempotency key");
80
- }
81
- return key;
82
- }
83
- function prepareStaticMapRequest(scene) {
84
- const validation = validateStaticScene(scene);
85
- if (!validation.ok) {
86
- if (isStaticMapRequestFailure(validation)) {
87
- const { ok: _ok, ...response } = validation;
88
- throw new StaticMapRequestError(response);
89
- }
90
- throw new Error(`Invalid Tileflow static scene: ${validation.error}`);
91
- }
92
- const prepared = Object.freeze({
93
- sceneKey: stableStringify(validation.scene)
94
- });
95
- preparedStaticMapRequestBodies.set(prepared, JSON.stringify(validation.scene));
96
- return prepared;
97
- }
98
- async function createStaticMap(scene, options) {
99
- return requestStaticMap(scene, options, "/v1/static/maps");
100
- }
101
- async function precacheStaticMap(scene, options) {
102
- return requestStaticMap(scene, options, "/v1/static/maps/precache");
103
- }
104
- async function requestStaticMap(scene, options, path) {
105
- const preparedRequest = prepareStaticMapRequest(scene);
106
- const { apiUrl = "https://api.tileflow.dev", ...requestOptions } = options;
107
- return requestStaticMapUntilReady(preparedRequest, {
108
- ...requestOptions,
109
- createUrl: `${normalizeUrl(apiUrl)}${path}`
110
- });
111
- }
112
- async function requestStaticMapUntilReady(request, options) {
113
- const body = preparedStaticMapRequestBodies.get(request);
114
- if (body === void 0) {
115
- throw new Error("Tileflow static map request must be created with prepareStaticMapRequest");
116
- }
117
- const idempotency = validateStaticMapIdempotencyKey(options.idempotencyKey);
118
- if (!idempotency.ok) {
119
- throw new Error(`Invalid Tileflow Static Maps idempotency key: ${idempotency.error}`);
120
- }
121
- const maxWaitMs = boundedClientDuration(options.maxWaitMs, 3e4, 100, 12e4, "maxWaitMs");
122
- const pollIntervalMs = boundedClientDuration(
123
- options.pollIntervalMs,
124
- 500,
125
- 0,
126
- 5e3,
127
- "pollIntervalMs"
128
- );
129
- const fetcher = options.fetch ?? fetch;
130
- const createUrl = normalizeStaticMapEndpointUrl(options.createUrl);
131
- const headers = {
132
- Accept: STATIC_MAP_RESULT_MEDIA_TYPE,
133
- "Content-Type": "application/json",
134
- "Idempotency-Key": idempotency.key
135
- };
136
- if (options.apiKey) {
137
- headers.Authorization = `Bearer ${options.apiKey}`;
138
- }
139
- if (options.mapId !== void 0) {
140
- if (!/^map_[A-Za-z0-9_-]{16}$/u.test(options.mapId)) {
141
- throw new Error("Invalid Tileflow Map ID.");
142
- }
143
- headers["X-Tileflow-Map-Id"] = options.mapId;
144
- }
145
- return runWithinStaticMapBudget(maxWaitMs, options.signal, async (signal) => {
146
- let operationId = null;
147
- while (true) {
148
- const response = await fetcher(createUrl, {
149
- body,
150
- headers,
151
- method: "POST",
152
- signal
153
- });
154
- throwIfAborted(signal);
155
- if (!response.ok) {
156
- const errorBody = await readStaticMapErrorBody(response, 8 * 1024);
157
- throwIfAborted(signal);
158
- if (response.status === 422) {
159
- const requestError = staticMapRequestErrorResponseSchema.safeParse(errorBody);
160
- if (requestError.success) {
161
- throw new StaticMapRequestError(requestError.data, response.status);
162
- }
163
- }
164
- const structured = staticMapErrorResponseSchema.safeParse(errorBody);
165
- if (structured.success) {
166
- throw new StaticMapError(structured.data, response.status);
167
- }
168
- throw new Error(`Tileflow static map failed (${response.status}).`);
169
- }
170
- const json = await readJsonResponse(response);
171
- throwIfAborted(signal);
172
- if (response.status !== 202) {
173
- const parsed = staticMapHostedResultSchema.safeParse(json);
174
- if (!parsed.success) {
175
- throw new Error(
176
- `Tileflow static map returned an invalid response: ${parsed.error.message}`
177
- );
178
- }
179
- assertStaticMapOperationIdentity(operationId, parsed.data.operationId);
180
- return parsed.data;
181
- }
182
- const pending = staticMapProcessingResultSchema.safeParse(json);
183
- if (!pending.success) {
184
- throw new Error(
185
- `Tileflow static map returned an invalid response: ${pending.error.message}`
186
- );
187
- }
188
- assertStaticMapOperationIdentity(operationId, pending.data.operationId);
189
- operationId ??= pending.data.operationId;
190
- await delay(Math.max(pollIntervalMs, pending.data.retryAfterMs), signal);
191
- }
192
- });
193
- }
194
- function hasNoControlCharacters(value) {
195
- return !Array.from(value).some((character) => {
196
- const codePoint = character.codePointAt(0) ?? 0;
197
- return codePoint <= 31 || codePoint === 127;
198
- });
199
- }
200
- function boundedClientDuration(value, fallback, minimum, maximum, name) {
201
- const resolved = value ?? fallback;
202
- if (!Number.isSafeInteger(resolved) || resolved < minimum || resolved > maximum) {
203
- throw new Error(
204
- `Tileflow Static Maps ${name} must be an integer from ${minimum} to ${maximum}`
205
- );
206
- }
207
- return resolved;
208
- }
209
- async function readJsonResponse(response) {
210
- const source = await readBoundedResponseText(response, maxStaticMapResponseBytes, "64 KiB");
211
- try {
212
- return JSON.parse(source);
213
- } catch {
214
- throw new Error("Tileflow static map returned an invalid response: expected JSON");
215
- }
216
- }
217
- async function readStaticMapErrorBody(response, maximumBytes) {
218
- try {
219
- const source = await readBoundedResponseText(response, maximumBytes, `${maximumBytes} bytes`);
220
- return JSON.parse(source);
221
- } catch {
222
- return null;
223
- }
224
- }
225
- function isStaticMapRequestFailure(value) {
226
- if (!("code" in value)) return false;
227
- const { ok: _ok, ...response } = value;
228
- return staticMapRequestErrorResponseSchema.safeParse(response).success;
229
- }
230
- async function readBoundedResponseText(response, maximumBytes, displayLimit) {
231
- if (!response.body) return "";
232
- const reader = response.body.getReader();
233
- const chunks = [];
234
- let byteLength = 0;
235
- while (true) {
236
- const { done, value } = await reader.read();
237
- if (done) break;
238
- byteLength += value.byteLength;
239
- if (byteLength > maximumBytes) {
240
- await reader.cancel();
241
- throw new Error(
242
- `Tileflow static map returned an invalid response: response exceeded ${displayLimit}`
243
- );
244
- }
245
- chunks.push(value);
246
- }
247
- const bytes = new Uint8Array(byteLength);
248
- let offset = 0;
249
- for (const chunk of chunks) {
250
- bytes.set(chunk, offset);
251
- offset += chunk.byteLength;
252
- }
253
- try {
254
- return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
255
- } catch {
256
- throw new Error("Tileflow static map returned an invalid response: expected UTF-8 JSON");
257
- }
258
- }
259
- async function runWithinStaticMapBudget(maxWaitMs, externalSignal, operation) {
260
- const controller = new AbortController();
261
- const timeoutError = new Error(`Tileflow static map timed out after ${maxWaitMs}ms`);
262
- const abortFromCaller = () => controller.abort(externalSignal?.reason);
263
- if (externalSignal?.aborted) {
264
- abortFromCaller();
265
- } else {
266
- externalSignal?.addEventListener("abort", abortFromCaller, { once: true });
267
- }
268
- const timeout = setTimeout(() => controller.abort(timeoutError), maxWaitMs);
269
- try {
270
- throwIfAborted(controller.signal);
271
- const pending = operation(controller.signal);
272
- return await raceWithAbort(pending, controller.signal);
273
- } finally {
274
- clearTimeout(timeout);
275
- externalSignal?.removeEventListener("abort", abortFromCaller);
276
- }
277
- }
278
- function delay(milliseconds, signal) {
279
- if (milliseconds === 0) {
280
- throwIfAborted(signal);
281
- return Promise.resolve();
282
- }
283
- return new Promise((resolve, reject) => {
284
- const timeout = setTimeout(() => {
285
- signal.removeEventListener("abort", onAbort);
286
- resolve();
287
- }, milliseconds);
288
- const onAbort = () => {
289
- clearTimeout(timeout);
290
- reject(abortReason(signal));
291
- };
292
- if (signal.aborted) {
293
- onAbort();
294
- } else {
295
- signal.addEventListener("abort", onAbort, { once: true });
296
- }
297
- });
298
- }
299
- function raceWithAbort(operation, signal) {
300
- if (signal.aborted) return Promise.reject(abortReason(signal));
301
- return new Promise((resolve, reject) => {
302
- const onAbort = () => {
303
- cleanup();
304
- reject(abortReason(signal));
305
- };
306
- const cleanup = () => signal.removeEventListener("abort", onAbort);
307
- signal.addEventListener("abort", onAbort, { once: true });
308
- operation.then(
309
- (value) => {
310
- cleanup();
311
- resolve(value);
312
- },
313
- (error) => {
314
- cleanup();
315
- reject(error);
316
- }
317
- );
318
- });
319
- }
320
- function throwIfAborted(signal) {
321
- if (signal.aborted) throw abortReason(signal);
322
- }
323
- function abortReason(signal) {
324
- if (signal.reason instanceof Error) return signal.reason;
325
- const error = new Error("Tileflow static map request was aborted");
326
- error.name = "AbortError";
327
- return error;
328
- }
329
- function assertStaticMapOperationIdentity(expected, actual) {
330
- if (expected !== null && actual !== expected) {
331
- throw new Error("Tileflow static map changed operation identity while polling");
332
- }
333
- }
334
- function normalizeUrl(value) {
335
- const url = new URL(value);
336
- if (!isSafeHttpUrl(value) || url.search) {
337
- throw new TypeError(
338
- "Tileflow Static Maps apiUrl must be HTTP(S) without credentials, query, or fragment"
339
- );
340
- }
341
- return url.toString().replace(/\/+$/, "");
342
- }
343
- function normalizeStaticMapEndpointUrl(value) {
344
- if (value.startsWith("/")) {
345
- if (value.startsWith("//") || value.length > 2048 || /[\\?#]/u.test(value) || hasControlCharacter(value)) {
346
- throw new TypeError(
347
- "Tileflow Static Maps createUrl must be HTTP(S) without credentials, query, or fragment or a safe root-relative path"
348
- );
349
- }
350
- return value;
351
- }
352
- const url = new URL(value);
353
- if (!isSafeHttpUrl(value) || url.search) {
354
- throw new TypeError(
355
- "Tileflow Static Maps createUrl must be HTTP(S) without credentials, query, or fragment or a safe root-relative path"
356
- );
357
- }
358
- return url.toString();
359
- }
360
- function hasControlCharacter(value) {
361
- for (let index = 0; index < value.length; index += 1) {
362
- const codePoint = value.charCodeAt(index);
363
- if (codePoint <= 31 || codePoint === 127) return true;
364
- }
365
- return false;
366
- }
367
-
368
- export {
369
- STATIC_MAP_RESULT_MEDIA_TYPE,
370
- staticMapAttributionEntrySchema,
371
- staticMapAttributionResultSchema,
372
- staticMapHostedResultSchema,
373
- staticMapProcessingResultSchema,
374
- validateStaticMapIdempotencyKey,
375
- createStaticMapIdempotencyKey,
376
- prepareStaticMapRequest,
377
- createStaticMap,
378
- precacheStaticMap,
379
- requestStaticMapUntilReady
380
- };