@duoquote/polytini 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +119 -2
  3. package/dist/deckgl.cjs +250 -0
  4. package/dist/flexible.cjs +229 -0
  5. package/dist/google.cjs +232 -0
  6. package/dist/leaflet-auto.cjs +209 -0
  7. package/dist/leaflet.cjs +231 -0
  8. package/dist/mapbox.cjs +185 -0
  9. package/dist/maplibre.cjs +185 -0
  10. package/dist/node.cjs +322 -0
  11. package/dist/presets.cjs +65 -0
  12. package/dist/turf.cjs +267 -0
  13. package/dist/types/cli.d.cts +2 -0
  14. package/dist/types/deckgl.d.cts +72 -0
  15. package/dist/types/flexible.d.cts +92 -0
  16. package/dist/types/geojson.jsr.d.cts +111 -0
  17. package/dist/types/google.d.cts +48 -0
  18. package/dist/types/google.jsr.d.cts +72 -0
  19. package/dist/types/index.d.cts +109 -0
  20. package/dist/types/leaflet-auto.d.cts +4 -0
  21. package/dist/types/leaflet-auto.jsr.d.cts +2 -0
  22. package/dist/types/leaflet.d.cts +39 -0
  23. package/dist/types/leaflet.jsr.d.cts +15 -0
  24. package/dist/types/mapbox.d.cts +50 -0
  25. package/dist/types/mapbox.jsr.d.cts +5 -0
  26. package/dist/types/maplibre.d.cts +54 -0
  27. package/dist/types/maplibre.jsr.d.cts +92 -0
  28. package/dist/types/openlayers.d.cts +23 -0
  29. package/dist/types/openlayers.jsr.d.cts +42 -0
  30. package/dist/types/presets.d.cts +70 -0
  31. package/dist/types/turf.d.cts +33 -0
  32. package/dist/types/turf.jsr.d.cts +46 -0
  33. package/dist/types/wasm.d.cts +42 -0
  34. package/dist/web.cjs +231 -0
  35. package/package.json +198 -4
  36. package/src/browser.js +15 -0
  37. package/src/bun.js +4 -0
  38. package/src/cli-lib.js +160 -0
  39. package/src/cli.js +7 -0
  40. package/src/core.js +268 -0
  41. package/src/deckgl.js +176 -0
  42. package/src/deno.js +12 -0
  43. package/src/error.js +15 -0
  44. package/src/fast.js +179 -0
  45. package/src/flexible.js +283 -0
  46. package/src/google.js +70 -0
  47. package/src/leaflet-auto.js +11 -0
  48. package/src/leaflet.js +44 -0
  49. package/src/mapbox.js +10 -0
  50. package/src/maplibre.js +57 -0
  51. package/src/node.js +17 -0
  52. package/src/openlayers.js +172 -0
  53. package/src/presets.js +242 -0
  54. package/src/text.js +111 -0
  55. package/src/turf.js +80 -0
  56. package/src/wasm-bytes.js +2 -0
  57. package/src/wasm.js +235 -0
  58. package/src/web.js +9 -0
  59. package/types/cli.d.ts +2 -0
  60. package/types/deckgl.d.ts +72 -0
  61. package/types/flexible.d.ts +92 -0
  62. package/types/geojson.jsr.d.ts +111 -0
  63. package/types/google.d.ts +48 -0
  64. package/types/google.jsr.d.ts +72 -0
  65. package/types/index.d.ts +109 -0
  66. package/types/leaflet-auto.d.ts +4 -0
  67. package/types/leaflet-auto.jsr.d.ts +2 -0
  68. package/types/leaflet.d.ts +39 -0
  69. package/types/leaflet.jsr.d.ts +15 -0
  70. package/types/mapbox.d.ts +50 -0
  71. package/types/mapbox.jsr.d.ts +5 -0
  72. package/types/maplibre.d.ts +54 -0
  73. package/types/maplibre.jsr.d.ts +92 -0
  74. package/types/openlayers.d.ts +23 -0
  75. package/types/openlayers.jsr.d.ts +42 -0
  76. package/types/presets.d.ts +70 -0
  77. package/types/turf.d.ts +33 -0
  78. package/types/turf.jsr.d.ts +46 -0
  79. package/types/wasm.d.ts +42 -0
  80. package/wasm/polytini.wasm +0 -0
