@mailwoman/core 7.2.0 → 7.3.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 (150) hide show
  1. package/api/APIClient.ts +175 -0
  2. package/api/headless.ts +23 -0
  3. package/api/index.ts +11 -0
  4. package/api/responses.ts +135 -0
  5. package/coarse-placer/coarse-placer.ts +300 -0
  6. package/coarse-placer/featurize.ts +171 -0
  7. package/coarse-placer/tools/build-dataset.ts +223 -0
  8. package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
  9. package/coarse-placer/tools/build-outlier-latin.ts +200 -0
  10. package/coarse-placer/tools/build-outlier-oa.ts +231 -0
  11. package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
  12. package/coarse-placer/tools/eval-openset.ts +519 -0
  13. package/coarse-placer/tools/eval-quant-compare.ts +151 -0
  14. package/coarse-placer/tools/eval.ts +187 -0
  15. package/coarse-placer/tools/fnv-hash.ts +24 -0
  16. package/coarse-placer/tools/index.ts +23 -0
  17. package/coarse-placer/tools/probe-frontier.ts +216 -0
  18. package/coarse-placer/tools/quantize.ts +116 -0
  19. package/coarse-placer/tools/train.ts +244 -0
  20. package/collections.ts +134 -0
  21. package/db/schema.ts +21 -0
  22. package/decoder/build-tree.ts +228 -0
  23. package/decoder/calibration.ts +101 -0
  24. package/decoder/containment.ts +87 -0
  25. package/decoder/index.ts +17 -0
  26. package/decoder/proposals-to-tree.ts +83 -0
  27. package/decoder/resolve-proposal-overlaps.ts +79 -0
  28. package/decoder/serialize-json.ts +70 -0
  29. package/decoder/serialize-tuples.ts +61 -0
  30. package/decoder/serialize-xml.ts +209 -0
  31. package/decoder/types.ts +159 -0
  32. package/decoder/unknown-spans.ts +103 -0
  33. package/decoder/validate-tree.ts +100 -0
  34. package/env/index.ts +42 -0
  35. package/env/load.ts +14 -0
  36. package/env/paths.ts +40 -0
  37. package/env/schema.ts +125 -0
  38. package/errors/index.ts +9 -0
  39. package/errors/schema.ts +155 -0
  40. package/fs/node.ts +38 -0
  41. package/identifiers.ts +58 -0
  42. package/index.ts +13 -0
  43. package/kysley/adapter.ts +29 -0
  44. package/kysley/client.ts +30 -0
  45. package/kysley/dialect-config.ts +30 -0
  46. package/kysley/dialect.ts +67 -0
  47. package/kysley/driver.ts +175 -0
  48. package/layers/index.ts +12 -0
  49. package/layers/manifest.ts +154 -0
  50. package/layers/schema.ts +105 -0
  51. package/locale/index.ts +9 -0
  52. package/locale/locale.ts +49 -0
  53. package/locale/profiles/en-us.ts +69 -0
  54. package/locale/profiles/fr-fr.ts +75 -0
  55. package/locale/profiles/index.ts +9 -0
  56. package/locale/profiles/ja-jp.ts +33 -0
  57. package/locale/registry.ts +68 -0
  58. package/logging/index.ts +8 -0
  59. package/logging/shared.ts +145 -0
  60. package/logging/utils.ts +46 -0
  61. package/objects.ts +211 -0
  62. package/out/api/APIClient.d.ts.map +1 -1
  63. package/out/api/APIClient.js +2 -2
  64. package/out/api/APIClient.js.map +1 -1
  65. package/out/pipeline/types.d.ts +13 -0
  66. package/out/pipeline/types.d.ts.map +1 -1
  67. package/out/pipeline/types.js.map +1 -1
  68. package/out/scripting/utils/index.d.ts.map +1 -1
  69. package/out/scripting/utils/index.js +3 -5
  70. package/out/scripting/utils/index.js.map +1 -1
  71. package/package.json +190 -107
  72. package/pipeline/index.ts +46 -0
  73. package/pipeline/reconcile-lookups.ts +108 -0
  74. package/pipeline/reconcile.ts +542 -0
  75. package/pipeline/runtime-pipeline.ts +732 -0
  76. package/pipeline/span-logit-aggregation.ts +151 -0
  77. package/pipeline/span-proposer.ts +587 -0
  78. package/pipeline/types.ts +357 -0
  79. package/policy/defaults.ts +35 -0
  80. package/policy/index.ts +10 -0
  81. package/policy/policy.ts +60 -0
  82. package/policy/proposal-collection.ts +64 -0
  83. package/policy/registry.ts +149 -0
  84. package/resolver/index.ts +29 -0
  85. package/resolver/types.ts +584 -0
  86. package/resources/LocaleIndex.ts +124 -0
  87. package/resources/ResourceMapCache.ts +126 -0
  88. package/resources/collections.ts +93 -0
  89. package/resources/debugging.ts +19 -0
  90. package/resources/git.ts +54 -0
  91. package/resources/index.ts +17 -0
  92. package/resources/languages/index.ts +49 -0
  93. package/resources/languages/types.gen.ts +1368 -0
  94. package/resources/libaddressinput.ts +105 -0
  95. package/resources/libpostal.ts +182 -0
  96. package/resources/locale.ts +23 -0
  97. package/resources/set.ts +179 -0
  98. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  99. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  100. package/resources/whosonfirst/index.ts +10 -0
  101. package/resources/whosonfirst/loader.ts +157 -0
  102. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  103. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  104. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  105. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  106. package/resources/whosonfirst/placetypes/index.ts +12 -0
  107. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  108. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  109. package/routing/index.ts +208 -0
  110. package/scripting/index.ts +40 -0
  111. package/scripting/utils/index.ts +103 -0
  112. package/tokenization/Graph.ts +50 -0
  113. package/tokenization/Span.ts +297 -0
  114. package/tokenization/index.ts +9 -0
  115. package/tokenization/normalizer.ts +123 -0
  116. package/tools/download-libpostal-resources.ts +98 -0
  117. package/tools/download-ssl-address.ts +99 -0
  118. package/tools/generate-language-types.ts +194 -0
  119. package/tools/index.ts +13 -0
  120. package/types/Classification.ts +211 -0
  121. package/types/classifier.ts +133 -0
  122. package/types/component.ts +75 -0
  123. package/types/index.ts +10 -0
  124. package/types/mapping.ts +81 -0
  125. package/utils/data-root.ts +56 -0
  126. package/utils/hash.ts +27 -0
  127. package/utils/index.ts +14 -0
  128. package/utils/jsonl.ts +43 -0
  129. package/utils/python-json.ts +105 -0
  130. package/utils/python-random.ts +90 -0
  131. package/utils/repo.ts +118 -0
  132. package/utils/sealed-db.ts +85 -0
  133. package/utils/stats.ts +32 -0
  134. package/vitest.config.ts +53 -0
  135. package/out/lifecycle/ServiceSymbol.d.ts +0 -57
  136. package/out/lifecycle/ServiceSymbol.d.ts.map +0 -1
  137. package/out/lifecycle/ServiceSymbol.js +0 -60
  138. package/out/lifecycle/ServiceSymbol.js.map +0 -1
  139. package/out/lifecycle/index.d.ts +0 -11
  140. package/out/lifecycle/index.d.ts.map +0 -1
  141. package/out/lifecycle/index.js +0 -11
  142. package/out/lifecycle/index.js.map +0 -1
  143. package/out/lifecycle/lru-cache.d.ts +0 -22
  144. package/out/lifecycle/lru-cache.d.ts.map +0 -1
  145. package/out/lifecycle/lru-cache.js +0 -31
  146. package/out/lifecycle/lru-cache.js.map +0 -1
  147. package/out/lifecycle/services.d.ts +0 -144
  148. package/out/lifecycle/services.d.ts.map +0 -1
  149. package/out/lifecycle/services.js +0 -191
  150. package/out/lifecycle/services.js.map +0 -1
