@mailwoman/record 10.0.0 → 10.2.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/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # @mailwoman/record
2
2
 
3
- **Record schema and per-field normalizers** for the geocode-first entity
4
- resolution matcher. Address-first design: the canonical `PostalAddress` record
5
- composes parsed address components, the formatter's match key, and a resolved
6
- geocode. Organization and contact records build on the same canonical record.
3
+ This package provides the **record schema and per-field normalizers** for the
4
+ geocode-first entity resolution matcher. The design starts from the address. The
5
+ canonical `PostalAddress` record combines parsed address components, the
6
+ formatter's match key, and a resolved geocode. Organization and contact records build on the same canonical record.
7
7
 
8
8
  ```ts
9
9
  import { PostalAddress, parsePersonName, canonicalizeOrganizationName } from "@mailwoman/record";
@@ -32,10 +32,8 @@ canonicalizeOrganizationName("Baylor Univ. Med. Ctr.");
32
32
  ```ts
33
33
  // Address record (the core of the record system)
34
34
  import { PostalAddress, createPostalAddress } from "@mailwoman/record/address"
35
-
36
35
  // Person name parsing → structured components
37
36
  import { parsePersonName, type ParsedPersonName } from "@mailwoman/record/name"
38
-
39
37
  // Organization name canonicalization → matchable key
40
38
  import { canonicalizeOrganizationName, type CanonicalizeOrgOpts } from "@mailwoman/record/organization"
