@india-boundary-corrector/tilefixer 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2580 @@
1
+ // ../../node_modules/fflate/esm/browser.js
2
+ var u8 = Uint8Array;
3
+ var u16 = Uint16Array;
4
+ var i32 = Int32Array;
5
+ var fleb = new u8([
6
+ 0,
7
+ 0,
8
+ 0,
9
+ 0,
10
+ 0,
11
+ 0,
12
+ 0,
13
+ 0,
14
+ 1,
15
+ 1,
16
+ 1,
17
+ 1,
18
+ 2,
19
+ 2,
20
+ 2,
21
+ 2,
22
+ 3,
23
+ 3,
24
+ 3,
25
+ 3,
26
+ 4,
27
+ 4,
28
+ 4,
29
+ 4,
30
+ 5,
31
+ 5,
32
+ 5,
33
+ 5,
34
+ 0,
35
+ /* unused */
36
+ 0,
37
+ 0,
38
+ /* impossible */
39
+ 0
40
+ ]);
41
+ var fdeb = new u8([
42
+ 0,
43
+ 0,
44
+ 0,
45
+ 0,
46
+ 1,
47
+ 1,
48
+ 2,
49
+ 2,
50
+ 3,
51
+ 3,
52
+ 4,
53
+ 4,
54
+ 5,
55
+ 5,
56
+ 6,
57
+ 6,
58
+ 7,
59
+ 7,
60
+ 8,
61
+ 8,
62
+ 9,
63
+ 9,
64
+ 10,
65
+ 10,
66
+ 11,
67
+ 11,
68
+ 12,
69
+ 12,
70
+ 13,
71
+ 13,
72
+ /* unused */
73
+ 0,
74
+ 0
75
+ ]);
76
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
77
+ var freb = function(eb, start) {
78
+ var b2 = new u16(31);
79
+ for (var i = 0; i < 31; ++i) {
80
+ b2[i] = start += 1 << eb[i - 1];
81
+ }
82
+ var r = new i32(b2[30]);
83
+ for (var i = 1; i < 30; ++i) {
84
+ for (var j2 = b2[i]; j2 < b2[i + 1]; ++j2) {
85
+ r[j2] = j2 - b2[i] << 5 | i;
86
+ }
87
+ }
88
+ return { b: b2, r };
89
+ };
90
+ var _a = freb(fleb, 2);
91
+ var fl = _a.b;
92
+ var revfl = _a.r;
93
+ fl[28] = 258, revfl[258] = 28;
94
+ var _b = freb(fdeb, 0);
95
+ var fd = _b.b;
96
+ var revfd = _b.r;
97
+ var rev = new u16(32768);
98
+ for (i = 0; i < 32768; ++i) {
99
+ x2 = (i & 43690) >> 1 | (i & 21845) << 1;
100
+ x2 = (x2 & 52428) >> 2 | (x2 & 13107) << 2;
101
+ x2 = (x2 & 61680) >> 4 | (x2 & 3855) << 4;
102
+ rev[i] = ((x2 & 65280) >> 8 | (x2 & 255) << 8) >> 1;
103
+ }
104
+ var x2;
105
+ var i;
106
+ var hMap = (function(cd, mb, r) {
107
+ var s = cd.length;
108
+ var i = 0;
109
+ var l2 = new u16(mb);
110
+ for (; i < s; ++i) {
111
+ if (cd[i])
112
+ ++l2[cd[i] - 1];
113
+ }
114
+ var le = new u16(mb);
115
+ for (i = 1; i < mb; ++i) {
116
+ le[i] = le[i - 1] + l2[i - 1] << 1;
117
+ }
118
+ var co;
119
+ if (r) {
120
+ co = new u16(1 << mb);
121
+ var rvb = 15 - mb;
122
+ for (i = 0; i < s; ++i) {
123
+ if (cd[i]) {
124
+ var sv = i << 4 | cd[i];
125
+ var r_1 = mb - cd[i];
126
+ var v2 = le[cd[i] - 1]++ << r_1;
127
+ for (var m2 = v2 | (1 << r_1) - 1; v2 <= m2; ++v2) {
128
+ co[rev[v2] >> rvb] = sv;
129
+ }
130
+ }
131
+ }
132
+ } else {
133
+ co = new u16(s);
134
+ for (i = 0; i < s; ++i) {
135
+ if (cd[i]) {
136
+ co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
137
+ }
138
+ }
139
+ }
140
+ return co;
141
+ });
142
+ var flt = new u8(288);
143
+ for (i = 0; i < 144; ++i)
144
+ flt[i] = 8;
145
+ var i;
146
+ for (i = 144; i < 256; ++i)
147
+ flt[i] = 9;
148
+ var i;
149
+ for (i = 256; i < 280; ++i)
150
+ flt[i] = 7;
151
+ var i;
152
+ for (i = 280; i < 288; ++i)
153
+ flt[i] = 8;
154
+ var i;
155
+ var fdt = new u8(32);
156
+ for (i = 0; i < 32; ++i)
157
+ fdt[i] = 5;
158
+ var i;
159
+ var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
160
+ var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
161
+ var max = function(a) {
162
+ var m2 = a[0];
163
+ for (var i = 1; i < a.length; ++i) {
164
+ if (a[i] > m2)
165
+ m2 = a[i];
166
+ }
167
+ return m2;
168
+ };
169
+ var bits = function(d, p, m2) {
170
+ var o = p / 8 | 0;
171
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m2;
172
+ };
173
+ var bits16 = function(d, p) {
174
+ var o = p / 8 | 0;
175
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
176
+ };
177
+ var shft = function(p) {
178
+ return (p + 7) / 8 | 0;
179
+ };
180
+ var slc = function(v2, s, e) {
181
+ if (s == null || s < 0)
182
+ s = 0;
183
+ if (e == null || e > v2.length)
184
+ e = v2.length;
185
+ return new u8(v2.subarray(s, e));
186
+ };
187
+ var ec = [
188
+ "unexpected EOF",
189
+ "invalid block type",
190
+ "invalid length/literal",
191
+ "invalid distance",
192
+ "stream finished",
193
+ "no stream handler",
194
+ ,
195
+ "no callback",
196
+ "invalid UTF-8 data",
197
+ "extra field too long",
198
+ "date not in range 1980-2099",
199
+ "filename too long",
200
+ "stream finishing",
201
+ "invalid zip data"
202
+ // determined by unknown compression method
203
+ ];
204
+ var err = function(ind, msg, nt) {
205
+ var e = new Error(msg || ec[ind]);
206
+ e.code = ind;
207
+ if (Error.captureStackTrace)
208
+ Error.captureStackTrace(e, err);
209
+ if (!nt)
210
+ throw e;
211
+ return e;
212
+ };
213
+ var inflt = function(dat, st, buf, dict) {
214
+ var sl = dat.length, dl = dict ? dict.length : 0;
215
+ if (!sl || st.f && !st.l)
216
+ return buf || new u8(0);
217
+ var noBuf = !buf;
218
+ var resize = noBuf || st.i != 2;
219
+ var noSt = st.i;
220
+ if (noBuf)
221
+ buf = new u8(sl * 3);
222
+ var cbuf = function(l3) {
223
+ var bl = buf.length;
224
+ if (l3 > bl) {
225
+ var nbuf = new u8(Math.max(bl * 2, l3));
226
+ nbuf.set(buf);
227
+ buf = nbuf;
228
+ }
229
+ };
230
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
231
+ var tbts = sl * 8;
232
+ do {
233
+ if (!lm) {
234
+ final = bits(dat, pos, 1);
235
+ var type = bits(dat, pos + 1, 3);
236
+ pos += 3;
237
+ if (!type) {
238
+ var s = shft(pos) + 4, l2 = dat[s - 4] | dat[s - 3] << 8, t = s + l2;
239
+ if (t > sl) {
240
+ if (noSt)
241
+ err(0);
242
+ break;
243
+ }
244
+ if (resize)
245
+ cbuf(bt + l2);
246
+ buf.set(dat.subarray(s, t), bt);
247
+ st.b = bt += l2, st.p = pos = t * 8, st.f = final;
248
+ continue;
249
+ } else if (type == 1)
250
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
251
+ else if (type == 2) {
252
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
253
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
254
+ pos += 14;
255
+ var ldt = new u8(tl);
256
+ var clt = new u8(19);
257
+ for (var i = 0; i < hcLen; ++i) {
258
+ clt[clim[i]] = bits(dat, pos + i * 3, 7);
259
+ }
260
+ pos += hcLen * 3;
261
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
262
+ var clm = hMap(clt, clb, 1);
263
+ for (var i = 0; i < tl; ) {
264
+ var r = clm[bits(dat, pos, clbmsk)];
265
+ pos += r & 15;
266
+ var s = r >> 4;
267
+ if (s < 16) {
268
+ ldt[i++] = s;
269
+ } else {
270
+ var c = 0, n = 0;
271
+ if (s == 16)
272
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
273
+ else if (s == 17)
274
+ n = 3 + bits(dat, pos, 7), pos += 3;
275
+ else if (s == 18)
276
+ n = 11 + bits(dat, pos, 127), pos += 7;
277
+ while (n--)
278
+ ldt[i++] = c;
279
+ }
280
+ }
281
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
282
+ lbt = max(lt);
283
+ dbt = max(dt);
284
+ lm = hMap(lt, lbt, 1);
285
+ dm = hMap(dt, dbt, 1);
286
+ } else
287
+ err(1);
288
+ if (pos > tbts) {
289
+ if (noSt)
290
+ err(0);
291
+ break;
292
+ }
293
+ }
294
+ if (resize)
295
+ cbuf(bt + 131072);
296
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
297
+ var lpos = pos;
298
+ for (; ; lpos = pos) {
299
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
300
+ pos += c & 15;
301
+ if (pos > tbts) {
302
+ if (noSt)
303
+ err(0);
304
+ break;
305
+ }
306
+ if (!c)
307
+ err(2);
308
+ if (sym < 256)
309
+ buf[bt++] = sym;
310
+ else if (sym == 256) {
311
+ lpos = pos, lm = null;
312
+ break;
313
+ } else {
314
+ var add = sym - 254;
315
+ if (sym > 264) {
316
+ var i = sym - 257, b2 = fleb[i];
317
+ add = bits(dat, pos, (1 << b2) - 1) + fl[i];
318
+ pos += b2;
319
+ }
320
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
321
+ if (!d)
322
+ err(3);
323
+ pos += d & 15;
324
+ var dt = fd[dsym];
325
+ if (dsym > 3) {
326
+ var b2 = fdeb[dsym];
327
+ dt += bits16(dat, pos) & (1 << b2) - 1, pos += b2;
328
+ }
329
+ if (pos > tbts) {
330
+ if (noSt)
331
+ err(0);
332
+ break;
333
+ }
334
+ if (resize)
335
+ cbuf(bt + 131072);
336
+ var end = bt + add;
337
+ if (bt < dt) {
338
+ var shift = dl - dt, dend = Math.min(dt, end);
339
+ if (shift + bt < 0)
340
+ err(3);
341
+ for (; bt < dend; ++bt)
342
+ buf[bt] = dict[shift + bt];
343
+ }
344
+ for (; bt < end; ++bt)
345
+ buf[bt] = buf[bt - dt];
346
+ }
347
+ }
348
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
349
+ if (lm)
350
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
351
+ } while (!final);
352
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
353
+ };
354
+ var et = /* @__PURE__ */ new u8(0);
355
+ var gzs = function(d) {
356
+ if (d[0] != 31 || d[1] != 139 || d[2] != 8)
357
+ err(6, "invalid gzip data");
358
+ var flg = d[3];
359
+ var st = 10;
360
+ if (flg & 4)
361
+ st += (d[10] | d[11] << 8) + 2;
362
+ for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
363
+ ;
364
+ return st + (flg & 2);
365
+ };
366
+ var gzl = function(d) {
367
+ var l2 = d.length;
368
+ return (d[l2 - 4] | d[l2 - 3] << 8 | d[l2 - 2] << 16 | d[l2 - 1] << 24) >>> 0;
369
+ };
370
+ var zls = function(d, dict) {
371
+ if ((d[0] & 15) != 8 || d[0] >> 4 > 7 || (d[0] << 8 | d[1]) % 31)
372
+ err(6, "invalid zlib data");
373
+ if ((d[1] >> 5 & 1) == +!dict)
374
+ err(6, "invalid zlib data: " + (d[1] & 32 ? "need" : "unexpected") + " dictionary");
375
+ return (d[1] >> 3 & 4) + 2;
376
+ };
377
+ function inflateSync(data, opts) {
378
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
379
+ }
380
+ function gunzipSync(data, opts) {
381
+ var st = gzs(data);
382
+ if (st + 8 > data.length)
383
+ err(6, "invalid gzip data");
384
+ return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
385
+ }
386
+ function unzlibSync(data, opts) {
387
+ return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
388
+ }
389
+ function decompressSync(data, opts) {
390
+ return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
391
+ }
392
+ var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
393
+ var tds = 0;
394
+ try {
395
+ td.decode(et, { stream: true });
396
+ tds = 1;
397
+ } catch (e) {
398
+ }
399
+
400
+ // ../../node_modules/pmtiles/dist/esm/index.js
401
+ var z = Object.defineProperty;
402
+ var b = Math.pow;
403
+ var l = (i, e) => z(i, "name", { value: e, configurable: true });
404
+ var m = (i, e, t) => new Promise((r, n) => {
405
+ var s = (u) => {
406
+ try {
407
+ a(t.next(u));
408
+ } catch (c) {
409
+ n(c);
410
+ }
411
+ }, o = (u) => {
412
+ try {
413
+ a(t.throw(u));
414
+ } catch (c) {
415
+ n(c);
416
+ }
417
+ }, a = (u) => u.done ? r(u.value) : Promise.resolve(u.value).then(s, o);
418
+ a((t = t.apply(i, e)).next());
419
+ });
420
+ var re = l((i, e) => {
421
+ let t = false, r = "", n = L.GridLayer.extend({ createTile: l((s, o) => {
422
+ let a = document.createElement("img"), u = new AbortController(), c = u.signal;
423
+ return a.cancel = () => {
424
+ u.abort();
425
+ }, t || (i.getHeader().then((d) => {
426
+ d.tileType === 1 ? console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details.") : d.tileType === 2 ? r = "image/png" : d.tileType === 3 ? r = "image/jpeg" : d.tileType === 4 ? r = "image/webp" : d.tileType === 5 && (r = "image/avif");
427
+ }), t = true), i.getZxy(s.z, s.x, s.y, c).then((d) => {
428
+ if (d) {
429
+ let h = new Blob([d.data], { type: r }), p = window.URL.createObjectURL(h);
430
+ a.src = p, a.cancel = void 0, o(void 0, a);
431
+ }
432
+ }).catch((d) => {
433
+ if (d.name !== "AbortError") throw d;
434
+ }), a;
435
+ }, "createTile"), _removeTile: l(function(s) {
436
+ let o = this._tiles[s];
437
+ o && (o.el.cancel && o.el.cancel(), o.el.width = 0, o.el.height = 0, o.el.deleted = true, L.DomUtil.remove(o.el), delete this._tiles[s], this.fire("tileunload", { tile: o.el, coords: this._keyToTileCoords(s) }));
438
+ }, "_removeTile") });
439
+ return new n(e);
440
+ }, "leafletRasterLayer");
441
+ var j = l((i) => (e, t) => {
442
+ if (t instanceof AbortController) return i(e, t);
443
+ let r = new AbortController();
444
+ return i(e, r).then((n) => t(void 0, n.data, n.cacheControl || "", n.expires || ""), (n) => t(n)).catch((n) => t(n)), { cancel: l(() => r.abort(), "cancel") };
445
+ }, "v3compat");
446
+ var T = class T2 {
447
+ constructor(e) {
448
+ this.tilev4 = l((e2, t) => m(this, null, function* () {
449
+ if (e2.type === "json") {
450
+ let p = e2.url.substr(10), y = this.tiles.get(p);
451
+ if (y || (y = new x(p), this.tiles.set(p, y)), this.metadata) return { data: yield y.getTileJson(e2.url) };
452
+ let f = yield y.getHeader();
453
+ return (f.minLon >= f.maxLon || f.minLat >= f.maxLat) && console.error(`Bounds of PMTiles archive ${f.minLon},${f.minLat},${f.maxLon},${f.maxLat} are not valid.`), { data: { tiles: [`${e2.url}/{z}/{x}/{y}`], minzoom: f.minZoom, maxzoom: f.maxZoom, bounds: [f.minLon, f.minLat, f.maxLon, f.maxLat] } };
454
+ }
455
+ let r = new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/), n = e2.url.match(r);
456
+ if (!n) throw new Error("Invalid PMTiles protocol URL");
457
+ let s = n[1], o = this.tiles.get(s);
458
+ o || (o = new x(s), this.tiles.set(s, o));
459
+ let a = n[2], u = n[3], c = n[4], d = yield o.getHeader(), h = yield o == null ? void 0 : o.getZxy(+a, +u, +c, t.signal);
460
+ if (h) return { data: new Uint8Array(h.data), cacheControl: h.cacheControl, expires: h.expires };
461
+ if (d.tileType === 1) {
462
+ if (this.errorOnMissingTile) throw new Error("Tile not found.");
463
+ return { data: new Uint8Array() };
464
+ }
465
+ return { data: null };
466
+ }), "tilev4");
467
+ this.tile = j(this.tilev4);
468
+ this.tiles = /* @__PURE__ */ new Map(), this.metadata = (e == null ? void 0 : e.metadata) || false, this.errorOnMissingTile = (e == null ? void 0 : e.errorOnMissingTile) || false;
469
+ }
470
+ add(e) {
471
+ this.tiles.set(e.source.getKey(), e);
472
+ }
473
+ get(e) {
474
+ return this.tiles.get(e);
475
+ }
476
+ };
477
+ l(T, "Protocol");
478
+ function w(i, e) {
479
+ return (e >>> 0) * 4294967296 + (i >>> 0);
480
+ }
481
+ l(w, "toNum");
482
+ function F(i, e) {
483
+ let t = e.buf, r = t[e.pos++], n = (r & 112) >> 4;
484
+ if (r < 128 || (r = t[e.pos++], n |= (r & 127) << 3, r < 128) || (r = t[e.pos++], n |= (r & 127) << 10, r < 128) || (r = t[e.pos++], n |= (r & 127) << 17, r < 128) || (r = t[e.pos++], n |= (r & 127) << 24, r < 128) || (r = t[e.pos++], n |= (r & 1) << 31, r < 128)) return w(i, n);
485
+ throw new Error("Expected varint not more than 10 bytes");
486
+ }
487
+ l(F, "readVarintRemainder");
488
+ function v(i) {
489
+ let e = i.buf, t = e[i.pos++], r = t & 127;
490
+ return t < 128 || (t = e[i.pos++], r |= (t & 127) << 7, t < 128) || (t = e[i.pos++], r |= (t & 127) << 14, t < 128) || (t = e[i.pos++], r |= (t & 127) << 21, t < 128) ? r : (t = e[i.pos], r |= (t & 15) << 28, F(r, i));
491
+ }
492
+ l(v, "readVarint");
493
+ function k(i, e, t, r) {
494
+ if (r === 0) {
495
+ t === 1 && (e[0] = i - 1 - e[0], e[1] = i - 1 - e[1]);
496
+ let n = e[0];
497
+ e[0] = e[1], e[1] = n;
498
+ }
499
+ }
500
+ l(k, "rotate");
501
+ function N(i, e) {
502
+ let t = b(2, i), r = e, n = e, s = e, o = [0, 0], a = 1;
503
+ for (; a < t; ) r = 1 & s / 2, n = 1 & (s ^ r), k(a, o, r, n), o[0] += a * r, o[1] += a * n, s = s / 4, a *= 2;
504
+ return [i, o[0], o[1]];
505
+ }
506
+ l(N, "idOnLevel");
507
+ var q = [0, 1, 5, 21, 85, 341, 1365, 5461, 21845, 87381, 349525, 1398101, 5592405, 22369621, 89478485, 357913941, 1431655765, 5726623061, 22906492245, 91625968981, 366503875925, 1466015503701, 5864062014805, 23456248059221, 93824992236885, 375299968947541, 1501199875790165];
508
+ function G(i, e, t) {
509
+ if (i > 26) throw new Error("Tile zoom level exceeds max safe number limit (26)");
510
+ if (e > b(2, i) - 1 || t > b(2, i) - 1) throw new Error("tile x/y outside zoom level bounds");
511
+ let r = q[i], n = b(2, i), s = 0, o = 0, a = 0, u = [e, t], c = n / 2;
512
+ for (; c > 0; ) s = (u[0] & c) > 0 ? 1 : 0, o = (u[1] & c) > 0 ? 1 : 0, a += c * c * (3 * s ^ o), k(c, u, s, o), c = c / 2;
513
+ return r + a;
514
+ }
515
+ l(G, "zxyToTileId");
516
+ function ie(i) {
517
+ let e = 0, t = 0;
518
+ for (let r = 0; r < 27; r++) {
519
+ let n = (1 << r) * (1 << r);
520
+ if (e + n > i) return N(r, i - e);
521
+ e += n;
522
+ }
523
+ throw new Error("Tile zoom level exceeds max safe number limit (26)");
524
+ }
525
+ l(ie, "tileIdToZxy");
526
+ var J = ((s) => (s[s.Unknown = 0] = "Unknown", s[s.None = 1] = "None", s[s.Gzip = 2] = "Gzip", s[s.Brotli = 3] = "Brotli", s[s.Zstd = 4] = "Zstd", s))(J || {});
527
+ function D(i, e) {
528
+ return m(this, null, function* () {
529
+ if (e === 1 || e === 0) return i;
530
+ if (e === 2) {
531
+ if (typeof globalThis.DecompressionStream == "undefined") return decompressSync(new Uint8Array(i));
532
+ let t = new Response(i).body;
533
+ if (!t) throw new Error("Failed to read response stream");
534
+ let r = t.pipeThrough(new globalThis.DecompressionStream("gzip"));
535
+ return new Response(r).arrayBuffer();
536
+ }
537
+ throw new Error("Compression method not supported");
538
+ });
539
+ }
540
+ l(D, "defaultDecompress");
541
+ var O = ((o) => (o[o.Unknown = 0] = "Unknown", o[o.Mvt = 1] = "Mvt", o[o.Png = 2] = "Png", o[o.Jpeg = 3] = "Jpeg", o[o.Webp = 4] = "Webp", o[o.Avif = 5] = "Avif", o))(O || {});
542
+ function _(i) {
543
+ return i === 1 ? ".mvt" : i === 2 ? ".png" : i === 3 ? ".jpg" : i === 4 ? ".webp" : i === 5 ? ".avif" : "";
544
+ }
545
+ l(_, "tileTypeExt");
546
+ var Y = 127;
547
+ function Q(i, e) {
548
+ let t = 0, r = i.length - 1;
549
+ for (; t <= r; ) {
550
+ let n = r + t >> 1, s = e - i[n].tileId;
551
+ if (s > 0) t = n + 1;
552
+ else if (s < 0) r = n - 1;
553
+ else return i[n];
554
+ }
555
+ return r >= 0 && (i[r].runLength === 0 || e - i[r].tileId < i[r].runLength) ? i[r] : null;
556
+ }
557
+ l(Q, "findTile");
558
+ var A = class A2 {
559
+ constructor(e) {
560
+ this.file = e;
561
+ }
562
+ getKey() {
563
+ return this.file.name;
564
+ }
565
+ getBytes(e, t) {
566
+ return m(this, null, function* () {
567
+ return { data: yield this.file.slice(e, e + t).arrayBuffer() };
568
+ });
569
+ }
570
+ };
571
+ l(A, "FileSource");
572
+ var U = class U2 {
573
+ constructor(e, t = new Headers()) {
574
+ this.url = e, this.customHeaders = t, this.mustReload = false;
575
+ let r = "";
576
+ "navigator" in globalThis && (r = globalThis.navigator.userAgent || "");
577
+ let n = r.indexOf("Windows") > -1, s = /Chrome|Chromium|Edg|OPR|Brave/.test(r);
578
+ this.chromeWindowsNoCache = false, n && s && (this.chromeWindowsNoCache = true);
579
+ }
580
+ getKey() {
581
+ return this.url;
582
+ }
583
+ setHeaders(e) {
584
+ this.customHeaders = e;
585
+ }
586
+ getBytes(e, t, r, n) {
587
+ return m(this, null, function* () {
588
+ let s, o;
589
+ r ? o = r : (s = new AbortController(), o = s.signal);
590
+ let a = new Headers(this.customHeaders);
591
+ a.set("range", `bytes=${e}-${e + t - 1}`);
592
+ let u;
593
+ this.mustReload ? u = "reload" : this.chromeWindowsNoCache && (u = "no-store");
594
+ let c = yield fetch(this.url, { signal: o, cache: u, headers: a });
595
+ if (e === 0 && c.status === 416) {
596
+ let y = c.headers.get("Content-Range");
597
+ if (!y || !y.startsWith("bytes */")) throw new Error("Missing content-length on 416 response");
598
+ let f = +y.substr(8);
599
+ c = yield fetch(this.url, { signal: o, cache: "reload", headers: { range: `bytes=0-${f - 1}` } });
600
+ }
601
+ let d = c.headers.get("Etag");
602
+ if (d != null && d.startsWith("W/") && (d = null), c.status === 416 || n && d && d !== n) throw this.mustReload = true, new E(`Server returned non-matching ETag ${n} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);
603
+ if (c.status >= 300) throw new Error(`Bad response code: ${c.status}`);
604
+ let h = c.headers.get("Content-Length");
605
+ if (c.status === 200 && (!h || +h > t)) throw s && s.abort(), new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");
606
+ return { data: yield c.arrayBuffer(), etag: d || void 0, cacheControl: c.headers.get("Cache-Control") || void 0, expires: c.headers.get("Expires") || void 0 };
607
+ });
608
+ }
609
+ };
610
+ l(U, "FetchSource");
611
+ var C = U;
612
+ function g(i, e) {
613
+ let t = i.getUint32(e + 4, true), r = i.getUint32(e + 0, true);
614
+ return t * b(2, 32) + r;
615
+ }
616
+ l(g, "getUint64");
617
+ function X(i, e) {
618
+ let t = new DataView(i), r = t.getUint8(7);
619
+ if (r > 3) throw new Error(`Archive is spec version ${r} but this library supports up to spec version 3`);
620
+ return { specVersion: r, rootDirectoryOffset: g(t, 8), rootDirectoryLength: g(t, 16), jsonMetadataOffset: g(t, 24), jsonMetadataLength: g(t, 32), leafDirectoryOffset: g(t, 40), leafDirectoryLength: g(t, 48), tileDataOffset: g(t, 56), tileDataLength: g(t, 64), numAddressedTiles: g(t, 72), numTileEntries: g(t, 80), numTileContents: g(t, 88), clustered: t.getUint8(96) === 1, internalCompression: t.getUint8(97), tileCompression: t.getUint8(98), tileType: t.getUint8(99), minZoom: t.getUint8(100), maxZoom: t.getUint8(101), minLon: t.getInt32(102, true) / 1e7, minLat: t.getInt32(106, true) / 1e7, maxLon: t.getInt32(110, true) / 1e7, maxLat: t.getInt32(114, true) / 1e7, centerZoom: t.getUint8(118), centerLon: t.getInt32(119, true) / 1e7, centerLat: t.getInt32(123, true) / 1e7, etag: e };
621
+ }
622
+ l(X, "bytesToHeader");
623
+ function Z(i) {
624
+ let e = { buf: new Uint8Array(i), pos: 0 }, t = v(e), r = [], n = 0;
625
+ for (let s = 0; s < t; s++) {
626
+ let o = v(e);
627
+ r.push({ tileId: n + o, offset: 0, length: 0, runLength: 1 }), n += o;
628
+ }
629
+ for (let s = 0; s < t; s++) r[s].runLength = v(e);
630
+ for (let s = 0; s < t; s++) r[s].length = v(e);
631
+ for (let s = 0; s < t; s++) {
632
+ let o = v(e);
633
+ o === 0 && s > 0 ? r[s].offset = r[s - 1].offset + r[s - 1].length : r[s].offset = o - 1;
634
+ }
635
+ return r;
636
+ }
637
+ l(Z, "deserializeIndex");
638
+ var R = class R2 extends Error {
639
+ };
640
+ l(R, "EtagMismatch");
641
+ var E = R;
642
+ function K(i, e) {
643
+ return m(this, null, function* () {
644
+ let t = yield i.getBytes(0, 16384);
645
+ if (new DataView(t.data).getUint16(0, true) !== 19792) throw new Error("Wrong magic number for PMTiles archive");
646
+ let n = t.data.slice(0, Y), s = X(n, t.etag), o = t.data.slice(s.rootDirectoryOffset, s.rootDirectoryOffset + s.rootDirectoryLength), a = `${i.getKey()}|${s.etag || ""}|${s.rootDirectoryOffset}|${s.rootDirectoryLength}`, u = Z(yield e(o, s.internalCompression));
647
+ return [s, [a, u.length, u]];
648
+ });
649
+ }
650
+ l(K, "getHeaderAndRoot");
651
+ function I(i, e, t, r, n) {
652
+ return m(this, null, function* () {
653
+ let s = yield i.getBytes(t, r, void 0, n.etag), o = yield e(s.data, n.internalCompression), a = Z(o);
654
+ if (a.length === 0) throw new Error("Empty directory is invalid");
655
+ return a;
656
+ });
657
+ }
658
+ l(I, "getDirectory");
659
+ var H = class H2 {
660
+ constructor(e = 100, t = true, r = D) {
661
+ this.cache = /* @__PURE__ */ new Map(), this.maxCacheEntries = e, this.counter = 1, this.decompress = r;
662
+ }
663
+ getHeader(e) {
664
+ return m(this, null, function* () {
665
+ let t = e.getKey(), r = this.cache.get(t);
666
+ if (r) return r.lastUsed = this.counter++, r.data;
667
+ let n = yield K(e, this.decompress);
668
+ return n[1] && this.cache.set(n[1][0], { lastUsed: this.counter++, data: n[1][2] }), this.cache.set(t, { lastUsed: this.counter++, data: n[0] }), this.prune(), n[0];
669
+ });
670
+ }
671
+ getDirectory(e, t, r, n) {
672
+ return m(this, null, function* () {
673
+ let s = `${e.getKey()}|${n.etag || ""}|${t}|${r}`, o = this.cache.get(s);
674
+ if (o) return o.lastUsed = this.counter++, o.data;
675
+ let a = yield I(e, this.decompress, t, r, n);
676
+ return this.cache.set(s, { lastUsed: this.counter++, data: a }), this.prune(), a;
677
+ });
678
+ }
679
+ prune() {
680
+ if (this.cache.size > this.maxCacheEntries) {
681
+ let e = 1 / 0, t;
682
+ this.cache.forEach((r, n) => {
683
+ r.lastUsed < e && (e = r.lastUsed, t = n);
684
+ }), t && this.cache.delete(t);
685
+ }
686
+ }
687
+ invalidate(e) {
688
+ return m(this, null, function* () {
689
+ this.cache.delete(e.getKey());
690
+ });
691
+ }
692
+ };
693
+ l(H, "ResolvedValueCache");
694
+ var M = class M2 {
695
+ constructor(e = 100, t = true, r = D) {
696
+ this.cache = /* @__PURE__ */ new Map(), this.invalidations = /* @__PURE__ */ new Map(), this.maxCacheEntries = e, this.counter = 1, this.decompress = r;
697
+ }
698
+ getHeader(e) {
699
+ return m(this, null, function* () {
700
+ let t = e.getKey(), r = this.cache.get(t);
701
+ if (r) return r.lastUsed = this.counter++, yield r.data;
702
+ let n = new Promise((s, o) => {
703
+ K(e, this.decompress).then((a) => {
704
+ a[1] && this.cache.set(a[1][0], { lastUsed: this.counter++, data: Promise.resolve(a[1][2]) }), s(a[0]), this.prune();
705
+ }).catch((a) => {
706
+ o(a);
707
+ });
708
+ });
709
+ return this.cache.set(t, { lastUsed: this.counter++, data: n }), n;
710
+ });
711
+ }
712
+ getDirectory(e, t, r, n) {
713
+ return m(this, null, function* () {
714
+ let s = `${e.getKey()}|${n.etag || ""}|${t}|${r}`, o = this.cache.get(s);
715
+ if (o) return o.lastUsed = this.counter++, yield o.data;
716
+ let a = new Promise((u, c) => {
717
+ I(e, this.decompress, t, r, n).then((d) => {
718
+ u(d), this.prune();
719
+ }).catch((d) => {
720
+ c(d);
721
+ });
722
+ });
723
+ return this.cache.set(s, { lastUsed: this.counter++, data: a }), a;
724
+ });
725
+ }
726
+ prune() {
727
+ if (this.cache.size >= this.maxCacheEntries) {
728
+ let e = 1 / 0, t;
729
+ this.cache.forEach((r, n) => {
730
+ r.lastUsed < e && (e = r.lastUsed, t = n);
731
+ }), t && this.cache.delete(t);
732
+ }
733
+ }
734
+ invalidate(e) {
735
+ return m(this, null, function* () {
736
+ let t = e.getKey();
737
+ if (this.invalidations.get(t)) return yield this.invalidations.get(t);
738
+ this.cache.delete(e.getKey());
739
+ let r = new Promise((n, s) => {
740
+ this.getHeader(e).then((o) => {
741
+ n(), this.invalidations.delete(t);
742
+ }).catch((o) => {
743
+ s(o);
744
+ });
745
+ });
746
+ this.invalidations.set(t, r);
747
+ });
748
+ }
749
+ };
750
+ l(M, "SharedPromiseCache");
751
+ var P = M;
752
+ var B = class B2 {
753
+ constructor(e, t, r) {
754
+ typeof e == "string" ? this.source = new C(e) : this.source = e, r ? this.decompress = r : this.decompress = D, t ? this.cache = t : this.cache = new P();
755
+ }
756
+ getHeader() {
757
+ return m(this, null, function* () {
758
+ return yield this.cache.getHeader(this.source);
759
+ });
760
+ }
761
+ getZxyAttempt(e, t, r, n) {
762
+ return m(this, null, function* () {
763
+ let s = G(e, t, r), o = yield this.cache.getHeader(this.source);
764
+ if (e < o.minZoom || e > o.maxZoom) return;
765
+ let a = o.rootDirectoryOffset, u = o.rootDirectoryLength;
766
+ for (let c = 0; c <= 3; c++) {
767
+ let d = yield this.cache.getDirectory(this.source, a, u, o), h = Q(d, s);
768
+ if (h) {
769
+ if (h.runLength > 0) {
770
+ let p = yield this.source.getBytes(o.tileDataOffset + h.offset, h.length, n, o.etag);
771
+ return { data: yield this.decompress(p.data, o.tileCompression), cacheControl: p.cacheControl, expires: p.expires };
772
+ }
773
+ a = o.leafDirectoryOffset + h.offset, u = h.length;
774
+ } else return;
775
+ }
776
+ throw new Error("Maximum directory depth exceeded");
777
+ });
778
+ }
779
+ getZxy(e, t, r, n) {
780
+ return m(this, null, function* () {
781
+ try {
782
+ return yield this.getZxyAttempt(e, t, r, n);
783
+ } catch (s) {
784
+ if (s instanceof E) return this.cache.invalidate(this.source), yield this.getZxyAttempt(e, t, r, n);
785
+ throw s;
786
+ }
787
+ });
788
+ }
789
+ getMetadataAttempt() {
790
+ return m(this, null, function* () {
791
+ let e = yield this.cache.getHeader(this.source), t = yield this.source.getBytes(e.jsonMetadataOffset, e.jsonMetadataLength, void 0, e.etag), r = yield this.decompress(t.data, e.internalCompression), n = new TextDecoder("utf-8");
792
+ return JSON.parse(n.decode(r));
793
+ });
794
+ }
795
+ getMetadata() {
796
+ return m(this, null, function* () {
797
+ try {
798
+ return yield this.getMetadataAttempt();
799
+ } catch (e) {
800
+ if (e instanceof E) return this.cache.invalidate(this.source), yield this.getMetadataAttempt();
801
+ throw e;
802
+ }
803
+ });
804
+ }
805
+ getTileJson(e) {
806
+ return m(this, null, function* () {
807
+ let t = yield this.getHeader(), r = yield this.getMetadata(), n = _(t.tileType);
808
+ return { tilejson: "3.0.0", scheme: "xyz", tiles: [`${e}/{z}/{x}/{y}${n}`], vector_layers: r.vector_layers, attribution: r.attribution, description: r.description, name: r.name, version: r.version, bounds: [t.minLon, t.minLat, t.maxLon, t.maxLat], center: [t.centerLon, t.centerLat, t.centerZoom], minzoom: t.minZoom, maxzoom: t.maxZoom };
809
+ });
810
+ }
811
+ };
812
+ l(B, "PMTiles");
813
+ var x = B;
814
+
815
+ // ../../node_modules/@mapbox/point-geometry/index.js
816
+ function Point(x2, y) {
817
+ this.x = x2;
818
+ this.y = y;
819
+ }
820
+ Point.prototype = {
821
+ /**
822
+ * Clone this point, returning a new point that can be modified
823
+ * without affecting the old one.
824
+ * @return {Point} the clone
825
+ */
826
+ clone() {
827
+ return new Point(this.x, this.y);
828
+ },
829
+ /**
830
+ * Add this point's x & y coordinates to another point,
831
+ * yielding a new point.
832
+ * @param {Point} p the other point
833
+ * @return {Point} output point
834
+ */
835
+ add(p) {
836
+ return this.clone()._add(p);
837
+ },
838
+ /**
839
+ * Subtract this point's x & y coordinates to from point,
840
+ * yielding a new point.
841
+ * @param {Point} p the other point
842
+ * @return {Point} output point
843
+ */
844
+ sub(p) {
845
+ return this.clone()._sub(p);
846
+ },
847
+ /**
848
+ * Multiply this point's x & y coordinates by point,
849
+ * yielding a new point.
850
+ * @param {Point} p the other point
851
+ * @return {Point} output point
852
+ */
853
+ multByPoint(p) {
854
+ return this.clone()._multByPoint(p);
855
+ },
856
+ /**
857
+ * Divide this point's x & y coordinates by point,
858
+ * yielding a new point.
859
+ * @param {Point} p the other point
860
+ * @return {Point} output point
861
+ */
862
+ divByPoint(p) {
863
+ return this.clone()._divByPoint(p);
864
+ },
865
+ /**
866
+ * Multiply this point's x & y coordinates by a factor,
867
+ * yielding a new point.
868
+ * @param {number} k factor
869
+ * @return {Point} output point
870
+ */
871
+ mult(k2) {
872
+ return this.clone()._mult(k2);
873
+ },
874
+ /**
875
+ * Divide this point's x & y coordinates by a factor,
876
+ * yielding a new point.
877
+ * @param {number} k factor
878
+ * @return {Point} output point
879
+ */
880
+ div(k2) {
881
+ return this.clone()._div(k2);
882
+ },
883
+ /**
884
+ * Rotate this point around the 0, 0 origin by an angle a,
885
+ * given in radians
886
+ * @param {number} a angle to rotate around, in radians
887
+ * @return {Point} output point
888
+ */
889
+ rotate(a) {
890
+ return this.clone()._rotate(a);
891
+ },
892
+ /**
893
+ * Rotate this point around p point by an angle a,
894
+ * given in radians
895
+ * @param {number} a angle to rotate around, in radians
896
+ * @param {Point} p Point to rotate around
897
+ * @return {Point} output point
898
+ */
899
+ rotateAround(a, p) {
900
+ return this.clone()._rotateAround(a, p);
901
+ },
902
+ /**
903
+ * Multiply this point by a 4x1 transformation matrix
904
+ * @param {[number, number, number, number]} m transformation matrix
905
+ * @return {Point} output point
906
+ */
907
+ matMult(m2) {
908
+ return this.clone()._matMult(m2);
909
+ },
910
+ /**
911
+ * Calculate this point but as a unit vector from 0, 0, meaning
912
+ * that the distance from the resulting point to the 0, 0
913
+ * coordinate will be equal to 1 and the angle from the resulting
914
+ * point to the 0, 0 coordinate will be the same as before.
915
+ * @return {Point} unit vector point
916
+ */
917
+ unit() {
918
+ return this.clone()._unit();
919
+ },
920
+ /**
921
+ * Compute a perpendicular point, where the new y coordinate
922
+ * is the old x coordinate and the new x coordinate is the old y
923
+ * coordinate multiplied by -1
924
+ * @return {Point} perpendicular point
925
+ */
926
+ perp() {
927
+ return this.clone()._perp();
928
+ },
929
+ /**
930
+ * Return a version of this point with the x & y coordinates
931
+ * rounded to integers.
932
+ * @return {Point} rounded point
933
+ */
934
+ round() {
935
+ return this.clone()._round();
936
+ },
937
+ /**
938
+ * Return the magnitude of this point: this is the Euclidean
939
+ * distance from the 0, 0 coordinate to this point's x and y
940
+ * coordinates.
941
+ * @return {number} magnitude
942
+ */
943
+ mag() {
944
+ return Math.sqrt(this.x * this.x + this.y * this.y);
945
+ },
946
+ /**
947
+ * Judge whether this point is equal to another point, returning
948
+ * true or false.
949
+ * @param {Point} other the other point
950
+ * @return {boolean} whether the points are equal
951
+ */
952
+ equals(other) {
953
+ return this.x === other.x && this.y === other.y;
954
+ },
955
+ /**
956
+ * Calculate the distance from this point to another point
957
+ * @param {Point} p the other point
958
+ * @return {number} distance
959
+ */
960
+ dist(p) {
961
+ return Math.sqrt(this.distSqr(p));
962
+ },
963
+ /**
964
+ * Calculate the distance from this point to another point,
965
+ * without the square root step. Useful if you're comparing
966
+ * relative distances.
967
+ * @param {Point} p the other point
968
+ * @return {number} distance
969
+ */
970
+ distSqr(p) {
971
+ const dx = p.x - this.x, dy = p.y - this.y;
972
+ return dx * dx + dy * dy;
973
+ },
974
+ /**
975
+ * Get the angle from the 0, 0 coordinate to this point, in radians
976
+ * coordinates.
977
+ * @return {number} angle
978
+ */
979
+ angle() {
980
+ return Math.atan2(this.y, this.x);
981
+ },
982
+ /**
983
+ * Get the angle from this point to another point, in radians
984
+ * @param {Point} b the other point
985
+ * @return {number} angle
986
+ */
987
+ angleTo(b2) {
988
+ return Math.atan2(this.y - b2.y, this.x - b2.x);
989
+ },
990
+ /**
991
+ * Get the angle between this point and another point, in radians
992
+ * @param {Point} b the other point
993
+ * @return {number} angle
994
+ */
995
+ angleWith(b2) {
996
+ return this.angleWithSep(b2.x, b2.y);
997
+ },
998
+ /**
999
+ * Find the angle of the two vectors, solving the formula for
1000
+ * the cross product a x b = |a||b|sin(θ) for θ.
1001
+ * @param {number} x the x-coordinate
1002
+ * @param {number} y the y-coordinate
1003
+ * @return {number} the angle in radians
1004
+ */
1005
+ angleWithSep(x2, y) {
1006
+ return Math.atan2(
1007
+ this.x * y - this.y * x2,
1008
+ this.x * x2 + this.y * y
1009
+ );
1010
+ },
1011
+ /** @param {[number, number, number, number]} m */
1012
+ _matMult(m2) {
1013
+ const x2 = m2[0] * this.x + m2[1] * this.y, y = m2[2] * this.x + m2[3] * this.y;
1014
+ this.x = x2;
1015
+ this.y = y;
1016
+ return this;
1017
+ },
1018
+ /** @param {Point} p */
1019
+ _add(p) {
1020
+ this.x += p.x;
1021
+ this.y += p.y;
1022
+ return this;
1023
+ },
1024
+ /** @param {Point} p */
1025
+ _sub(p) {
1026
+ this.x -= p.x;
1027
+ this.y -= p.y;
1028
+ return this;
1029
+ },
1030
+ /** @param {number} k */
1031
+ _mult(k2) {
1032
+ this.x *= k2;
1033
+ this.y *= k2;
1034
+ return this;
1035
+ },
1036
+ /** @param {number} k */
1037
+ _div(k2) {
1038
+ this.x /= k2;
1039
+ this.y /= k2;
1040
+ return this;
1041
+ },
1042
+ /** @param {Point} p */
1043
+ _multByPoint(p) {
1044
+ this.x *= p.x;
1045
+ this.y *= p.y;
1046
+ return this;
1047
+ },
1048
+ /** @param {Point} p */
1049
+ _divByPoint(p) {
1050
+ this.x /= p.x;
1051
+ this.y /= p.y;
1052
+ return this;
1053
+ },
1054
+ _unit() {
1055
+ this._div(this.mag());
1056
+ return this;
1057
+ },
1058
+ _perp() {
1059
+ const y = this.y;
1060
+ this.y = this.x;
1061
+ this.x = -y;
1062
+ return this;
1063
+ },
1064
+ /** @param {number} angle */
1065
+ _rotate(angle) {
1066
+ const cos = Math.cos(angle), sin = Math.sin(angle), x2 = cos * this.x - sin * this.y, y = sin * this.x + cos * this.y;
1067
+ this.x = x2;
1068
+ this.y = y;
1069
+ return this;
1070
+ },
1071
+ /**
1072
+ * @param {number} angle
1073
+ * @param {Point} p
1074
+ */
1075
+ _rotateAround(angle, p) {
1076
+ const cos = Math.cos(angle), sin = Math.sin(angle), x2 = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);
1077
+ this.x = x2;
1078
+ this.y = y;
1079
+ return this;
1080
+ },
1081
+ _round() {
1082
+ this.x = Math.round(this.x);
1083
+ this.y = Math.round(this.y);
1084
+ return this;
1085
+ },
1086
+ constructor: Point
1087
+ };
1088
+ Point.convert = function(p) {
1089
+ if (p instanceof Point) {
1090
+ return (
1091
+ /** @type {Point} */
1092
+ p
1093
+ );
1094
+ }
1095
+ if (Array.isArray(p)) {
1096
+ return new Point(+p[0], +p[1]);
1097
+ }
1098
+ if (p.x !== void 0 && p.y !== void 0) {
1099
+ return new Point(+p.x, +p.y);
1100
+ }
1101
+ throw new Error("Expected [x, y] or {x, y} point format");
1102
+ };
1103
+
1104
+ // ../../node_modules/@mapbox/vector-tile/index.js
1105
+ var VectorTileFeature = class {
1106
+ /**
1107
+ * @param {Pbf} pbf
1108
+ * @param {number} end
1109
+ * @param {number} extent
1110
+ * @param {string[]} keys
1111
+ * @param {(number | string | boolean)[]} values
1112
+ */
1113
+ constructor(pbf, end, extent, keys, values) {
1114
+ this.properties = {};
1115
+ this.extent = extent;
1116
+ this.type = 0;
1117
+ this.id = void 0;
1118
+ this._pbf = pbf;
1119
+ this._geometry = -1;
1120
+ this._keys = keys;
1121
+ this._values = values;
1122
+ pbf.readFields(readFeature, this, end);
1123
+ }
1124
+ loadGeometry() {
1125
+ const pbf = this._pbf;
1126
+ pbf.pos = this._geometry;
1127
+ const end = pbf.readVarint() + pbf.pos;
1128
+ const lines = [];
1129
+ let line;
1130
+ let cmd = 1;
1131
+ let length = 0;
1132
+ let x2 = 0;
1133
+ let y = 0;
1134
+ while (pbf.pos < end) {
1135
+ if (length <= 0) {
1136
+ const cmdLen = pbf.readVarint();
1137
+ cmd = cmdLen & 7;
1138
+ length = cmdLen >> 3;
1139
+ }
1140
+ length--;
1141
+ if (cmd === 1 || cmd === 2) {
1142
+ x2 += pbf.readSVarint();
1143
+ y += pbf.readSVarint();
1144
+ if (cmd === 1) {
1145
+ if (line) lines.push(line);
1146
+ line = [];
1147
+ }
1148
+ if (line) line.push(new Point(x2, y));
1149
+ } else if (cmd === 7) {
1150
+ if (line) {
1151
+ line.push(line[0].clone());
1152
+ }
1153
+ } else {
1154
+ throw new Error(`unknown command ${cmd}`);
1155
+ }
1156
+ }
1157
+ if (line) lines.push(line);
1158
+ return lines;
1159
+ }
1160
+ bbox() {
1161
+ const pbf = this._pbf;
1162
+ pbf.pos = this._geometry;
1163
+ const end = pbf.readVarint() + pbf.pos;
1164
+ let cmd = 1, length = 0, x2 = 0, y = 0, x1 = Infinity, x22 = -Infinity, y1 = Infinity, y2 = -Infinity;
1165
+ while (pbf.pos < end) {
1166
+ if (length <= 0) {
1167
+ const cmdLen = pbf.readVarint();
1168
+ cmd = cmdLen & 7;
1169
+ length = cmdLen >> 3;
1170
+ }
1171
+ length--;
1172
+ if (cmd === 1 || cmd === 2) {
1173
+ x2 += pbf.readSVarint();
1174
+ y += pbf.readSVarint();
1175
+ if (x2 < x1) x1 = x2;
1176
+ if (x2 > x22) x22 = x2;
1177
+ if (y < y1) y1 = y;
1178
+ if (y > y2) y2 = y;
1179
+ } else if (cmd !== 7) {
1180
+ throw new Error(`unknown command ${cmd}`);
1181
+ }
1182
+ }
1183
+ return [x1, y1, x22, y2];
1184
+ }
1185
+ /**
1186
+ * @param {number} x
1187
+ * @param {number} y
1188
+ * @param {number} z
1189
+ * @return {Feature}
1190
+ */
1191
+ toGeoJSON(x2, y, z2) {
1192
+ const size = this.extent * Math.pow(2, z2), x0 = this.extent * x2, y0 = this.extent * y, vtCoords = this.loadGeometry();
1193
+ function projectPoint(p) {
1194
+ return [
1195
+ (p.x + x0) * 360 / size - 180,
1196
+ 360 / Math.PI * Math.atan(Math.exp((1 - (p.y + y0) * 2 / size) * Math.PI)) - 90
1197
+ ];
1198
+ }
1199
+ function projectLine(line) {
1200
+ return line.map(projectPoint);
1201
+ }
1202
+ let geometry;
1203
+ if (this.type === 1) {
1204
+ const points = [];
1205
+ for (const line of vtCoords) {
1206
+ points.push(line[0]);
1207
+ }
1208
+ const coordinates = projectLine(points);
1209
+ geometry = points.length === 1 ? { type: "Point", coordinates: coordinates[0] } : { type: "MultiPoint", coordinates };
1210
+ } else if (this.type === 2) {
1211
+ const coordinates = vtCoords.map(projectLine);
1212
+ geometry = coordinates.length === 1 ? { type: "LineString", coordinates: coordinates[0] } : { type: "MultiLineString", coordinates };
1213
+ } else if (this.type === 3) {
1214
+ const polygons = classifyRings(vtCoords);
1215
+ const coordinates = [];
1216
+ for (const polygon of polygons) {
1217
+ coordinates.push(polygon.map(projectLine));
1218
+ }
1219
+ geometry = coordinates.length === 1 ? { type: "Polygon", coordinates: coordinates[0] } : { type: "MultiPolygon", coordinates };
1220
+ } else {
1221
+ throw new Error("unknown feature type");
1222
+ }
1223
+ const result = {
1224
+ type: "Feature",
1225
+ geometry,
1226
+ properties: this.properties
1227
+ };
1228
+ if (this.id != null) {
1229
+ result.id = this.id;
1230
+ }
1231
+ return result;
1232
+ }
1233
+ };
1234
+ VectorTileFeature.types = ["Unknown", "Point", "LineString", "Polygon"];
1235
+ function readFeature(tag, feature, pbf) {
1236
+ if (tag === 1) feature.id = pbf.readVarint();
1237
+ else if (tag === 2) readTag(pbf, feature);
1238
+ else if (tag === 3) feature.type = /** @type {0 | 1 | 2 | 3} */
1239
+ pbf.readVarint();
1240
+ else if (tag === 4) feature._geometry = pbf.pos;
1241
+ }
1242
+ function readTag(pbf, feature) {
1243
+ const end = pbf.readVarint() + pbf.pos;
1244
+ while (pbf.pos < end) {
1245
+ const key = feature._keys[pbf.readVarint()];
1246
+ const value = feature._values[pbf.readVarint()];
1247
+ feature.properties[key] = value;
1248
+ }
1249
+ }
1250
+ function classifyRings(rings) {
1251
+ const len = rings.length;
1252
+ if (len <= 1) return [rings];
1253
+ const polygons = [];
1254
+ let polygon, ccw;
1255
+ for (let i = 0; i < len; i++) {
1256
+ const area = signedArea(rings[i]);
1257
+ if (area === 0) continue;
1258
+ if (ccw === void 0) ccw = area < 0;
1259
+ if (ccw === area < 0) {
1260
+ if (polygon) polygons.push(polygon);
1261
+ polygon = [rings[i]];
1262
+ } else if (polygon) {
1263
+ polygon.push(rings[i]);
1264
+ }
1265
+ }
1266
+ if (polygon) polygons.push(polygon);
1267
+ return polygons;
1268
+ }
1269
+ function signedArea(ring) {
1270
+ let sum = 0;
1271
+ for (let i = 0, len = ring.length, j2 = len - 1, p1, p2; i < len; j2 = i++) {
1272
+ p1 = ring[i];
1273
+ p2 = ring[j2];
1274
+ sum += (p2.x - p1.x) * (p1.y + p2.y);
1275
+ }
1276
+ return sum;
1277
+ }
1278
+ var VectorTileLayer = class {
1279
+ /**
1280
+ * @param {Pbf} pbf
1281
+ * @param {number} [end]
1282
+ */
1283
+ constructor(pbf, end) {
1284
+ this.version = 1;
1285
+ this.name = "";
1286
+ this.extent = 4096;
1287
+ this.length = 0;
1288
+ this._pbf = pbf;
1289
+ this._keys = [];
1290
+ this._values = [];
1291
+ this._features = [];
1292
+ pbf.readFields(readLayer, this, end);
1293
+ this.length = this._features.length;
1294
+ }
1295
+ /** return feature `i` from this layer as a `VectorTileFeature`
1296
+ * @param {number} i
1297
+ */
1298
+ feature(i) {
1299
+ if (i < 0 || i >= this._features.length) throw new Error("feature index out of bounds");
1300
+ this._pbf.pos = this._features[i];
1301
+ const end = this._pbf.readVarint() + this._pbf.pos;
1302
+ return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values);
1303
+ }
1304
+ };
1305
+ function readLayer(tag, layer, pbf) {
1306
+ if (tag === 15) layer.version = pbf.readVarint();
1307
+ else if (tag === 1) layer.name = pbf.readString();
1308
+ else if (tag === 5) layer.extent = pbf.readVarint();
1309
+ else if (tag === 2) layer._features.push(pbf.pos);
1310
+ else if (tag === 3) layer._keys.push(pbf.readString());
1311
+ else if (tag === 4) layer._values.push(readValueMessage(pbf));
1312
+ }
1313
+ function readValueMessage(pbf) {
1314
+ let value = null;
1315
+ const end = pbf.readVarint() + pbf.pos;
1316
+ while (pbf.pos < end) {
1317
+ const tag = pbf.readVarint() >> 3;
1318
+ value = tag === 1 ? pbf.readString() : tag === 2 ? pbf.readFloat() : tag === 3 ? pbf.readDouble() : tag === 4 ? pbf.readVarint64() : tag === 5 ? pbf.readVarint() : tag === 6 ? pbf.readSVarint() : tag === 7 ? pbf.readBoolean() : null;
1319
+ }
1320
+ if (value == null) {
1321
+ throw new Error("unknown feature value");
1322
+ }
1323
+ return value;
1324
+ }
1325
+ var VectorTile = class {
1326
+ /**
1327
+ * @param {Pbf} pbf
1328
+ * @param {number} [end]
1329
+ */
1330
+ constructor(pbf, end) {
1331
+ this.layers = pbf.readFields(readTile, {}, end);
1332
+ }
1333
+ };
1334
+ function readTile(tag, layers, pbf) {
1335
+ if (tag === 3) {
1336
+ const layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos);
1337
+ if (layer.length) layers[layer.name] = layer;
1338
+ }
1339
+ }
1340
+
1341
+ // ../../node_modules/pbf/index.js
1342
+ var SHIFT_LEFT_32 = (1 << 16) * (1 << 16);
1343
+ var SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
1344
+ var TEXT_DECODER_MIN_LENGTH = 12;
1345
+ var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8");
1346
+ var PBF_VARINT = 0;
1347
+ var PBF_FIXED64 = 1;
1348
+ var PBF_BYTES = 2;
1349
+ var PBF_FIXED32 = 5;
1350
+ var Pbf = class {
1351
+ /**
1352
+ * @param {Uint8Array | ArrayBuffer} [buf]
1353
+ */
1354
+ constructor(buf = new Uint8Array(16)) {
1355
+ this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf);
1356
+ this.dataView = new DataView(this.buf.buffer);
1357
+ this.pos = 0;
1358
+ this.type = 0;
1359
+ this.length = this.buf.length;
1360
+ }
1361
+ // === READING =================================================================
1362
+ /**
1363
+ * @template T
1364
+ * @param {(tag: number, result: T, pbf: Pbf) => void} readField
1365
+ * @param {T} result
1366
+ * @param {number} [end]
1367
+ */
1368
+ readFields(readField, result, end = this.length) {
1369
+ while (this.pos < end) {
1370
+ const val = this.readVarint(), tag = val >> 3, startPos = this.pos;
1371
+ this.type = val & 7;
1372
+ readField(tag, result, this);
1373
+ if (this.pos === startPos) this.skip(val);
1374
+ }
1375
+ return result;
1376
+ }
1377
+ /**
1378
+ * @template T
1379
+ * @param {(tag: number, result: T, pbf: Pbf) => void} readField
1380
+ * @param {T} result
1381
+ */
1382
+ readMessage(readField, result) {
1383
+ return this.readFields(readField, result, this.readVarint() + this.pos);
1384
+ }
1385
+ readFixed32() {
1386
+ const val = this.dataView.getUint32(this.pos, true);
1387
+ this.pos += 4;
1388
+ return val;
1389
+ }
1390
+ readSFixed32() {
1391
+ const val = this.dataView.getInt32(this.pos, true);
1392
+ this.pos += 4;
1393
+ return val;
1394
+ }
1395
+ // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
1396
+ readFixed64() {
1397
+ const val = this.dataView.getUint32(this.pos, true) + this.dataView.getUint32(this.pos + 4, true) * SHIFT_LEFT_32;
1398
+ this.pos += 8;
1399
+ return val;
1400
+ }
1401
+ readSFixed64() {
1402
+ const val = this.dataView.getUint32(this.pos, true) + this.dataView.getInt32(this.pos + 4, true) * SHIFT_LEFT_32;
1403
+ this.pos += 8;
1404
+ return val;
1405
+ }
1406
+ readFloat() {
1407
+ const val = this.dataView.getFloat32(this.pos, true);
1408
+ this.pos += 4;
1409
+ return val;
1410
+ }
1411
+ readDouble() {
1412
+ const val = this.dataView.getFloat64(this.pos, true);
1413
+ this.pos += 8;
1414
+ return val;
1415
+ }
1416
+ /**
1417
+ * @param {boolean} [isSigned]
1418
+ */
1419
+ readVarint(isSigned) {
1420
+ const buf = this.buf;
1421
+ let val, b2;
1422
+ b2 = buf[this.pos++];
1423
+ val = b2 & 127;
1424
+ if (b2 < 128) return val;
1425
+ b2 = buf[this.pos++];
1426
+ val |= (b2 & 127) << 7;
1427
+ if (b2 < 128) return val;
1428
+ b2 = buf[this.pos++];
1429
+ val |= (b2 & 127) << 14;
1430
+ if (b2 < 128) return val;
1431
+ b2 = buf[this.pos++];
1432
+ val |= (b2 & 127) << 21;
1433
+ if (b2 < 128) return val;
1434
+ b2 = buf[this.pos];
1435
+ val |= (b2 & 15) << 28;
1436
+ return readVarintRemainder(val, isSigned, this);
1437
+ }
1438
+ readVarint64() {
1439
+ return this.readVarint(true);
1440
+ }
1441
+ readSVarint() {
1442
+ const num = this.readVarint();
1443
+ return num % 2 === 1 ? (num + 1) / -2 : num / 2;
1444
+ }
1445
+ readBoolean() {
1446
+ return Boolean(this.readVarint());
1447
+ }
1448
+ readString() {
1449
+ const end = this.readVarint() + this.pos;
1450
+ const pos = this.pos;
1451
+ this.pos = end;
1452
+ if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) {
1453
+ return utf8TextDecoder.decode(this.buf.subarray(pos, end));
1454
+ }
1455
+ return readUtf8(this.buf, pos, end);
1456
+ }
1457
+ readBytes() {
1458
+ const end = this.readVarint() + this.pos, buffer = this.buf.subarray(this.pos, end);
1459
+ this.pos = end;
1460
+ return buffer;
1461
+ }
1462
+ // verbose for performance reasons; doesn't affect gzipped size
1463
+ /**
1464
+ * @param {number[]} [arr]
1465
+ * @param {boolean} [isSigned]
1466
+ */
1467
+ readPackedVarint(arr = [], isSigned) {
1468
+ const end = this.readPackedEnd();
1469
+ while (this.pos < end) arr.push(this.readVarint(isSigned));
1470
+ return arr;
1471
+ }
1472
+ /** @param {number[]} [arr] */
1473
+ readPackedSVarint(arr = []) {
1474
+ const end = this.readPackedEnd();
1475
+ while (this.pos < end) arr.push(this.readSVarint());
1476
+ return arr;
1477
+ }
1478
+ /** @param {boolean[]} [arr] */
1479
+ readPackedBoolean(arr = []) {
1480
+ const end = this.readPackedEnd();
1481
+ while (this.pos < end) arr.push(this.readBoolean());
1482
+ return arr;
1483
+ }
1484
+ /** @param {number[]} [arr] */
1485
+ readPackedFloat(arr = []) {
1486
+ const end = this.readPackedEnd();
1487
+ while (this.pos < end) arr.push(this.readFloat());
1488
+ return arr;
1489
+ }
1490
+ /** @param {number[]} [arr] */
1491
+ readPackedDouble(arr = []) {
1492
+ const end = this.readPackedEnd();
1493
+ while (this.pos < end) arr.push(this.readDouble());
1494
+ return arr;
1495
+ }
1496
+ /** @param {number[]} [arr] */
1497
+ readPackedFixed32(arr = []) {
1498
+ const end = this.readPackedEnd();
1499
+ while (this.pos < end) arr.push(this.readFixed32());
1500
+ return arr;
1501
+ }
1502
+ /** @param {number[]} [arr] */
1503
+ readPackedSFixed32(arr = []) {
1504
+ const end = this.readPackedEnd();
1505
+ while (this.pos < end) arr.push(this.readSFixed32());
1506
+ return arr;
1507
+ }
1508
+ /** @param {number[]} [arr] */
1509
+ readPackedFixed64(arr = []) {
1510
+ const end = this.readPackedEnd();
1511
+ while (this.pos < end) arr.push(this.readFixed64());
1512
+ return arr;
1513
+ }
1514
+ /** @param {number[]} [arr] */
1515
+ readPackedSFixed64(arr = []) {
1516
+ const end = this.readPackedEnd();
1517
+ while (this.pos < end) arr.push(this.readSFixed64());
1518
+ return arr;
1519
+ }
1520
+ readPackedEnd() {
1521
+ return this.type === PBF_BYTES ? this.readVarint() + this.pos : this.pos + 1;
1522
+ }
1523
+ /** @param {number} val */
1524
+ skip(val) {
1525
+ const type = val & 7;
1526
+ if (type === PBF_VARINT) while (this.buf[this.pos++] > 127) {
1527
+ }
1528
+ else if (type === PBF_BYTES) this.pos = this.readVarint() + this.pos;
1529
+ else if (type === PBF_FIXED32) this.pos += 4;
1530
+ else if (type === PBF_FIXED64) this.pos += 8;
1531
+ else throw new Error(`Unimplemented type: ${type}`);
1532
+ }
1533
+ // === WRITING =================================================================
1534
+ /**
1535
+ * @param {number} tag
1536
+ * @param {number} type
1537
+ */
1538
+ writeTag(tag, type) {
1539
+ this.writeVarint(tag << 3 | type);
1540
+ }
1541
+ /** @param {number} min */
1542
+ realloc(min) {
1543
+ let length = this.length || 16;
1544
+ while (length < this.pos + min) length *= 2;
1545
+ if (length !== this.length) {
1546
+ const buf = new Uint8Array(length);
1547
+ buf.set(this.buf);
1548
+ this.buf = buf;
1549
+ this.dataView = new DataView(buf.buffer);
1550
+ this.length = length;
1551
+ }
1552
+ }
1553
+ finish() {
1554
+ this.length = this.pos;
1555
+ this.pos = 0;
1556
+ return this.buf.subarray(0, this.length);
1557
+ }
1558
+ /** @param {number} val */
1559
+ writeFixed32(val) {
1560
+ this.realloc(4);
1561
+ this.dataView.setInt32(this.pos, val, true);
1562
+ this.pos += 4;
1563
+ }
1564
+ /** @param {number} val */
1565
+ writeSFixed32(val) {
1566
+ this.realloc(4);
1567
+ this.dataView.setInt32(this.pos, val, true);
1568
+ this.pos += 4;
1569
+ }
1570
+ /** @param {number} val */
1571
+ writeFixed64(val) {
1572
+ this.realloc(8);
1573
+ this.dataView.setInt32(this.pos, val & -1, true);
1574
+ this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true);
1575
+ this.pos += 8;
1576
+ }
1577
+ /** @param {number} val */
1578
+ writeSFixed64(val) {
1579
+ this.realloc(8);
1580
+ this.dataView.setInt32(this.pos, val & -1, true);
1581
+ this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true);
1582
+ this.pos += 8;
1583
+ }
1584
+ /** @param {number} val */
1585
+ writeVarint(val) {
1586
+ val = +val || 0;
1587
+ if (val > 268435455 || val < 0) {
1588
+ writeBigVarint(val, this);
1589
+ return;
1590
+ }
1591
+ this.realloc(4);
1592
+ this.buf[this.pos++] = val & 127 | (val > 127 ? 128 : 0);
1593
+ if (val <= 127) return;
1594
+ this.buf[this.pos++] = (val >>>= 7) & 127 | (val > 127 ? 128 : 0);
1595
+ if (val <= 127) return;
1596
+ this.buf[this.pos++] = (val >>>= 7) & 127 | (val > 127 ? 128 : 0);
1597
+ if (val <= 127) return;
1598
+ this.buf[this.pos++] = val >>> 7 & 127;
1599
+ }
1600
+ /** @param {number} val */
1601
+ writeSVarint(val) {
1602
+ this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
1603
+ }
1604
+ /** @param {boolean} val */
1605
+ writeBoolean(val) {
1606
+ this.writeVarint(+val);
1607
+ }
1608
+ /** @param {string} str */
1609
+ writeString(str) {
1610
+ str = String(str);
1611
+ this.realloc(str.length * 4);
1612
+ this.pos++;
1613
+ const startPos = this.pos;
1614
+ this.pos = writeUtf8(this.buf, str, this.pos);
1615
+ const len = this.pos - startPos;
1616
+ if (len >= 128) makeRoomForExtraLength(startPos, len, this);
1617
+ this.pos = startPos - 1;
1618
+ this.writeVarint(len);
1619
+ this.pos += len;
1620
+ }
1621
+ /** @param {number} val */
1622
+ writeFloat(val) {
1623
+ this.realloc(4);
1624
+ this.dataView.setFloat32(this.pos, val, true);
1625
+ this.pos += 4;
1626
+ }
1627
+ /** @param {number} val */
1628
+ writeDouble(val) {
1629
+ this.realloc(8);
1630
+ this.dataView.setFloat64(this.pos, val, true);
1631
+ this.pos += 8;
1632
+ }
1633
+ /** @param {Uint8Array} buffer */
1634
+ writeBytes(buffer) {
1635
+ const len = buffer.length;
1636
+ this.writeVarint(len);
1637
+ this.realloc(len);
1638
+ for (let i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
1639
+ }
1640
+ /**
1641
+ * @template T
1642
+ * @param {(obj: T, pbf: Pbf) => void} fn
1643
+ * @param {T} obj
1644
+ */
1645
+ writeRawMessage(fn, obj) {
1646
+ this.pos++;
1647
+ const startPos = this.pos;
1648
+ fn(obj, this);
1649
+ const len = this.pos - startPos;
1650
+ if (len >= 128) makeRoomForExtraLength(startPos, len, this);
1651
+ this.pos = startPos - 1;
1652
+ this.writeVarint(len);
1653
+ this.pos += len;
1654
+ }
1655
+ /**
1656
+ * @template T
1657
+ * @param {number} tag
1658
+ * @param {(obj: T, pbf: Pbf) => void} fn
1659
+ * @param {T} obj
1660
+ */
1661
+ writeMessage(tag, fn, obj) {
1662
+ this.writeTag(tag, PBF_BYTES);
1663
+ this.writeRawMessage(fn, obj);
1664
+ }
1665
+ /**
1666
+ * @param {number} tag
1667
+ * @param {number[]} arr
1668
+ */
1669
+ writePackedVarint(tag, arr) {
1670
+ if (arr.length) this.writeMessage(tag, writePackedVarint, arr);
1671
+ }
1672
+ /**
1673
+ * @param {number} tag
1674
+ * @param {number[]} arr
1675
+ */
1676
+ writePackedSVarint(tag, arr) {
1677
+ if (arr.length) this.writeMessage(tag, writePackedSVarint, arr);
1678
+ }
1679
+ /**
1680
+ * @param {number} tag
1681
+ * @param {boolean[]} arr
1682
+ */
1683
+ writePackedBoolean(tag, arr) {
1684
+ if (arr.length) this.writeMessage(tag, writePackedBoolean, arr);
1685
+ }
1686
+ /**
1687
+ * @param {number} tag
1688
+ * @param {number[]} arr
1689
+ */
1690
+ writePackedFloat(tag, arr) {
1691
+ if (arr.length) this.writeMessage(tag, writePackedFloat, arr);
1692
+ }
1693
+ /**
1694
+ * @param {number} tag
1695
+ * @param {number[]} arr
1696
+ */
1697
+ writePackedDouble(tag, arr) {
1698
+ if (arr.length) this.writeMessage(tag, writePackedDouble, arr);
1699
+ }
1700
+ /**
1701
+ * @param {number} tag
1702
+ * @param {number[]} arr
1703
+ */
1704
+ writePackedFixed32(tag, arr) {
1705
+ if (arr.length) this.writeMessage(tag, writePackedFixed32, arr);
1706
+ }
1707
+ /**
1708
+ * @param {number} tag
1709
+ * @param {number[]} arr
1710
+ */
1711
+ writePackedSFixed32(tag, arr) {
1712
+ if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr);
1713
+ }
1714
+ /**
1715
+ * @param {number} tag
1716
+ * @param {number[]} arr
1717
+ */
1718
+ writePackedFixed64(tag, arr) {
1719
+ if (arr.length) this.writeMessage(tag, writePackedFixed64, arr);
1720
+ }
1721
+ /**
1722
+ * @param {number} tag
1723
+ * @param {number[]} arr
1724
+ */
1725
+ writePackedSFixed64(tag, arr) {
1726
+ if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr);
1727
+ }
1728
+ /**
1729
+ * @param {number} tag
1730
+ * @param {Uint8Array} buffer
1731
+ */
1732
+ writeBytesField(tag, buffer) {
1733
+ this.writeTag(tag, PBF_BYTES);
1734
+ this.writeBytes(buffer);
1735
+ }
1736
+ /**
1737
+ * @param {number} tag
1738
+ * @param {number} val
1739
+ */
1740
+ writeFixed32Field(tag, val) {
1741
+ this.writeTag(tag, PBF_FIXED32);
1742
+ this.writeFixed32(val);
1743
+ }
1744
+ /**
1745
+ * @param {number} tag
1746
+ * @param {number} val
1747
+ */
1748
+ writeSFixed32Field(tag, val) {
1749
+ this.writeTag(tag, PBF_FIXED32);
1750
+ this.writeSFixed32(val);
1751
+ }
1752
+ /**
1753
+ * @param {number} tag
1754
+ * @param {number} val
1755
+ */
1756
+ writeFixed64Field(tag, val) {
1757
+ this.writeTag(tag, PBF_FIXED64);
1758
+ this.writeFixed64(val);
1759
+ }
1760
+ /**
1761
+ * @param {number} tag
1762
+ * @param {number} val
1763
+ */
1764
+ writeSFixed64Field(tag, val) {
1765
+ this.writeTag(tag, PBF_FIXED64);
1766
+ this.writeSFixed64(val);
1767
+ }
1768
+ /**
1769
+ * @param {number} tag
1770
+ * @param {number} val
1771
+ */
1772
+ writeVarintField(tag, val) {
1773
+ this.writeTag(tag, PBF_VARINT);
1774
+ this.writeVarint(val);
1775
+ }
1776
+ /**
1777
+ * @param {number} tag
1778
+ * @param {number} val
1779
+ */
1780
+ writeSVarintField(tag, val) {
1781
+ this.writeTag(tag, PBF_VARINT);
1782
+ this.writeSVarint(val);
1783
+ }
1784
+ /**
1785
+ * @param {number} tag
1786
+ * @param {string} str
1787
+ */
1788
+ writeStringField(tag, str) {
1789
+ this.writeTag(tag, PBF_BYTES);
1790
+ this.writeString(str);
1791
+ }
1792
+ /**
1793
+ * @param {number} tag
1794
+ * @param {number} val
1795
+ */
1796
+ writeFloatField(tag, val) {
1797
+ this.writeTag(tag, PBF_FIXED32);
1798
+ this.writeFloat(val);
1799
+ }
1800
+ /**
1801
+ * @param {number} tag
1802
+ * @param {number} val
1803
+ */
1804
+ writeDoubleField(tag, val) {
1805
+ this.writeTag(tag, PBF_FIXED64);
1806
+ this.writeDouble(val);
1807
+ }
1808
+ /**
1809
+ * @param {number} tag
1810
+ * @param {boolean} val
1811
+ */
1812
+ writeBooleanField(tag, val) {
1813
+ this.writeVarintField(tag, +val);
1814
+ }
1815
+ };
1816
+ function readVarintRemainder(l2, s, p) {
1817
+ const buf = p.buf;
1818
+ let h, b2;
1819
+ b2 = buf[p.pos++];
1820
+ h = (b2 & 112) >> 4;
1821
+ if (b2 < 128) return toNum(l2, h, s);
1822
+ b2 = buf[p.pos++];
1823
+ h |= (b2 & 127) << 3;
1824
+ if (b2 < 128) return toNum(l2, h, s);
1825
+ b2 = buf[p.pos++];
1826
+ h |= (b2 & 127) << 10;
1827
+ if (b2 < 128) return toNum(l2, h, s);
1828
+ b2 = buf[p.pos++];
1829
+ h |= (b2 & 127) << 17;
1830
+ if (b2 < 128) return toNum(l2, h, s);
1831
+ b2 = buf[p.pos++];
1832
+ h |= (b2 & 127) << 24;
1833
+ if (b2 < 128) return toNum(l2, h, s);
1834
+ b2 = buf[p.pos++];
1835
+ h |= (b2 & 1) << 31;
1836
+ if (b2 < 128) return toNum(l2, h, s);
1837
+ throw new Error("Expected varint not more than 10 bytes");
1838
+ }
1839
+ function toNum(low, high, isSigned) {
1840
+ return isSigned ? high * 4294967296 + (low >>> 0) : (high >>> 0) * 4294967296 + (low >>> 0);
1841
+ }
1842
+ function writeBigVarint(val, pbf) {
1843
+ let low, high;
1844
+ if (val >= 0) {
1845
+ low = val % 4294967296 | 0;
1846
+ high = val / 4294967296 | 0;
1847
+ } else {
1848
+ low = ~(-val % 4294967296);
1849
+ high = ~(-val / 4294967296);
1850
+ if (low ^ 4294967295) {
1851
+ low = low + 1 | 0;
1852
+ } else {
1853
+ low = 0;
1854
+ high = high + 1 | 0;
1855
+ }
1856
+ }
1857
+ if (val >= 18446744073709552e3 || val < -18446744073709552e3) {
1858
+ throw new Error("Given varint doesn't fit into 10 bytes");
1859
+ }
1860
+ pbf.realloc(10);
1861
+ writeBigVarintLow(low, high, pbf);
1862
+ writeBigVarintHigh(high, pbf);
1863
+ }
1864
+ function writeBigVarintLow(low, high, pbf) {
1865
+ pbf.buf[pbf.pos++] = low & 127 | 128;
1866
+ low >>>= 7;
1867
+ pbf.buf[pbf.pos++] = low & 127 | 128;
1868
+ low >>>= 7;
1869
+ pbf.buf[pbf.pos++] = low & 127 | 128;
1870
+ low >>>= 7;
1871
+ pbf.buf[pbf.pos++] = low & 127 | 128;
1872
+ low >>>= 7;
1873
+ pbf.buf[pbf.pos] = low & 127;
1874
+ }
1875
+ function writeBigVarintHigh(high, pbf) {
1876
+ const lsb = (high & 7) << 4;
1877
+ pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 128 : 0);
1878
+ if (!high) return;
1879
+ pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
1880
+ if (!high) return;
1881
+ pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
1882
+ if (!high) return;
1883
+ pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
1884
+ if (!high) return;
1885
+ pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
1886
+ if (!high) return;
1887
+ pbf.buf[pbf.pos++] = high & 127;
1888
+ }
1889
+ function makeRoomForExtraLength(startPos, len, pbf) {
1890
+ const extraLen = len <= 16383 ? 1 : len <= 2097151 ? 2 : len <= 268435455 ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7));
1891
+ pbf.realloc(extraLen);
1892
+ for (let i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
1893
+ }
1894
+ function writePackedVarint(arr, pbf) {
1895
+ for (let i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);
1896
+ }
1897
+ function writePackedSVarint(arr, pbf) {
1898
+ for (let i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);
1899
+ }
1900
+ function writePackedFloat(arr, pbf) {
1901
+ for (let i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);
1902
+ }
1903
+ function writePackedDouble(arr, pbf) {
1904
+ for (let i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);
1905
+ }
1906
+ function writePackedBoolean(arr, pbf) {
1907
+ for (let i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);
1908
+ }
1909
+ function writePackedFixed32(arr, pbf) {
1910
+ for (let i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);
1911
+ }
1912
+ function writePackedSFixed32(arr, pbf) {
1913
+ for (let i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]);
1914
+ }
1915
+ function writePackedFixed64(arr, pbf) {
1916
+ for (let i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);
1917
+ }
1918
+ function writePackedSFixed64(arr, pbf) {
1919
+ for (let i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]);
1920
+ }
1921
+ function readUtf8(buf, pos, end) {
1922
+ let str = "";
1923
+ let i = pos;
1924
+ while (i < end) {
1925
+ const b0 = buf[i];
1926
+ let c = null;
1927
+ let bytesPerSequence = b0 > 239 ? 4 : b0 > 223 ? 3 : b0 > 191 ? 2 : 1;
1928
+ if (i + bytesPerSequence > end) break;
1929
+ let b1, b2, b3;
1930
+ if (bytesPerSequence === 1) {
1931
+ if (b0 < 128) {
1932
+ c = b0;
1933
+ }
1934
+ } else if (bytesPerSequence === 2) {
1935
+ b1 = buf[i + 1];
1936
+ if ((b1 & 192) === 128) {
1937
+ c = (b0 & 31) << 6 | b1 & 63;
1938
+ if (c <= 127) {
1939
+ c = null;
1940
+ }
1941
+ }
1942
+ } else if (bytesPerSequence === 3) {
1943
+ b1 = buf[i + 1];
1944
+ b2 = buf[i + 2];
1945
+ if ((b1 & 192) === 128 && (b2 & 192) === 128) {
1946
+ c = (b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63;
1947
+ if (c <= 2047 || c >= 55296 && c <= 57343) {
1948
+ c = null;
1949
+ }
1950
+ }
1951
+ } else if (bytesPerSequence === 4) {
1952
+ b1 = buf[i + 1];
1953
+ b2 = buf[i + 2];
1954
+ b3 = buf[i + 3];
1955
+ if ((b1 & 192) === 128 && (b2 & 192) === 128 && (b3 & 192) === 128) {
1956
+ c = (b0 & 15) << 18 | (b1 & 63) << 12 | (b2 & 63) << 6 | b3 & 63;
1957
+ if (c <= 65535 || c >= 1114112) {
1958
+ c = null;
1959
+ }
1960
+ }
1961
+ }
1962
+ if (c === null) {
1963
+ c = 65533;
1964
+ bytesPerSequence = 1;
1965
+ } else if (c > 65535) {
1966
+ c -= 65536;
1967
+ str += String.fromCharCode(c >>> 10 & 1023 | 55296);
1968
+ c = 56320 | c & 1023;
1969
+ }
1970
+ str += String.fromCharCode(c);
1971
+ i += bytesPerSequence;
1972
+ }
1973
+ return str;
1974
+ }
1975
+ function writeUtf8(buf, str, pos) {
1976
+ for (let i = 0, c, lead; i < str.length; i++) {
1977
+ c = str.charCodeAt(i);
1978
+ if (c > 55295 && c < 57344) {
1979
+ if (lead) {
1980
+ if (c < 56320) {
1981
+ buf[pos++] = 239;
1982
+ buf[pos++] = 191;
1983
+ buf[pos++] = 189;
1984
+ lead = c;
1985
+ continue;
1986
+ } else {
1987
+ c = lead - 55296 << 10 | c - 56320 | 65536;
1988
+ lead = null;
1989
+ }
1990
+ } else {
1991
+ if (c > 56319 || i + 1 === str.length) {
1992
+ buf[pos++] = 239;
1993
+ buf[pos++] = 191;
1994
+ buf[pos++] = 189;
1995
+ } else {
1996
+ lead = c;
1997
+ }
1998
+ continue;
1999
+ }
2000
+ } else if (lead) {
2001
+ buf[pos++] = 239;
2002
+ buf[pos++] = 191;
2003
+ buf[pos++] = 189;
2004
+ lead = null;
2005
+ }
2006
+ if (c < 128) {
2007
+ buf[pos++] = c;
2008
+ } else {
2009
+ if (c < 2048) {
2010
+ buf[pos++] = c >> 6 | 192;
2011
+ } else {
2012
+ if (c < 65536) {
2013
+ buf[pos++] = c >> 12 | 224;
2014
+ } else {
2015
+ buf[pos++] = c >> 18 | 240;
2016
+ buf[pos++] = c >> 12 & 63 | 128;
2017
+ }
2018
+ buf[pos++] = c >> 6 & 63 | 128;
2019
+ }
2020
+ buf[pos++] = c & 63 | 128;
2021
+ }
2022
+ }
2023
+ return pos;
2024
+ }
2025
+
2026
+ // src/corrections.js
2027
+ var DEFAULT_CACHE_SIZE = 64;
2028
+ function toIndex(z2, x2, y) {
2029
+ return `${x2}:${y}:${z2}`;
2030
+ }
2031
+ function parseTile(buffer) {
2032
+ const tile = new VectorTile(new Pbf(buffer));
2033
+ const result = {};
2034
+ for (const [layerName, layer] of Object.entries(tile.layers)) {
2035
+ const features = [];
2036
+ for (let i = 0; i < layer.length; i++) {
2037
+ const feature = layer.feature(i);
2038
+ features.push({
2039
+ id: feature.id,
2040
+ type: feature.type,
2041
+ properties: feature.properties,
2042
+ geometry: feature.loadGeometry(),
2043
+ extent: layer.extent
2044
+ });
2045
+ }
2046
+ result[layerName] = features;
2047
+ }
2048
+ return result;
2049
+ }
2050
+ function transformForOverzoom(corrections, scale, offsetX, offsetY) {
2051
+ const result = {};
2052
+ for (const [layerName, features] of Object.entries(corrections)) {
2053
+ result[layerName] = features.map((feature) => {
2054
+ const extent = feature.extent;
2055
+ const childExtent = extent / scale;
2056
+ const startX = offsetX * childExtent;
2057
+ const startY = offsetY * childExtent;
2058
+ const newGeometry = feature.geometry.map((ring) => {
2059
+ return ring.map((point) => {
2060
+ const x2 = (point.x - startX) * scale;
2061
+ const y = (point.y - startY) * scale;
2062
+ return { x: x2, y };
2063
+ });
2064
+ });
2065
+ return {
2066
+ ...feature,
2067
+ geometry: newGeometry,
2068
+ // Keep original extent since we scaled coordinates to match
2069
+ extent
2070
+ };
2071
+ });
2072
+ }
2073
+ return result;
2074
+ }
2075
+ var CorrectionsSource = class {
2076
+ /**
2077
+ * @param {string} pmtilesUrl - URL to the PMTiles file
2078
+ * @param {Object} [options] - Options
2079
+ * @param {number} [options.cacheSize=64] - Maximum number of tiles to cache
2080
+ * @param {number} [options.maxDataZoom] - Maximum zoom level in PMTiles (auto-detected if not provided)
2081
+ */
2082
+ constructor(pmtilesUrl, options = {}) {
2083
+ this.pmtilesUrl = pmtilesUrl;
2084
+ this.pmtiles = new x(pmtilesUrl);
2085
+ this.cacheSize = options.cacheSize ?? DEFAULT_CACHE_SIZE;
2086
+ this.maxDataZoom = options.maxDataZoom;
2087
+ this.cache = /* @__PURE__ */ new Map();
2088
+ this.inflight = /* @__PURE__ */ new Map();
2089
+ }
2090
+ /**
2091
+ * Get the PMTiles source object.
2092
+ * @returns {PMTiles}
2093
+ */
2094
+ getSource() {
2095
+ return this.pmtiles;
2096
+ }
2097
+ /**
2098
+ * Clear the tile cache.
2099
+ */
2100
+ clearCache() {
2101
+ this.cache.clear();
2102
+ this.inflight.clear();
2103
+ }
2104
+ /**
2105
+ * Auto-detect max zoom from PMTiles metadata.
2106
+ * @returns {Promise<number>}
2107
+ * @private
2108
+ */
2109
+ async _getMaxDataZoom() {
2110
+ if (this.maxDataZoom !== void 0) {
2111
+ return this.maxDataZoom;
2112
+ }
2113
+ const header = await this.pmtiles.getHeader();
2114
+ this.maxDataZoom = header.maxZoom;
2115
+ return this.maxDataZoom;
2116
+ }
2117
+ /**
2118
+ * Fetch and parse a tile from PMTiles.
2119
+ * Implements in-flight request deduplication from protomaps-leaflet.
2120
+ * @param {number} z
2121
+ * @param {number} x
2122
+ * @param {number} y
2123
+ * @returns {Promise<Object<string, Array>>}
2124
+ * @private
2125
+ */
2126
+ async _fetchTile(z2, x2, y) {
2127
+ const idx = toIndex(z2, x2, y);
2128
+ return new Promise((resolve, reject) => {
2129
+ const entry = this.cache.get(idx);
2130
+ if (entry) {
2131
+ entry.used = performance.now();
2132
+ resolve(entry.data);
2133
+ return;
2134
+ }
2135
+ const ifentry = this.inflight.get(idx);
2136
+ if (ifentry) {
2137
+ ifentry.push({ resolve, reject });
2138
+ return;
2139
+ }
2140
+ this.inflight.set(idx, []);
2141
+ this.pmtiles.getZxy(z2, x2, y).then((result) => {
2142
+ let data;
2143
+ if (result) {
2144
+ data = parseTile(result.data);
2145
+ } else {
2146
+ data = {};
2147
+ }
2148
+ this.cache.set(idx, { used: performance.now(), data });
2149
+ const ifentry2 = this.inflight.get(idx);
2150
+ if (ifentry2) {
2151
+ for (const waiter of ifentry2) {
2152
+ waiter.resolve(data);
2153
+ }
2154
+ }
2155
+ this.inflight.delete(idx);
2156
+ resolve(data);
2157
+ if (this.cache.size > this.cacheSize) {
2158
+ let minUsed = Infinity;
2159
+ let minKey = void 0;
2160
+ this.cache.forEach((value, key) => {
2161
+ if (value.used < minUsed) {
2162
+ minUsed = value.used;
2163
+ minKey = key;
2164
+ }
2165
+ });
2166
+ if (minKey) {
2167
+ this.cache.delete(minKey);
2168
+ }
2169
+ }
2170
+ }).catch((e) => {
2171
+ const ifentry2 = this.inflight.get(idx);
2172
+ if (ifentry2) {
2173
+ for (const waiter of ifentry2) {
2174
+ waiter.reject(e);
2175
+ }
2176
+ }
2177
+ this.inflight.delete(idx);
2178
+ reject(e);
2179
+ });
2180
+ });
2181
+ }
2182
+ /**
2183
+ * Get corrections for a tile as a dict of layer name to features.
2184
+ * Supports overzoom beyond maxDataZoom by scaling parent tile data.
2185
+ * @param {number} z - Zoom level
2186
+ * @param {number} x - Tile X coordinate
2187
+ * @param {number} y - Tile Y coordinate
2188
+ * @returns {Promise<Object<string, Array>>} Map of layer name to array of features
2189
+ */
2190
+ async get(z2, x2, y) {
2191
+ const maxDataZoom = await this._getMaxDataZoom();
2192
+ if (z2 > maxDataZoom) {
2193
+ const zoomDiff = z2 - maxDataZoom;
2194
+ const scale = 1 << zoomDiff;
2195
+ const parentX = Math.floor(x2 / scale);
2196
+ const parentY = Math.floor(y / scale);
2197
+ const offsetX = x2 % scale;
2198
+ const offsetY = y % scale;
2199
+ const corrections = await this._fetchTile(maxDataZoom, parentX, parentY);
2200
+ if (Object.keys(corrections).length > 0) {
2201
+ return transformForOverzoom(corrections, scale, offsetX, offsetY);
2202
+ }
2203
+ return {};
2204
+ }
2205
+ return await this._fetchTile(z2, x2, y);
2206
+ }
2207
+ };
2208
+
2209
+ // src/index.js
2210
+ var MIN_LINE_WIDTH = 0.5;
2211
+ function getLineWidth(zoom, lineWidthStops) {
2212
+ const zooms = Object.keys(lineWidthStops).map(Number).sort((a, b2) => a - b2);
2213
+ if (lineWidthStops[zoom] !== void 0) {
2214
+ return lineWidthStops[zoom];
2215
+ }
2216
+ if (zoom < zooms[0]) {
2217
+ const z1 = zooms[0];
2218
+ const z2 = zooms[1];
2219
+ const w1 = lineWidthStops[z1];
2220
+ const w2 = lineWidthStops[z2];
2221
+ const slope = (w2 - w1) / (z2 - z1);
2222
+ return Math.max(MIN_LINE_WIDTH, w1 + slope * (zoom - z1));
2223
+ }
2224
+ if (zoom > zooms[zooms.length - 1]) {
2225
+ const z1 = zooms[zooms.length - 2];
2226
+ const z2 = zooms[zooms.length - 1];
2227
+ const w1 = lineWidthStops[z1];
2228
+ const w2 = lineWidthStops[z2];
2229
+ const slope = (w2 - w1) / (z2 - z1);
2230
+ return Math.max(MIN_LINE_WIDTH, w2 + slope * (zoom - z2));
2231
+ }
2232
+ for (let i = 0; i < zooms.length - 1; i++) {
2233
+ if (zoom > zooms[i] && zoom < zooms[i + 1]) {
2234
+ const z1 = zooms[i];
2235
+ const z2 = zooms[i + 1];
2236
+ const w1 = lineWidthStops[z1];
2237
+ const w2 = lineWidthStops[z2];
2238
+ const t = (zoom - z1) / (z2 - z1);
2239
+ return w1 + t * (w2 - w1);
2240
+ }
2241
+ }
2242
+ return 1;
2243
+ }
2244
+ function getFeaturesBoundingBox(features, tileSize, padding = 0) {
2245
+ let minX = Infinity, minY = Infinity;
2246
+ let maxX = -Infinity, maxY = -Infinity;
2247
+ for (const feature of features) {
2248
+ const scale = tileSize / feature.extent;
2249
+ for (const ring of feature.geometry) {
2250
+ for (const point of ring) {
2251
+ const px = point.x * scale;
2252
+ const py = point.y * scale;
2253
+ if (px < minX) minX = px;
2254
+ if (py < minY) minY = py;
2255
+ if (px > maxX) maxX = px;
2256
+ if (py > maxY) maxY = py;
2257
+ }
2258
+ }
2259
+ }
2260
+ return {
2261
+ minX: Math.max(0, Math.floor(minX - padding)),
2262
+ minY: Math.max(0, Math.floor(minY - padding)),
2263
+ maxX: Math.min(tileSize, Math.ceil(maxX + padding)),
2264
+ maxY: Math.min(tileSize, Math.ceil(maxY + padding))
2265
+ };
2266
+ }
2267
+ function medianFromHistogram(histogram, values) {
2268
+ const count = values.length;
2269
+ if (count === 0) return 0;
2270
+ histogram.fill(0);
2271
+ for (let i = 0; i < count; i++) {
2272
+ histogram[values[i]]++;
2273
+ }
2274
+ const medianPos = count >> 1;
2275
+ let cumulative = 0;
2276
+ for (let v2 = 0; v2 < 256; v2++) {
2277
+ cumulative += histogram[v2];
2278
+ if (cumulative > medianPos) {
2279
+ return v2;
2280
+ }
2281
+ }
2282
+ return 0;
2283
+ }
2284
+ function applyMedianBlurAlongPath(ctx, features, lineWidth, tileSize, maskCanvas) {
2285
+ if (features.length === 0) return;
2286
+ const imageData = ctx.getImageData(0, 0, tileSize, tileSize);
2287
+ const data = imageData.data;
2288
+ const width = tileSize;
2289
+ const height = tileSize;
2290
+ if (!maskCanvas || maskCanvas.width !== tileSize || maskCanvas.height !== tileSize) {
2291
+ maskCanvas = new OffscreenCanvas(tileSize, tileSize);
2292
+ }
2293
+ const maskCtx = maskCanvas.getContext("2d");
2294
+ maskCtx.fillStyle = "black";
2295
+ maskCtx.fillRect(0, 0, tileSize, tileSize);
2296
+ maskCtx.strokeStyle = "white";
2297
+ maskCtx.lineWidth = lineWidth;
2298
+ maskCtx.lineCap = "round";
2299
+ maskCtx.lineJoin = "round";
2300
+ for (const feature of features) {
2301
+ const scale = tileSize / feature.extent;
2302
+ for (const ring of feature.geometry) {
2303
+ if (ring.length === 0) continue;
2304
+ maskCtx.beginPath();
2305
+ maskCtx.moveTo(ring[0].x * scale, ring[0].y * scale);
2306
+ for (let i = 1; i < ring.length; i++) {
2307
+ maskCtx.lineTo(ring[i].x * scale, ring[i].y * scale);
2308
+ }
2309
+ maskCtx.stroke();
2310
+ }
2311
+ }
2312
+ const maskData = maskCtx.getImageData(0, 0, tileSize, tileSize).data;
2313
+ const radius = Math.max(2, Math.ceil(lineWidth / 2) + 1);
2314
+ const output = new Uint8ClampedArray(data);
2315
+ const bbox = getFeaturesBoundingBox(features, tileSize, radius);
2316
+ const histogram = new Uint16Array(256);
2317
+ const rValues = [];
2318
+ const gValues = [];
2319
+ const bValues = [];
2320
+ for (let y = bbox.minY; y < bbox.maxY; y++) {
2321
+ for (let x2 = bbox.minX; x2 < bbox.maxX; x2++) {
2322
+ const maskIdx = (y * width + x2) * 4;
2323
+ if (maskData[maskIdx] < 128) continue;
2324
+ rValues.length = 0;
2325
+ gValues.length = 0;
2326
+ bValues.length = 0;
2327
+ for (let dy = -radius; dy <= radius; dy++) {
2328
+ for (let dx = -radius; dx <= radius; dx++) {
2329
+ const nx = x2 + dx;
2330
+ const ny = y + dy;
2331
+ if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
2332
+ const nMaskIdx = (ny * width + nx) * 4;
2333
+ if (maskData[nMaskIdx] >= 128) continue;
2334
+ const nIdx = nMaskIdx;
2335
+ rValues.push(data[nIdx]);
2336
+ gValues.push(data[nIdx + 1]);
2337
+ bValues.push(data[nIdx + 2]);
2338
+ }
2339
+ }
2340
+ if (rValues.length >= 3) {
2341
+ const idx = maskIdx;
2342
+ output[idx] = medianFromHistogram(histogram, rValues);
2343
+ output[idx + 1] = medianFromHistogram(histogram, gValues);
2344
+ output[idx + 2] = medianFromHistogram(histogram, bValues);
2345
+ }
2346
+ }
2347
+ }
2348
+ ctx.putImageData(new ImageData(output, width, height), 0, 0);
2349
+ }
2350
+ function isAtExtentEdge(coord, extent, tolerance = 0.01) {
2351
+ const tol = extent * tolerance;
2352
+ return coord <= tol || coord >= extent - tol;
2353
+ }
2354
+ function extendFeaturesEnds(features, extensionLength) {
2355
+ return features.map((feature) => {
2356
+ const extent = feature.extent;
2357
+ const newGeometry = feature.geometry.map((ring) => {
2358
+ if (ring.length < 2) return ring;
2359
+ const newRing = [...ring];
2360
+ const start = ring[0];
2361
+ const second = ring[1];
2362
+ if (!isAtExtentEdge(start.x, extent) && !isAtExtentEdge(start.y, extent)) {
2363
+ const dx = start.x - second.x;
2364
+ const dy = start.y - second.y;
2365
+ const len = Math.sqrt(dx * dx + dy * dy);
2366
+ if (len > 0) {
2367
+ const ux = dx / len;
2368
+ const uy = dy / len;
2369
+ newRing[0] = {
2370
+ x: start.x + ux * extensionLength,
2371
+ y: start.y + uy * extensionLength
2372
+ };
2373
+ }
2374
+ }
2375
+ const lastIdx = ring.length - 1;
2376
+ const end = ring[lastIdx];
2377
+ const prev = ring[lastIdx - 1];
2378
+ if (!isAtExtentEdge(end.x, extent) && !isAtExtentEdge(end.y, extent)) {
2379
+ const dx = end.x - prev.x;
2380
+ const dy = end.y - prev.y;
2381
+ const len = Math.sqrt(dx * dx + dy * dy);
2382
+ if (len > 0) {
2383
+ const ux = dx / len;
2384
+ const uy = dy / len;
2385
+ newRing[lastIdx] = {
2386
+ x: end.x + ux * extensionLength,
2387
+ y: end.y + uy * extensionLength
2388
+ };
2389
+ }
2390
+ }
2391
+ return newRing;
2392
+ });
2393
+ return { ...feature, geometry: newGeometry };
2394
+ });
2395
+ }
2396
+ function drawFeatures(ctx, features, color, lineWidth, tileSize, dashArray, alpha) {
2397
+ const prevAlpha = ctx.globalAlpha;
2398
+ if (alpha !== void 0) {
2399
+ ctx.globalAlpha = alpha;
2400
+ }
2401
+ ctx.strokeStyle = color;
2402
+ ctx.lineWidth = lineWidth;
2403
+ ctx.lineJoin = "round";
2404
+ if (dashArray && dashArray.length > 0) {
2405
+ ctx.setLineDash(dashArray);
2406
+ ctx.lineCap = "butt";
2407
+ } else {
2408
+ ctx.setLineDash([]);
2409
+ ctx.lineCap = "round";
2410
+ }
2411
+ for (const feature of features) {
2412
+ const scale = tileSize / feature.extent;
2413
+ for (const ring of feature.geometry) {
2414
+ if (ring.length === 0) continue;
2415
+ ctx.beginPath();
2416
+ ctx.moveTo(ring[0].x * scale, ring[0].y * scale);
2417
+ for (let i = 1; i < ring.length; i++) {
2418
+ ctx.lineTo(ring[i].x * scale, ring[i].y * scale);
2419
+ }
2420
+ ctx.stroke();
2421
+ }
2422
+ }
2423
+ if (alpha !== void 0) {
2424
+ ctx.globalAlpha = prevAlpha;
2425
+ }
2426
+ }
2427
+ var BoundaryCorrector = class {
2428
+ /**
2429
+ * @param {string} pmtilesUrl - URL to the PMTiles file
2430
+ * @param {Object} [options] - Options
2431
+ * @param {number} [options.cacheSize=64] - Maximum number of tiles to cache
2432
+ * @param {number} [options.maxDataZoom] - Maximum zoom level in PMTiles (auto-detected if not provided)
2433
+ */
2434
+ constructor(pmtilesUrl, options = {}) {
2435
+ this.correctionsSource = new CorrectionsSource(pmtilesUrl, options);
2436
+ this._maskCanvas = null;
2437
+ }
2438
+ /**
2439
+ * Get the PMTiles source object.
2440
+ * @returns {PMTiles}
2441
+ */
2442
+ getSource() {
2443
+ return this.correctionsSource.getSource();
2444
+ }
2445
+ /**
2446
+ * Clear the tile cache.
2447
+ */
2448
+ clearCache() {
2449
+ this.correctionsSource.clearCache();
2450
+ }
2451
+ /**
2452
+ * Get corrections for a tile as a dict of layer name to features.
2453
+ * Supports overzoom beyond maxDataZoom by scaling parent tile data.
2454
+ * @param {number} z - Zoom level
2455
+ * @param {number} x - Tile X coordinate
2456
+ * @param {number} y - Tile Y coordinate
2457
+ * @returns {Promise<Object<string, Array>>} Map of layer name to array of features
2458
+ */
2459
+ async getCorrections(z2, x2, y) {
2460
+ return await this.correctionsSource.get(z2, x2, y);
2461
+ }
2462
+ /**
2463
+ * Apply corrections to a raster tile.
2464
+ * @param {Object<string, Array>} corrections - Feature map from getCorrections
2465
+ * @param {ArrayBuffer} rasterTile - The original raster tile as ArrayBuffer
2466
+ * @param {Object} layerConfig - Layer configuration with colors and styles
2467
+ * @param {number} zoom - Current zoom level
2468
+ * @param {number} [tileSize=256] - Size of the tile in pixels
2469
+ * @returns {Promise<ArrayBuffer>} The corrected tile as ArrayBuffer (PNG)
2470
+ */
2471
+ async fixTile(corrections, rasterTile, layerConfig, zoom, tileSize = 256) {
2472
+ const {
2473
+ startZoom = 0,
2474
+ zoomThreshold,
2475
+ lineWidthStops,
2476
+ delWidthFactor
2477
+ } = layerConfig;
2478
+ if (zoom < startZoom) {
2479
+ return rasterTile;
2480
+ }
2481
+ let activeLineStyles;
2482
+ if (layerConfig.getLineStylesForZoom) {
2483
+ activeLineStyles = layerConfig.getLineStylesForZoom(zoom);
2484
+ } else {
2485
+ const allStyles = layerConfig.lineStyles || [];
2486
+ activeLineStyles = allStyles.filter((style) => {
2487
+ const styleStart = style.startZoom ?? startZoom;
2488
+ const styleEnd = style.endZoom ?? Infinity;
2489
+ return zoom >= styleStart && zoom <= styleEnd;
2490
+ });
2491
+ }
2492
+ const useOsm = zoom >= zoomThreshold;
2493
+ const addLayerName = useOsm ? "to-add-osm" : "to-add-ne";
2494
+ const delLayerName = useOsm ? "to-del-osm" : "to-del-ne";
2495
+ const canvas = new OffscreenCanvas(tileSize, tileSize);
2496
+ const ctx = canvas.getContext("2d");
2497
+ const blob = new Blob([rasterTile]);
2498
+ const imageBitmap = await createImageBitmap(blob);
2499
+ ctx.drawImage(imageBitmap, 0, 0, tileSize, tileSize);
2500
+ const baseLineWidth = getLineWidth(zoom, lineWidthStops);
2501
+ const maxWidthFraction = activeLineStyles.length > 0 ? Math.max(...activeLineStyles.map((s) => s.widthFraction ?? 1)) : 1;
2502
+ const delLineWidth = baseLineWidth * maxWidthFraction * delWidthFactor;
2503
+ const delFeatures = corrections[delLayerName] || [];
2504
+ if (delFeatures.length > 0) {
2505
+ if (!this._maskCanvas || this._maskCanvas.width !== tileSize) {
2506
+ this._maskCanvas = new OffscreenCanvas(tileSize, tileSize);
2507
+ }
2508
+ applyMedianBlurAlongPath(ctx, delFeatures, delLineWidth, tileSize, this._maskCanvas);
2509
+ }
2510
+ let addFeatures = corrections[addLayerName] || [];
2511
+ if (addFeatures.length > 0 && activeLineStyles.length > 0) {
2512
+ const extensionFactor = layerConfig.lineExtensionFactor ?? 0.5;
2513
+ if (extensionFactor > 0 && delFeatures.length > 0) {
2514
+ const extent = addFeatures[0]?.extent || 4096;
2515
+ const extensionLength = delLineWidth * extensionFactor / tileSize * extent;
2516
+ addFeatures = extendFeaturesEnds(addFeatures, extensionLength);
2517
+ }
2518
+ for (const style of activeLineStyles) {
2519
+ const { color, widthFraction = 1, dashArray, alpha = 1 } = style;
2520
+ const lineWidth = baseLineWidth * widthFraction;
2521
+ drawFeatures(ctx, addFeatures, color, lineWidth, tileSize, dashArray, alpha);
2522
+ }
2523
+ }
2524
+ const outputBlob = await canvas.convertToBlob({ type: "image/png" });
2525
+ return outputBlob.arrayBuffer();
2526
+ }
2527
+ /**
2528
+ * Fetch a tile, apply corrections, and return the result.
2529
+ * @param {string} tileUrl - URL of the raster tile
2530
+ * @param {number} z - Zoom level
2531
+ * @param {number} x - Tile X coordinate
2532
+ * @param {number} y - Tile Y coordinate
2533
+ * @param {Object} layerConfig - Layer configuration with colors and styles
2534
+ * @param {Object} [options] - Fetch options
2535
+ * @param {number} [options.tileSize=256] - Tile size in pixels
2536
+ * @param {AbortSignal} [options.signal] - Abort signal for fetch
2537
+ * @param {RequestMode} [options.mode] - Fetch mode (e.g., 'cors')
2538
+ * @returns {Promise<{data: ArrayBuffer, wasFixed: boolean}>}
2539
+ */
2540
+ async fetchAndFixTile(tileUrl, z2, x2, y, layerConfig, options = {}) {
2541
+ const { tileSize = 256, signal, mode } = options;
2542
+ const fetchOptions = {};
2543
+ if (signal) fetchOptions.signal = signal;
2544
+ if (mode) fetchOptions.mode = mode;
2545
+ if (!layerConfig) {
2546
+ const response = await fetch(tileUrl, fetchOptions);
2547
+ if (!response.ok) throw new Error(`Tile fetch failed: ${response.status}`);
2548
+ return { data: await response.arrayBuffer(), wasFixed: false };
2549
+ }
2550
+ const [tileResult, correctionsResult] = await Promise.allSettled([
2551
+ fetch(tileUrl, fetchOptions).then((r) => {
2552
+ if (!r.ok) throw new Error(`Tile fetch failed: ${r.status}`);
2553
+ return r.arrayBuffer();
2554
+ }),
2555
+ this.getCorrections(z2, x2, y)
2556
+ ]);
2557
+ if (signal?.aborted) {
2558
+ throw new DOMException("Aborted", "AbortError");
2559
+ }
2560
+ if (tileResult.status === "rejected") {
2561
+ throw tileResult.reason;
2562
+ }
2563
+ const tileData = tileResult.value;
2564
+ const correctionsFailed = correctionsResult.status === "rejected";
2565
+ const correctionsError = correctionsFailed ? correctionsResult.reason : null;
2566
+ const corrections = correctionsResult.status === "fulfilled" ? correctionsResult.value : {};
2567
+ const hasCorrections = Object.values(corrections).some((arr) => arr && arr.length > 0);
2568
+ if (!hasCorrections) {
2569
+ return { data: tileData, wasFixed: false, correctionsFailed, correctionsError };
2570
+ }
2571
+ const fixedData = await this.fixTile(corrections, tileData, layerConfig, z2, tileSize);
2572
+ return { data: fixedData, wasFixed: true, correctionsFailed: false, correctionsError: null };
2573
+ }
2574
+ };
2575
+ export {
2576
+ BoundaryCorrector,
2577
+ MIN_LINE_WIDTH,
2578
+ getLineWidth
2579
+ };
2580
+ //# sourceMappingURL=index.js.map