package/src/fast.js ADDED
@@ -0,0 +1,179 @@
1
+ // Fast paths for runtimes with Node's Buffer: Node and Bun. Each choice here
2
+ // was measured with the benchmark fixtures (see "Platform notes" in the
3
+ // README):
4
+ //
5
+ // - Decode copies the string into a scratch buffer with `ucs2Write` and
6
+ // parses the Uint16Array. On V8, charCodeAt in a hot loop re-checks the
7
+ // string representation on every call, and the copy is close to a memcpy.
8
+ // `latin1Write` is a bit faster but keeps only the low byte, so U+0151
9
+ // would turn into a valid "Q". UTF-16 keeps strict mode exact.
10
+ // - The decoder counts the points first (two characters per step, through
11
+ // a Uint32Array view), so the output array is allocated at its exact size.
12
+ // Growing it with push, or trimming an oversized one, both measured slower.
13
+ // - Encode writes bytes into a scratch buffer and makes the string with one
14
+ // `latin1Slice` call. That was 2 to 4 times faster than building the string
15
+ // with += on both V8 and JavaScriptCore, and the result is a flat string.
16
+ // - The character loops branch on "is there another chunk". A branchless
17
+ // version was faster on the real-world lines, where 1 and 2 character
18
+ // values alternate at random, but slower on the GPS tracks, where they come
19
+ // in runs the branch predictor learns. Branchy won 5 of the 6 columns.
20
+ // - Strings under 64 characters skip the copy and use the core's loop.
21
+ import { opts, st, LIMIT, slowDecode, slowEncode, decodeLoop, flip } from './core.js';
22
+
23
+ // Scratch memory is reused between calls up to this size. Bigger inputs get
24
+ // a temporary buffer, so one huge line doesn't pin megabytes for good.
25
+ const KEEP = 1 << 20;
26
+
27
+ // `grow`: above this many points, build the result by appending instead of
28
+ // allocating it at its final size. See node.js for why.
29
+ export function fast(Buffer, grow = Infinity) {
30
+ const ucs2Write = Buffer.prototype.ucs2Write, latin1Slice = Buffer.prototype.latin1Slice;
31
+ // The kept scratch buffer and its views. allocUnsafeSlow gives each buffer
32
+ // its own ArrayBuffer at offset 0, so the wider views are aligned.
33
+ let kept, k16, k32, u16;
34
+ const views = (buf) => [buf, new Uint16Array(buf.buffer, 0, buf.length >> 1), new Uint32Array(buf.buffer, 0, buf.length >> 2)];
35
+ [kept, k16, k32] = views(Buffer.allocUnsafeSlow(1 << 14));
36
+ const scratch = (bytes) => (bytes <= kept.length ? kept : bytes <= KEEP ? ([kept, k16, k32] = views(Buffer.allocUnsafeSlow(bytes)))[0] : Buffer.allocUnsafeSlow(bytes));
37
+
38
+ // Copies str into scratch as UTF-16, points u16 at it, and returns the
39
+ // number of values.
40
+ function load(str, len) {
41
+ const buf = scratch((len + 4) * 2 + 8);
42
+ ucs2Write.call(buf, str, 0);
43
+ let u32 = k32;
44
+ if (buf == kept) u16 = k16;
45
+ else [, u16, u32] = views(buf);
46
+ // Padding: '?' is a complete zero value, so a truncated string stops
47
+ // inside the buffer and leaves the index past len.
48
+ u16[len] = u16[len + 1] = u16[len + 2] = 63;
49
+ // Every value ends with one character below code 95. Count the others,
50
+ // which have bit 5 set after adding 1, two characters per word.
51
+ let more = 0;
52
+ for (let k = 0, w = (len + 1) >> 1; k < w; k++) {
53
+ const y = ((u32[k] + 0x10001) >>> 5) & 0x10001;
54
+ more += (y & 0xffff) + (y >>> 16);
55
+ }
56
+ return len - more;
57
+ }
58
+
59
+ // decodeLoop over the UTF-16 copy, with an exactly sized output. Returns
60
+ // null for slowDecode. Tuples and flat output are separate loops here: one
61
+ // shared loop with a per-point branch measured about 20% slower on
62
+ // JavaScriptCore at 10,000 points.
63
+ function big(str, f) {
64
+ const len = str.length, want = load(str, len) >> 1, b = u16, out = want > grow ? [] : Array(want);
65
+ let i = 0, n = 0, lat = 0, lng = 0, bad = 0, c, v, s;
66
+ while (i < len) {
67
+ c = b[i++] - 63;
68
+ bad |= c;
69
+ v = c & 31;
70
+ for (s = 5; c >= 32; s += 5) {
71
+ c = b[i++] - 63;
72
+ bad |= c | (25 - s);
73
+ v |= (c & 31) << s;
74
+ }
75
+ lat += (v >>> 1) ^ -(v & 1);
76
+ c = b[i++] - 63;
77
+ bad |= c;
78
+ v = c & 31;
79
+ for (s = 5; c >= 32; s += 5) {
80
+ c = b[i++] - 63;
81
+ bad |= c | (25 - s);
82
+ v |= (c & 31) << s;
83
+ }
84
+ lng += (v >>> 1) ^ -(v & 1);
85
+ out[n++] = [lat / f, lng / f];
86
+ }
87
+ // The count is exact for valid input, and invalid input stops here.
88
+ return bad & ~63 || i != len ? null : out;
89
+ }
90
+
91
+ function bigFlat(str, f, sw) {
92
+ const len = str.length, out = new Float64Array(load(str, len) & ~1), b = u16, a = +sw;
93
+ let i = 0, n = 0, lat = 0, lng = 0, bad = 0, c, v, s;
94
+ while (i < len) {
95
+ c = b[i++] - 63;
96
+ bad |= c;
97
+ v = c & 31;
98
+ for (s = 5; c >= 32; s += 5) {
99
+ c = b[i++] - 63;
100
+ bad |= c | (25 - s);
101
+ v |= (c & 31) << s;
102
+ }
103
+ lat += (v >>> 1) ^ -(v & 1);
104
+ c = b[i++] - 63;
105
+ bad |= c;
106
+ v = c & 31;
107
+ for (s = 5; c >= 32; s += 5) {
108
+ c = b[i++] - 63;
109
+ bad |= c | (25 - s);
110
+ v |= (c & 31) << s;
111
+ }
112
+ lng += (v >>> 1) ^ -(v & 1);
113
+ out[n + a] = lat / f;
114
+ out[n + 1 - a] = lng / f;
115
+ n += 2;
116
+ }
117
+ return bad & ~63 || i != len ? null : out;
118
+ }
119
+
120
+ const decodeWith = (str, o, flat) => {
121
+ const f = opts(o);
122
+ if (st.dims != 2 || typeof str != 'string') return slowDecode(str, f, flat);
123
+ const out = str.length < 64 ? decodeLoop(str, f, st.swap, flat) : flat ? bigFlat(str, f, st.swap) : big(str, f);
124
+ return out ? (st.swap && !flat ? flip(out) : out) : slowDecode(str, f, flat);
125
+ };
126
+
127
+ // Writes bytes into scratch, 7 per value at most below LIMIT. Returns null
128
+ // for slowEncode.
129
+ function encodeLoop(src, f, a, flat) {
130
+ const n = flat ? src.length >> 1 : src.length, buf = scratch(n * 14 + 8);
131
+ let i = 0, k = 0, la = 0, lb = 0, x, y, p, q, z, pt;
132
+ try {
133
+ for (; i < n; i++) {
134
+ if (flat) {
135
+ x = src[i * 2 + a];
136
+ y = src[i * 2 + 1 - a];
137
+ } else {
138
+ pt = src[i];
139
+ x = pt[a];
140
+ y = pt[1 - a];
141
+ }
142
+ if (typeof x != 'number' || typeof y != 'number' || !((x *= f) < LIMIT && x > -LIMIT && (y *= f) < LIMIT && y > -LIMIT)) return null;
143
+ // Round half away from zero. floor(|x| + 0.5) is exact here except for
144
+ // |x| = 0.49999999999999994, where the addition rounds up to 1, so any
145
+ // |x| < 0.5 is set to 0 afterwards. Math.round would be exact on its own,
146
+ // but it measured 40% slower on JavaScriptCore.
147
+ p = x < 0 ? -((0.5 - x) | 0) : (x + 0.5) | 0;
148
+ q = y < 0 ? -((0.5 - y) | 0) : (y + 0.5) | 0;
149
+ if (x < 0.5 && x > -0.5) p = 0;
150
+ if (y < 0.5 && y > -0.5) q = 0;
151
+ z = p - la;
152
+ z = (z << 1) ^ (z >> 31);
153
+ for (; z >= 32; z >>>= 5) buf[k++] = (z & 31) + 95;
154
+ buf[k++] = z + 63;
155
+ z = q - lb;
156
+ z = (z << 1) ^ (z >> 31);
157
+ for (; z >= 32; z >>>= 5) buf[k++] = (z & 31) + 95;
158
+ buf[k++] = z + 63;
159
+ la = p;
160
+ lb = q;
161
+ }
162
+ } catch {
163
+ return null;
164
+ }
165
+ return latin1Slice.call(buf, 0, k);
166
+ }
167
+
168
+ const encodeWith = (src, o, flat) => {
169
+ const f = opts(o);
170
+ return (st.dims == 2 && f <= 1e6 && (flat ? src != null && !(src.length % 2) : Array.isArray(src)) ? encodeLoop(src, f, +st.swap, flat) : null) ?? slowEncode(src, f, flat);
171
+ };
172
+
173
+ return {
174
+ decode: (str, o) => decodeWith(str, o, 0),
175
+ decodeFlat: (str, o) => decodeWith(str, o, 1),
176
+ encode: (src, o) => encodeWith(src, o, 0),
177
+ encodeFlat: (src, o) => encodeWith(src, o, 1),
178
+ };
179
+ }
@@ -0,0 +1,283 @@
1
+ // HERE's Flexible Polyline format, version 1:
2
+ // https://github.com/heremaps/flexible-polyline
3
+ //
4
+ // A string is [version][header][data], each part made of varints written
5
+ // with a URL-safe 64 character alphabet: 5 data bits per character, and a
6
+ // sixth bit that says another character follows. The header holds the
7
+ // precision (bits 0 to 3), the third dimension type (bits 4 to 6) and its
8
+ // precision (bits 7 to 10). The data is zigzag encoded deltas, 2 or 3 values
9
+ // per point, the first point relative to 0.
10
+ //
11
+ // Like the Google-format core, decode and encode have a fast loop for the
12
+ // common case and an exact `slow*` function for the rest, which also reports
13
+ // every kind of bad input. Precision 15 needs up to 64 bits, more than a
14
+ // Number holds exactly, so the slow functions switch to BigInt where Number
15
+ // math would lose bits.
16
+ //
17
+ // Errors are PolylineError with one of these codes:
18
+ // 'input' decode got a non-string, or encode got no array of points
19
+ // 'option' precision or thirdDimPrecision not an integer from 0 to 15,
20
+ // or thirdDim not 0, 1, 2, 3, 6 or 7
21
+ // 'char' a character outside the alphabet (index = its position)
22
+ // 'truncated' the string ends inside the header, a value or a point
23
+ // 'version' the format version is not 1, or the header has bits set
24
+ // above bit 10, which version 1 doesn't define
25
+ // 'overflow' a value needs more than 64 bits, the limit of the other
26
+ // implementations
27
+ // 'coordinate' encode got a missing or non-finite value (index = point)
28
+ /* @ts-self-types="../types/flexible.d.ts" */
29
+ import { PolylineError, fail } from './error.js';
30
+
31
+ export { PolylineError };
32
+
33
+ // Third dimension types, as stored in the header. 4 and 5 are reserved:
34
+ // decode accepts them and encode refuses them, like the official code.
35
+ export const ABSENT = 0;
36
+ export const LEVEL = 1;
37
+ export const ALTITUDE = 2;
38
+ export const ELEVATION = 3;
39
+ export const RESERVED1 = 4;
40
+ export const RESERVED2 = 5;
41
+ export const CUSTOM1 = 6;
42
+ export const CUSTOM2 = 7;
43
+ const TYPES = [0, 1, 2, 3, 6, 7];
44
+
45
+ const E = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
46
+
47
+ // Character code to 6-bit value. 64 marks a character outside the alphabet,
48
+ // so OR-ing every value together and testing for > 63 finds them all.
49
+ const T = new Uint8Array(128).fill(64);
50
+ for (let i = 0; i < 64; i++) T[E.charCodeAt(i)] = i;
51
+
52
+ // The characters of every value below 1024, so one or two characters cost
53
+ // one concatenation instead of a loop.
54
+ const C = [];
55
+ for (let z = 0; z < 1024; z++) C[z] = z < 32 ? E[z] : E[(z & 31) | 32] + E[z >> 5];
56
+
57
+ // 10 ** p from parsed literals, so every factor is exact.
58
+ const P = [];
59
+ for (let p = 0; p < 16; p++) P[p] = +('1e' + p);
60
+
61
+ // The characters of an unsigned value below 2^53. Float math, because the
62
+ // bit operators would cut it to 32 bits.
63
+ const chars = (z) => {
64
+ let s = '';
65
+ for (; z > 31; z = Math.floor(z / 32)) s += E[(z % 32) | 32];
66
+ return s + E[z];
67
+ };
68
+
69
+ const range = (p, name) => (typeof p == 'number' && p >= 0 && p <= 15 && p % 1 == 0 ? p : fail('option', name + ' must be an integer from 0 to 15'));
70
+
71
+ /**
72
+ * Reads the version and the header. Returns the header bits plus 2048 times
73
+ * the index where the data starts, so decode allocates nothing for it.
74
+ */
75
+ function head(str) {
76
+ if (typeof str != 'string') fail('input', 'Expected a string');
77
+ let i = 0, k = 0, v, m, c;
78
+ for (; k < 2; k++) {
79
+ // Both are varints. The version is always 'B' in practice, and the
80
+ // header takes 1 to 3 characters.
81
+ for (v = 0, m = 1, c = 32; c & 32; m *= 32, i++) {
82
+ if (i >= str.length) fail('truncated', 'Polyline ends inside the header', i);
83
+ c = T[str.charCodeAt(i)];
84
+ if (!(c < 64)) fail('char', 'Invalid character ' + JSON.stringify(str[i]), i);
85
+ v += (c & 31) * m;
86
+ }
87
+ if (!k && v != 1) fail('version', 'Unsupported format version ' + v, 0);
88
+ }
89
+ // Also false for NaN, from a long run of continuation characters.
90
+ return v < 2048 ? v + i * 2048 : fail('version', 'Invalid header', i);
91
+ }
92
+
93
+ /** Reads the header without decoding the points. */
94
+ export function header(str) {
95
+ const h = head(str) % 2048;
96
+ return { precision: h & 15, thirdDim: (h >> 4) & 7, thirdDimPrecision: h >> 7 };
97
+ }
98
+
99
+ /**
100
+ * Decodes to { precision, thirdDim, thirdDimPrecision, polyline }, the same
101
+ * object @here/flexpolyline returns. Points are [lat, lng], or [lat, lng, z]
102
+ * when the header has a third dimension.
103
+ */
104
+ export function decode(str) {
105
+ const r = head(str), h = r % 2048, i = (r - h) / 2048, t = (h >> 4) & 7, f = P[h & 15], fz = P[h >> 7];
106
+ return { precision: h & 15, thirdDim: t, thirdDimPrecision: h >> 7, polyline: decodeLoop(str, i, f, fz, t) || slowDecode(str, i, f, fz, t ? 3 : 2) };
107
+ }
108
+
109
+ // The fast loop, or null when the input needs slowDecode: an invalid
110
+ // character, a truncated string, or a value of more than 10 characters.
111
+ // The value reader is written out three times: a shared helper or one
112
+ // generic loop over the axes measured 15 to 25% slower on V8.
113
+ function decodeLoop(str, i, f, fz, three) {
114
+ const len = str.length, out = [];
115
+ let n = 0, a = 0, b = 0, z = 0, bad = 0, w = 0, k, c, v, s;
116
+ // A code above 127 keeps its high bits in c, which marks it bad without
117
+ // changing the 6 value bits. Past the end, NaN reads as T[0], also bad,
118
+ // and ends the value. The first 6 characters (30 bits) use 32-bit math,
119
+ // later ones float math, exact up to 10 characters (50 bits). Float
120
+ // values then need float zigzag, as the bit operators cut to 32 bits.
121
+ // The sums stay exact below 2^53: w bounds what the large values add up
122
+ // to, and small ones would need a string of over 64 million characters.
123
+ while (i < len) {
124
+ k = str.charCodeAt(i++);
125
+ bad |= c = T[k & 127] | (k & -128);
126
+ for (v = c & 31, s = 5; c & 32; s += 5) {
127
+ k = str.charCodeAt(i++);
128
+ bad |= c = T[k & 127] | (k & -128);
129
+ if (s < 30) v |= (c & 31) << s;
130
+ else if (s < 50) w += v += (c & 31) * 2 ** s;
131
+ else bad = 64;
132
+ }
133
+ a += s > 30 ? (v % 2 ? -(v + 1) / 2 : v / 2) : (v >>> 1) ^ -(v & 1);
134
+ k = str.charCodeAt(i++);
135
+ bad |= c = T[k & 127] | (k & -128);
136
+ for (v = c & 31, s = 5; c & 32; s += 5) {
137
+ k = str.charCodeAt(i++);
138
+ bad |= c = T[k & 127] | (k & -128);
139
+ if (s < 30) v |= (c & 31) << s;
140
+ else if (s < 50) w += v += (c & 31) * 2 ** s;
141
+ else bad = 64;
142
+ }
143
+ b += s > 30 ? (v % 2 ? -(v + 1) / 2 : v / 2) : (v >>> 1) ^ -(v & 1);
144
+ if (three) {
145
+ k = str.charCodeAt(i++);
146
+ bad |= c = T[k & 127] | (k & -128);
147
+ for (v = c & 31, s = 5; c & 32; s += 5) {
148
+ k = str.charCodeAt(i++);
149
+ bad |= c = T[k & 127] | (k & -128);
150
+ if (s < 30) v |= (c & 31) << s;
151
+ else if (s < 50) w += v += (c & 31) * 2 ** s;
152
+ else bad = 64;
153
+ }
154
+ z += s > 30 ? (v % 2 ? -(v + 1) / 2 : v / 2) : (v >>> 1) ^ -(v & 1);
155
+ out[n++] = [a / f, b / f, z / fz];
156
+ } else out[n++] = [a / f, b / f];
157
+ }
158
+ return bad > 63 || i > len || w > 2 ** 52 ? null : out;
159
+ }
160
+
161
+ /** Exact decoder with BigInt sums, which also reports errors. */
162
+ function slowDecode(str, i, f, fz, d) {
163
+ const out = [], sum = [0n, 0n, 0n];
164
+ let pt = [], j = 0, v = 0n, s = 0n, k, c;
165
+ for (; i < str.length; i++) {
166
+ k = str.charCodeAt(i);
167
+ c = k < 128 ? T[k] : 64;
168
+ if (c > 63) fail('char', 'Invalid character ' + JSON.stringify(str[i]), i);
169
+ v |= BigInt(c & 31) << s;
170
+ if (c & 32) {
171
+ if ((s += 5n) > 60n) fail('overflow', 'Value too large', i);
172
+ continue;
173
+ }
174
+ if (v >> 64n) fail('overflow', 'Value too large', i);
175
+ sum[j] += v & 1n ? ~(v >> 1n) : v >> 1n;
176
+ pt[j] = Number(sum[j]) / (j < 2 ? f : fz);
177
+ if (++j == d) {
178
+ out.push(pt);
179
+ pt = [];
180
+ j = 0;
181
+ }
182
+ v = s = 0n;
183
+ }
184
+ if (s || j) fail('truncated', 'Polyline ends inside a ' + (s ? 'value' : 'point'), i);
185
+ return out;
186
+ }
187
+
188
+ /**
189
+ * Encodes points. Takes the @here/flexpolyline argument,
190
+ * { polyline, precision, thirdDim, thirdDimPrecision }, or the points with
191
+ * those fields in `options`, which win over the object's. Points are
192
+ * [lat, lng] or [lat, lng, z] arrays, or one flat array of numbers. Rounds
193
+ * half away from zero.
194
+ */
195
+ export function encode(input, options) {
196
+ const obj = input != null && typeof input == 'object' && !(input.length >= 0), a = obj ? input : {}, o = options || {};
197
+ const pts = obj ? input.polyline : input;
198
+ const p = range(o.precision ?? a.precision ?? 5, 'precision');
199
+ const q = range(o.thirdDimPrecision ?? a.thirdDimPrecision ?? 0, 'thirdDimPrecision');
200
+ const t = o.thirdDim ?? a.thirdDim ?? 0;
201
+ if (!TYPES.includes(t)) fail('option', 'thirdDim must be 0, 1, 2, 3, 6 or 7');
202
+ if (pts == null || !(pts.length >= 0)) fail('input', 'Expected an array of points');
203
+ const s = 'B' + chars((q << 7) | (t << 4) | p), d = t ? 3 : 2, flat = typeof pts[0] == 'number';
204
+ if (flat && pts.length % d) fail('input', 'Flat array length is not a multiple of ' + d);
205
+ return (!flat && encodeLoop(pts, P[p], P[q], t, s)) || slowEncode(pts, P[p], P[q], d, flat, s);
206
+ }
207
+
208
+ // Scaled values below this keep deltas and zigzag values in 32-bit math.
209
+ // It covers coordinates up to precision 6.
210
+ const LIMIT = 2 ** 29;
211
+
212
+ // Rounded values below this keep deltas and zigzag values below 2^53.
213
+ const WIDE = 2 ** 51;
214
+
215
+ // The fast loop for arrays of points, or undefined when the input needs
216
+ // slowEncode: a value that is missing, not finite or too large.
217
+ function encodeLoop(pts, f, fz, three, s) {
218
+ const n = pts.length;
219
+ let i = 0, la = 0, lb = 0, lz = 0, x, y, w, p, q, r, z, pt;
220
+ try {
221
+ for (; i < n; i++) {
222
+ pt = pts[i];
223
+ x = pt[0] * f;
224
+ y = pt[1] * f;
225
+ w = three ? pt[2] * fz : 0;
226
+ // Also false for NaN, so missing values go the slow way.
227
+ if (!(x < LIMIT && x > -LIMIT && y < LIMIT && y > -LIMIT && w < LIMIT && w > -LIMIT)) return;
228
+ // Round half away from zero. Below LIMIT, adding 0.5 and truncating
229
+ // gives the exact result.
230
+ p = x < 0 ? -((0.5 - x) | 0) : (x + 0.5) | 0;
231
+ q = y < 0 ? -((0.5 - y) | 0) : (y + 0.5) | 0;
232
+ z = p - la;
233
+ z = (z << 1) ^ (z >> 31);
234
+ s += z < 1024 ? C[z] : chars(z);
235
+ z = q - lb;
236
+ z = (z << 1) ^ (z >> 31);
237
+ s += z < 1024 ? C[z] : chars(z);
238
+ la = p;
239
+ lb = q;
240
+ if (three) {
241
+ r = w < 0 ? -((0.5 - w) | 0) : (w + 0.5) | 0;
242
+ z = r - lz;
243
+ z = (z << 1) ^ (z >> 31);
244
+ s += z < 1024 ? C[z] : chars(z);
245
+ lz = r;
246
+ }
247
+ }
248
+ } catch {
249
+ return;
250
+ }
251
+ return s;
252
+ }
253
+
254
+ /**
255
+ * Exact encoder for any input. Rounded values are whole doubles, exact at
256
+ * any size, so they stay Numbers. Their deltas and zigzag values use float
257
+ * math below WIDE, where it is exact, and BigInt above.
258
+ */
259
+ function slowEncode(pts, f, fz, d, flat, s) {
260
+ const n = flat ? pts.length / d : pts.length, last = [0, 0, 0];
261
+ for (let i = 0; i < n; i++) {
262
+ const pt = flat ? null : pts[i];
263
+ if (!flat && pt == null) fail('coordinate', 'Invalid point', i);
264
+ for (let a = 0; a < d; a++) {
265
+ const x = (flat ? pts[i * d + a] : pt[a]) * (a < 2 ? f : fz);
266
+ if (!(x - x == 0)) fail('coordinate', 'Invalid coordinate', i);
267
+ // Math.round of the magnitude is exact at any size. Adding 0.5 and
268
+ // flooring would round 2^52 + 1 up to 2^52 + 2.
269
+ const r = x < 0 ? -Math.round(-x) : Math.round(x), l = last[a];
270
+ let z = r - l;
271
+ last[a] = r;
272
+ if (r < WIDE && r > -WIDE && l < WIDE && l > -WIDE) s += chars(z < 0 ? -2 * z - 1 : 2 * z);
273
+ else {
274
+ z = BigInt(r) - BigInt(l);
275
+ z = z < 0n ? ~(z << 1n) : z << 1n;
276
+ if (z >> 64n) fail('overflow', 'Value too large', i);
277
+ for (; z > 31n; z >>= 5n) s += E[Number(z & 31n) | 32];
278
+ s += E[Number(z)];
279
+ }
280
+ }
281
+ }
282
+ return s;
283
+ }
package/src/google.js ADDED
@@ -0,0 +1,70 @@
1
+ // Google Maps JavaScript API helpers: decodePath and encodePath with the
2
+ // signatures of google.maps.geometry.encoding, without loading the geometry
3
+ // library.
4
+ //
5
+ // import { decodePath, encodePath } from '@duoquote/polytini/google';
6
+ // const path = decodePath(route.polyline.encodedPolyline);
7
+ // new google.maps.Polyline({ path, map });
8
+ // encodePath(polyline.getPath()); // an MVCArray<LatLng>
9
+ //
10
+ // Differences from google.maps.geometry.encoding:
11
+ // - Both take an optional second argument: polytini's precision (a number)
12
+ // or options object. Precision defaults to 5, Google's fixed value.
13
+ // - decodePath returns google.maps.LatLng objects when a LatLng constructor
14
+ // is available (the LatLng option, else globalThis.google.maps.LatLng),
15
+ // and plain { lat, lng } literals otherwise, so it also works in Node or
16
+ // before the Maps API has loaded. Pass `LatLng: false` for literals even
17
+ // when the API is loaded. Polyline, Polygon and most Maps API methods
18
+ // take literals as well as LatLng, and literals are cheaper to create.
19
+ // - Strict by default: malformed strings and invalid coordinates throw a
20
+ // PolylineError. Google documents no error behavior for decodePath or
21
+ // encodePath, so what they return for such input can't be matched; a
22
+ // thrown error is easier to find than a wrong line on the map, and valid
23
+ // input gives the same result either way. Pass `strict: false` to never
24
+ // throw on bad characters or truncated strings (invalid characters are
25
+ // skipped and an incomplete last point is dropped) or on invalid
26
+ // coordinates (encoded as 0).
27
+ // - encodePath also takes polytini's [lat, lng] tuples and encodes
28
+ // LatLngLiteral values as given, without clamping or wrapping them.
29
+ /* @ts-self-types="../types/google.jsr.d.ts" */
30
+ import { decode, encode } from './web.js';
31
+
32
+ export { PolylineError } from './web.js';
33
+
34
+ // decodePath reads the tuples as [lat, lng], so it ignores order 'lnglat'.
35
+ const latFirst = (o) => (o?.order == 'lnglat' ? { ...o, order: 'latlng' } : o);
36
+
37
+ /**
38
+ * Decodes an encoded path to google.maps.LatLng objects, or to LatLngLiteral
39
+ * objects when no LatLng constructor is available. Options: polytini's
40
+ * (precision, strict, factor, dimensions), plus `LatLng` (a constructor, or
41
+ * false for literals) and `noClampNoWrap` (passed to the LatLng constructor;
42
+ * without it, Google's LatLng clamps latitude and wraps longitude 180 to -180).
43
+ */
44
+ export function decodePath(encodedPath, o) {
45
+ // o is a number, an options object or undefined; o?.x reads all three.
46
+ const C = o?.LatLng !== undefined ? o.LatLng : globalThis.google?.maps?.LatLng;
47
+ const pts = decode(encodedPath, latFirst(o)), nw = o?.noClampNoWrap;
48
+ for (let i = 0; i < pts.length; i++) {
49
+ const [lat, lng] = pts[i];
50
+ pts[i] = C ? new C(lat, lng, nw) : { lat, lng };
51
+ }
52
+ return pts;
53
+ }
54
+
55
+ /**
56
+ * Encodes an array or MVCArray of google.maps.LatLng objects, LatLngLiteral
57
+ * objects or [lat, lng] tuples (mixed is fine). Options: polytini's
58
+ * (precision, strict, factor, dimensions, and order for tuples and LatLng
59
+ * objects; literals are read by name).
60
+ */
61
+ export function encodePath(path, o) {
62
+ if (path && typeof path.getArray == 'function') path = path.getArray();
63
+ if (Array.isArray(path)) {
64
+ const sw = o?.order == 'lnglat';
65
+ // LatLng objects have lat() and lng() methods; the core reads literals
66
+ // and tuples directly.
67
+ path = path.map((p) => (p && typeof p.lat == 'function' ? (sw ? [p.lng(), p.lat()] : [p.lat(), p.lng()]) : p));
68
+ }
69
+ return encode(path, o);
70
+ }
@@ -0,0 +1,11 @@
1
+ // Side-effect import: patches the global L (Leaflet's UMD build sets it).
2
+ // import 'leaflet';
3
+ // import '@duoquote/polytini/leaflet/auto';
4
+ // For ES module imports of Leaflet, and Leaflet 2, call install(L) from
5
+ // @duoquote/polytini/leaflet instead.
6
+ /* @ts-self-types="../types/leaflet-auto.jsr.d.ts" */
7
+ import { install } from './leaflet.js';
8
+
9
+ const L = globalThis.L;
10
+ if (!L?.Polyline) throw new Error('@duoquote/polytini/leaflet/auto: load Leaflet first, or call install(L) from @duoquote/polytini/leaflet');
11
+ install(L);
package/src/leaflet.js ADDED
@@ -0,0 +1,44 @@
1
+ // Leaflet plugin: encoded polylines in and out of L.Polyline and L.Polygon.
2
+ //
3
+ // import L from 'leaflet';
4
+ // import { install } from '@duoquote/polytini/leaflet';
5
+ // install(L);
6
+ // L.Polyline.fromEncoded('_p~iF~ps|U_ulLnnqC_mqNvxq`@', { color: 'red' }).addTo(map);
7
+ //
8
+ // Works with Leaflet 1.9 (the global L, the UMD build or ESM imports) and the
9
+ // Leaflet 2 betas, where L is a frozen module namespace of ES classes: there
10
+ // the static and prototype methods are added, and the lower-case factories
11
+ // are skipped because the namespace can't take new properties.
12
+ //
13
+ // It also covers the API of the old Polyline.encoded.js plugin (npm
14
+ // polyline-encoded): L.Polyline.fromEncoded, L.Polygon.fromEncoded,
15
+ // encodePath() and L.PolylineUtil, so it can replace it.
16
+ /* @ts-self-types="../types/leaflet.jsr.d.ts" */
17
+ import { encode, decode } from './web.js';
18
+
19
+ // One string decodes to one line or ring, arrays nest: string[] is a
20
+ // multi-polyline or a polygon with holes, string[][] a multi-polygon.
21
+ const toLatLngs = (s, o) => (typeof s == 'string' ? decode(s, o) : s.map((x) => toLatLngs(x, o)));
22
+
23
+ // The reverse, from getLatLngs(): LatLng[] encodes to a string, nested arrays
24
+ // to nested arrays of strings.
25
+ const toStrings = (l, o) => (Array.isArray(l[0]) ? l.map((x) => toStrings(x, o)) : encode(l.map((p) => [p.lat, p.lng]), o));
26
+
27
+ export function install(L) {
28
+ const { Polyline, Polygon } = L;
29
+ const add = (C, name) => {
30
+ C.fromEncoded = (s, o) => new C(toLatLngs(s, o), o);
31
+ C.prototype.toEncoded = function (o) {
32
+ return toStrings(this.getLatLngs(), o);
33
+ };
34
+ // Polyline.encoded.js name.
35
+ C.prototype.encodePath = C.prototype.toEncoded;
36
+ if (Object.isExtensible(L)) L[name] = C.fromEncoded;
37
+ };
38
+ add(Polyline, 'polylineEncoded');
39
+ add(Polygon, 'polygonEncoded');
40
+ if (Object.isExtensible(L)) L.PolylineUtil ??= { encode, decode };
41
+ return L;
42
+ }
43
+
44
+ export { encode, decode };
package/src/mapbox.js ADDED
@@ -0,0 +1,10 @@
1
+ // Mapbox GL JS 3: the same functions as the MapLibre module. The calls they
2
+ // make (addSource with a GeoJSON source specification, addLayer with a line
3
+ // layer and a beforeId, getSource(id).setData) take the same arguments in
4
+ // both libraries, so only the types differ: types/mapbox.d.ts uses
5
+ // mapbox-gl's.
6
+ //
7
+ // import { addPolylineLayer } from '@duoquote/polytini/mapbox';
8
+ // map.on('load', () => addPolylineLayer(map, 'route', encoded, { layer: { paint: { 'line-color': '#c00' } } }));
9
+ /* @ts-self-types="../types/mapbox.jsr.d.ts" */
10
+ export { polylineData, polylineSource, addPolylineLayer, setPolylineData } from './maplibre.js';
@@ -0,0 +1,57 @@
1
+ // MapLibre GL JS (and Mapbox GL JS, see mapbox.js): encoded polylines as
2
+ // GeoJSON sources and line layers.
3
+ //
4
+ // import { addPolylineLayer, setPolylineData } from '@duoquote/polytini/maplibre';
5
+ // map.on('load', () => {
6
+ // addPolylineLayer(map, 'route', route.geometry, { precision: 6, layer: { paint: { 'line-width': 4 } } });
7
+ // });
8
+ // setPolylineData(map, 'route', newRoute.geometry, { precision: 6 });
9
+ //
10
+ // No map library code is imported: the functions only call addSource,
11
+ // addLayer and getSource(id).setData on the map they are given, which
12
+ // MapLibre GL 4 to 6 and Mapbox GL 3 all have with the same arguments.
13
+ // Coordinates come out as [lng, lat] like all GeoJSON, whatever `order` the
14
+ // options or a preset say.
15
+ /* @ts-self-types="../types/maplibre.jsr.d.ts" */
16
+ import { toFeatureCollection } from './turf.js';
17
+ import { fail } from './core.js';
18
+
19
+ const list = (encoded) => (typeof encoded == 'string' ? [encoded] : encoded);
20
+
21
+ /**
22
+ * The FeatureCollection<LineString> for one encoded string or many.
23
+ * Options: polytini options or a preset, plus `properties` and `id` (one
24
+ * value for all lines or an array with one per line) and `bbox`.
25
+ */
26
+ export const polylineData = (encoded, options) => toFeatureCollection(list(encoded), options);
27
+
28
+ /**
29
+ * A GeoJSON source specification, `{ type: 'geojson', data }`, for addSource
30
+ * or a style's `sources`. `options.source` adds source options such as
31
+ * lineMetrics, tolerance or promoteId.
32
+ */
33
+ export const polylineSource = (encoded, options) => ({ ...options?.source, type: 'geojson', data: polylineData(encoded, options) });
34
+
35
+ /**
36
+ * Adds a GeoJSON source and a line layer that draws it, both named `id`.
37
+ * `options.layer` is merged into the layer (paint, layout, filter, minzoom,
38
+ * a different id, and so on), and `options.beforeId` is passed to addLayer.
39
+ * Returns the map.
40
+ */
41
+ export function addPolylineLayer(map, id, encoded, options) {
42
+ map.addSource(id, polylineSource(encoded, options));
43
+ map.addLayer({ id, type: 'line', source: id, ...options?.layer }, options?.beforeId);
44
+ return map;
45
+ }
46
+
47
+ /**
48
+ * Replaces the data of the GeoJSON source `id` with new lines and returns
49
+ * what the source's setData returns (a Promise in MapLibre, the source in
50
+ * Mapbox). Throws a PolylineError with code 'input' if there is no such
51
+ * GeoJSON source.
52
+ */
53
+ export function setPolylineData(map, id, encoded, options) {
54
+ const source = map.getSource(id);
55
+ if (typeof source?.setData != 'function') fail('input', 'No GeoJSON source named ' + id);
56
+ return source.setData(polylineData(encoded, options));
57
+ }