@@ -0,0 +1,101 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Opt-in confidence calibration for decoded spans.
7
+ *
8
+ * The decoder emits a per-span `confidence` that is the mean of the span's per-token softmax
9
+ * probabilities (`build-tree.ts`). Softmax probabilities are NOT calibrated — a CE-trained model
10
+ * is systematically over/under-confident in bands. Task #59 fits an isotonic-regression
11
+ * calibrator on a held-out OpenAddresses + corpus set
12
+ * (`scripts/eval/fit-isotonic-calibration.py`) and ships the result as a 20-bin lookup table
13
+ * (`data/eval/calibration/isotonic-<locale>-<version>.json`).
14
+ *
15
+ * This module turns that table into a pure `(rawConfidence) => calibratedConfidence` function. It
16
+ * is deliberately decoupled from the table source: pass the PARSED JSON object so this stays
17
+ * browser-safe (no `node:fs`) — the demo imports the JSON directly, Node scripts `JSON.parse`
18
+ * it.
19
+ *
20
+ * Wiring is OPT-IN. The default decode path is unchanged (byte-stable `conf=` output). A caller
21
+ * that wants calibrated confidences builds a `Calibrator` here and passes it via
22
+ * `ParseOpts.calibrate` (neural) / `BuildTreeOpts.calibrate` (decoder), which `build-tree.ts`
23
+ * applies in `flush()`.
24
+ */
25
+
26
+ /** One row of the lookup table: a confidence bin and the calibrated value at its center. */
27
+ export interface CalibrationBin {
28
+ lo: number
29
+ hi: number
30
+ center: number
31
+ calibrated: number
32
+ }
33
+
34
+ /** The full calibration artifact emitted by `fit-isotonic-calibration.py`. */
35
+ export interface CalibrationTable {
36
+ model: string
37
+ model_version: string
38
+ method: string
39
+ bins: number
40
+ table: CalibrationBin[]
41
+ [key: string]: unknown
42
+ }
43
+
44
+ /** Maps a raw span confidence in [0, 1] to its calibrated probability of correctness. */
45
+ export type Calibrator = (rawConfidence: number) => number
46
+
47
+ /**
48
+ * Build a calibrator from an isotonic lookup table. The mapping is piecewise-linear between bin centers and clamped to
49
+ * the table's range outside it (the table is monotone non-decreasing by construction, so the interpolation is monotone
50
+ * too). Accepts either the full `CalibrationTable` or a bare `CalibrationBin[]`.
51
+ */
52
+ export function createCalibrator(table: CalibrationTable | CalibrationBin[]): Calibrator {
53
+ const bins = Array.isArray(table) ? table : table.table
54
+
55
+ if (!bins || bins.length === 0) {
56
+ throw new Error("createCalibrator: empty calibration table")
57
+ }
58
+ // Sort by center and extract parallel arrays for interpolation.
59
+ const sorted = [...bins].sort((a, b) => a.center - b.center)
60
+ const centers = sorted.map((b) => b.center)
61
+ const cals = sorted.map((b) => clamp01(b.calibrated))
62
+ const n = centers.length
63
+
64
+ return (raw: number): number => {
65
+ const x = clamp01(raw)
66
+
67
+ if (x <= centers[0]!) return cals[0]!
68
+
69
+ if (x >= centers[n - 1]!) return cals[n - 1]!
70
+ // Binary search for the interval [centers[i], centers[i+1]] containing x.
71
+ let lo = 0
72
+ let hi = n - 1
73
+
74
+ while (hi - lo > 1) {
75
+ const mid = (lo + hi) >> 1
76
+
77
+ if (centers[mid]! <= x) {
78
+ lo = mid
79
+ } else {
80
+ hi = mid
81
+ }
82
+ }
83
+ const x0 = centers[lo]!
84
+ const x1 = centers[hi]!
85
+ const y0 = cals[lo]!
86
+ const y1 = cals[hi]!
87
+ const t = x1 === x0 ? 0 : (x - x0) / (x1 - x0)
88
+
89
+ return y0 + t * (y1 - y0)
90
+ }
91
+ }
92
+
93
+ function clamp01(v: number): number {
94
+ if (Number.isNaN(v)) return 0
95
+
96
+ if (v < 0) return 0
97
+
98
+ if (v > 1) return 1
99
+
100
+ return v
101
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Containment rule for the address tree.
7
+ *
8
+ * Each tag lists permitted parents in priority order (most-preferred first). The tree builder
9
+ * resolves each span's parent by walking this list and picking the first tag that has at least
10
+ * one labeled span; if multiple spans share that tag, the one nearest to this span in char
11
+ * distance wins. Spans whose tag is absent from this map (or has no labeled parent) become
12
+ * roots.
13
+ *
14
+ * Tags absent from a map are treated as root-only (no parent ever accepted).
15
+ *
16
+ * ## Per-system containment (anti-lock-in)
17
+ *
18
+ * Addressing _systems_ disagree on hierarchy: a US street address nests `house_number → street →
19
+ * locality`, while a Japanese block address nests `building_number → sub_block → block →
20
+ * district` — there is no `street` parent at all. Today a single global map suffices only because
21
+ * the tag sets don't collide, but the moment the resolver or tree builder hardcodes the Western
22
+ * shape, retrofitting a second system gets expensive (DeepSeek resolver consult, 2026-05-30).
23
+ *
24
+ * The cheap insurance is this indirection: callers ask `containmentFor(system)` rather than
25
+ * importing one global constant. Today every system resolves to `WESTERN_PARENT_OF` (the
26
+ * historical map, behavior-identical), and `PARENT_OF` is kept as an alias so existing imports
27
+ * don't break. When a distinct system map lands (Phase 6 JP), it slots in here with zero
28
+ * call-site churn. See `AddressSystem` in `./types.ts`.
29
+ */
30
+
31
+ import type { ComponentTag } from "../types/component.ts"
32
+ import type { AddressSystem } from "./types.ts"
33
+
34
+ /** Preferred-parent ordering for each tag. Empty / missing = always root. */
35
+ export const WESTERN_PARENT_OF: Partial<Record<ComponentTag, ComponentTag[]>> = {
36
+ // Universal coarse — containment follows geographic granularity.
37
+ region: ["country"],
38
+ subregion: ["region", "country"],
39
+ locality: ["subregion", "region", "country"],
40
+ dependent_locality: ["locality"],
41
+ postcode: ["locality", "subregion", "region", "country"],
42
+ cedex: ["postcode", "locality"],
43
+
44
+ // Street-level — street nests inside locality; house_number/unit/intersections nest inside street.
45
+ street: ["dependent_locality", "locality", "subregion", "region"],
46
+ street_prefix: ["street"],
47
+ street_prefix_particle: ["street_prefix", "street"],
48
+ street_suffix: ["street"],
49
+ house_number: ["street"],
50
+ unit: ["street", "house_number"],
51
+ intersection_a: ["street", "locality"],
52
+ intersection_b: ["street", "locality"],
53
+
54
+ // Venue / mailing — separate top-level concepts; attach to street if labeled.
55
+ venue: ["street", "locality"],
56
+ attention: ["venue"],
57
+ po_box: ["locality", "subregion", "region"],
58
+
59
+ // JP — declared for forward-compat; mapping is provisional and will be revisited in Phase 6, when
60
+ // a dedicated `japanese` system map likely supersedes these entries with a no-street hierarchy.
61
+ prefecture: ["country"],
62
+ municipality: ["prefecture"],
63
+ district: ["municipality"],
64
+ block: ["district"],
65
+ sub_block: ["block"],
66
+ building_number: ["sub_block", "block"],
67
+ building_name: ["building_number", "sub_block", "block"],
68
+ }
69
+
70
+ /**
71
+ * The containment map for a given addressing system.
72
+ *
73
+ * Currently every system maps to {@link WESTERN_PARENT_OF} — the indirection exists so a future system-specific map
74
+ * (e.g. Japanese block addressing) can be introduced without touching the tree builder or validator. `undefined` (the
75
+ * common case — system not yet detected) uses the default.
76
+ */
77
+ export function containmentFor(_system?: AddressSystem): Partial<Record<ComponentTag, ComponentTag[]>> {
78
+ // Single system today. The parameter is intentionally consumed lazily — adding `case "japanese":`
79
+ // here is the entire surface area for a new system's hierarchy.
80
+ return WESTERN_PARENT_OF
81
+ }
82
+
83
+ /**
84
+ * Backwards-compatible alias for the default (Western) containment map. Prefer `containmentFor()` in new code so the
85
+ * system parameter threads through; this export remains for existing call sites.
86
+ */
87
+ export const PARENT_OF = WESTERN_PARENT_OF
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "./build-tree.ts"
8
+ export * from "./calibration.ts"
9
+ export * from "./containment.ts"
10
+ export * from "./proposals-to-tree.ts"
11
+ export * from "./resolve-proposal-overlaps.ts"
12
+ export * from "./serialize-json.ts"
13
+ export * from "./serialize-tuples.ts"
14
+ export * from "./serialize-xml.ts"
15
+ export * from "./types.ts"
16
+ export * from "./unknown-spans.ts"
17
+ export * from "./validate-tree.ts"
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Project a flat list of `ClassificationProposal`s into a flat `AddressTree` (every proposal
7
+ * becomes a root node, no containment nesting). Useful for surfacing policy-filtered output
8
+ * through the existing JSON/tuple/XML decoder projections without rebuilding the original
9
+ * containment hierarchy — which is intentionally lossy: once proposals are individually
10
+ * accept/rejected by policy, the containment relationships from the source tree may no longer be
11
+ * meaningful.
12
+ *
13
+ * For consumers that need containment back, re-tokenize the input and run the full decoder
14
+ * pipeline.
15
+ */
16
+
17
+ import type { Span } from "../tokenization/index.ts"
18
+ import type { ClassificationProposal, ClassificationProposalSource, ComponentTag } from "../types/index.ts"
19
+ import type { AddressNode, AddressTree } from "./types.ts"
20
+
21
+ export function proposalsToTree(raw: string, proposals: readonly ClassificationProposal[]): AddressTree {
22
+ const roots: AddressNode[] = proposals.map((p) => ({
23
+ tag: p.component as ComponentTag,
24
+ value: p.span.body,
25
+ start: p.span.start,
26
+ end: p.span.end,
27
+ confidence: p.confidence,
28
+ children: [],
29
+ source: p.source,
30
+ sourceID: p.source_id,
31
+ }))
32
+ roots.sort((a, b) => a.start - b.start)
33
+
34
+ return { raw, roots }
35
+ }
36
+
37
+ /**
38
+ * The inverse of {@link proposalsToTree}: walk an `AddressTree` into a flat list of `ClassificationProposal`s (one per
39
+ * node, depth-first), tagged with the given `source` (#478 increment 3). Used to bring the whole-text neural parse into
40
+ * the arbitration layer's proposal currency so it can be unioned with rule proposals and filtered by the policy
41
+ * registry.
42
+ *
43
+ * The spans are structural (`{ start, end, body }`) — we intentionally avoid `Span.from(...)` (which forces the
44
+ * tokenization module's filesystem-bound init); downstream proposal consumers read only `start` / `end` / `body`. Same
45
+ * convention as the neural proposal-classifier adapter.
46
+ *
47
+ * @param tree The parsed tree (e.g. the neural argmax tree).
48
+ * @param source Provenance stamped on every emitted proposal (`"neural"` here).
49
+ * @param opts.sourceID Optional stable id surfaced as `source_id`.
50
+ * @param opts.emits Optional tag allow-list; when set, only nodes with these tags are emitted.
51
+ */
52
+ export function treeToProposals(
53
+ tree: AddressTree,
54
+ source: ClassificationProposalSource,
55
+ opts: { sourceID?: string; emits?: ReadonlySet<ComponentTag> } = {}
56
+ ): ClassificationProposal[] {
57
+ const proposals: ClassificationProposal[] = []
58
+ const { sourceID, emits } = opts
59
+
60
+ const visit = (node: AddressNode): void => {
61
+ if (!emits || emits.has(node.tag)) {
62
+ const span = { start: node.start, end: node.end, body: node.value } as unknown as Span
63
+ proposals.push({
64
+ span,
65
+ component: node.tag,
66
+ confidence: node.confidence,
67
+ source,
68
+ source_id: sourceID ?? node.sourceID ?? source,
69
+ penalty: 0,
70
+ })
71
+ }
72
+
73
+ for (const child of node.children) {
74
+ visit(child)
75
+ }
76
+ }
77
+
78
+ for (const root of tree.roots) {
79
+ visit(root)
80
+ }
81
+
82
+ return proposals
83
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Coherence pass for arbitrated proposals (#478 increment 3).
7
+ *
8
+ * The arbitration layer unions proposals from multiple sources (whole-text `neural`, per-section
9
+ * `rule`) and filters them per-component via the policy registry. That per-_tag_ filter is blind
10
+ * to cross-_tag_ span overlap: a `neural` street span `[0,11]` ("350 5th Ave") and a `rule`
11
+ * house_number `[0,3]` ("350") can both survive — different tags, overlapping spans. Fed straight
12
+ * into {@link proposalsToTree} (which emits one flat root node per proposal, no overlap handling)
13
+ * that yields an incoherent tree with overlapping nodes, which degrades or breaks the resolver.
14
+ *
15
+ * This pass guarantees the invariant {@link proposalsToTree} needs: **no two surviving proposals
16
+ * have overlapping spans.** It is a greedy interval selection — accept proposals in priority
17
+ * order, skip any that overlap an already-accepted span.
18
+ *
19
+ * ## The selection policy (the gate-tunable lever)
20
+ *
21
+ * Priority is **confidence desc, then shorter span first, then earlier start**:
22
+ *
23
+ * - _Confidence primary_ respects the arbitration that already happened — a source the registry kept
24
+ * at high confidence wins its span.
25
+ * - _Shorter-span-first on ties_ preserves finer decompositions: given equal-confidence
26
+ * `street[0,11]` vs `{house_number[0,3], street[4,11]}`, the two finer spans are accepted and
27
+ * the coarse subsuming span is dropped — keeping the street+house_number precondition intact
28
+ * (the thing #566 broke). The neural argmax path labels per-token, so it normally emits the
29
+ * finer decomposition itself; this tiebreak is the safety net when a coarse rule span
30
+ * competes.
31
+ *
32
+ * This policy is deliberately simple and deterministic. It is the lever the inc-3 assembled gate
33
+ * validates: if it drops too many house numbers (precondition regression) the comparator is where
34
+ * to look. (An alternative — earliest-end-first maximal-tiling, ignoring confidence — maximizes
35
+ * the _count_ of non-overlapping spans but can let a spurious tiny span evict a correct large
36
+ * one; confidence-primary guards against that.)
37
+ *
38
+ * Pure module: reads only `span.{start,end}` + `confidence`. Safe to import anywhere.
39
+ */
40
+
41
+ import type { ClassificationProposal } from "../types/index.ts"
42
+
43
+ /** Half-open interval overlap: `[aStart,aEnd)` and `[bStart,bEnd)` share at least one position. */
44
+ function spansOverlap(a: ClassificationProposal["span"], b: ClassificationProposal["span"]): boolean {
45
+ return a.start < b.end && b.start < a.end
46
+ }
47
+
48
+ /**
49
+ * Reduce a set of (possibly overlapping) arbitrated proposals to a coherent, non-overlapping set via greedy interval
50
+ * selection. The output is sorted by span start (the order {@link proposalsToTree} expects). Input is not mutated.
51
+ *
52
+ * @param proposals Arbitrated proposals (post policy-registry filter), any source, possibly overlapping.
53
+ *
54
+ * @returns A subset with no two spans overlapping, in span-start order.
55
+ */
56
+ export function resolveProposalOverlaps(proposals: readonly ClassificationProposal[]): ClassificationProposal[] {
57
+ if (proposals.length <= 1) return [...proposals]
58
+
59
+ const ranked = [...proposals].sort((a, b) => {
60
+ if (b.confidence !== a.confidence) return b.confidence - a.confidence // higher confidence first
61
+ const lenA = a.span.end - a.span.start
62
+ const lenB = b.span.end - b.span.start
63
+
64
+ if (lenA !== lenB) return lenA - lenB
65
+
66
+ // shorter (finer) span first — preserve decompositions
67
+ return a.span.start - b.span.start // earlier start first — stable, deterministic
68
+ })
69
+
70
+ const kept: ClassificationProposal[] = []
71
+
72
+ for (const proposal of ranked) {
73
+ if (kept.every((k) => !spansOverlap(k.span, proposal.span))) {
74
+ kept.push(proposal)
75
+ }
76
+ }
77
+
78
+ return kept.sort((a, b) => a.span.start - b.span.start)
79
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Libpostal-compatible JSON projection.
7
+ *
8
+ * Flattens the tree to `{ tag: value }`. First-occurrence wins for repeated tags — matches
9
+ * libpostal's behavior. Use `decodeAsTuples` if order or repetition matters.
10
+ *
11
+ * A multi-role node (#413 — a city-state span tagged `region` that also plays `locality`) emits one
12
+ * entry per role from its `interpretations`, so `out.locality` still surfaces for a completed
13
+ * city-state. The shared span means every role gets the same `value`.
14
+ */
15
+
16
+ import type { ComponentTag } from "../types/component.ts"
17
+ import type { AddressNode, AddressTree } from "./types.ts"
18
+ import { type UnknownSpan, unknownSpans } from "./unknown-spans.ts"
19
+
20
+ /** Options for {@link decodeAsJSON}. */
21
+ export interface SerializeJSONOpts {
22
+ /**
23
+ * Add an `unknown` array of the all-O spans the model left unclassified (#493). Default false — keeps the output
24
+ * libpostal-compatible (a flat tag→value map) unless the caller asks for the gaps.
25
+ */
26
+ includeUnknown?: boolean
27
+ }
28
+
29
+ function visit(node: AddressNode, out: Partial<Record<ComponentTag, string>>): void {
30
+ if (!(node.tag in out)) {
31
+ out[node.tag] = node.value
32
+ }
33
+
34
+ if (node.interpretations) {
35
+ for (const interp of node.interpretations) {
36
+ if (!(interp.tag in out)) {
37
+ out[interp.tag] = node.value
38
+ }
39
+ }
40
+ }
41
+
42
+ for (const child of node.children) {
43
+ visit(child, out)
44
+ }
45
+ }
46
+
47
+ /** Project an `AddressTree` to a flat libpostal-style component map. */
48
+ export function decodeAsJSON(tree: AddressTree): Partial<Record<ComponentTag, string>>
49
+ export function decodeAsJSON(
50
+ tree: AddressTree,
51
+ opts: SerializeJSONOpts
52
+ ): Partial<Record<ComponentTag, string>> & { unknown?: UnknownSpan[] }
53
+ export function decodeAsJSON(
54
+ tree: AddressTree,
55
+ opts: SerializeJSONOpts = {}
56
+ ): Partial<Record<ComponentTag, string>> & { unknown?: UnknownSpan[] } {
57
+ const out: Partial<Record<ComponentTag, string>> & { unknown?: UnknownSpan[] } = {}
58
+
59
+ for (const root of tree.roots) {
60
+ visit(root, out)
61
+ }
62
+
63
+ // Always emit `unknown` (even `[]`) when asked — a consumer that opted in can iterate it without a
64
+ // presence check. Omitting-when-empty was a libpostal-flat-map instinct that doesn't fit the opt-in path.
65
+ if (opts.includeUnknown) {
66
+ out.unknown = unknownSpans(tree)
67
+ }
68
+
69
+ return out
70
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Order-preserving tuple projection.
7
+ *
8
+ * Emits `Array<[tag, value]>` in source order (sorted by `start`). Preserves repeated tags (e.g.
9
+ * two `locality` entries for "Springfield, IL — sent from Springfield, MA"). Hierarchy is lost —
10
+ * use `decodeAsXML` when containment matters.
11
+ */
12
+
13
+ import type { ComponentTag } from "../types/component.ts"
14
+ import type { AddressNode, AddressTree } from "./types.ts"
15
+ import { unknownSpans } from "./unknown-spans.ts"
16
+
17
+ /** Options for {@link decodeAsTuples}. */
18
+ export interface SerializeTuplesOpts {
19
+ /**
20
+ * Interleave `["unknown", value]` tuples for the all-O spans the model left unclassified (#493), in source order.
21
+ * Default false — keeps the existing tag-only shape unless the caller asks for the gaps.
22
+ */
23
+ includeUnknown?: boolean
24
+ }
25
+
26
+ function flatten(node: AddressNode, out: AddressNode[]): void {
27
+ out.push(node)
28
+
29
+ for (const child of node.children) {
30
+ flatten(child, out)
31
+ }
32
+ }
33
+
34
+ /** Project an `AddressTree` to a source-ordered list of (tag, value) pairs. */
35
+ export function decodeAsTuples(tree: AddressTree): Array<[ComponentTag, string]>
36
+ export function decodeAsTuples(tree: AddressTree, opts: SerializeTuplesOpts): Array<[ComponentTag | "unknown", string]>
37
+ export function decodeAsTuples(
38
+ tree: AddressTree,
39
+ opts: SerializeTuplesOpts = {}
40
+ ): Array<[ComponentTag | "unknown", string]> {
41
+ const all: AddressNode[] = []
42
+
43
+ for (const root of tree.roots) {
44
+ flatten(root, all)
45
+ }
46
+
47
+ const entries: Array<{ start: number; tuple: [ComponentTag | "unknown", string] }> = all.map((n) => ({
48
+ start: n.start,
49
+ tuple: [n.tag, n.value],
50
+ }))
51
+
52
+ if (opts.includeUnknown) {
53
+ for (const u of unknownSpans(tree)) {
54
+ entries.push({ start: u.start, tuple: ["unknown", u.value] })
55
+ }
56
+ }
57
+
58
+ entries.sort((a, b) => a.start - b.start)
59
+
60
+ return entries.map((e) => e.tuple)
61
+ }