41
39
  ```
@@ -50,24 +48,24 @@ import { canonicalizeOrganizationName, type CanonicalizeOrgOpts } from "@mailwom
50
48
 
51
49
  ## Design
52
50
 
53
- - **Plain data, no classes.** Records are plain TypeScript objects with
51
+ - **Plain data without classes.** Records are plain TypeScript objects with
54
52
  branded types where needed.
55
- - **Address-first.** The `PostalAddress` is the canonical record — the geocode-first
56
- matcher resolves places, not strings.
53
+ - **Address-first.** `PostalAddress` is the canonical record, because the
54
+ geocode-first matcher resolves places and not strings.
57
55
  - **Domain-scoped.** Organization canonicalization supports jurisdiction and
58
56
  domain context (e.g., `{jurisdiction: "ID"}` for Indonesian legal designations,
59
- `{domain: "healthcare"}` to protect PT/SCA from collision with medical
57
+ `{domain: "healthcare"}` to keep PT/SCA from colliding with medical
60
58
  abbreviations).
61
- - **Lean dependencies.** Only depends on `@mailwoman/formatter` for the
62
- canonical key.
59
+ - **Lean dependencies.** The package depends only on `@mailwoman/formatter`, for
60
+ the canonical key.
63
61
 
64
62
  ## Related
65
63
 
66
- - [`@mailwoman/match`](../match) — the fuzzy matcher that consumes these records
67
- - [`@mailwoman/formatter`](../formatter) — `canonicalKey` used by `PostalAddress`
68
- - [`@mailwoman/registry`](../registry) — high-level `resolveEntities` that uses records
64
+ - [`@mailwoman/match`](../match): the fuzzy matcher that consumes these records.
65
+ - [`@mailwoman/formatter`](../formatter): provides the `canonicalKey` that `PostalAddress` uses.
66
+ - [`@mailwoman/registry`](../registry): the high-level `resolveEntities` that uses records.
69
67
  - [Geocode-First Record Matching](https://mailwoman.ai/articles/concepts/geocode-first-record-matching/)
70
68
 
71
69
  ## License
72
70
 
73
- [AGPL-3.0-only](https://www.gnu.org/licenses/agpl-3.0.html)
71
+ [AGPL-3.0-only](https://www.gnu.org/licenses/AGPL-3.0.html)
package/lib/address.ts CHANGED
@@ -2,39 +2,13 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
- *
6
- * The canonical address record — the matcher's unit of address identity, and the canonical record
7
- * the organization and contact records build on.
8
- *
9
- * It is plain data: parser components + the formatter's match key + an optional resolved geocode,
10
- * composed into one object. No ORM, no decorators, no schema-generation implementation — if we need a
11
- * database we reach for Kysely at the call site, not a model layer here.
12
- *
13
- * The geocode fields mirror mailwoman's `GeocodeResult` (tier + calibrated uncertainty + hierarchy)
14
- * on purpose: that is the location signal the Fellegi-Sunter scorer weights its distance evidence
15
- * by — two records sharing a `address_point` coordinate is strong agreement; sharing an
16
- * `interpolated` centroid is weak; a PO-box / multi-unit coordinate is barely location agreement
17
- * at all (the NAACCR precedent, see the geocode-first record-matching concept doc).
18
- */
19
-
20
- import { type ComponentDict, type FormatAddressOptions, formatAddress } from "@mailwoman/codex/address-format"
21
- import { canonicalKey } from "@mailwoman/codex/address-key"
22
-
23
- /**
24
- * A geographic coordinate (WGS84 decimal degrees).
25
5
  */
26
- export interface GeoCoordinate {
27
- latitude: number
28
- longitude: number
29
- }
30
6
 
31
- /**
32
- * The resolution tier that produced a coordinate, mirroring mailwoman's geocoder (`address_point` > `interpolated` >
33
- * `street` > `admin`). Kept as a local plain union so this package stays decoupled from the heavy geocoder runtime; a
34
- * `GeocodeResult.resolution_tier` maps in directly. (`street` = a street centroid for a street-only query, #1042 —
35
- * coarser than a house-number estimate, finer than an admin centroid.)
36
- */
37
- export type ResolutionTier = "address_point" | "interpolated" | "street" | "admin" | "venue" | "plus_code"
7
+ import type { ResolutionTier } from "@mailwoman/annotations/geo"
8
+ import { type FormatAddressOptions, formatAddress } from "@mailwoman/codex/address/format"
9
+ import { canonicalKey } from "@mailwoman/codex/address/key"
10
+ import type { ComponentDict } from "@mailwoman/codex/address/render"
11
+ import type { GeoCoordinate } from "@mailwoman/spatial"
38
12
 
39
13
  /**
40
14
  * One resolved admin-hierarchy ancestor (most specific first), for spelling-invariant blocking.
@@ -42,7 +16,7 @@ export type ResolutionTier = "address_point" | "interpolated" | "street" | "admi
42
16
  export interface HierarchyNode {
43
17
  tag: string
44
18
  value: string
45
- placeID?: string
19
+ placeID: string | null
46
20
  }
47
21
 
48
22
  /**
@@ -51,49 +25,60 @@ export interface HierarchyNode {
51
25
  export interface AddressGeocode {
52
26
  coordinate: GeoCoordinate
53
27
  tier: ResolutionTier
28
+
54
29
  /**
55
- * Calibrated uncertainty radius in meters; `null` for the admin tier (no sub-locality estimate).
30
+ * Gives the uncertainty radius in meters.
31
+ *
32
+ * It is `null` on the admin tier and whenever the tier reports none.
56
33
  */
57
34
  uncertaintyMeters: number | null
35
+
58
36
  /**
59
- * Resolved admin hierarchy, locality → country (most specific first).
37
+ * Lists the resolved admin hierarchy from the locality up to the country.
60
38
  */
61
- hierarchy?: HierarchyNode[]
39
+ hierarchy: HierarchyNode[] | null
40
+
62
41
  /**
63
- * A delivery point, not a building — weakens location agreement even at a precise coordinate.
42
+ * Marks a delivery point, such as a PO box, rather than a building,
43
+ * so the coordinate does not locate the addressee.
64
44
  */
65
- poBox?: boolean
45
+ poBox: boolean | null
46
+
66
47
  /**
67
- * A multi-unit building where many records share one coordinate — weakens unit-level agreement.
48
+ * Marks a multi-unit building whose records share one coordinate,
49
+ * so the coordinate cannot distinguish units.
68
50
  */
69
- multiUnit?: boolean
51
+ multiUnit: boolean | null
70
52
  }
71
53
 
72
54
  /**
73
- * The canonical address record. Composes the parser's components, the formatter's match key, an optional human-readable
74
- * form, and an optional resolved geocode. Plain data — no behavior.
55
+ * Describes the canonical address record with parsed components plus a match key.
56
+ *
57
+ * It may also include formatted text, raw input or a resolved geocode.
75
58
  */
76
59
  export interface PostalAddress {
77
60
  /**
78
- * Parsed address components (`ComponentTag`-keyed).
61
+ * Holds the parsed address components keyed by component tag.
79
62
  */
80
63
  components: ComponentDict
64
+
81
65
  /**
82
- * Normalized, deterministic match key for blocking (from `@mailwoman/formatter`).
66
+ * Holds the normalized, deterministic match key used for blocking, built by
67
+ * `canonicalKey` from `@mailwoman/codex/address/key`.
83
68
  */
84
69
  canonicalKey: string
70
+
85
71
  /**
86
- * Optional human-readable single-line form, for display.
87
- */
88
- formatted?: string
89
- /**
90
- * Resolved location, when geocoded.
72
+ * Gives a human-readable single-line form for display.
91
73
  */
92
- geocode?: AddressGeocode
74
+ formatted: string | null
75
+
76
+ geocode: AddressGeocode | null
77
+
93
78
  /**
94
- * The original free-text input, when known (provenance).
79
+ * Keeps the original free-text input for provenance.
95
80
  */
96
- raw?: string
81
+ raw: string | null
97
82
  }
98
83
 
99
84
  /**
@@ -101,48 +86,49 @@ export interface PostalAddress {
101
86
  */
102
87
  export interface ToPostalAddressOptions {
103
88
  /**
104
- * Country (ISO-2 or name) for formatting. Defaults to the `country` component, else unset.
89
+ * Supplies the country for formatting as an ISO-2 code or a name.
90
+ *
91
+ * @defaultValue the `country` component.
105
92
  */
106
- country?: string
93
+ country?: string | null
94
+
107
95
  /**
108
- * The original free-text input to retain as provenance.
96
+ * Supplies the original free-text input to keep as provenance.
109
97
  */
110
- raw?: string
98
+ raw?: string | null
99
+
111
100
  /**
112
- * Also compute a human-readable `formatted` string. Default `true`.
101
+ * Indicates whether to compute the `formatted` string.
102
+ *
103
+ * @defaultValue `true`
113
104
  */
114
105
  format?: boolean
106
+
115
107
  /**
116
- * Formatting options forwarded to the formatter. Defaults to single-line (`", "`).
108
+ * Passes options to the formatter, defaulting to a single line joined with `", "`.
117
109
  */
118
110
  formatOptions?: FormatAddressOptions
119
111
  }
120
112
 
121
113
  /**
122
- * Build a canonical {@linkcode PostalAddress} from parsed components: fills the match key (always) and a human-readable
123
- * form (unless disabled). Attach a geocode separately with {@linkcode withGeocode} once the address is resolved.
114
+ * Builds a {@linkcode PostalAddress} from parsed components, always filling the match key
115
+ * and, unless `format` is `false`, the formatted address.
116
+ *
117
+ * Attach a geocode separately with {@linkcode withGeocode}.
124
118
  */
125
119
  export function toPostalAddress(components: ComponentDict, opts: ToPostalAddressOptions = {}): PostalAddress {
126
120
  const country = opts.country ?? components.country ?? ""
127
121
 
128
- const record: PostalAddress = {
122
+ const formatted =
123
+ opts.format === false ? null : formatAddress(components, country, opts.formatOptions ?? { separator: ", " })
124
+
125
+ return {
129
126
  components,
130
127
  canonicalKey: canonicalKey(components),
128
+ formatted: formatted || null,
129
+ geocode: null,
130
+ raw: opts.raw ?? null,
131
131
  }
132
-
133
- if (opts.raw !== undefined) {
134
- record.raw = opts.raw
135
- }
136
-
137
- if (opts.format !== false) {
138
- const formatted = formatAddress(components, country, opts.formatOptions ?? { separator: ", " })
139
-
140
- if (formatted) {
141
- record.formatted = formatted
142
- }
143
- }
144
-
145
- return record
146
132
  }
147
133
 
148
134
  /**
package/lib/name.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { TextSpliterator } from "spliterator"
2
+
1
3
  /**
2
4
  * @copyright Sister Software
3
5
  * @license AGPL-3.0
@@ -14,53 +16,58 @@
14
16
  *
15
17
  * Scope + honesty (per the name-canonicalization research pass):
16
18
  *
17
- * - Western / romanized names only. Cultural given-family ORDER variation (East-Asian family-first)
19
+ * - Western / romanized names only. Cultural given-family order variation (East-Asian family-first)
18
20
  * and transliteration are not handled here — a documented follow-up.
19
- * - Nickname → canonical-root mapping is intentionally NOT done at parse time: it is lossy and
21
+ * - Nickname → canonical-root mapping is intentionally not done at parse time: it is lossy and
20
22
  * gendered (Bobbie → Robert _or_ Roberta), so equivalence belongs in the matcher as a fuzzy
21
- * agreement level, not a destructive rewrite. We only _extract_ a parenthetical/quoted
23
+ * agreement level rather than a destructive rewrite. We only _extract_ a parenthetical/quoted
22
24
  * nickname.
23
- * - A CRF parser (probablepeople) is the gold-standard reference but too heavy to port; this
25
+ * - A CRF parser (probablepeople) is the gold-standard reference but too heavy to port. this
24
26
  * positional parser covers the documented hard cases (inversion, particles, generational +
25
27
  * professional suffixes) without a model.
26
28
  */
27
29
 
28
30
  /**
29
- * A parsed person name. All fields optional — the parser fills what it can identify.
31
+ * A parsed person name.
32
+ *
33
+ * Every field is nullable.
34
+ * The parser fills what it can identify.
30
35
  */
31
36
  export interface PersonName {
32
37
  /**
33
38
  * Title / salutation that preceded the name (`Dr`, `Mr`, `Capt`).
34
39
  */
35
- prefix?: string
40
+ prefix: string | null
36
41
  /**
37
42
  * First / given name.
38
43
  */
39
- given?: string
44
+ given: string | null
40
45
  /**
41
46
  * Middle name(s) or initial.
42
47
  */
43
- middle?: string
48
+ middle: string | null
44
49
  /**
45
50
  * Surname, _without_ any particle (`Vega`, not `de la Vega`).
46
51
  */
47
- family?: string
52
+ family: string | null
48
53
  /**
49
54
  * Surname particle, stored separately (`de la`, `van der`, `von`).
50
55
  */
51
- familyParticle?: string
56
+ familyParticle: string | null
52
57
  /**
53
58
  * Generational or professional suffix (`Jr`, `III`, `PhD`, `MD`).
54
59
  */
55
- suffix?: string
60
+ suffix: string | null
56
61
  /**
57
62
  * A parenthetical or quoted nickname (`"Gob"` in `George "Gob" Bluth`).
58
63
  */
59
- nickname?: string
64
+ nickname: string | null
60
65
  }
61
66
 
62
67
  /**
63
- * Titles / salutations that lead a name. Matched case-insensitively, trailing `.` ignored.
68
+ * Titles / salutations that lead a name.
69
+ *
70
+ * Matched case-insensitively, trailing `.` ignored.
64
71
  */
65
72
  const TITLES = new Set([
66
73
  "airman",
@@ -161,8 +168,10 @@ const SUFFIXES = new Set([
161
168
  ])
162
169
 
163
170
  /**
164
- * Surname particles. Consecutive particles fold together (`de` + `la` → `de la`), and the next non-particle token
165
- * begins the bare surname.
171
+ * Surname particles.
172
+ *
173
+ * Consecutive particles fold together (`de` + `la` → `de la`), and the next
174
+ * non-particle token begins the bare surname.
166
175
  */
167
176
  const PARTICLES = new Set([
168
177
  "al",
@@ -204,13 +213,23 @@ const norm = (token: string): string => token.replace(/\.$/, "").toLowerCase()
204
213
  const countChar = (s: string, c: string): number => s.split(c).length - 1
205
214
 
206
215
  /**
207
- * Parse a full name into components. Returns `null` for empty input. Best-effort and non-throwing — ambiguous input
208
- * degrades gracefully rather than erroring.
216
+ * Parse a full name into components.
217
+ *
218
+ * @returns `null` for empty input.
219
+ * Best-effort and non-throwing — ambiguous input degrades gracefully rather than erroring.
209
220
  */
210
- export function parsePersonName(input: string | null | undefined): PersonName | null {
221
+ export function parsePersonName(input: string | null): PersonName | null {
211
222
  if (!isPresent(input)) return null
212
223
 
213
- const result: PersonName = {}
224
+ const result: PersonName = {
225
+ prefix: null,
226
+ given: null,
227
+ middle: null,
228
+ family: null,
229
+ familyParticle: null,
230
+ suffix: null,
231
+ nickname: null,
232
+ }
214
233
 
215
234
  // 1. Extract a parenthetical "(Jim)" or quoted "Jim" nickname, then strip it out.
216
235
  let working = input
@@ -234,7 +253,7 @@ export function parsePersonName(input: string | null | undefined): PersonName |
234
253
  // 2. Resolve a single comma: "Last, First" inversion, unless the tail is a known suffix
235
254
  // ("John Smith, Jr."), in which case keep order and treat the tail as a suffix.
236
255
  if (countChar(working, ",") === 1) {
237
- const [head, tail] = working.split(",").map((p) => p.trim())
256
+ const [head, tail] = TextSpliterator.from(working, { delimiter: "," }).toArray()
238
257
 
239
258
  if (tail && tail.split(/\s+/).every((t) => SUFFIXES.has(norm(t)))) {
240
259
  result.suffix = tail
@@ -244,11 +263,11 @@ export function parsePersonName(input: string | null | undefined): PersonName |
244
263
  }
245
264
  }
246
265
 
247
- const tokens = working.split(/\s+/).filter((value) => value.length > 0)
266
+ const tokens = working.split(/\s+/).filter((value) => value.length)
248
267
 
249
- if (!tokens.length) return Object.keys(result).length ? result : null
268
+ if (!tokens.length) return Object.values(result).some((value) => value !== null) ? result : null
250
269
 
251
- // 3. Leading titles → prefix.
270
+ // 3. Titles at the start become the prefix.
252
271
  const prefixParts: string[] = []
253
272
 
254
273
  while (tokens.length > 1 && TITLES.has(norm(tokens[0]!))) {
@@ -259,7 +278,7 @@ export function parsePersonName(input: string | null | undefined): PersonName |
259
278
  result.prefix = prefixParts.join(" ")
260
279
  }
261
280
 
262
- // 4. Trailing suffixes → suffix (a single name token must remain).
281
+ // 4. Suffixes at the end become the suffix, while one name token must remain.
263
282
  const suffixParts: string[] = []
264
283
 
265
284
  while (tokens.length > 1 && SUFFIXES.has(norm(tokens.at(-1)!))) {
@@ -272,7 +291,8 @@ export function parsePersonName(input: string | null | undefined): PersonName |
272
291
 
273
292
  if (!tokens.length) return result
274
293
 
275
- // 5. Locate the surname particle run; everything from it onward is the (particled) surname.
294
+ // 5. Locate the surname particle run.
295
+ // Everything from it onward is the (particled) surname.
276
296
  let particleStart = -1
277
297
 
278
298
  for (let i = 0; i < tokens.length; i++) {
@@ -299,7 +319,7 @@ export function parsePersonName(input: string | null | undefined): PersonName |
299
319
  const before = tokens.slice(0, particleStart)
300
320
 
301
321
  if (before.length) {
302
- result.given = before[0]
322
+ result.given = before[0]!
303
323
  }
304
324
 
305
325
  if (before.length > 1) {
@@ -311,13 +331,13 @@ export function parsePersonName(input: string | null | undefined): PersonName |
311
331
 
312
332
  // 6. No particle: last token is the surname, first is given, the rest is middle.
313
333
  if (tokens.length === 1) {
314
- result.given = tokens[0]
334
+ result.given = tokens[0]!
315
335
 
316
336
  return result
317
337
  }
318
338
 
319
- result.given = tokens[0]
320
- result.family = tokens.at(-1)
339
+ result.given = tokens[0]!
340
+ result.family = tokens.at(-1)!
321
341
 
322
342
  if (tokens.length > 2) {
323
343
  result.middle = tokens.slice(1, -1).join(" ")
@@ -327,14 +347,18 @@ export function parsePersonName(input: string | null | undefined): PersonName |
327
347
  }
328
348
 
329
349
  /**
330
- * The ORDER a person name prints in. Western / romanized only, the same scope {@linkcode parsePersonName} declares: a
331
- * family-first system is not this order reversed, and inventing one here would be worse than having none.
350
+ * The order a person name prints in.
351
+ *
352
+ * Western / romanized only, the same scope {@linkcode parsePersonName} declares.
353
+ * A family-first system does not use this order in reverse.
354
+ * An invented order here would be worse than having none.
332
355
  */
333
356
  const NAME_ORDER: readonly (keyof PersonName)[] = ["prefix", "given", "middle", "familyParticle", "family", "suffix"]
334
357
 
335
358
  /**
336
- * The parts {@linkcode formatPersonName} prints for the short style — what a person is addressed by, without the title,
337
- * the nickname or the letters after.
359
+ * The parts {@linkcode formatPersonName} prints for the short style.
360
+ *
361
+ * What a person is addressed by, without the title, the nickname or the letters after.
338
362
  */
339
363
  const SHORT_NAME_ORDER: readonly (keyof PersonName)[] = ["given", "familyParticle", "family"]
340
364
 
@@ -346,14 +370,17 @@ export type PersonNameStyle = "full" | "short"
346
370
  /**
347
371
  * Render a {@linkcode PersonName} back to a string — the inverse of {@linkcode parsePersonName}.
348
372
  *
349
- * `"full"` prints every part the parser identified except the nickname, which is an alternative to the given name
350
- * rather than an addition to it. `"short"` prints what a person is addressed by, which is the form a display label and
351
- * a match key want.
373
+ * `"full"` prints every part the parser identified except the nickname.
374
+ * A nickname is an alternative to the given name rather than an addition to it.
375
+ *
376
+ * `"short"` prints what a person is addressed by.
377
+ * Display labels and match keys use this form.
352
378
  *
353
- * The particle travels WITH the surname in both styles. The parser stores it separately so the matcher can compare
354
- * `Vega` independently of `de la`; printing them apart would produce a name nobody wrote.
379
+ * The particle travels with the surname in both styles.
380
+ * The parser stores it separately so the matcher can compare `Vega` independently of `de la`;
381
+ * printing them apart would produce a form absent from the input name.
355
382
  */
356
- export function formatPersonName(name: PersonName | null | undefined, style: PersonNameStyle = "full"): string {
383
+ export function formatPersonName(name: Partial<PersonName> | null, style: PersonNameStyle = "full"): string {
357
384
  if (!name) return ""
358
385
 
359
386
  const order = style === "short" ? SHORT_NAME_ORDER : NAME_ORDER