@geolith/glx 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ geolith .glx
2
+ Copyright 2026 Vinayak Kulkarni
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # @geolith/glx
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reads [`.glx`](https://github.com/geolith/glx) geocoding files from object
4
+ storage or HTTP: search, autocomplete, structured search, reverse geocoding,
5
+ nearby and place lookup.
6
+
7
+ A `.glx` file is a single-file geocoding index, as a `.pmtiles` file is for map
8
+ tiles. The reader keeps a small part of the file in memory and reads the rest
9
+ with byte-range requests, so the file can stay in R2, S3 or behind any HTTP
10
+ server. The reader is the same Rust code that the geolith search server runs,
11
+ built to WebAssembly, so both give the same answers.
12
+
13
+ Documentation: [docs.geolith.app/glx](https://docs.geolith.app/glx).
14
+ Format: [spec/v1/spec.md](https://github.com/geolith/glx/blob/main/spec/v1/spec.md).
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ npm install @geolith/glx
20
+ ```
21
+
22
+ ESM only. Node 26 or later, Cloudflare Workers, or a modern browser.
23
+
24
+ ## Use it in a Cloudflare Worker (R2)
25
+
26
+ ```ts
27
+ import wasm from '@geolith/glx/glx.wasm';
28
+ import { GlxFile, R2Source, init } from '@geolith/glx';
29
+
30
+ init(wasm);
31
+
32
+ export default {
33
+ async fetch(request: Request, env: { GLX: R2Bucket }): Promise<Response> {
34
+ const file = await GlxFile.open(new R2Source(env.GLX, 'planet.glx'));
35
+ const text = new URL(request.url).searchParams.get('text') ?? '';
36
+ const { collection } = await file.search({ text });
37
+ return Response.json(collection);
38
+ },
39
+ };
40
+ ```
41
+
42
+ Open the file once per isolate and reuse the `GlxFile`: opening reads the
43
+ header and the small in-memory sections.
44
+
45
+ ## Use it over HTTP (Node or the browser)
46
+
47
+ ```ts
48
+ import { readFile } from 'node:fs/promises';
49
+ import { fileURLToPath } from 'node:url';
50
+ import { FetchSource, GlxFile, init } from '@geolith/glx';
51
+
52
+ init(
53
+ await readFile(fileURLToPath(import.meta.resolve('@geolith/glx/glx.wasm'))),
54
+ );
55
+
56
+ const file = await GlxFile.open(
57
+ new FetchSource('https://example.com/planet.glx'),
58
+ );
59
+ const { collection } = await file.reverse({
60
+ lon: 77.2295,
61
+ lat: 28.6129,
62
+ radiusKm: 1,
63
+ });
64
+ ```
65
+
66
+ The server must answer `Range` requests. In the browser, fetch the `.wasm`
67
+ bytes (for example with a bundler `?url` import) and pass them to `init`.
68
+ `FileSource` reads a local `File` or `Blob`.
69
+
70
+ ## Exports
71
+
72
+ | Export | What |
73
+ | ------------------------------ | ----------------------------------------------------------------- |
74
+ | `@geolith/glx` | `init`, `GlxFile`, `R2Source`, `FetchSource`, `FileSource`, types |
75
+ | `@geolith/glx/glx.wasm` | The reader |
76
+ | `@geolith/glx/glx-parser.wasm` | The reader with the trained query parser (larger; same API) |
77
+
78
+ ## License
79
+
80
+ Apache-2.0. See [LICENSE](https://github.com/geolith/glx/blob/main/LICENSE)
81
+ and NOTICE.
Binary file
Binary file
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Merges byte spans `[offset, length]` into at most `count` ranges. The pair
3
+ * with the smallest gap merges first; a merge whose range would pass
4
+ * `maxBytes` is not made, so more than `count` ranges can remain.
5
+ */
6
+ export declare function coalesce(spans: readonly (readonly [number, number])[], count: number, maxBytes: number): [number, number][];
7
+ /** An invalid query, rejected before any read. */
8
+ export declare class GlxQueryError extends Error {
9
+ readonly name = "GlxQueryError";
10
+ }
11
+ /** Where a `.glx` file's bytes come from. */
12
+ interface Source {
13
+ /** Names the file, for logs and cache keys. */
14
+ readonly key: string;
15
+ /** The bytes `[offset, offset + length)`. */
16
+ getBytes(offset: number, length: number): Promise<Uint8Array>;
17
+ }
18
+ /** The part of a Cloudflare R2 bucket binding that a source needs. */
19
+ interface R2BucketLike {
20
+ get(key: string, options: {
21
+ range: {
22
+ offset: number;
23
+ length: number;
24
+ };
25
+ }): Promise<{
26
+ arrayBuffer(): Promise<ArrayBuffer>;
27
+ } | null>;
28
+ }
29
+ /** How a wave of reads is sent. */
30
+ interface ReadOptions {
31
+ /** Most ranges one wave is merged into. Default 3. */
32
+ maxRanges?: number;
33
+ /** A merge that would make a range longer than this is not made. Default 4 MiB. */
34
+ maxRangeBytes?: number;
35
+ /**
36
+ * Copies of each range sent at once; the first answer wins, which cuts
37
+ * the slow tail of object storage. Used only while ranges × copies fits in
38
+ * six concurrent reads. Default 2.
39
+ */
40
+ hedge?: number;
41
+ }
42
+ /** Read limits for one query; unset fields keep the reader's default. */
43
+ interface Budget {
44
+ /** Posting bytes one search may walk (default 16 MiB). */
45
+ walkBytes?: number;
46
+ /** Document-block bytes one search may read (default 12 MiB). */
47
+ recordBytes?: number;
48
+ /** Read waves one search may take (default 16). */
49
+ maxWaves?: number;
50
+ /**
51
+ * Record blocks one record wave may ask for beyond the first page
52
+ * (default 512). Smaller reads far fewer bytes; answers can change for
53
+ * searches that then reach the wave or record budget.
54
+ */
55
+ recordWaveBlocks?: number;
56
+ }
57
+ /** A layer of the index: the seven layers the `.glx` format codes. */
58
+ type Layer = 'venue' | 'address' | 'street' | 'locality' | 'county' | 'region' | 'country';
59
+ /** Filters shared by every query. */
60
+ interface Filters {
61
+ /** Results wanted, 1 to 40. Default 10. */
62
+ size?: number;
63
+ /** Layers to search; empty or unset means all. */
64
+ layers?: readonly Layer[];
65
+ /** ISO 3166-1 alpha-2 codes, any case; empty or unset means all. */
66
+ countries?: readonly string[];
67
+ }
68
+ /** A point, in degrees. */
69
+ interface Point {
70
+ lon: number;
71
+ lat: number;
72
+ }
73
+ /** Options of {@link GlxFile.search} and {@link GlxFile.autocomplete}. */
74
+ interface SearchParams extends Filters {
75
+ text: string;
76
+ /** Places near this point rank higher. */
77
+ focus?: Point;
78
+ budget?: Budget;
79
+ }
80
+ /** Fields of {@link GlxFile.structured}; at least one must be set. */
81
+ interface StructuredParams extends Filters {
82
+ address?: string;
83
+ neighbourhood?: string;
84
+ borough?: string;
85
+ locality?: string;
86
+ county?: string;
87
+ region?: string;
88
+ postalcode?: string;
89
+ /** A two-letter code becomes a country filter; other text is searched. */
90
+ country?: string;
91
+ focus?: Point;
92
+ budget?: Budget;
93
+ }
94
+ /** Options of {@link GlxFile.reverse} and {@link GlxFile.nearby}. */
95
+ interface NearbyParams extends Filters, Point {
96
+ /** Radius in kilometres, greater than 0. */
97
+ radiusKm: number;
98
+ }
99
+ /** A ring of `[lon, lat]` points, closed. */
100
+ type Ring = Array<[number, number]>;
101
+ /** A feature's geometry: its point, or its outline when asked for. */
102
+ type Geometry = {
103
+ type: 'Point';
104
+ coordinates: [number, number];
105
+ } | {
106
+ type: 'Polygon';
107
+ coordinates: Ring[];
108
+ } | {
109
+ type: 'MultiPolygon';
110
+ coordinates: Ring[][];
111
+ };
112
+ /** A Pelias GeoJSON feature. */
113
+ interface Feature {
114
+ type: 'Feature';
115
+ geometry: Geometry;
116
+ properties: Properties;
117
+ /** The outline's box, `[west, south, east, north]`, when it has one. */
118
+ bbox?: [number, number, number, number];
119
+ }
120
+ /** Options of {@link GlxFile.place}. */
121
+ interface PlaceOptions {
122
+ /** Return each place's outline as its geometry when it has one. */
123
+ geometry?: boolean;
124
+ }
125
+ /** Properties of a {@link Feature}. */
126
+ interface Properties {
127
+ id: string;
128
+ /** `geolith:<layer>:<id>`. */
129
+ gid: string;
130
+ layer: string;
131
+ source: 'geolith';
132
+ name: string;
133
+ label: string;
134
+ importance: number;
135
+ street?: string;
136
+ postalcode?: string;
137
+ country_code?: string;
138
+ country?: string;
139
+ region?: string;
140
+ county?: string;
141
+ locality?: string;
142
+ /** Share of the query's words the place contains (text searches). */
143
+ confidence?: number;
144
+ /** Kilometres from the focus or query point. */
145
+ distance?: number;
146
+ /** The place's point, when its geometry is its outline. */
147
+ center?: [number, number];
148
+ }
149
+ /** How a result list was ranked. */
150
+ type Ranking = 'importance' | 'importance+distance';
151
+ /** A Pelias `FeatureCollection`. */
152
+ interface FeatureCollection {
153
+ type: 'FeatureCollection';
154
+ geocoding: {
155
+ version: string;
156
+ attribution: string;
157
+ query: Record<string, unknown>;
158
+ engine: {
159
+ name: string;
160
+ version: string;
161
+ };
162
+ };
163
+ features: Feature[];
164
+ bbox?: [number, number, number, number];
165
+ }
166
+ /** What one query read. */
167
+ interface QueryStats {
168
+ /** Waves of parallel reads. */
169
+ waves: number;
170
+ /** Range reads the reader asked for. */
171
+ reads: number;
172
+ /** Bytes the reader received. */
173
+ bytes: number;
174
+ }
175
+ /** A collection and what it cost to read. */
176
+ interface Answer {
177
+ collection: FeatureCollection;
178
+ stats: QueryStats;
179
+ }
180
+ /** A gid split into its parts. */
181
+ interface Gid {
182
+ layer: string;
183
+ /** Record id, as a decimal string. */
184
+ id: string;
185
+ }
186
+ /** One wave step from the wasm reader. */
187
+ type WasmStep = {
188
+ fetch: [number, number][];
189
+ } | {
190
+ done: Feature[];
191
+ distanceRanked: boolean;
192
+ };
193
+ /** Largest `size`. */
194
+ export declare const MAX_SIZE = 40;
195
+ /** `size` when unset. */
196
+ export declare const DEFAULT_SIZE = 10;
197
+ /** Every layer of the index, in the order the `.glx` format codes them (1 to 7). */
198
+ export declare const LAYERS: readonly Layer[];
199
+ /**
200
+ * One `.glx` file. Open it once per isolate with {@link GlxFile.open}; every
201
+ * query then reads only the byte ranges it needs from the {@link Source}.
202
+ */
203
+ export declare class GlxFile {
204
+ #private;
205
+ private constructor();
206
+ /**
207
+ * Reads the header and the boot sections (dictionary root, spatial
208
+ * directory, id directory) and opens the index. Call `init` (the wasm
209
+ * module) first.
210
+ */
211
+ static open(source: Source, read?: ReadOptions): Promise<GlxFile>;
212
+ /** Places in the file. */
213
+ get places(): number;
214
+ /** Forward geocoding: places matching free text. */
215
+ search(params: SearchParams): Promise<Answer>;
216
+ /** Search as you type: the last word may be unfinished. */
217
+ autocomplete(params: SearchParams): Promise<Answer>;
218
+ /** Structured geocoding: the fields are joined and searched. */
219
+ structured(params: StructuredParams): Promise<Answer>;
220
+ /** Reverse geocoding: places nearest to a point within `radiusKm`. */
221
+ reverse(params: NearbyParams): Promise<Answer>;
222
+ /** Places around a point within `radiusKm`, nearest first. */
223
+ nearby(params: NearbyParams): Promise<Answer>;
224
+ /**
225
+ * Places by gid (`geolith:<layer>:<id>`), in the asked order. A gid whose
226
+ * layer does not match the place's is left out. With `geometry`, a place
227
+ * with an outline returns it as its geometry (`Polygon` or
228
+ * `MultiPolygon`), its point in `properties.center` and its box in `bbox`.
229
+ */
230
+ place(gids: readonly string[], options?: PlaceOptions): Promise<Answer>;
231
+ }
232
+ /** Reads a `.glx` file over HTTP range requests. */
233
+ export declare class FetchSource implements Source {
234
+ #private;
235
+ readonly key: string;
236
+ /** `init` is merged into every request (headers, for example). */
237
+ constructor(url: string, init?: RequestInit);
238
+ getBytes(offset: number, length: number): Promise<Uint8Array>;
239
+ }
240
+ /** Reads a `.glx` file from a browser `Blob` or `File`, for example one a user dropped on a page. */
241
+ export declare class FileSource implements Source {
242
+ #private;
243
+ readonly key: string;
244
+ /** `key` is the file's name when `blob` is a `File`, else `blob.glx`. */
245
+ constructor(blob: Blob);
246
+ getBytes(offset: number, length: number): Promise<Uint8Array>;
247
+ }
248
+ /** Reads a `.glx` file from a Cloudflare R2 bucket binding. */
249
+ export declare class R2Source implements Source {
250
+ #private;
251
+ readonly key: string;
252
+ constructor(bucket: R2BucketLike, key: string);
253
+ getBytes(offset: number, length: number): Promise<Uint8Array>;
254
+ }
255
+ /**
256
+ * Loads the wasm reader once per isolate: pass the compiled module (a
257
+ * Worker's wasm import) or the `.wasm` bytes.
258
+ */
259
+ export declare function init(module: WebAssembly.Module | BufferSource): void;
260
+ export type { Answer, Budget, Feature, FeatureCollection, Filters, Geometry, Gid, Layer, NearbyParams, PlaceOptions, Point, Properties, QueryStats, R2BucketLike, Ranking, ReadOptions, Ring, SearchParams, Source, StructuredParams, WasmStep };
package/dist/index.js ADDED
@@ -0,0 +1,732 @@
1
+ // src/wasm/glx.js
2
+ /**
3
+ * The in-memory index of one `.glx` file.
4
+ */
5
+ var Engine = class {
6
+ __destroy_into_raw() {
7
+ const ptr = this.__wbg_ptr;
8
+ this.__wbg_ptr = 0;
9
+ EngineFinalization.unregister(this);
10
+ return ptr;
11
+ }
12
+ free() {
13
+ const ptr = this.__destroy_into_raw();
14
+ wasm.__wbg_engine_free(ptr, 0);
15
+ }
16
+ /**
17
+ * Starts a search for the places nearest to a point. `options` is
18
+ * JSON: `lon`, `lat`, `radiusKm`, `size`, optional `layers` and
19
+ * `countries`.
20
+ *
21
+ * # Errors
22
+ * When the options do not parse.
23
+ * @param {string} options_json
24
+ * @returns {Query}
25
+ */
26
+ nearby(options_json) {
27
+ const ptr0 = passStringToWasm0(options_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
28
+ const len0 = WASM_VECTOR_LEN;
29
+ const ret = wasm.engine_nearby(this.__wbg_ptr, ptr0, len0);
30
+ if (ret[2]) throw takeFromExternrefTable0(ret[1]);
31
+ return Query.__wrap(ret[0]);
32
+ }
33
+ /**
34
+ * Opens the index. It lives as long as the isolate.
35
+ *
36
+ * # Errors
37
+ * When the bytes do not decode.
38
+ * @param {Uint8Array | number[]} header
39
+ * @param {Uint8Array | number[]} boot
40
+ */
41
+ constructor(header, boot) {
42
+ let ptr0, len0, ptr1, len1;
43
+ try {
44
+ ptr0 = passArray8ToWasm0(header, wasm.__wbindgen_malloc);
45
+ len0 = WASM_VECTOR_LEN;
46
+ ptr1 = passArray8ToWasm0(boot, wasm.__wbindgen_malloc);
47
+ len1 = WASM_VECTOR_LEN;
48
+ } catch (e) {
49
+ if (ptr1) wasm.__wbindgen_free(ptr1, len1 * 1, 1);
50
+ if (ptr0) wasm.__wbindgen_free(ptr0, len0 * 1, 1);
51
+ throw e;
52
+ }
53
+ const ret = wasm.engine_new(ptr0, len0, ptr1, len1);
54
+ if (ret[2]) throw takeFromExternrefTable0(ret[1]);
55
+ this.__wbg_ptr = ret[0];
56
+ EngineFinalization.register(this, this.__wbg_ptr, this);
57
+ return this;
58
+ }
59
+ /**
60
+ * Starts a lookup of places by id. `ids_json` is a JSON array of ids
61
+ * as decimal strings (ids pass the 53-bit JavaScript number range).
62
+ * With `shapes`, each place with an outline returns it as its
63
+ * geometry, read in the same wave as the records.
64
+ *
65
+ * # Errors
66
+ * When the ids do not parse.
67
+ * @param {string} ids_json
68
+ * @param {boolean} shapes
69
+ * @returns {Query}
70
+ */
71
+ place(ids_json, shapes) {
72
+ const val2 = +shapes;
73
+ const ptr0 = passStringToWasm0(ids_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
74
+ const len0 = WASM_VECTOR_LEN;
75
+ const ret = wasm.engine_place(this.__wbg_ptr, ptr0, len0, val2);
76
+ if (ret[2]) throw takeFromExternrefTable0(ret[1]);
77
+ return Query.__wrap(ret[0]);
78
+ }
79
+ /**
80
+ * Places in the file.
81
+ * @returns {number}
82
+ */
83
+ places() {
84
+ return wasm.engine_places(this.__wbg_ptr);
85
+ }
86
+ /**
87
+ * Starts a ranked text search. `options` is JSON: `text`, `size`,
88
+ * optional `autocomplete`, `layers`, `countries`, `focus` (`[lon,
89
+ * lat]`) and `budget` (`walkBytes`, `recordBytes`, `maxWaves`).
90
+ *
91
+ * # Errors
92
+ * When the options do not parse.
93
+ * @param {string} options_json
94
+ * @returns {Query}
95
+ */
96
+ search(options_json) {
97
+ const ptr0 = passStringToWasm0(options_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
98
+ const len0 = WASM_VECTOR_LEN;
99
+ const ret = wasm.engine_search(this.__wbg_ptr, ptr0, len0);
100
+ if (ret[2]) throw takeFromExternrefTable0(ret[1]);
101
+ return Query.__wrap(ret[0]);
102
+ }
103
+ };
104
+ if (Symbol.dispose) Engine.prototype[Symbol.dispose] = Engine.prototype.free;
105
+ /**
106
+ * One query in progress.
107
+ */
108
+ var Query = class Query {
109
+ static __wrap(ptr) {
110
+ const obj = Object.create(Query.prototype);
111
+ obj.__wbg_ptr = ptr;
112
+ QueryFinalization.register(obj, obj.__wbg_ptr, obj);
113
+ return obj;
114
+ }
115
+ __destroy_into_raw() {
116
+ const ptr = this.__wbg_ptr;
117
+ this.__wbg_ptr = 0;
118
+ QueryFinalization.unregister(this);
119
+ return ptr;
120
+ }
121
+ free() {
122
+ const ptr = this.__destroy_into_raw();
123
+ wasm.__wbg_query_free(ptr, 0);
124
+ }
125
+ /**
126
+ * Bytes fetched so far.
127
+ * @returns {number}
128
+ */
129
+ bytes() {
130
+ return wasm.query_bytes(this.__wbg_ptr);
131
+ }
132
+ /**
133
+ * Range reads so far.
134
+ * @returns {number}
135
+ */
136
+ reads() {
137
+ return wasm.query_reads(this.__wbg_ptr) >>> 0;
138
+ }
139
+ /**
140
+ * Next step as JSON.
141
+ * @returns {string}
142
+ */
143
+ step() {
144
+ let deferred1_0;
145
+ let deferred1_1;
146
+ try {
147
+ const ret = wasm.query_step(this.__wbg_ptr);
148
+ deferred1_0 = ret[0];
149
+ deferred1_1 = ret[1];
150
+ return getStringFromWasm0(ret[0], ret[1]);
151
+ } finally {
152
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
153
+ }
154
+ }
155
+ /**
156
+ * Hands back the bytes of a span from the last `step()`.
157
+ * @param {number} offset
158
+ * @param {Uint8Array | number[]} bytes
159
+ */
160
+ supply(offset, bytes) {
161
+ const val2 = +offset;
162
+ const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
163
+ const len0 = WASM_VECTOR_LEN;
164
+ wasm.query_supply(this.__wbg_ptr, val2, ptr0, len0);
165
+ }
166
+ /**
167
+ * Waves so far.
168
+ * @returns {number}
169
+ */
170
+ waves() {
171
+ return wasm.query_waves(this.__wbg_ptr) >>> 0;
172
+ }
173
+ };
174
+ if (Symbol.dispose) Query.prototype[Symbol.dispose] = Query.prototype.free;
175
+ /**
176
+ * `[offset, length]` of the boot bytes, from the header bytes.
177
+ *
178
+ * # Errors
179
+ * When the bytes are not a `.glx` version 1 header, or the file lacks a
180
+ * record feature this reader needs.
181
+ * @param {Uint8Array | number[]} header
182
+ * @returns {Float64Array}
183
+ */
184
+ function bootSpan(header) {
185
+ const ptr0 = passArray8ToWasm0(header, wasm.__wbindgen_malloc);
186
+ const len0 = WASM_VECTOR_LEN;
187
+ const ret = wasm.bootSpan(ptr0, len0);
188
+ if (ret[3]) throw takeFromExternrefTable0(ret[2]);
189
+ var v2 = getArrayF64FromWasm0(ret[0], ret[1]).slice();
190
+ wasm.__wbindgen_free(ret[0], ret[1] * 8, 8);
191
+ return v2;
192
+ }
193
+ /**
194
+ * A Pelias `FeatureCollection` around `features` (a JSON array), with
195
+ * `query` (a JSON object) and the engine's name and version.
196
+ *
197
+ * # Errors
198
+ * When `query` or `features` is not valid JSON.
199
+ * @param {string} query
200
+ * @param {string} features
201
+ * @param {string} name
202
+ * @param {string} version
203
+ * @returns {string}
204
+ */
205
+ function collection(query, features, name, version) {
206
+ let deferred6_0;
207
+ let deferred6_1;
208
+ try {
209
+ let ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3;
210
+ try {
211
+ ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
212
+ len0 = WASM_VECTOR_LEN;
213
+ ptr1 = passStringToWasm0(features, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
214
+ len1 = WASM_VECTOR_LEN;
215
+ ptr2 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
216
+ len2 = WASM_VECTOR_LEN;
217
+ ptr3 = passStringToWasm0(version, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
218
+ len3 = WASM_VECTOR_LEN;
219
+ } catch (e) {
220
+ if (ptr3) wasm.__wbindgen_free(ptr3, len3 * 1, 1);
221
+ if (ptr2) wasm.__wbindgen_free(ptr2, len2 * 1, 1);
222
+ if (ptr1) wasm.__wbindgen_free(ptr1, len1 * 1, 1);
223
+ if (ptr0) wasm.__wbindgen_free(ptr0, len0 * 1, 1);
224
+ throw e;
225
+ }
226
+ const ret = wasm.collection(ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3);
227
+ var ptr5 = ret[0];
228
+ var len5 = ret[1];
229
+ if (ret[3]) {
230
+ ptr5 = 0;
231
+ len5 = 0;
232
+ throw takeFromExternrefTable0(ret[2]);
233
+ }
234
+ deferred6_0 = ptr5;
235
+ deferred6_1 = len5;
236
+ return getStringFromWasm0(ptr5, len5);
237
+ } finally {
238
+ wasm.__wbindgen_free(deferred6_0, deferred6_1, 1);
239
+ }
240
+ }
241
+ /**
242
+ * Header length in bytes.
243
+ * @returns {number}
244
+ */
245
+ function headerLength() {
246
+ return wasm.headerLength() >>> 0;
247
+ }
248
+ function __wbg_get_imports() {
249
+ return {
250
+ __proto__: null,
251
+ "./glx_bg.js": {
252
+ __proto__: null,
253
+ __wbg_Error_208446807d0d1e30: function(arg0, arg1) {
254
+ return Error(getStringFromWasm0(arg0, arg1));
255
+ },
256
+ __wbg___wbindgen_throw_4c88d8bf264fd984: function(arg0, arg1) {
257
+ throw new Error(getStringFromWasm0(arg0, arg1));
258
+ },
259
+ __wbindgen_init_externref_table: function() {
260
+ const table = wasm.__wbindgen_externrefs;
261
+ table.set(0, void 0);
262
+ table.set(1024, void 0);
263
+ table.set(1025, null);
264
+ table.set(1026, true);
265
+ table.set(1027, false);
266
+ }
267
+ }
268
+ };
269
+ }
270
+ const EngineFinalization = typeof FinalizationRegistry === "undefined" ? {
271
+ register: () => {},
272
+ unregister: () => {}
273
+ } : new FinalizationRegistry((ptr) => wasm.__wbg_engine_free(ptr, 1));
274
+ const QueryFinalization = typeof FinalizationRegistry === "undefined" ? {
275
+ register: () => {},
276
+ unregister: () => {}
277
+ } : new FinalizationRegistry((ptr) => wasm.__wbg_query_free(ptr, 1));
278
+ function getArrayF64FromWasm0(ptr, len) {
279
+ ptr = ptr >>> 0;
280
+ return getFloat64ArrayMemory0().subarray(ptr / 8, ptr / 8 + len);
281
+ }
282
+ let cachedFloat64ArrayMemory0 = null;
283
+ function getFloat64ArrayMemory0() {
284
+ if (cachedFloat64ArrayMemory0 === null || cachedFloat64ArrayMemory0.byteLength === 0) cachedFloat64ArrayMemory0 = new Float64Array(wasm.memory.buffer);
285
+ return cachedFloat64ArrayMemory0;
286
+ }
287
+ function getStringFromWasm0(ptr, len) {
288
+ ptr = ptr >>> 0;
289
+ return decodeText(getUint8ArrayMemory0().subarray(ptr, ptr + len));
290
+ }
291
+ let cachedUint8ArrayMemory0 = null;
292
+ function getUint8ArrayMemory0() {
293
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
294
+ return cachedUint8ArrayMemory0;
295
+ }
296
+ function passArray8ToWasm0(arg, malloc) {
297
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
298
+ getUint8ArrayMemory0().set(arg, ptr / 1);
299
+ WASM_VECTOR_LEN = arg.length;
300
+ return ptr;
301
+ }
302
+ function passStringToWasm0(arg, malloc, realloc) {
303
+ if (realloc === void 0) {
304
+ const buf = cachedTextEncoder.encode(arg);
305
+ const ptr = malloc(buf.length, 1) >>> 0;
306
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
307
+ WASM_VECTOR_LEN = buf.length;
308
+ return ptr;
309
+ }
310
+ let len = arg.length;
311
+ let ptr = malloc(len, 1) >>> 0;
312
+ const mem = getUint8ArrayMemory0();
313
+ let offset = 0;
314
+ for (; offset < len; offset++) {
315
+ const code = arg.charCodeAt(offset);
316
+ if (code > 127) break;
317
+ mem[ptr + offset] = code;
318
+ }
319
+ if (offset !== len) {
320
+ if (offset !== 0) arg = arg.slice(offset);
321
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
322
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
323
+ const ret = cachedTextEncoder.encodeInto(arg, view);
324
+ offset += ret.written;
325
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
326
+ }
327
+ WASM_VECTOR_LEN = offset;
328
+ return ptr;
329
+ }
330
+ function takeFromExternrefTable0(idx) {
331
+ const value = wasm.__wbindgen_externrefs.get(idx);
332
+ wasm.__externref_table_dealloc(idx);
333
+ return value;
334
+ }
335
+ let cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
336
+ cachedTextDecoder.decode();
337
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
338
+ let numBytesDecoded = 0;
339
+ function decodeText(bytes) {
340
+ numBytesDecoded += bytes.length;
341
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
342
+ cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
343
+ cachedTextDecoder.decode();
344
+ numBytesDecoded = bytes.length;
345
+ }
346
+ return cachedTextDecoder.decode(bytes);
347
+ }
348
+ const cachedTextEncoder = new TextEncoder();
349
+ if (!("encodeInto" in cachedTextEncoder)) cachedTextEncoder.encodeInto = function(arg, view) {
350
+ const buf = cachedTextEncoder.encode(arg);
351
+ view.set(buf);
352
+ return {
353
+ read: arg.length,
354
+ written: buf.length
355
+ };
356
+ };
357
+ let WASM_VECTOR_LEN = 0;
358
+ let wasm;
359
+ function __wbg_finalize_init(instance, module) {
360
+ wasm = instance.exports;
361
+ cachedFloat64ArrayMemory0 = null;
362
+ cachedUint8ArrayMemory0 = null;
363
+ wasm.__wbindgen_start();
364
+ return wasm;
365
+ }
366
+ function initSync(module) {
367
+ if (wasm !== void 0) return wasm;
368
+ if (module !== void 0) {
369
+ if (Object.getPrototypeOf(module) === Object.prototype) ({module} = module);
370
+ else console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
371
+ }
372
+ const imports = __wbg_get_imports();
373
+ if (!(module instanceof WebAssembly.Module)) module = new WebAssembly.Module(module);
374
+ return __wbg_finalize_init(new WebAssembly.Instance(module, imports), module);
375
+ }
376
+ // src/coalesce.ts
377
+ /**
378
+ * Merges byte spans `[offset, length]` into at most `count` ranges. The pair
379
+ * with the smallest gap merges first; a merge whose range would pass
380
+ * `maxBytes` is not made, so more than `count` ranges can remain.
381
+ */
382
+ function coalesce(spans, count, maxBytes) {
383
+ const ranges = [...spans].sort((a, b) => a[0] - b[0]).map(([offset, length]) => [offset, offset + length]);
384
+ const out = [];
385
+ for (const range of ranges) {
386
+ const last = out.at(-1);
387
+ if (last && range[0] <= last[1]) last[1] = Math.max(last[1], range[1]);
388
+ else out.push(range);
389
+ }
390
+ while (out.length > count) {
391
+ let best = -1;
392
+ let bestGap = Infinity;
393
+ for (let i = 0; i + 1 < out.length; i++) {
394
+ const [start] = out[i];
395
+ const [nextStart, nextEnd] = out[i + 1];
396
+ if (nextEnd - start > maxBytes) continue;
397
+ const gap = nextStart - out[i][1];
398
+ if (gap < bestGap) {
399
+ best = i;
400
+ bestGap = gap;
401
+ }
402
+ }
403
+ if (best < 0) break;
404
+ out[best][1] = out[best + 1][1];
405
+ out.splice(best + 1, 1);
406
+ }
407
+ return out.map(([start, end]) => [start, end - start]);
408
+ }
409
+ // src/error.ts
410
+ /** An invalid query, rejected before any read. */
411
+ var GlxQueryError = class extends Error {
412
+ name = "GlxQueryError";
413
+ };
414
+ // src/gid.ts
415
+ /** Parses `geolith:<layer>:<id>` gids; at least one, at most `max`. */
416
+ function parseGids(gids, max) {
417
+ const parsed = gids.map((gid) => gid.trim()).filter((gid) => gid !== "").map(parseGid);
418
+ if (parsed.length === 0) throw new GlxQueryError("missing param ids");
419
+ if (parsed.length > max) throw new GlxQueryError(`ids holds more than ${max} gids`);
420
+ return parsed;
421
+ }
422
+ function parseGid(gid) {
423
+ const match = /^geolith:([^:]+):(-?\d+)$/.exec(gid);
424
+ if (match === null) throw new GlxQueryError(`gid '${gid}' is not a geolith gid`);
425
+ const [, layer, id] = match;
426
+ return {
427
+ layer,
428
+ id
429
+ };
430
+ }
431
+ // src/glxfile.ts
432
+ /** Engine name and version written into every response. */
433
+ const ENGINE = {
434
+ name: "geolith-glx",
435
+ version: "0.1.0"
436
+ };
437
+ /** Largest `size`. */
438
+ const MAX_SIZE = 40;
439
+ /** `size` when unset. */
440
+ const DEFAULT_SIZE = 10;
441
+ /** Every layer of the index, in the order the `.glx` format codes them (1 to 7). */
442
+ const LAYERS = [
443
+ "venue",
444
+ "address",
445
+ "street",
446
+ "locality",
447
+ "county",
448
+ "region",
449
+ "country"
450
+ ];
451
+ /**
452
+ * One `.glx` file. Open it once per isolate with {@link GlxFile.open}; every
453
+ * query then reads only the byte ranges it needs from the {@link Source}.
454
+ */
455
+ var GlxFile = class GlxFile {
456
+ #source;
457
+ #engine;
458
+ #read;
459
+ constructor(source, engine, read) {
460
+ this.#source = source;
461
+ this.#engine = engine;
462
+ this.#read = read;
463
+ }
464
+ /**
465
+ * Reads the header and the boot sections (dictionary root, spatial
466
+ * directory, id directory) and opens the index. Call `init` (the wasm
467
+ * module) first.
468
+ */
469
+ static async open(source, read = {}) {
470
+ const header = await source.getBytes(0, headerLength());
471
+ const span = bootSpan(header);
472
+ const boot = await source.getBytes(span[0] ?? 0, span[1] ?? 0);
473
+ return new GlxFile(source, new Engine(header, boot), {
474
+ maxRanges: read.maxRanges ?? 3,
475
+ maxRangeBytes: read.maxRangeBytes ?? 4194304,
476
+ hedge: read.hedge ?? 2
477
+ });
478
+ }
479
+ /** Places in the file. */
480
+ get places() {
481
+ return this.#engine.places();
482
+ }
483
+ /** Forward geocoding: places matching free text. */
484
+ search(params) {
485
+ return this.#text(params, false);
486
+ }
487
+ /** Search as you type: the last word may be unfinished. */
488
+ autocomplete(params) {
489
+ return this.#text(params, true);
490
+ }
491
+ /** Structured geocoding: the fields are joined and searched. */
492
+ async structured(params) {
493
+ const fields = [
494
+ params.address,
495
+ params.neighbourhood,
496
+ params.borough,
497
+ params.locality,
498
+ params.county,
499
+ params.region,
500
+ params.postalcode,
501
+ params.country
502
+ ].filter((field) => field !== void 0 && field.trim() !== "");
503
+ let countries = params.countries;
504
+ let words = fields;
505
+ const country = params.country?.trim();
506
+ if (country !== void 0 && /^[a-z]{2}$/i.test(country)) {
507
+ countries = [country];
508
+ words = fields.filter((field) => field.trim() !== country);
509
+ }
510
+ const text = words.join(" ");
511
+ if (text.trim() === "") throw new GlxQueryError("set at least one of address, locality, region, postalcode or country");
512
+ return this.#text({
513
+ ...params,
514
+ text,
515
+ ...countries ? { countries } : {}
516
+ }, false, { fields });
517
+ }
518
+ /** Reverse geocoding: places nearest to a point within `radiusKm`. */
519
+ reverse(params) {
520
+ return this.nearby(params);
521
+ }
522
+ /** Places around a point within `radiusKm`, nearest first. */
523
+ async nearby(params) {
524
+ checkPoint(params);
525
+ if (!(params.radiusKm > 0)) throw new GlxQueryError("radiusKm must be greater than 0");
526
+ const size = checkSize(params.size);
527
+ const query = this.#engine.nearby(JSON.stringify({
528
+ lon: params.lon,
529
+ lat: params.lat,
530
+ radiusKm: params.radiusKm,
531
+ size,
532
+ ...limits(params)
533
+ }));
534
+ const { features, stats } = await this.#run(query);
535
+ return {
536
+ collection: this.#collection({
537
+ "point.lat": params.lat,
538
+ "point.lon": params.lon,
539
+ "boundary.circle.radius": params.radiusKm,
540
+ size
541
+ }, features),
542
+ stats
543
+ };
544
+ }
545
+ /**
546
+ * Places by gid (`geolith:<layer>:<id>`), in the asked order. A gid whose
547
+ * layer does not match the place's is left out. With `geometry`, a place
548
+ * with an outline returns it as its geometry (`Polygon` or
549
+ * `MultiPolygon`), its point in `properties.center` and its box in `bbox`.
550
+ */
551
+ async place(gids, options = {}) {
552
+ const parsed = parseGids(gids, 40);
553
+ const query = this.#engine.place(JSON.stringify(parsed.map((gid) => gid.id)), options.geometry === true);
554
+ const { features, stats } = await this.#run(query);
555
+ const kept = features.filter((feature) => parsed.some((gid) => gid.id === feature.properties.id && gid.layer === feature.properties.layer));
556
+ const ids = parsed.map((gid) => ({
557
+ source: "geolith",
558
+ layer: gid.layer,
559
+ id: gid.id
560
+ }));
561
+ return {
562
+ collection: this.#collection({
563
+ ids,
564
+ size: parsed.length
565
+ }, kept),
566
+ stats
567
+ };
568
+ }
569
+ async #text(params, autocomplete, echo = { text: params.text }) {
570
+ if (params.text.trim() === "") throw new GlxQueryError("missing param text");
571
+ const size = checkSize(params.size);
572
+ if (params.focus) checkPoint(params.focus);
573
+ const query = this.#engine.search(JSON.stringify({
574
+ text: params.text,
575
+ autocomplete,
576
+ size,
577
+ ...limits(params),
578
+ ...params.focus ? { focus: [params.focus.lon, params.focus.lat] } : {},
579
+ budget: { ...params.budget }
580
+ }));
581
+ const { features, stats, distanceRanked } = await this.#run(query);
582
+ const ranking = distanceRanked ? "importance+distance" : "importance";
583
+ return {
584
+ collection: this.#collection({
585
+ ...echo,
586
+ size,
587
+ ranking
588
+ }, features),
589
+ stats
590
+ };
591
+ }
592
+ /** Drives a query to the end, reading each wave from the source. */
593
+ async #run(query) {
594
+ try {
595
+ return await this.#drive(query);
596
+ } finally {
597
+ query.free();
598
+ }
599
+ }
600
+ /**
601
+ * Steps the query until it is done. Waves run one after another: the
602
+ * query names the next wave's ranges only after it has the last one's bytes.
603
+ */
604
+ async #drive(query) {
605
+ const step = JSON.parse(query.step());
606
+ if ("done" in step) return {
607
+ features: step.done,
608
+ distanceRanked: step.distanceRanked,
609
+ stats: {
610
+ waves: query.waves(),
611
+ reads: query.reads(),
612
+ bytes: query.bytes()
613
+ }
614
+ };
615
+ const parts = await this.#wave(step.fetch);
616
+ step.fetch.forEach(([offset], index) => query.supply(offset, parts[index]));
617
+ return this.#drive(query);
618
+ }
619
+ /** Reads one wave in at most `maxRanges` merged, hedged range reads. */
620
+ async #wave(spans) {
621
+ const { maxRanges, maxRangeBytes, hedge } = this.#read;
622
+ const ranges = coalesce(spans, maxRanges, maxRangeBytes);
623
+ const copies = ranges.length * hedge <= 6 ? hedge : 1;
624
+ const bytes = await Promise.all(ranges.map(([offset, length]) => Promise.any(Array.from({ length: copies }, () => this.#source.getBytes(offset, length)))));
625
+ return spans.map(([offset, length]) => {
626
+ const at = ranges.findIndex(([start, size]) => offset >= start && offset + length <= start + size);
627
+ const start = offset - ranges[at][0];
628
+ return bytes[at].subarray(start, start + length);
629
+ });
630
+ }
631
+ #collection(query, features) {
632
+ return JSON.parse(collection(JSON.stringify(query), JSON.stringify(features), ENGINE.name, ENGINE.version));
633
+ }
634
+ };
635
+ function checkSize(size) {
636
+ const value = size ?? 10;
637
+ if (!Number.isInteger(value) || value < 1 || value > 40) throw new GlxQueryError(`size must be between 1 and 40`);
638
+ return value;
639
+ }
640
+ function checkPoint({ lon, lat }) {
641
+ if (!(lat >= -90 && lat <= 90)) throw new GlxQueryError("latitude must be between -90 and 90");
642
+ if (!(lon >= -180 && lon <= 180)) throw new GlxQueryError("longitude must be between -180 and 180");
643
+ }
644
+ function limits({ layers, countries }) {
645
+ for (const country of countries ?? []) if (!/^[a-z]{2}$/i.test(country)) throw new GlxQueryError(`country '${country}' is not a two-letter code`);
646
+ return {
647
+ layers: [...layers ?? []],
648
+ countries: [...countries ?? []]
649
+ };
650
+ }
651
+ // src/source.ts
652
+ /** Reads a `.glx` file over HTTP range requests. */
653
+ var FetchSource = class {
654
+ key;
655
+ #url;
656
+ #init;
657
+ /** `init` is merged into every request (headers, for example). */
658
+ constructor(url, init = {}) {
659
+ this.key = url;
660
+ this.#url = url;
661
+ this.#init = init;
662
+ }
663
+ async getBytes(offset, length) {
664
+ const headers = new Headers(this.#init.headers);
665
+ headers.set("range", `bytes=${offset}-${offset + length - 1}`);
666
+ const response = await fetch(this.#url, {
667
+ ...this.#init,
668
+ headers
669
+ });
670
+ if (response.status !== 206) throw new Error(`${this.#url}: range request answered ${response.status}`);
671
+ const bytes = new Uint8Array(await response.arrayBuffer());
672
+ if (bytes.length !== length) throw new Error(`${this.#url}: asked ${length} bytes at ${offset}, got ${bytes.length}`);
673
+ return bytes;
674
+ }
675
+ };
676
+ /** Reads a `.glx` file from a browser `Blob` or `File`, for example one a user dropped on a page. */
677
+ var FileSource = class {
678
+ key;
679
+ #blob;
680
+ /** `key` is the file's name when `blob` is a `File`, else `blob.glx`. */
681
+ constructor(blob) {
682
+ this.key = blob instanceof File ? blob.name : "blob.glx";
683
+ this.#blob = blob;
684
+ }
685
+ async getBytes(offset, length) {
686
+ const bytes = new Uint8Array(await this.#blob.slice(offset, offset + length).arrayBuffer());
687
+ if (bytes.length !== length) throw new Error(`${this.key}: asked ${length} bytes at ${offset}, got ${bytes.length}`);
688
+ return bytes;
689
+ }
690
+ };
691
+ /** Reads a `.glx` file from a Cloudflare R2 bucket binding. */
692
+ var R2Source = class {
693
+ key;
694
+ #bucket;
695
+ constructor(bucket, key) {
696
+ this.key = key;
697
+ this.#bucket = bucket;
698
+ }
699
+ async getBytes(offset, length) {
700
+ const object = await this.#bucket.get(this.key, { range: {
701
+ offset,
702
+ length
703
+ } });
704
+ if (object === null) throw new Error(`R2 object ${this.key} is missing`);
705
+ const bytes = new Uint8Array(await object.arrayBuffer());
706
+ if (bytes.length !== length) throw new Error(`${this.key}: asked ${length} bytes at ${offset}, got ${bytes.length}`);
707
+ return bytes;
708
+ }
709
+ };
710
+ // src/index.ts
711
+ /**
712
+ * `@geolith/glx`: reads a `.glx` geocoding file from object storage or HTTP,
713
+ * as `pmtiles` reads a `.pmtiles` file. The reader is the same Rust code the
714
+ * geolith search server runs, built to WebAssembly, so both answer alike.
715
+ *
716
+ * ```ts
717
+ * import wasm from '@geolith/glx/glx.wasm';
718
+ * import { GlxFile, R2Source, init } from '@geolith/glx';
719
+ *
720
+ * init(wasm);
721
+ * const file = await GlxFile.open(new R2Source(env.GLX, 'planet.glx'));
722
+ * const { collection } = await file.search({ text: 'india gate' });
723
+ * ```
724
+ */
725
+ /**
726
+ * Loads the wasm reader once per isolate: pass the compiled module (a
727
+ * Worker's wasm import) or the `.wasm` bytes.
728
+ */
729
+ function init(module) {
730
+ initSync({ module });
731
+ }
732
+ export { DEFAULT_SIZE, FetchSource, FileSource, GlxFile, GlxQueryError, LAYERS, MAX_SIZE, R2Source, coalesce, init };
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@geolith/glx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Reads .glx geocoding files from R2 or HTTP range requests: search, autocomplete, structured, reverse, nearby and place lookup.",
5
+ "keywords": [
6
+ "autocomplete",
7
+ "cloudflare-workers",
8
+ "geocoder",
9
+ "geocoding",
10
+ "glx",
11
+ "openstreetmap",
12
+ "overture-maps",
13
+ "r2",
14
+ "range-requests",
15
+ "reverse-geocoding",
16
+ "search",
17
+ "wasm",
18
+ "webassembly"
19
+ ],
20
+ "homepage": "https://docs.geolith.app/glx",
21
+ "bugs": {
22
+ "url": "https://github.com/geolith/glx/issues"
23
+ },
24
+ "license": "Apache-2.0",
25
+ "author": {
26
+ "name": "Vinayak Kulkarni",
27
+ "email": "inbox.vinayak@gmail.com",
28
+ "url": "https://vinayakkulkarni.dev"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/geolith/glx.git",
33
+ "directory": "packages/js"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "NOTICE"
38
+ ],
39
+ "type": "module",
40
+ "sideEffects": false,
41
+ "types": "./dist/index.d.ts",
42
+ "exports": {
43
+ ".": {
44
+ "types": "./dist/index.d.ts",
45
+ "default": "./dist/index.js"
46
+ },
47
+ "./glx.wasm": "./dist/glx_bg.wasm",
48
+ "./glx-parser.wasm": "./dist/glx_parser_bg.wasm",
49
+ "./package.json": "./package.json"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "scripts": {
55
+ "wasm": "node scripts/wasm.ts",
56
+ "fixture": "cargo run --manifest-path ../../Cargo.toml --example fixture -- test/fixture.glx",
57
+ "build": "pnpm wasm && tsdown",
58
+ "test": "pnpm wasm && pnpm fixture && vitest run",
59
+ "typecheck": "pnpm wasm && tsc --noEmit",
60
+ "lint": "oxlint src test scripts",
61
+ "prepublishOnly": "pnpm build"
62
+ },
63
+ "devDependencies": {
64
+ "@types/node": "26.6.6",
65
+ "oxlint": "1.91.0",
66
+ "tsdown": "0.23.5",
67
+ "typescript": "7.0.2",
68
+ "vitest": "5.1.0"
69
+ },
70
+ "engines": {
71
+ "node": ">=26"
72
+ },
73
+ "packageManager": "pnpm@12.16.1+sha512.091d1dee7927575661b25dab3c2ae31cafc1c54d6b71ed6a6600cf0c1cb10434a447eae14015f1b23e2e6bedeed79df94a932e2164d2832280dce3fb32f656d1"
74
+ }