@mailwoman/resolver-wof-wasm 9.3.0 → 9.4.0

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 (41) hide show
  1. package/lib/browser-cascade.ts +4 -8
  2. package/lib/host-assets.ts +99 -0
  3. package/lib/httpvfs/poi.ts +283 -0
  4. package/lib/httpvfs/resolver.ts +750 -0
  5. package/lib/httpvfs/rows.ts +60 -0
  6. package/lib/httpvfs/street.ts +294 -0
  7. package/lib/index.ts +0 -8
  8. package/lib/lookup.ts +2 -1
  9. package/out/browser-cascade.d.ts +4 -8
  10. package/out/browser-cascade.d.ts.map +1 -1
  11. package/out/browser-cascade.js +4 -8
  12. package/out/browser-cascade.js.map +1 -1
  13. package/out/host-assets.d.ts +28 -0
  14. package/out/host-assets.d.ts.map +1 -0
  15. package/out/host-assets.js +80 -0
  16. package/out/host-assets.js.map +1 -0
  17. package/out/httpvfs/poi.d.ts +88 -0
  18. package/out/httpvfs/poi.d.ts.map +1 -0
  19. package/out/httpvfs/poi.js +190 -0
  20. package/out/httpvfs/poi.js.map +1 -0
  21. package/out/httpvfs/resolver.d.ts +171 -0
  22. package/out/httpvfs/resolver.d.ts.map +1 -0
  23. package/out/httpvfs/resolver.js +542 -0
  24. package/out/httpvfs/resolver.js.map +1 -0
  25. package/out/httpvfs/rows.d.ts +32 -0
  26. package/out/httpvfs/rows.d.ts.map +1 -0
  27. package/out/httpvfs/rows.js +41 -0
  28. package/out/httpvfs/rows.js.map +1 -0
  29. package/out/httpvfs/street.d.ts +123 -0
  30. package/out/httpvfs/street.d.ts.map +1 -0
  31. package/out/httpvfs/street.js +172 -0
  32. package/out/httpvfs/street.js.map +1 -0
  33. package/out/index.d.ts +0 -1
  34. package/out/index.d.ts.map +1 -1
  35. package/out/index.js +1 -0
  36. package/out/index.js.map +1 -1
  37. package/out/lookup.d.ts +1 -1
  38. package/out/lookup.d.ts.map +1 -1
  39. package/out/lookup.js +2 -1
  40. package/out/lookup.js.map +1 -1
  41. package/package.json +59 -6
@@ -3,15 +3,11 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * Tree resolution over a browser-side place lookup.
6
+ * Tree resolution over a browser-side place lookup: the browser half of the same resolve cascade the
7
+ * node path runs, with nothing in it that belongs to one host.
7
8
  *
8
- * This lived in the docs site (`docs/src/shared/`), which made it unreachable from the packages that
9
- * need it: `hot-db.test.ts` here had to reach across a workspace boundary into a private Docusaurus
10
- * app, dragging its React graph into a project that has no business type-checking it. Nothing in this
11
- * file is docs-specific — it is the browser half of the same resolve cascade the node path runs.
12
- *
13
- * The lookup is structural (`MailwomanLookupLike`) rather than a concrete class, so the demo's HTTPVFS
14
- * lookup, the WASM lookup here, and any future one all satisfy it.
9
+ * The lookup is structural (`MailwomanLookupLike`) rather than a concrete class, so the HTTPVFS lookup,
10
+ * the WASM lookup here, and any future one all satisfy it.
15
11
  */
16
12
 
17
13
  import { areaPostcodeLeadsLocality, isUnitGradePostcodeHit } from "@mailwoman/codex"
