@mailwoman/resolver 11.4.0 → 12.0.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.
- package/lib/bare-toponym-race.ts +31 -0
- package/lib/decorate-node.ts +6 -0
- package/lib/outcome/fetch.ts +82 -0
- package/lib/outcome/ordering.ts +224 -0
- package/lib/outcome/span.ts +106 -0
- package/lib/outcome/walk.ts +132 -0
- package/lib/resolve/landmark.ts +57 -8
- package/lib/resolve/passes.ts +14 -0
- package/lib/resolve/priors.ts +123 -0
- package/lib/resolve/region-city.ts +53 -11
- package/lib/resolve.ts +152 -170
- package/out/bare-toponym-race.d.ts +8 -0
- package/out/bare-toponym-race.d.ts.map +1 -1
- package/out/bare-toponym-race.js +27 -0
- package/out/bare-toponym-race.js.map +1 -1
- package/out/decorate-node.d.ts +1 -1
- package/out/decorate-node.d.ts.map +1 -1
- package/out/decorate-node.js +5 -0
- package/out/decorate-node.js.map +1 -1
- package/out/outcome/fetch.d.ts +39 -0
- package/out/outcome/fetch.d.ts.map +1 -0
- package/out/outcome/fetch.js +59 -0
- package/out/outcome/fetch.js.map +1 -0
- package/out/outcome/ordering.d.ts +56 -0
- package/out/outcome/ordering.d.ts.map +1 -0
- package/out/outcome/ordering.js +152 -0
- package/out/outcome/ordering.js.map +1 -0
- package/out/outcome/span.d.ts +52 -0
- package/out/outcome/span.d.ts.map +1 -0
- package/out/outcome/span.js +66 -0
- package/out/outcome/span.js.map +1 -0
- package/out/outcome/walk.d.ts +42 -0
- package/out/outcome/walk.d.ts.map +1 -0
- package/out/outcome/walk.js +83 -0
- package/out/outcome/walk.js.map +1 -0
- package/out/resolve/landmark.d.ts +14 -2
- package/out/resolve/landmark.d.ts.map +1 -1
- package/out/resolve/landmark.js +47 -8
- package/out/resolve/landmark.js.map +1 -1
- package/out/resolve/passes.d.ts +13 -1
- package/out/resolve/passes.d.ts.map +1 -1
- package/out/resolve/passes.js.map +1 -1
- package/out/resolve/priors.d.ts +17 -0
- package/out/resolve/priors.d.ts.map +1 -0
- package/out/resolve/priors.js +79 -0
- package/out/resolve/priors.js.map +1 -0
- package/out/resolve/region-city.d.ts +7 -0
- package/out/resolve/region-city.d.ts.map +1 -1
- package/out/resolve/region-city.js +45 -10
- package/out/resolve/region-city.js.map +1 -1
- package/out/resolve.d.ts.map +1 -1
- package/out/resolve.js +113 -122
- package/out/resolve.js.map +1 -1
- package/package.json +10 -10
package/lib/bare-toponym-race.ts
CHANGED
|
@@ -17,6 +17,7 @@ import type { PlacetypeMap } from "@mailwoman/codex/labels/placetype-map"
|
|
|
17
17
|
import type { AddressNode, AddressTree } from "@mailwoman/core/decoder"
|
|
18
18
|
import { loneValueNode } from "@mailwoman/core/decoder"
|
|
19
19
|
import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
|
|
20
|
+
import { OutcomeRequestError } from "@mailwoman/core/resolver/outcome"
|
|
20
21
|
import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetypes/specificity"
|
|
21
22
|
|
|
22
23
|
/**
|
|
@@ -204,6 +205,36 @@ export async function bareSublocalityCandidate(
|
|
|
204
205
|
return null
|
|
205
206
|
}
|
|
206
207
|
|
|
208
|
+
/**
|
|
209
|
+
* Exact, located sub-locality rows for a country-scoped `locality` query that found no locality.
|
|
210
|
+
*
|
|
211
|
+
* Probes {@link BARE_SUBLOCALITY_BANDS} coarse to fine and returns the first band with exact hits.
|
|
212
|
+
* Keeps the query's country, limit, qualifiers, bias, and outcome filters while excluding
|
|
213
|
+
* abbreviation and gloss aliases ({@link BARE_RACE_EXCLUDED_NAME_ROLES}).
|
|
214
|
+
*/
|
|
215
|
+
export async function scopedSublocalityCandidates(
|
|
216
|
+
backend: ResolverBackend,
|
|
217
|
+
query: Parameters<ResolverBackend["findPlace"]>[0]
|
|
218
|
+
): Promise<ResolvedPlace[]> {
|
|
219
|
+
for (const band of BARE_SUBLOCALITY_BANDS) {
|
|
220
|
+
try {
|
|
221
|
+
const hits = await backend.findPlace({
|
|
222
|
+
...query,
|
|
223
|
+
placetype: band,
|
|
224
|
+
excludeNameRoles: BARE_RACE_EXCLUDED_NAME_ROLES,
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
const exact = hits.filter((c) => c.placetype === band && c.exactMatch !== false && !(c.lat === 0 && c.lon === 0))
|
|
228
|
+
|
|
229
|
+
if (exact.length) return exact
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (error instanceof OutcomeRequestError) throw error
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return []
|
|
236
|
+
}
|
|
237
|
+
|
|
207
238
|
/**
|
|
208
239
|
* The place a bare toponym with no locality row resolves to, or null.
|
|
209
240
|
*
|
package/lib/decorate-node.ts
CHANGED
|
@@ -46,6 +46,7 @@ export const PICK_METADATA_KEYS = [
|
|
|
46
46
|
"resolver_encyclopedic",
|
|
47
47
|
"resolver_importance",
|
|
48
48
|
"resolver_matched_alias",
|
|
49
|
+
"resolver_name_role",
|
|
49
50
|
"resolver_bbox",
|
|
50
51
|
"postcode_city_mismatch",
|
|
51
52
|
"resolution_quality",
|
|
@@ -103,6 +104,7 @@ export function placeOfNode(node: AddressNode): ResolvedPlace | null {
|
|
|
103
104
|
prominence: number("resolver_prominence"),
|
|
104
105
|
importance: number("resolver_importance"),
|
|
105
106
|
...(meta["resolver_matched_alias"] ? { matchedAlias: true as const } : {}),
|
|
107
|
+
...(typeof meta["resolver_name_role"] === "string" ? { nameRole: meta["resolver_name_role"] } : {}),
|
|
106
108
|
}
|
|
107
109
|
}
|
|
108
110
|
|
|
@@ -208,6 +210,10 @@ export function decorateNode(
|
|
|
208
210
|
node.metadata["resolver_matched_alias"] = true
|
|
209
211
|
}
|
|
210
212
|
|
|
213
|
+
if (resolved.nameRole) {
|
|
214
|
+
node.metadata["resolver_name_role"] = resolved.nameRole
|
|
215
|
+
}
|
|
216
|
+
|
|
211
217
|
// A point-only row stores its coordinate as both corners, and a row stored
|
|
212
218
|
// in single precision can hold them a few millionths of a degree apart,
|
|
213
219
|
// so only an extent wider than that measures the place's size.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The outcome request's two fetches of each data layer: the usual fetch with the filter as its
|
|
6
|
+
* predicate, and a second fetch of the rows that satisfy the hint, or the head's first reading.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { LandmarkHit, LandmarkLookup } from "@mailwoman/core/resolver"
|
|
10
|
+
import { admittedOutcomeIDs, type OutcomeQuery, type ResolveOutcome } from "@mailwoman/core/resolver/outcome"
|
|
11
|
+
|
|
12
|
+
import type { OutcomeOrder } from "#outcome/ordering"
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The node metadata key that marks the span outcome ordering applied to.
|
|
16
|
+
*/
|
|
17
|
+
export const OUTCOME_TARGET_KEY = "outcome_target"
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The node metadata key that holds the resolved place's outcome set.
|
|
21
|
+
*/
|
|
22
|
+
export const OUTCOME_SET_KEY = "outcomes"
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The query of the usual fetch: every row's set is read, and the filter admits rows.
|
|
26
|
+
*/
|
|
27
|
+
export function filterQuery(outcome: ResolveOutcome): OutcomeQuery {
|
|
28
|
+
return {
|
|
29
|
+
vocabulary: outcome.vocabulary,
|
|
30
|
+
admit: outcome.filter ? admittedOutcomeIDs(outcome.filter, outcome.vocabulary) : null,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The reading the second fetch reads: the hint, or the head's first reading without one.
|
|
36
|
+
*/
|
|
37
|
+
export function secondFetchReading(outcome: ResolveOutcome): string | null {
|
|
38
|
+
return outcome.hint ?? outcome.headOrder?.[0] ?? null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The query of the second fetch, or null without a hint or a head order.
|
|
43
|
+
*
|
|
44
|
+
* Its rows satisfy the reading and, under a filter, the filter too.
|
|
45
|
+
*/
|
|
46
|
+
export function secondFetchQuery(outcome: ResolveOutcome): OutcomeQuery | null {
|
|
47
|
+
const reading = secondFetchReading(outcome)
|
|
48
|
+
|
|
49
|
+
if (reading == null) return null
|
|
50
|
+
|
|
51
|
+
const filtered = filterQuery(outcome).admit
|
|
52
|
+
const ids = admittedOutcomeIDs([reading], outcome.vocabulary)
|
|
53
|
+
|
|
54
|
+
return { vocabulary: outcome.vocabulary, admit: filtered ? ids.filter((id) => filtered.includes(id)) : ids }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The order the partition reads: the hint, or the head's order without one.
|
|
59
|
+
*/
|
|
60
|
+
export function outcomeOrderOf(outcome: ResolveOutcome): OutcomeOrder {
|
|
61
|
+
return { hint: outcome.hint, headOrder: outcome.hint == null ? outcome.headOrder : null }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A landmark layer's hits for a name under the outcome request: the filtered read,
|
|
66
|
+
* then the rows of the second fetch it missed.
|
|
67
|
+
*/
|
|
68
|
+
export async function findWithOutcome(
|
|
69
|
+
lookup: LandmarkLookup,
|
|
70
|
+
name: string,
|
|
71
|
+
outcome: ResolveOutcome
|
|
72
|
+
): Promise<LandmarkHit[]> {
|
|
73
|
+
const read = (query: OutcomeQuery) => Promise.resolve(lookup.find.call(lookup, name, query))
|
|
74
|
+
const first = await read(filterQuery(outcome))
|
|
75
|
+
const second = secondFetchQuery(outcome)
|
|
76
|
+
|
|
77
|
+
if (!second) return first
|
|
78
|
+
|
|
79
|
+
const seen = new Set(first.map((hit) => hit.qid))
|
|
80
|
+
|
|
81
|
+
return [...first, ...(await read(second)).filter((hit) => !seen.has(hit.qid))]
|
|
82
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The outcome partition, order 4 in the pass table of `docs/engineering/reference/outcome-kinds.mdx`,
|
|
6
|
+
* and the cross-layer merge it runs over.
|
|
7
|
+
*
|
|
8
|
+
* The partition moves candidates only inside one conformance class.
|
|
9
|
+
* Each class keeps the positions its members held, so a candidate the stated
|
|
10
|
+
* geography doesn't admit never moves ahead of one it does.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { ResolvedPlace } from "@mailwoman/core/resolver"
|
|
14
|
+
import { OutcomeLayer, outcomeSatisfies, outcomesSatisfy, unionOutcomes } from "@mailwoman/core/resolver/outcome"
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The order of the data layers when cross-layer prominence is missing.
|
|
18
|
+
*/
|
|
19
|
+
const LAYER_ORDER: readonly string[] = [OutcomeLayer.Candidate, OutcomeLayer.Landmarks, OutcomeLayer.OpenStreetMap]
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* What the partition orders by: the request's hint, or the head's readings when no hint is set.
|
|
23
|
+
*/
|
|
24
|
+
export interface OutcomeOrder {
|
|
25
|
+
hint: string | null
|
|
26
|
+
/**
|
|
27
|
+
* The head's identity top levels, most probable first.
|
|
28
|
+
* Read only without a hint.
|
|
29
|
+
*/
|
|
30
|
+
headOrder: readonly string[] | null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The key two candidates share when they're in one conformance class: the `exactMatch` tier,
|
|
35
|
+
* whether the postcode's country posterior gives the candidate's country mass, and
|
|
36
|
+
* whether the stated country and locality admit a landmark or OpenStreetMap candidate.
|
|
37
|
+
*/
|
|
38
|
+
export function conformanceKey(
|
|
39
|
+
candidate: ResolvedPlace,
|
|
40
|
+
posterior: Readonly<Record<string, number>> | null | undefined
|
|
41
|
+
): string {
|
|
42
|
+
const exact = candidate.exactMatch === true ? "1" : "0"
|
|
43
|
+
|
|
44
|
+
const mass = posterior ? (candidate.country && (posterior[candidate.country] ?? 0) > 0 ? "1" : "0") : "-"
|
|
45
|
+
|
|
46
|
+
const admitted = candidate.contextAdmits === false ? "0" : "1"
|
|
47
|
+
|
|
48
|
+
return `${exact}${mass}${admitted}`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Whether a place satisfies a requested outcome id.
|
|
53
|
+
* A place whose set wasn't read satisfies none.
|
|
54
|
+
*/
|
|
55
|
+
export function placeSatisfies(place: Pick<ResolvedPlace, "outcomes">, requested: string): boolean {
|
|
56
|
+
return outcomesSatisfy([requested], place.outcomes ?? [])
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The group a candidate falls in: 0 before 1, and so on.
|
|
61
|
+
*
|
|
62
|
+
* With a hint, the satisfying candidates are group 0 and the rest group 1.
|
|
63
|
+
* With the head's order, a candidate's group is the best rank among its identity top levels,
|
|
64
|
+
* and a candidate with none of them follows every reading.
|
|
65
|
+
*/
|
|
66
|
+
function groupOf(candidate: Pick<ResolvedPlace, "outcomes">, order: OutcomeOrder): number {
|
|
67
|
+
if (order.hint != null) return placeSatisfies(candidate, order.hint) ? 0 : 1
|
|
68
|
+
|
|
69
|
+
const readings = order.headOrder ?? []
|
|
70
|
+
|
|
71
|
+
const ranks = (candidate.outcomes ?? [])
|
|
72
|
+
.map((m) => readings.findIndex((reading) => outcomeSatisfies(reading, m.outcome)))
|
|
73
|
+
.filter((rank) => rank >= 0)
|
|
74
|
+
|
|
75
|
+
return ranks.length ? Math.min(...ranks) : readings.length
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function layerRank(candidate: ResolvedPlace): number {
|
|
79
|
+
const rank = LAYER_ORDER.indexOf(candidate.layer ?? OutcomeLayer.Candidate)
|
|
80
|
+
|
|
81
|
+
return rank === -1 ? LAYER_ORDER.length : rank
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Orders one group: each layer keeps its own order, and the layers interleave by the
|
|
86
|
+
* comparable prominence `s(e)` when every member has it, or follow the layer order otherwise.
|
|
87
|
+
*/
|
|
88
|
+
function orderGroup(members: readonly ResolvedPlace[]): ResolvedPlace[] {
|
|
89
|
+
if (!members.every((m) => typeof m.sitelinkProminence === "number")) {
|
|
90
|
+
return members.toSorted((a, b) => layerRank(a) - layerRank(b))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// A merge of the per-layer runs: the next member is the run head with the largest `s(e)`.
|
|
94
|
+
// Any candidate whose layer sits outside `LAYER_ORDER` joins a trailing run
|
|
95
|
+
// so `orderGroup` stays a permutation.
|
|
96
|
+
const knownLayers = new Set<string>(LAYER_ORDER)
|
|
97
|
+
|
|
98
|
+
const runs = [
|
|
99
|
+
...LAYER_ORDER.map((layer) => members.filter((m) => (m.layer ?? OutcomeLayer.Candidate) === layer)),
|
|
100
|
+
members.filter((m) => !knownLayers.has(m.layer ?? OutcomeLayer.Candidate)),
|
|
101
|
+
]
|
|
102
|
+
|
|
103
|
+
const merged: ResolvedPlace[] = []
|
|
104
|
+
|
|
105
|
+
while (runs.some((run) => run.length)) {
|
|
106
|
+
let best = -1
|
|
107
|
+
|
|
108
|
+
for (let i = 0; i < runs.length; i++) {
|
|
109
|
+
if (!runs[i]!.length) continue
|
|
110
|
+
|
|
111
|
+
if (best < 0 || runs[i]![0]!.sitelinkProminence! > runs[best]![0]!.sitelinkProminence!) {
|
|
112
|
+
best = i
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
merged.push(runs[best]!.shift()!)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return merged
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The outcome partition.
|
|
124
|
+
*
|
|
125
|
+
* Inside each conformance class, the candidates are grouped by {@link OutcomeOrder},
|
|
126
|
+
* and the class's members refill the positions the class held.
|
|
127
|
+
* Without a hint or a head order, the list returns unchanged.
|
|
128
|
+
*/
|
|
129
|
+
export function partitionByOutcome(
|
|
130
|
+
ranked: readonly ResolvedPlace[],
|
|
131
|
+
order: OutcomeOrder,
|
|
132
|
+
posterior: Readonly<Record<string, number>> | null | undefined
|
|
133
|
+
): ResolvedPlace[] {
|
|
134
|
+
if (order.hint == null && !order.headOrder?.length) return [...ranked]
|
|
135
|
+
|
|
136
|
+
const classes = new Map<string, number[]>()
|
|
137
|
+
|
|
138
|
+
ranked.forEach((candidate, index) => {
|
|
139
|
+
const key = conformanceKey(candidate, posterior)
|
|
140
|
+
const slots = classes.get(key) ?? []
|
|
141
|
+
|
|
142
|
+
slots.push(index)
|
|
143
|
+
classes.set(key, slots)
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
const out: ResolvedPlace[] = [...ranked]
|
|
147
|
+
|
|
148
|
+
for (const slots of classes.values()) {
|
|
149
|
+
const members = slots.map((i) => ranked[i]!)
|
|
150
|
+
const groups = new Map<number, ResolvedPlace[]>()
|
|
151
|
+
|
|
152
|
+
for (const member of members) {
|
|
153
|
+
const group = groupOf(member, order)
|
|
154
|
+
|
|
155
|
+
groups.set(group, [...(groups.get(group) ?? []), member])
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const reordered = [...groups.entries()].toSorted(([a], [b]) => a - b).flatMap(([, group]) => orderGroup(group))
|
|
159
|
+
|
|
160
|
+
slots.forEach((slot, i) => {
|
|
161
|
+
out[slot] = reordered[i]!
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return out
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Orders the rows of one data layer, all in one conformance class, by {@link OutcomeOrder},
|
|
170
|
+
* keeping the layer's order inside each group.
|
|
171
|
+
*/
|
|
172
|
+
export function orderWithinLayerByOutcome<T extends Pick<ResolvedPlace, "outcomes">>(
|
|
173
|
+
rows: readonly T[],
|
|
174
|
+
order: OutcomeOrder
|
|
175
|
+
): T[] {
|
|
176
|
+
if (order.hint == null && !order.headOrder?.length) return [...rows]
|
|
177
|
+
|
|
178
|
+
return rows
|
|
179
|
+
.map((row, index) => ({ row, index, group: groupOf(row, order) }))
|
|
180
|
+
.toSorted((a, b) => a.group - b.group || a.index - b.index)
|
|
181
|
+
.map(({ row }) => row)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Merges candidates that share a Wikidata item into one, keeping the first one's place and position.
|
|
186
|
+
*
|
|
187
|
+
* The merged candidate's set is the union of both sets, each member with the sources of both.
|
|
188
|
+
* Two candidates without a shared item stay two.
|
|
189
|
+
*/
|
|
190
|
+
export function mergeByWikidata(candidates: readonly ResolvedPlace[]): ResolvedPlace[] {
|
|
191
|
+
const byItem = new Map<string, ResolvedPlace>()
|
|
192
|
+
const out: ResolvedPlace[] = []
|
|
193
|
+
|
|
194
|
+
for (const candidate of candidates) {
|
|
195
|
+
const item = candidate.wikidata
|
|
196
|
+
const held = item ? byItem.get(item) : undefined
|
|
197
|
+
|
|
198
|
+
if (!held) {
|
|
199
|
+
const kept = { ...candidate }
|
|
200
|
+
|
|
201
|
+
out.push(kept)
|
|
202
|
+
|
|
203
|
+
if (item) {
|
|
204
|
+
byItem.set(item, kept)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
continue
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
held.outcomes = unionOutcomes(held.outcomes ?? [], candidate.outcomes ?? [])
|
|
211
|
+
held.sitelinkProminence ??= candidate.sitelinkProminence ?? null
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return out
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Merges two fetches of one data layer by place id, the first fetch's rows first.
|
|
219
|
+
*/
|
|
220
|
+
export function mergeFetches(first: readonly ResolvedPlace[], second: readonly ResolvedPlace[]): ResolvedPlace[] {
|
|
221
|
+
const seen = new Set(first.map((c) => String(c.id)))
|
|
222
|
+
|
|
223
|
+
return [...first, ...second.filter((c) => !seen.has(String(c.id)))]
|
|
224
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The span outcome ordering applies to, and the landmark candidates it reads beside the candidate table's.
|
|
6
|
+
*
|
|
7
|
+
* The hint and the filter describe the returned records, so they act on the input's
|
|
8
|
+
* leading name: the span that starts first among the spans the walk looks up.
|
|
9
|
+
* Every other span is context, ranked by the passes that exist today.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { PlacetypeMap } from "@mailwoman/codex/labels/placetype-map"
|
|
13
|
+
import { collectNodes, type AddressNode } from "@mailwoman/core/decoder"
|
|
14
|
+
import type { LandmarkHit, LandmarkLookup, ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
|
|
15
|
+
import { OUTCOME_TABLES, refuseMissingOutcomeTables, type ResolveOutcome } from "@mailwoman/core/resolver/outcome"
|
|
16
|
+
import { haversine } from "@mailwoman/spatial/geometries/point/distance"
|
|
17
|
+
|
|
18
|
+
import { findWithOutcome } from "#outcome/fetch"
|
|
19
|
+
import { placeOfLandmark, STATED_LOCALITY_RADIUS_KM } from "#resolve/landmark"
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The span outcome ordering applies to: the input's leading span, when the walk looks it up.
|
|
23
|
+
*
|
|
24
|
+
* A leading span the walk doesn't look up, such as the venue or category in `coffee near Mt. Tabor`,
|
|
25
|
+
* names the returned records, so every span after it is an anchor and keeps today's order.
|
|
26
|
+
* The landmark pass reads a leading venue under the request instead.
|
|
27
|
+
*/
|
|
28
|
+
export function outcomeTargetSpan(roots: readonly AddressNode[], placetypeMap: PlacetypeMap): AddressNode | null {
|
|
29
|
+
const leading = collectNodes(roots, (node) => !!node.value.trim()).toSorted((a, b) => a.start - b.start)[0]
|
|
30
|
+
|
|
31
|
+
return leading && placetypeMap[leading.tag as keyof PlacetypeMap] ? leading : null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Refuses an outcome request when the gazetteer or a landmark layer predates the outcome tables.
|
|
36
|
+
*
|
|
37
|
+
* A data layer without a report of its tables reads no outcome sets, so it is refused with every table.
|
|
38
|
+
*
|
|
39
|
+
* @throws {OutcomeRequestError} Naming the data layer and its missing tables.
|
|
40
|
+
*/
|
|
41
|
+
export function refuseLayersWithoutOutcomeTables(
|
|
42
|
+
backend: Pick<ResolverBackend, "missingOutcomeTables">,
|
|
43
|
+
layers: ReadonlyArray<{ name: string; lookup: LandmarkLookup }>
|
|
44
|
+
): void {
|
|
45
|
+
refuseMissingOutcomeTables("the gazetteer database", backend.missingOutcomeTables?.() ?? OUTCOME_TABLES)
|
|
46
|
+
|
|
47
|
+
for (const { name, lookup } of layers) {
|
|
48
|
+
refuseMissingOutcomeTables(`the ${name} database`, lookup.missingOutcomeTables?.() ?? OUTCOME_TABLES)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The context a landmark candidate is admitted under: the lookup's country
|
|
54
|
+
* and the nearest resolved locality above the span.
|
|
55
|
+
*/
|
|
56
|
+
export interface LandmarkContext {
|
|
57
|
+
country: string | null
|
|
58
|
+
locality: { lat: number; lon: number } | null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The landmark layers' candidates for a span, each marked whether the stated context admits it,
|
|
63
|
+
* under the layer's existing rule: the stated country, and 50 km of a stated locality.
|
|
64
|
+
*
|
|
65
|
+
* `hits` maps each candidate back to the hit it came from.
|
|
66
|
+
*/
|
|
67
|
+
export async function landmarkSpanCandidates(
|
|
68
|
+
layers: readonly LandmarkLookup[],
|
|
69
|
+
value: string,
|
|
70
|
+
outcome: ResolveOutcome,
|
|
71
|
+
context: LandmarkContext
|
|
72
|
+
): Promise<{ candidates: ResolvedPlace[]; hits: Map<string, LandmarkHit> }> {
|
|
73
|
+
const hits = new Map<string, LandmarkHit>()
|
|
74
|
+
const candidates: ResolvedPlace[] = []
|
|
75
|
+
|
|
76
|
+
for (const layer of layers) {
|
|
77
|
+
for (const hit of await findWithOutcome(layer, value, outcome)) {
|
|
78
|
+
// A settlement row is the admin ladder's to answer.
|
|
79
|
+
if (hit.kind !== "venue" || hits.has(hit.qid)) continue
|
|
80
|
+
|
|
81
|
+
const inCountry = !context.country || hit.country === context.country
|
|
82
|
+
|
|
83
|
+
const nearLocality =
|
|
84
|
+
!context.locality ||
|
|
85
|
+
haversine(context.locality.lat, context.locality.lon, hit.lat, hit.lon) <= STATED_LOCALITY_RADIUS_KM
|
|
86
|
+
|
|
87
|
+
const admits = inCountry && nearLocality
|
|
88
|
+
|
|
89
|
+
hits.set(hit.qid, hit)
|
|
90
|
+
|
|
91
|
+
candidates.push({
|
|
92
|
+
...placeOfLandmark(hit),
|
|
93
|
+
exactMatch: hit.primary || hit.code,
|
|
94
|
+
contextAdmits: admits,
|
|
95
|
+
// A place within reach of the stated locality is inside it for the containment partition.
|
|
96
|
+
containedByQualifier: context.locality ? admits : null,
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// A candidate the stated context doesn't admit follows every one it does.
|
|
102
|
+
return {
|
|
103
|
+
candidates: [...candidates.filter((c) => c.contextAdmits), ...candidates.filter((c) => !c.contextAdmits)],
|
|
104
|
+
hits,
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The steps the resolver walk runs on the span outcome ordering applies to:
|
|
6
|
+
* the request's state, the extra fetches of the candidate table, the landmark candidates,
|
|
7
|
+
* the order-4 partition and the pick's stamps.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { DEFAULT_PLACETYPE_MAP } from "@mailwoman/codex/labels/placetype-map"
|
|
11
|
+
import type { AddressNode, AddressTree } from "@mailwoman/core/decoder"
|
|
12
|
+
import type { LandmarkHit, ResolvedPlace, ResolveOpts, ResolverBackend } from "@mailwoman/core/resolver"
|
|
13
|
+
import { OutcomeLayer } from "@mailwoman/core/resolver/outcome"
|
|
14
|
+
|
|
15
|
+
import { BARE_SUBLOCALITY_BANDS } from "#bare-toponym-race"
|
|
16
|
+
import { OUTCOME_SET_KEY, OUTCOME_TARGET_KEY, outcomeOrderOf, secondFetchQuery } from "#outcome/fetch"
|
|
17
|
+
import { mergeByWikidata, mergeFetches, partitionByOutcome } from "#outcome/ordering"
|
|
18
|
+
import { landmarkSpanCandidates, outcomeTargetSpan, refuseLayersWithoutOutcomeTables } from "#outcome/span"
|
|
19
|
+
import type { CoordinateOptionalPlace } from "#postcode/prefix"
|
|
20
|
+
import type { ResolutionState } from "#resolve/passes"
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The outcome state of one span: the request, the span and the landmark layers it reads.
|
|
24
|
+
*/
|
|
25
|
+
export type OutcomeSpan = NonNullable<ResolutionState["outcome"]>
|
|
26
|
+
|
|
27
|
+
type FindPlaceQuery = Parameters<ResolverBackend["findPlace"]>[0]
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The resolver state of an outcome request, or an empty object without a request or a leading span to order.
|
|
31
|
+
*
|
|
32
|
+
* @throws {OutcomeRequestError} When a data layer predates the outcome tables.
|
|
33
|
+
*/
|
|
34
|
+
export function outcomeState(
|
|
35
|
+
tree: AddressTree,
|
|
36
|
+
opts: ResolveOpts,
|
|
37
|
+
backend: ResolverBackend
|
|
38
|
+
): Pick<ResolutionState, "outcome"> {
|
|
39
|
+
if (!opts.outcome) return {}
|
|
40
|
+
|
|
41
|
+
const named = [
|
|
42
|
+
...(opts.landmarks ? [{ name: OutcomeLayer.Landmarks, lookup: opts.landmarks }] : []),
|
|
43
|
+
...(opts.osmPlaces ? [{ name: OutcomeLayer.OpenStreetMap, lookup: opts.osmPlaces }] : []),
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
refuseLayersWithoutOutcomeTables(backend, named)
|
|
47
|
+
|
|
48
|
+
const target = outcomeTargetSpan(tree.roots, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP)
|
|
49
|
+
|
|
50
|
+
if (!target) return {}
|
|
51
|
+
|
|
52
|
+
return { outcome: { request: opts.outcome, target, layers: named.map((layer) => layer.lookup) } }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The candidate table's fetches beyond the usual one.
|
|
57
|
+
*
|
|
58
|
+
* The hint, or the head's first reading, adds one fetch of the rows that satisfy it.
|
|
59
|
+
* The bare-toponym race stands down on an outcome-ordered span, so a bare name also
|
|
60
|
+
* reads the sub-locality and admin bands the race would have probed.
|
|
61
|
+
*/
|
|
62
|
+
export async function outcomeFetches(
|
|
63
|
+
backend: ResolverBackend,
|
|
64
|
+
query: FindPlaceQuery,
|
|
65
|
+
span: OutcomeSpan,
|
|
66
|
+
bareName: boolean,
|
|
67
|
+
candidates: ResolvedPlace[]
|
|
68
|
+
): Promise<ResolvedPlace[]> {
|
|
69
|
+
let merged = candidates
|
|
70
|
+
const second = secondFetchQuery(span.request)
|
|
71
|
+
|
|
72
|
+
if (second) {
|
|
73
|
+
merged = mergeFetches(merged, await backend.findPlace({ ...query, outcome: second }))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (bareName) {
|
|
77
|
+
const bands = [...BARE_SUBLOCALITY_BANDS, "region", "country"]
|
|
78
|
+
|
|
79
|
+
merged = mergeFetches(merged, await backend.findPlace({ ...query, placetype: bands }))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return merged
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The landmark layers' candidates for the span, admitted under the lookup's country
|
|
87
|
+
* and the span's resolved locality parent.
|
|
88
|
+
*/
|
|
89
|
+
export function spanLayerCandidates(
|
|
90
|
+
span: OutcomeSpan,
|
|
91
|
+
node: AddressNode,
|
|
92
|
+
country: string | null,
|
|
93
|
+
parentResolved: CoordinateOptionalPlace | null
|
|
94
|
+
): ReturnType<typeof landmarkSpanCandidates> {
|
|
95
|
+
const locality =
|
|
96
|
+
parentResolved?.placetype === "locality" && parentResolved.lat != null && parentResolved.lon != null
|
|
97
|
+
? { lat: parentResolved.lat, lon: parentResolved.lon }
|
|
98
|
+
: null
|
|
99
|
+
|
|
100
|
+
return landmarkSpanCandidates(span.layers, node.value, span.request, { country, locality })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Order 4: one candidate list across the data layers, one place per Wikidata item,
|
|
105
|
+
* then the outcome partition inside each conformance class.
|
|
106
|
+
*/
|
|
107
|
+
export function orderSpanByOutcome(
|
|
108
|
+
ranked: readonly ResolvedPlace[],
|
|
109
|
+
span: OutcomeSpan,
|
|
110
|
+
layered: readonly ResolvedPlace[],
|
|
111
|
+
posterior: Readonly<Record<string, number>> | null | undefined
|
|
112
|
+
): ResolvedPlace[] {
|
|
113
|
+
const table = ranked.map((c) => ({ ...c, layer: OutcomeLayer.Candidate }))
|
|
114
|
+
|
|
115
|
+
return partitionByOutcome(mergeByWikidata([...table, ...layered]), outcomeOrderOf(span.request), posterior)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The metadata an outcome-ordered span's pick writes: the span's mark, the place's
|
|
120
|
+
* outcome set, and a landmark winner's sitelinks and source.
|
|
121
|
+
* The geocode result reads all four.
|
|
122
|
+
*/
|
|
123
|
+
export function outcomePickStamps(top: ResolvedPlace, hits: ReadonlyMap<string, LandmarkHit>): Record<string, unknown> {
|
|
124
|
+
const hit = top.layer && top.layer !== OutcomeLayer.Candidate ? hits.get(String(top.id)) : undefined
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
[OUTCOME_TARGET_KEY]: true,
|
|
128
|
+
[OUTCOME_SET_KEY]: top.outcomes ?? [],
|
|
129
|
+
...(hit ? { landmark_sitelinks: hit.sitelinks } : {}),
|
|
130
|
+
...(top.layer === OutcomeLayer.OpenStreetMap ? { landmark_source: "openstreetmap:planet" } : {}),
|
|
131
|
+
}
|
|
132
|
+
}
|