@tileflow/static 0.1.0-alpha.3 → 0.1.0-alpha.30

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/index.js DELETED
@@ -1,396 +0,0 @@
1
- // src/index.ts
2
- import { z } from "zod";
3
- var staticSceneSchemaVersion = 1;
4
- var staticRendererSchemaVersion = 1;
5
- var staticSceneLimits = {
6
- maxDimension: 1280,
7
- maxGeoJsonBytes: 96e3,
8
- maxOverlays: 24,
9
- maxPathCoordinates: 2e3,
10
- maxPhysicalPixels: 1280 * 1280,
11
- minDimension: 64
12
- };
13
- var coordinateSchema = z.tuple([z.number().finite(), z.number().finite()]).refine(([lng, lat]) => lng >= -180 && lng <= 180 && lat >= -90 && lat <= 90, {
14
- message: "Expected [lng, lat] within world bounds"
15
- });
16
- var colorSchema = z.string().regex(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, {
17
- message: "Expected a hex color like #C6A15B"
18
- });
19
- var sizeSchema = z.object({
20
- dpr: z.literal(1).optional(),
21
- height: z.number().int().min(staticSceneLimits.minDimension).max(staticSceneLimits.maxDimension),
22
- width: z.number().int().min(staticSceneLimits.minDimension).max(staticSceneLimits.maxDimension)
23
- }).refine(
24
- (size) => size.width * size.height * (size.dpr ?? 1) <= staticSceneLimits.maxPhysicalPixels,
25
- {
26
- message: "Static map exceeds the maximum render pixel budget"
27
- }
28
- );
29
- var centerCameraSchema = z.object({
30
- bearing: z.number().finite().min(-180).max(180).optional(),
31
- center: coordinateSchema,
32
- type: z.literal("center"),
33
- zoom: z.number().finite().min(0).max(22)
34
- });
35
- var boundsCameraSchema = z.object({
36
- bearing: z.number().finite().min(-180).max(180).optional(),
37
- bounds: z.tuple([z.number().finite(), z.number().finite(), z.number().finite(), z.number().finite()]).refine(
38
- ([west, south, east, north]) => west >= -180 && west <= 180 && east >= -180 && east <= 180 && south >= -90 && south <= 90 && north >= -90 && north <= 90 && west !== east && south !== north,
39
- { message: "Expected bounds as [west, south, east, north]" }
40
- ),
41
- padding: z.number().int().min(0).max(256).optional(),
42
- type: z.literal("bounds")
43
- }).refine((camera) => camera.bounds[3] > camera.bounds[1], {
44
- message: "Bounds north must be greater than south"
45
- });
46
- var lineOverlaySchema = z.object({
47
- color: colorSchema.default("#C6A15B"),
48
- coordinates: z.array(coordinateSchema).min(2).max(staticSceneLimits.maxPathCoordinates),
49
- id: z.string().trim().min(1).max(64).optional(),
50
- opacity: z.number().finite().min(0).max(1).default(1),
51
- type: z.literal("line"),
52
- width: z.number().finite().min(0.5).max(32).default(4)
53
- });
54
- var circleOverlaySchema = z.object({
55
- color: colorSchema.default("#C6A15B"),
56
- coordinate: coordinateSchema,
57
- id: z.string().trim().min(1).max(64).optional(),
58
- opacity: z.number().finite().min(0).max(1).default(1),
59
- radius: z.number().finite().min(1).max(64).default(6),
60
- strokeColor: colorSchema.optional(),
61
- strokeWidth: z.number().finite().min(0).max(16).default(0),
62
- type: z.literal("circle")
63
- });
64
- var markerOverlaySchema = z.object({
65
- color: colorSchema.default("#C6A15B"),
66
- coordinate: coordinateSchema,
67
- id: z.string().trim().min(1).max(64).optional(),
68
- radius: z.number().finite().min(2).max(64).default(8),
69
- strokeColor: colorSchema.default("#ffffff"),
70
- strokeWidth: z.number().finite().min(0).max(16).default(2),
71
- type: z.literal("marker")
72
- });
73
- var polygonOverlaySchema = z.object({
74
- coordinates: z.array(z.array(coordinateSchema).min(4).max(staticSceneLimits.maxPathCoordinates)).min(1).max(16),
75
- fill: colorSchema.default("#C6A15B"),
76
- id: z.string().trim().min(1).max(64).optional(),
77
- opacity: z.number().finite().min(0).max(1).default(0.28),
78
- stroke: colorSchema.optional(),
79
- strokeWidth: z.number().finite().min(0).max(16).default(0),
80
- type: z.literal("polygon")
81
- });
82
- var staticOverlaySchema = z.discriminatedUnion("type", [
83
- lineOverlaySchema,
84
- circleOverlaySchema,
85
- markerOverlaySchema,
86
- polygonOverlaySchema
87
- ]);
88
- var staticSceneSchema = z.object({
89
- camera: z.discriminatedUnion("type", [centerCameraSchema, boundsCameraSchema]),
90
- map: z.string().trim().min(1).max(128),
91
- overlays: z.array(staticOverlaySchema).max(staticSceneLimits.maxOverlays).default([]),
92
- size: sizeSchema
93
- });
94
- var staticRenderManifestSchema = z.object({
95
- mapId: z.string().trim().min(1).max(128),
96
- rendererVersion: z.string().trim().min(1).max(64),
97
- schemaVersion: z.literal(staticRendererSchemaVersion),
98
- scene: staticSceneSchema,
99
- styleId: z.string().trim().min(1).max(128).optional(),
100
- styleRevision: z.string().trim().min(1).max(128),
101
- styleUrl: z.string().trim().url().max(512).refine((value) => /^https?:\/\//.test(value), {
102
- message: "Expected an http(s) style URL"
103
- })
104
- });
105
- function line(input) {
106
- return normalizeOverlay({ ...input, type: "line" });
107
- }
108
- function circle(input) {
109
- return normalizeOverlay({ ...input, type: "circle" });
110
- }
111
- function marker(input) {
112
- return normalizeOverlay({ ...input, type: "marker" });
113
- }
114
- function polygon(input) {
115
- return normalizeOverlay({ ...input, type: "polygon" });
116
- }
117
- function validateStaticScene(input) {
118
- const parsed = staticSceneSchema.safeParse(input);
119
- if (!parsed.success) {
120
- return {
121
- error: parsed.error.issues.map((issue) => `${issue.path.join(".") || "scene"}: ${issue.message}`).join("; "),
122
- ok: false
123
- };
124
- }
125
- if (jsonByteLength(parsed.data.overlays) > staticSceneLimits.maxGeoJsonBytes) {
126
- return {
127
- error: `overlays exceed ${staticSceneLimits.maxGeoJsonBytes} bytes`,
128
- ok: false
129
- };
130
- }
131
- return { ok: true, scene: normalizeStaticScene(parsed.data) };
132
- }
133
- function validateStaticRenderManifest(input) {
134
- const parsed = staticRenderManifestSchema.safeParse(input);
135
- if (!parsed.success) {
136
- return {
137
- error: parsed.error.issues.map((issue) => `${issue.path.join(".") || "manifest"}: ${issue.message}`).join("; "),
138
- ok: false
139
- };
140
- }
141
- const sceneValidation = validateStaticScene(parsed.data.scene);
142
- if (!sceneValidation.ok) {
143
- return sceneValidation;
144
- }
145
- return {
146
- manifest: {
147
- ...parsed.data,
148
- scene: sceneValidation.scene
149
- },
150
- ok: true
151
- };
152
- }
153
- function normalizeStaticScene(scene) {
154
- const parsed = staticSceneSchema.parse(scene);
155
- return stripUndefined({
156
- camera: parsed.camera.type === "center" ? {
157
- bearing: roundNumber(parsed.camera.bearing ?? 0),
158
- center: normalizeCoordinate(parsed.camera.center),
159
- type: "center",
160
- zoom: roundNumber(parsed.camera.zoom)
161
- } : {
162
- bearing: roundNumber(parsed.camera.bearing ?? 0),
163
- bounds: parsed.camera.bounds.map(roundNumber),
164
- padding: parsed.camera.padding ?? 32,
165
- type: "bounds"
166
- },
167
- map: parsed.map,
168
- overlays: parsed.overlays.map(
169
- (overlay, index) => normalizeOverlay({
170
- ...overlay,
171
- id: overlay.id ?? `overlay-${index + 1}`
172
- })
173
- ),
174
- size: {
175
- dpr: parsed.size.dpr ?? 1,
176
- height: parsed.size.height,
177
- width: parsed.size.width
178
- }
179
- });
180
- }
181
- function createRenderManifest(input) {
182
- return staticRenderManifestSchema.parse(
183
- stripUndefined({
184
- mapId: input.mapId,
185
- rendererVersion: input.rendererVersion,
186
- schemaVersion: staticRendererSchemaVersion,
187
- scene: normalizeStaticScene({
188
- ...input.scene,
189
- map: input.mapId
190
- }),
191
- styleId: input.styleId,
192
- styleRevision: input.styleRevision,
193
- styleUrl: input.styleUrl
194
- })
195
- );
196
- }
197
- async function hashRenderManifest(manifest) {
198
- const normalized = staticRenderManifestSchema.parse({
199
- ...manifest,
200
- scene: normalizeStaticScene(manifest.scene)
201
- });
202
- const bytes = new TextEncoder().encode(stableStringify(normalized));
203
- const digest = await crypto.subtle.digest("SHA-256", bytes);
204
- return base64Url(new Uint8Array(digest));
205
- }
206
- function compileStaticOverlays(overlays) {
207
- const sources = {};
208
- const layers = [];
209
- for (const [index, overlay] of overlays.entries()) {
210
- const id = safeLayerId(`overlay-${index + 1}-${overlay.id ?? overlay.type}`);
211
- const sourceId = `${id}-source`;
212
- if (overlay.type === "line") {
213
- sources[sourceId] = {
214
- data: feature("LineString", overlay.coordinates),
215
- type: "geojson"
216
- };
217
- layers.push({
218
- id,
219
- layout: { "line-cap": "round", "line-join": "round" },
220
- paint: {
221
- "line-color": overlay.color,
222
- "line-opacity": overlay.opacity,
223
- "line-width": overlay.width
224
- },
225
- source: sourceId,
226
- type: "line"
227
- });
228
- continue;
229
- }
230
- if (overlay.type === "polygon") {
231
- sources[sourceId] = {
232
- data: feature("Polygon", overlay.coordinates),
233
- type: "geojson"
234
- };
235
- layers.push({
236
- id,
237
- paint: {
238
- "fill-color": overlay.fill,
239
- "fill-opacity": overlay.opacity
240
- },
241
- source: sourceId,
242
- type: "fill"
243
- });
244
- if (overlay.stroke && overlay.strokeWidth > 0) {
245
- layers.push({
246
- id: `${id}-stroke`,
247
- layout: { "line-cap": "round", "line-join": "round" },
248
- paint: {
249
- "line-color": overlay.stroke,
250
- "line-width": overlay.strokeWidth
251
- },
252
- source: sourceId,
253
- type: "line"
254
- });
255
- }
256
- continue;
257
- }
258
- sources[sourceId] = {
259
- data: feature("Point", overlay.coordinate),
260
- type: "geojson"
261
- };
262
- layers.push({
263
- id,
264
- paint: {
265
- "circle-color": overlay.color,
266
- "circle-opacity": overlay.type === "circle" ? overlay.opacity : 1,
267
- "circle-radius": overlay.radius,
268
- "circle-stroke-color": overlay.strokeColor ?? overlay.color,
269
- "circle-stroke-width": overlay.strokeWidth
270
- },
271
- source: sourceId,
272
- type: "circle"
273
- });
274
- }
275
- return { layers, sources };
276
- }
277
- async function createStaticMap(scene, options = {}) {
278
- return requestStaticMap(scene, options, "/v1/static/maps");
279
- }
280
- async function precacheStaticMap(scene, options = {}) {
281
- return requestStaticMap(scene, options, "/v1/static/maps/precache");
282
- }
283
- async function requestStaticMap(scene, options, path) {
284
- const validation = validateStaticScene(scene);
285
- if (!validation.ok) {
286
- throw new Error(`Invalid Tileflow static scene: ${validation.error}`);
287
- }
288
- const fetcher = options.fetch ?? fetch;
289
- const apiUrl = normalizeUrl(options.apiUrl ?? "https://api.tileflow.dev");
290
- const headers = {
291
- "Content-Type": "application/json"
292
- };
293
- if (options.apiKey) {
294
- headers.Authorization = `Bearer ${options.apiKey}`;
295
- }
296
- const response = await fetcher(`${apiUrl}${path}`, {
297
- body: JSON.stringify(validation.scene),
298
- headers,
299
- method: "POST"
300
- });
301
- if (!response.ok) {
302
- const error = await response.text();
303
- throw new Error(`Tileflow static map failed: ${response.status} ${error}`);
304
- }
305
- return await response.json();
306
- }
307
- function stableStringify(value) {
308
- return JSON.stringify(sortJson(value));
309
- }
310
- function normalizeOverlay(overlay) {
311
- const parsed = staticOverlaySchema.parse(overlay);
312
- const normalized = stripUndefined({ ...parsed });
313
- if ("coordinate" in normalized) {
314
- normalized.coordinate = normalizeCoordinate(normalized.coordinate);
315
- }
316
- if ("coordinates" in normalized) {
317
- normalized.coordinates = normalizeCoordinates(normalized.coordinates);
318
- }
319
- return normalized;
320
- }
321
- function normalizeCoordinates(value) {
322
- if (!Array.isArray(value)) {
323
- return value;
324
- }
325
- if (value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number") {
326
- return normalizeCoordinate(value);
327
- }
328
- return value.map(normalizeCoordinates);
329
- }
330
- function normalizeCoordinate(coordinate) {
331
- return [roundNumber(coordinate[0]), roundNumber(coordinate[1])];
332
- }
333
- function roundNumber(value) {
334
- return Number(value.toFixed(6));
335
- }
336
- function stripUndefined(value) {
337
- if (!value || typeof value !== "object" || Array.isArray(value)) {
338
- return value;
339
- }
340
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
341
- }
342
- function sortJson(value) {
343
- if (Array.isArray(value)) {
344
- return value.map(sortJson);
345
- }
346
- if (value && typeof value === "object") {
347
- return Object.fromEntries(
348
- Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, sortJson(entry)])
349
- );
350
- }
351
- return value;
352
- }
353
- function feature(type, coordinates) {
354
- return {
355
- geometry: { coordinates, type },
356
- properties: {},
357
- type: "Feature"
358
- };
359
- }
360
- function safeLayerId(value) {
361
- return value.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 80);
362
- }
363
- function jsonByteLength(value) {
364
- return new TextEncoder().encode(JSON.stringify(value)).length;
365
- }
366
- function base64Url(bytes) {
367
- let binary = "";
368
- for (const byte of bytes) {
369
- binary += String.fromCharCode(byte);
370
- }
371
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
372
- }
373
- function normalizeUrl(value) {
374
- return value.replace(/\/+$/, "");
375
- }
376
- export {
377
- circle,
378
- compileStaticOverlays,
379
- createRenderManifest,
380
- createStaticMap,
381
- hashRenderManifest,
382
- line,
383
- marker,
384
- normalizeStaticScene,
385
- polygon,
386
- precacheStaticMap,
387
- stableStringify,
388
- staticOverlaySchema,
389
- staticRenderManifestSchema,
390
- staticRendererSchemaVersion,
391
- staticSceneLimits,
392
- staticSceneSchema,
393
- staticSceneSchemaVersion,
394
- validateStaticRenderManifest,
395
- validateStaticScene
396
- };