@@ -0,0 +1,99 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * What a host must stage to serve the httpvfs readers: sql.js-httpvfs's UMD bundle, its worker and its WASM, loaded
7
+ * at run time by URL (the UMD via a classic script tag, the worker and WASM handed to `createDbWorker`), so no bundler
8
+ * ever sees them. Node-side, a build step, never the browser. `syncArtifact` is the idempotent copy every staged asset
9
+ * goes through: a size-identical destination is left alone so a dev server watching it sees no change.
10
+ */
11
+
12
+ import { ByteFormatter } from "@mailwoman/core/fs/formatters"
13
+ import { pathExists, statPath } from "@mailwoman/core/fs/readers"
14
+ import { copyFileTo } from "@mailwoman/core/fs/writers"
15
+ import { tryResolvePackageSpecifier } from "@mailwoman/core/module/resolve-from"
16
+ import { dirname, resolvePath } from "path-ts"
17
+
18
+ /**
19
+ * Copy a file to the static directory, but only if it differs (by size) from what's already there.
20
+ *
21
+ * @param label - For logging
22
+ *
23
+ * @returns True if the file was copied
24
+ */
25
+ export async function syncArtifact(sourcePath: string, destPath: string, label: string): Promise<boolean> {
26
+ if (!(await pathExists(sourcePath))) {
27
+ console.warn(`[host-assets] ${label}: source missing at ${sourcePath}`)
28
+
29
+ return false
30
+ }
31
+
32
+ const sourceSize = (await statPath(sourcePath)).size
33
+
34
+ if (await pathExists(destPath)) {
35
+ const destSize = (await statPath(destPath)).size
36
+
37
+ if (sourceSize === destSize) return false
38
+ }
39
+
40
+ await copyFileTo(sourcePath, destPath)
41
+
42
+ console.log(`[host-assets] ${label}: synced (${ByteFormatter.formatIEC(sourceSize)})`)
43
+
44
+ return true
45
+ }
46
+
47
+ /**
48
+ * Stage sql.js-httpvfs's runtime assets (the UMD bundle + its Worker + WASM) into `destDir`. The demo loads these at
49
+ * RUNTIME by URL — the UMD via a classic <script>, the worker + wasm passed to createDbWorker — so webpack never sees
50
+ * them. That's deliberate: bundling sql.js-httpvfs (a webpack UMD bundle with dynamic Worker/wasm requires) is exactly
51
+ * what produces "Critical dependency" build warnings, so we keep it out of the graph entirely.
52
+ *
53
+ * @param destDir - E.g. static/mailwoman/sqljs
54
+ */
55
+ export async function stageSQLJSAssets(destDir: string): Promise<boolean> {
56
+ // The runtime files live under the package's `dist/`, so the anchor is the bundle inside it, not the manifest at
57
+ // the package root.
58
+ const entry = tryResolvePackageSpecifier(import.meta.url, "sql.js-httpvfs", "dist/index.js")
59
+
60
+ if (!entry) {
61
+ console.warn("[host-assets] sql.js-httpvfs not resolvable — HTTP-VFS assets not staged")
62
+
63
+ return false
64
+ }
65
+
66
+ const distDir = dirname(entry)
67
+
68
+ const files = ["index.js", "sqlite.worker.js", "sql-wasm.wasm"]
69
+ let copied = 0
70
+
71
+ for (const f of files) {
72
+ const src = resolvePath(distDir, f)
73
+
74
+ if (!(await pathExists(src))) {
75
+ console.warn(`[host-assets] sql.js-httpvfs: missing ${f} in dist`)
76
+
77
+ return false
78
+ }
79
+
80
+ const dest = resolvePath(destDir, f)
81
+
82
+ // Idempotent stage — syncArtifact skips a size-identical copy. This runs in loadContent(), which
83
+ // the Docusaurus dev server (`yarn start`) re-invokes on reload — and `destDir` lives under the
84
+ // watched `static/` tree. An UNCONDITIONAL copy rewrites the file (fresh mtime) even when the
85
+ // bytes are identical, the watcher sees a "change" and reloads, loadContent() re-runs and
86
+ // re-copies… a reload LOOP that shows up as the /demo page flickering during `start`. Skipping
87
+ // the no-op copy breaks the cycle. (Prod `build` runs loadContent once, so the loop is a
88
+ // dev-server-only hazard.)
89
+ if (await syncArtifact(src, dest, `sql.js-httpvfs ${f}`)) {
90
+ copied++
91
+ }
92
+ }
93
+
94
+ if (copied > 0) {
95
+ console.log(`[host-assets] sql.js-httpvfs: staged ${copied} runtime asset(s)`)
96
+ }
97
+
98
+ return true
99
+ }
@@ -0,0 +1,283 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * A SECOND sql.js-httpvfs worker, byte-ranged over the published `poi.db` (`poiLayerURL()`) —
7
+ * category-only k-ring search for a live POI explorer. Independent of
8
+ * `resolver.ts`'s admin-gazetteer worker: a POI search opens its OWN worker over a
9
+ * different DB, over the same staged sql.js-httpvfs UMD/worker/wasm assets.
10
+ *
11
+ * The k-ring walk + h3 packing REPLICATE `resolver-wof-sqlite/poi-lookup.ts`'s Node reader exactly
12
+ * — `latLngToCell` → `shortCellToInt` (the SHARED `@mailwoman/spatial` 48-bit packer, never
13
+ * reimplemented), then the same per-cell probe SQL, ring-by-ring dedup, and a final haversine sort.
14
+ * Keep the two readers in lockstep; a probe-semantics cross-check against the Node reader lives in
15
+ * the PR description, not in this tree (throwaway verification script, not shipped).
16
+ *
17
+ * CATEGORY-ONLY, matching the runbook: no FTS name search, no brand search — the multi-hop demo
18
+ * path is deliberately excluded from this tester.
19
+ */
20
+
21
+ import { isUSStateAbbreviation } from "@mailwoman/codex/us"
22
+ import { haversineKm, shortCellToInt, type H3Cell } from "@mailwoman/spatial"
23
+ import { gridDisk, latLngToCell } from "h3-js"
24
+
25
+ import { loadHTTPVFSDatabase, WOFCandidateTableLookup } from "#httpvfs/resolver"
26
+ import { rowsFromExec } from "#httpvfs/rows"
27
+
28
+ /**
29
+ * Resolution the published `poi.db`'s `h3_cell` column is keyed at — MUST match the builder (poi-lookup.ts's
30
+ * `POI_H3_RESOLUTION`).
31
+ */
32
+ const POI_H3_RESOLUTION = 9
33
+
34
+ /**
35
+ * The worker handle `loadHTTPVFSDatabase` resolves to — named here since `resolver.ts` doesn't export its
36
+ * `HTTPVFSWorker` interface.
37
+ */
38
+ export type POIHTTPVFSWorker = Awaited<ReturnType<typeof loadHTTPVFSDatabase>>
39
+
40
+ /**
41
+ * Open a worker over the published POI layer. Independent of the admin-gazetteer worker — a fresh `createDbWorker`
42
+ * call, same staged UMD.
43
+ */
44
+ export async function loadPOIWorker(poiDatabaseURL: string, sqljsBaseURL: string): Promise<POIHTTPVFSWorker> {
45
+ return loadHTTPVFSDatabase(poiDatabaseURL, sqljsBaseURL)
46
+ }
47
+
48
+ const categoryCodesCache = new WeakMap<POIHTTPVFSWorker, Promise<Map<string, number>>>()
49
+
50
+ /**
51
+ * `category → poi_category_codes.id`, loaded once per worker and cached (mirrors the Node reader's constructor-time
52
+ * load).
53
+ */
54
+ export function loadPOICategoryCodes(worker: POIHTTPVFSWorker): Promise<Map<string, number>> {
55
+ let cached = categoryCodesCache.get(worker)
56
+
57
+ if (!cached) {
58
+ cached = worker.db.exec("SELECT id, category FROM poi_category_codes").then((res) => {
59
+ const map = new Map<string, number>()
60
+
61
+ for (const row of rowsFromExec(res)) {
62
+ map.set(String(row.category), Number(row.id))
63
+ }
64
+
65
+ return map
66
+ })
67
+
68
+ categoryCodesCache.set(worker, cached)
69
+ }
70
+
71
+ return cached
72
+ }
73
+
74
+ export interface POISearchOpts {
75
+ categoryID: string
76
+ /**
77
+ * Fan-out leaves — the Overture `taxonomy.primary` ids this canonical category rolls up into (`supermarket` →
78
+ * `grocery_store`, …), from `@mailwoman/poi-taxonomy`'s `resolveOvertureCategories`. When set, every resolvable leaf
79
+ * is probed per cell and the rows are unioned; unknown leaves are skipped. Absent ⇒ probe `categoryID` alone
80
+ * (identity) — matching the Node reader's back-compat.
81
+ */
82
+ categoryIDs?: string[]
83
+ center: { lat: number; lon: number }
84
+ /**
85
+ * Ring budget (default 6, k reaches 5 — empirically ~1 km against the sealed layer: a live cross-check against a real
86
+ * Springfield-IL cafe cluster found its NEAREST hit only at k=3, so a smaller default returned zero results for a
87
+ * perfectly ordinary query). Still well under the Node reader's 12-ring/~4 km default — the tester issues one
88
+ * explicit-click search, not a per-keystroke probe, so the request count stays bounded either way.
89
+ */
90
+ maxRings?: number
91
+ limit?: number
92
+ }
93
+
94
+ export interface POISearchHit {
95
+ name: string
96
+ lat: number
97
+ lon: number
98
+ distanceM: number
99
+ country: string
100
+ confidence: number
101
+ }
102
+
103
+ const DEFAULT_MAX_RINGS = 6
104
+ const DEFAULT_LIMIT = 10
105
+
106
+ /**
107
+ * Category-only k-ring search. Probes `opts.center`'s res-9 cell, expanding ring-by-ring (deduping cells already
108
+ * probed) until `limit` rows are on hand after a completed ring or `maxRings` is exhausted, then haversine-sorts the
109
+ * pool. Returns `[]` for a category the DB's dictionary doesn't carry — a clean miss, not a throw.
110
+ */
111
+ export async function searchPOICategory(worker: POIHTTPVFSWorker, opts: POISearchOpts): Promise<POISearchHit[]> {
112
+ const limit = Math.max(1, opts.limit ?? DEFAULT_LIMIT)
113
+ const maxRings = Math.max(1, opts.maxRings ?? DEFAULT_MAX_RINGS)
114
+ const codes = await loadPOICategoryCodes(worker)
115
+ // Fan the canonical seed id out over its Overture leaves (`supermarket` → grocery_store, …), resolving each through
116
+ // the db's dictionary and dropping the ones it doesn't carry. Absent list ⇒ the seed id itself (identity).
117
+ const seedIDs = opts.categoryIDs?.length ? opts.categoryIDs : [opts.categoryID]
118
+ const categoryIDs = seedIDs.map((id) => codes.get(id)).filter((id): id is number => id !== undefined)
119
+
120
+ if (!categoryIDs.length) return []
121
+ const categoryIDList = categoryIDs.join(", ")
122
+
123
+ const origin = latLngToCell(opts.center.lat, opts.center.lon, POI_H3_RESOLUTION) as H3Cell
124
+ const seenCells = new Set<string>()
125
+ const rows: Array<{ name: string; latitude: number; longitude: number; country: string; confidence: number }> = []
126
+
127
+ // `ring` starts at 0 (the origin cell itself) — mirrors poi-lookup.ts's `#searchKRing` loop exactly.
128
+ for (let ring = 0; ring < maxRings; ring++) {
129
+ const diskCells = gridDisk(origin, ring) as string[]
130
+ const newCells = diskCells.filter((cell) => !seenCells.has(cell))
131
+
132
+ for (const cell of newCells) {
133
+ seenCells.add(cell)
134
+ // The SAME packing as poi-lookup.ts: the shared @mailwoman/spatial `shortCellToInt` 48-bit
135
+ // packer — `poi.h3_cell` is the SHORTENED cell.
136
+ const shortCell = shortCellToInt(cell as H3Cell)
137
+
138
+ // Country is appended to the per-cell probe (beyond the spec's literal 4-column SQL) so the
139
+ // tester's results list can show it — same WHERE/ORDER/LIMIT + packing, one extra column.
140
+ // `category_id IN (…)` unions the fan-out leaves in one probe per cell (the ids are dictionary ints, never
141
+ // user input — no injection surface). LIMIT still caps the per-cell pull; the outer ring loop + final sort
142
+ // trim to the nearest `limit`.
143
+ const sql =
144
+ `SELECT name, latitude, longitude, confidence, country FROM poi ` +
145
+ `WHERE h3_cell = ${shortCell} AND category_id IN (${categoryIDList}) ORDER BY neg_rank ASC LIMIT ${limit}`
146
+
147
+ const hits = rowsFromExec<{
148
+ name: string | null
149
+ latitude: number
150
+ longitude: number
151
+ country: string | null
152
+ confidence: number
153
+ }>(await worker.db.exec(sql))
154
+
155
+ for (const hit of hits) {
156
+ if (hit.name) {
157
+ rows.push({
158
+ name: hit.name,
159
+ latitude: hit.latitude,
160
+ longitude: hit.longitude,
161
+ country: hit.country ?? "",
162
+ confidence: hit.confidence,
163
+ })
164
+ }
165
+ }
166
+ }
167
+
168
+ if (rows.length >= limit) break
169
+ }
170
+
171
+ return rows
172
+ .map((row) => ({
173
+ name: row.name,
174
+ lat: row.latitude,
175
+ lon: row.longitude,
176
+ country: row.country,
177
+ confidence: row.confidence,
178
+ distanceM: haversineKm(opts.center.lat, opts.center.lon, row.latitude, row.longitude) * 1000,
179
+ }))
180
+ .toSorted((a, b) => a.distanceM - b.distanceM)
181
+ .slice(0, limit)
182
+ }
183
+
184
+ // MARK: Anchor → center resolution (no neural runtime)
185
+
186
+ let candidateWorkerPromise: Promise<POIHTTPVFSWorker> | undefined
187
+
188
+ /**
189
+ * Lazily open (once, shared across calls) the ADMIN CANDIDATE gazetteer worker used only for anchor→center resolution.
190
+ * Independent of the POI-layer worker — a separate byte-ranged DB, the same one `/demo`'s cascade resolves localities
191
+ * against ({@link WOFCandidateTableLookup}).
192
+ */
193
+ function loadCandidateWorker(gazetteerURL: string, sqljsBaseURL: string): Promise<POIHTTPVFSWorker> {
194
+ if (!candidateWorkerPromise) {
195
+ candidateWorkerPromise = loadHTTPVFSDatabase(gazetteerURL, sqljsBaseURL).catch((error: unknown) => {
196
+ candidateWorkerPromise = undefined
197
+ throw error
198
+ })
199
+ }
200
+
201
+ return candidateWorkerPromise
202
+ }
203
+
204
+ export interface AnchorCenter {
205
+ lat: number
206
+ lon: number
207
+ /**
208
+ * The resolved place's canonical name — surfaced so the UI can show what "Springfield" resolved to.
209
+ */
210
+ name: string
211
+ }
212
+
213
+ /**
214
+ * Split an anchor string into a locality + an optional region qualifier, WITHOUT a neural parse. Two forms: a comma
215
+ * ("Springfield, IL") splits there; otherwise a trailing US state abbreviation token ("Springfield IL" — the common
216
+ * comma-less form) splits on whitespace. Anything else is treated as a bare locality name — no disambiguation region,
217
+ * population-first candidate ranking wins (which is exactly the ambiguity a query like "Springfield" alone has: this
218
+ * tester makes no claim to resolve it "correctly", only consistently with the `/demo` cascade's default).
219
+ */
220
+ function splitAnchor(text: string): { localityText: string; regionText?: string } {
221
+ const commaIndex = text.indexOf(",")
222
+
223
+ if (commaIndex !== -1) {
224
+ return { localityText: text.slice(0, commaIndex).trim(), regionText: text.slice(commaIndex + 1).trim() }
225
+ }
226
+
227
+ const lastSpace = text.lastIndexOf(" ")
228
+
229
+ if (lastSpace > 0) {
230
+ const trailingToken = text.slice(lastSpace + 1).trim()
231
+
232
+ if (isUSStateAbbreviation(trailingToken)) {
233
+ return { localityText: text.slice(0, lastSpace).trim(), regionText: trailingToken }
234
+ }
235
+ }
236
+
237
+ return { localityText: text }
238
+ }
239
+
240
+ /**
241
+ * Resolve an anchor string ("Springfield", "Springfield, IL", or "Springfield IL") to a center point against the admin
242
+ * candidate gazetteer — no neural runtime, no full-address parse. When a region qualifier splits off (see
243
+ * {@link splitAnchor}) it's resolved FIRST (for its bbox), then the locality lookup is point-in-bbox-constrained by it,
244
+ * the same disambiguation the `/demo` cascade uses. Returns `null` when nothing resolves — callers show "couldn't place
245
+ * '<anchor>'" rather than silently defaulting to zero results.
246
+ */
247
+ export async function resolveAnchorCenter(
248
+ gazetteerURL: string,
249
+ sqljsBaseURL: string,
250
+ anchorText: string
251
+ ): Promise<AnchorCenter | null> {
252
+ const trimmed = anchorText.trim()
253
+
254
+ if (!trimmed) return null
255
+
256
+ const worker = await loadCandidateWorker(gazetteerURL, sqljsBaseURL)
257
+ const lookup = new WOFCandidateTableLookup(worker)
258
+
259
+ const { localityText, regionText } = splitAnchor(trimmed)
260
+
261
+ let bbox: { minLat: number; maxLat: number; minLon: number; maxLon: number } | undefined
262
+
263
+ if (regionText) {
264
+ const regionHits = await lookup.findPlace({ text: regionText, placetype: "region", limit: 1 })
265
+
266
+ bbox = regionHits[0]?.bbox
267
+ }
268
+
269
+ if (!localityText) return null
270
+
271
+ const localityHits = await lookup.findPlace({
272
+ text: localityText,
273
+ placetype: ["locality"],
274
+ ...(bbox ? { bbox } : {}),
275
+ limit: 1,
276
+ })
277
+
278
+ const hit = localityHits[0]
279
+
280
+ if (!hit) return null
281
+
282
+ return { lat: hit.lat, lon: hit.lon, name: hit.name }
283
+ }