@mailwoman/core 7.1.0 → 7.2.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/api/APIClient.ts +175 -0
- package/api/headless.ts +23 -0
- package/api/index.ts +11 -0
- package/api/responses.ts +135 -0
- package/coarse-placer/coarse-placer.ts +300 -0
- package/coarse-placer/featurize.ts +171 -0
- package/coarse-placer/tools/build-dataset.ts +223 -0
- package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
- package/coarse-placer/tools/build-outlier-latin.ts +200 -0
- package/coarse-placer/tools/build-outlier-oa.ts +231 -0
- package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
- package/coarse-placer/tools/eval-openset.ts +519 -0
- package/coarse-placer/tools/eval-quant-compare.ts +151 -0
- package/coarse-placer/tools/eval.ts +187 -0
- package/coarse-placer/tools/fnv-hash.ts +24 -0
- package/coarse-placer/tools/index.ts +23 -0
- package/coarse-placer/tools/probe-frontier.ts +216 -0
- package/coarse-placer/tools/quantize.ts +116 -0
- package/coarse-placer/tools/train.ts +244 -0
- package/collections.ts +134 -0
- package/db/schema.ts +21 -0
- package/decoder/build-tree.ts +228 -0
- package/decoder/calibration.ts +101 -0
- package/decoder/containment.ts +87 -0
- package/decoder/index.ts +17 -0
- package/decoder/proposals-to-tree.ts +83 -0
- package/decoder/resolve-proposal-overlaps.ts +79 -0
- package/decoder/serialize-json.ts +70 -0
- package/decoder/serialize-tuples.ts +61 -0
- package/decoder/serialize-xml.ts +209 -0
- package/decoder/types.ts +159 -0
- package/decoder/unknown-spans.ts +103 -0
- package/decoder/validate-tree.ts +100 -0
- package/env/index.ts +42 -0
- package/env/load.ts +14 -0
- package/env/paths.ts +40 -0
- package/env/schema.ts +125 -0
- package/errors/index.ts +9 -0
- package/errors/schema.ts +155 -0
- package/fs/node.ts +38 -0
- package/identifiers.ts +58 -0
- package/index.ts +13 -0
- package/kysley/adapter.ts +29 -0
- package/kysley/client.ts +30 -0
- package/kysley/dialect-config.ts +30 -0
- package/kysley/dialect.ts +67 -0
- package/kysley/driver.ts +175 -0
- package/layers/index.ts +12 -0
- package/layers/manifest.ts +154 -0
- package/layers/schema.ts +105 -0
- package/lifecycle/ServiceSymbol.ts +95 -0
- package/lifecycle/index.ts +11 -0
- package/lifecycle/lru-cache.ts +44 -0
- package/lifecycle/services.ts +322 -0
- package/locale/index.ts +9 -0
- package/locale/locale.ts +49 -0
- package/locale/profiles/en-us.ts +69 -0
- package/locale/profiles/fr-fr.ts +75 -0
- package/locale/profiles/index.ts +9 -0
- package/locale/profiles/ja-jp.ts +33 -0
- package/locale/registry.ts +68 -0
- package/logging/index.ts +8 -0
- package/logging/shared.ts +145 -0
- package/logging/utils.ts +46 -0
- package/objects.ts +211 -0
- package/out/layers/index.d.ts +12 -0
- package/out/layers/index.d.ts.map +1 -0
- package/out/layers/index.js +12 -0
- package/out/layers/index.js.map +1 -0
- package/out/layers/manifest.d.ts +64 -0
- package/out/layers/manifest.d.ts.map +1 -0
- package/out/layers/manifest.js +102 -0
- package/out/layers/manifest.js.map +1 -0
- package/out/layers/schema.d.ts +72 -0
- package/out/layers/schema.d.ts.map +1 -0
- package/out/layers/schema.js +61 -0
- package/out/layers/schema.js.map +1 -0
- package/out/pipeline/index.d.ts +1 -1
- package/out/pipeline/index.d.ts.map +1 -1
- package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
- package/out/pipeline/runtime-pipeline.js +27 -0
- package/out/pipeline/runtime-pipeline.js.map +1 -1
- package/out/pipeline/types.d.ts +74 -4
- package/out/pipeline/types.d.ts.map +1 -1
- package/out/pipeline/types.js.map +1 -1
- package/package.json +21 -21
- package/pipeline/index.ts +46 -0
- package/pipeline/reconcile-lookups.ts +108 -0
- package/pipeline/reconcile.ts +542 -0
- package/pipeline/runtime-pipeline.ts +732 -0
- package/pipeline/span-logit-aggregation.ts +151 -0
- package/pipeline/span-proposer.ts +587 -0
- package/pipeline/types.ts +348 -0
- package/policy/defaults.ts +35 -0
- package/policy/index.ts +10 -0
- package/policy/policy.ts +60 -0
- package/policy/proposal-collection.ts +64 -0
- package/policy/registry.ts +149 -0
- package/resolver/index.ts +29 -0
- package/resolver/types.ts +584 -0
- package/resources/LocaleIndex.ts +124 -0
- package/resources/ResourceMapCache.ts +126 -0
- package/resources/collections.ts +93 -0
- package/resources/debugging.ts +19 -0
- package/resources/git.ts +54 -0
- package/resources/index.ts +17 -0
- package/resources/languages/index.ts +49 -0
- package/resources/languages/types.gen.ts +1368 -0
- package/resources/libaddressinput.ts +105 -0
- package/resources/libpostal.ts +182 -0
- package/resources/locale.ts +23 -0
- package/resources/set.ts +179 -0
- package/resources/whosonfirst/DataSourceCache.ts +72 -0
- package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
- package/resources/whosonfirst/index.ts +10 -0
- package/resources/whosonfirst/loader.ts +157 -0
- package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
- package/resources/whosonfirst/placetypes/admin.ts +173 -0
- package/resources/whosonfirst/placetypes/definition.ts +135 -0
- package/resources/whosonfirst/placetypes/graph.ts +0 -0
- package/resources/whosonfirst/placetypes/index.ts +12 -0
- package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
- package/resources/whosonfirst/placetypes/tree.ts +46 -0
- package/routing/index.ts +208 -0
- package/scripting/index.ts +40 -0
- package/scripting/utils/index.ts +106 -0
- package/tokenization/Graph.ts +50 -0
- package/tokenization/Span.ts +297 -0
- package/tokenization/index.ts +9 -0
- package/tokenization/normalizer.ts +123 -0
- package/tools/download-libpostal-resources.ts +98 -0
- package/tools/download-ssl-address.ts +99 -0
- package/tools/generate-language-types.ts +194 -0
- package/tools/index.ts +13 -0
- package/types/Classification.ts +211 -0
- package/types/classifier.ts +133 -0
- package/types/component.ts +75 -0
- package/types/index.ts +10 -0
- package/types/mapping.ts +81 -0
- package/utils/data-root.ts +56 -0
- package/utils/hash.ts +27 -0
- package/utils/index.ts +14 -0
- package/utils/jsonl.ts +43 -0
- package/utils/python-json.ts +105 -0
- package/utils/python-random.ts +90 -0
- package/utils/repo.ts +118 -0
- package/utils/sealed-db.ts +85 -0
- package/utils/stats.ts +32 -0
- package/vitest.config.ts +53 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Download Google/Chromium's per-country `ssl-address` postal-address metadata — the
|
|
7
|
+
* {@link https://github.com/google/libaddressinput libaddressinput} AddressValidationMetadata that
|
|
8
|
+
* seeds the per-locale field order, required-field, and upper-casing conventions.
|
|
9
|
+
*
|
|
10
|
+
* See: https://github.com/google/libaddressinput/wiki/AddressValidationMetadata
|
|
11
|
+
*
|
|
12
|
+
* Replaces the bash `ssl-address-download.sh` (curl + jq) with native `fetch` + `JSON.parse`. The
|
|
13
|
+
* country list lives at `…/ssl-address/data` as a `~`-delimited `.countries` string; each country's
|
|
14
|
+
* record is then fetched from `…/ssl-address/data/<CC>` and written to `<out-dir>/<CC>.json`.
|
|
15
|
+
*
|
|
16
|
+
* ## Usage
|
|
17
|
+
*
|
|
18
|
+
* ```sh
|
|
19
|
+
* mailwoman dev download ssl-address [--concurrency 16]
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* ## Flags
|
|
23
|
+
*
|
|
24
|
+
* - `--out-dir <path>` — destination directory; default `./ssl-address` (next to this script)
|
|
25
|
+
* - `--concurrency <n>` — parallel per-country fetches; default `8`
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { mkdir, writeFile } from "node:fs/promises"
|
|
29
|
+
import { join } from "node:path"
|
|
30
|
+
|
|
31
|
+
import { corePackagePath } from "@mailwoman/core/utils"
|
|
32
|
+
|
|
33
|
+
const BASE_URL = "https://chromium-i18n.appspot.com/ssl-address/data"
|
|
34
|
+
|
|
35
|
+
/** Flag-shaped options for {@linkcode downloadSSLAddress}. */
|
|
36
|
+
export interface DownloadSSLAddressOptions {
|
|
37
|
+
/** Destination directory. Default: the checked-in `core/data/chromium-i18n/ssl-address`. */
|
|
38
|
+
outDir?: string
|
|
39
|
+
/** Parallel per-country fetches. Default 8. */
|
|
40
|
+
concurrency?: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Fetch the `~`-delimited country list and return it as an array of ISO codes. */
|
|
44
|
+
async function fetchCountryCodes(): Promise<string[]> {
|
|
45
|
+
const res = await fetch(BASE_URL, { signal: AbortSignal.timeout(60_000) })
|
|
46
|
+
|
|
47
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText} fetching country list`)
|
|
48
|
+
const data = (await res.json()) as { countries?: string }
|
|
49
|
+
|
|
50
|
+
return (data.countries ?? "").split("~").filter(Boolean)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Fetch a single country's metadata record and write its raw JSON body to `<outDir>/<cc>.json`. */
|
|
54
|
+
async function fetchCountry(cc: string, outDir: string): Promise<void> {
|
|
55
|
+
const res = await fetch(`${BASE_URL}/${cc}`, { signal: AbortSignal.timeout(60_000) })
|
|
56
|
+
|
|
57
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText} on ${cc}`)
|
|
58
|
+
await writeFile(join(outDir, `${cc}.json`), await res.text())
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Download every country's ssl-address metadata record. Returns the failure count (the command maps `failed > 0` to
|
|
63
|
+
* exit 1).
|
|
64
|
+
*/
|
|
65
|
+
export async function downloadSSLAddress(
|
|
66
|
+
options: DownloadSSLAddressOptions = {},
|
|
67
|
+
report?: (line: string) => void
|
|
68
|
+
): Promise<{ written: number; failed: number }> {
|
|
69
|
+
const outDir = options.outDir ?? corePackagePath("data", "chromium-i18n", "ssl-address")
|
|
70
|
+
const concurrency = options.concurrency ?? 8
|
|
71
|
+
await mkdir(outDir, { recursive: true })
|
|
72
|
+
|
|
73
|
+
const codes = await fetchCountryCodes()
|
|
74
|
+
report?.(`=== ssl-address: ${codes.length} countries → ${outDir}`)
|
|
75
|
+
|
|
76
|
+
let nextSlot = 0
|
|
77
|
+
let failures = 0
|
|
78
|
+
const workers = Array.from({ length: Math.min(concurrency, codes.length) }, async () => {
|
|
79
|
+
while (true) {
|
|
80
|
+
const slot = nextSlot++
|
|
81
|
+
|
|
82
|
+
if (slot >= codes.length) return
|
|
83
|
+
const cc = codes[slot]!
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
await fetchCountry(cc, outDir)
|
|
87
|
+
report?.(` ✓ ${cc}`)
|
|
88
|
+
} catch (err) {
|
|
89
|
+
failures++
|
|
90
|
+
report?.(` ✗ ${cc}: ${(err as Error).message}`)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
})
|
|
94
|
+
await Promise.all(workers)
|
|
95
|
+
|
|
96
|
+
report?.(`=== done: ${codes.length - failures}/${codes.length} written, ${failures} failed`)
|
|
97
|
+
|
|
98
|
+
return { written: codes.length - failures, failed: failures }
|
|
99
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Regenerate `core/resources/languages/types.gen.ts` — the ISO 639-1/639-2b language-code types +
|
|
7
|
+
* label maps — from the committed `internal/languages.csv` resource dictionary.
|
|
8
|
+
*
|
|
9
|
+
* Usage: mailwoman dev generate language-types
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { createReadStream } from "node:fs"
|
|
13
|
+
import * as fs from "node:fs/promises"
|
|
14
|
+
|
|
15
|
+
import { pascalCase } from "change-case"
|
|
16
|
+
|
|
17
|
+
import { repoRootPath, resourceDictionaryPath } from "../utils/index.ts"
|
|
18
|
+
|
|
19
|
+
/** Options for {@linkcode generateLanguageTypes}. */
|
|
20
|
+
export interface GenerateLanguageTypesOptions {
|
|
21
|
+
/** Output path override. Default: `core/resources/languages/types.gen.ts` (the committed types). */
|
|
22
|
+
out?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Summary returned by {@linkcode generateLanguageTypes}. */
|
|
26
|
+
export interface GenerateLanguageTypesSummary {
|
|
27
|
+
languages: number
|
|
28
|
+
outPath: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Regenerate the committed language-code types from `internal/languages.csv`. */
|
|
32
|
+
export async function generateLanguageTypes(
|
|
33
|
+
options: GenerateLanguageTypesOptions = {},
|
|
34
|
+
report?: (line: string) => void
|
|
35
|
+
): Promise<GenerateLanguageTypesSummary> {
|
|
36
|
+
const outfile = options.out ?? repoRootPath("core", "resources", "languages", "types.gen.ts")
|
|
37
|
+
const dataSourcePath = resourceDictionaryPath("internal", "languages.csv")
|
|
38
|
+
|
|
39
|
+
const alpha2Entries = new Map<string, string[]>()
|
|
40
|
+
const alpha3bEntries = new Map<string, string[]>()
|
|
41
|
+
const entryLines: [alpha2: string, alpha3b: string][] = []
|
|
42
|
+
|
|
43
|
+
report?.(`Reading ${dataSourcePath}`)
|
|
44
|
+
|
|
45
|
+
// csv-parse is an optional peer — lazy import (the pipeline convention).
|
|
46
|
+
const csv = await import("csv-parse")
|
|
47
|
+
|
|
48
|
+
const parser = csv.parse({
|
|
49
|
+
delimiter: ",",
|
|
50
|
+
columns: false,
|
|
51
|
+
skip_empty_lines: true,
|
|
52
|
+
from_line: 2,
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
const stream = createReadStream(dataSourcePath).pipe(parser)
|
|
56
|
+
|
|
57
|
+
for await (const columns of stream) {
|
|
58
|
+
const alpha3b = columns[0] as string
|
|
59
|
+
const alpha2 = columns[1] as string
|
|
60
|
+
const labelsConcatenated = columns[2] as string
|
|
61
|
+
|
|
62
|
+
const labels = labelsConcatenated.split("; ")
|
|
63
|
+
|
|
64
|
+
alpha2Entries.set(alpha2, labels)
|
|
65
|
+
alpha3bEntries.set(alpha3b, labels)
|
|
66
|
+
|
|
67
|
+
entryLines.push([alpha2, alpha3b])
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const handle = await fs.open(outfile, "w")
|
|
71
|
+
const writeLine = (line: string) => handle.writeFile(`${line}\n`)
|
|
72
|
+
|
|
73
|
+
// Header.
|
|
74
|
+
|
|
75
|
+
await writeLine(`
|
|
76
|
+
/**
|
|
77
|
+
* @copyright Sister Software
|
|
78
|
+
* @license AGPL-3.0
|
|
79
|
+
* @author Teffen Ellis, et al.
|
|
80
|
+
*
|
|
81
|
+
* This file was generated by: mailwoman dev generate language-types
|
|
82
|
+
*/
|
|
83
|
+
`)
|
|
84
|
+
|
|
85
|
+
// Types.
|
|
86
|
+
|
|
87
|
+
await writeLine(`
|
|
88
|
+
/**
|
|
89
|
+
* A two-letter language code.
|
|
90
|
+
*/
|
|
91
|
+
export type Alpha2LanguageCode =
|
|
92
|
+
`)
|
|
93
|
+
|
|
94
|
+
for (const alpha2 of alpha2Entries.keys()) {
|
|
95
|
+
await writeLine(` | "${alpha2}"`)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
await writeLine(`
|
|
99
|
+
/**
|
|
100
|
+
* An enumeration of ISO 639-1 language codes.
|
|
101
|
+
*/
|
|
102
|
+
export const Alpha2LanguageCode = {
|
|
103
|
+
`)
|
|
104
|
+
|
|
105
|
+
for (const [alpha2, labels] of alpha2Entries) {
|
|
106
|
+
for (const label of labels) {
|
|
107
|
+
await writeLine(` ${pascalCase(label)}: "${alpha2}",`)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
await writeLine(`} as const satisfies Record<string, Alpha2LanguageCode>`)
|
|
112
|
+
|
|
113
|
+
await writeLine(`
|
|
114
|
+
/**
|
|
115
|
+
* A three-letter language code.
|
|
116
|
+
*/
|
|
117
|
+
export type Alpha3bLanguageCode =
|
|
118
|
+
`)
|
|
119
|
+
|
|
120
|
+
for (const alpha3b of alpha3bEntries.keys()) {
|
|
121
|
+
await writeLine(` | "${alpha3b}"`)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
await writeLine(`
|
|
125
|
+
/**
|
|
126
|
+
* A valid ISO 639-1 or ISO 639-2 language code.
|
|
127
|
+
*/
|
|
128
|
+
export type LanguageCode = Alpha2LanguageCode | Alpha3bLanguageCode | "all"
|
|
129
|
+
`)
|
|
130
|
+
|
|
131
|
+
// Maps.
|
|
132
|
+
|
|
133
|
+
await writeLine(`
|
|
134
|
+
/**
|
|
135
|
+
* A map of two-letter language codes to their labels.
|
|
136
|
+
*/
|
|
137
|
+
export const Alpha2LabelMap: ReadonlyMap<Alpha2LanguageCode, string[]> = new Map([
|
|
138
|
+
`)
|
|
139
|
+
|
|
140
|
+
for (const [alpha2, labels] of alpha2Entries) {
|
|
141
|
+
await writeLine(`["${alpha2}", ${JSON.stringify(labels)}],`)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
await writeLine(`])`)
|
|
145
|
+
|
|
146
|
+
await writeLine(`
|
|
147
|
+
/**
|
|
148
|
+
* A map of three-letter language codes to their labels.
|
|
149
|
+
*/
|
|
150
|
+
export const Alpha3bLabelMap: ReadonlyMap<Alpha3bLanguageCode, string[]> = new Map([
|
|
151
|
+
`)
|
|
152
|
+
|
|
153
|
+
for (const [alpha3b, labels] of alpha3bEntries) {
|
|
154
|
+
await writeLine(`["${alpha3b}", ${JSON.stringify(labels)}],`)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
await writeLine(`])`)
|
|
158
|
+
|
|
159
|
+
// Conversion
|
|
160
|
+
|
|
161
|
+
await writeLine(`
|
|
162
|
+
/**
|
|
163
|
+
* Convert a two-letter language code to a three-letter language code.
|
|
164
|
+
*/
|
|
165
|
+
export const Alpha2ToAlpha3b: ReadonlyMap<Alpha2LanguageCode, Alpha3bLanguageCode> = new Map([
|
|
166
|
+
`)
|
|
167
|
+
|
|
168
|
+
for (const [alpha2, alpha3b] of entryLines) {
|
|
169
|
+
await writeLine(`["${alpha2}", "${alpha3b}"],`)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
await writeLine(`])`)
|
|
173
|
+
|
|
174
|
+
await writeLine(`
|
|
175
|
+
/**
|
|
176
|
+
* Convert a three-letter language code to a two-letter language code.
|
|
177
|
+
*/
|
|
178
|
+
export const Alpha3bToAlpha2: ReadonlyMap<Alpha3bLanguageCode, Alpha2LanguageCode> = new Map([
|
|
179
|
+
`)
|
|
180
|
+
|
|
181
|
+
for (const [alpha2, alpha3b] of entryLines) {
|
|
182
|
+
await writeLine(`["${alpha3b}", "${alpha2}"],`)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
await writeLine(`])`)
|
|
186
|
+
|
|
187
|
+
// Cleanup.
|
|
188
|
+
|
|
189
|
+
await handle.close()
|
|
190
|
+
|
|
191
|
+
report?.(`Wrote ${outfile}`)
|
|
192
|
+
|
|
193
|
+
return { languages: entryLines.length, outPath: outfile }
|
|
194
|
+
}
|
package/tools/index.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Core operator tools — the `run()`-style modules behind `mailwoman dev generate …` commands. No
|
|
7
|
+
* argv, no `process.exit`: commands own parsing, rendering, and exit codes (see the 2026-07-09
|
|
8
|
+
* scripts→Pastel spec).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export * from "./download-libpostal-resources.ts"
|
|
12
|
+
export * from "./download-ssl-address.ts"
|
|
13
|
+
export * from "./generate-language-types.ts"
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Displayable } from "../resources/debugging.ts"
|
|
8
|
+
import type { Alpha3bLanguageCode } from "../resources/languages/index.ts"
|
|
9
|
+
import type { LibPostalLanguageCode } from "../resources/libpostal.ts"
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Classification recognized by Mailwoman.
|
|
13
|
+
*/
|
|
14
|
+
export const Classifications = new Set([
|
|
15
|
+
"adjacent",
|
|
16
|
+
"alpha",
|
|
17
|
+
"alphanumeric",
|
|
18
|
+
"area",
|
|
19
|
+
"chain",
|
|
20
|
+
"country",
|
|
21
|
+
"dependency",
|
|
22
|
+
"directional",
|
|
23
|
+
"end_token_single_character",
|
|
24
|
+
"end_token",
|
|
25
|
+
"given_name",
|
|
26
|
+
"house_number",
|
|
27
|
+
"intersection",
|
|
28
|
+
"level_designator",
|
|
29
|
+
"level",
|
|
30
|
+
"locality",
|
|
31
|
+
"middle_initial",
|
|
32
|
+
"multistreet",
|
|
33
|
+
"numeric",
|
|
34
|
+
"ordinal",
|
|
35
|
+
"person",
|
|
36
|
+
"personal_suffix",
|
|
37
|
+
"personal_title",
|
|
38
|
+
"place",
|
|
39
|
+
"postcode",
|
|
40
|
+
"punctuation",
|
|
41
|
+
"region",
|
|
42
|
+
"road_type",
|
|
43
|
+
"start_token",
|
|
44
|
+
"stop_word",
|
|
45
|
+
"street_name",
|
|
46
|
+
"street_prefix",
|
|
47
|
+
"street_proper_name",
|
|
48
|
+
"street_suffix",
|
|
49
|
+
"street",
|
|
50
|
+
"surname",
|
|
51
|
+
"toponym",
|
|
52
|
+
"unit_designator",
|
|
53
|
+
"unit",
|
|
54
|
+
"unknown",
|
|
55
|
+
"venue",
|
|
56
|
+
] as const)
|
|
57
|
+
|
|
58
|
+
export type Classification = typeof Classifications extends Set<infer T> ? T : never
|
|
59
|
+
|
|
60
|
+
const ClassificationConfidenceBias = new Map<Classification, number>([["country", 0.9]])
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Public classification labels.
|
|
64
|
+
*/
|
|
65
|
+
const VisibleClassification = new Set([
|
|
66
|
+
"country",
|
|
67
|
+
"dependency",
|
|
68
|
+
"house_number",
|
|
69
|
+
"level_designator",
|
|
70
|
+
"level",
|
|
71
|
+
"locality",
|
|
72
|
+
"postcode",
|
|
73
|
+
"region",
|
|
74
|
+
"street",
|
|
75
|
+
"unit_designator",
|
|
76
|
+
"unit",
|
|
77
|
+
"venue",
|
|
78
|
+
] as const satisfies Classification[])
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Classification labels that are exposed to API consumers.
|
|
82
|
+
*/
|
|
83
|
+
export type VisibleClassification = typeof VisibleClassification extends Set<infer T> ? T : never
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Type guard for visible classification labels.
|
|
87
|
+
*/
|
|
88
|
+
export function isVisibleClassification(
|
|
89
|
+
match: ClassificationMatch
|
|
90
|
+
): match is ClassificationMatch & { classification: VisibleClassification }
|
|
91
|
+
export function isVisibleClassification(classification: Classification): classification is VisibleClassification
|
|
92
|
+
export function isVisibleClassification(input: Classification | ClassificationMatch): input is VisibleClassification {
|
|
93
|
+
const classification = typeof input === "string" ? input : input.classification
|
|
94
|
+
|
|
95
|
+
return VisibleClassification.has(classification as VisibleClassification)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export type ClassificationMap = Map<VisibleClassification, string[]>
|
|
99
|
+
export type ClassificationConfidenceMap = Map<VisibleClassification, number>
|
|
100
|
+
export type ClassificationConfidenceRecord = Record<VisibleClassification, number | undefined>
|
|
101
|
+
export type ClassificationRecord = Partial<Record<VisibleClassification, string[]>>
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A classification match for a span of text.
|
|
105
|
+
*/
|
|
106
|
+
export interface ClassificationMatch {
|
|
107
|
+
/**
|
|
108
|
+
* The classification assigned to the text.
|
|
109
|
+
*/
|
|
110
|
+
readonly classification: Classification
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The confidence of the classification.
|
|
114
|
+
*/
|
|
115
|
+
readonly confidence: number
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Languages for which the classification is valid.
|
|
119
|
+
*
|
|
120
|
+
* If a language is present in this set, it means that the value which it is associated with is a valid value in that
|
|
121
|
+
* language.
|
|
122
|
+
*/
|
|
123
|
+
readonly languages?: Displayable<ReadonlySet<LibPostalLanguageCode | Alpha3bLanguageCode>>
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Flags associated with the classification, i.e. clarifying details to enhance the classification.
|
|
127
|
+
*/
|
|
128
|
+
readonly flags?: Set<string>
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export type ClassificationsMatchInput = ClassificationMatch | Classification
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* A map of classifications to matches.
|
|
135
|
+
*/
|
|
136
|
+
export class ClassificationsMatchMap extends Map<Classification, ClassificationMatch> {
|
|
137
|
+
/**
|
|
138
|
+
* Add a classification to the map if it has a higher confidence than the existing classification.
|
|
139
|
+
*/
|
|
140
|
+
public add(classification: Classification, confidence?: number): void
|
|
141
|
+
public add(classificationMatch: Partial<ClassificationMatch>): void
|
|
142
|
+
public add(...args: [Partial<ClassificationMatch>] | [Classification, number?]): void {
|
|
143
|
+
let match: Partial<ClassificationMatch>
|
|
144
|
+
|
|
145
|
+
if (typeof args[0] === "string") {
|
|
146
|
+
const classification = args[0]
|
|
147
|
+
const confidence = typeof args[1] === "number" ? args[1] : (ClassificationConfidenceBias.get(classification) ?? 1)
|
|
148
|
+
|
|
149
|
+
match = {
|
|
150
|
+
classification,
|
|
151
|
+
confidence,
|
|
152
|
+
}
|
|
153
|
+
} else {
|
|
154
|
+
match = {
|
|
155
|
+
...args[0],
|
|
156
|
+
confidence: args[0].confidence ?? ClassificationConfidenceBias.get(args[0].classification!) ?? 1,
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (!match.classification) {
|
|
161
|
+
throw new TypeError("Classification must be a non-empty string")
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (typeof match.confidence !== "number") {
|
|
165
|
+
throw new TypeError("Confidence must be a number")
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (match.confidence < 0) {
|
|
169
|
+
throw new RangeError(
|
|
170
|
+
`${match.classification}: Confidence must be greater than or equal to 0: ${match.confidence}`
|
|
171
|
+
)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (match.confidence > 1) {
|
|
175
|
+
throw new RangeError(`${match.classification}: Confidence must be less than or equal to 1: ${match.confidence}`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const existing = this.get(match.classification)
|
|
179
|
+
|
|
180
|
+
// Ensure that duplicate classifications do not reduce confidence
|
|
181
|
+
if (existing && existing.confidence >= match.confidence) {
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
this.set(match.classification, match as ClassificationMatch)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Predicate to determine if the map contains a classification that is visible.
|
|
190
|
+
*/
|
|
191
|
+
public hasVisibleClassification(classification?: VisibleClassification): boolean {
|
|
192
|
+
return classification ? this.has(classification) : Iterator.from(this.keys()).some(isVisibleClassification)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Serialize the classification map to JSON.
|
|
197
|
+
*/
|
|
198
|
+
public toJSON(): ClassificationMatch[] {
|
|
199
|
+
return this.values().toArray()
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
static from(...input: ClassificationsMatchInput[]): ClassificationsMatchMap {
|
|
203
|
+
const map = new ClassificationsMatchMap()
|
|
204
|
+
|
|
205
|
+
for (const entry of input) {
|
|
206
|
+
map.add(entry as ClassificationMatch)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return map
|
|
210
|
+
}
|
|
211
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Classifier-side contracts for the neural integration (per #6).
|
|
7
|
+
*
|
|
8
|
+
* These interfaces are deliberately distinct from the existing `Classifier` shape in
|
|
9
|
+
* `../classification/BaseClassifier.ts`. The legacy shape is mutation-based —
|
|
10
|
+
* `classifyTokens(context): void` — and runs synchronously over the span graph. The shape
|
|
11
|
+
* declared here is pull-based and async: a classifier returns a list of `ClassificationProposal`
|
|
12
|
+
* objects keyed by the canonical `ComponentTag` union.
|
|
13
|
+
*
|
|
14
|
+
* The neural classifier implements this interface natively. The rule classifiers that once
|
|
15
|
+
* also implemented it (via a `wrapLegacyClassifier` adapter) were removed in v7.0.0 with the
|
|
16
|
+
* `@mailwoman/classifiers` workspace; this contract now describes the neural path only.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { Span } from "../tokenization/index.ts"
|
|
20
|
+
import type { ComponentTag } from "./component.ts"
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Sections in Mailwoman are sub-Spans of the tokenized input (split by boundary characters: commas, line breaks, etc.).
|
|
24
|
+
* They are surfaced as `Span` instances in `TokenContext.sections`; this alias documents the call-site intent.
|
|
25
|
+
*/
|
|
26
|
+
export type Section = Span
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Source of a `ClassificationProposal`. Drives policy decisions and downstream telemetry.
|
|
30
|
+
*
|
|
31
|
+
* - `rule`: emitted by a legacy rule classifier through the adapter.
|
|
32
|
+
* - `neural`: emitted by an ONNX-backed sequence classifier.
|
|
33
|
+
* - `merged`: synthetic source for a merger that fused proposals from multiple classifiers (rare; mostly for telemetry on
|
|
34
|
+
* `merged` ids).
|
|
35
|
+
*/
|
|
36
|
+
export type ClassificationProposalSource = "rule" | "neural" | "merged"
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A typed classification candidate produced by any classifier.
|
|
40
|
+
*
|
|
41
|
+
* Mirrors Mailwoman's pre-refactor per-component output shape with the addition of `source` and `source_id` so
|
|
42
|
+
* downstream code can identify the origin of each proposal without consulting external state.
|
|
43
|
+
*/
|
|
44
|
+
export interface ClassificationProposal {
|
|
45
|
+
/** Span this proposal applies to. */
|
|
46
|
+
span: Span
|
|
47
|
+
|
|
48
|
+
/** Component type the classifier thinks this span is. */
|
|
49
|
+
component: ComponentTag
|
|
50
|
+
|
|
51
|
+
/** Classifier confidence in [0, 1]. */
|
|
52
|
+
confidence: number
|
|
53
|
+
|
|
54
|
+
/** Provenance — which classifier family produced this proposal. */
|
|
55
|
+
source: ClassificationProposalSource
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Identifier of the specific classifier instance. Rule wrappers use the legacy classifier's stable id (e.g.
|
|
59
|
+
* `house_number`, `postcode`, `whos_on_first`). Neural classifiers use a versioned model id like
|
|
60
|
+
* `neural-v0.3.1-en-us`.
|
|
61
|
+
*/
|
|
62
|
+
source_id: string
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Solver penalty applied to this proposal. Higher penalty makes the proposal less likely to appear in the winning
|
|
66
|
+
* solution.
|
|
67
|
+
*/
|
|
68
|
+
penalty: number
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Opaque metadata for debugging and telemetry. Never consulted by the solver. Common keys: `languages`, `flags`,
|
|
72
|
+
* `legacyClassification`.
|
|
73
|
+
*/
|
|
74
|
+
metadata?: Record<string, unknown>
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Per-request context handed to a classifier.
|
|
79
|
+
*/
|
|
80
|
+
export interface ClassifierContext {
|
|
81
|
+
/** Locale for this classification request, if known. */
|
|
82
|
+
locale?: string
|
|
83
|
+
|
|
84
|
+
/** Proposals already produced for this request (for composites). */
|
|
85
|
+
prior?: readonly ClassificationProposal[]
|
|
86
|
+
|
|
87
|
+
/** Cancellation signal. */
|
|
88
|
+
signal?: AbortSignal
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Plug-in contract every classifier implements.
|
|
93
|
+
*
|
|
94
|
+
* Construction must be cheap; per-classification work runs in {@link classify}. Pre-flight work (loading dictionaries,
|
|
95
|
+
* warming up an ONNX session) belongs in the optional `ready()` step.
|
|
96
|
+
*/
|
|
97
|
+
export interface ProposalClassifier {
|
|
98
|
+
/** Stable identifier. Used as `source_id` on emitted proposals. */
|
|
99
|
+
readonly id: string
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Components this classifier may emit. Enforced — proposals for tags outside this list are dropped by the adapter
|
|
103
|
+
* with a warning.
|
|
104
|
+
*/
|
|
105
|
+
readonly emits: readonly ComponentTag[]
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Locales this classifier serves. `"*"` means locale-agnostic.
|
|
109
|
+
*
|
|
110
|
+
* The policy layer uses this to skip classifiers that aren't relevant to the requested locale.
|
|
111
|
+
*/
|
|
112
|
+
readonly locales: readonly (string | "*")[]
|
|
113
|
+
|
|
114
|
+
/** Optional async pre-flight. */
|
|
115
|
+
ready?(): Promise<void>
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Classify a section. Implementations MUST NOT throw — return an empty array on failure and log via the project
|
|
119
|
+
* logger.
|
|
120
|
+
*/
|
|
121
|
+
classify(section: Section, context: ClassifierContext): Promise<ClassificationProposal[]>
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Convenience: synchronous classifier (legacy rule wrappers usually fit here). The adapter wraps these into the async
|
|
126
|
+
* `ProposalClassifier` interface so the solver path stays uniform.
|
|
127
|
+
*/
|
|
128
|
+
export interface SyncProposalClassifier {
|
|
129
|
+
readonly id: string
|
|
130
|
+
readonly emits: readonly ComponentTag[]
|
|
131
|
+
readonly locales: readonly (string | "*")[]
|
|
132
|
+
classifySync(section: Section, context: ClassifierContext): ClassificationProposal[]
|
|
133
|
+
}
|